Skip to content

Commit 9b30776

Browse files
perf(mobile): Metro runs the React Compiler, with a coverage ratchet (pingdotgg#20967)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 16918b5 commit 9b30776

10 files changed

Lines changed: 330 additions & 22 deletions

File tree

‎apps/mobile/app.config.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,10 @@ const config: ExpoConfig = {
489489
},
490490
},
491491
owner: "pingdotgg",
492+
experiments: {
493+
// Metro only runs babel-plugin-react-compiler when this is set; see src/reactCompilerCoverage.test.ts.
494+
reactCompiler: true,
495+
},
492496
};
493497

494498
export default config;

‎apps/mobile/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@
140140
"uniwind": "1.12.1"
141141
},
142142
"devDependencies": {
143+
"@babel/core": "^7.29.7",
143144
"@effect/vitest": "catalog:",
144145
"@pierre/trees": "1.0.0-beta.6",
145146
"@types/mdast": "^4.0.4",

‎apps/mobile/src/Stack.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -669,7 +669,9 @@ function NotFoundScreen() {
669669

670670
const RootStackConfig = createWorkspaceStackNavigator({
671671
initialRouteName: "Home",
672-
layout: RootStackLayout,
672+
// React Navigation calls layouts as plain functions inside its own render. Passing a
673+
// compiled component directly would put its memo cache among the navigator's hooks.
674+
layout: (props) => <RootStackLayout {...props} />,
673675
screenOptions: {
674676
headerShown: false,
675677
},
@@ -1012,7 +1014,7 @@ export const RootStack = RootStackConfig.with(function AdaptiveRootStack({ Navig
10121014

10131015
return (
10141016
<Navigator
1015-
screenLayout={GuardedScreenLayout}
1017+
screenLayout={(props) => <GuardedScreenLayout {...props} />}
10161018
screenOptions={({ route }) => {
10171019
if (route.name !== "SettingsSheet" && route.name !== "NewTaskSheet") {
10181020
return {};

‎apps/mobile/src/features/threads/thread-list-v2-items.tsx‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -605,21 +605,28 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
605605
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
606606

607607
const canUnsettle = variant === "slim";
608-
const [snoozeGateTick, bumpSnoozeGateTick] = useState(0);
608+
// The React Compiler caches render results on props and state, so a clock read
609+
// in render would stay frozen until `thread` changes: the gate could never
610+
// expire and its timer would re-fire every 50ms. The gate's clock is state.
611+
const [snoozeGateClock, setSnoozeGateClock] = useState(() => ({ thread, now: Date.now() }));
612+
if (snoozeGateClock.thread !== thread) setSnoozeGateClock({ thread, now: Date.now() });
613+
const snoozeGateNow = new Date(snoozeGateClock.now).toISOString();
609614
const snoozeGateExpiryMs = props.snoozeSupported
610-
? resolveThreadListV2SnoozeGateExpiryMs(thread, { now: new Date().toISOString() })
615+
? resolveThreadListV2SnoozeGateExpiryMs(thread, { now: snoozeGateNow })
611616
: null;
612617
useEffect(() => {
613-
if (snoozeGateExpiryMs === null) return;
614-
const delayMs = Math.min(Math.max(0, snoozeGateExpiryMs - Date.now()) + 50, 2_147_483_647);
615-
const id = setTimeout(() => bumpSnoozeGateTick((tick) => tick + 1), delayMs);
618+
// A gate still closed past its expiry is held by runtime status, not time,
619+
// so no clock tick can open it.
620+
if (snoozeGateExpiryMs === null || snoozeGateExpiryMs <= snoozeGateClock.now) return;
621+
const delayMs = Math.min(snoozeGateExpiryMs - Date.now() + 50, 2_147_483_647);
622+
const id = setTimeout(() => setSnoozeGateClock({ thread, now: Date.now() }), delayMs);
616623
return () => clearTimeout(id);
617-
}, [snoozeGateExpiryMs, snoozeGateTick]);
624+
}, [snoozeGateExpiryMs, snoozeGateClock.now, thread]);
618625
const swipeActions = resolveThreadListV2SwipeActions({
619626
variant,
620627
settlementSupported: props.settlementSupported,
621628
snoozeSupported: props.snoozeSupported,
622-
snoozable: canSnooze(thread, { now: new Date().toISOString() }),
629+
snoozable: canSnooze(thread, { now: snoozeGateNow }),
623630
snoozed: snoozedRow,
624631
});
625632
const snoozePresets = useMemo(
Lines changed: 226 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,226 @@
1+
// @effect-diagnostics nodeBuiltinImport:off - compiles real source files on disk.
2+
import * as NodeFS from "node:fs";
3+
import * as NodeModule from "node:module";
4+
import * as NodePath from "node:path";
5+
import { describe, expect, it } from "vite-plus/test";
6+
7+
const mobileRoot = NodePath.resolve(__dirname, "..");
8+
const requireFromMobile = NodeModule.createRequire(NodePath.join(mobileRoot, "package.json"));
9+
const babel: {
10+
transformFileSync: (file: string, options: Record<string, unknown>) => unknown;
11+
} = requireFromMobile("@babel/core");
12+
const metroConfig: Promise<{ transformer: { babelTransformerPath: string } }> =
13+
requireFromMobile("./metro.config.js");
14+
15+
// Files the compiler skips today. A skipped file still ships, just unmemoized.
16+
// This list only shrinks: the test fails when a file here starts compiling, so
17+
// delete its entry (and its manual useMemo/useCallback/memo) in the same change.
18+
const KNOWN_BAILOUTS: Record<string, string> = {
19+
"src/components/ComposerAttachmentStrip.tsx": "unsupported syntax",
20+
"src/components/ComposerContextAttachment.tsx":
21+
"throw inside try, try without catch, try/finally",
22+
"src/components/ComposerEditor.tsx": "try/finally",
23+
"src/components/VideoPreviewModal.ios.tsx": "try without catch",
24+
"src/components/VideoPreviewModal.tsx": "ref read during render",
25+
"src/components/ui/AndroidAnchoredMenu.tsx": "ref read during render",
26+
"src/components/ui/Menu.tsx": "ref read during render",
27+
"src/components/ui/OverlayPortal.tsx": "unsupported syntax",
28+
"src/features/cloud/ConnectOnboardingRouteScreen.tsx": "try without catch",
29+
"src/features/connection/ConnectionsNewRouteScreen.tsx": "try without catch",
30+
"src/features/devices/DevicePreviewRouteScreen.tsx": "try without catch",
31+
"src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render",
32+
"src/features/files/AttachmentFileScreen.tsx": "manual memo not preserved",
33+
"src/features/files/FileMarkdownPreview.tsx": "try without catch",
34+
"src/features/files/FileTreeBrowser.tsx": "ref read during render",
35+
"src/features/files/SourceFileSurface.tsx": "try without catch",
36+
"src/features/files/ThreadFilesRouteScreen.tsx": "manual memo not preserved",
37+
"src/features/files/useFileTreeEntries.ts": "manual memo not preserved",
38+
"src/features/home/HomeScreen.tsx": "ref read during render",
39+
"src/features/home/WorkspaceConnectionTitle.tsx": "ref read during render",
40+
"src/features/home/home-list-options.ts": "manual memo not preserved",
41+
"src/features/home/thread-swipe-actions.tsx": "ref read during render",
42+
"src/features/home/useThreadListActions.ts": "try without catch",
43+
"src/features/layout/AdaptiveWorkspaceLayout.tsx": "ref read during render",
44+
"src/features/layout/workspace-inspector-pane.tsx": "mutates a frozen value",
45+
"src/features/layout/workspace-pane-divider.tsx": "ref read during render",
46+
"src/features/projects/AddProjectScreen.tsx": "try without catch",
47+
"src/features/pull-requests/PullRequestDiscussionScreen.tsx": "try/finally",
48+
"src/features/pull-requests/PullRequestInlineCommentScreen.tsx": "try without catch",
49+
"src/features/pull-requests/PullRequestMergeControls.tsx": "throw inside try, try/finally",
50+
"src/features/pull-requests/PullRequestReviewSheet.tsx": "try/finally",
51+
"src/features/pull-requests/PullRequestReviewersScreen.tsx": "throw inside try, try/finally",
52+
"src/features/pull-requests/PullRequestRouteScreen.tsx": "manual memo not preserved",
53+
"src/features/pull-requests/guide/PullRequestGuideScreen.tsx": "conditional inside try",
54+
"src/features/pull-requests/guide/ReviewGuideExcerpt.tsx": "conditional inside try",
55+
"src/features/pull-requests/guide/useReviewGuide.ts": "try without catch",
56+
"src/features/pull-requests/usePullRequestAction.ts": "throw inside try, try/finally",
57+
"src/features/pull-requests/usePullRequestListActions.ts": "throw inside try, try/finally",
58+
"src/features/pull-requests/usePullRequestListControls.ts": "unsupported syntax",
59+
"src/features/pull-requests/usePullRequestThreads.ts": "throw inside try, try/finally",
60+
"src/features/review/ReviewSheet.tsx": "try without catch",
61+
"src/features/review/reviewDiffRendering.tsx": "mutates a frozen value",
62+
"src/features/review/useNativeReviewDiffHighlighting.ts": "conditional inside try",
63+
"src/features/settings/SettingsAboutRouteScreen.tsx": "try without catch",
64+
"src/features/settings/SettingsAuthRouteScreen.tsx": "ref read during render",
65+
"src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx":
66+
"try without catch, try/finally",
67+
"src/features/settings/SettingsEnvironmentsRouteScreen.tsx": "try without catch",
68+
"src/features/settings/SettingsNotificationsRouteScreen.tsx": "try without catch",
69+
"src/features/settings/SettingsProjectOverviewRouteScreen.tsx": "try without catch",
70+
"src/features/settings/SettingsProviderAccountsRouteScreen.tsx": "conditional inside try",
71+
"src/features/settings/SettingsScheduledTasksRouteScreen.tsx": "unsupported syntax",
72+
"src/features/settings/components/SettingsDragHandle.tsx": "ref read during render",
73+
"src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
74+
"src/features/threads/NewTaskContextPickerScreens.tsx":
75+
"manual memo not preserved, try without catch",
76+
"src/features/threads/NewTaskDraftScreen.tsx": "try/finally",
77+
"src/features/threads/NewTaskRouteScreen.tsx": "try without catch",
78+
"src/features/threads/PendingUserInputCard.tsx": "mutates a frozen value",
79+
"src/features/threads/QuestionAttachments.tsx": "try/finally",
80+
"src/features/threads/ThreadArrangementSheet.tsx": "ref read during render",
81+
"src/features/threads/ThreadComposer.tsx": "try without catch",
82+
"src/features/threads/ThreadDetailScreen.tsx": "mutates a frozen value",
83+
"src/features/threads/ThreadFeed.tsx": "ref read during render, throw inside try, try/finally",
84+
"src/features/threads/ThreadGitControls.tsx": "manual memo not preserved",
85+
"src/features/threads/ThreadNavigationSidebar.tsx": "ref read during render",
86+
"src/features/threads/ThreadQueueControl.tsx": "ref read during render, try without catch",
87+
"src/features/threads/ThreadRouteScreen.tsx": "try without catch",
88+
"src/features/threads/ThreadSettingsSheet.tsx": "manual memo not preserved, try without catch",
89+
"src/features/threads/UsageLimitRecoveryCard.tsx": "throw inside try, try/finally",
90+
"src/features/threads/git/GitCommitSheet.tsx": "manual memo not preserved",
91+
"src/features/threads/git/GitOverviewSheet.tsx": "try without catch",
92+
"src/features/threads/new-task-flow-provider.tsx": "try without catch",
93+
"src/features/threads/thread-work-log.tsx": "manual memo not preserved",
94+
"src/features/threads/use-composer-command-menu.ts": "manual memo not preserved",
95+
"src/features/threads/use-thread-list-v2-shelf-preferences.ts": "ref read during render",
96+
"src/features/usage/UsageLimitsSection.tsx": "try without catch",
97+
"src/features/usage/UsageRouteScreen.tsx": "try without catch",
98+
"src/features/voice-input/VoiceInputProvider.tsx": "ref read during render",
99+
"src/features/voice-input/useVoiceInputController.ts": "ref read during render",
100+
"src/lib/attachmentDocument.ts": "try/finally",
101+
"src/native/StackHeader.tsx": "ref read during render",
102+
"src/native/T3ComposerEditor.ios.tsx": "ref read during render",
103+
"src/native/T3ComposerEditor.native.tsx": "ref read during render",
104+
"src/state/composer-attachment-uploads.ts": "try without catch",
105+
"src/state/mediaActions.ts": "try without catch",
106+
"src/state/queries.ts": "manual memo not preserved",
107+
"src/state/use-thread-composer-state.ts": "try without catch",
108+
"src/state/use-thread-selection.ts": "ref read during render",
109+
"src/state/use-vcs-action-state.ts": "manual memo not preserved",
110+
};
111+
112+
// Caller flags Metro passes for an iOS release bundle. supportsReactCompiler is
113+
// what `experiments.reactCompiler` in app.config.ts turns on.
114+
const metroCaller = {
115+
name: "metro",
116+
bundler: "metro",
117+
platform: "ios",
118+
isDev: false,
119+
isServer: false,
120+
isNodeModule: false,
121+
supportsStaticESM: true,
122+
supportsReactCompiler: true,
123+
};
124+
125+
const sourceFiles = NodeFS.readdirSync(NodePath.join(mobileRoot, "src"), { recursive: true })
126+
.map(String)
127+
.filter((file) => /\.tsx?$/.test(file) && !/\.(test\.tsx?|d\.ts)$/.test(file))
128+
.map((file) => `src/${file.split(NodePath.sep).join("/")}`)
129+
.sort();
130+
131+
type CompilerLoc = { readonly start?: { readonly line?: number } } | null;
132+
133+
interface CompilerEvent {
134+
readonly kind: string;
135+
readonly detail?: {
136+
readonly options?: {
137+
readonly category?: string;
138+
readonly reason?: string;
139+
readonly loc?: CompilerLoc;
140+
readonly details?: readonly { readonly loc?: CompilerLoc }[];
141+
};
142+
};
143+
}
144+
145+
// babel.config.js is the file Metro loads; the logger rides on the preset's
146+
// own react-compiler option so the plugin runs with Metro's exact settings.
147+
function compilerBailouts(file: string): string[] {
148+
const events: CompilerEvent[] = [];
149+
const babelConfig = requireFromMobile("./babel.config.js")({ cache: () => {} });
150+
const presets = babelConfig.presets.map(([name, options]: [string, object]) =>
151+
name === "babel-preset-expo"
152+
? [
153+
requireFromMobile.resolve(name),
154+
{
155+
...options,
156+
"react-compiler": {
157+
logger: { logEvent: (_: string, event: CompilerEvent) => events.push(event) },
158+
},
159+
},
160+
]
161+
: [name, options],
162+
);
163+
babel.transformFileSync(NodePath.join(mobileRoot, file), {
164+
babelrc: false,
165+
configFile: false,
166+
cwd: mobileRoot,
167+
presets,
168+
caller: metroCaller,
169+
code: false,
170+
});
171+
return events
172+
.filter((event) => event.kind === "CompileError" || event.kind === "CompileSkip")
173+
.map(
174+
(event) =>
175+
`line ${(event.detail?.options?.loc ?? event.detail?.options?.details?.[0]?.loc)?.start?.line ?? "?"}: ${event.detail?.options?.category ?? event.kind} ${event.detail?.options?.reason ?? ""}`,
176+
);
177+
}
178+
179+
describe("React Compiler coverage", () => {
180+
it("Metro's transformer applies the compiler", async () => {
181+
const { transformer } = await metroConfig;
182+
const metroTransformer = requireFromMobile(transformer.babelTransformerPath);
183+
const filename = NodePath.join(
184+
mobileRoot,
185+
"src/features/archive/ArchivedThreadsRouteScreen.tsx",
186+
);
187+
const transformed = (reactCompiler: string) => {
188+
const { ast } = metroTransformer.transform({
189+
filename,
190+
src: NodeFS.readFileSync(filename, "utf8"),
191+
plugins: [],
192+
options: {
193+
dev: false,
194+
hot: false,
195+
platform: "ios",
196+
projectRoot: mobileRoot,
197+
type: "module",
198+
enableBabelRCLookup: false,
199+
experimentalImportSupport: false,
200+
customTransformOptions: { reactCompiler, routerRoot: "app" },
201+
},
202+
});
203+
return JSON.stringify(ast.program.body);
204+
};
205+
expect(transformed("true")).toContain("react/compiler-runtime");
206+
expect(transformed("false")).not.toContain("react/compiler-runtime");
207+
});
208+
209+
it("app.config.ts turns the compiler on for Metro", () => {
210+
const appConfig = NodeFS.readFileSync(NodePath.join(mobileRoot, "app.config.ts"), "utf8");
211+
expect(appConfig).toMatch(/experiments:\s*\{[^}]*reactCompiler:\s*true/);
212+
});
213+
214+
it.each(sourceFiles)("compiles %s", (file) => {
215+
const bailouts = compilerBailouts(file);
216+
if (file in KNOWN_BAILOUTS) {
217+
expect(bailouts, `${file} compiles now; remove it from KNOWN_BAILOUTS`).not.toEqual([]);
218+
} else {
219+
expect(bailouts).toEqual([]);
220+
}
221+
});
222+
223+
it("lists only files that exist", () => {
224+
expect(Object.keys(KNOWN_BAILOUTS).filter((file) => !sourceFiles.includes(file))).toEqual([]);
225+
});
226+
}, 300_000);

‎docs/internals/mobile-development.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,17 @@ copies those into its virtual store instead of linking them. Metro bundles the c
3434
so an edit to a module's TypeScript is invisible to a running dev client until
3535
`vp i` re-syncs it, while Gradle and CocoaPods compile the worktree directory
3636
directly. A JavaScript change that "has no effect" on device is usually this.
37+
38+
## React Compiler
39+
40+
Metro runs the compiler only because `experiments.reactCompiler` is set in `app.config.ts`. Expo
41+
then passes `supportsReactCompiler` to `babel-preset-expo`, which owns the plugin options; there is
42+
no `babel.config.js` entry to look for. Release bundles use `panicThreshold: "NONE"`, so a function
43+
the compiler can't prove safe ships unmemoized with no build error.
44+
[`reactCompilerCoverage.test.ts`](../../apps/mobile/src/reactCompilerCoverage.test.ts) runs the
45+
same preset over every source file. It fails on a new bailout, and on a file in `KNOWN_BAILOUTS`
46+
that now compiles, so the list only shrinks. When you fix a listed file, delete its entry and its
47+
manual `useMemo`/`useCallback`/`memo` in the same change. Most mobile bailouts are `try` without
48+
`catch` or with `finally`, and refs read during render; see [Web UI](web-ui.md#react-compiler)
49+
for the usual rewrites. Mobile runs `t3code/no-manual-memo` with `allowMemoHooks`, so memo
50+
directives are errors but the hooks stay legal until `KNOWN_BAILOUTS` is empty.

‎oxlint-plugin-t3code/rules/no-manual-memo.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,26 @@ describe("t3code/no-manual-memo", () => {
2828
"reports React.useMemo",
2929
`const total = React.useMemo(() => items.length, [items]);`,
3030
);
31+
32+
rule.invalid('reports "use no memo"', `function Panel() { "use no memo"; return null; }`);
33+
34+
rule.invalid('reports a module-level "use no forget"', `"use no forget";\nexport const a = 1;`);
35+
36+
rule.valid("allows the same text as a string value", `const label = "use no memo";`);
37+
});
38+
39+
const ratchet = createOxlintRuleHarness("t3code/no-manual-memo", {
40+
filename: "fixture.tsx",
41+
ruleOptions: [{ allowMemoHooks: true }],
42+
});
43+
44+
describe("t3code/no-manual-memo with allowMemoHooks", () => {
45+
ratchet.valid("allows useMemo", `const total = useMemo(() => items.length, [items]);`);
46+
47+
ratchet.valid("allows useCallback", `const onClick = useCallback(() => save(), []);`);
48+
49+
ratchet.invalid(
50+
'still reports "use no memo"',
51+
`function Panel() { "use no memo"; return null; }`,
52+
);
3153
});

0 commit comments

Comments
 (0)