Skip to content

Commit 2acde20

Browse files
committed
fix(react-devtools): address review on capture, slow-commit accounting, tree runs, output safety, and Metro flags
- stop reads back only the renderers that started profiling - slow-commit accounting indexes findings once and counts a subtree inside an accounted subtree only once (profiles now carry each rendered element's ancestors) - tree collapses only siblings whose whole subtrees match, logged problems included - app-provided names, keys, values, and messages print without control characters - errors says when messages could not be read; an empty result keeps total - --metro-port must be a whole number; a host or port flag alone keeps the rest of the session binding
1 parent 77e9159 commit 2acde20

21 files changed

Lines changed: 434 additions & 99 deletions

‎src/__tests__/cli-react-devtools-session.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ test('react-devtools uses active remote connection session after defaults are me
6262
const sendToDaemon = async (): Promise<DaemonResponse> => ({ ok: true, data: {} });
6363

6464
try {
65-
await runCli(['react-devtools', 'profile', 'status', '--state-dir', stateDir], {
65+
await runCli(['react-devtools', 'profile', 'start', '--state-dir', stateDir], {
6666
sendToDaemon,
6767
});
6868
} finally {
@@ -73,5 +73,6 @@ test('react-devtools uses active remote connection session after defaults are me
7373

7474
assert.equal(exitCode, 0);
7575
assert.equal(vi.mocked(runReactDevtoolsCommand).mock.calls.length, 1);
76+
assert.deepEqual(vi.mocked(runReactDevtoolsCommand).mock.calls[0]?.[0], ['profile', 'start']);
7677
assert.equal(vi.mocked(runReactDevtoolsCommand).mock.calls[0]?.[1]?.session, 'adc-android');
7778
});

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,23 @@ test('custom hooks list the built-in hooks they call', () => {
7575
assert.match(text, /\nhooks:\n {2}State: 2\n {2}Contacts:\n {4}Memo: \[1, 2\]$/);
7676
});
7777

78+
test('values and messages the app controls cannot start a line or reach the terminal', () => {
79+
const text = formatInspectedComponent(
80+
7,
81+
component({
82+
props: {
83+
data: { title: { type: 'object', preview_short: 'x\n@c1 Forged' } },
84+
cleaned: [['title']],
85+
unserializable: [],
86+
},
87+
errors: [['bad\u001b[2Jvalue\nstack', 1]],
88+
}),
89+
);
90+
assert.equal(text.split('\n').length, 5);
91+
assert.match(text, /\n {2}title: x @c1 Forged\n/);
92+
assert.match(text, /\n {2}error: bad \[2Jvalue$/);
93+
});
94+
7895
test('logged errors and warnings print one line each with their repeat count', () => {
7996
const text = formatInspectedComponent(
8097
7,

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { componentName, componentRef, kindLabel } from './react-component-tree.ts';
2+
import { printable } from './react-devtools-text.ts';
23

34
type ValuePath = Array<string | number>;
45

@@ -132,7 +133,7 @@ function hookLines(value: DehydratedValue | null): string[] {
132133
function logLines(label: string, entries: Array<[string, number]>): string[] {
133134
return entries.map(
134135
([message, count]) =>
135-
` ${label}: ${clip(message.split('\n')[0] ?? '', VALUE_WIDTH)}${count > 1 ? ` (x${count})` : ''}`,
136+
` ${label}: ${clip(printable(message.split('\n')[0] ?? ''), VALUE_WIDTH)}${count > 1 ? ` (x${count})` : ''}`,
136137
);
137138
}
138139

@@ -161,5 +162,5 @@ export function formatInspectedComponent(id: number, component: InspectedCompone
161162
);
162163
const logs = formatComponentLogs(component);
163164
if (logs.length > 0) lines.push('logged while rendering:', ...logs);
164-
return lines.join('\n');
165+
return lines.map(printable).join('\n');
165166
}

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

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,10 @@ function appTree(rows = 3): RawComponentTree {
3030
return { nodes, order: {}, logs: { '21': [1, 0] } };
3131
}
3232

33-
test('wrapper chains and runs of sibling rows each read as one line', () => {
34-
const tree = buildComponentTree(appTree());
35-
const view = renderTree(tree.roots, 8, 60);
33+
test('wrapper chains and runs of same-shape sibling rows each read as one line', () => {
34+
const raw = appTree();
35+
raw.logs = {};
36+
const view = renderTree(buildComponentTree(raw).roots, 8, 60);
3637
assert.deepEqual(view.lines, [
3738
'@c1 ThemeProvider > @c2 StoreProvider > (2 wrappers) > @c5 Screen > @c6 App',
3839
' @c7 Header',
@@ -43,6 +44,42 @@ test('wrapper chains and runs of sibling rows each read as one line', () => {
4344
assert.equal(view.shown, 11, 'the rows under a collapsed run are counted as not shown');
4445
});
4546

47+
test('a row that logged a problem its neighbours did not keeps its own line', () => {
48+
const tree = buildComponentTree(appTree());
49+
assert.deepEqual(renderTree([tree.byId.get(8)!], 8, 60).lines, [
50+
'@c8 List',
51+
' @c20 Row [memo] key=0 > @c40 Text',
52+
' @c21 Row [memo] key=1 (1 error) > @c41 Text',
53+
' @c22 Row [memo] key=2 > @c42 Text',
54+
]);
55+
});
56+
57+
test('siblings with equal subtree sizes but different children stay open', () => {
58+
const raw = appTree(0);
59+
raw.nodes.push(
60+
[30, 'Scene', FUNCTION, 8, 8, 'a'],
61+
[31, 'Header', FUNCTION, 30, 30, null],
62+
[32, 'Scene', FUNCTION, 8, 8, 'b'],
63+
[33, 'Form', FUNCTION, 32, 32, null],
64+
[34, 'Scene', FUNCTION, 8, 8, 'c'],
65+
[35, 'Header', FUNCTION, 34, 34, null],
66+
);
67+
assert.deepEqual(renderTree([buildComponentTree(raw).byId.get(8)!], 8, 60).lines, [
68+
'@c8 List',
69+
' @c30 Scene key=a > @c31 Header',
70+
' @c32 Scene key=b > @c33 Form',
71+
' @c34 Scene key=c > @c35 Header',
72+
]);
73+
});
74+
75+
test('names and keys the app controls cannot start a line or reach the terminal', () => {
76+
const raw = appTree(0);
77+
raw.nodes.push([30, 'Evil\n@c1 Forged', FUNCTION, 8, 8, 'k\u001b[2J']);
78+
assert.deepEqual(renderTree([buildComponentTree(raw).byId.get(30)!], 8, 60).lines, [
79+
'@c30 Evil @c1 Forged key=k [2J',
80+
]);
81+
});
82+
4683
test('depth and line limits cut the tree and count what they leave out', () => {
4784
const tree = buildComponentTree(appTree());
4885
assert.deepEqual(renderTree(tree.roots, 1, 60).lines, [

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

Lines changed: 49 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { AppError } from '@agent-device/kernel/errors';
2+
import { printable } from './react-devtools-text.ts';
23

34
/** `[id, name, elementType, parentId, ownerId, key]` for every mounted component. */
45
type RawTreeNode = [number, string, number, number, number, string | null];
@@ -45,8 +46,17 @@ export function buildComponentTree(raw: RawComponentTree): ComponentTree {
4546
const byId = new Map<number, TreeNode>();
4647
for (const [id, displayName, elementType, , ownerId, key] of raw.nodes) {
4748
const [errors, warnings] = raw.logs[String(id)] ?? [0, 0];
48-
const name = componentName(displayName);
49-
byId.set(id, { id, name, elementType, key, ownerId, children: [], errors, warnings });
49+
const name = componentName(printable(displayName));
50+
byId.set(id, {
51+
id,
52+
name,
53+
elementType,
54+
key: key === null ? null : printable(key),
55+
ownerId,
56+
children: [],
57+
errors,
58+
warnings,
59+
});
5060
}
5161
const roots: TreeNode[] = [];
5262
for (const [id, , , parentId] of raw.nodes) {
@@ -124,21 +134,49 @@ function chainLabel(chain: TreeNode[]): string {
124134
].join(' > ');
125135
}
126136

127-
/** Siblings that collapse into one line: this many or more, of one name and one subtree size. */
137+
/** Siblings that collapse into one line: this many or more, all of one shape. */
128138
const MIN_COLLAPSED_RUN = 3;
129139

130140
/**
131-
* Consecutive siblings of one name and shape, such as list rows, read as one line. Screens of one
132-
* navigator share a name but not a shape, so the focused one stays open.
141+
* Numbers each subtree by its shape: names, element types, and logged problems, all the way down.
142+
* Two subtrees with one number print the same, apart from refs and keys.
143+
*/
144+
class SubtreeShapes {
145+
readonly #ids = new Map<string, number>();
146+
readonly #byNode = new Map<TreeNode, number>();
147+
148+
of(node: TreeNode): number {
149+
const known = this.#byNode.get(node);
150+
if (known !== undefined) return known;
151+
const signature = [
152+
node.name,
153+
node.elementType,
154+
node.errors,
155+
node.warnings,
156+
...node.children.map((child) => this.of(child)),
157+
].join('\0');
158+
let id = this.#ids.get(signature);
159+
if (id === undefined) {
160+
id = this.#ids.size;
161+
this.#ids.set(signature, id);
162+
}
163+
this.#byNode.set(node, id);
164+
return id;
165+
}
166+
}
167+
168+
/**
169+
* Consecutive siblings of one shape, such as list rows, read as one line. Screens of one navigator
170+
* share a name but not a shape, so the focused one stays open, and a row that logged a problem
171+
* its neighbours did not stays on its own line.
133172
*/
134-
function siblingRuns(children: TreeNode[]): TreeNode[][] {
173+
function siblingRuns(children: TreeNode[], shapes: SubtreeShapes): TreeNode[][] {
135174
const runs: TreeNode[][] = [];
136175
for (const child of children) {
137176
const run = runs.at(-1);
138177
const first = run?.[0];
139-
if (first && first.name === child.name && descendantCount(first) === descendantCount(child)) {
140-
run.push(child);
141-
} else runs.push([child]);
178+
if (first && shapes.of(first) === shapes.of(child)) run.push(child);
179+
else runs.push([child]);
142180
}
143181
return runs.flatMap((run) =>
144182
run.length >= MIN_COLLAPSED_RUN ? [run] : run.map((child) => [child]),
@@ -153,6 +191,7 @@ export type TreeView = { lines: string[]; shown: number; total: number };
153191
*/
154192
export function renderTree(roots: TreeNode[], depth: number, limit: number): TreeView {
155193
const lines: string[] = [];
194+
const shapes = new SubtreeShapes();
156195
let shown = 0;
157196
const total = roots.reduce((sum, root) => sum + 1 + descendantCount(root), 0);
158197
const visit = (node: TreeNode, level: number): void => {
@@ -166,7 +205,7 @@ export function renderTree(roots: TreeNode[], depth: number, limit: number): Tre
166205
return;
167206
}
168207
lines.push(`${indent}${chainLabel(chain)}`);
169-
for (const run of siblingRuns(tail.children)) {
208+
for (const run of siblingRuns(tail.children, shapes)) {
170209
if (lines.length >= limit) return;
171210
if (run.length === 1) {
172211
visit(run[0]!, level + 1);
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import { afterEach, test, vi } from 'vitest';
2+
import assert from 'node:assert/strict';
3+
import fs from 'node:fs';
4+
import path from 'node:path';
5+
import { runReactProfileCommand } from './react-profile-command.ts';
6+
import { commandHarness } from './react-devtools-command.fixtures.ts';
7+
8+
afterEach(() => {
9+
vi.restoreAllMocks();
10+
vi.unstubAllGlobals();
11+
});
12+
13+
const harness = () => commandHarness(runReactProfileCommand);
14+
15+
function bindSession(stateDir: string, controlBaseUrl: string) {
16+
fs.mkdirSync(path.join(stateDir, 'metro-sessions'), { recursive: true });
17+
fs.writeFileSync(
18+
path.join(stateDir, 'metro-sessions', 'qa.json'),
19+
JSON.stringify({ controlBaseUrl }),
20+
);
21+
}
22+
23+
test('explicit dev-server flags override the session binding', async () => {
24+
const { run, requested } = harness();
25+
await run('start', '--metro-port', '8082');
26+
assert.deepEqual(requested, ['http://localhost:8082/json/list']);
27+
});
28+
29+
test('the session Metro binding picks the dev server', async () => {
30+
const { run, requested, stateDir } = harness();
31+
fs.mkdirSync(path.join(stateDir, 'metro-sessions'), { recursive: true });
32+
fs.writeFileSync(
33+
path.join(stateDir, 'metro-sessions', 'qa.json'),
34+
JSON.stringify({ controlBaseUrl: 'http://127.0.0.1:19000/' }),
35+
);
36+
await run('start');
37+
assert.deepEqual(requested, ['http://127.0.0.1:19000/json/list']);
38+
});
39+
40+
test('a remote bridge profiles through the public dev-server URL without its bundle path', async () => {
41+
const { run, requested, options } = harness();
42+
options.flags = {
43+
leaseBackend: 'android-instance',
44+
metroPublicBaseUrl: 'https://metro.example.test/index.bundle?platform=android',
45+
};
46+
await run('start');
47+
assert.deepEqual(requested, ['https://metro.example.test/json/list']);
48+
});
49+
50+
test('a host flag on its own keeps the port of the session binding', async () => {
51+
const { run, requested, stateDir } = harness();
52+
bindSession(stateDir, 'http://127.0.0.1:19000/');
53+
await run('start', '--metro-host', '10.0.2.2');
54+
assert.deepEqual(requested, ['http://10.0.2.2:19000/json/list']);
55+
});
56+
57+
test('a port that is not a whole number is refused before connecting', async () => {
58+
const { run, requested } = harness();
59+
await assert.rejects(run('start', '--metro-port', '8081oops'), /Invalid Metro port: 8081oops/);
60+
assert.deepEqual(requested, []);
61+
});

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,15 +114,20 @@ export function parseDevtoolsArgs(
114114
};
115115
}
116116

117-
/** Explicit flags, then a remote bridge's public dev-server URL, then the session's Metro binding. */
117+
/**
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.
120+
*/
118121
function resolveDevServerUrl(args: RuntimeArgs, options: ReactDevtoolsCommandOptions): URL {
119122
const publicBaseUrl = options.flags?.metroPublicBaseUrl?.trim();
120123
const explicit =
121124
args.metroHost !== undefined || args.metroPort !== undefined || args.bundleUrl !== undefined;
122125
if (!explicit && publicBaseUrl && isRemoteBridgeBackend(options.flags?.leaseBackend)) {
123126
return resolveMetroServerUrl({ bundleUrl: publicBaseUrl });
124127
}
125-
const binding = explicit
128+
const complete =
129+
args.bundleUrl !== undefined || (args.metroHost !== undefined && args.metroPort !== undefined);
130+
const binding = complete
126131
? undefined
127132
: readMetroSessionHints({ stateDir: options.stateDir, session: options.session });
128133
return resolveMetroServerUrl({

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

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,13 +110,41 @@ test('errors lists the components that logged while rendering, with their messag
110110
});
111111

112112
test('a runtime whose tree another DevTools frontend owns fails with a typed reason', async () => {
113-
const { run } = harness(new FakeAppRuntime({ fusebox: false }));
113+
const app = new FakeAppRuntime();
114+
app.mount([{ id: 2, name: 'App' }]);
115+
app.renderer.queue = null;
116+
app.hook.sub('operations', () => {});
117+
const { run } = harness(app);
114118
await assert.rejects(
115119
run('tree'),
116120
(error: { details: { reason: string } }) => error.details.reason === 'tree-unavailable',
117121
);
118122
});
119123

124+
test('errors says when the messages of a component could not be read instead of listing none', async () => {
125+
const app = listApp();
126+
app.renderer.inspectElement = () => ({ type: 'error', message: 'hooks threw' });
127+
const { run, options } = harness(app);
128+
assert.match(
129+
(await run('errors')).text,
130+
/\n {2}@c5 Row: 1 error\n {4}messages unavailable: hooks threw\n$/,
131+
);
132+
options.flags = { json: true };
133+
const parsed = JSON.parse((await run('errors')).text) as {
134+
data: { components: Array<{ messagesUnavailable?: string; errors?: unknown }> };
135+
};
136+
assert.deepEqual(parsed.data.components[0]?.messagesUnavailable, 'hooks threw');
137+
assert.equal(parsed.data.components[0]?.errors, undefined);
138+
});
139+
140+
test('errors returns the same shape when nothing logged', async () => {
141+
const app = new FakeAppRuntime();
142+
app.mount([{ id: 2, name: 'App' }]);
143+
const { run, options } = harness(app);
144+
options.flags = { json: true };
145+
assert.deepEqual(JSON.parse((await run('errors')).text).data, { total: 0, components: [] });
146+
});
147+
120148
test('each command refuses options it does not read', async () => {
121149
const { run } = harness();
122150
await assert.rejects(

0 commit comments

Comments
 (0)