Skip to content

Commit f25394b

Browse files
committed
fix(react-devtools): fail closed across devices, drop test seams, and word findings as heuristics
1 parent 273417d commit f25394b

16 files changed

Lines changed: 401 additions & 478 deletions

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { runCmdStreaming } from '@agent-device/host-kit/command';
2+
import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution';
23
import {
34
ensureReactDevtoolsCompanion,
45
stopReactDevtoolsCompanion,
@@ -199,7 +200,9 @@ export async function runReactDevtoolsCommand(
199200
const { runReactProfileCommand } = await import('../react-profiler/react-profile-command.ts');
200201
return await runReactProfileCommand(args.slice(1), {
201202
flags: options.flags,
202-
stateDir: options.stateDir ?? process.cwd(),
203+
stateDir:
204+
options.stateDir ??
205+
resolveDaemonPaths((options.env ?? process.env).AGENT_DEVICE_STATE_DIR).baseDir,
203206
session: options.session ?? options.flags?.session ?? 'default',
204207
});
205208
}

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

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { test } from 'vitest';
1+
import { afterEach, test, vi } from 'vitest';
22
import assert from 'node:assert/strict';
33
import { createHash } from 'node:crypto';
44
import { createServer, type IncomingMessage } from 'node:http';
@@ -40,12 +40,26 @@ test('auxiliary pages without React Native metadata are never profiled', () => {
4040
);
4141
});
4242

43-
test('the most recently listed device wins when one app runs on several devices', () => {
44-
const selected = selectReactNativeTarget([
45-
target('ipad-1', { appId: 'com.app' }),
46-
target('pixel-1', { appId: 'com.app' }),
47-
]);
48-
assert.equal(selected.id, 'pixel-1');
43+
afterEach(() => {
44+
vi.unstubAllGlobals();
45+
});
46+
47+
test('one app on several devices fails closed until --metro-device names one', () => {
48+
const targets = [
49+
target('ipad-1', { appId: 'com.app', deviceName: 'iPad Air' }),
50+
target('pixel-1', { appId: 'com.app', deviceName: 'Pixel 9' }),
51+
target('pixel-2', { appId: 'com.app', deviceName: 'Pixel 9' }),
52+
];
53+
assert.throws(
54+
() => selectReactNativeTarget(targets),
55+
(error: { code: string; details: { hint: string } }) => {
56+
assert.equal(error.code, 'INVALID_ARGS');
57+
assert.equal(error.details.hint, 'Pass --metro-device with one of: iPad Air, Pixel 9.');
58+
return true;
59+
},
60+
);
61+
assert.equal(selectReactNativeTarget(targets, { device: 'Pixel 9' }).id, 'pixel-1');
62+
assert.equal(selectReactNativeTarget(targets, { device: 'ipad' }).id, 'ipad-1');
4963
});
5064

5165
test('distinct apps need --app; older dev servers report the app id as the description', () => {
@@ -55,32 +69,33 @@ test('distinct apps need --app; older dev servers report the app id as the descr
5569
];
5670
assert.throws(
5771
() => selectReactNativeTarget(targets),
58-
(error: { details: { hint: string } }) => {
72+
(error: { code: string; details: { hint: string } }) => {
73+
assert.equal(error.code, 'INVALID_ARGS');
5974
assert.equal(error.details.hint, 'Pass --app with one of: com.one, com.two.');
6075
return true;
6176
},
6277
);
63-
assert.equal(selectReactNativeTarget(targets, 'com.two').id, 'b-1');
78+
assert.equal(selectReactNativeTarget(targets, { appId: 'com.two' }).id, 'b-1');
6479
assert.throws(
65-
() => selectReactNativeTarget(targets, 'com.three'),
66-
/No React Native runtime for com\.three/,
80+
() => selectReactNativeTarget(targets, { appId: 'com.three' }),
81+
/No matching React Native runtime/,
6782
);
6883
});
6984

7085
test('an unreachable dev server names the address it tried', async () => {
71-
const failingFetch = (async () => {
86+
vi.stubGlobal('fetch', async () => {
7287
throw new TypeError('fetch failed');
73-
}) as typeof fetch;
88+
});
7489
await assert.rejects(
75-
listMetroInspectorTargets(new URL('http://localhost:8081'), failingFetch),
90+
listMetroInspectorTargets(new URL('http://localhost:8081')),
7691
/Could not reach the React Native dev server at http:\/\/localhost:8081/,
7792
);
7893
});
7994

8095
test('a server that is not a dev server is named instead of yielding no targets', async () => {
81-
const htmlFetch = (async () => new Response('<html></html>', { status: 200 })) as typeof fetch;
96+
vi.stubGlobal('fetch', async () => new Response('<html></html>', { status: 200 }));
8297
await assert.rejects(
83-
listMetroInspectorTargets(new URL('http://localhost:8081'), htmlFetch),
98+
listMetroInspectorTargets(new URL('http://localhost:8081')),
8499
/is not a React Native dev server/,
85100
);
86101
});

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

Lines changed: 46 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,11 @@ export function targetAppId(target: MetroInspectorTarget): string {
2424
return target.appId ?? target.description ?? target.title;
2525
}
2626

27-
export async function listMetroInspectorTargets(
28-
serverUrl: URL,
29-
fetchImpl: typeof fetch = fetch,
30-
): Promise<MetroInspectorTarget[]> {
27+
export async function listMetroInspectorTargets(serverUrl: URL): Promise<MetroInspectorTarget[]> {
3128
const listUrl = new URL('json/list', withTrailingSlash(serverUrl));
3229
let response: Response;
3330
try {
34-
response = await fetchImpl(listUrl, { signal: AbortSignal.timeout(TARGET_LIST_TIMEOUT_MS) });
31+
response = await fetch(listUrl, { signal: AbortSignal.timeout(TARGET_LIST_TIMEOUT_MS) });
3532
} catch (error) {
3633
throw new AppError(
3734
'COMMAND_FAILED',
@@ -81,27 +78,42 @@ function deviceKey(target: MetroInspectorTarget): string {
8178
);
8279
}
8380

81+
export type RuntimeTargetFilter = {
82+
/** Bundle id or package name, as the dev server reports it. */
83+
appId?: string;
84+
/** Device name or logical device id, as the dev server reports it. */
85+
device?: string;
86+
};
87+
8488
/**
85-
* Picks the React Native runtime to profile. Pages without the `reactNative` field are not app
89+
* Picks the one React Native runtime to profile. Pages without the `reactNative` field are not app
8690
* runtimes, and worklet runtimes render no React tree. A device registers its main runtime before
87-
* any secondary one, so the lowest page number wins per device; with several devices running one
88-
* app, the most recently listed device wins. Distinct apps need `appId` to disambiguate.
91+
* any secondary one, so the lowest page number wins per device. Several apps or several devices
92+
* fail closed: the caller must narrow to exactly one runtime.
8993
*/
9094
export function selectReactNativeTarget(
9195
targets: MetroInspectorTarget[],
92-
appId?: string,
96+
filter: RuntimeTargetFilter = {},
9397
): MetroInspectorTarget {
9498
const runtimes = targets.filter(
9599
(target) =>
96100
target.reactNative !== undefined && !WORKLET_RUNTIME_PATTERN.test(target.description ?? ''),
97101
);
98-
const candidates = appId ? runtimes.filter((target) => targetAppId(target) === appId) : runtimes;
102+
const candidates = runtimes.filter(
103+
(target) =>
104+
(filter.appId === undefined || targetAppId(target) === filter.appId) &&
105+
(filter.device === undefined ||
106+
target.deviceName === filter.device ||
107+
deviceKey(target) === filter.device),
108+
);
99109
if (candidates.length === 0) {
100-
const seen = runtimes.map(targetAppId);
110+
const seen = runtimes.map(
111+
(target) => `${targetAppId(target)} on ${target.deviceName ?? deviceKey(target)}`,
112+
);
101113
throw new AppError(
102114
'COMMAND_FAILED',
103-
appId
104-
? `No React Native runtime for ${appId} is connected to the dev server.`
115+
filter.appId || filter.device
116+
? 'No matching React Native runtime is connected to the dev server.'
105117
: 'No React Native runtime is connected to the dev server.',
106118
{
107119
hint:
@@ -125,12 +137,30 @@ export function selectReactNativeTarget(
125137
for (const target of candidates) {
126138
const key = deviceKey(target);
127139
const current = devices.get(key);
128-
devices.delete(key);
129140
devices.set(key, current && pageNumber(current) <= pageNumber(target) ? current : target);
130141
}
131-
return [...devices.values()].at(-1)!;
142+
if (devices.size > 1) {
143+
const names = [...devices.values()].map((target) => target.deviceName ?? deviceKey(target));
144+
throw new AppError(
145+
'INVALID_ARGS',
146+
'The app is connected to the dev server from several devices.',
147+
{
148+
hint: `Pass --metro-device with one of: ${names.join(', ')}.`,
149+
},
150+
);
151+
}
152+
return [...devices.values()][0]!;
132153
}
133154

155+
/**
156+
* Node's WebSocket (undici) accepts an init object with request headers; the DOM typing this
157+
* repo compiles against only declares subprotocols.
158+
*/
159+
const WebSocketWithHeaders = WebSocket as unknown as new (
160+
url: URL,
161+
init: { headers: Record<string, string> },
162+
) => WebSocket;
163+
134164
type PendingCall = { resolve: (value: unknown) => void; reject: (error: Error) => void };
135165

136166
/** Minimal Chrome DevTools Protocol client over the dev server's inspector proxy. */
@@ -155,7 +185,7 @@ export class InspectorSession {
155185
// Metro refuses debugger upgrades without a loopback Origin, and Expo's dev server terminates
156186
// any whose Origin host differs from its own 127.0.0.1:<port> base URL.
157187
const origin = `http://127.0.0.1:${url.port || (url.protocol === 'wss:' ? '443' : '80')}`;
158-
const socket = new WebSocket(url, { headers: { origin } } as unknown as string[]);
188+
const socket = new WebSocketWithHeaders(url, { headers: { origin } });
159189
await new Promise<void>((resolve, reject) => {
160190
const timer = setTimeout(() => {
161191
socket.close();

‎src/cli/react-profiler/react-profile-analysis.test.ts‎

Lines changed: 89 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,10 @@ test('memo bypassed by props that change on every render names the props, their
4848
);
4949

5050
const request = selectPropKindRequests(raw);
51-
assert.deepEqual(Object.values(request), [['onPress', 'style']]);
51+
assert.deepEqual(
52+
new Set(Object.values(request).map((keys) => keys.join())),
53+
new Set(['onPress,style']),
54+
);
5255
const [id] = Object.keys(request);
5356
const [finding] = analyzeReactProfile(raw, {
5457
[id!]: { onPress: 'function', style: 'object' },
@@ -57,7 +60,7 @@ test('memo bypassed by props that change on every render names the props, their
5760
assert.equal(finding?.component, 'Row');
5861
assert.match(
5962
finding?.evidence ?? '',
60-
/onPress \(function\), style \(object\) every render from List/,
63+
/onPress \(function\), style \(object\) on those updates from List/,
6164
);
6265
});
6366

@@ -96,7 +99,7 @@ test('renders forced only by a parent re-render point at the owner to memoize be
9699
assert.deepEqual(kinds(raw), ['parent-cascade ResultRow']);
97100
assert.match(
98101
analyzeReactProfile(raw).findings[0]!.evidence,
99-
/whenever Search rendered across 15 instances/,
102+
/when Search rendered across 15 instances/,
100103
);
101104
});
102105

@@ -157,6 +160,89 @@ test('a state update set right after the previous commit is reported as an effec
157160
assert.ok(kinds(raw).includes('effect-chain Filtered'));
158161
});
159162

163+
test('a follow-up commit counts once per component however many of its instances triggered it', () => {
164+
const raw = rawProfile(
165+
{
166+
1: ['Screen'],
167+
2: ['Filtered', FUNCTION, 1],
168+
3: ['Filtered', FUNCTION, 1],
169+
4: ['Filtered', FUNCTION, 1],
170+
},
171+
repeat(3, (i) => i).flatMap((i): Array<[number, number, number[], Render[]]> => [
172+
[
173+
i * 300,
174+
10,
175+
[1],
176+
[
177+
[1, 1, [0, null, [0], null]],
178+
[2, 2],
179+
[3, 2],
180+
[4, 2],
181+
],
182+
],
183+
[
184+
i * 300 + 12,
185+
10,
186+
[2, 3, 4],
187+
[
188+
[2, 3, [0, null, [0], null]],
189+
[3, 3, [0, null, [0], null]],
190+
[4, 3, [0, null, [0], null]],
191+
],
192+
],
193+
]),
194+
);
195+
const chain = analyzeReactProfile(raw).findings.find(
196+
(finding) => finding.kind === 'effect-chain',
197+
);
198+
assert.match(
199+
chain?.evidence ?? '',
200+
/^3 follow-up commits it triggered right after rendering, likely state set in an effect \(30ms\)$/,
201+
);
202+
});
203+
204+
test('without inspected value kinds a memo bypass names the changed props without claiming new identities', () => {
205+
const rows = repeat(12, (i) => 10 + i);
206+
const elements: Record<number, [string, number?, number?]> = { 1: ['List'] };
207+
for (const id of rows) elements[id] = ['Row', MEMO, 1];
208+
const raw = rawProfile(
209+
elements,
210+
repeat(3, (i) => [
211+
i * 200,
212+
30,
213+
[1],
214+
[[1, 1, [0, null, [0], null]], ...rows.map((id): Render => [id, 2, [0, [0], null, null]])],
215+
]),
216+
['onPress'],
217+
);
218+
const [finding] = analyzeReactProfile(raw).findings;
219+
assert.equal(
220+
finding?.evidence,
221+
'memo bypassed on 36/36 updates; onPress changed from List (value kinds not inspected)',
222+
);
223+
});
224+
225+
test('every large mount group in a commit is its own eager-mount finding', () => {
226+
const tiles = repeat(220, (i) => 10 + i);
227+
const rows = repeat(210, (i) => 1000 + i);
228+
const elements: Record<number, [string, number?, number?]> = { 1: ['Catalog'] };
229+
for (const id of tiles) elements[id] = ['Tile', FUNCTION, 1];
230+
for (const id of rows) elements[id] = ['Row', FUNCTION, 1];
231+
const raw = rawProfile(elements, [
232+
[
233+
0,
234+
400,
235+
[1],
236+
[
237+
[1, 5, [0, null, [0], null]],
238+
...tiles.map((id): Render => [id, 1, 1]),
239+
...rows.map((id): Render => [id, 1, 1]),
240+
],
241+
],
242+
]);
243+
assert.deepEqual(kinds(raw).sort(), ['eager-mount Row', 'eager-mount Tile']);
244+
});
245+
160246
test('many commits from one updater in a short span are a render storm', () => {
161247
const raw = rawProfile(
162248
{ 1: ['Clock'] },

0 commit comments

Comments
 (0)