Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 28 additions & 18 deletions apps/mobile/src/features/threads/ThreadFeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1734,6 +1734,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);
Expand All @@ -1759,7 +1786,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);
Expand Down Expand Up @@ -2315,23 +2341,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",
);
Expand Down
60 changes: 57 additions & 3 deletions apps/mobile/src/reactCompilerCoverage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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(
Expand All @@ -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;
Expand Down Expand Up @@ -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([]);
});
Expand Down
Loading