Skip to content

Commit 46cdf10

Browse files
flambohclaude
andcommitted
perf(mobile): restore memoization the React Compiler drops
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 143ab16 commit 46cdf10

4 files changed

Lines changed: 148 additions & 56 deletions

File tree

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2091,22 +2091,38 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
20912091
reportHeaderMaterialVisibility(false);
20922092
}, [feedThreadKey, reportHeaderMaterialVisibility]);
20932093

2094-
const presentedFeed = appendPendingThreadMessages(
2095-
deriveThreadFeedPresentation(
2096-
props.feed,
2097-
props.latestRun,
2098-
expandedTurnIds,
2099-
new Set(
2100-
Object.entries(expandedWorkGroups)
2101-
.filter(([, expanded]) => expanded)
2102-
.map(([groupId]) => groupId),
2094+
// The compiler can't memoize this: it stays live across later hook calls. A new array here
2095+
// reruns the whole feed derivation on every render and hands LegendList new data, which
2096+
// re-pins the list through maintainScrollAtEnd.
2097+
const presentedFeed = useMemo(
2098+
() =>
2099+
appendPendingThreadMessages(
2100+
deriveThreadFeedPresentation(
2101+
props.feed,
2102+
props.latestRun,
2103+
expandedTurnIds,
2104+
new Set(
2105+
Object.entries(expandedWorkGroups)
2106+
.filter(([, expanded]) => expanded)
2107+
.map(([groupId]) => groupId),
2108+
),
2109+
props.activeWorkStartedAt,
2110+
props.runlessWorkActive ?? false,
2111+
feedCache,
2112+
),
2113+
props.feed,
2114+
props.queuedMessages,
21032115
),
2104-
props.activeWorkStartedAt,
2105-
props.runlessWorkActive ?? false,
2116+
[
2117+
expandedTurnIds,
2118+
expandedWorkGroups,
21062119
feedCache,
2107-
),
2108-
props.feed,
2109-
props.queuedMessages,
2120+
props.activeWorkStartedAt,
2121+
props.feed,
2122+
props.latestRun,
2123+
props.queuedMessages,
2124+
props.runlessWorkActive,
2125+
],
21102126
);
21112127
const setupAnchorIndex = presentedFeed.findIndex(
21122128
(entry) => entry.type === "message" && entry.message.role === "user",

‎apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx‎

Lines changed: 69 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,14 @@ function ThreadNavigationSidebarPane(
192192
}
193193
return matches;
194194
}, [threadSearch.matches]);
195-
const matchedThreadKeys = new Set(threadSearch.matches.map(threadSearchMatchKey));
195+
// listItems and the values it derives from: the compiler can't memoize them because they stay
196+
// live across later hook calls. A new listItems hands LegendList new data and re-registers every
197+
// thread jump shortcut, which re-renders the app-root keyboard command provider and resends the
198+
// native command list.
199+
const matchedThreadKeys = useMemo(
200+
() => new Set(threadSearch.matches.map(threadSearchMatchKey)),
201+
[threadSearch.matches],
202+
);
196203
const projectScopeKey = options.selectedProjectKey;
197204
const resolvedProjectKey = resolveScratchProjectScopeKey(projectScopeKey, projects, {
198205
sidebarProjectGroupingMode: options.projectGroupingMode,
@@ -231,17 +238,22 @@ function ThreadNavigationSidebarPane(
231238
),
232239
[projectScopes],
233240
);
234-
const selectedProjectScope =
235-
projectScopes.find((scope) => scope.key === resolvedProjectKey) ?? null;
241+
const selectedProjectScope = useMemo(
242+
() => projectScopes.find((scope) => scope.key === resolvedProjectKey) ?? null,
243+
[projectScopes, resolvedProjectKey],
244+
);
236245
const selectedProjectKey = selectedProjectScope?.key ?? null;
237-
const selectedProjectRefs =
238-
selectedProjectScope === null
239-
? null
240-
: new Set(
241-
selectedProjectScope.projectRefs.map((projectRef) =>
242-
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
246+
const selectedProjectRefs = useMemo(
247+
() =>
248+
selectedProjectScope === null
249+
? null
250+
: new Set(
251+
selectedProjectScope.projectRefs.map((projectRef) =>
252+
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
253+
),
243254
),
244-
);
255+
[selectedProjectScope],
256+
);
245257
const projectByKey = useMemo(() => {
246258
const map = new Map<string, EnvironmentProject>();
247259
for (const project of projects) {
@@ -299,7 +311,7 @@ function ThreadNavigationSidebarPane(
299311
// Up/down menu availability for every card, computed once per section per
300312
// rebuild (see computeThreadMoveAvailability): per-thread planner calls made
301313
// list construction quadratic, and this list rebuilds on every minute tick.
302-
const threadMoveAvailability = (() => {
314+
const threadMoveAvailability = useMemo(() => {
303315
const sectionAvailability = (section: "pinned" | "active") =>
304316
computeThreadMoveAvailability({
305317
allThreads: threads,
@@ -321,8 +333,18 @@ function ThreadNavigationSidebarPane(
321333
...sectionAvailability("pinned"),
322334
...(workingShelfEnabled ? [] : sectionAvailability("active")),
323335
]);
324-
})();
325-
const threadListV2Layout = (() => {
336+
}, [
337+
activeReorderEnvironmentIds,
338+
now,
339+
pendingOrder,
340+
pinReorderEnvironmentIds,
341+
queuedThreadKeys,
342+
settlementEnvironmentIds,
343+
snoozeEnvironmentIds,
344+
threads,
345+
workingShelfEnabled,
346+
]);
347+
const threadListV2Layout = useMemo(() => {
326348
threadListInboxReturns.observe(workingShelfEnabled ? threads : null);
327349
return buildThreadListV2Items({
328350
pendingOrder,
@@ -343,7 +365,24 @@ function ThreadNavigationSidebarPane(
343365
settledShelfExpanded,
344366
selectedThreadKey: props.selectedThreadKey ?? null,
345367
});
346-
})();
368+
}, [
369+
matchedThreadKeys,
370+
now,
371+
options.selectedEnvironmentId,
372+
pendingOrder,
373+
props.searchQuery,
374+
props.selectedThreadKey,
375+
queuedThreadKeys,
376+
selectedProjectScope,
377+
settledShelfExpanded,
378+
settledVisibleCount,
379+
settlementEnvironmentIds,
380+
snoozeEnvironmentIds,
381+
snoozedShelfExpanded,
382+
threads,
383+
workingShelfEnabled,
384+
workingShelfExpanded,
385+
]);
347386
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
348387
useEffect(() => {
349388
if (nextSnoozeWakeAt === null) return;
@@ -359,7 +398,7 @@ function ThreadNavigationSidebarPane(
359398
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
360399
// range) the boundary string is identical and the chain would die.
361400
}, [nextSnoozeWakeAt, snoozeWakeTick]);
362-
const listItems = ((): readonly SidebarListItem[] => {
401+
const listItems = useMemo((): readonly SidebarListItem[] => {
363402
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
364403
const v2PendingTasks = pendingTasks.filter(
365404
(pendingTask) =>
@@ -398,7 +437,21 @@ function ThreadNavigationSidebarPane(
398437
});
399438
}
400439
return items;
401-
})();
440+
}, [
441+
nowMinute,
442+
options.selectedEnvironmentId,
443+
pendingTasks,
444+
props.searchQuery,
445+
queuedThreadKeys,
446+
threadMoveAvailability,
447+
selectedProjectRefs,
448+
settledShelfExpanded,
449+
shelfPreferencesLoaded,
450+
snoozedShelfExpanded,
451+
snoozeEnvironmentIds,
452+
threadListV2Layout,
453+
workingShelfExpanded,
454+
]);
402455
const listMenuActions = [
403456
{
404457
id: "environment",

‎apps/mobile/src/features/threads/new-task-flow-provider.tsx‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as Dialog from "../../components/ui/Dialog";
22
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
33
import { useEnvironmentPresentation } from "../../state/presentation";
44
import { environmentSession } from "../../state/session";
5-
import React, { useEffect, useRef, useState } from "react";
5+
import React, { useEffect, useMemo, useRef, useState } from "react";
66

77
import type {
88
EnvironmentId,
@@ -353,12 +353,18 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
353353
isScratchProject(selectedProject, selectedEnvironmentServerConfig?.scratchWorkspaceRoot);
354354
const serverConfigs = useServerConfigs();
355355
const { connectedEnvironments } = useRemoteConnectionStatus();
356-
const scratchEnvironments = connectedEnvironments.filter(
357-
(environment) =>
358-
availableScratchWorkspaceRoot(
359-
environment.connectionState,
360-
serverConfigs.get(environment.environmentId),
361-
) !== null,
356+
// The compiler can't memoize the scratch environments: they stay live across later hook
357+
// calls. A new list here changes the new-task context value on every render in scratch drafts.
358+
const scratchEnvironments = useMemo(
359+
() =>
360+
connectedEnvironments.filter(
361+
(environment) =>
362+
availableScratchWorkspaceRoot(
363+
environment.connectionState,
364+
serverConfigs.get(environment.environmentId),
365+
) !== null,
366+
),
367+
[connectedEnvironments, serverConfigs],
362368
);
363369

364370
const selectedRepositoryKey = selectedProject?.repositoryIdentity
@@ -368,7 +374,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
368374
// workspaceRoot, and an "" basename would reject every real host below.
369375
const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
370376
const selectedProjectTitle = selectedProject?.title ?? null;
371-
const environments = (() => {
377+
const environments = useMemo(() => {
372378
if (isScratchDraft) {
373379
return scratchEnvironments.map((environment) => ({
374380
environmentId: environment.environmentId,
@@ -413,7 +419,15 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
413419
});
414420
}
415421
return result;
416-
})();
422+
}, [
423+
isScratchDraft,
424+
projects,
425+
savedConnectionsById,
426+
scratchEnvironments,
427+
selectedProjectTitle,
428+
selectedRepositoryKey,
429+
selectedWorkspaceBasename,
430+
]);
417431

418432
const selectedProjectDraftKey = editingPendingTask
419433
? pendingTaskDraftKey(editingPendingTask.messageId)

‎apps/mobile/src/state/queries.ts‎

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import * as Cause from "effect/Cause";
2424
import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
2525
import * as Option from "effect/Option";
2626
import { AsyncResult, Atom } from "effect/reactivity";
27-
import { useEffect, useState } from "react";
27+
import { useEffect, useMemo, useState } from "react";
2828

2929
import { appAtomRegistry } from "./atom-registry";
3030
import { orchestrationEnvironment } from "./orchestration";
@@ -216,22 +216,31 @@ export function usePaginatedBranches(target: VcsRefTarget) {
216216
cursors: INITIAL_BRANCH_CURSORS,
217217
});
218218
const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
219-
const pageAtoms =
220-
target.environmentId !== null && target.cwd !== null
221-
? cursors.map((cursor) =>
222-
vcsEnvironment.listRefs({
223-
environmentId: target.environmentId!,
224-
input: {
225-
cwd: target.cwd!,
226-
...(query.length > 0 ? { query } : {}),
227-
...(cursor === undefined ? {} : { cursor }),
228-
limit: VCS_REF_LIST_LIMIT,
229-
},
230-
}),
231-
)
232-
: [];
233-
const pagesAtom = Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
234-
Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
219+
// The compiler can't memoize these: they stay live across the useAtomValue call. A new
220+
// pagesAtom on every render makes useAtomValue resubscribe and render the caller twice.
221+
const pageAtoms = useMemo(
222+
() =>
223+
target.environmentId !== null && target.cwd !== null
224+
? cursors.map((cursor) =>
225+
vcsEnvironment.listRefs({
226+
environmentId: target.environmentId!,
227+
input: {
228+
cwd: target.cwd!,
229+
...(query.length > 0 ? { query } : {}),
230+
...(cursor === undefined ? {} : { cursor }),
231+
limit: VCS_REF_LIST_LIMIT,
232+
},
233+
}),
234+
)
235+
: [],
236+
[cursors, query, target.cwd, target.environmentId],
237+
);
238+
const pagesAtom = useMemo(
239+
() =>
240+
Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
241+
Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
242+
),
243+
[pageAtoms, targetKey],
235244
);
236245
const results = useAtomValue(pagesAtom);
237246
const values = results.flatMap((result) => {

0 commit comments

Comments
 (0)