test(mobile): measure renders on a device #21001
Mergedjuliusmarmingemerged 11 commits into
main fromrefs/pull/21001/headmerged by juliusmarminge View on GitHubjuliusmarminge added labelsmacroscope-review
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labels📱 Native Change
- @@ -0,0 +140,21 @@140+ return original(id, root, ...rest);141+ };142+}143+144+const state: RenderCounterState = {145+ on: false,146+ commits: 0,147+ regionRoots: new Map(),148+ counts: new Map(),149+ causes: new Map(),150+};151+152+install(state);153+154+Object.assign(globalThis, {155+ /** Routes an app link in-process, so drivers need no simctl or adb access. */156+ __t3RenderCounterOpen(url: string) {157+ const { Linking } = require("react-native") as typeof import("react-native");158+ void Linking.openURL(url);159+ return true;160+ },apps/mobile/src/features/development/render-counter.ts line 123Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +107,21 @@107+function install(state: RenderCounterState) {108+ const hook = (globalThis as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook })109+ .__REACT_DEVTOOLS_GLOBAL_HOOK__;110+ if (!hook || typeof hook.onCommitFiberRoot !== "function") {111+ setTimeout(() => install(state), 50);112+ return;113+ }114+ if (hook.__t3RenderCounter) return;115+ hook.__t3RenderCounter = true;116+ const original = hook.onCommitFiberRoot.bind(hook);117+118+ const visit = (fiber: Fiber | null, parentName: string, region: string) => {119+ let node = fiber;120+ while (node) {121+ const alternate = node.alternate;122+ const name = COMPONENT_TAGS.has(node.tag) ? nameOf(node) : null;123+ const nodeRegion = (name && state.regionRoots.get(name)) || region;124+ const rendered = name !== null && (node.flags & PERFORMED_WORK) === PERFORMED_WORK;125+ if (rendered) {126+ increment(state.counts, `${nodeRegion}\u0000${name}`);127+ increment(state.causes, `${name} ${causeOf(node, parentName)}`);@@ -0,0 +129,21 @@129+130+const connectServer = Effect.fn("measure.connectServer")(function* (options: Options) {131+ const http = (yield* HttpClient.HttpClient).pipe(132+ HttpClient.mapRequest((request) =>133+ request.pipe(134+ HttpClientRequest.bearerToken(options.token),135+ HttpClientRequest.setHeader(136+ ORCHESTRATION_PROTOCOL_HEADER,137+ String(ORCHESTRATION_PROTOCOL_VERSION),138+ ),139+ ),140+ ),141+ HttpClient.filterStatusOk,142+ );143+ const descriptor = yield* http144+ .get(`${options.server}/.well-known/t3/environment`)145+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)));146+ const shell = yield* http147+ .get(`${options.server}/api/orchestration/shell`)148+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(OrchestrationV2ShellSnapshot)));149+ let projectId = shell.projects.find(apps/mobile/scripts/measure-renders.mts line 239Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +208,21 @@208+ instanceId: ProviderInstanceId.make(options.provider),209+ model: options.model,210+ },211+ // The prompt needs no tools; approval-required keeps a stray call from acting.212+ runtimeMode: "approval-required",213+ interactionMode: "default",214+ workspaceStrategy: { type: "root" },215+ initialMessage: { text: STREAM_PROMPT, attachments: [] },216+ });217+ yield* evaluate(218+ `__t3RenderCounterOpen(${encodeJson(`${options.scheme}://threads/${environmentId}/${threadId}`)})`,219+ );220+ const projectionOf = (item: { kind: string; projection?: OrchestrationV2ThreadProjection }) =>221+ item.kind === "snapshot" && item.projection222+ ? Effect.succeed(item.projection)223+ : client["orchestration.getThreadProjection"]({ threadId });224+ const streaming = yield* client["orchestration.subscribeThread"]({ threadId }).pipe(225+ Stream.mapEffect(projectionOf),226+ Stream.filter((projection) => streamingItem(projection) !== undefined),227+ Stream.runHead,228+ Effect.timeout("90 seconds"),@@ -0,0 +135,21 @@135+ HttpClientRequest.setHeader(136+ ORCHESTRATION_PROTOCOL_HEADER,137+ String(ORCHESTRATION_PROTOCOL_VERSION),138+ ),139+ ),140+ ),141+ HttpClient.filterStatusOk,142+ );143+ const descriptor = yield* http144+ .get(`${options.server}/.well-known/t3/environment`)145+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)));146+ const shell = yield* http147+ .get(`${options.server}/api/orchestration/shell`)148+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(OrchestrationV2ShellSnapshot)));149+ let projectId = shell.projects.find(150+ (project) => project.workspaceRoot === options.projectRoot,151+ )?.id;152+ if (!projectId) {153+ projectId = ProjectId.make(yield* uuid);154+ yield* (yield* FileSystem.FileSystem).makeDirectory(options.projectRoot, { recursive: true });155+ yield* http.execute(
- apps/mobile/scripts/measure-renders.mts lines 202 to 251OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +231,21 @@231+ return yield* new MeasureError({ message: `Run ${run}: the reply never started streaming.` });232+ yield* evaluate(`__t3RenderCounterStart(${encodeJson(REGION_ROOTS)})`);233+ yield* Effect.sleep(`${options.windowSeconds} seconds`);234+ const report = yield* decodeReport(yield* evaluate("JSON.stringify(__t3RenderCounterStop())"));235+ // React commits on every streamed delta, so an empty window means the app is not on the thread.236+ if (report.commits === 0)237+ return yield* new MeasureError({238+ message: `Run ${run}: no React commits in the window. Check the device for a red box.`,239+ });240+ const after = yield* client["orchestration.getThreadProjection"]({ threadId });241+ const stillStreaming = streamingItem(after) !== undefined;242+ const activeRun = after.runs.find(243+ (entry) => !["completed", "failed", "interrupted", "cancelled"].includes(entry.status),244+ );245+ if (activeRun)246+ yield* client["orchestration.dispatchCommand"]({247+ type: "run.interrupt",248+ commandId: CommandId.make(yield* uuid),249+ threadId,250+ runId: activeRun.id,251+ });
- @@ -0,0 +213,21 @@213+ runtimeMode: "approval-required",214+ interactionMode: "default",215+ workspaceStrategy: { type: "root" },216+ initialMessage: { text: STREAM_PROMPT, attachments: [] },217+ });218+ // A failed or interrupted window must not leave a provider turn running.219+ yield* Effect.addFinalizer(() =>220+ Effect.gen(function* () {221+ const after = yield* client["orchestration.getThreadProjection"]({ threadId });222+ const activeRun = after.runs.find(223+ (entry) => !["completed", "failed", "interrupted", "cancelled"].includes(entry.status),224+ );225+ if (!activeRun) return;226+ yield* client["orchestration.dispatchCommand"]({227+ type: "run.interrupt",228+ commandId: CommandId.make(yield* uuid),229+ threadId,230+ runId: activeRun.id,231+ });232+ }).pipe(Effect.ignore),233+ );
- apps/mobile/src/features/development/render-counter.ts lines 77 to 77OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +57,21 @@57+58+function isEffect(value: unknown): boolean {59+ return (60+ typeof value === "object" &&61+ value !== null &&62+ "create" in value &&63+ "deps" in value &&64+ "tag" in value65+ );66+}67+68+function changedStateSlot(alternate: Fiber, node: Fiber): number {69+ let a = alternate.memoizedState;70+ let b = node.memoizedState;71+ for (let index = 0; a && b && index < 800; index++) {72+ const before = a.memoizedState;73+ const after = b.memoizedState;74+ if (!isEffect(after) && !Object.is(before, after)) {75+ // A memo/callback slot whose deps did not change is a recompute, not a cause.76+ const memoSlot =77+ Array.isArray(before) && Array.isArray(after) && before.length === 2 && after.length === 2;
- @@ -0,0 +220,21 @@220+ threadId,221+ runId: activeRun.id,222+ });223+ }).pipe(Effect.ignore),224+ );225+ yield* evaluate(226+ `__t3RenderCounterOpen(${encodeJson(`${options.scheme}://threads/${environmentId}/${threadId}`)})`,227+ );228+ const projectionOf = (item: { kind: string; projection?: OrchestrationV2ThreadProjection }) =>229+ item.kind === "snapshot" && item.projection230+ ? Effect.succeed(item.projection)231+ : client["orchestration.getThreadProjection"]({ threadId });232+ const streaming = yield* client["orchestration.subscribeThread"]({ threadId }).pipe(233+ Stream.mapEffect(projectionOf),234+ Stream.filter((projection) => streamingItem(projection) !== undefined),235+ Stream.runHead,236+ Effect.timeout("90 seconds"),237+ );238+ if (Option.isNone(streaming))239+ return yield* new MeasureError({ message: `Run ${run}: the reply never started streaming.` });240+ yield* evaluate("__t3RenderCounterStart()");@@ -0,0 +102,21 @@102+}103+104+function install(state: RenderCounterState) {105+ const hook = (globalThis as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook })106+ .__REACT_DEVTOOLS_GLOBAL_HOOK__;107+ if (!hook || typeof hook.onCommitFiberRoot !== "function") {108+ setTimeout(() => install(state), 50);109+ return;110+ }111+ if (hook.__t3RenderCounter) return;112+ hook.__t3RenderCounter = true;113+ const original = hook.onCommitFiberRoot.bind(hook);114+115+ const visit = (fiber: Fiber | null, parentName: string) => {116+ let node = fiber;117+ while (node) {118+ const alternate = node.alternate;119+ const name = COMPONENT_TAGS.has(node.tag) ? nameOf(node) : null;120+ const rendered = name !== null && (node.flags & PERFORMED_WORK) === PERFORMED_WORK;121+ if (rendered) {122+ increment(state.counts, name);
- @@ -0,0 +243,21 @@243+ // React commits on every streamed delta, so an empty window means the app is not on the thread.244+ if (report.commits === 0)245+ return yield* new MeasureError({246+ message: `Run ${run}: no React commits in the window. Check the device for a red box.`,247+ });248+ const after = yield* client["orchestration.getThreadProjection"]({ threadId });249+ return { report, stillStreaming: streamingItem(after) !== undefined };250+}, Effect.scoped);251+252+/** Opens a screen from a freshly loaded Home and records its mount and data settling. */253+const measureRouteOpen = Effect.fn("measure.routeOpen")(function* (254+ options: Options,255+ route: string,256+ run: number,257+) {258+ // A link to an already-open screen only refocuses it, so each run starts from a reload.259+ yield* Effect.scoped(260+ Effect.flatMap(connectInspector(options.metro), (evaluate) =>261+ evaluate("__t3RenderCounterReload()"),262+ ),263+ );
juliusmarminge merged thisea97e8b
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed