Skip to content

Commit cbe1a08

Browse files
committed
perf(mobile): reuse chat lists across navigation renders
1 parent 960d576 commit cbe1a08

3 files changed

Lines changed: 270 additions & 84 deletions

File tree

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
import { act, useLayoutEffect } from "react";
2+
import { createRoot } from "react-dom/client";
3+
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
4+
import { expect, it, vi } from "vite-plus/test";
5+
6+
import { makeThreadShellFixture } from "../../test-fixtures";
7+
import { useThreadListV2 } from "./useThreadListV2";
8+
9+
vi.mock("../../state/olderSettledShelf", () => {
10+
const isListed = () => true;
11+
const unloadedCount = () => 0;
12+
return {
13+
useOlderSettledShelf: () => ({ isListed, unloadedCount }),
14+
useOlderSettledShelfGrowth: () => undefined,
15+
};
16+
});
17+
18+
it("reuses a large thread list across tab renders and updates when its inputs change", async () => {
19+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
20+
using _globals = { [Symbol.dispose]: () => vi.unstubAllGlobals() };
21+
const environmentId = EnvironmentId.make("environment-1");
22+
const otherEnvironmentId = EnvironmentId.make("environment-2");
23+
const threads = Array.from({ length: 1200 }, (_, index) =>
24+
makeThreadShellFixture({
25+
id: ThreadId.make(`thread-${index}`),
26+
title: `Thread ${index}`,
27+
environmentId: index % 2 === 0 ? environmentId : otherEnvironmentId,
28+
settledOverride: index < 150 ? "active" : "settled",
29+
settledAt: index < 150 ? null : "2026-01-01T00:00:00.000Z",
30+
}),
31+
);
32+
const environmentIds = new Set([environmentId, otherEnvironmentId]);
33+
const input: Parameters<typeof useThreadListV2>[0] = {
34+
threads,
35+
pendingTasks: [],
36+
environmentId: null,
37+
projectRefs: null,
38+
searchQuery: "",
39+
searchMatches: new Map(),
40+
settlementEnvironmentIds: environmentIds,
41+
snoozeEnvironmentIds: environmentIds,
42+
pinReorderEnvironmentIds: environmentIds,
43+
activeReorderEnvironmentIds: environmentIds,
44+
queuedThreadKeys: new Set(),
45+
settledLimit: 10,
46+
now: "2026-01-02T00:00:00.000Z",
47+
pendingOrder: null,
48+
shelfPreferencesLoaded: true,
49+
workingShelfEnabled: true,
50+
workingShelfExpanded: false,
51+
snoozedShelfExpanded: false,
52+
settledShelfExpanded: true,
53+
selectedThreadKey: null,
54+
};
55+
const seen: Array<ReturnType<typeof useThreadListV2>> = [];
56+
function Probe(props: { input: typeof input; tab: string }) {
57+
const result = useThreadListV2(props.input);
58+
useLayoutEffect(() => {
59+
seen.push(result);
60+
});
61+
return <div>{props.tab}</div>;
62+
}
63+
64+
const root = createRoot(document.createElement("div"));
65+
using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
66+
await act(async () => root.render(<Probe input={{ ...input }} tab="chats" />));
67+
const initial = seen.at(-1)!;
68+
expect(initial.layout.items).toHaveLength(160);
69+
expect(initial.layout.settledCount).toBe(1050);
70+
71+
for (const tab of ["pullRequests", "chats", "settings", "chats"]) {
72+
await act(async () => root.render(<Probe input={{ ...input }} tab={tab} />));
73+
expect(seen.at(-1)!.layout).toBe(initial.layout);
74+
expect(seen.at(-1)!.items).toBe(initial.items);
75+
}
76+
77+
await act(async () => root.render(<Probe input={{ ...input, environmentId }} tab="chats" />));
78+
expect(seen.at(-1)!.layout.items).toHaveLength(85);
79+
expect(seen.at(-1)!.layout.settledCount).toBe(525);
80+
expect(
81+
seen.at(-1)!.layout.items.every((item) => item.thread.environmentId === environmentId),
82+
).toBe(true);
83+
84+
const queuedThreadKeys = new Set([`${environmentId}:thread-150`]);
85+
await act(async () => root.render(<Probe input={{ ...input, queuedThreadKeys }} tab="chats" />));
86+
const queued = seen.at(-1)!;
87+
expect(queued.layout.items).toHaveLength(161);
88+
expect(queued.layout.settledCount).toBe(1049);
89+
expect(
90+
queued.items.find((item) => item.type === "v2-thread" && item.item.thread.id === "thread-150"),
91+
).toMatchObject({ hasQueuedMessages: true, item: { variant: "card" } });
92+
93+
await act(async () => root.render(<Probe input={{ ...input, settledLimit: 35 }} tab="chats" />));
94+
expect(seen.at(-1)!.layout.items).toHaveLength(185);
95+
96+
const updatedThreads = threads.map((thread) =>
97+
thread.id === "thread-0" ? { ...thread, title: "Updated title" } : thread,
98+
);
99+
await act(async () =>
100+
root.render(<Probe input={{ ...input, threads: updatedThreads }} tab="chats" />),
101+
);
102+
expect(
103+
seen.at(-1)!.layout.items.find((item) => item.thread.id === "thread-0")?.thread.title,
104+
).toBe("Updated title");
105+
106+
await act(async () =>
107+
root.render(
108+
<Probe
109+
input={{ ...input, threads: updatedThreads, searchQuery: "Updated title" }}
110+
tab="chats"
111+
/>,
112+
),
113+
);
114+
expect(seen.at(-1)!.layout.items.map((item) => item.thread.title)).toEqual(["Updated title"]);
115+
116+
await act(async () =>
117+
root.render(<Probe input={{ ...input, now: "2026-01-02T00:01:00.000Z" }} tab="chats" />),
118+
);
119+
expect(seen.at(-1)!.items).not.toBe(initial.items);
120+
});

‎apps/mobile/src/features/threads/useThreadListV2.ts‎

Lines changed: 149 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,8 @@ function useKeySet(newlineSeparatedKeys: string): ReadonlySet<string> {
2828
type LayoutInput = Parameters<typeof buildThreadListV2Items>[0];
2929

3030
/**
31-
* Home's and the thread sidebar's thread list. Its result is one value a screen only reads:
32-
* built inline, the list's inputs stayed open to mutation across the screen's other hooks, so
33-
* the React Compiler cached none of it and every render of the screen re-rendered every row.
31+
* Shelf callbacks prevent compiler caching across the whole derivation, so each stage keeps
32+
* its own memo boundary to preserve the list's identity during unrelated navigation renders.
3433
*/
3534
export function useThreadListV2(input: {
3635
readonly threads: LayoutInput["threads"];
@@ -69,101 +68,167 @@ export function useThreadListV2(input: {
6968
// Up/down menu availability for every card, computed once per section per
7069
// rebuild (see computeThreadMoveAvailability): per-thread planner calls made
7170
// list construction quadratic, and this list rebuilds on every minute tick.
72-
const sectionAvailability = (section: "pinned" | "active") =>
73-
computeThreadMoveAvailability({
74-
allThreads: threads,
75-
section,
76-
pendingOrder: input.pendingOrder,
77-
reorderableEnvironmentIds:
78-
section === "pinned" ? input.pinReorderEnvironmentIds : input.activeReorderEnvironmentIds,
79-
ordered: getThreadListV2OrderedSection({
80-
threads,
71+
const moveAvailability = useMemo(() => {
72+
const sectionAvailability = (section: "pinned" | "active") =>
73+
computeThreadMoveAvailability({
74+
allThreads: threads,
8175
section,
8276
pendingOrder: input.pendingOrder,
83-
now: input.now,
84-
settlementEnvironmentIds: input.settlementEnvironmentIds,
85-
snoozeEnvironmentIds: input.snoozeEnvironmentIds,
86-
queuedThreadKeys: input.queuedThreadKeys,
87-
}),
88-
});
89-
const moveAvailability = new Map([
90-
...sectionAvailability("pinned"),
91-
...(workingShelfEnabled ? [] : sectionAvailability("active")),
77+
reorderableEnvironmentIds:
78+
section === "pinned" ? input.pinReorderEnvironmentIds : input.activeReorderEnvironmentIds,
79+
ordered: getThreadListV2OrderedSection({
80+
threads,
81+
section,
82+
pendingOrder: input.pendingOrder,
83+
now: input.now,
84+
settlementEnvironmentIds: input.settlementEnvironmentIds,
85+
snoozeEnvironmentIds: input.snoozeEnvironmentIds,
86+
queuedThreadKeys: input.queuedThreadKeys,
87+
}),
88+
});
89+
return new Map([
90+
...sectionAvailability("pinned"),
91+
...(workingShelfEnabled ? [] : sectionAvailability("active")),
92+
]);
93+
}, [
94+
threads,
95+
input.pendingOrder,
96+
input.pinReorderEnvironmentIds,
97+
input.activeReorderEnvironmentIds,
98+
input.now,
99+
input.settlementEnvironmentIds,
100+
input.snoozeEnvironmentIds,
101+
input.queuedThreadKeys,
102+
workingShelfEnabled,
92103
]);
93104
// Older settled threads load in pages; the shelf lists them only as far as they are loaded.
94-
const scopes = olderSettledScopes(input);
105+
const scopes = useMemo(
106+
() =>
107+
olderSettledScopes({
108+
environmentId: input.environmentId,
109+
projectRefs: input.projectRefs,
110+
settlementEnvironmentIds: input.settlementEnvironmentIds,
111+
}),
112+
[input.environmentId, input.projectRefs, input.settlementEnvironmentIds],
113+
);
95114
const olderSettledShelf = useOlderSettledShelf({
96115
scopes,
97116
expanded: input.settledShelfExpanded,
98117
// A search lists only matches, so the shelf would page forever; loaded pages stay.
99118
visibleCount: input.searchQuery.trim().length === 0 ? input.settledLimit : 0,
100119
});
101-
const layout = buildThreadListV2Items({
102-
pendingOrder: input.pendingOrder,
103-
threads: threads.filter((thread) => thread.archivedAt === null),
104-
environmentId: input.environmentId,
105-
projectRefs: input.projectRefs,
106-
searchQuery: input.searchQuery,
107-
matchedThreadKeys: new Set(input.searchMatches.keys()),
108-
settlementEnvironmentIds: input.settlementEnvironmentIds,
109-
snoozeEnvironmentIds: input.snoozeEnvironmentIds,
110-
queuedThreadKeys: input.queuedThreadKeys,
111-
settledLimit: input.settledLimit,
112-
now: input.now,
113-
workingShelfEnabled,
114-
workingShelfExpanded: input.workingShelfExpanded,
115-
inboxReturnAt: inbox.returnedAt,
116-
isWorking: inbox.isWorking,
117-
snoozedShelfExpanded: input.snoozedShelfExpanded,
118-
settledShelfExpanded: input.settledShelfExpanded,
119-
selectedThreadKey: input.selectedThreadKey,
120-
isListedSettled: olderSettledShelf.isListed,
121-
unloadedSettledCount: olderSettledShelf.unloadedCount(
122-
threads.filter(
123-
(thread) =>
124-
thread.archivedAt === null &&
125-
scopes.some(
126-
(scope) =>
127-
scope.environmentId === thread.environmentId &&
128-
(scope.projectIds === null || scope.projectIds.includes(thread.projectId)),
120+
const { isListed, unloadedCount } = olderSettledShelf;
121+
const layout = useMemo(
122+
() =>
123+
buildThreadListV2Items({
124+
pendingOrder: input.pendingOrder,
125+
threads: threads.filter((thread) => thread.archivedAt === null),
126+
environmentId: input.environmentId,
127+
projectRefs: input.projectRefs,
128+
searchQuery: input.searchQuery,
129+
matchedThreadKeys: new Set(input.searchMatches.keys()),
130+
settlementEnvironmentIds: input.settlementEnvironmentIds,
131+
snoozeEnvironmentIds: input.snoozeEnvironmentIds,
132+
queuedThreadKeys: input.queuedThreadKeys,
133+
settledLimit: input.settledLimit,
134+
now: input.now,
135+
workingShelfEnabled,
136+
workingShelfExpanded: input.workingShelfExpanded,
137+
inboxReturnAt: inbox.returnedAt,
138+
isWorking: inbox.isWorking,
139+
snoozedShelfExpanded: input.snoozedShelfExpanded,
140+
settledShelfExpanded: input.settledShelfExpanded,
141+
selectedThreadKey: input.selectedThreadKey,
142+
isListedSettled: isListed,
143+
unloadedSettledCount: unloadedCount(
144+
threads.filter(
145+
(thread) =>
146+
thread.archivedAt === null &&
147+
scopes.some(
148+
(scope) =>
149+
scope.environmentId === thread.environmentId &&
150+
(scope.projectIds === null || scope.projectIds.includes(thread.projectId)),
151+
),
129152
),
130-
),
131-
),
132-
});
153+
),
154+
}),
155+
[
156+
input.pendingOrder,
157+
threads,
158+
input.environmentId,
159+
input.projectRefs,
160+
input.searchQuery,
161+
input.searchMatches,
162+
input.settlementEnvironmentIds,
163+
input.snoozeEnvironmentIds,
164+
input.queuedThreadKeys,
165+
input.settledLimit,
166+
input.now,
167+
workingShelfEnabled,
168+
input.workingShelfExpanded,
169+
inbox.returnedAt,
170+
inbox.isWorking,
171+
input.snoozedShelfExpanded,
172+
input.settledShelfExpanded,
173+
input.selectedThreadKey,
174+
isListed,
175+
unloadedCount,
176+
scopes,
177+
],
178+
);
133179
useOlderSettledShelfGrowth(olderSettledShelf, layout.listedSettledThreads);
134180
const contentOnlyThreadKeys = useKeySet([...layout.contentOnlyThreadKeys].sort().join("\n"));
135-
const scopedProjectKeys =
136-
input.projectRefs == null
137-
? null
138-
: new Set(input.projectRefs.map((ref) => scopedProjectKey(ref.environmentId, ref.projectId)));
139-
const searchQuery = input.searchQuery.trim().toLocaleLowerCase();
140-
const pendingTasks = input.pendingTasks.filter(
141-
(pendingTask) =>
142-
(input.environmentId === null || pendingTask.environmentId === input.environmentId) &&
143-
(scopedProjectKeys === null ||
144-
scopedProjectKeys.has(
145-
scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
146-
)) &&
147-
(searchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(searchQuery)),
181+
const pendingTasks = useMemo(() => {
182+
const scopedProjectKeys =
183+
input.projectRefs == null
184+
? null
185+
: new Set(
186+
input.projectRefs.map((ref) => scopedProjectKey(ref.environmentId, ref.projectId)),
187+
);
188+
const searchQuery = input.searchQuery.trim().toLocaleLowerCase();
189+
return input.pendingTasks.filter(
190+
(pendingTask) =>
191+
(input.environmentId === null || pendingTask.environmentId === input.environmentId) &&
192+
(scopedProjectKeys === null ||
193+
scopedProjectKeys.has(
194+
scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
195+
)) &&
196+
(searchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(searchQuery)),
197+
);
198+
}, [input.projectRefs, input.searchQuery, input.pendingTasks, input.environmentId]);
199+
const items = useMemo(
200+
() =>
201+
buildThreadListV2ListItems({
202+
items: layout.items,
203+
pendingTasks,
204+
workingCount: layout.workingCount,
205+
workingShelfExpanded: input.workingShelfExpanded,
206+
workingShelfHeaderIndex: layout.workingShelfHeaderIndex,
207+
snoozedCount: layout.snoozedCount,
208+
snoozedShelfExpanded: input.snoozedShelfExpanded,
209+
snoozedShelfHeaderIndex: layout.snoozedShelfHeaderIndex,
210+
settledCount: layout.settledCount,
211+
settledShelfExpanded: input.settledShelfExpanded,
212+
settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
213+
snoozeLabelNow: `${input.now.slice(0, 16)}:00.000Z`,
214+
snoozeEnvironmentIds: input.snoozeEnvironmentIds,
215+
queuedThreadKeys: input.queuedThreadKeys,
216+
moveAvailability,
217+
shelfPreferencesLoading: !input.shelfPreferencesLoaded,
218+
}),
219+
[
220+
layout,
221+
pendingTasks,
222+
input.workingShelfExpanded,
223+
input.snoozedShelfExpanded,
224+
input.settledShelfExpanded,
225+
input.now,
226+
input.snoozeEnvironmentIds,
227+
input.queuedThreadKeys,
228+
moveAvailability,
229+
input.shelfPreferencesLoaded,
230+
],
148231
);
149-
const items = buildThreadListV2ListItems({
150-
items: layout.items,
151-
pendingTasks,
152-
workingCount: layout.workingCount,
153-
workingShelfExpanded: input.workingShelfExpanded,
154-
workingShelfHeaderIndex: layout.workingShelfHeaderIndex,
155-
snoozedCount: layout.snoozedCount,
156-
snoozedShelfExpanded: input.snoozedShelfExpanded,
157-
snoozedShelfHeaderIndex: layout.snoozedShelfHeaderIndex,
158-
settledCount: layout.settledCount,
159-
settledShelfExpanded: input.settledShelfExpanded,
160-
settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
161-
snoozeLabelNow: `${input.now.slice(0, 16)}:00.000Z`,
162-
snoozeEnvironmentIds: input.snoozeEnvironmentIds,
163-
queuedThreadKeys: input.queuedThreadKeys,
164-
moveAvailability,
165-
shelfPreferencesLoading: !input.shelfPreferencesLoaded,
166-
});
167232
return { layout, items, contentOnlyThreadKeys, olderSettledShelf };
168233
}
169234

‎apps/mobile/vite.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ const reactTests = [
2929
"src/state/use-selected-thread-git-actions.test.tsx",
3030
"src/features/terminal/useTerminalExitNavigation.test.tsx",
3131
"src/features/threads/use-thread-list-now.test.tsx",
32+
"src/features/threads/useThreadListV2.test.tsx",
3233
"src/features/home/home-list-options.test.tsx",
3334
"src/features/connection/ConnectionsNewRouteScreen.test.tsx",
3435
];

0 commit comments

Comments
 (0)