TypeScript
fix(mobile): chat feed no longer re-derives on every render (#22913)
Theo Browne71b867080b1d
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex 8c07123dd3a..a3d956a4ac5 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -1875,6 +1875,33 @@ function ThreadFeedPlaceholder(props: {);}+// A hook's return value is frozen to the compiler, so ThreadFeed's later+// hooks can't drag this derivation into an uncached scope.+function useThreadFeedPresentation(+ props: ThreadFeedProps,+ expandedTurnIds: ReadonlySet<RunId>,+ expandedWorkGroups: Record<string, boolean>,+) {+ const [feedCache] = useState(createThreadFeedCache);+ return appendPendingThreadMessages(+ deriveThreadFeedPresentation(+ props.feed,+ props.latestRun,+ expandedTurnIds,+ new Set(+ Object.entries(expandedWorkGroups)+ .filter(([, expanded]) => expanded)+ .map(([groupId]) => groupId),+ ),+ props.activeWorkStartedAt,+ props.runlessWorkActive ?? false,+ feedCache,+ ),+ props.feed,+ props.queuedMessages,+ );+}+export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {const { listRef, onEndFollowEnabledChange, onHeaderMaterialVisibilityChange } = props;const workflowOpening = useWorkflowOpening(props.environmentId, props.threadId);@@ -1900,7 +1927,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {const disclosureSettleFrameRef = useRef<number | null>(null);const disclosureSettleSecondFrameRef = useRef<number | null>(null);const disclosureAnchorKeyRef = useRef<string | null>(null);- const [feedCache] = useState(createThreadFeedCache);const previousLatestTurnRef = useRef(props.latestRun);const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const headerMaterialVisibleRef = useRef(false);@@ -2456,23 +2482,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {reportHeaderMaterialVisibility(false);}, [feedThreadKey, reportHeaderMaterialVisibility]);- const presentedFeed = appendPendingThreadMessages(- deriveThreadFeedPresentation(- props.feed,- props.latestRun,- expandedTurnIds,- new Set(- Object.entries(expandedWorkGroups)- .filter(([, expanded]) => expanded)- .map(([groupId]) => groupId),- ),- props.activeWorkStartedAt,- props.runlessWorkActive ?? false,- feedCache,- ),- props.feed,- props.queuedMessages,- );+ const presentedFeed = useThreadFeedPresentation(props, expandedTurnIds, expandedWorkGroups);const setupAnchorIndex = presentedFeed.findIndex((entry) => entry.type === "message" && entry.message.role === "user",);diff --git a/apps/mobile/src/reactCompilerCoverage.test.ts b/apps/mobile/src/reactCompilerCoverage.test.tsindex fc6c04aa583..f51c729f319 100644--- a/apps/mobile/src/reactCompilerCoverage.test.ts+++ b/apps/mobile/src/reactCompilerCoverage.test.ts@@ -66,8 +66,7 @@ interface CompilerEvent {// babel.config.js is the file Metro loads; the logger rides on the preset's// own react-compiler option so the plugin runs with Metro's exact settings.-function compilerBailouts(file: string): string[] {- const events: CompilerEvent[] = [];+function compileLikeMetro(file: string, events: CompilerEvent[], output: Record<string, unknown>) {const babelConfig = requireFromMobile("./babel.config.js")({ cache: () => {} });const presets = babelConfig.presets.map(([name, options]: [string, object]) =>name === "babel-preset-expo"@@ -82,14 +81,20 @@ function compilerBailouts(file: string): string[] {]: [name, options],);- babel.transformFileSync(NodePath.join(mobileRoot, file), {+ return babel.transformFileSync(NodePath.join(mobileRoot, file), {babelrc: false,configFile: false,cwd: mobileRoot,presets,caller: metroCaller,code: false,+ ...output,});+}++function compilerBailouts(file: string): string[] {+ const events: CompilerEvent[] = [];+ compileLikeMetro(file, events, {});return events.filter((event) => event.kind === "CompileError" || event.kind === "CompileSkip").map(@@ -98,6 +103,47 @@ function compilerBailouts(file: string): string[] {);}+interface AstNode {+ readonly type: string;+ readonly [key: string]: unknown;+}++const isAstNode = (value: unknown): value is AstNode =>+ typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";++function walkAst(+ value: unknown,+ visit: (node: AstNode, ancestors: readonly AstNode[]) => void,+ ancestors: readonly AstNode[] = [],+) {+ if (typeof value !== "object" || value === null) return;+ const node = isAstNode(value) ? value : null;+ if (node) visit(node, ancestors);+ const childAncestors = node ? [...ancestors, node] : ancestors;+ for (const child of Object.values(value)) walkAst(child, visit, childAncestors);+}++// For each call to `callee`, whether it runs only on the cache-miss branch of+// an `if ($[n] !== dep)` block rather than on every render.+function compilerCachedCalls(file: string, callee: string): boolean[] {+ const result = compileLikeMetro(file, [], { ast: true });+ const cached: boolean[] = [];+ if (typeof result !== "object" || result === null || !("ast" in result)) return cached;+ walkAst(result.ast, (node, ancestors) => {+ if (node.type !== "CallExpression" || !isAstNode(node.callee)) return;+ if (node.callee.type !== "Identifier" || node.callee.name !== callee) return;+ cached.push(+ ancestors.some(+ (ancestor, index) =>+ ancestor.type === "IfStatement" &&+ ancestors[index + 1] === ancestor.consequent &&+ JSON.stringify(ancestor.test).includes('"name":"$"'),+ ),+ );+ });+ return cached;+}+describe("React Compiler coverage", () => {it("Metro's transformer applies the compiler", async () => {const { transformer } = await metroConfig;@@ -137,6 +183,14 @@ describe("React Compiler coverage", () => {}});+ // The compiler once silently dropped this cache, so every+ // ThreadFeed render rebuilt the feed and handed LegendList a new data array.+ it("caches the thread feed derivation", () => {+ expect(+ compilerCachedCalls("src/features/threads/ThreadFeed.tsx", "deriveThreadFeedPresentation"),+ ).toEqual([true]);+ });+it("lists only files that exist", () => {expect(Object.keys(KNOWN_BAILOUTS).filter((file) => !sourceFiles.includes(file))).toEqual([]);});