Skip to content

Commit 6b3a539

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

4 files changed

Lines changed: 146 additions & 55 deletions

File tree

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

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2085,21 +2085,36 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
20852085
reportHeaderMaterialVisibility(false);
20862086
}, [feedThreadKey, reportHeaderMaterialVisibility]);
20872087

2088-
const presentedFeed = appendPendingThreadMessages(
2089-
deriveThreadFeedPresentation(
2090-
props.feed,
2091-
props.latestRun,
2092-
expandedTurnIds,
2093-
new Set(
2094-
Object.entries(expandedWorkGroups)
2095-
.filter(([, expanded]) => expanded)
2096-
.map(([groupId]) => groupId),
2088+
// The compiler can't memoize this: it stays live across later hook calls. A new array here
2089+
// reruns the whole feed derivation on every render and hands LegendList new data, which
2090+
// re-pins the list through maintainScrollAtEnd.
2091+
const presentedFeed = useMemo(
2092+
() =>
2093+
appendPendingThreadMessages(
2094+
deriveThreadFeedPresentation(
2095+
props.feed,
2096+
props.latestRun,
2097+
expandedTurnIds,
2098+
new Set(
2099+
Object.entries(expandedWorkGroups)
2100+
.filter(([, expanded]) => expanded)
2101+
.map(([groupId]) => groupId),
2102+
),
2103+
props.activeWorkStartedAt,
2104+
props.runlessWorkActive ?? false,
2105+
),
2106+
props.feed,
2107+
props.queuedMessages,
20972108
),
2109+
[
2110+
expandedTurnIds,
2111+
expandedWorkGroups,
20982112
props.activeWorkStartedAt,
2099-
props.runlessWorkActive ?? false,
2100-
),
2101-
props.feed,
2102-
props.queuedMessages,
2113+
props.feed,
2114+
props.latestRun,
2115+
props.queuedMessages,
2116+
props.runlessWorkActive,
2117+
],
21032118
);
21042119
const setupAnchorIndex = presentedFeed.findIndex(
21052120
(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
@@ -191,7 +191,14 @@ function ThreadNavigationSidebarPane(
191191
}
192192
return matches;
193193
}, [threadSearch.matches]);
194-
const matchedThreadKeys = new Set(threadSearch.matches.map(threadSearchMatchKey));
194+
// listItems and the values it derives from: the compiler can't memoize them because they stay
195+
// live across later hook calls. A new listItems hands LegendList new data and re-registers every
196+
// thread jump shortcut, which re-renders the app-root keyboard command provider and resends the
197+
// native command list.
198+
const matchedThreadKeys = useMemo(
199+
() => new Set(threadSearch.matches.map(threadSearchMatchKey)),
200+
[threadSearch.matches],
201+
);
195202
const projectScopeKey = options.selectedProjectKey;
196203
const resolvedProjectKey = resolveScratchProjectScopeKey(projectScopeKey, projects, {
197204
sidebarProjectGroupingMode: options.projectGroupingMode,
@@ -230,17 +237,22 @@ function ThreadNavigationSidebarPane(
230237
),
231238
[projectScopes],
232239
);
233-
const selectedProjectScope =
234-
projectScopes.find((scope) => scope.key === resolvedProjectKey) ?? null;
240+
const selectedProjectScope = useMemo(
241+
() => projectScopes.find((scope) => scope.key === resolvedProjectKey) ?? null,
242+
[projectScopes, resolvedProjectKey],
243+
);
235244
const selectedProjectKey = selectedProjectScope?.key ?? null;
236-
const selectedProjectRefs =
237-
selectedProjectScope === null
238-
? null
239-
: new Set(
240-
selectedProjectScope.projectRefs.map((projectRef) =>
241-
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
245+
const selectedProjectRefs = useMemo(
246+
() =>
247+
selectedProjectScope === null
248+
? null
249+
: new Set(
250+
selectedProjectScope.projectRefs.map((projectRef) =>
251+
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
252+
),
242253
),
243-
);
254+
[selectedProjectScope],
255+
);
244256
const projectByKey = useMemo(() => {
245257
const map = new Map<string, EnvironmentProject>();
246258
for (const project of projects) {
@@ -298,7 +310,7 @@ function ThreadNavigationSidebarPane(
298310
// Up/down menu availability for every card, computed once per section per
299311
// rebuild (see computeThreadMoveAvailability): per-thread planner calls made
300312
// list construction quadratic, and this list rebuilds on every minute tick.
301-
const threadMoveAvailability = (() => {
313+
const threadMoveAvailability = useMemo(() => {
302314
const sectionAvailability = (section: "pinned" | "active") =>
303315
computeThreadMoveAvailability({
304316
allThreads: threads,
@@ -320,8 +332,18 @@ function ThreadNavigationSidebarPane(
320332
...sectionAvailability("pinned"),
321333
...(workingShelfEnabled ? [] : sectionAvailability("active")),
322334
]);
323-
})();
324-
const threadListV2Layout = (() => {
335+
}, [
336+
activeReorderEnvironmentIds,
337+
now,
338+
pendingOrder,
339+
pinReorderEnvironmentIds,
340+
queuedThreadKeys,
341+
settlementEnvironmentIds,
342+
snoozeEnvironmentIds,
343+
threads,
344+
workingShelfEnabled,
345+
]);
346+
const threadListV2Layout = useMemo(() => {
325347
threadListInboxReturns.observe(workingShelfEnabled ? threads : null);
326348
return buildThreadListV2Items({
327349
pendingOrder,
@@ -342,7 +364,24 @@ function ThreadNavigationSidebarPane(
342364
settledShelfExpanded,
343365
selectedThreadKey: props.selectedThreadKey ?? null,
344366
});
345-
})();
367+
}, [
368+
matchedThreadKeys,
369+
now,
370+
options.selectedEnvironmentId,
371+
pendingOrder,
372+
props.searchQuery,
373+
props.selectedThreadKey,
374+
queuedThreadKeys,
375+
selectedProjectScope,
376+
settledShelfExpanded,
377+
settledVisibleCount,
378+
settlementEnvironmentIds,
379+
snoozeEnvironmentIds,
380+
snoozedShelfExpanded,
381+
threads,
382+
workingShelfEnabled,
383+
workingShelfExpanded,
384+
]);
346385
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
347386
useEffect(() => {
348387
if (nextSnoozeWakeAt === null) return;
@@ -358,7 +397,7 @@ function ThreadNavigationSidebarPane(
358397
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
359398
// range) the boundary string is identical and the chain would die.
360399
}, [nextSnoozeWakeAt, snoozeWakeTick]);
361-
const listItems = ((): readonly SidebarListItem[] => {
400+
const listItems = useMemo((): readonly SidebarListItem[] => {
362401
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
363402
const v2PendingTasks = pendingTasks.filter(
364403
(pendingTask) =>
@@ -397,7 +436,21 @@ function ThreadNavigationSidebarPane(
397436
});
398437
}
399438
return items;
400-
})();
439+
}, [
440+
nowMinute,
441+
options.selectedEnvironmentId,
442+
pendingTasks,
443+
props.searchQuery,
444+
queuedThreadKeys,
445+
threadMoveAvailability,
446+
selectedProjectRefs,
447+
settledShelfExpanded,
448+
shelfPreferencesLoaded,
449+
snoozedShelfExpanded,
450+
snoozeEnvironmentIds,
451+
threadListV2Layout,
452+
workingShelfExpanded,
453+
]);
401454
const listMenuActions = [
402455
{
403456
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)