Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

behavior-probe.ts

458 lines16.9 KB

1// Read by evals/mobile-behavior through the Hermes inspector; product modules load lazily so import order is unchanged.
2​
3interface Fiber {
4 readonly tag: number;
5 readonly type: unknown;
6 readonly child: Fiber | null;
7 readonly sibling: Fiber | null;
8 readonly memoizedProps: Record<string, unknown> | null;
9}
10interface DevToolsHook {
11 onCommitFiberRoot?: (
12 id: unknown,
13 root: { current: Fiber & { readonly actualDuration?: number } },
14 ...rest: unknown[]
15 ) => unknown;
16 __t3BehaviorProbe?: true;
18interface ListState {
19 readonly scroll: number;
20 readonly scrollLength: number;
21 readonly contentLength: number;
22 readonly isAtEnd: boolean;
23 readonly start: number;
24 readonly end: number;
25 readonly data: ReadonlyArray<{ readonly id?: string; readonly key?: string }>;
26 readonly positionAtIndex: (index: number) => number;
28interface Feed {
29 readonly threadId: string;
30 readonly environmentId: string;
31 readonly list: { readonly current: { getState?: () => ListState } | null } | undefined;
32 following: boolean | null;
34interface Atom {
35 readonly _atom: true;
37​
38// Every root React has committed; LogBox and other overlays commit their own.
39const roots = new Set<{ current: Fiber }>();
40​
41function installCommitHook() {
42 const hook = (globalThis as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook })
43 .__REACT_DEVTOOLS_GLOBAL_HOOK__;
44 if (!hook || typeof hook.onCommitFiberRoot !== "function") {
45 setTimeout(installCommitHook, 50);
46 return;
47 }
48 if (hook.__t3BehaviorProbe) return;
49 hook.__t3BehaviorProbe = true;
50 const original = hook.onCommitFiberRoot.bind(hook);
51 hook.onCommitFiberRoot = (id, next, ...rest) => {
52 roots.add(next);
53 // Development builds time each commit's render work on the root fiber.
54 if (perf) perf.commits.push({ at: performance.now(), ms: next.current.actualDuration ?? 0 });
55 return original(id, next, ...rest);
56 };
58​
59/** What one measured interaction did, from `perfStart` to `perfStop`; read by mobile:metrics. */
60interface PerfWindow {
61 readonly startedAt: number;
62 readonly inputs: Array<{ readonly kind: string; readonly at: number }>;
63 readonly commits: Array<{ readonly at: number; readonly ms: number }>;
64 readonly content: Array<{ readonly thread: string; readonly at: number; frameAt: number | null }>;
65 readonly keys: number[];
67let perf: PerfWindow | null = null;
68const perfInput = (kind: string) => perf?.inputs.push({ kind, at: performance.now() });
69​
70// The app's input points (see perf-probe-hooks.ts); they record only inside a window.
71Object.assign(globalThis, {
72 __t3PerfProbe: {
73 touchStart: () => perfInput("touch-start"),
74 touchEnd: () => perfInput("touch-end"),
75 menuAction: () => perfInput("menu-action"),
76 key: () => {
77 const window = perf;
78 if (!window) return;
79 const at = performance.now();
80 window.inputs.push({ kind: "key", at });
81 requestAnimationFrame(() => window.keys.push(performance.now() - at));
82 },
83 contentShown: (thread: string) => {
84 const window = perf;
85 if (!window) return;
86 const entry = { thread, at: performance.now(), frameAt: null as number | null };
87 window.content.push(entry);
88 requestAnimationFrame(() => {
89 entry.frameAt = performance.now();
90 });
91 },
92 },
93});
94​
95/** Visits every mounted fiber; `enter` returns the context passed to the fiber's children. */
96function walk<C>(fiber: Fiber | null, context: C, enter: (fiber: Fiber, context: C) => C) {
97 let node = fiber;
98 while (node) {
99 const next = enter(node, context);
100 if (node.child) walk(node.child, next, enter);
101 node = node.sibling;
102 }
104​
105const readAtom = <T>(atom: Atom): T => {
106 const { appAtomRegistry } = require("../../state/atom-registry") as {
107 appAtomRegistry: { get: (atom: Atom) => unknown };
108 };
109 return appAtomRegistry.get(atom) as T;
110};
111​
112/** Mounted thread feeds, the composer text the native editor was given, and the status pill. */
113function scanTree() {
114 const feeds = new Map<string, Feed>();
115 const editors: Array<{ value: string; expanded: boolean }> = [];
116 let floatingStatus: string | null = null;
117 let homeList: Array<{
118 type: string;
119 threadId?: string;
120 status?: string;
121 pinned?: boolean;
122 count?: number;
123 expanded?: boolean;
124 }> | null = null;
125 const enter = (fiber: Fiber, feed: Feed | null): Feed | null => {
126 const props = fiber.memoizedProps;
127 if (!props || typeof props !== "object") return feed;
128 if ("listRef" in props && typeof props.threadId === "string" && "detailRef" in props) {
129 const existing = feeds.get(props.threadId);
130 if (existing) return existing;
131 const created: Feed = {
132 threadId: props.threadId,
133 environmentId: String(props.environmentId),
134 list: props.listRef as Feed["list"],
135 following: null,
136 };
137 feeds.set(props.threadId, created);
138 return created;
139 }
140 if (feed && "maintainScrollAtEnd" in props && "maintainVisibleContentPosition" in props)
141 feed.following = props.maintainScrollAtEnd !== false;
142 if (typeof props.value === "string" && "chipsInert" in props)
143 editors.push({ value: props.value, expanded: props.chipsInert === false });
144 if ("status" in props && "showScrollToEnd" in props) {
145 const status = props.status as { kind?: string } | null;
146 floatingStatus = status?.kind ?? null;
147 }
148 if (homeList === null && Array.isArray(props.data) && "renderItem" in props) {
149 const data = props.data as ReadonlyArray<{
150 type?: string;
151 item?: { thread?: { id?: string }; pinned?: boolean };
152 count?: number;
153 expanded?: boolean;
154 }>;
155 if (data.some((entry) => entry?.type?.startsWith("v2-"))) {
156 const { resolveThreadListV2Status } = require("../threads/threadListV2") as {
157 resolveThreadListV2Status: (thread: unknown) => string;
158 };
159 homeList = data.map((entry) => ({
160 type: String(entry.type),
161 ...(entry.item?.thread?.id
162 ? {
163 threadId: entry.item.thread.id,
164 status: resolveThreadListV2Status(entry.item.thread),
165 pinned: entry.item.pinned === true,
166 }
167 : {}),
168 ...(typeof entry.count === "number" ? { count: entry.count } : {}),
169 ...(typeof entry.expanded === "boolean" ? { expanded: entry.expanded } : {}),
170 }));
171 }
172 }
173 return feed;
174 };
175 for (const root of roots) walk(root.current, null, enter);
176 return { feeds: [...feeds.values()], editors, floatingStatus, homeList };
178​
179function feedState(feed: Feed) {
180 const state = feed.list?.current?.getState?.();
181 if (!state) return { threadId: feed.threadId, ready: false as const };
182 const start = Math.max(0, state.start);
183 const end = Math.min(state.data.length - 1, state.end);
184 const rows: Record<string, number> = {};
185 for (let index = start; index <= end; index++) {
186 const row = state.data[index];
187 const key = row?.id ?? row?.key;
188 if (key) rows[key] = Math.round(state.positionAtIndex(index) - state.scroll);
189 }
190 return {
191 threadId: feed.threadId,
192 ready: true as const,
193 scroll: Math.round(state.scroll),
194 viewport: Math.round(state.scrollLength),
195 content: Math.round(state.contentLength),
196 fromEnd: Math.round(state.contentLength - state.scroll - state.scrollLength),
197 atEnd: state.isAtEnd,
198 following: feed.following,
199 count: state.data.length,
200 /** Screen y of each visible row, keyed by row id. */
201 rows,
202 };
204​
205function route() {
206 const { rootNavigationRef } =
207 require("../../lib/rootNavigation") as typeof import("../../lib/rootNavigation");
208 if (!rootNavigationRef.isReady()) return null;
209 const current = rootNavigationRef.getCurrentRoute();
210 const { workspaceHasColumns } = require("../layout/workspace/workspace-selection-store") as {
211 workspaceHasColumns: () => boolean;
212 };
213 return {
214 name: current?.name ?? null,
215 params: (current?.params ?? {}) as Record<string, unknown>,
216 columns: workspaceHasColumns(),
217 };
219​
220function snapshot() {
221 const scan = scanTree();
222 const at = route();
223 const threadId = typeof at?.params.threadId === "string" ? at.params.threadId : null;
224 const environmentId =
225 typeof at?.params.environmentId === "string" ? at.params.environmentId : null;
226 const threadKey = threadId && environmentId ? `${environmentId}:${threadId}` : null;
227 const { composerDraftsAtom } = require("../../state/use-composer-drafts") as {
228 composerDraftsAtom: Atom;
229 };
230 const { threadComposerErrorsAtom } = require("../../state/thread-composer-error") as {
231 threadComposerErrorsAtom: Atom;
232 };
233 const drafts = readAtom<Record<string, { text?: string }>>(composerDraftsAtom);
234 const errors = readAtom<Record<string, { message: string }>>(threadComposerErrorsAtom);
235 const { KeyboardController } = require("react-native-keyboard-controller") as {
236 KeyboardController: { isVisible: () => boolean };
237 };
238 const feed = visibleFeed(scan.feeds);
239 const { environmentThreadShells } = require("../../state/threads") as {
240 environmentThreadShells: { threadShellsAtom: Atom };
241 };
242 const { resolveThreadListV2Status } = require("../threads/threadListV2") as {
243 resolveThreadListV2Status: (thread: unknown) => string;
244 };
245 const shells = readAtom<ReadonlyArray<{ id: string; environmentId: string }>>(
246 environmentThreadShells.threadShellsAtom,
247 );
248 return {
249 /** Saved environments the app has threads from. */
250 environments: [...new Set(shells.map((shell) => shell.environmentId))],
251 /** The app's own status for every thread it knows, including rows folded into a shelf. */
252 threads: Object.fromEntries(
253 shells.map((shell) => [shell.id, resolveThreadListV2Status(shell)]),
254 ),
255 route: at,
256 feed: feed ? feedState(feed) : null,
257 composer: {
258 key: threadKey,
259 draft: threadKey ? (drafts[threadKey]?.text ?? "") : null,
260 drafts: Object.fromEntries(
261 Object.entries(drafts).map(([key, draft]) => [key, draft.text ?? ""]),
262 ),
263 editors: scan.editors,
264 error: threadKey ? (errors[threadKey]?.message ?? null) : null,
265 keyboard: KeyboardController.isVisible(),
266 },
267 floatingStatus: scan.floatingStatus,
268 homeList: scan.homeList,
269 };
271​
272const frames = { js: [] as number[], on: false };
273​
274function jsFrame(time: number) {
275 if (!frames.on) return;
276 frames.js.push(time);
277 requestAnimationFrame(jsFrame);
279​
280function uiFramesStart() {
281 "worklet";
282 const ui = globalThis as { __t3UiFrames?: number[]; __t3UiFramesOn?: boolean };
283 ui.__t3UiFrames = [];
284 ui.__t3UiFramesOn = true;
285 const tick = (time: number) => {
286 if (!ui.__t3UiFramesOn) return;
287 ui.__t3UiFrames!.push(time);
288 requestAnimationFrame(tick);
289 };
290 requestAnimationFrame(tick);
292​
293function uiFramesStop() {
294 "worklet";
295 const ui = globalThis as { __t3UiFrames?: number[]; __t3UiFramesOn?: boolean };
296 ui.__t3UiFramesOn = false;
297 return ui.__t3UiFrames ?? [];
299​
300let samples: Array<Record<string, unknown>> = [];
301let sampled: Feed | null = null;
302​
303// The feed is found once per recording; a tree walk on every frame would itself cause jank.
304function sampleFeed(time: number) {
305 if (!sampled) return;
306 const { following: _following, ...state } = feedState(sampled);
307 samples.push({ at: time, ...state });
308 requestAnimationFrame(sampleFeed);
310​
311function visibleFeed(feeds: ReadonlyArray<Feed>) {
312 const threadId = route()?.params.threadId;
313 return feeds.find((feed) => feed.threadId === threadId) ?? feeds.at(-1) ?? null;
315​
316installCommitHook();
317​
318Object.assign(globalThis, {
319 __t3Behavior: {
320 open(url: string) {
321 const { Linking } = require("react-native") as typeof import("react-native");
322 void Linking.openURL(url);
323 return true;
324 },
325 /** Restarts the JS app; deferred so the inspector call can reply first. */
326 reload() {
327 const { DevSettings } = require("react-native") as typeof import("react-native");
328 setTimeout(() => DevSettings.reload(), 100);
329 return true;
330 },
331 state: () => JSON.stringify(snapshot()),
332 /** Removes these saved environments (and their cached threads) through the app's own command. */
333 async forgetEnvironments(ids: ReadonlyArray<string>) {
334 const { runAtomCommand } = require("@t3tools/client-runtime/state/runtime") as {
335 runAtomCommand: (
336 registry: unknown,
337 command: unknown,
338 value: unknown,
339 options: object,
340 ) => Promise<unknown>;
341 };
342 const { appAtomRegistry } = require("../../state/atom-registry") as {
343 appAtomRegistry: unknown;
344 };
345 const { environmentCatalog } = require("../../connection/catalog") as {
346 environmentCatalog: { remove: unknown };
347 };
348 for (const id of ids)
349 await runAtomCommand(appAtomRegistry, environmentCatalog.remove, id, {
350 label: "behavior probe",
351 });
352 return true;
353 },
354 /** Records JS and UI frame times, and the visible feed on every JS frame. */
355 recordStart(withFeed: boolean) {
356 const { scheduleOnUI } =
357 require("react-native-worklets") as typeof import("react-native-worklets");
358 frames.js = [];
359 frames.on = true;
360 requestAnimationFrame(jsFrame);
361 scheduleOnUI(uiFramesStart);
362 samples = [];
363 sampled = withFeed ? visibleFeed(scanTree().feeds) : null;
364 if (sampled) requestAnimationFrame(sampleFeed);
365 return true;
366 },
367 recordStop() {
368 const { runOnUISync } =
369 require("react-native-worklets") as typeof import("react-native-worklets");
370 frames.on = false;
371 sampled = null;
372 return JSON.stringify({ js: frames.js, ui: runOnUISync(uiFramesStop), feed: samples });
373 },
374 /** Opens a perf window: inputs, commits, timeline content and frames until `perfStop`. */
375 perfStart() {
376 perf = { startedAt: performance.now(), inputs: [], commits: [], content: [], keys: [] };
377 const counter = globalThis as { __t3RenderCounterStart?: () => boolean };
378 counter.__t3RenderCounterStart?.();
379 return this.recordStart(false);
380 },
381 /** Cheap progress of the open window, so the harness can wait for quiet without a tree walk. */
382 perfPeek() {
383 const window = perf;
384 const last = Math.max(
385 window?.inputs.at(-1)?.at ?? 0,
386 window?.commits.at(-1)?.at ?? 0,
387 window?.content.at(-1)?.frameAt ?? 0,
388 );
389 return JSON.stringify({
390 now: performance.now(),
391 last,
392 inputs: window?.inputs.length ?? 0,
393 content: window?.content.flatMap((entry) => (entry.frameAt === null ? [] : [entry.thread])),
394 });
395 },
396 perfStop() {
397 const window = perf;
398 perf = null;
399 const counter = globalThis as { __t3RenderCounterStop?: () => unknown };
400 const { js, ui } = JSON.parse(this.recordStop()) as { js: number[]; ui: number[] };
401 const hermes = (
402 globalThis as { HermesInternal?: { getInstrumentedStats?: () => Record<string, number> } }
403 ).HermesInternal?.getInstrumentedStats?.();
404 return JSON.stringify({
405 ...window,
406 js,
407 ui,
408 renders: counter.__t3RenderCounterStop?.() ?? null,
409 heapBytes: hermes?.js_heapSize ?? null,
410 });
411 },
412 /** What the app holds: atom registry nodes by label, and mounted fibers by component. */
413 retention() {
414 const { appAtomRegistry } = require("../../state/atom-registry") as {
415 appAtomRegistry: { getNodes: () => ReadonlyMap<unknown, unknown> };
416 };
417 const atoms = new Map<string, number>();
418 for (const key of appAtomRegistry.getNodes().keys()) {
419 const label =
420 typeof key === "string"
421 ? `key:${key.split(/[:/]/)[0]}`
422 : ((key as { label?: readonly [string, ...unknown[]] | string }).label ?? "unlabeled");
423 const name = Array.isArray(label) ? String(label[0]) : String(label);
424 atoms.set(name, (atoms.get(name) ?? 0) + 1);
425 }
426 const fibers = new Map<string, number>();
427 let fiberCount = 0;
428 for (const root of roots)
429 walk(root.current, null, (fiber) => {
430 fiberCount += 1;
431 const type = fiber.type as { displayName?: string; name?: string } | string | null;
432 const name = typeof type === "string" ? type : (type?.displayName ?? type?.name ?? "");
433 if (name) fibers.set(name, (fibers.get(name) ?? 0) + 1);
434 return null;
435 });
436 const top = (map: Map<string, number>) =>
437 Object.fromEntries([...map].sort((a, b) => b[1] - a[1]).slice(0, 25));
438 return JSON.stringify({
439 atomCount: appAtomRegistry.getNodes().size,
440 fiberCount,
441 atoms: top(atoms),
442 fibers: top(fibers),
443 });
444 },
445 /** The Hermes heap, after a full collection when this runtime exposes `gc`. */
446 heap() {
447 const internal = globalThis as {
448 gc?: () => void;
449 HermesInternal?: { getInstrumentedStats?: () => Record<string, number> };
450 };
451 internal.gc?.();
452 return JSON.stringify({
453 bytes: internal.HermesInternal?.getInstrumentedStats?.().js_heapSize ?? null,
454 collected: typeof internal.gc === "function",
455 });
456 },
457 },
458});