diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx
index 16a77b049efa3..7193fcb9b7af8 100644
--- a/apps/mobile/src/App.tsx
+++ b/apps/mobile/src/App.tsx
@@ -109,6 +109,7 @@ import {
import { pruneNewTaskFlowStates } from "./features/threads/new-task-flow-state";
import { pruneNewTaskBranchCheckouts } from "./features/threads/NewTaskDraftRouteScreen";
import { installAppUpdateChecks } from "./features/updates/app-updates";
+import { perfProbe } from "./features/development/perf-probe-hooks";
import "../global.css";
@@ -303,7 +304,12 @@ function AppContent() {
-
+
diff --git a/apps/mobile/src/components/ui/Menu.tsx b/apps/mobile/src/components/ui/Menu.tsx
index 17757fe84b3d6..d82313f2d1948 100644
--- a/apps/mobile/src/components/ui/Menu.tsx
+++ b/apps/mobile/src/components/ui/Menu.tsx
@@ -11,6 +11,7 @@ import type { ColorValue, PressableProps } from "react-native";
import { withUniwind } from "uniwind";
import { useAppearancePreferences } from "../../features/settings/appearance/AppearancePreferencesProvider";
import { withMenuActionIconColors } from "../../lib/menu-action-colors";
+import { perfProbe } from "../../features/development/perf-probe-hooks";
import type { MenuProps } from "./Menu.types";
const ThemedMenuView = withUniwind(
@@ -99,6 +100,13 @@ export function Menu(props: MenuProps) {
}
};
}
+ const { onPressAction } = props;
+ const probe = perfProbe;
+ if (probe && onPressAction)
+ menuProps.onPressAction = (event) => {
+ probe.menuAction();
+ onPressAction(event);
+ };
return (
) {
+ const probe = perfProbe;
return items.map((item) =>
"items" in item ? (
@@ -16,7 +18,14 @@ function renderMenuItems(items: ReadonlyArray) {
disabled={item.disabled}
destructive={item.destructive}
isOn={item.selected}
- onPress={item.onPress}
+ onPress={
+ probe
+ ? () => {
+ probe.menuAction();
+ item.onPress();
+ }
+ : item.onPress
+ }
>
{item.title}
diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx
index b0d78ef3acbce..c5f5b1d64f997 100644
--- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx
+++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx
@@ -85,6 +85,7 @@ vi.mock("./environmentSections", () => ({
vi.mock("./devAutoConnect", () => ({
autoConnectReport: () => ({ connecting: false, error: null }),
devAutoConnectAttemptAtom: {},
+ pairingLinksAllowed: () => __DEV__,
}));
vi.mock("../../state/use-remote-environment-registry", () => ({
setPendingConnectionError: (message: string | null) => {
diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
index 67a2935174fdd..d1dab03ae4da6 100644
--- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
+++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
@@ -29,7 +29,11 @@ import { useRemoteConnections } from "../../state/use-remote-environment-registr
import { SymbolView } from "../../components/ui/AppSymbol";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
import { CloudEnvironmentRows } from "./CloudEnvironmentRows";
-import { autoConnectReport, devAutoConnectAttemptAtom } from "./devAutoConnect";
+import {
+ autoConnectReport,
+ devAutoConnectAttemptAtom,
+ pairingLinksAllowed,
+} from "./devAutoConnect";
import { linkedEnvironmentPrefillAtom } from "./linkedEnvironmentPrefill";
import { splitEnvironmentSections } from "./environmentSections";
import { leaveSettingsPage } from "../settings/settings-navigation";
@@ -49,8 +53,8 @@ export function ConnectionsNewRouteScreen({
route,
}: StaticScreenProps) {
const params = route.params ?? {};
- // Dev-only prefill prevents production links from supplying an attacker-chosen host and token.
- const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : "";
+ // Store builds ignore the prefill so a link can never supply an attacker-chosen host and token.
+ const routePairingUrl = pairingLinksAllowed() ? (params.pairingUrl?.trim() ?? "") : "";
const known = useAtomValue(linkedEnvironmentPrefillAtom);
const linked = known !== null && known.environmentId === params.linked ? known : null;
// A new prefill link replaces whatever the form held.
diff --git a/apps/mobile/src/features/connection/devAutoConnect.test.ts b/apps/mobile/src/features/connection/devAutoConnect.test.ts
index 54886437e3282..418bae7396e10 100644
--- a/apps/mobile/src/features/connection/devAutoConnect.test.ts
+++ b/apps/mobile/src/features/connection/devAutoConnect.test.ts
@@ -124,6 +124,16 @@ it("only prefills without the flag, and ignores the flag in production builds",
expect(harness.pair).not.toHaveBeenCalled();
});
+it("auto-connects in a production bundle only when mobile:metrics built it with the probe", () => {
+ harness.pair.mockClear();
+ harness.pair.mockResolvedValueOnce({ ok: false, error: null });
+ vi.stubGlobal("__DEV__", false);
+ vi.stubEnv("EXPO_PUBLIC_T3_BEHAVIOR_PROBE", "1");
+ startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
+ vi.unstubAllEnvs();
+ expect(harness.pair).toHaveBeenCalledOnce();
+});
+
it("forgets a failed auto-connect once the form is opened again without the flag", async () => {
vi.stubGlobal("__DEV__", true);
const failed = Promise.withResolvers<{ ok: boolean; error: string | null }>();
diff --git a/apps/mobile/src/features/connection/devAutoConnect.ts b/apps/mobile/src/features/connection/devAutoConnect.ts
index 7f2b12a9d371d..bbe101e7a97ec 100644
--- a/apps/mobile/src/features/connection/devAutoConnect.ts
+++ b/apps/mobile/src/features/connection/devAutoConnect.ts
@@ -84,6 +84,13 @@ export function withoutPairingTarget(
});
}
+/**
+ * Pairing links prefill and auto-connect only in development and in mobile:metrics' release
+ * bundles, the one production bundle built with the probe flag; store builds never set it.
+ */
+export const pairingLinksAllowed = () =>
+ __DEV__ || process.env.EXPO_PUBLIC_T3_BEHAVIOR_PROBE === "1";
+
/**
* `connections/new?pairingUrl=…&autoConnect=1` (or `settings/environment-new?…`) pairs from the
* link itself, so a remount of the form never pairs twice. Production builds ignore the flag so
@@ -92,7 +99,7 @@ export function withoutPairingTarget(
export function startDevAutoConnect(
state: PartialState | undefined,
): PartialState | undefined {
- if (!__DEV__) return state;
+ if (!pairingLinksAllowed()) return state;
const route = findLinkedRoute(state, PAIRING_FORM_ROUTES);
if (route === undefined) return state;
const params = (route.params ?? {}) as {
diff --git a/apps/mobile/src/features/development/behavior-probe-entry.ts b/apps/mobile/src/features/development/behavior-probe-entry.ts
index 0771a35dd1c62..6662d18d23288 100644
--- a/apps/mobile/src/features/development/behavior-probe-entry.ts
+++ b/apps/mobile/src/features/development/behavior-probe-entry.ts
@@ -1,4 +1,19 @@
-// Metro folds this condition before collecting dependencies, excluding the probe from release bundles.
-if (__DEV__ && process.env.EXPO_PUBLIC_T3_BEHAVIOR_PROBE === "1") {
+// Production bundles inline the unset flag, so Metro folds this away before collecting dependencies.
+// Only mobile:behavior's and mobile:metrics' Metro sets it, including mobile:metrics' release bundle.
+if (process.env.EXPO_PUBLIC_T3_BEHAVIOR_PROBE === "1") {
+ // A production bundle sets up no DevTools hook; React still reports commits to one it finds.
+ const global = globalThis as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: object };
+ if (!__DEV__)
+ global.__REACT_DEVTOOLS_GLOBAL_HOOK__ ??= {
+ isDisabled: false,
+ supportsFiber: true,
+ renderers: new Map(),
+ inject: () => 1,
+ onScheduleFiberRoot: () => {},
+ onCommitFiberRoot: () => {},
+ onCommitFiberUnmount: () => {},
+ onPostCommitFiberRoot: () => {},
+ checkDCE: () => {},
+ };
require("./behavior-probe");
}
diff --git a/apps/mobile/src/features/development/behavior-probe.ts b/apps/mobile/src/features/development/behavior-probe.ts
index 6da06f4289cbd..4cde4d7f12370 100644
--- a/apps/mobile/src/features/development/behavior-probe.ts
+++ b/apps/mobile/src/features/development/behavior-probe.ts
@@ -8,7 +8,11 @@ interface Fiber {
readonly memoizedProps: Record | null;
}
interface DevToolsHook {
- onCommitFiberRoot?: (id: unknown, root: { current: Fiber }, ...rest: unknown[]) => unknown;
+ onCommitFiberRoot?: (
+ id: unknown,
+ root: { current: Fiber & { readonly actualDuration?: number } },
+ ...rest: unknown[]
+ ) => unknown;
__t3BehaviorProbe?: true;
}
interface ListState {
@@ -46,10 +50,48 @@ function installCommitHook() {
const original = hook.onCommitFiberRoot.bind(hook);
hook.onCommitFiberRoot = (id, next, ...rest) => {
roots.add(next);
+ // Development builds time each commit's render work on the root fiber.
+ if (perf) perf.commits.push({ at: performance.now(), ms: next.current.actualDuration ?? 0 });
return original(id, next, ...rest);
};
}
+/** What one measured interaction did, from `perfStart` to `perfStop`; read by mobile:metrics. */
+interface PerfWindow {
+ readonly startedAt: number;
+ readonly inputs: Array<{ readonly kind: string; readonly at: number }>;
+ readonly commits: Array<{ readonly at: number; readonly ms: number }>;
+ readonly content: Array<{ readonly thread: string; readonly at: number; frameAt: number | null }>;
+ readonly keys: number[];
+}
+let perf: PerfWindow | null = null;
+const perfInput = (kind: string) => perf?.inputs.push({ kind, at: performance.now() });
+
+// The app's input points (see perf-probe-hooks.ts); they record only inside a window.
+Object.assign(globalThis, {
+ __t3PerfProbe: {
+ touchStart: () => perfInput("touch-start"),
+ touchEnd: () => perfInput("touch-end"),
+ menuAction: () => perfInput("menu-action"),
+ key: () => {
+ const window = perf;
+ if (!window) return;
+ const at = performance.now();
+ window.inputs.push({ kind: "key", at });
+ requestAnimationFrame(() => window.keys.push(performance.now() - at));
+ },
+ contentShown: (thread: string) => {
+ const window = perf;
+ if (!window) return;
+ const entry = { thread, at: performance.now(), frameAt: null as number | null };
+ window.content.push(entry);
+ requestAnimationFrame(() => {
+ entry.frameAt = performance.now();
+ });
+ },
+ },
+});
+
/** Visits every mounted fiber; `enter` returns the context passed to the fiber's children. */
function walk(fiber: Fiber | null, context: C, enter: (fiber: Fiber, context: C) => C) {
let node = fiber;
@@ -329,5 +371,88 @@ Object.assign(globalThis, {
sampled = null;
return JSON.stringify({ js: frames.js, ui: runOnUISync(uiFramesStop), feed: samples });
},
+ /** Opens a perf window: inputs, commits, timeline content and frames until `perfStop`. */
+ perfStart() {
+ perf = { startedAt: performance.now(), inputs: [], commits: [], content: [], keys: [] };
+ const counter = globalThis as { __t3RenderCounterStart?: () => boolean };
+ counter.__t3RenderCounterStart?.();
+ return this.recordStart(false);
+ },
+ /** Cheap progress of the open window, so the harness can wait for quiet without a tree walk. */
+ perfPeek() {
+ const window = perf;
+ const last = Math.max(
+ window?.inputs.at(-1)?.at ?? 0,
+ window?.commits.at(-1)?.at ?? 0,
+ window?.content.at(-1)?.frameAt ?? 0,
+ );
+ return JSON.stringify({
+ now: performance.now(),
+ last,
+ inputs: window?.inputs.length ?? 0,
+ content: window?.content.flatMap((entry) => (entry.frameAt === null ? [] : [entry.thread])),
+ });
+ },
+ perfStop() {
+ const window = perf;
+ perf = null;
+ const counter = globalThis as { __t3RenderCounterStop?: () => unknown };
+ const { js, ui } = JSON.parse(this.recordStop()) as { js: number[]; ui: number[] };
+ const hermes = (
+ globalThis as { HermesInternal?: { getInstrumentedStats?: () => Record } }
+ ).HermesInternal?.getInstrumentedStats?.();
+ return JSON.stringify({
+ ...window,
+ js,
+ ui,
+ renders: counter.__t3RenderCounterStop?.() ?? null,
+ heapBytes: hermes?.js_heapSize ?? null,
+ });
+ },
+ /** What the app holds: atom registry nodes by label, and mounted fibers by component. */
+ retention() {
+ const { appAtomRegistry } = require("../../state/atom-registry") as {
+ appAtomRegistry: { getNodes: () => ReadonlyMap };
+ };
+ const atoms = new Map();
+ for (const key of appAtomRegistry.getNodes().keys()) {
+ const label =
+ typeof key === "string"
+ ? `key:${key.split(/[:/]/)[0]}`
+ : ((key as { label?: readonly [string, ...unknown[]] | string }).label ?? "unlabeled");
+ const name = Array.isArray(label) ? String(label[0]) : String(label);
+ atoms.set(name, (atoms.get(name) ?? 0) + 1);
+ }
+ const fibers = new Map();
+ let fiberCount = 0;
+ for (const root of roots)
+ walk(root.current, null, (fiber) => {
+ fiberCount += 1;
+ const type = fiber.type as { displayName?: string; name?: string } | string | null;
+ const name = typeof type === "string" ? type : (type?.displayName ?? type?.name ?? "");
+ if (name) fibers.set(name, (fibers.get(name) ?? 0) + 1);
+ return null;
+ });
+ const top = (map: Map) =>
+ Object.fromEntries([...map].sort((a, b) => b[1] - a[1]).slice(0, 25));
+ return JSON.stringify({
+ atomCount: appAtomRegistry.getNodes().size,
+ fiberCount,
+ atoms: top(atoms),
+ fibers: top(fibers),
+ });
+ },
+ /** The Hermes heap, after a full collection when this runtime exposes `gc`. */
+ heap() {
+ const internal = globalThis as {
+ gc?: () => void;
+ HermesInternal?: { getInstrumentedStats?: () => Record };
+ };
+ internal.gc?.();
+ return JSON.stringify({
+ bytes: internal.HermesInternal?.getInstrumentedStats?.().js_heapSize ?? null,
+ collected: typeof internal.gc === "function",
+ });
+ },
},
});
diff --git a/apps/mobile/src/features/development/perf-probe-hooks.ts b/apps/mobile/src/features/development/perf-probe-hooks.ts
new file mode 100644
index 0000000000000..038b49b2fe3e4
--- /dev/null
+++ b/apps/mobile/src/features/development/perf-probe-hooks.ts
@@ -0,0 +1,15 @@
+/** Input points for mobile:metrics' perf windows; null unless the env-gated behavior probe loaded. */
+export interface PerfProbe {
+ readonly touchStart: () => void;
+ readonly touchEnd: () => void;
+ /** A native menu item's JS handler ran: the first point JS sees of a tap inside a native menu. */
+ readonly menuAction: () => void;
+ /** The composer's text changed: one key. */
+ readonly key: () => void;
+ /** A thread's timeline rows became visible. */
+ readonly contentShown: (thread: string) => void;
+}
+
+// behavior-probe-entry runs before the app's modules in index.ts, so this is read after it installs.
+export const perfProbe: PerfProbe | null =
+ (globalThis as { __t3PerfProbe?: PerfProbe }).__t3PerfProbe ?? null;
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index d21ae90a0392c..2d108bde5192b 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -123,6 +123,7 @@ import {
import { useVoiceInputController } from "../voice-input/useVoiceInputController";
import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
import type { ExistingThreadSettingsRouteParams } from "./ThreadSettingsSheet";
+import { perfProbe } from "../development/perf-probe-hooks";
import {
useThreadSettingsSheetPresentation,
type NavigationWithFinishTransitioning,
@@ -901,6 +902,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
skills={composerMenu.skills}
selection={composerMenu.selection}
onChangeText={(text) => {
+ perfProbe?.key();
if (!isSubmissionLocked) props.onChangeDraftMessage(text);
}}
onSelectionChange={composerMenu.onSelectionChange}
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index c1522eab19131..992ba4779f34d 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -344,6 +344,7 @@ import {
THREAD_FEED_MAINTAIN_SCROLL_AT_END_THRESHOLD,
} from "./threadFeedEndFollow";
import { useMessageTimeFormatter } from "./useMessageTimeFormatter";
+import { perfProbe, type PerfProbe } from "../development/perf-probe-hooks";
const linkedThreadEnvironmentIds = (markdown: string, environmentId: EnvironmentId) =>
hasThreadLinks(markdown)
@@ -3096,6 +3097,14 @@ function DisclosureRow(props: {
// instead of at width 0 and again when the new feed's own layout reports the same width.
let lastSplitViewport: { windowWidth: number; width: number; height: number } | null = null;
+/** Tells mobile:metrics' probe the commit that first showed this thread's rows. */
+function PerfContentMark(props: { readonly probe: PerfProbe; readonly thread: string }) {
+ const { probe, thread } = props;
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports the visible commit to the dev-only perf probe
+ useLayoutEffect(() => probe.contentShown(thread), [probe, thread]);
+ return null;
+}
+
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const gt = useGT();
const m = useMessages();
@@ -4306,6 +4315,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
className="flex-1"
style={splitLayout && viewportWidth > 0 ? { width: viewportWidth } : undefined}
>
+ {perfProbe && !settling && props.feed.length > 0 ? (
+
+ ) : null}
{/* oxlint-disable-next-line t3code/require-registered-list-scroll -- ThreadFeedScrollView is passed through the iOS-only spread below; the prop rejects undefined. */}
` and `compare` work like client-metrics' and share its gate:
+ each app launch's median is one sample, so gate only with `--ab-rounds 2` or more, on one
+ simulator model. `noise` calibrates floors from A/A runs.
+- Latency counts from the touch's end as JS sees it, so a JS thread too busy to take the touch
+ hides part of the delay. A tap on a native menu item (the Git controls' Review changes, the
+ list switcher's Issues) never reaches JS as a touch, so it counts from the item's JS handler,
+ which the shared `Menu` and native header menu report to the probe: later than the finger.
+- A side chat is seeded with one exchange, since an empty one shows a placeholder rather than a
+ timeline and would never count as content.
+- `--soak ` repeats the switch cases and samples the Hermes heap after each one, with growth
+ per iteration after warm-up and per case. Each sample follows a full Hermes `gc()`. Soak with
+ `--build release`: the dev build grows about 5 MB an iteration with no leak, all of it the
+ DevTools backend, the debugger-enabled Hermes keeping closure locals alive, react-refresh, and
+ React's dev debug stacks.
+- `settled` is the last commit before a second of quiet. Any streaming thread keeps Home
+ committing, so only `switch-working` streams, and it stops its thread when done.
+
## Persistence and background work invariants
- Event-store sequence cursors and startup recovery candidate selection must seek indexes rather
diff --git a/package.json b/package.json
index 22407fdf41bd5..2e04dfa060b9b 100644
--- a/package.json
+++ b/package.json
@@ -44,6 +44,7 @@
"mobile:install": "node scripts/mobile-native-client.ts ensure",
"mobile:audit": "node scripts/mobile-audit.ts",
"mobile:behavior": "node scripts/mobile-behavior.ts",
+ "mobile:metrics": "node scripts/mobile-metrics.ts",
"mobile:e2e": "node scripts/mobile-e2e.ts",
"scenarios": "vp run --filter @t3tools/scripts scenarios",
"scenarios:prove": "node scripts/prove-scenario.ts",
diff --git a/scripts/client-metrics-fixture.ts b/scripts/client-metrics-fixture.ts
new file mode 100644
index 0000000000000..068ccf0521295
--- /dev/null
+++ b/scripts/client-metrics-fixture.ts
@@ -0,0 +1,58 @@
+// The weight client-metrics and mobile-metrics seed: a branch changing many files, and its pull
+// request on the fake GitHub with a long body, files, commits and comments.
+import type { FakePullRequestDetail } from "./server-metrics-forge.ts";
+
+/** Many files with many lines, so the Diff panel and the PR's files have real weight. */
+export const DIFF_FILES = 40;
+const DIFF_LINES = 60;
+export const sourceFile = (index: number, variant: "before" | "after") =>
+ Array.from({ length: DIFF_LINES }, (_, line) =>
+ line % 10 === 0
+ ? `export function helper${index}_${line}(input: ReadonlyArray) {`
+ : line % 10 === 9
+ ? "}"
+ : variant === "after" && line % 3 === 0
+ ? ` const value${line} = input.map((entry) => entry ** ${line}).filter(Boolean); // changed`
+ : ` const value${line} = input.map((entry) => entry * ${line}).filter(Boolean);`,
+ ).join("\n") + "\n";
+
+export const pullRequestDetail = (): FakePullRequestDetail => {
+ const files = Array.from({ length: DIFF_FILES }, (_, index) => {
+ const changed = Array.from({ length: DIFF_LINES }, (_, line) => line).filter(
+ (line) => line % 10 !== 0 && line % 10 !== 9 && line % 3 === 0,
+ );
+ const patch = [
+ `@@ -1,${DIFF_LINES} +1,${DIFF_LINES} @@`,
+ ...changed.flatMap((line) => [
+ `- const value${line} = input.map((entry) => entry * ${line}).filter(Boolean);`,
+ `+ const value${line} = input.map((entry) => entry ** ${line}).filter(Boolean); // changed`,
+ ]),
+ ].join("\n");
+ return {
+ path: `src/module${index}.ts`,
+ additions: changed.length,
+ deletions: changed.length,
+ patch,
+ };
+ });
+ const section = (title: string) =>
+ `## ${title}\n\nThis part of the change moves the helpers behind one entry point. Callers keep their signatures; each module now **squares** its inputs before filtering, and the filters skip falsy values.\n\n- \`src/module0.ts\` through \`src/module9.ts\` read the new helpers\n- the tests cover the empty input and the largest one\n- nothing outside \`src/\` moves\n\n\`\`\`ts\nexport function helper0_0(input: ReadonlyArray) {\n return input.map((entry) => entry ** 2).filter(Boolean);\n}\n\`\`\`\n`;
+ return {
+ body: [
+ "Squares every helper's input and moves them behind one entry point.",
+ ...["Why", "What changed", "How it was tested", "Follow-ups", "Risks"].map(section),
+ "| module | before | after |\n| :-- | --: | --: |\n" +
+ Array.from(
+ { length: 12 },
+ (_, index) => `| module${index} | ${index * 3} ms | ${index * 2} ms |`,
+ ).join("\n"),
+ ].join("\n\n"),
+ files,
+ comments: Array.from(
+ { length: 12 },
+ (_, index) =>
+ `Comment ${index + 1}: the helper in \`src/module${index}.ts\` reads better now. Could the filter keep zero?\n\n> ${"Quoted context from the review. ".repeat(3)}`,
+ ),
+ commits: 8,
+ };
+};
diff --git a/scripts/client-metrics-report.ts b/scripts/client-metrics-report.ts
index 208f97fa95486..7fa6c02ec0f6e 100644
--- a/scripts/client-metrics-report.ts
+++ b/scripts/client-metrics-report.ts
@@ -547,12 +547,29 @@ export function compareClientMetrics(
threshold = 10,
floors?: Floors,
) {
- const a = flatten(before);
- const b = flatten(after);
+ return compareSeries(
+ flatten(before),
+ flatten(after),
+ [
+ "### Client metrics (lower is better)",
+ "",
+ `before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs)${floors ? `, floors calibrated on ${floors.platform}` : ""}`,
+ ],
+ threshold,
+ floors,
+ );
+}
+
+/** `compareClientMetrics` over any two files' per-run metric values, under `header`. */
+export function compareSeries(
+ a: ReadonlyMap>,
+ b: ReadonlyMap>,
+ header: ReadonlyArray,
+ threshold = 10,
+ floors?: Floors,
+) {
const lines = [
- "### Client metrics (lower is better)",
- "",
- `before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs)${floors ? `, floors calibrated on ${floors.platform}` : ""}`,
+ ...header,
"",
"| metric | before | after | change | 95% interval | |",
"| :-- | --: | --: | --: | --: | :-- |",
@@ -617,11 +634,25 @@ export const NOISY_SHARE = 0.5;
export function noiseReport(
pairs: ReadonlyArray,
platform: string,
+) {
+ return noiseOfSeries(
+ pairs.map(([before, after]) => [flatten(before), flatten(after)] as const),
+ platform,
+ );
+}
+
+/** `noiseReport` over any A/A pairs' per-run metric values. */
+export function noiseOfSeries(
+ pairs: ReadonlyArray<
+ readonly [
+ ReadonlyMap>,
+ ReadonlyMap>,
+ ]
+ >,
+ platform: string,
) {
const found = new Map();
- for (const [before, after] of pairs) {
- const a = flatten(before);
- const b = flatten(after);
+ for (const [a, b] of pairs) {
for (const [metric, x] of a) {
const y = b.get(metric);
if (!y) continue;
diff --git a/scripts/client-metrics.ts b/scripts/client-metrics.ts
index f87d7266d18ff..e2888e3776dc3 100644
--- a/scripts/client-metrics.ts
+++ b/scripts/client-metrics.ts
@@ -68,7 +68,8 @@ import {
} from "./client-metrics-trace.ts";
import { prepareHome, SCENARIO_MACHINE_ENV } from "./scenarios/start-app.ts";
import { run } from "./scenarios/shell.ts";
-import { serveFakeGitHub, type FakePullRequestDetail } from "./server-metrics-forge.ts";
+import { DIFF_FILES, pullRequestDetail, sourceFile } from "./client-metrics-fixture.ts";
+import { serveFakeGitHub } from "./server-metrics-forge.ts";
import { describeFailure, loadWarnings } from "./server-metrics-report.ts";
import {
descendantsOf,
@@ -111,61 +112,6 @@ const browserPromise = (what: string, evaluate: () => Promise) =>
catch: (cause) => new MetricsError({ message: `${what}: ${describeFailure(cause)}` }),
});
-/** Many files with many lines, so the Diff panel and the PR's files have real weight. */
-const DIFF_FILES = 40;
-const DIFF_LINES = 60;
-const sourceFile = (index: number, variant: "before" | "after") =>
- Array.from({ length: DIFF_LINES }, (_, line) =>
- line % 10 === 0
- ? `export function helper${index}_${line}(input: ReadonlyArray) {`
- : line % 10 === 9
- ? "}"
- : variant === "after" && line % 3 === 0
- ? ` const value${line} = input.map((entry) => entry ** ${line}).filter(Boolean); // changed`
- : ` const value${line} = input.map((entry) => entry * ${line}).filter(Boolean);`,
- ).join("\n") + "\n";
-
-const pullRequestDetail = (): FakePullRequestDetail => {
- const files = Array.from({ length: DIFF_FILES }, (_, index) => {
- const changed = Array.from({ length: DIFF_LINES }, (_, line) => line).filter(
- (line) => line % 10 !== 0 && line % 10 !== 9 && line % 3 === 0,
- );
- const patch = [
- `@@ -1,${DIFF_LINES} +1,${DIFF_LINES} @@`,
- ...changed.flatMap((line) => [
- `- const value${line} = input.map((entry) => entry * ${line}).filter(Boolean);`,
- `+ const value${line} = input.map((entry) => entry ** ${line}).filter(Boolean); // changed`,
- ]),
- ].join("\n");
- return {
- path: `src/module${index}.ts`,
- additions: changed.length,
- deletions: changed.length,
- patch,
- };
- });
- const section = (title: string) =>
- `## ${title}\n\nThis part of the change moves the helpers behind one entry point. Callers keep their signatures; each module now **squares** its inputs before filtering, and the filters skip falsy values.\n\n- \`src/module0.ts\` through \`src/module9.ts\` read the new helpers\n- the tests cover the empty input and the largest one\n- nothing outside \`src/\` moves\n\n\`\`\`ts\nexport function helper0_0(input: ReadonlyArray) {\n return input.map((entry) => entry ** 2).filter(Boolean);\n}\n\`\`\`\n`;
- return {
- body: [
- "Squares every helper's input and moves them behind one entry point.",
- ...["Why", "What changed", "How it was tested", "Follow-ups", "Risks"].map(section),
- "| module | before | after |\n| :-- | --: | --: |\n" +
- Array.from(
- { length: 12 },
- (_, index) => `| module${index} | ${index * 3} ms | ${index * 2} ms |`,
- ).join("\n"),
- ].join("\n\n"),
- files,
- comments: Array.from(
- { length: 12 },
- (_, index) =>
- `Comment ${index + 1}: the helper in \`src/module${index}.ts\` reads better now. Could the filter keep zero?\n\n> ${"Quoted context from the review. ".repeat(3)}`,
- ),
- commits: 8,
- };
-};
-
const FIXTURE_PAGE = `
Bench fixture
diff --git a/scripts/mobile-behavior.ts b/scripts/mobile-behavior.ts
index aa5f28f7483f3..4444f7ff2e8fd 100644
--- a/scripts/mobile-behavior.ts
+++ b/scripts/mobile-behavior.ts
@@ -1,10 +1,9 @@
#!/usr/bin/env node
-// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalTimers:off globalFetch:off - Host-side device automation uses Node subprocess and filesystem APIs directly.
+// @effect-diagnostics nodeBuiltinImport:off globalDate:off - Host-side device automation uses Node subprocess and filesystem APIs directly.
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeFSP from "node:fs/promises";
-import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeProcess from "node:process";
import * as NodeReadline from "node:readline";
@@ -12,7 +11,14 @@ import * as NodeURL from "node:url";
import { CASES } from "./mobile-behavior/cases.ts";
import { blockingResults, resultsFor, summarize, type SampleRow } from "./mobile-behavior/grade.ts";
-import { Device, type Pool, poolError, run } from "./mobile-e2e/device.ts";
+import { type Device, run } from "./mobile-e2e/device.ts";
+import {
+ leaseAndInstall,
+ openPool,
+ releaseOnCrash,
+ renewWhileRunning,
+ type PoolAccess,
+} from "./mobile-behavior/pool.ts";
import type { Pose } from "./mobile-e2e/poses.ts";
const REPO_ROOT = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
@@ -32,34 +38,14 @@ interface TargetRun {
readonly error?: string;
}
-/** Keeps a lease alive while the cases run: they go minutes without an agent-device call. */
-function renewWhileRunning(pool: Pool, stateDir: string, session: string, token: string) {
- const gateway = pool.agentDeviceUrl.replace(/\/v1\/agent-device\/?$/, "");
- const timer = setInterval(() => {
- const record = NodePath.join(stateDir, "remote-connections", `${session}.json`);
- void NodeFSP.readFile(record, "utf8")
- .then((text) => (JSON.parse(text) as { leaseId: string }).leaseId)
- .then((leaseId) =>
- fetch(`${gateway}/v1/leases/${encodeURIComponent(leaseId)}/renew`, {
- method: "POST",
- headers: { authorization: `Bearer ${token}` },
- }),
- )
- .catch(() => undefined);
- }, 90_000);
- return () => clearInterval(timer);
-}
-
async function runTarget(
target: Target,
- pool: Pool,
+ access: PoolAccess,
runId: string,
outputDirectory: string,
- config: string,
- stateDir: string,
- token: string,
passThrough: ReadonlyArray,
): Promise {
+ const { pool, config } = access;
const directory = NodePath.join(outputDirectory, target.id);
await NodeFSP.mkdir(directory, { recursive: true });
const pose: Pose = {
@@ -69,22 +55,14 @@ async function runTarget(
form: target.form,
appearance: "light",
};
- let device: Device | null = null;
- for (let attempt = 1; !device; attempt++) {
- try {
- log(target.id, `leasing ${target.device}`);
- device = await Device.lease(pose, pool, attempt === 1 ? runId : `${runId}-retry`);
- log(target.id, "installing the dev client");
- await device.install();
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- await device?.release();
- device = null;
- if (attempt >= 2 || !poolError(message)) return { target, directory, error: message };
- log(target.id, `retrying after: ${message.split("\n")[0]}`);
- }
+ let device: Device;
+ try {
+ device = await leaseAndInstall(pose, pool, runId, (message) => log(target.id, message));
+ } catch (error) {
+ return { target, directory, error: error instanceof Error ? error.message : String(error) };
}
- const stopRenewing = renewWhileRunning(pool, stateDir, device.session, token);
+ const stopRenewing = renewWhileRunning(access, device.session);
+ const stopCrashGuard = releaseOnCrash(device, access);
try {
log(target.id, "running the behavior cases");
const child = NodeChildProcess.spawn(
@@ -126,6 +104,7 @@ async function runTarget(
: { target, directory, error: `the cases stopped (exit ${code}); see ${directory}/run.log` };
} finally {
stopRenewing();
+ stopCrashGuard();
await device.release();
}
}
@@ -149,32 +128,10 @@ async function main() {
...values("--case").flatMap((value) => ["--case", value]),
];
- const agentDeviceUrl = NodeProcess.env.SIMLOCK_AGENT_DEVICE_URL;
- const token = NodeProcess.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
- if (!agentDeviceUrl || !token)
- throw new Error(
- "Set SIMLOCK_AGENT_DEVICE_URL (/v1/agent-device) and AGENT_DEVICE_DAEMON_AUTH_TOKEN (a Simlock agent token) to run on the device pool.",
- );
-
const runId = new Date().toISOString().replaceAll(/[:.]/g, "-");
const outputDirectory = NodePath.join(REPO_ROOT, "artifacts/mobile-behavior", runId);
await NodeFSP.mkdir(outputDirectory, { recursive: true });
- const rootDir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-mobile-behavior-"));
- const workspace = await NodeFSP.realpath(outputDirectory);
- const config = NodePath.join(rootDir, "agent-device.json");
- const stateDir = NodePath.join(rootDir, "agent-device");
- await NodeFSP.writeFile(
- config,
- JSON.stringify({ daemonBaseUrl: agentDeviceUrl, daemonAuthToken: token, stateDir }),
- { mode: 0o600 },
- );
- const pool: Pool = {
- repoRoot: REPO_ROOT,
- agentDevice: NodePath.join(REPO_ROOT, "scripts/node_modules/agent-device/bin/agent-device.mjs"),
- agentDeviceUrl,
- workspace,
- env: { ...NodeProcess.env, AGENT_DEVICE_CONFIG: config, PWD: workspace },
- };
+ const access = await openPool(REPO_ROOT, outputDirectory);
try {
// A cache miss builds the dev client, which can outlast a lease, so it is ready first.
log("behavior", "preparing the ios dev client");
@@ -184,9 +141,7 @@ async function main() {
{ cwd: REPO_ROOT, timeoutMs: 1_800_000 },
);
const runs = await Promise.all(
- targets.map((target) =>
- runTarget(target, pool, runId, outputDirectory, config, stateDir, token, passThrough),
- ),
+ targets.map((target) => runTarget(target, access, runId, outputDirectory, passThrough)),
);
const rows = runs.flatMap((entry) => {
@@ -220,7 +175,7 @@ async function main() {
);
process.exitCode = blocking.length || stopped.length ? 1 : 0;
} finally {
- await NodeFSP.rm(rootDir, { recursive: true, force: true });
+ await access.close();
}
}
diff --git a/scripts/mobile-behavior/README.md b/scripts/mobile-behavior/README.md
index d2a5e0b7407a6..3cdc3d9b64b01 100644
--- a/scripts/mobile-behavior/README.md
+++ b/scripts/mobile-behavior/README.md
@@ -1,8 +1,8 @@
# Mobile behavior
-`vp run mobile:behavior` checks what the iOS app does, from its own state rather than pixels: scroll position, dropped frames, composer drafts and focus, status labels, and which thread opens. It leases an iPhone 18 Pro and an iPad Pro 13 from the Simlock pool and runs the cases on both in parallel. It is the companion to `vp run mobile:e2e`, which checks layout.
+`vp run mobile:behavior` checks what the iOS app does, from its own state rather than pixels: scroll position, dropped frames, composer drafts and focus, status labels, and which thread opens. It leases an iPhone 18 Pro and an iPad Pro 13 from the Simlock pool and runs the cases on both in parallel. It is the companion to `vp run mobile:e2e`, which checks layout. `vp run mobile:metrics` reuses its server, Metro, probe and leases ([`session.ts`](session.ts), [`pool.ts`](pool.ts)) to benchmark interactions.
-No model runs. Each device gets its own server whose only provider, `evalbot`, is an Fx instance backed by [`fake-fx.ts`](fake-fx.ts). A `[[eval:…]]` marker in a message picks its scripted reply: a paced stream, a held turn, a question, two subagents, or a failure. Each device also gets its own Metro with the dev-only probe ([`behavior-probe.ts`](../../apps/mobile/src/features/development/behavior-probe.ts)) compiled in. The probe reads app state through Metro's Hermes inspector, and agent-device drives the touches.
+No model runs. Each device gets its own server whose only provider, `evalbot`, is an Fx instance backed by [`fake-fx.ts`](fake-fx.ts). A `[[eval:…]]` marker in a message picks its scripted reply: a paced stream, a held turn, a question, two subagents, or a failure. Each device also gets its own Metro with the env-gated probe ([`behavior-probe.ts`](../../apps/mobile/src/features/development/behavior-probe.ts)) compiled in. The probe reads app state through Metro's Hermes inspector, and agent-device drives the touches.
## Run
diff --git a/scripts/mobile-behavior/environment.ts b/scripts/mobile-behavior/environment.ts
index 000e8d2f030bb..885f26a5d64e7 100644
--- a/scripts/mobile-behavior/environment.ts
+++ b/scripts/mobile-behavior/environment.ts
@@ -120,14 +120,34 @@ function writeScratch(baseDir: string) {
return { workspace, control };
}
+/** Extras a caller layers on the scratch workspace, such as mobile:metrics' fake GitHub. */
+export interface EnvironmentOptions {
+ /** Runs on the committed scratch repository before the server starts. */
+ readonly prepareWorkspace?: (
+ workspace: string,
+ ) => Effect.Effect;
+ readonly serverEnv?: Readonly>;
+}
+
/** Starts the server in the caller's scope; the scope's end stops it. */
-export const startEnvironment = Effect.fn("environment.start")(function* (input: {
- readonly baseDir: string;
- /** Origin the device uses to reach this machine, without a port. */
- readonly deviceHost: string;
-}) {
+export const startEnvironment = Effect.fn("environment.start")(function* (
+ input: {
+ readonly baseDir: string;
+ /** Origin the device uses to reach this machine, without a port. */
+ readonly deviceHost: string;
+ } & EnvironmentOptions,
+) {
NodeFS.rmSync(input.baseDir, { recursive: true, force: true });
const { workspace, control } = writeScratch(input.baseDir);
+ if (input.prepareWorkspace)
+ yield* input
+ .prepareWorkspace(workspace)
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new EnvironmentError({ message: `Preparing the workspace failed: ${cause.message}` }),
+ ),
+ );
const home = NodePath.join(input.baseDir, "home");
NodeFS.mkdirSync(home, { recursive: true });
const port = yield* freePort();
@@ -151,7 +171,11 @@ export const startEnvironment = Effect.fn("environment.start")(function* (input:
workspace,
],
// A scratch HOME keeps the user's own skills and config out of the app under test.
- { cwd: REPO_ROOT, stdio: ["ignore", log, log], env: { ...process.env, HOME: home } },
+ {
+ cwd: REPO_ROOT,
+ stdio: ["ignore", log, log],
+ env: { ...process.env, ...input.serverEnv, HOME: home },
+ },
),
),
(child) => Effect.sync(() => child.kill("SIGTERM")),
@@ -385,6 +409,25 @@ export const startEnvironment = Effect.fn("environment.start")(function* (input:
),
Effect.asVoid,
),
+ /** A side chat forked from `source`'s latest settled point, as the app's own command does. */
+ forkSideChat: Effect.fn("environment.forkSideChat")(function* (
+ source: ThreadId,
+ title: string,
+ ) {
+ const targetThreadId = ThreadId.make(yield* uuid);
+ yield* client["orchestration.dispatchCommand"]({
+ type: "thread.fork",
+ commandId: yield* command,
+ createdBy: "user",
+ creationSource: "server",
+ sourceThreadId: source,
+ targetThreadId,
+ sourcePoint: { type: "latest_stable" },
+ sideChat: true,
+ title,
+ });
+ return targetThreadId;
+ }),
projection,
launch,
send,
diff --git a/scripts/mobile-behavior/pool.ts b/scripts/mobile-behavior/pool.ts
new file mode 100644
index 0000000000000..cd7d053668b19
--- /dev/null
+++ b/scripts/mobile-behavior/pool.ts
@@ -0,0 +1,116 @@
+// @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalFetch:off - host-side lease bookkeeping.
+/** Simlock leases for mobile:behavior and mobile:metrics: one agent-device config, leases kept alive. */
+import * as NodeFSP from "node:fs/promises";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+import * as NodeProcess from "node:process";
+
+import { Device, type Pool, poolError } from "../mobile-e2e/device.ts";
+import type { Pose } from "../mobile-e2e/poses.ts";
+
+export interface PoolAccess {
+ readonly pool: Pool;
+ /** The agent-device config file a run's `--device-config` names. */
+ readonly config: string;
+ readonly stateDir: string;
+ readonly token: string;
+ readonly close: () => Promise;
+}
+
+/** Writes the pool's agent-device config; `close` removes it. `workspace` must already exist. */
+export async function openPool(repoRoot: string, workspace: string): Promise {
+ const agentDeviceUrl = NodeProcess.env.SIMLOCK_AGENT_DEVICE_URL;
+ const token = NodeProcess.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
+ if (!agentDeviceUrl || !token)
+ throw new Error(
+ "Set SIMLOCK_AGENT_DEVICE_URL (/v1/agent-device) and AGENT_DEVICE_DAEMON_AUTH_TOKEN (a Simlock agent token) to run on the device pool.",
+ );
+ const rootDir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-mobile-pool-"));
+ const config = NodePath.join(rootDir, "agent-device.json");
+ const stateDir = NodePath.join(rootDir, "agent-device");
+ await NodeFSP.writeFile(
+ config,
+ JSON.stringify({ daemonBaseUrl: agentDeviceUrl, daemonAuthToken: token, stateDir }),
+ { mode: 0o600 },
+ );
+ const real = await NodeFSP.realpath(workspace);
+ return {
+ pool: {
+ repoRoot,
+ agentDevice: NodePath.join(
+ repoRoot,
+ "scripts/node_modules/agent-device/bin/agent-device.mjs",
+ ),
+ agentDeviceUrl,
+ workspace: real,
+ env: { ...NodeProcess.env, AGENT_DEVICE_CONFIG: config, PWD: real },
+ },
+ config,
+ stateDir,
+ token,
+ close: () => NodeFSP.rm(rootDir, { recursive: true, force: true }),
+ };
+}
+
+/** Leases a device for `pose` and installs the dev client, retrying once on a pool hiccup. */
+export async function leaseAndInstall(
+ pose: Pose,
+ pool: Pool,
+ runId: string,
+ log: (message: string) => void,
+): Promise {
+ for (let attempt = 1; ; attempt++) {
+ let device: Device | null = null;
+ try {
+ log(`leasing ${pose.device}`);
+ device = await Device.lease(pose, pool, attempt === 1 ? runId : `${runId}-retry`);
+ log("installing the dev client");
+ await device.install();
+ return device;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ await device?.release();
+ if (attempt >= 2 || !poolError(message)) throw error;
+ log(`retrying after: ${message.split("\n")[0]}`);
+ }
+ }
+}
+
+/** Keeps a lease alive while cases run: they go minutes without an agent-device call. */
+export function renewWhileRunning(access: PoolAccess, session: string) {
+ const gateway = access.pool.agentDeviceUrl.replace(/\/v1\/agent-device\/?$/, "");
+ const timer = setInterval(() => {
+ const record = NodePath.join(access.stateDir, "remote-connections", `${session}.json`);
+ void NodeFSP.readFile(record, "utf8")
+ .then((text) => (JSON.parse(text) as { leaseId: string }).leaseId)
+ .then((leaseId) =>
+ fetch(`${gateway}/v1/leases/${encodeURIComponent(leaseId)}/renew`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${access.token}` },
+ }),
+ )
+ .catch(() => undefined);
+ }, 90_000);
+ return () => clearInterval(timer);
+}
+
+/**
+ * Releases the lease if the process dies on an uncaught error, which skips every finalizer; a
+ * leaked lease holds the device until the pool's TTL. Returns the function that unregisters it.
+ */
+export function releaseOnCrash(device: Device, access: PoolAccess) {
+ const crash = (error: unknown) => {
+ NodeProcess.stderr.write(`Crashed (${String(error)}); releasing ${device.session}.\n`);
+ void device
+ .release()
+ .catch(() => undefined)
+ .then(() => access.close())
+ .finally(() => NodeProcess.exit(1));
+ };
+ process.on("uncaughtException", crash);
+ process.on("unhandledRejection", crash);
+ return () => {
+ process.off("uncaughtException", crash);
+ process.off("unhandledRejection", crash);
+ };
+}
diff --git a/scripts/mobile-behavior/release-bytecode.ts b/scripts/mobile-behavior/release-bytecode.ts
new file mode 100644
index 0000000000000..f166d5d5115e7
--- /dev/null
+++ b/scripts/mobile-behavior/release-bytecode.ts
@@ -0,0 +1,160 @@
+// @effect-diagnostics nodeBuiltinImport:off - proxies Metro's HTTP and inspector sockets.
+/**
+ * mobile:metrics' `--build release`: the dev client runs Metro's production bundle as `hermesc -O`
+ * bytecode, like a store build, so timings and heap growth leave out React's and Hermes's dev
+ * machinery. A proxy on the port the app opens answers bundle requests with that bytecode and passes
+ * everything else, inspector websockets included, through to Metro.
+ */
+import * as NodeHttp from "node:http";
+import * as NodeModule from "node:module";
+import * as NodeNet from "node:net";
+import * as NodePath from "node:path";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+
+import { run } from "../scenarios/shell.ts";
+import { DeviceError } from "./device.ts";
+
+const BUNDLE_PATH =
+ "/apps/mobile/index.ts.bundle?platform=ios&dev=false&hot=false&minify=true&transform.engine=hermes&transform.bytecode=1&transform.routerRoot=app&transform.reactCompiler=true&unstable_transformProfile=hermes-stable";
+
+/** The checkout's own hermesc, so the bytecode matches the Hermes in its dev client. */
+function hermesc(checkout: string, host: string) {
+ const fromApp = NodeModule.createRequire(NodePath.join(checkout, "apps/mobile/package.json"));
+ const fromReactNative = NodeModule.createRequire(fromApp.resolve("react-native/package.json"));
+ const platform = host === "darwin" ? "osx-bin" : "linux64-bin";
+ return NodePath.join(
+ NodePath.dirname(fromReactNative.resolve("hermes-compiler/package.json")),
+ "hermesc",
+ platform,
+ "hermesc",
+ );
+}
+
+// node:http, not fetch: Metro answers only once the bundle is built, past undici's header timeout.
+const metroGet = (port: number, path: string) =>
+ Effect.callback((resume) => {
+ const request = NodeHttp.get({ host: "127.0.0.1", port, path }, (response) => {
+ const chunks: Buffer[] = [];
+ response.on("data", (chunk: Buffer) => chunks.push(chunk));
+ response.on("end", () => {
+ const body = Buffer.concat(chunks);
+ resume(
+ response.statusCode === 200
+ ? Effect.succeed(body)
+ : Effect.fail(
+ new DeviceError({
+ message: `Metro's production bundle failed (${response.statusCode}): ${body.toString().slice(0, 500)}`,
+ }),
+ ),
+ );
+ });
+ });
+ request.on("error", (error) =>
+ resume(Effect.fail(new DeviceError({ message: `Metro did not answer: ${error.message}` }))),
+ );
+ return Effect.sync(() => request.destroy());
+ });
+
+/** Metro's production bundle compiled to Hermes bytecode. */
+const compile = Effect.fn("releaseBytecode.compile")(function* (input: {
+ readonly metroPort: number;
+ readonly checkout: string;
+ readonly out: string;
+}) {
+ const fs = yield* FileSystem.FileSystem;
+ const js = NodePath.join(input.out, "release.bundle.js");
+ yield* fs.writeFile(js, yield* metroGet(input.metroPort, BUNDLE_PATH));
+ yield* run(hermesc(input.checkout, yield* HostProcess.Platform), [
+ "-O",
+ "-emit-binary",
+ "-w",
+ "-out",
+ `${js}.hbc`,
+ js,
+ ]);
+ return yield* fs.readFile(`${js}.hbc`);
+});
+
+/** Metro's text answers name its own port, which the app must not bypass the proxy for. */
+function forward(metroPort: number, port: number) {
+ return (request: NodeHttp.IncomingMessage, response: NodeHttp.ServerResponse) => {
+ const headers = { ...request.headers };
+ delete headers["accept-encoding"];
+ const upstream = NodeHttp.request(
+ { host: "127.0.0.1", port: metroPort, method: request.method, path: request.url, headers },
+ (answer) => {
+ const chunks: Buffer[] = [];
+ answer.on("data", (chunk: Buffer) => chunks.push(chunk));
+ answer.on("end", () => {
+ let body = Buffer.concat(chunks);
+ if (/json|text|multipart/.test(String(answer.headers["content-type"] ?? "")))
+ body = Buffer.from(body.toString("utf8").replaceAll(`:${metroPort}`, `:${port}`));
+ const out = { ...answer.headers, "content-length": String(body.length) };
+ delete out["transfer-encoding"];
+ response.writeHead(answer.statusCode ?? 502, out);
+ response.end(body);
+ });
+ },
+ );
+ upstream.on("error", (error) => {
+ response.writeHead(502);
+ response.end(String(error));
+ });
+ request.pipe(upstream);
+ };
+}
+
+/** Metro's inspector accepts DevTools origins on its own port only. */
+function forwardUpgrade(metroPort: number, port: number) {
+ return (request: NodeHttp.IncomingMessage, socket: NodeNet.Socket, head: Buffer) => {
+ const upstream = NodeNet.connect(metroPort, "127.0.0.1", () => {
+ const lines = [`${request.method} ${request.url} HTTP/${request.httpVersion}`];
+ for (let index = 0; index < request.rawHeaders.length; index += 2)
+ lines.push(
+ `${request.rawHeaders[index]}: ${request.rawHeaders[index + 1]?.replaceAll(`:${port}`, `:${metroPort}`)}`,
+ );
+ upstream.write(`${lines.join("\r\n")}\r\n\r\n`);
+ if (head.length > 0) upstream.write(head);
+ socket.pipe(upstream);
+ upstream.pipe(socket);
+ });
+ upstream.on("error", () => socket.destroy());
+ socket.on("error", () => upstream.destroy());
+ };
+}
+
+/** Compiles the release bytecode, then serves it on `port` until the scope closes. */
+export const serveReleaseBytecode = Effect.fn("releaseBytecode.serve")(function* (input: {
+ readonly port: number;
+ readonly metroPort: number;
+ readonly checkout: string;
+ readonly out: string;
+}) {
+ const bytecode = yield* compile(input);
+ const toMetro = forward(input.metroPort, input.port);
+ const server = NodeHttp.createServer((request, response) => {
+ if (!/\.bundle(\?|$)/.test(request.url ?? "")) return toMetro(request, response);
+ response.writeHead(200, {
+ "content-type": "application/javascript",
+ "content-length": String(bytecode.length),
+ });
+ response.end(bytecode);
+ });
+ server.on("upgrade", forwardUpgrade(input.metroPort, input.port));
+ yield* Effect.acquireRelease(
+ Effect.callback((resume) => {
+ server.once("error", (error) =>
+ resume(Effect.fail(new DeviceError({ message: error.message }))),
+ );
+ server.listen(input.port, "0.0.0.0", () => resume(Effect.void));
+ }),
+ () =>
+ Effect.sync(() => {
+ server.closeAllConnections();
+ server.close();
+ }),
+ );
+ return bytecode.length;
+});
diff --git a/scripts/mobile-behavior/run.ts b/scripts/mobile-behavior/run.ts
index 7254b9884d0fb..e9444d88d8663 100644
--- a/scripts/mobile-behavior/run.ts
+++ b/scripts/mobile-behavior/run.ts
@@ -1,12 +1,10 @@
#!/usr/bin/env node
-// @effect-diagnostics nodeBuiltinImport:off globalJsonInEffect:off - owns Metro and writes result files.
+// @effect-diagnostics nodeBuiltinImport:off globalJsonInEffect:off - writes result files.
/**
* Drives the T3 Code iOS dev client on one simulator against an isolated server with scripted
* replies, and grades app behavior from the dev-only probe and server state. See README.md.
*/
-import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
-import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
@@ -16,68 +14,16 @@ import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { Command, Flag } from "effect/cli";
-import { FetchHttpClient, HttpClient } from "effect/http";
import { CASES, type MobileBehaviorCase } from "./cases.ts";
-import { APP_ID, DeviceError, makeDevice, SCHEME } from "./device.ts";
-import { freePort, startEnvironment, uuid } from "./environment.ts";
+import { DeviceError } from "./device.ts";
import { blockingResults, checkFails, resultsFor, summarize, type SampleRow } from "./grade.ts";
import { SCENARIOS, type Pose, type ScenarioContext } from "./scenarios.ts";
+import { reachableHost, startSession } from "./session.ts";
const REPO_ROOT = NodePath.resolve(import.meta.dirname, "../..");
const POSES = ["phone", "duo-closed", "duo-open", "ipad"] as const satisfies ReadonlyArray;
-/** This machine's address as the simulator sees it: the tailnet address, else the first LAN IPv4. */
-function reachableHost(): string {
- const tailnet = NodeChildProcess.spawnSync("tailscale", ["ip", "-4"], { encoding: "utf8" });
- const ip = tailnet.status === 0 ? tailnet.stdout.trim().split("\n")[0] : undefined;
- if (ip) return ip;
- const lan = Object.values(NodeOS.networkInterfaces())
- .flatMap((entries) => entries ?? [])
- .find((entry) => entry.family === "IPv4" && !entry.internal);
- return lan?.address ?? "127.0.0.1";
-}
-
-/** Metro with the behavior probe compiled in, stopped with its process group when the scope ends. */
-const startMetro = Effect.fn("run.startMetro")(function* (host: string, out: string) {
- const port = yield* freePort();
- const log = NodeFS.openSync(NodePath.join(out, "metro.log"), "w");
- yield* Effect.acquireRelease(
- Effect.sync(() =>
- NodeChildProcess.spawn(
- "npx",
- ["expo", "start", "--dev-client", "--scheme", SCHEME, "--lan", "--port", String(port)],
- {
- cwd: NodePath.join(REPO_ROOT, "apps/mobile"),
- detached: true,
- stdio: ["ignore", log, log],
- env: {
- ...process.env,
- APP_VARIANT: "development",
- CI: "1",
- // Lazily fetched chunks sometimes arrive broken on pool emulators and throw SyntaxErrors.
- EXPO_NO_METRO_LAZY: "1",
- EXPO_PUBLIC_T3_BEHAVIOR_PROBE: "1",
- REACT_NATIVE_PACKAGER_HOSTNAME: host,
- },
- },
- ),
- ),
- (child) => Effect.sync(() => child.pid !== undefined && process.kill(-child.pid, "SIGTERM")),
- );
- const metro = `http://${host}:${port}`;
- for (let attempt = 0; attempt < 120; attempt++) {
- const ready = yield* HttpClient.get(`${metro}/status`).pipe(
- Effect.flatMap((response) => response.text),
- Effect.provide(FetchHttpClient.layer),
- Effect.orElseSucceed(() => ""),
- );
- if (ready.includes("running")) return metro;
- yield* Effect.sleep("1 second");
- }
- return yield* new DeviceError({ message: `Metro never started; see ${out}/metro.log.` });
-});
-
const decodeRows = (file: string): ReadonlyArray =>
NodeFS.readFileSync(file, "utf8")
.split("\n")
@@ -160,82 +106,19 @@ const command = Command.make(
const host = Option.getOrElse(flags.host, reachableHost);
const startedAt = yield* Clock.currentTimeMillis;
- const env = yield* startEnvironment({ baseDir: NodePath.join(out, "env"), deviceHost: host });
- const tag = (yield* uuid).slice(0, 4);
- yield* Console.error(`Seeding a 60-turn thread on ${env.origin}...`);
- const longThread = yield* env.longThread(`Long settled thread ${tag}`, 60);
-
- const metro = yield* startMetro(host, out);
- const device = makeDevice({
+ const { env, device, longThread, seeded } = yield* startSession({
+ out,
+ host,
agentDevice: flags.agentDevice,
- targetArgs: [
- "--platform",
- "ios",
- ...(flags.device ? ["--udid", flags.device] : []),
- "--config",
- flags.deviceConfig,
- "--session",
- flags.deviceSession,
- ],
- metro,
+ deviceConfig: flags.deviceConfig,
+ deviceSession: flags.deviceSession,
+ device: flags.device,
deviceName: flags.deviceName,
+ ...(flags.pose === "duo-closed" ? { fold: "closed" as const } : {}),
+ ...(flags.pose === "duo-open" ? { fold: "open" as const } : {}),
+ forgetOtherEnvironments: flags.forgetOtherEnvironments,
+ longTurns: 60,
});
- yield* Console.error(`Opening the dev client against ${metro}...`);
- // agent-device answers iOS's "Open in" prompt; the flags keep dev-menu chrome off the app.
- const metroUrl = new URL(metro);
- const launchUrl = `${SCHEME}://expo-development-client/?url=${encodeURIComponent(metro)}&disableOnboarding=1&__expo_disable_fab=1&__expo_disable_auto_launch=1`;
- yield* device
- .run(
- [
- "open",
- APP_ID,
- "--relaunch",
- "--metro-host",
- metroUrl.hostname,
- "--metro-port",
- metroUrl.port,
- "--launch-url",
- launchUrl,
- ],
- 240_000,
- )
- .pipe(Effect.retry({ times: 2 }));
- for (let attempt = 0; ; attempt++) {
- const loaded = yield* device
- .evaluate("typeof __t3Behavior")
- .pipe(Effect.orElseSucceed(() => ""));
- if (loaded === "object") break;
- // iOS asks before a URL opens another app; busy hosts can miss the first accept.
- if (attempt % 5 === 0) yield* device.acceptOpenPrompt.pipe(Effect.ignore);
- if (attempt > 120)
- return yield* new DeviceError({
- message:
- "The probe never loaded. Is this a dev client built from this checkout's native fingerprint?",
- });
- yield* Effect.sleep("2 seconds");
- }
- if (flags.pose === "duo-closed" || flags.pose === "duo-open")
- yield* device.fold(flags.pose === "duo-closed" ? "closed" : "open");
- const forget = (ids: ReadonlyArray) =>
- device
- .evaluate(`__t3Behavior.forgetEnvironments(${JSON.stringify(ids)})`)
- .pipe(Effect.andThen(Effect.sleep("3 seconds")));
- const pairing = yield* env.pairingUrl();
- yield* device.openUrl(
- `${SCHEME}://connections/new?pairingUrl=${encodeURIComponent(pairing)}&autoConnect=1`,
- );
- // Registered once pairing starts, so a stopped run never leaves its environment in the app.
- yield* Effect.addFinalizer(() => forget([env.environmentId]).pipe(Effect.ignore));
- const seeded = (state: { homeList: unknown; threads: Record }) =>
- state.homeList !== null && longThread in state.threads;
- yield* device.waitFor("the paired environment's threads on Home", seeded, 60_000);
- // Other saved environments keep cached threads (some stuck working) that skew status cases.
- const others = (yield* device.state).environments.filter((id) => id !== env.environmentId);
- if (others.length > 0 && !flags.forgetOtherEnvironments)
- return yield* new DeviceError({
- message: `The app has ${others.length} other saved environment(s). Use a simulator with no other connections, or pass --forget-other-environments to remove them.`,
- });
- if (others.length > 0) yield* forget(others);
const ctx: ScenarioContext = {
env,
device,
diff --git a/scripts/mobile-behavior/session.ts b/scripts/mobile-behavior/session.ts
new file mode 100644
index 0000000000000..ee5d235b8c9f4
--- /dev/null
+++ b/scripts/mobile-behavior/session.ts
@@ -0,0 +1,231 @@
+// @effect-diagnostics nodeBuiltinImport:off - owns Metro.
+/**
+ * One device's run state, shared by mobile:behavior and mobile:metrics: an isolated server with a
+ * long settled thread, a Metro serving a checkout with the behavior probe, and the dev client opened
+ * on it and paired with the server. Everything stops when the caller's scope closes.
+ */
+import * as NodeChildProcess from "node:child_process";
+import * as NodeFS from "node:fs";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+import type { ThreadId } from "@t3tools/contracts";
+import * as Console from "effect/Console";
+import * as Effect from "effect/Effect";
+import { FetchHttpClient, HttpClient } from "effect/http";
+
+import { APP_ID, DeviceError, makeDevice, SCHEME, type ProbeState } from "./device.ts";
+import { freePort, startEnvironment, uuid, type EnvironmentOptions } from "./environment.ts";
+import { serveReleaseBytecode } from "./release-bytecode.ts";
+
+const REPO_ROOT = NodePath.resolve(import.meta.dirname, "../..");
+
+/** This machine's address as the simulator sees it: the tailnet address, else the first LAN IPv4. */
+export function reachableHost(): string {
+ const tailnet = NodeChildProcess.spawnSync("tailscale", ["ip", "-4"], { encoding: "utf8" });
+ const ip = tailnet.status === 0 ? tailnet.stdout.trim().split("\n")[0] : undefined;
+ if (ip) return ip;
+ const lan = Object.values(NodeOS.networkInterfaces())
+ .flatMap((entries) => entries ?? [])
+ .find((entry) => entry.family === "IPv4" && !entry.internal);
+ return lan?.address ?? "127.0.0.1";
+}
+
+/**
+ * `dev` serves the development bundle; `release` serves the production bundle as Hermes bytecode
+ * (see release-bytecode.ts) to the same dev client.
+ */
+export type Build = "dev" | "release";
+
+/** Metro with the behavior probe compiled in, stopped with its process group when the scope ends. */
+export const startMetro = Effect.fn("session.startMetro")(function* (input: {
+ readonly host: string;
+ readonly out: string;
+ /** The checkout whose app Metro serves; defaults to this one. */
+ readonly checkout?: string;
+ readonly env?: Readonly>;
+ readonly build?: Build;
+}) {
+ const checkout = input.checkout ?? REPO_ROOT;
+ const release = input.build === "release";
+ const port = yield* freePort();
+ // In release mode the app opens the bytecode proxy on `port`, which fronts Metro.
+ const metroPort = release ? yield* freePort() : port;
+ const log = NodeFS.openSync(NodePath.join(input.out, "metro.log"), "w");
+ yield* Effect.acquireRelease(
+ Effect.sync(() =>
+ NodeChildProcess.spawn(
+ "npx",
+ [
+ "expo",
+ "start",
+ "--dev-client",
+ "--scheme",
+ SCHEME,
+ "--lan",
+ "--port",
+ String(metroPort),
+ ...(release ? ["--no-dev", "--minify"] : []),
+ ],
+ {
+ cwd: NodePath.join(checkout, "apps/mobile"),
+ detached: true,
+ stdio: ["ignore", log, log],
+ env: {
+ ...process.env,
+ APP_VARIANT: "development",
+ CI: "1",
+ // Lazily fetched chunks sometimes arrive broken on pool emulators and throw SyntaxErrors.
+ EXPO_NO_METRO_LAZY: "1",
+ EXPO_PUBLIC_T3_BEHAVIOR_PROBE: "1",
+ REACT_NATIVE_PACKAGER_HOSTNAME: input.host,
+ ...input.env,
+ },
+ },
+ ),
+ ),
+ (child) => Effect.sync(() => child.pid !== undefined && process.kill(-child.pid, "SIGTERM")),
+ );
+ const metro = `http://${input.host}:${port}`;
+ for (let attempt = 0; ; attempt++) {
+ const ready = yield* HttpClient.get(`http://${input.host}:${metroPort}/status`).pipe(
+ Effect.flatMap((response) => response.text),
+ Effect.provide(FetchHttpClient.layer),
+ Effect.orElseSucceed(() => ""),
+ );
+ if (ready.includes("running")) break;
+ if (attempt >= 120)
+ return yield* new DeviceError({
+ message: `Metro never started; see ${input.out}/metro.log.`,
+ });
+ yield* Effect.sleep("1 second");
+ }
+ if (!release) return metro;
+ yield* Console.error("Compiling the production bundle to Hermes bytecode (a few minutes)...");
+ const bytes = yield* serveReleaseBytecode({ port, metroPort, checkout, out: input.out });
+ yield* Console.error(`Serving ${Math.round(bytes / 1024)} KB of release bytecode on ${metro}.`);
+ return metro;
+});
+
+export interface SessionOptions {
+ readonly out: string;
+ readonly host: string;
+ readonly agentDevice: string;
+ readonly deviceConfig: string;
+ readonly deviceSession: string;
+ /** Simulator UDID; empty for a Simlock lease, whose gateway picks it. */
+ readonly device: string;
+ readonly deviceName: string;
+ readonly fold?: "closed" | "open";
+ readonly forgetOtherEnvironments: boolean;
+ /** Turns in the long settled thread every run seeds. */
+ readonly longTurns: number;
+ readonly checkout?: string;
+ readonly metroEnv?: Readonly>;
+ readonly build?: Build;
+ readonly environment?: EnvironmentOptions;
+}
+
+export const startSession = Effect.fn("session.start")(function* (options: SessionOptions) {
+ const env = yield* startEnvironment({
+ baseDir: NodePath.join(options.out, "env"),
+ deviceHost: options.host,
+ ...options.environment,
+ });
+ const tag = (yield* uuid).slice(0, 4);
+ yield* Console.error(`Seeding a ${options.longTurns}-turn thread on ${env.origin}...`);
+ const longTitle = `Long settled thread ${tag}`;
+ const longThread: ThreadId = yield* env.longThread(longTitle, options.longTurns);
+
+ const metro = yield* startMetro({
+ host: options.host,
+ out: options.out,
+ ...(options.checkout ? { checkout: options.checkout } : {}),
+ ...(options.metroEnv ? { env: options.metroEnv } : {}),
+ ...(options.build ? { build: options.build } : {}),
+ });
+ const device = makeDevice({
+ agentDevice: options.agentDevice,
+ targetArgs: [
+ "--platform",
+ "ios",
+ ...(options.device ? ["--udid", options.device] : []),
+ "--config",
+ options.deviceConfig,
+ "--session",
+ options.deviceSession,
+ ],
+ metro,
+ deviceName: options.deviceName,
+ });
+ yield* Console.error(`Opening the dev client against ${metro}...`);
+ // agent-device answers iOS's "Open in" prompt; the flags keep dev-menu chrome off the app.
+ const metroUrl = new URL(metro);
+ const launchUrl = `${SCHEME}://expo-development-client/?url=${encodeURIComponent(metro)}&disableOnboarding=1&__expo_disable_fab=1&__expo_disable_auto_launch=1`;
+ yield* device
+ .run(
+ [
+ "open",
+ APP_ID,
+ "--relaunch",
+ "--metro-host",
+ metroUrl.hostname,
+ "--metro-port",
+ metroUrl.port,
+ "--launch-url",
+ launchUrl,
+ ],
+ 240_000,
+ )
+ .pipe(Effect.retry({ times: 2 }));
+ for (let attempt = 0; ; attempt++) {
+ const loaded = yield* device
+ .evaluate("typeof __t3Behavior")
+ .pipe(Effect.orElseSucceed(() => ""));
+ if (loaded === "object") break;
+ // iOS asks before a URL opens another app; busy hosts can miss the first accept.
+ if (attempt % 5 === 0) yield* device.acceptOpenPrompt.pipe(Effect.ignore);
+ if (attempt > 120)
+ return yield* new DeviceError({
+ message:
+ "The probe never loaded. Is this a dev client built from this checkout's native fingerprint?",
+ });
+ yield* Effect.sleep("2 seconds");
+ }
+ if (options.fold) yield* device.fold(options.fold);
+ const forget = (ids: ReadonlyArray) =>
+ device
+ .evaluate(`__t3Behavior.forgetEnvironments(${JSON.stringify(ids)})`)
+ .pipe(Effect.andThen(Effect.sleep("3 seconds")));
+ const pair = Effect.gen(function* () {
+ const pairing = yield* env.pairingUrl();
+ yield* device.openUrl(
+ `${SCHEME}://connections/new?pairingUrl=${encodeURIComponent(pairing)}&autoConnect=1`,
+ );
+ });
+ yield* pair;
+ // Registered once pairing starts, so a stopped run never leaves its environment in the app.
+ yield* Effect.addFinalizer(() => forget([env.environmentId]).pipe(Effect.ignore));
+ const seeded = (state: ProbeState) => state.homeList !== null && longThread in state.threads;
+ // A busy pool simulator sometimes drops the first pairing link; a fresh credential retries it.
+ yield* device
+ .waitFor("the paired environment's threads on Home", seeded, 60_000)
+ .pipe(
+ Effect.catch(() =>
+ pair.pipe(
+ Effect.andThen(
+ device.waitFor("the paired environment's threads on Home", seeded, 60_000),
+ ),
+ ),
+ ),
+ );
+ // Other saved environments keep cached threads (some stuck working) that skew status cases.
+ const others = (yield* device.state).environments.filter((id) => id !== env.environmentId);
+ if (others.length > 0 && !options.forgetOtherEnvironments)
+ return yield* new DeviceError({
+ message: `The app has ${others.length} other saved environment(s). Use a simulator with no other connections, or pass --forget-other-environments to remove them.`,
+ });
+ if (others.length > 0) yield* forget(others);
+ return { env, device, metro, longThread, longTitle, seeded };
+});
+
+export type Session = Effect.Success>;
diff --git a/scripts/mobile-e2e/device.ts b/scripts/mobile-e2e/device.ts
index f27092d35dcf7..7d2b3218a3b03 100644
--- a/scripts/mobile-e2e/device.ts
+++ b/scripts/mobile-e2e/device.ts
@@ -153,12 +153,12 @@ export class Device {
return parsed.data ?? {};
}
- /** The shared-cache dev client for this checkout; the worker downloads it itself. */
- async install() {
+ /** The shared-cache dev client for a checkout (this one by default); the worker downloads it itself. */
+ async install(checkout = this.pool.repoRoot) {
await run(
NodeProcess.execPath,
[
- NodePath.join(this.pool.repoRoot, "scripts/mobile-native-client.ts"),
+ NodePath.join(checkout, "scripts/mobile-native-client.ts"),
"ensure",
this.pose.platform,
"--session",
diff --git a/scripts/mobile-metrics.ts b/scripts/mobile-metrics.ts
new file mode 100644
index 0000000000000..030e7c39e2bf7
--- /dev/null
+++ b/scripts/mobile-metrics.ts
@@ -0,0 +1,727 @@
+#!/usr/bin/env node
+// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalJsonInEffect:off - leases go through mobile-behavior's Promise-based pool helpers.
+/**
+ * Measures the mobile app like client-metrics measures the web one: thread switches, tabs, a pull
+ * request, typing and scrolling on a Simlock iOS simulator, through mobile:behavior's server,
+ * Metro and probe. See docs/internals/16_performance-regressions.md#mobile-switch-metrics.
+ */
+import * as NodeFSP from "node:fs/promises";
+import * as NodePath from "node:path";
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
+import * as Console from "effect/Console";
+import * as DateTime from "effect/DateTime";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+import { Argument, Command, Flag } from "effect/cli";
+import { ChildProcessSpawner } from "effect/process";
+
+import { compareSeries, Floors, noiseOfSeries } from "./client-metrics-report.ts";
+import { DIFF_FILES, pullRequestDetail, sourceFile } from "./client-metrics-fixture.ts";
+import {
+ leaseAndInstall,
+ openPool,
+ releaseOnCrash,
+ renewWhileRunning,
+ type PoolAccess,
+} from "./mobile-behavior/pool.ts";
+import { reachableHost, startSession, type Build } from "./mobile-behavior/session.ts";
+import type { Device as PoolDevice } from "./mobile-e2e/device.ts";
+import {
+ CASE_NAMES,
+ CASES,
+ type CaseContext,
+ type CaseName,
+ type Fixtures,
+} from "./mobile-metrics/cases.ts";
+import {
+ flatten,
+ MobileMetrics,
+ PROBE_KEYS,
+ summaryTable,
+ WORKLOAD_KEYS,
+ workloadDifferences,
+ type Memory,
+ type Run,
+ type SoakSample,
+ type Step,
+} from "./mobile-metrics/report.ts";
+import { run } from "./scenarios/shell.ts";
+import { serveFakeGitHub, type FakeGitHub } from "./server-metrics-forge.ts";
+import { machineLoad, MetricsError, output, runAbRounds } from "./server-metrics.ts";
+
+const REPO_ROOT = NodePath.resolve(import.meta.dirname, "..");
+const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
+const decodeMetrics = Schema.decodeUnknownEffect(Schema.fromJsonString(MobileMetrics));
+const encodeMetrics = Schema.encodeEffect(fromJsonStringPretty(MobileMetrics));
+const decodeFloors = Schema.decodeUnknownEffect(Schema.fromJsonString(Floors));
+const encodeFloors = Schema.encodeEffect(fromJsonStringPretty(Floors));
+
+const log = (message: string) => Console.error(`[mobile-metrics] ${message}`);
+
+/** The scratch repository on a branch changing many files, with an open PR on the fake GitHub. */
+const prepareBenchProject = (forge: FakeGitHub) =>
+ Effect.fn("mobileMetrics.prepareProject")(function* (workspace: string) {
+ const fs = yield* FileSystem.FileSystem;
+ const git = (args: ReadonlyArray) => run("git", args, { cwd: workspace });
+ const author = ["-c", "user.email=bench@t3.codes", "-c", "user.name=bench"];
+ yield* git(["branch", "-M", "main"]);
+ yield* fs.makeDirectory(NodePath.join(workspace, "src"), { recursive: true });
+ for (let index = 0; index < DIFF_FILES; index++)
+ yield* fs.writeFileString(
+ NodePath.join(workspace, `src/module${index}.ts`),
+ sourceFile(index, "before"),
+ );
+ yield* git(["add", "."]);
+ yield* git([...author, "commit", "-qm", "modules"]);
+ // The feature branch commits these, so its diff against main is the pull request's weight.
+ for (let index = 0; index < DIFF_FILES; index++)
+ yield* fs.writeFileString(
+ NodePath.join(workspace, `src/module${index}.ts`),
+ sourceFile(index, "after"),
+ );
+ yield* forge.setupProject(workspace);
+ });
+
+/** The app process's memory from agent-device, in MB; its field differs by platform. */
+const processMemory = Effect.fn("mobileMetrics.processMemory")(function* (
+ device: CaseContext["device"],
+ raw: string,
+) {
+ const out = yield* device.run(["perf", "memory", "sample", "--json"]).pipe(Effect.option);
+ if (Option.isNone(out)) return null;
+ yield* Effect.promise(() => NodeFSP.writeFile(raw, out.value));
+ const memory = (
+ JSON.parse(out.value) as { data?: { metrics?: { memory?: Record } } }
+ ).data?.metrics?.memory;
+ if (!memory || memory.available === false) return null;
+ const field =
+ ["physFootprintKb", "footprintKb", "totalPssKb", "residentMemoryKb", "totalRssKb"].find(
+ (key) => typeof memory[key] === "number",
+ ) ?? Object.keys(memory).find((key) => /Kb$/.test(key) && typeof memory[key] === "number");
+ return field ? Math.round(((memory[field] as number) / 1024) * 10) / 10 : null;
+});
+
+const memorySample = Effect.fn("mobileMetrics.memory")(function* (
+ device: CaseContext["device"],
+ label: string,
+ out: string,
+) {
+ const heap = yield* device.evaluate("__t3Behavior.heap()").pipe(
+ Effect.map((value) => {
+ // Older probes return the byte count itself.
+ if (typeof value === "number") return value;
+ const parsed = JSON.parse(String(value)) as { bytes: number | null };
+ return parsed.bytes;
+ }),
+ Effect.orElseSucceed(() => null),
+ );
+ const sample: Memory = {
+ label,
+ heapMB: typeof heap === "number" ? Math.round((heap / 1_048_576) * 10) / 10 : null,
+ processMB: yield* processMemory(device, NodePath.join(out, `memory-${label}.json`)),
+ };
+ return sample;
+});
+
+interface MeasureOptions {
+ readonly checkout: string;
+ readonly out: string;
+ readonly access: PoolAccess;
+ readonly deviceSession: string;
+ readonly cases: ReadonlyArray;
+ readonly rounds: number;
+ readonly longTurns: number;
+ readonly renders: boolean;
+ readonly host: string;
+ readonly soak: number;
+ readonly build: Build;
+}
+
+/** The cases `--soak` repeats: thread switches, the flow whose memory matters most. */
+const SOAK_CASES = ["switch-short", "switch-long"] as const satisfies ReadonlyArray;
+
+/** One app launch on a checkout's Metro: seed, pair, run every case `rounds` times. */
+const measureOnce = Effect.fn("mobileMetrics.measureOnce")(function* (options: MeasureOptions) {
+ yield* Effect.promise(() => NodeFSP.mkdir(options.out, { recursive: true }));
+ const forge = yield* serveFakeGitHub({ detail: pullRequestDetail() });
+ const fs = yield* FileSystem.FileSystem;
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const session = yield* startSession({
+ out: options.out,
+ host: options.host,
+ agentDevice: options.access.pool.agentDevice,
+ deviceConfig: options.access.config,
+ deviceSession: options.deviceSession,
+ device: "",
+ deviceName: "",
+ // A leased simulator is wiped on release; anything saved on it is a previous run's.
+ forgetOtherEnvironments: true,
+ longTurns: options.longTurns,
+ checkout: options.checkout,
+ metroEnv: options.renders ? { EXPO_PUBLIC_T3_RENDER_COUNTER: "1" } : {},
+ build: options.build,
+ environment: {
+ serverEnv: forge.env,
+ prepareWorkspace: (workspace) =>
+ prepareBenchProject(forge)(workspace).pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
+ ),
+ },
+ });
+ const { env, device } = session;
+ const short = yield* env.launch("Bench short", "Hi. [[eval:reply]]");
+ yield* env.settled(short);
+ // A side chat people open holds a message; an empty one shows a placeholder, not a timeline.
+ const sideChat = yield* env.forkSideChat(short, "Bench side chat");
+ yield* env.send(sideChat, "Hi from the side. [[eval:reply]]");
+ yield* env.settled(sideChat);
+ const fixtures: Fixtures = {
+ sideChat: { id: sideChat, title: "Bench side chat" },
+ short: { id: short, title: "Bench short" },
+ long: { id: session.longThread, title: session.longTitle },
+ };
+ const supported = yield* device
+ .evaluate("typeof __t3Behavior.perfStart")
+ .pipe(Effect.orElseSucceed(() => "undefined"));
+ if (supported !== "function") {
+ const reason = "this checkout's behavior probe has no perf window";
+ return {
+ steps: [],
+ memory: [],
+ skipped: options.cases.map((name) => ({ case: name, reason })),
+ } satisfies Run;
+ }
+ yield* Effect.sleep("3 seconds");
+ const memory: Memory[] = [yield* memorySample(device, "launch", options.out)];
+ const steps: Step[] = [];
+ const skipped: Array<{ case: string; reason: string }> = [];
+ const visited = new Set();
+ for (let round = 1; round <= options.rounds; round++) {
+ for (const name of options.cases) {
+ const ctx: CaseContext = { session, device, fixtures, round, visited };
+ const result = yield* CASES[name](ctx).pipe(
+ Effect.map((measured) => ({ measured })),
+ Effect.catch((error) => Effect.succeed({ error: error.message })),
+ );
+ if ("error" in result) {
+ yield* log(`${name} round ${round}: ${result.error}`);
+ // What was on screen, so a selector that missed can be fixed from the labels.
+ const labels = yield* device.nodes.pipe(
+ Effect.map((nodes) =>
+ nodes.flatMap((node) =>
+ node.label ? [`${node.kind ?? node.type}: ${node.label}`] : [],
+ ),
+ ),
+ Effect.orElseSucceed(() => []),
+ );
+ yield* Effect.promise(() =>
+ NodeFSP.writeFile(
+ NodePath.join(options.out, `${name}-r${round}-screen.txt`),
+ labels.join("\n"),
+ ),
+ );
+ skipped.push({ case: name, reason: result.error.slice(0, 300) });
+ // A case that failed midway can leave a menu or another tab up; start the next from Home.
+ yield* device.reload(session.seeded).pipe(Effect.ignore);
+ } else {
+ steps.push(...result.measured);
+ for (const step of result.measured)
+ yield* log(
+ `${name} ${step.step} r${round}: content ${step.contentMs ?? "–"} settled ${step.settledMs ?? "–"} commits ${step.commits}`,
+ );
+ }
+ }
+ }
+ memory.push(yield* memorySample(device, "after-cases", options.out));
+ const soak: SoakSample[] = [];
+ const sample = Effect.fn("mobileMetrics.soakSample")(function* (iteration: number, name: string) {
+ const at = yield* memorySample(device, `soak-${iteration}-${name}`, options.out);
+ soak.push({ iteration, case: name, heapMB: at.heapMB, processMB: at.processMB });
+ // What the app retains, so heap growth can be traced to atoms or mounted components.
+ const retention = yield* device
+ .evaluate("__t3Behavior.retention()")
+ .pipe(Effect.orElseSucceed(() => null));
+ if (typeof retention === "string")
+ yield* Effect.promise(() =>
+ NodeFSP.appendFile(
+ NodePath.join(options.out, "soak-retention.ndjson"),
+ `${JSON.stringify({ iteration, case: name, heapMB: at.heapMB, ...JSON.parse(retention) })}\n`,
+ ),
+ );
+ yield* log(`soak ${iteration} ${name}: heap ${at.heapMB} MB, process ${at.processMB} MB`);
+ });
+ if (options.soak > 0) yield* sample(0, "start");
+ for (let iteration = 1; iteration <= options.soak; iteration++) {
+ for (const name of SOAK_CASES) {
+ const ctx: CaseContext = {
+ session,
+ device,
+ fixtures,
+ round: options.rounds + iteration,
+ visited,
+ };
+ const ran = yield* CASES[name](ctx).pipe(
+ Effect.as(true),
+ Effect.catch((error) =>
+ log(`soak ${iteration} ${name}: ${error.message}`).pipe(Effect.as(false)),
+ ),
+ );
+ if (!ran) yield* device.reload(session.seeded).pipe(Effect.ignore);
+ yield* sample(iteration, name);
+ }
+ }
+ return {
+ steps,
+ memory,
+ ...(soak.length ? { soak } : {}),
+ ...(skipped.length ? { skipped } : {}),
+ } satisfies Run;
+}, Effect.scoped);
+
+/** Leases the device for a command, keeps the lease alive, and releases it at the end. */
+const withLease = Effect.fn("mobileMetrics.withLease")(function* (
+ out: string,
+ deviceName: string,
+ use: (access: PoolAccess, device: PoolDevice) => Effect.Effect,
+) {
+ const runId = DateTime.formatIso(yield* DateTime.now).replaceAll(/[:.]/g, "-");
+ return yield* Effect.acquireUseRelease(
+ Effect.promise(async () => {
+ await NodeFSP.mkdir(out, { recursive: true });
+ const access = await openPool(REPO_ROOT, out);
+ let device: PoolDevice | null = null;
+ try {
+ device = await leaseAndInstall(
+ {
+ id: "metrics",
+ platform: "ios",
+ device: deviceName,
+ form: "phone",
+ appearance: "light",
+ },
+ access.pool,
+ `metrics-${runId}`,
+ (message) => process.stderr.write(`[mobile-metrics] ${message}\n`),
+ );
+ const renewing = renewWhileRunning(access, device.session);
+ const crashing = releaseOnCrash(device, access);
+ return {
+ access,
+ device,
+ stop: () => {
+ renewing();
+ crashing();
+ },
+ };
+ } catch (error) {
+ await device?.release();
+ await access.close();
+ throw error;
+ }
+ }),
+ ({ access, device }) => use(access, device),
+ ({ access, device, stop }) =>
+ Effect.promise(async () => {
+ stop();
+ await device.release();
+ await access.close();
+ }),
+ );
+});
+
+const metaFor = Effect.fn("mobileMetrics.metaFor")(function* (
+ checkout: string,
+ workload: {
+ readonly cases: ReadonlyArray;
+ readonly rounds: number;
+ readonly longTurns: number;
+ readonly renders: boolean;
+ readonly device: string;
+ readonly build: Build;
+ },
+) {
+ return {
+ commit: Option.getOrNull(yield* output("git", ["rev-parse", "--short=12", "HEAD"], checkout)),
+ device: workload.device,
+ platform: "ios-simulator",
+ build: workload.build === "release" ? "release" : "development",
+ cases: workload.cases.join(","),
+ rounds: workload.rounds,
+ longTurns: workload.longTurns,
+ renders: workload.renders,
+ loadBefore: yield* machineLoad,
+ measuredAt: DateTime.formatIso(yield* DateTime.now),
+ };
+});
+
+const writeMetrics = Effect.fn("mobileMetrics.write")(function* (
+ file: string,
+ metrics: MobileMetrics,
+) {
+ const fs = yield* FileSystem.FileSystem;
+ yield* fs.writeFileString(`${file}.tmp`, `${yield* encodeMetrics(metrics)}\n`);
+ yield* fs.rename(`${file}.tmp`, file);
+});
+
+const readMetrics = Effect.fn("mobileMetrics.read")(function* (file: string) {
+ const fs = yield* FileSystem.FileSystem;
+ return yield* fs.readFileString(file).pipe(Effect.flatMap(decodeMetrics));
+});
+
+const readFloors = Effect.fn("mobileMetrics.readFloors")(function* (file: Option.Option) {
+ const fs = yield* FileSystem.FileSystem;
+ if (Option.isNone(file)) return undefined;
+ return yield* fs.readFileString(file.value).pipe(Effect.flatMap(decodeFloors));
+});
+
+/** Prints the comparison and sets exit code 1 when a metric got worse. */
+const report = Effect.fn("mobileMetrics.report")(function* (
+ before: MobileMetrics,
+ after: MobileMetrics,
+ threshold: number,
+ floors: Floors | undefined,
+) {
+ const workload = workloadDifferences(before, after);
+ if (workload.differ.length > 0)
+ return yield* new MetricsError({
+ message: `the files ran different workloads (${workload.differ.join("; ")}); rerun one side with the other's settings`,
+ });
+ const { table, regressed, improved, noisy, compared } = compareSeries(
+ flatten(before),
+ flatten(after),
+ [
+ "### Mobile metrics (lower is better)",
+ "",
+ `before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs), ${before.meta.device}, ${before.meta.build} build${floors ? `, floors calibrated on ${floors.platform}` : ""}`,
+ ],
+ threshold,
+ floors,
+ );
+ yield* Console.log(table);
+ if (before.meta.renders !== after.meta.renders)
+ yield* Console.error(
+ "Warning: one side counted renders, which slows commits; compare like with like",
+ );
+ if (compared === 0) return yield* new MetricsError({ message: "the two files share no metric" });
+ if (noisy.length)
+ yield* Console.error(
+ `Moved, but not gated (too noisy, or one run a side): ${noisy.join(", ")}`,
+ );
+ if (improved.length) yield* Console.error(`Better: ${improved.join(", ")}`);
+ if (regressed.length === 0) return;
+ yield* Console.error(`Worse: ${regressed.join(", ")}`);
+ yield* Effect.sync(() => {
+ process.exitCode = 1;
+ });
+});
+
+/** The render counter reads React's development-only fiber fields. */
+const checkBuild = (input: { readonly renders: boolean; readonly build: Build }) =>
+ input.renders && input.build === "release"
+ ? Effect.fail(new MetricsError({ message: "--renders needs --build dev" }))
+ : Effect.void;
+
+const casesOf = (list: string) => {
+ const named = list
+ .split(",")
+ .map((entry) => entry.trim())
+ .filter(Boolean);
+ if (named.length === 0) return Effect.succeed(CASE_NAMES);
+ if (named.includes("switches"))
+ named.splice(named.indexOf("switches"), 1, "switch-short", "switch-long", "switch-working");
+ const unknown = named.filter((entry) => !(CASE_NAMES as ReadonlyArray).includes(entry));
+ return unknown.length
+ ? Effect.fail(
+ new MetricsError({
+ message: `unknown cases: ${unknown.join(", ")}; choose from switches, ${CASE_NAMES.join(", ")}`,
+ }),
+ )
+ : Effect.succeed(CASE_NAMES.filter((name) => named.includes(name)));
+};
+
+const measureFlags = {
+ device: Flag.String("device").pipe(
+ Flag.withDescription("Simlock iOS model to lease; compare only runs on one model."),
+ Flag.withDefault("iPhone 18 Pro"),
+ ),
+ rounds: Flag.Int("rounds").pipe(
+ Flag.withSchema(PositiveInt),
+ Flag.withDescription(
+ "Rounds over every case per app launch; a switch's first round is its first visit.",
+ ),
+ Flag.withDefault(3),
+ ),
+ longTurns: Flag.Int("long-turns").pipe(
+ Flag.withSchema(PositiveInt),
+ Flag.withDescription("Turns in the long settled thread."),
+ Flag.withDefault(40),
+ ),
+ cases: Flag.String("cases").pipe(
+ Flag.withDescription(
+ `Cases, comma separated: switches, ${CASE_NAMES.join(", ")}. Default: all.`,
+ ),
+ Flag.withDefault(""),
+ ),
+ renders: Flag.Boolean("renders").pipe(
+ Flag.withDescription(
+ "Count component renders and their causes per step with the render counter. It slows commits; compare like with like.",
+ ),
+ Flag.withDefault(false),
+ ),
+ build: Flag.Literals("build", ["dev", "release"]).pipe(
+ Flag.withDescription(
+ "dev runs the development bundle; release runs the production bundle as Hermes bytecode on the same dev client (compiling takes a few minutes per launch). Soak in release: dev-build heap grows with dev machinery.",
+ ),
+ Flag.withDefault("dev"),
+ ),
+ soak: Flag.Int("soak").pipe(
+ Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
+ Flag.withDescription(
+ "After the rounds, repeat the switch cases this many times, sampling the Hermes heap and process memory after each, with growth per iteration.",
+ ),
+ Flag.withDefault(0),
+ ),
+ host: Flag.String("host").pipe(
+ Flag.withDescription(
+ "Address the simulator reaches this machine on; defaults to the tailnet IP.",
+ ),
+ Flag.optional,
+ ),
+};
+const thresholdFlag = Flag.Int("threshold").pipe(
+ Flag.withDescription("Percent a metric must move, past its floor, to count."),
+ Flag.withDefault(10),
+);
+const floorsFlag = Flag.String("floors").pipe(
+ Flag.withDescription("Floors file from `noise --out`."),
+ Flag.optional,
+);
+
+const runCommand = Command.make(
+ "run",
+ {
+ ...measureFlags,
+ out: Flag.String("out").pipe(
+ Flag.withDescription("JSON file to write."),
+ Flag.withDefault("mobile-metrics.json"),
+ ),
+ checkout: Flag.String("checkout").pipe(
+ Flag.withDescription("Checkout whose app Metro serves, with dependencies installed."),
+ Flag.withDefault(REPO_ROOT),
+ ),
+ },
+ Effect.fn("mobileMetrics.run")(function* (input) {
+ const checkout = NodePath.resolve(input.checkout);
+ const out = NodePath.resolve(input.out);
+ const cases = yield* casesOf(input.cases);
+ yield* checkBuild(input);
+ const meta = yield* metaFor(checkout, { ...input, cases });
+ const artifacts = `${out.replace(/\.json$/, "")}-artifacts`;
+ const measured = yield* withLease(artifacts, input.device, (access, device) =>
+ Effect.gen(function* () {
+ if (checkout !== REPO_ROOT) yield* Effect.promise(() => device.install(checkout));
+ return yield* measureOnce({
+ checkout,
+ out: NodePath.join(artifacts, "run-1"),
+ access,
+ deviceSession: device.session,
+ cases,
+ rounds: input.rounds,
+ longTurns: input.longTurns,
+ renders: input.renders,
+ soak: input.soak,
+ build: input.build,
+ host: Option.getOrElse(input.host, reachableHost),
+ });
+ }),
+ );
+ const metrics: MobileMetrics = {
+ meta: { ...meta, loadAfter: yield* machineLoad },
+ runs: [measured],
+ };
+ yield* writeMetrics(out, metrics);
+ yield* Console.log(summaryTable(metrics));
+ }),
+).pipe(
+ Command.withDescription(
+ "Lease a Simlock iOS simulator, seed a server (replayed threads, a 40-file branch with a PR on a fake GitHub), open a checkout's dev client and measure each case.",
+ ),
+);
+
+const abCommand = Command.make(
+ "ab",
+ {
+ ...measureFlags,
+ checkoutA: Argument.String("checkout-a").pipe(Argument.withDescription("Baseline checkout.")),
+ checkoutB: Argument.String("checkout-b").pipe(Argument.withDescription("Candidate checkout.")),
+ abRounds: Flag.Int("ab-rounds").pipe(
+ Flag.withSchema(PositiveInt),
+ Flag.withDescription(
+ "App launches a side; each round runs A and B once, alternating which goes first.",
+ ),
+ Flag.withDefault(2),
+ ),
+ outDir: Flag.String("out-dir").pipe(Flag.withDefault("mobile-metrics-ab")),
+ threshold: thresholdFlag,
+ floors: floorsFlag,
+ },
+ Effect.fn("mobileMetrics.ab")(function* (input) {
+ const outDir = NodePath.resolve(input.outDir);
+ const cases = yield* casesOf(input.cases);
+ yield* checkBuild(input);
+ const floors = yield* readFloors(input.floors);
+ const checkouts = [
+ NodePath.resolve(input.checkoutA),
+ NodePath.resolve(input.checkoutB),
+ ] as const;
+ const metas = [
+ yield* metaFor(checkouts[0], { ...input, cases }),
+ yield* metaFor(checkouts[1], { ...input, cases }),
+ ] as const;
+ const host = Option.getOrElse(input.host, reachableHost);
+ let launches = 0;
+ const saved = yield* withLease(outDir, input.device, (access, device) =>
+ runAbRounds({
+ rounds: input.abRounds,
+ outDir,
+ runSide: Effect.fn("mobileMetrics.abSide")(function* (side: 0 | 1) {
+ // Each side's dev client, from the cache when both share a native fingerprint.
+ yield* Effect.promise(() => device.install(checkouts[side]));
+ return yield* measureOnce({
+ checkout: checkouts[side],
+ out: NodePath.join(outDir, `${side === 0 ? "a" : "b"}-${++launches}`),
+ access,
+ deviceSession: device.session,
+ cases,
+ rounds: input.rounds,
+ longTurns: input.longTurns,
+ renders: input.renders,
+ soak: input.soak,
+ build: input.build,
+ host,
+ });
+ }),
+ save: Effect.fn("mobileMetrics.abSave")(function* (side: 0 | 1, runs: ReadonlyArray) {
+ const file: MobileMetrics = {
+ meta: { ...metas[side], loadAfter: yield* machineLoad },
+ runs: [...runs],
+ };
+ yield* writeMetrics(NodePath.join(outDir, side === 0 ? "a.json" : "b.json"), file);
+ return file;
+ }),
+ }),
+ );
+ yield* report(saved[0], saved[1], input.threshold, floors);
+ }),
+).pipe(
+ Command.withDescription(
+ "Run two checkouts alternately (A B, then B A) on one leased simulator and compare them. The harness, server and seed come from this script; each side's Metro serves its own app.",
+ ),
+);
+
+const compareCommand = Command.make(
+ "compare",
+ {
+ before: Argument.String("before").pipe(Argument.withDescription("Baseline JSON.")),
+ after: Argument.String("after").pipe(Argument.withDescription("Candidate JSON.")),
+ threshold: thresholdFlag,
+ floors: floorsFlag,
+ },
+ Effect.fn("mobileMetrics.compare")(function* (input) {
+ yield* report(
+ yield* readMetrics(input.before),
+ yield* readMetrics(input.after),
+ input.threshold,
+ yield* readFloors(input.floors),
+ );
+ }),
+).pipe(
+ Command.withDescription(
+ "Markdown table of two result files, gated like client-metrics: each app launch's median is one sample, and a metric counts only with 2+ launches a side when its bootstrap interval clears the threshold and floor. Exits 1 on a regression.",
+ ),
+);
+
+const noiseCommand = Command.make(
+ "noise",
+ {
+ dirs: Argument.String("dir").pipe(
+ Argument.withDescription("An `ab` out dir of one checkout against itself."),
+ Argument.atLeast(1),
+ ),
+ out: Flag.String("out").pipe(Flag.withDescription("Floors file to write."), Flag.optional),
+ },
+ Effect.fn("mobileMetrics.noise")(function* (input) {
+ const fs = yield* FileSystem.FileSystem;
+ const pairs = yield* Effect.forEach(input.dirs, (dir) =>
+ Effect.gen(function* () {
+ const a = yield* readMetrics(NodePath.join(dir, "a.json"));
+ const b = yield* readMetrics(NodePath.join(dir, "b.json"));
+ const settings = workloadDifferences(a, b, [...WORKLOAD_KEYS, ...PROBE_KEYS]).differ;
+ if (a.meta.commit !== b.meta.commit || settings.length > 0)
+ return yield* new MetricsError({
+ message: `${dir}: floors need one commit against itself with one set of settings`,
+ });
+ return [flatten(a), flatten(b)] as const;
+ }),
+ );
+ const { floors, table } = noiseOfSeries(pairs, "ios-simulator");
+ yield* Console.log(table);
+ if (Option.isSome(input.out))
+ yield* fs.writeFileString(input.out.value, `${yield* encodeFloors(floors)}\n`);
+ }),
+).pipe(Command.withDescription("Each metric's A/A spread and a floor for `compare --floors`."));
+
+const summaryCommand = Command.make(
+ "summary",
+ { file: Argument.String("file").pipe(Argument.withDescription("A result JSON.")) },
+ Effect.fn("mobileMetrics.summary")(function* (input) {
+ yield* Console.log(summaryTable(yield* readMetrics(input.file)));
+ }),
+).pipe(Command.withDescription("Print a result file's tables."));
+
+const command = Command.make("mobile-metrics").pipe(
+ Command.withDescription(
+ `Measure the iOS app on a Simlock simulator with mobile:behavior's server, Metro and behavior probe. Needs SIMLOCK_AGENT_DEVICE_URL and AGENT_DEVICE_DAEMON_AUTH_TOKEN.
+
+Cases (real taps, swipes and typing through agent-device):
+ switch-short, switch-long Tap a Home row: tap to the frame showing the thread's rows.
+ switch-working A thread streaming a reply, opened twice; each round starts and stops its own.
+ tabs PRs, Usage, then Chats in the tab bar.
+ pull-request The PR list, then the branch PR (40 files, long body, comments; fake GitHub).
+ issues The issues list, which shares the PR tab's slot.
+ diff A thread's git menu, then Review changes on the 40-file branch.
+ side-chat A thread's side chat chip.
+ type Keys typed into a composer, each to its next JS frame.
+ scroll-long Drag up through the long timeline: JS and UI frame drops.
+
+\`--build dev\` (the default) runs the development bundle: render and commit counts and A/B
+differences are representative, absolute times and heap growth are not. \`--build release\` runs
+the production bundle as Hermes bytecode: real times and a flat heap, but no commit ms, no
+\`--renders\`, and minified component names in soak retention. Soak in release. Trust a change
+only from \`ab\` on one simulator model and build.`,
+ ),
+ Command.withSubcommands([runCommand, abCommand, compareCommand, noiseCommand, summaryCommand]),
+);
+
+if (import.meta.main) {
+ Command.run(command, { version: "0.0.0" }).pipe(
+ Effect.provide([NodeServices.layer, NodeCrypto.layer]),
+ Effect.catchTags({
+ MetricsError: (error) =>
+ Console.error(`mobile-metrics: ${error.message}`).pipe(
+ Effect.andThen(
+ Effect.sync(() => {
+ process.exitCode = 1;
+ }),
+ ),
+ ),
+ }),
+ NodeRuntime.runMain,
+ );
+}
diff --git a/scripts/mobile-metrics/cases.ts b/scripts/mobile-metrics/cases.ts
new file mode 100644
index 0000000000000..5868a15d2c036
--- /dev/null
+++ b/scripts/mobile-metrics/cases.ts
@@ -0,0 +1,365 @@
+// @effect-diagnostics globalDate:off globalJsonInEffect:off - probe windows are wall-clock; the probe types its own JSON.
+/**
+ * mobile:metrics' interactions. Each measured step opens a probe window, makes one real tap,
+ * swipe or typed string through agent-device, waits until the app is quiet, and reads the window.
+ */
+import type { ThreadId } from "@t3tools/contracts";
+import * as Clock from "effect/Clock";
+import type * as SecureRandom from "effect/crypto/SecureRandom";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+
+import type { AxNode, Device, ProbeState } from "../mobile-behavior/device.ts";
+import type { Session } from "../mobile-behavior/session.ts";
+import { stepOf, type PerfWindow, type Step } from "./report.ts";
+
+export class CaseFailure extends Schema.TaggedError()("CaseFailure", {
+ message: Schema.String,
+}) {}
+
+/** Threads the seed creates, by the title their Home row shows. */
+export interface Fixtures {
+ readonly short: { readonly id: ThreadId; readonly title: string };
+ readonly long: { readonly id: ThreadId; readonly title: string };
+ /** A side chat of the short thread. */
+ readonly sideChat: { readonly id: ThreadId; readonly title: string };
+}
+
+export interface CaseContext {
+ readonly session: Session;
+ readonly device: Device;
+ readonly fixtures: Fixtures;
+ readonly round: number;
+ /** Threads opened so far in this app launch, for first visit versus revisit. */
+ readonly visited: Set;
+}
+
+/** How long the app must stay without input, commits or new content to end a step. */
+const QUIET_MS = 1_000;
+/** A working thread commits on every streamed chunk, so its steps end this long after content. */
+const AFTER_CONTENT_MS = 1_200;
+const STEP_TIMEOUT_MS = 15_000;
+
+const Peek = Schema.fromJsonString(
+ Schema.Struct({
+ now: Schema.Number,
+ last: Schema.Number,
+ inputs: Schema.Number,
+ content: Schema.Array(Schema.String),
+ }),
+);
+const decodePeek = Schema.decodeUnknownEffect(Peek);
+
+/** Runs `act` inside a probe window and returns what it measured. */
+const measure = Effect.fn("metrics.measure")(function* (
+ ctx: CaseContext,
+ step: Pick,
+ act: Effect.Effect,
+ options: { readonly thread?: string } = {},
+) {
+ const { device } = ctx;
+ yield* device.evaluate("__t3Behavior.perfStart()");
+ const acted = yield* Effect.result(act);
+ const deadline = (yield* Clock.currentTimeMillis) + STEP_TIMEOUT_MS;
+ let contentSince: number | null = null;
+ while (acted._tag === "Success" && (yield* Clock.currentTimeMillis) < deadline) {
+ const peek = yield* device.evaluate("__t3Behavior.perfPeek()").pipe(
+ Effect.flatMap((value) => decodePeek(value)),
+ Effect.orElseSucceed(() => null),
+ );
+ if (peek) {
+ const shown = options.thread
+ ? peek.content.some((thread) => thread.endsWith(options.thread!))
+ : true;
+ if (shown && options.thread) contentSince ??= peek.now;
+ const quiet = peek.inputs > 0 && peek.now - peek.last > QUIET_MS;
+ if (shown && (quiet || (contentSince !== null && peek.now - contentSince > AFTER_CONTENT_MS)))
+ break;
+ }
+ yield* Effect.sleep("250 millis");
+ }
+ const window = JSON.parse(
+ String(yield* device.evaluate("__t3Behavior.perfStop()")),
+ ) as PerfWindow;
+ if (acted._tag === "Failure")
+ return yield* new CaseFailure({
+ message: `${step.case} ${step.step}: ${acted.failure.message}`,
+ });
+ return stepOf(window, { ...step, round: ctx.round }, options.thread ?? null);
+});
+
+const isThread = (state: ProbeState, threadId: string) =>
+ state.route?.name === "Thread" && state.route.params.threadId === threadId;
+
+/** Back to Home's chat list, unmeasured: phones stack threads over it, and tabs share its route. */
+const toHome = Effect.fn("metrics.toHome")(function* (ctx: CaseContext) {
+ for (let attempt = 0; attempt < 4; attempt++) {
+ const state = yield* ctx.device.state;
+ if (state.route?.name === "Home") break;
+ // UIKit can report an unknown outcome while the pop animates; the next state read decides.
+ yield* ctx.device.back.pipe(Effect.ignore);
+ yield* Effect.sleep("800 millis");
+ }
+ yield* ctx.device.waitFor("Home", (state) => state.route?.name === "Home", 5_000);
+ yield* ctx.device.press('role=button label="Chats"').pipe(Effect.ignore);
+});
+
+/** Finds an on-screen node, skipping list containers that repeat a row's label. */
+const findNode = Effect.fn("metrics.findNode")(function* (
+ ctx: CaseContext,
+ description: string,
+ match: (label: string) => boolean,
+) {
+ for (let attempt = 0; attempt < 10; attempt++) {
+ const node = (yield* ctx.device.nodes).find(
+ (entry) => entry.label !== undefined && entry.kind !== "scroll-area" && match(entry.label),
+ ) as (AxNode & { readonly ref?: string }) | undefined;
+ if (node?.ref) return `@${node.ref}`;
+ if (node?.label) return `label="${node.label}"`;
+ yield* Effect.sleep("500 millis");
+ }
+ return yield* new CaseFailure({ message: `No ${description} on screen.` });
+});
+
+/** Taps the shared PR/issues list switcher by the centre of its labelled view. */
+const pressSwitcher = Effect.fn("metrics.pressSwitcher")(function* (
+ ctx: CaseContext,
+ label: string,
+) {
+ for (let attempt = 0; attempt < 10; attempt++) {
+ const node = (yield* ctx.device.nodes).find((entry) => entry.label === label && entry.rect);
+ if (node) {
+ const { x, y } = ctx.device.center(node);
+ return yield* ctx.device.pressAt(x, y);
+ }
+ yield* Effect.sleep("500 millis");
+ }
+ return yield* new CaseFailure({ message: `No "${label}" on screen.` });
+});
+
+/** A Home row's label is its title and status, e.g. "Bench short, Done". */
+const isRow = (label: string | undefined, title: string) =>
+ label === title || label?.startsWith(`${title}, `) === true;
+
+/** Waits for a Home row and returns its selector, opening the Working shelf if the row folded into it. */
+const waitForRow = Effect.fn("metrics.waitForRow")(function* (ctx: CaseContext, title: string) {
+ for (let attempt = 0; attempt < 20; attempt++) {
+ const nodes = yield* ctx.device.nodes;
+ const row = nodes.find((node) => isRow(node.label, title)) as
+ | (AxNode & { readonly ref?: string })
+ | undefined;
+ // The label ends in a relative time ("Bench short, 4m") that can tick before the press.
+ if (row?.ref) return `@${row.ref}`;
+ if (row?.label) return `label="${row.label}"`;
+ const shelf = nodes.find((node) => /^\d+ working threads?$/.test(node.label ?? ""));
+ if (shelf?.label && attempt % 4 === 1) yield* ctx.device.press(`label="${shelf.label}"`);
+ yield* Effect.sleep("500 millis");
+ }
+ return yield* new CaseFailure({ message: `Row "${title}" never appeared on Home.` });
+});
+
+/** Opens a thread by tapping its Home row, measured from the tap to its rows on screen. */
+const openFromHome = Effect.fn("metrics.openFromHome")(function* (
+ ctx: CaseContext,
+ name: string,
+ thread: { readonly id: ThreadId; readonly title: string },
+) {
+ yield* toHome(ctx);
+ const row = yield* waitForRow(ctx, thread.title);
+ const visit = ctx.visited.has(thread.id) ? "revisit" : "first";
+ ctx.visited.add(thread.id);
+ const step = yield* measure(ctx, { case: name, step: "open", visit }, ctx.device.press(row), {
+ thread: thread.id,
+ });
+ yield* ctx.device.waitFor("the tapped thread", (state) => isThread(state, thread.id), 10_000);
+ return step;
+});
+
+const switchTo = (name: "short" | "long") =>
+ Effect.fn(`metrics.switch.${name}`)(function* (ctx: CaseContext) {
+ return [yield* openFromHome(ctx, `switch-${name}`, ctx.fixtures[name])];
+ });
+
+/** Opens a thread, unmeasured, and waits for its feed. */
+const openThread = Effect.fn("metrics.openThread")(function* (
+ ctx: CaseContext,
+ thread: Fixtures[keyof Fixtures],
+) {
+ yield* toHome(ctx);
+ yield* ctx.device.press(yield* waitForRow(ctx, thread.title));
+ ctx.visited.add(thread.id);
+ yield* ctx.device.waitFor(
+ "the thread's feed",
+ (state) => isThread(state, thread.id) && state.feed?.ready === true,
+ 20_000,
+ );
+ yield* Effect.sleep("1 second");
+});
+
+const TYPED = "check the helpers";
+
+type CaseRun = (
+ ctx: CaseContext,
+) => Effect.Effect, { readonly message: string }, SecureRandom.SecureRandom>;
+
+export const CASES = {
+ "switch-short": switchTo("short"),
+ "switch-long": switchTo("long"),
+ /**
+ * A thread streaming a reply, opened twice. Each round starts its own and stops it after, since a
+ * stream anywhere keeps Home committing and no other step would ever go quiet.
+ */
+ "switch-working": Effect.fn("metrics.switch.working")(function* (ctx: CaseContext) {
+ const title = `Bench working ${ctx.round}`;
+ const id = yield* ctx.session.env.launch(title, "Write the report. [[eval:stream:3000:120]]");
+ const thread = { id, title };
+ return yield* Effect.gen(function* () {
+ yield* waitForRow(ctx, `${title}, Working`).pipe(Effect.ignore);
+ return [
+ yield* openFromHome(ctx, "switch-working", thread),
+ yield* openFromHome(ctx, "switch-working", thread),
+ ];
+ }).pipe(Effect.ensuring(ctx.session.env.interruptAll().pipe(Effect.ignore)));
+ }),
+
+ /** The tab bar: pull requests, usage, then back to chats. */
+ tabs: Effect.fn("metrics.tabs")(function* (ctx: CaseContext) {
+ yield* toHome(ctx);
+ const steps: Step[] = [];
+ for (const [step, label] of [
+ ["pulls", "PRs"],
+ ["usage", "Usage"],
+ ["chats", "Chats"],
+ ] as const) {
+ steps.push(
+ yield* measure(
+ ctx,
+ { case: "tabs", step, visit: "step" },
+ ctx.device.press(`role=button label="${label}"`),
+ ),
+ );
+ }
+ return steps;
+ }),
+
+ /** The pull request list, then the branch's pull request with its body, files and comments. */
+ "pull-request": Effect.fn("metrics.pullRequest")(function* (ctx: CaseContext) {
+ yield* toHome(ctx);
+ const steps: Step[] = [];
+ steps.push(
+ yield* measure(
+ ctx,
+ { case: "pull-request", step: "list", visit: "step" },
+ ctx.device.press('role=button label="PRs"'),
+ ),
+ );
+ const row = yield* findNode(ctx, "pull request row", (label) =>
+ label.includes("Bench change 1"),
+ );
+ steps.push(
+ yield* measure(
+ ctx,
+ { case: "pull-request", step: "details", visit: "step" },
+ ctx.device.press(row),
+ ),
+ );
+ yield* ctx.device.back;
+ yield* Effect.sleep("800 millis");
+ yield* ctx.device.press('role=button label="Chats"');
+ return steps;
+ }),
+
+ /** The issues list, which shares the pull requests' tab slot through the list switcher. */
+ issues: Effect.fn("metrics.issues")(function* (ctx: CaseContext) {
+ yield* toHome(ctx);
+ yield* ctx.device.press('role=button label="PRs"');
+ // The header title (SharedSlotTitle) is a menu trigger whose whole area belongs to its child
+ // views, so agent-device will not tap it by ref; tap its centre instead.
+ yield* pressSwitcher(ctx, "Pull requests, switch list");
+ const target = yield* findNode(ctx, "Issues menu item", (label) => label === "Issues");
+ const step = yield* measure(
+ ctx,
+ { case: "issues", step: "list", visit: "step" },
+ ctx.device.press(target),
+ );
+ // Hand the slot back, so the pull request case finds its tab.
+ yield* pressSwitcher(ctx, "Issues, switch list");
+ yield* ctx.device.press(
+ yield* findNode(ctx, "Pull requests menu item", (label) => label === "Pull requests"),
+ );
+ return [step];
+ }),
+
+ /** The thread on the 40-file branch: its git menu, then Review changes. */
+ diff: Effect.fn("metrics.diff")(function* (ctx: CaseContext) {
+ yield* openThread(ctx, ctx.fixtures.short);
+ const git = yield* findNode(ctx, "Git controls menu", (label) => label === "Git controls");
+ yield* ctx.device.press(git);
+ const review = yield* findNode(ctx, "Review changes item", (label) =>
+ label.startsWith("Review changes"),
+ );
+ const step = yield* measure(
+ ctx,
+ { case: "diff", step: "review", visit: "step" },
+ ctx.device.press(review),
+ );
+ yield* ctx.device.back.pipe(Effect.ignore);
+ return [step];
+ }),
+
+ /** From the short thread, its side chat's chip: tap to the side chat's rows. */
+ "side-chat": Effect.fn("metrics.sideChat")(function* (ctx: CaseContext) {
+ yield* openThread(ctx, ctx.fixtures.short);
+ const chat = ctx.fixtures.sideChat;
+ const visit = ctx.visited.has(chat.id) ? "revisit" : "first";
+ ctx.visited.add(chat.id);
+ const step = yield* measure(
+ ctx,
+ { case: "side-chat", step: "open", visit },
+ ctx.device.press(
+ yield* findNode(ctx, "side chat chip", (label) =>
+ label.startsWith(`Open side chat ${chat.title}`),
+ ),
+ ),
+ { thread: chat.id },
+ );
+ return [step];
+ }),
+
+ /** Keys typed into a short thread's composer, each to its next JS frame. */
+ type: Effect.fn("metrics.type")(function* (ctx: CaseContext) {
+ yield* openThread(ctx, ctx.fixtures.short);
+ const editor = (yield* ctx.device.nodes).find(
+ (node) => node.kind === "text-view" && node.editable === true,
+ );
+ if (!editor?.rect) return yield* new CaseFailure({ message: "No composer on screen." });
+ const { x, y } = ctx.device.center(editor);
+ yield* ctx.device.pressAt(x, y);
+ yield* ctx.device.waitFor("the keyboard", (state) => state.composer.keyboard, 10_000);
+ yield* Effect.sleep("1 second");
+ const step = yield* measure(
+ ctx,
+ { case: "type", step: "keys", visit: "step" },
+ ctx.device.type(TYPED),
+ );
+ // Clear the draft so the next round types into the same empty composer.
+ yield* ctx.device.run(["fill", String(x), String(y), ""]).pipe(Effect.ignore);
+ yield* ctx.device.run(["keyboard", "dismiss"]).pipe(Effect.ignore);
+ return [step];
+ }),
+
+ /** Drags the long timeline up through history: frames while the list lays out older rows. */
+ "scroll-long": Effect.fn("metrics.scrollLong")(function* (ctx: CaseContext) {
+ yield* openThread(ctx, ctx.fixtures.long);
+ const root = (yield* ctx.device.nodes)[0]?.rect ?? { x: 0, y: 0, width: 400, height: 870 };
+ const x = Math.round(root.width / 2);
+ const drag = Effect.gen(function* () {
+ for (let swipe = 0; swipe < 4; swipe++)
+ yield* ctx.device.swipe(x, Math.round(root.height * 0.3), Math.round(root.height * 0.8));
+ });
+ return [yield* measure(ctx, { case: "scroll-long", step: "drag-up", visit: "step" }, drag)];
+ }),
+} satisfies Record;
+
+export type CaseName = keyof typeof CASES;
+export const CASE_NAMES = Object.keys(CASES) as ReadonlyArray;
diff --git a/scripts/mobile-metrics/report.test.ts b/scripts/mobile-metrics/report.test.ts
new file mode 100644
index 0000000000000..92f47a5b203c8
--- /dev/null
+++ b/scripts/mobile-metrics/report.test.ts
@@ -0,0 +1,120 @@
+import { expect, it } from "@effect/vitest";
+
+import {
+ flatten,
+ soakCaseDeltas,
+ soakGrowth,
+ stepOf,
+ type MobileMetrics,
+ type PerfWindow,
+} from "./report.ts";
+
+const frames = (from: number, count: number, gap = 1000 / 60) =>
+ Array.from({ length: count }, (_, index) => from + index * gap);
+
+const window = (overrides: Partial): PerfWindow => ({
+ startedAt: 0,
+ inputs: [],
+ commits: [],
+ content: [],
+ keys: [],
+ js: [],
+ ui: [],
+ renders: null,
+ heapBytes: null,
+ ...overrides,
+});
+
+it("times a tap from its touch end, and counts only what happened after it", () => {
+ const step = stepOf(
+ window({
+ inputs: [
+ { kind: "touch-start", at: 100 },
+ { kind: "touch-end", at: 180 },
+ ],
+ // The first commit is the harness's own perfStart call, before the tap.
+ commits: [
+ { at: 50, ms: 9 },
+ { at: 260, ms: 30 },
+ { at: 420, ms: 12 },
+ ],
+ content: [
+ { thread: "env:other", at: 200, frameAt: 210 },
+ { thread: "env:target", at: 400, frameAt: 415 },
+ ],
+ js: frames(0, 60),
+ }),
+ { case: "switch-long", step: "open", visit: "first", round: 1 },
+ "target",
+ );
+ expect(step).toMatchObject({ contentMs: 235, settledMs: 240, commits: 2, commitMs: 42 });
+});
+
+it("measures typing from the first key, and reports no content without a target", () => {
+ const step = stepOf(
+ window({
+ inputs: [
+ { kind: "key", at: 1000 },
+ { kind: "key", at: 1100 },
+ ],
+ commits: [{ at: 1010, ms: 4 }],
+ keys: [20, 12, 16],
+ }),
+ { case: "type", step: "keys", visit: "step", round: 1 },
+ null,
+ );
+ expect(step).toMatchObject({ contentMs: null, settledMs: 10, keyP50Ms: 16, keyP90Ms: 20 });
+});
+
+it("takes each run's median as one sample, so steps of one launch never pass for runs", () => {
+ const step = (contentMs: number) =>
+ stepOf(
+ window({
+ inputs: [{ kind: "touch-end", at: 0 }],
+ content: [{ thread: "t", at: contentMs, frameAt: contentMs }],
+ }),
+ { case: "switch-short", step: "open", visit: "revisit", round: 1 },
+ "t",
+ );
+ const metrics: MobileMetrics = {
+ meta: {},
+ runs: [
+ { steps: [step(100), step(300), step(200)], memory: [] },
+ { steps: [step(400)], memory: [{ label: "launch", heapMB: 80, processMB: null }] },
+ ],
+ };
+ const flat = flatten(metrics);
+ expect(flat.get("switch-short.open.revisit.contentMs")).toEqual([200, 400]);
+ expect(flat.get("memory.launch.heapMB")).toEqual([80]);
+ expect(flat.has("memory.launch.processMB")).toBe(false);
+});
+
+it("times a native menu item from its JS handler, since the tap never reaches JS as a touch", () => {
+ const step = stepOf(
+ window({
+ inputs: [{ kind: "menu-action", at: 500 }],
+ commits: [
+ { at: 520, ms: 10 },
+ { at: 700, ms: 40 },
+ ],
+ }),
+ { case: "diff", step: "review", visit: "step", round: 1 },
+ null,
+ );
+ expect(step).toMatchObject({ settledMs: 200, commits: 2 });
+});
+
+it("fits soak growth past warm-up per iteration, and names the case that grew the heap", () => {
+ const samples = [
+ { iteration: 0, case: "start", heapMB: 90, processMB: null },
+ // Warm-up: the first iteration loads code and caches.
+ { iteration: 1, case: "a", heapMB: 140, processMB: null },
+ { iteration: 1, case: "b", heapMB: 150, processMB: null },
+ { iteration: 2, case: "a", heapMB: 150, processMB: null },
+ { iteration: 2, case: "b", heapMB: 152, processMB: null },
+ { iteration: 3, case: "a", heapMB: 152, processMB: null },
+ { iteration: 3, case: "b", heapMB: 154, processMB: null },
+ ];
+ expect(soakGrowth(samples)).toMatchObject({ heapMB: 2 });
+ expect(soakCaseDeltas(samples).find((entry) => entry.case === "b")?.medianMB).toBe(2);
+});
diff --git a/scripts/mobile-metrics/report.ts b/scripts/mobile-metrics/report.ts
new file mode 100644
index 0000000000000..386d7bcdc28e4
--- /dev/null
+++ b/scripts/mobile-metrics/report.ts
@@ -0,0 +1,373 @@
+// The pure half of scripts/mobile-metrics.ts: what one probe window measured, the JSON a run
+// writes, its tables, and the series `compare` and `noise` share with client-metrics.
+import * as Schema from "effect/Schema";
+
+import { median, percentile, slope, topCounts } from "../client-metrics-report.ts";
+import { frameStats } from "../mobile-behavior/grade.ts";
+import { MachineState, round } from "../server-metrics-report.ts";
+
+/** One perf window as the probe's `perfStop` returns it (see behavior-probe.ts). */
+export interface PerfWindow {
+ readonly startedAt: number;
+ readonly inputs: ReadonlyArray<{ readonly kind: string; readonly at: number }>;
+ readonly commits: ReadonlyArray<{ readonly at: number; readonly ms: number }>;
+ readonly content: ReadonlyArray<{
+ readonly thread: string;
+ readonly at: number;
+ readonly frameAt: number | null;
+ }>;
+ readonly keys: ReadonlyArray;
+ readonly js: ReadonlyArray;
+ readonly ui: ReadonlyArray;
+ readonly renders: {
+ readonly commits: number;
+ readonly totalRenders: number;
+ readonly components: ReadonlyArray<{ readonly key: string; readonly count: number }>;
+ readonly causes: ReadonlyArray<{ readonly key: string; readonly count: number }>;
+ } | null;
+ readonly heapBytes: number | null;
+}
+
+const Count = Schema.Struct({ name: Schema.String, count: Schema.Number });
+const Renders = Schema.Struct({
+ commits: Schema.Number,
+ renders: Schema.Number,
+ top: Schema.Array(Count),
+ causes: Schema.Array(Count),
+});
+
+const Step = Schema.Struct({
+ case: Schema.String,
+ step: Schema.String,
+ /** A thread's first open in this app launch, or a later one; other steps say `step`. */
+ visit: Schema.Literals(["first", "revisit", "step"]),
+ round: Schema.Number,
+ /** Input to the frame after the commit that showed the target thread's rows. */
+ contentMs: Schema.NullOr(Schema.Number),
+ /** Input to the last React commit before the app went quiet. */
+ settledMs: Schema.NullOr(Schema.Number),
+ commits: Schema.Number,
+ /** Render work React timed in those commits (development builds only). */
+ commitMs: Schema.Number,
+ jsDroppedPct: Schema.NullOr(Schema.Number),
+ jsMaxFrameMs: Schema.NullOr(Schema.Number),
+ uiDroppedPct: Schema.NullOr(Schema.Number),
+ uiMaxFrameMs: Schema.NullOr(Schema.Number),
+ /** Composer key to the next JS frame, for typing steps. */
+ keyP50Ms: Schema.NullOr(Schema.Number),
+ keyP90Ms: Schema.NullOr(Schema.Number),
+ renders: Schema.optional(Renders),
+});
+export type Step = typeof Step.Type;
+
+const Memory = Schema.Struct({
+ label: Schema.String,
+ /** Hermes heap after a collection. */
+ heapMB: Schema.NullOr(Schema.Number),
+ /** The app process's footprint from agent-device (`perf memory sample`). */
+ processMB: Schema.NullOr(Schema.Number),
+});
+export type Memory = typeof Memory.Type;
+
+/** Memory after each repeat of the switch cases (`--soak`). */
+const SoakSample = Schema.Struct({
+ iteration: Schema.Number,
+ /** The case that just ran; iteration 0 is the sample before the first. */
+ case: Schema.String,
+ heapMB: Schema.NullOr(Schema.Number),
+ processMB: Schema.NullOr(Schema.Number),
+});
+export type SoakSample = typeof SoakSample.Type;
+
+const Run = Schema.Struct({
+ steps: Schema.Array(Step),
+ memory: Schema.Array(Memory),
+ soak: Schema.optional(Schema.Array(SoakSample)),
+ skipped: Schema.optional(
+ Schema.Array(Schema.Struct({ case: Schema.String, reason: Schema.String })),
+ ),
+ machine: Schema.optional(MachineState),
+});
+export type Run = typeof Run.Type;
+
+export const MobileMetrics = Schema.Struct({
+ meta: Schema.Record(
+ Schema.String,
+ Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]),
+ ),
+ runs: Schema.Array(Run),
+});
+export type MobileMetrics = typeof MobileMetrics.Type;
+
+/** Settings that change what shared metrics measure. */
+export const WORKLOAD_KEYS = ["cases", "rounds", "longTurns", "device", "build"] as const;
+/** Settings that change timing without changing the workload. */
+export const PROBE_KEYS = ["renders"] as const;
+
+/**
+ * Where a tap's latency counts from: the first touch's end, or a native menu item's JS handler
+ * (a tap inside a native menu never reaches JS as a touch), else the touch's start.
+ */
+export function inputAt(window: Pick) {
+ const end = window.inputs.find(
+ (input) => input.kind === "touch-end" || input.kind === "menu-action",
+ );
+ return (end ?? window.inputs.find((input) => input.kind === "touch-start"))?.at ?? null;
+}
+
+/**
+ * One step's metrics from its window. `thread` names the thread whose rows count as content;
+ * commits before the input belong to the harness's own calls, so they are left out.
+ */
+export function stepOf(
+ window: PerfWindow,
+ step: Pick,
+ thread: string | null,
+): Step {
+ const keyed = window.keys.length > 0;
+ const from = keyed ? window.inputs.find((input) => input.kind === "key")?.at : inputAt(window);
+ const start = from ?? window.startedAt;
+ const commits = window.commits.filter((commit) => commit.at >= start);
+ const shown = thread
+ ? window.content.find((entry) => entry.thread.endsWith(thread) && entry.at >= start)
+ : undefined;
+ const since = (at: number | null | undefined) =>
+ from === undefined || from === null || at === null || at === undefined
+ ? null
+ : round(Math.max(0, at - from), 0);
+ const frames = (timestamps: ReadonlyArray, prefix: "js" | "ui") => {
+ const stats = frameStats(
+ timestamps.filter((at) => at >= start),
+ prefix,
+ );
+ const dropped = stats[`${prefix}DroppedPct`];
+ const max = stats[`${prefix}MaxMs`];
+ return {
+ dropped: typeof dropped === "number" ? dropped : null,
+ max: typeof max === "number" ? max : null,
+ };
+ };
+ const js = frames(window.js, "js");
+ const ui = frames(window.ui, "ui");
+ const keys = window.keys.toSorted((a, b) => a - b);
+ return {
+ ...step,
+ contentMs: since(shown?.frameAt),
+ settledMs: since(commits.at(-1)?.at),
+ commits: commits.length,
+ commitMs: round(
+ commits.reduce((sum, commit) => sum + commit.ms, 0),
+ 0,
+ ),
+ jsDroppedPct: js.dropped,
+ jsMaxFrameMs: js.max,
+ uiDroppedPct: ui.dropped,
+ uiMaxFrameMs: ui.max,
+ keyP50Ms: keys.length ? round(median(keys)!, 1) : null,
+ keyP90Ms: keys.length ? round(percentile(keys, 90)!, 1) : null,
+ ...(window.renders
+ ? {
+ renders: {
+ commits: window.renders.commits,
+ renders: window.renders.totalRenders,
+ top: window.renders.components
+ .slice(0, 8)
+ .map(({ key, count }) => ({ name: key, count })),
+ causes: window.renders.causes
+ .slice(0, 8)
+ .map(({ key, count }) => ({ name: key, count })),
+ },
+ }
+ : {}),
+ };
+}
+
+const NUMERIC = [
+ "contentMs",
+ "settledMs",
+ "commits",
+ "commitMs",
+ "jsDroppedPct",
+ "jsMaxFrameMs",
+ "uiDroppedPct",
+ "uiMaxFrameMs",
+ "keyP50Ms",
+ "keyP90Ms",
+] as const;
+
+/** Every compared metric, one value per run: the median of the run's samples of it. */
+export function flatten(metrics: MobileMetrics): Map {
+ const values = new Map();
+ for (const run of metrics.runs) {
+ const inRun = new Map();
+ const add = (key: string, value: number | null | undefined) => {
+ if (value === null || value === undefined || !Number.isFinite(value)) return;
+ inRun.set(key, [...(inRun.get(key) ?? []), value]);
+ };
+ for (const entry of run.steps) {
+ const key = `${entry.case}.${entry.step}${entry.visit === "step" ? "" : `.${entry.visit}`}`;
+ for (const field of NUMERIC) add(`${key}.${field}`, entry[field]);
+ add(`${key}.renders`, entry.renders?.renders);
+ }
+ for (const entry of run.memory) {
+ add(`memory.${entry.label}.heapMB`, entry.heapMB);
+ add(`memory.${entry.label}.processMB`, entry.processMB);
+ }
+ if (run.soak && run.soak.length > 2) {
+ const growth = soakGrowth(run.soak);
+ add("soak.heapMBPerIteration", growth.heapMB);
+ add("soak.processMBPerIteration", growth.processMB);
+ }
+ for (const [key, samples] of inRun)
+ values.set(key, [...(values.get(key) ?? []), median(samples)!]);
+ }
+ return values;
+}
+
+/** Growth per soak iteration past the first (warm-up) sample, and over the last half alone. */
+export function soakGrowth(samples: ReadonlyArray) {
+ const fit = (rows: ReadonlyArray, pick: (sample: SoakSample) => number | null) =>
+ slope(
+ rows.flatMap((sample) => {
+ const value = pick(sample);
+ return value === null ? [] : [[sample.iteration, value] as const];
+ }),
+ );
+ // One point per iteration: the sample after its last case.
+ const perIteration = [...new Map(samples.map((sample) => [sample.iteration, sample])).values()];
+ const settled = perIteration.slice(1);
+ const late = perIteration.slice(Math.floor(perIteration.length / 2));
+ return {
+ heapMB: fit(settled, (sample) => sample.heapMB),
+ processMB: fit(settled, (sample) => sample.processMB),
+ lateHeapMB: fit(late, (sample) => sample.heapMB),
+ perIteration,
+ };
+}
+
+/** Mean Hermes heap change across each case's runs in a soak: which steps grow it. */
+export function soakCaseDeltas(samples: ReadonlyArray) {
+ const deltas = new Map();
+ for (let index = 1; index < samples.length; index++) {
+ const before = samples[index - 1]!.heapMB;
+ const after = samples[index]!.heapMB;
+ if (before === null || after === null) continue;
+ const name = samples[index]!.case;
+ deltas.set(name, [...(deltas.get(name) ?? []), after - before]);
+ }
+ return [...deltas].map(([name, values]) => ({
+ case: name,
+ meanMB: values.reduce((sum, value) => sum + value, 0) / values.length,
+ medianMB: median(values)!,
+ }));
+}
+
+/** Settings two files disagree on, and those one of them did not record. */
+export function workloadDifferences(
+ before: MobileMetrics,
+ after: MobileMetrics,
+ keys: ReadonlyArray = WORKLOAD_KEYS,
+) {
+ const differ: string[] = [];
+ const unrecorded: string[] = [];
+ for (const key of keys) {
+ const a = before.meta[key];
+ const b = after.meta[key];
+ if (a === undefined || b === undefined) {
+ if (a !== b) unrecorded.push(key);
+ } else if (a !== b) differ.push(`${key} ${a} vs ${b}`);
+ }
+ return { differ, unrecorded };
+}
+
+const cell = (value: number | null | undefined, digits = 0) =>
+ value === null || value === undefined ? "–" : `${round(value, digits)}`;
+const present = (values: ReadonlyArray) =>
+ values.filter((value): value is number => value !== null);
+const listOf = (entries: ReadonlyArray<{ readonly name: string; readonly count: number }>) =>
+ entries.map((entry) => `${entry.name} ${entry.count}`).join(", ") || "–";
+
+/** The run's markdown: per step latency and frames, renders, memory. */
+export function summaryTable(metrics: MobileMetrics) {
+ const steps = metrics.runs.flatMap((run) => run.steps);
+ const lines = [
+ "### Mobile metrics (ms, lower is better)",
+ "",
+ `\`${metrics.meta.commit}\`, ${metrics.runs.length} run(s), ${metrics.meta.device}, ${metrics.meta.build} build`,
+ ];
+ const keys = [
+ ...new Set(steps.map((entry) => `${entry.case}\u0000${entry.step}\u0000${entry.visit}`)),
+ ];
+ if (keys.length > 0) {
+ lines.push(
+ "",
+ "| case | step | visit | n | content p50 | content p90 | settled p50 | settled p90 | commits p50 | commit ms p50 | JS dropped % p50 | JS max frame p50 | UI dropped % p50 | key p50 |",
+ "| :-- | :-- | :-- | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: |",
+ );
+ for (const key of keys) {
+ const [name, step, visit] = key.split("\u0000") as [string, string, string];
+ const rows = steps.filter(
+ (entry) => entry.case === name && entry.step === step && entry.visit === visit,
+ );
+ const pick = (field: (typeof NUMERIC)[number]) => present(rows.map((entry) => entry[field]));
+ lines.push(
+ `| ${name} | ${step} | ${visit === "step" ? "" : visit} | ${rows.length} | ${cell(median(pick("contentMs")))} | ${cell(percentile(pick("contentMs"), 90))} | ${cell(median(pick("settledMs")))} | ${cell(percentile(pick("settledMs"), 90))} | ${cell(median(pick("commits")))} | ${cell(median(pick("commitMs")))} | ${cell(median(pick("jsDroppedPct")), 1)} | ${cell(median(pick("jsMaxFrameMs")))} | ${cell(median(pick("uiDroppedPct")), 1)} | ${cell(median(pick("keyP50Ms")), 1)} |`,
+ );
+ }
+ }
+ const rendered = steps.filter((entry) => entry.renders !== undefined);
+ if (rendered.length > 0) {
+ lines.push(
+ "",
+ "| renders per step | n | renders p50 | top components (mean per step) | top causes |",
+ "| :-- | --: | --: | :-- | :-- |",
+ );
+ for (const key of new Set(rendered.map((entry) => `${entry.case}: ${entry.step}`))) {
+ const rows = rendered
+ .filter((entry) => `${entry.case}: ${entry.step}` === key)
+ .map((entry) => entry.renders!);
+ lines.push(
+ `| ${key} | ${rows.length} | ${cell(median(rows.map((entry) => entry.renders)))} | ${listOf(topCounts(rows.map((entry) => entry.top)))} | ${listOf(
+ topCounts(
+ rows.map((entry) => entry.causes),
+ 3,
+ ),
+ )} |`,
+ );
+ }
+ }
+ const memory = metrics.runs.flatMap((run) => run.memory);
+ if (memory.length > 0) {
+ lines.push("", "| memory | Hermes heap MB | process MB |", "| :-- | --: | --: |");
+ for (const label of new Set(memory.map((entry) => entry.label))) {
+ const rows = memory.filter((entry) => entry.label === label);
+ lines.push(
+ `| ${label} | ${cell(median(present(rows.map((entry) => entry.heapMB))), 1)} | ${cell(median(present(rows.map((entry) => entry.processMB))), 1)} |`,
+ );
+ }
+ }
+ metrics.runs.forEach((run, index) => {
+ if (!run.soak || run.soak.length < 3) return;
+ const growth = soakGrowth(run.soak);
+ lines.push(
+ "",
+ `| soak, run ${index + 1}: iteration | Hermes heap MB | process MB |`,
+ "| --: | --: | --: |",
+ ...growth.perIteration.map(
+ (sample) =>
+ `| ${sample.iteration} | ${cell(sample.heapMB, 1)} | ${cell(sample.processMB, 1)} |`,
+ ),
+ `| growth per iteration (after warm-up) | ${cell(growth.heapMB, 2)} | ${cell(growth.processMB, 2)} |`,
+ `| growth per iteration (last half) | ${cell(growth.lateHeapMB, 2)} | |`,
+ "",
+ "| soak case | heap change per run, mean MB | median MB |",
+ "| :-- | --: | --: |",
+ ...soakCaseDeltas(run.soak).map(
+ (entry) => `| ${entry.case} | ${cell(entry.meanMB, 2)} | ${cell(entry.medianMB, 2)} |`,
+ ),
+ );
+ });
+ for (const entry of metrics.runs.flatMap((run) => run.skipped ?? []))
+ lines.push("", `Not measured in a round, ${entry.case}: ${entry.reason}`);
+ return lines.join("\n");
+}
diff --git a/scripts/server-metrics-forge.ts b/scripts/server-metrics-forge.ts
index 1e462d5e169b5..bfdf2a356d2c8 100644
--- a/scripts/server-metrics-forge.ts
+++ b/scripts/server-metrics-forge.ts
@@ -509,6 +509,8 @@ export const serveFakeGitHub = Effect.fn("serverMetrics.serveFakeGitHub")(functi
});
proxy.on("connect", (request: NodeHttp.IncomingMessage, client: NodeNet.Socket) => {
if (request.url !== `${HOST}:443`) {
+ // A refused client may reset before the 403 lands; unhandled, that crashes the harness.
+ client.on("error", () => client.destroy());
client.end("HTTP/1.1 403 Forbidden\r\n\r\n");
return;
}