Skip to content

feat(network): capture React Native traffic over the Metro debugger - #4693

Closed
thymikee wants to merge 8 commits into
mainfrom
t3/rn-metro-network-capture
Closed

thymikee wants to merge 8 commits into
mainfrom
t3/rn-metro-network-capture

Conversation

@thymikee

@thymikee thymikee commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds React Native network capture over the Metro debugger to the shared network start / network dump / network stop surface (ADR 0037). One source is armed at start and reported on every dump: CDP Network on RN >= 0.83, the in-app fetch/XHR hook on older runtimes, chosen from Metro's target list and bound to one device + app identity. A detached holder keeps the CDP connection and hands each window over exactly once, proven by the socket reply; a capture failure never rejects the app's own fetch. 39 files. Supersedes #3930, now closed unmerged.

Validation

  • Tested SHA f9929574b1. pnpm check:affected --run --head f9929574b1: all runnable checks passed (receipt run-e2AIVN); full suite 1999 files green at that head.
  • Live Android emulator (dev client + Metro): CDP capture of GET/POST/XHR/failed requests, x-api-key redaction, bodies via --include all, owner-only socket/state files, network stop leaves no holder process and no state files.
  • Three independent review rounds; round-2 fixes at 247995a825/09f3a14308, round-3 (delivery proof, queue recovery, body-rule honesty) at 35adecf512/f9929574b1.
  • The gross diff exceeds the 2,500-line guideline: it is one self-contained capture engine plus its tests (production ~3.3k, tests ~1.8k), at the scale of the PR it supersedes.
  • CI device lanes still to confirm.

🤖 Generated with Claude Code

thymikee and others added 8 commits October 26, 2026 13:18
…o debugger

network start chooses one source per session and arms it: the CDP Network
domain on React Native 0.83+ runtimes, or an in-app fetch/XHR hook on older
ones. network dump reads only the armed source and reports it; with none
armed it keeps the daemon app-log parse as source=app-log. network stop
closes the capture. The CDP source runs in a detached holder process beside
react-devtools, so remote daemons and companion-tunnel devices work; a JS
reload is followed once, anything else fails closed.
…sults

Apply what the live drives and device runs surfaced after the first cut:

- `network start`/`stop` render their outcome in text output instead of
  falling through to "No recent HTTP(s) entries found.", and `requiresRelaunch`
  joins the metadata line.
- A failed request names its error in text output through `metadata.error`.
- A socket `stop` no longer records `holder-terminated`: the stopper deletes
  the capture's files as it answers, and a status written after that survives
  as an orphan claiming an ending nobody asked for.
- Request ids belong to one debugger connection: the buffer remembers which
  ids it settled, so a runtime re-emitting completed requests under the same
  id cannot duplicate entries, and a holder re-arm clears the ledger so a
  reused id on the new connection still settles.
- `selectReactNativeCaptureTarget` applies `--device` before its single-match
  shortcut, so a capture never arms on another device's runtime when the
  caller named one.
- A dump with nothing armed keeps its `await` and falls through to the app-log
  parse rather than resolving undefined.
- Header redaction moved to the read; the shared JSON readers live in
  network-capture-json.ts.

output-economy: the network digest now names its source (+20 bytes, waived).
readBoundCaptureTarget asked the same question bindingMatchesTarget answers and
answered it with a narrower one; the holder now asks the function itself.
…nd stop paths

A drain committed its window before the reply crossed the socket, so a reader
that gave up waiting was answered afterwards by an empty window it was never
watched. The buffer now hands a drain over only once the reply is delivered:
the serve loop answers whether each write crossed the socket, the holder
commits on delivery and re-attaches otherwise, and body reads run inside one
budget short of the reader's deadline. Binary and timed-out bodies are counted
and named instead of silently skipped.

- The serve loop serializes requests across connections and reads pipelined
  lines, so two concurrent drains can no longer open two debugger connections
  on one holder.
- The holder's socket, log, and state files are owner-only: its replies carry
  unredacted captured headers and bodies.
- The fallback probe now branches on the JSON-RPC method-not-found code that
  InspectorSession carries, not on error wording.
- A holder that cannot arm records its typed reason before exiting, and the
  readiness wait carries that reason; a `network stop` whose holder never
  reads its socket retires the recorded pid rather than abandoning it.
- The JavaScript hook only records bodies when the start opted in, discards a
  pre-existing hook's unread buffer at arm, and records what the runtime
  actually does when a hook was already installed.
- A pid-less `metro-cdp` state stops claiming a capture past a spawn grace
  window; the dump's positional include mode works over the CLI route; the
  stop line no longer renders a report path it never returns.
- Dead seam surface removed: an unconsumed typed reason, an unconsumed body
  flag, an unwired session-device option; `metro-runtime-ambiguous` and
  `metro-cdp-network-unsupported` now name themselves through the contracts
  table.
- New: a VM test executes the injected hook source as written, and a buffer
  test covers the re-attach path.
… the body rule true

- A holder that answered one request badly kept serving: the request queue
  catches a rejected answer rather than poisoning every later request with it,
  and stopServing runs its cleanup steps even when one of them refuses.
- The drain's eviction count is spent only for what its reply reported:
  evictions that land while a body-read drain is open belong to the next
  window, and an undelivered drain re-offers its count without doubling it.
- A hook adopted from an earlier run records the body rule that hook runs,
  and a dump says what would change it (reload, then stop and start) instead
  of advising a start again that cannot move the rule. A hook predating the
  stats field keeps this start's rule rather than a false body-off.
- network stop proves a holder's identity by its entry name, so the signal
  cannot land on a recycled pid, and the state writer narrows a stale temp
  file's mode before renaming it into place.

Co-Authored-By: Claude <noreply@anthropic.com>
…overy

The serve step made the state dir but binds its socket in the capture's
subdirectory, so the directory that must be owner-only is the one it creates.
A test now answers one request from a holder whose drain throws and reads the
next one over the same socket, which the queue's catch makes possible.
…ndow

- The drain reply's flush proof comes from write's error-first callback: a
  reader that vanished mid-write reported success, and the holder spent a
  window nobody received. Bodies now share the body budget per entry, so one
  hung getResponseBody cannot push the drain past the reader's deadline.
- A drain's window is returned when its answer throws anywhere, not only when
  delivery reports undelivered.
- The queue's recovery test fails at the seam production does: inside respond's
  own error handler, past the guard that already answers drain failures.
- The holder's stop path names its entry file with its extension, so tooling
  that merely names the file can never match, and a stop reports a holder it
  could not prove gone instead of claiming a stop it did not confirm.
- network start reports the body rule the runtime will run, and says at start
  when an adopted hook contradicts what the caller asked for.
- A reply the reader abandons mid-write hands its window back: the test proves
  the delivery check by destroying the socket during a 16 MB drain reply, and
  it fails on the pre-fix write-proof shape.
- A stop aimed at a recycled pid leaves the innocent process alone, the holder
  entry predicate matches only the entry file with its extension, and an
  adopted hook that contradicts the request says so at start.
- respond's failure path moved to answerFailure so the queue stays legible.
@thymikee

Copy link
Copy Markdown
Member Author

This head conflicts with main, so it needs a rebase before a full review. A necessity review of the feature's shape is running in the meantime, because it adds about 3,500 production lines and the linked issue #3930 is closed. I'll post its result here, so the rebase can include any reshaping.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of f992957

1 finding(s): 1 minor.

🟡 Minor (1)

Where Finding
packages/react-native/src/network/network-capture-runtime.ts:250 Hook body read locks the app's own response stream, breaking the app's response.text()

1 finding below minor hidden (user_settings.min_severity).

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

💬 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.

@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 f992957. The verdict and the full list are in the summary comment.

Comment on lines +250 to +274
var body = response && response.body;
var clone = response && typeof response.clone === 'function' ? response.clone() : undefined;
var declared = undefined;
try { declared = Number(response && response.headers && response.headers.get('content-length')); } catch (e) {}
// A body larger than the cap is never read whole to be cut down afterwards: when its
// size is declared, the read is skipped; when the runtime streams it, the read stops at
// the cap. Only a body of unknown size with no stream is read as text, and the cap
// still bounds what the buffer keeps.
var readable = CAPTURE_BODIES &&
!isBinaryContentType(contentType) &&
!(isFinite(declared) && declared > BODY_CAP);
if (readable && (body || clone)) {
// Record in a detached chain: the app receives its response at once, and the entry
// joins the buffer when the body read settles. A drain taken inside that window
// reports this request on a later dump, never half-written, and never delays the
// app for the read.
try {
var beganBody = readBodyBounded(body, clone, function (text) {
if (text !== undefined) entry.responseBody = cap(text);
try { record(entry); } catch (e) {}
});
if (beganBody) return response;
} catch (captureError) {}
}
record(entry);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Minor · Hook body read locks the app's own response stream, breaking the app's response.text()

On an RN runtime where Response exposes a ReadableStream (whatwg-fetch/Hermes), a --include body capture calls response.body.getReader() and reader.cancel(), so the app's own response.text()/json() on that same response throws or gets a cancelled body. readBodyBounded receives the live body as its first argument with clone only as fallback, so the bounded read always runs on the response the app is about to consume. The in-runtime test only uses a fixture with body: undefined, so this stream path is untested.

⚠️ Check this patch before you commit it: the review doubted it would be right as written.

Suggested change
var body = response && response.body;
var clone = response && typeof response.clone === 'function' ? response.clone() : undefined;
var declared = undefined;
try { declared = Number(response && response.headers && response.headers.get('content-length')); } catch (e) {}
// A body larger than the cap is never read whole to be cut down afterwards: when its
// size is declared, the read is skipped; when the runtime streams it, the read stops at
// the cap. Only a body of unknown size with no stream is read as text, and the cap
// still bounds what the buffer keeps.
var readable = CAPTURE_BODIES &&
!isBinaryContentType(contentType) &&
!(isFinite(declared) && declared > BODY_CAP);
if (readable && (body || clone)) {
// Record in a detached chain: the app receives its response at once, and the entry
// joins the buffer when the body read settles. A drain taken inside that window
// reports this request on a later dump, never half-written, and never delays the
// app for the read.
try {
var beganBody = readBodyBounded(body, clone, function (text) {
if (text !== undefined) entry.responseBody = cap(text);
try { record(entry); } catch (e) {}
});
if (beganBody) return response;
} catch (captureError) {}
}
record(entry);
var body = undefined;
var clone = response && typeof response.clone === 'function' ? response.clone() : undefined;
var declared = undefined;
Details

persona: senior-developer

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if it is wrong — I will re-check the cited code.

@thymikee

Copy link
Copy Markdown
Member Author

Closing this. It revives #3930, which was closed in favor of provider-owned network capture written as a HAR artifact (Limrun first). This branch predates that decision and now conflicts with main, including on ADR numbers. If React Native traffic capture is still needed, a smaller version would cover it. It would support React Native 0.83+ only through the built-in debugger network domain, read without consuming entries, and have network stop write the same HAR format as the provider path. It would also keep URL redaction and require an explicit device. That can start from a fresh issue.

@thymikee thymikee closed this Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant