Skip to content

Commit 4178ccd

Browse files
committed
fix(react-devtools): reach the debugger through the listing server, prefer the session's Metro on bridges, and flag untracked logs
- the CDP socket opens on the server that listed the target: behind a tunnel Metro advertises its own loopback address, which a client elsewhere cannot reach - a remote bridge session uses its recorded Metro server next to the agent before the public URL - errors notes that its list can be incomplete when the backend does not attribute every log to a component (React DevTools 5, seen on React Native 0.74 and 0.76) - help and docs: verified through agent-device proxy and on remote bridge sessions
1 parent 2acde20 commit 4178ccd

15 files changed

Lines changed: 136 additions & 33 deletions

‎src/cli/react-devtools/metro-inspector.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { createServer, type IncomingMessage } from 'node:http';
55
import { once } from 'node:events';
66
import type { Duplex } from 'node:stream';
77
import {
8+
debuggerUrlOn,
89
InspectorSession,
910
listMetroInspectorTargets,
1011
selectReactNativeTarget,
@@ -262,3 +263,19 @@ test('a dropped connection rejects the pending evaluation', async () => {
262263
await server.close().catch(() => {});
263264
}
264265
});
266+
267+
test('the debugger socket is opened on the server that listed the target', () => {
268+
const target = {
269+
id: 'device-1',
270+
title: 'app',
271+
webSocketDebuggerUrl: 'ws://127.0.0.1:8081/inspector/debug?device=d1&page=1',
272+
};
273+
assert.equal(
274+
debuggerUrlOn(new URL('http://10.0.2.2:8081'), target),
275+
'ws://10.0.2.2:8081/inspector/debug?device=d1&page=1',
276+
);
277+
assert.equal(
278+
debuggerUrlOn(new URL('https://bridge.example.test/api/metro/runtimes/r1/'), target),
279+
'wss://bridge.example.test/api/metro/runtimes/r1/inspector/debug?device=d1&page=1',
280+
);
281+
});

‎src/cli/react-devtools/metro-inspector.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,20 @@ export class InspectorSession {
313313
}
314314
}
315315

316+
/**
317+
* The target's debugger socket on the server that listed it. Metro builds `webSocketDebuggerUrl`
318+
* from the Host header it received, and a bridge or tunnel in front of Metro shows it Metro's own
319+
* loopback address, which a caller on another machine cannot reach.
320+
*/
321+
export function debuggerUrlOn(serverUrl: URL, target: MetroInspectorTarget): string {
322+
const advertised = new URL(target.webSocketDebuggerUrl);
323+
const url = withTrailingSlash(serverUrl);
324+
url.protocol = serverUrl.protocol === 'https:' ? 'wss:' : 'ws:';
325+
url.pathname = `${url.pathname.replace(/\/+$/, '')}${advertised.pathname}`;
326+
url.search = advertised.search;
327+
return url.toString();
328+
}
329+
316330
function withTrailingSlash(url: URL): URL {
317331
const copy = new URL(url);
318332
if (!copy.pathname.endsWith('/')) copy.pathname = `${copy.pathname}/`;

‎src/cli/react-devtools/react-component-tree.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ function appTree(rows = 3): RawComponentTree {
2727
nodes.push([20 + index, 'Memo(Row)', MEMO, 8, 8, String(index)]);
2828
nodes.push([40 + index, 'Text', FUNCTION, 20 + index, 20 + index, null]);
2929
}
30-
return { nodes, order: {}, logs: { '21': [1, 0] } };
30+
return { nodes, order: {}, logs: { '21': [1, 0] }, logsTracked: true };
3131
}
3232

3333
test('wrapper chains and runs of same-shape sibling rows each read as one line', () => {

‎src/cli/react-devtools/react-component-tree.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ export type RawComponentTree = {
1111
order: Record<string, number[]>;
1212
/** `[errors, warnings]` the component logged while rendering, by id. */
1313
logs: Record<string, [number, number]>;
14+
/**
15+
* Whether the backend attributes console errors and warnings to components from app start.
16+
* Older backends attribute them partly or not at all, so missing counts prove nothing.
17+
*/
18+
logsTracked: boolean;
1419
};
1520

1621
export type TreeNode = {
@@ -25,7 +30,11 @@ export type TreeNode = {
2530
warnings: number;
2631
};
2732

28-
export type ComponentTree = { roots: TreeNode[]; byId: Map<number, TreeNode> };
33+
export type ComponentTree = {
34+
roots: TreeNode[];
35+
byId: Map<number, TreeNode>;
36+
logsTracked: boolean;
37+
};
2938

3039
const ELEMENT_CLASS = 1;
3140
const ELEMENT_FORWARD_REF = 6;
@@ -77,7 +86,7 @@ export function buildComponentTree(raw: RawComponentTree): ComponentTree {
7786
(a, b) => (position.get(a.id) ?? Infinity) - (position.get(b.id) ?? Infinity),
7887
);
7988
}
80-
return { roots, byId };
89+
return { roots, byId, logsTracked: raw.logsTracked };
8190
}
8291

8392
export function componentRef(node: { id: number }): string {

‎src/cli/react-devtools/react-devtools-connection.test.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ test('the session Metro binding picks the dev server', async () => {
3737
assert.deepEqual(requested, ['http://127.0.0.1:19000/json/list']);
3838
});
3939

40-
test('a remote bridge profiles through the public dev-server URL without its bundle path', async () => {
40+
test('a remote bridge without a Metro binding profiles through the public dev-server URL without its bundle path', async () => {
4141
const { run, requested, options } = harness();
4242
options.flags = {
4343
leaseBackend: 'android-instance',
@@ -47,6 +47,17 @@ test('a remote bridge profiles through the public dev-server URL without its bun
4747
assert.deepEqual(requested, ['https://metro.example.test/json/list']);
4848
});
4949

50+
test('a remote bridge prefers the Metro server next to the agent over the public URL', async () => {
51+
const { run, requested, options, stateDir } = harness();
52+
bindSession(stateDir, 'http://127.0.0.1:8081/');
53+
options.flags = {
54+
leaseBackend: 'android-instance',
55+
metroPublicBaseUrl: 'https://metro.example.test',
56+
};
57+
await run('start');
58+
assert.deepEqual(requested, ['http://127.0.0.1:8081/json/list']);
59+
});
60+
5061
test('a host flag on its own keeps the port of the session binding', async () => {
5162
const { run, requested, stateDir } = harness();
5263
bindSession(stateDir, 'http://127.0.0.1:19000/');

‎src/cli/react-devtools/react-devtools-connection.ts‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { resolveMetroServerUrl } from '../../metro/metro-reload-endpoints.ts';
55
import { readMetroSessionHints } from '../../metro/metro-session-hints.ts';
66
import { isRemoteBridgeBackend } from '../commands/remote-bridge.ts';
77
import {
8+
debuggerUrlOn,
89
InspectorSession,
910
listMetroInspectorTargets,
1011
selectReactNativeTarget,
@@ -115,21 +116,28 @@ export function parseDevtoolsArgs(
115116
}
116117

117118
/**
118-
* Explicit flags, then a remote bridge's public dev-server URL, then the session's Metro binding.
119-
* A host or port flag on its own overrides that part of the binding and keeps the rest.
119+
* Explicit flags, then the session's Metro binding, then a remote bridge's public dev-server URL.
120+
* A host or port flag on its own overrides that part of the binding and keeps the rest. A bridged
121+
* session's binding is the Metro server next to the agent, which the app reaches through the
122+
* bridge; the public URL is the fallback when no binding was recorded.
120123
*/
121124
function resolveDevServerUrl(args: RuntimeArgs, options: ReactDevtoolsCommandOptions): URL {
122-
const publicBaseUrl = options.flags?.metroPublicBaseUrl?.trim();
123125
const explicit =
124126
args.metroHost !== undefined || args.metroPort !== undefined || args.bundleUrl !== undefined;
125-
if (!explicit && publicBaseUrl && isRemoteBridgeBackend(options.flags?.leaseBackend)) {
126-
return resolveMetroServerUrl({ bundleUrl: publicBaseUrl });
127-
}
128127
const complete =
129128
args.bundleUrl !== undefined || (args.metroHost !== undefined && args.metroPort !== undefined);
130129
const binding = complete
131130
? undefined
132131
: readMetroSessionHints({ stateDir: options.stateDir, session: options.session });
132+
const publicBaseUrl = options.flags?.metroPublicBaseUrl?.trim();
133+
if (
134+
!explicit &&
135+
!binding &&
136+
publicBaseUrl &&
137+
isRemoteBridgeBackend(options.flags?.leaseBackend)
138+
) {
139+
return resolveMetroServerUrl({ bundleUrl: publicBaseUrl });
140+
}
133141
return resolveMetroServerUrl({
134142
metroHost: args.metroHost,
135143
metroPort: args.metroPort,
@@ -149,7 +157,9 @@ export async function withAppRuntime<T>(
149157
appId: args.app,
150158
device: args.metroDevice,
151159
});
152-
const session: InspectorSession = await InspectorSession.connect(target.webSocketDebuggerUrl);
160+
const session: InspectorSession = await InspectorSession.connect(
161+
debuggerUrlOn(serverUrl, target),
162+
);
153163
try {
154164
await session.evaluate(
155165
`(${REACT_DEVTOOLS_RUNTIME_SOURCE})(${JSON.stringify(REACT_DEVTOOLS_RUNTIME_VERSION)})`,

‎src/cli/react-devtools/react-devtools-inspect-command.test.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,25 @@ test('errors returns the same shape when nothing logged', async () => {
142142
app.mount([{ id: 2, name: 'App' }]);
143143
const { run, options } = harness(app);
144144
options.flags = { json: true };
145-
assert.deepEqual(JSON.parse((await run('errors')).text).data, { total: 0, components: [] });
145+
assert.deepEqual(JSON.parse((await run('errors')).text).data, {
146+
total: 0,
147+
logsTracked: true,
148+
components: [],
149+
});
150+
});
151+
152+
test('errors says its list can be incomplete when the backend does not track logs per component', async () => {
153+
const app = new FakeAppRuntime({ consoleSettings: false });
154+
app.mount([{ id: 2, name: 'App' }]);
155+
const { run } = harness(app);
156+
assert.equal(
157+
(await run('errors')).text,
158+
[
159+
'No mounted component logged an error or warning while rendering.',
160+
"Note: this app's React DevTools backend does not attribute every console error and warning to a component, so this list can be incomplete; check agent-device logs as well.",
161+
'',
162+
].join('\n'),
163+
);
146164
});
147165

148166
test('each command refuses options it does not read', async () => {

‎src/cli/react-devtools/react-devtools-inspect-command.ts‎

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ type TreeResult = ({ ok: true } & RawComponentTree) | RuntimeFailure;
4545
type InspectedResult = InspectedComponent | { missing: true } | { error: string };
4646
type InspectResult = { ok: true; elements: Record<string, InspectedResult> } | RuntimeFailure;
4747

48+
const UNTRACKED_LOGS_NOTE =
49+
"Note: this app's React DevTools backend does not attribute every console error and warning to a component, so this list can be incomplete; check agent-device logs as well.";
50+
4851
const TREE_DEPTH = 8;
4952
const TREE_LINES = 60;
5053
const FIND_LIMIT = 20;
@@ -152,19 +155,30 @@ const HANDLERS: Record<InspectCommand, Handler> = {
152155
},
153156
errors: async (args, options, emit) => {
154157
const limit = args.limit ?? ERRORS_LIMIT;
155-
const { logged, inspected } = await withAppRuntime(args, options, async (session) => {
156-
const tree = await readTree(session);
157-
const logged = [...tree.byId.values()]
158-
.filter((node) => node.errors + node.warnings > 0)
159-
.sort((a, b) => b.errors - a.errors || b.warnings - a.warnings);
160-
const ids = logged.slice(0, limit).map((node) => node.id);
161-
return { logged, inspected: ids.length > 0 ? await inspectIds(session, ids) : {} };
162-
});
158+
const { logged, inspected, logsTracked } = await withAppRuntime(
159+
args,
160+
options,
161+
async (session) => {
162+
const tree = await readTree(session);
163+
const logged = [...tree.byId.values()]
164+
.filter((node) => node.errors + node.warnings > 0)
165+
.sort((a, b) => b.errors - a.errors || b.warnings - a.warnings);
166+
const ids = logged.slice(0, limit).map((node) => node.id);
167+
return {
168+
logged,
169+
inspected: ids.length > 0 ? await inspectIds(session, ids) : {},
170+
logsTracked: tree.logsTracked,
171+
};
172+
},
173+
);
174+
const untracked = logsTracked ? [] : [UNTRACKED_LOGS_NOTE];
163175
if (logged.length === 0) {
164-
emit('No mounted component logged an error or warning while rendering.', {
165-
total: 0,
166-
components: [],
167-
});
176+
emit(
177+
['No mounted component logged an error or warning while rendering.', ...untracked].join(
178+
'\n',
179+
),
180+
{ total: 0, logsTracked, components: [] },
181+
);
168182
return;
169183
}
170184
const shown = logged.slice(0, limit);
@@ -180,8 +194,10 @@ const HANDLERS: Record<InspectCommand, Handler> = {
180194
}
181195
if (logged.length > shown.length)
182196
lines.push(` +${logged.length - shown.length} more (--limit ${logged.length})`);
197+
lines.push(...untracked);
183198
emit(lines.join('\n'), {
184199
total: logged.length,
200+
logsTracked,
185201
components: shown.map((node) => {
186202
const messages = loggedMessages(inspected[String(node.id)]);
187203
return 'unavailable' in messages

‎src/cli/react-devtools/react-devtools-runtime.fixtures.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,8 @@ export type FakeRuntimeOptions = {
186186
fusebox?: boolean;
187187
devtoolsCoreModule?: boolean;
188188
hook?: boolean;
189+
/** React DevTools 6 hooks carry console settings and attribute logs to components from app start. */
190+
consoleSettings?: boolean;
189191
};
190192

191193
/** A JavaScript realm shaped like a React Native dev runtime, with the profiler runtime evaluable. */
@@ -198,6 +200,7 @@ export class FakeAppRuntime {
198200
listeners: Record<string, Listener[]>;
199201
sub: (event: string, fn: Listener) => () => void;
200202
emit: (event: string, payload: number[]) => void;
203+
settings?: { showInlineWarningsAndErrors: boolean };
201204
};
202205
domainInitializations = 0;
203206
customConnections = 0;
@@ -219,6 +222,9 @@ export class FakeAppRuntime {
219222
};
220223
},
221224
emit,
225+
...(options.consoleSettings === false
226+
? {}
227+
: { settings: { showInlineWarningsAndErrors: true } }),
222228
};
223229
const attach = () => this.hook.rendererInterfaces.set(1, this.renderer);
224230
if (options.attachAtInject !== false) attach();

‎src/cli/react-devtools/react-devtools-runtime.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,9 @@ export const REACT_DEVTOOLS_RUNTIME_SOURCE = String.raw`
312312
order.forEach(function (children, id) { childOrder[id] = children; });
313313
var counts = Object.create(null);
314314
logs.forEach(function (count, id) { counts[id] = count; });
315-
return { ok: true, nodes: nodes, order: childOrder, logs: counts };
315+
var h = hook();
316+
var logsTracked = !!(h.settings && h.settings.showInlineWarningsAndErrors !== false);
317+
return { ok: true, nodes: nodes, order: childOrder, logs: counts, logsTracked: logsTracked };
316318
}
317319
318320
function inspectOne(id) {

0 commit comments

Comments
 (0)