@devries-cameron20 / t3code Mirror · read-only / commits / 0366a19436
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 08:15 UTC

perf(mobile): reuse chat lists across navigation renders (#27026)

Co-authored-by: maria-rcks <maria@kuuro.net>

Alex committed Nov 1, 2026 at 13:03 UTC 0366a1943673b4034e314f6df51412a03f57205b
7 files changed +515 -96
apps/mobile/src/features/home/HomeScreen.tsx
+11 -6
@@ -13,7 +13,7 @@ import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-gro
13 import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
14 import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
15 import { useAtomValue } from "@effect/atom-react";
16 -import { use, useEffect, useRef, useState, type ComponentProps } from "react";
16 +import { use, useEffect, useMemo, useRef, useState, type ComponentProps } from "react";
17 import {
18 Platform,
19 ScrollView,
@@ -362,11 +362,16 @@ export function HomeScreen(props: HomeScreenProps) {
362 onScrollBeginDrag: handleScrollBeginDrag,
363 });
364
365 - const projectScopes = buildHomeProjectScopes({
366 - projects: props.projects,
367 - environmentId: props.selectedEnvironmentId,
368 - projectGroupingMode: props.projectGroupingMode,
369 - });
365 + const { projects, selectedEnvironmentId, projectGroupingMode } = props;
366 + const projectScopes = useMemo(
367 + () =>
368 + buildHomeProjectScopes({
369 + projects,
370 + environmentId: selectedEnvironmentId,
371 + projectGroupingMode,
372 + }),
373 + [projects, selectedEnvironmentId, projectGroupingMode],
374 + );
375 const hasSearchQuery = props.searchQuery.trim().length > 0;
376 const projectByKey = (() => {
377 const map = new Map<string, EnvironmentProject>();
apps/mobile/src/features/threads/threadListV2.ts
+21
@@ -168,6 +168,27 @@ export function nextSnoozeWakeAfter(
168 return next;
169 }
170
171 +// Outside search, the clock only changes list membership/order at snooze deadlines.
172 +export function threadListV2LayoutTime(input: {
173 + readonly threads: ReadonlyArray<{ readonly snoozedUntil?: string | null }>;
174 + readonly now: string;
175 + readonly searchQuery: string;
176 +}) {
177 + if (input.searchQuery !== "") return input.now;
178 + const nowMs = Date.parse(input.now);
179 + if (!Number.isFinite(nowMs)) return input.now;
180 + let previousWakeAt: number | undefined;
181 + let nextWakeAt: number | undefined;
182 + for (const thread of input.threads) {
183 + if (thread.snoozedUntil == null) continue;
184 + const wakeAt = Date.parse(thread.snoozedUntil);
185 + if (!Number.isFinite(wakeAt)) continue;
186 + if (wakeAt <= nowMs) previousWakeAt = Math.max(previousWakeAt ?? wakeAt, wakeAt);
187 + else nextWakeAt = Math.min(nextWakeAt ?? wakeAt, wakeAt);
188 + }
189 + return new Date(previousWakeAt ?? (nextWakeAt === undefined ? 0 : nextWakeAt - 1)).toISOString();
190 +}
191 +
192 export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
193 export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
194
apps/mobile/src/features/threads/useThreadListV2.test.tsx new
+244
@@ -0,0 +1,244 @@
1 +import { act, useLayoutEffect } from "react";
2 +import { createRoot } from "react-dom/client";
3 +import { RegistryContext } from "@effect/atom-react";
4 +import type { OlderSettledShelfEnvironment } from "@t3tools/client-runtime/state/threads";
5 +import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
6 +import * as DateTime from "effect/DateTime";
7 +import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
8 +import { Atom, AtomRegistry } from "effect/reactivity";
9 +import { expect, it, vi } from "vite-plus/test";
10 +
11 +import { olderSettledThreads } from "../../state/threads";
12 +import { makeRawThreadShell } from "../../test-fixtures";
13 +import { useThreadListV2 } from "./useThreadListV2";
14 +
15 +vi.mock("../../state/threads", () => ({
16 + olderSettledThreads: { shelfAtom: vi.fn() },
17 + threadFamilies: { mountRows: () => () => {} },
18 +}));
19 +vi.mock("../../state/atom-registry", () => ({ appAtomRegistry: undefined }));
20 +
21 +it("reuses a large thread list across tab renders and updates when its inputs change", async () => {
22 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
23 + using _globals = { [Symbol.dispose]: () => vi.unstubAllGlobals() };
24 + const shelfAtom = Atom.make<ReadonlyMap<EnvironmentId, OlderSettledShelfEnvironment>>(new Map());
25 + vi.mocked(olderSettledThreads.shelfAtom).mockReturnValue(shelfAtom);
26 + const registry = AtomRegistry.make();
27 + using _registry = { [Symbol.dispose]: () => registry.dispose() };
28 + const environmentId = EnvironmentId.make("environment-1");
29 + const otherEnvironmentId = EnvironmentId.make("environment-2");
30 + const threads = Array.from({ length: 1200 }, (_, index) =>
31 + presentThreadShell(
32 + index % 2 === 0 ? environmentId : otherEnvironmentId,
33 + makeRawThreadShell({
34 + id: ThreadId.make(`thread-${index}`),
35 + title: `Thread ${index}`,
36 + settledOverride: index < 150 ? "active" : "settled",
37 + settledAt: index < 150 ? null : DateTime.makeUnsafe("2026-01-01T00:00:00.000Z"),
38 + }),
39 + ),
40 + );
41 + const environmentIds = new Set([environmentId, otherEnvironmentId]);
42 + const input: Parameters<typeof useThreadListV2>[0] = {
43 + threads,
44 + pendingTasks: [],
45 + environmentId: null,
46 + projectRefs: null,
47 + searchQuery: "",
48 + searchMatches: new Map(),
49 + settlementEnvironmentIds: environmentIds,
50 + snoozeEnvironmentIds: environmentIds,
51 + pinReorderEnvironmentIds: environmentIds,
52 + activeReorderEnvironmentIds: environmentIds,
53 + queuedThreadKeys: new Set(),
54 + settledLimit: 10,
55 + now: "2026-01-02T00:00:00.000Z",
56 + pendingOrder: null,
57 + shelfPreferencesLoaded: true,
58 + workingShelfEnabled: true,
59 + workingShelfExpanded: false,
60 + snoozedShelfExpanded: false,
61 + settledShelfExpanded: true,
62 + selectedThreadKey: null,
63 + };
64 + const seen: Array<ReturnType<typeof useThreadListV2>> = [];
65 + function Probe(props: { input: typeof input; tab: string }) {
66 + return (
67 + <RegistryContext value={registry}>
68 + <ListProbe {...props} />
69 + </RegistryContext>
70 + );
71 + }
72 + function ListProbe(props: { input: typeof input; tab: string }) {
73 + const result = useThreadListV2(props.input);
74 + useLayoutEffect(() => {
75 + seen.push(result);
76 + });
77 + return <div>{props.tab}</div>;
78 + }
79 +
80 + const root = createRoot(document.createElement("div"));
81 + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
82 + await act(async () => root.render(<Probe input={{ ...input }} tab="chats" />));
83 + const initial = seen.at(-1)!;
84 + expect(initial.layout.items).toHaveLength(160);
85 + expect(initial.layout.settledCount).toBe(1050);
86 +
87 + for (const tab of ["pullRequests", "chats", "settings", "chats"]) {
88 + await act(async () => root.render(<Probe input={{ ...input }} tab={tab} />));
89 + expect(seen.at(-1)!.olderSettledShelf.isListed).toBe(initial.olderSettledShelf.isListed);
90 + expect(seen.at(-1)!.olderSettledShelf.unloadedCount).toBe(
91 + initial.olderSettledShelf.unloadedCount,
92 + );
93 + expect(seen.at(-1)!.layout).toBe(initial.layout);
94 + expect(seen.at(-1)!.items).toBe(initial.items);
95 + }
96 +
97 + const nextMinute = { ...input, now: "2026-01-02T00:01:00.000Z" };
98 + await act(async () => root.render(<Probe input={nextMinute} tab="chats" />));
99 + expect(seen.at(-1)!.layout).toBe(initial.layout);
100 + expect(seen.at(-1)!.items).not.toBe(initial.items);
101 + expect(seen.at(-1)!.items.find((item) => item.type === "v2-thread")).toMatchObject({
102 + snoozePresetMinute: nextMinute.now,
103 + });
104 +
105 + await act(async () => root.render(<Probe input={{ ...input, environmentId }} tab="chats" />));
106 + expect(seen.at(-1)!.layout.items).toHaveLength(85);
107 + expect(seen.at(-1)!.layout.settledCount).toBe(525);
108 + expect(
109 + seen.at(-1)!.layout.items.every((item) => item.thread.environmentId === environmentId),
110 + ).toBe(true);
111 +
112 + const queuedThreadKeys = new Set([`${environmentId}:thread-150`]);
113 + await act(async () => root.render(<Probe input={{ ...input, queuedThreadKeys }} tab="chats" />));
114 + const queued = seen.at(-1)!;
115 + expect(queued.layout.items).toHaveLength(161);
116 + expect(queued.layout.settledCount).toBe(1049);
117 + expect(
118 + queued.items.find((item) => item.type === "v2-thread" && item.item.thread.id === "thread-150"),
119 + ).toMatchObject({ hasQueuedMessages: true, item: { variant: "card" } });
120 +
121 + await act(async () => root.render(<Probe input={{ ...input, settledLimit: 35 }} tab="chats" />));
122 + expect(seen.at(-1)!.layout.items).toHaveLength(185);
123 +
124 + const updatedThreads = threads.map((thread) =>
125 + thread.id === "thread-0" ? { ...thread, title: "Updated title" } : thread,
126 + );
127 + await act(async () =>
128 + root.render(<Probe input={{ ...input, threads: updatedThreads }} tab="chats" />),
129 + );
130 + expect(
131 + seen.at(-1)!.layout.items.find((item) => item.thread.id === "thread-0")?.thread.title,
132 + ).toBe("Updated title");
133 +
134 + await act(async () =>
135 + root.render(
136 + <Probe
137 + input={{ ...input, threads: updatedThreads, searchQuery: "Updated title" }}
138 + tab="chats"
139 + />,
140 + ),
141 + );
142 + expect(seen.at(-1)!.layout.items.map((item) => item.thread.title)).toEqual(["Updated title"]);
143 + const search = seen.at(-1)!;
144 + await act(async () =>
145 + root.render(
146 + <Probe
147 + input={{ ...nextMinute, threads: updatedThreads, searchQuery: "Updated title" }}
148 + tab="chats"
149 + />,
150 + ),
151 + );
152 + expect(seen.at(-1)!.layout).not.toBe(search.layout);
153 + expect(seen.at(-1)!.layout.items.map((item) => item.thread.title)).toEqual(["Updated title"]);
154 +
155 + const clockThreads = threads.map((thread) =>
156 + thread.id === "thread-0" ? { ...thread, snoozedUntil: "2026-01-02T00:00:30.000Z" } : thread,
157 + );
158 + const clockInput = { ...input, threads: clockThreads, snoozedShelfExpanded: true };
159 + await act(async () => root.render(<Probe input={clockInput} tab="chats" />));
160 + const beforeClock = seen.at(-1)!;
161 + expect(beforeClock.layout.snoozedCount).toBe(1);
162 + expect(beforeClock.layout.items.find((item) => item.thread.id === "thread-0")?.snoozed).toBe(
163 + true,
164 + );
165 + await act(async () => root.render(<Probe input={clockInput} tab="settings" />));
166 + expect(seen.at(-1)!.items).toBe(beforeClock.items);
167 +
168 + await act(async () =>
169 + root.render(<Probe input={{ ...clockInput, now: "2026-01-02T00:00:10.000Z" }} tab="chats" />),
170 + );
171 + expect(seen.at(-1)!.layout).toBe(beforeClock.layout);
172 + expect(seen.at(-1)!.layout.snoozedCount).toBe(1);
173 +
174 + await act(async () =>
175 + root.render(<Probe input={{ ...clockInput, now: "2026-01-02T00:01:00.000Z" }} tab="chats" />),
176 + );
177 + const afterClock = seen.at(-1)!;
178 + expect(afterClock.items).not.toBe(beforeClock.items);
179 + expect(afterClock.layout.snoozedCount).toBe(0);
180 + expect(afterClock.layout.items.find((item) => item.thread.id === "thread-0")?.snoozed).toBe(
181 + false,
182 + );
183 + await act(async () =>
184 + root.render(<Probe input={{ ...clockInput, now: "2026-01-02T00:02:00.000Z" }} tab="chats" />),
185 + );
186 + expect(seen.at(-1)!.layout).toBe(afterClock.layout);
187 + expect(seen.at(-1)!.items).not.toBe(afterClock.items);
188 +
189 + await act(async () =>
190 + root.render(<Probe input={{ ...clockInput, now: "2026-01-02T00:00:20.000Z" }} tab="chats" />),
191 + );
192 + expect(seen.at(-1)!.layout.snoozedCount).toBe(1);
193 + expect(seen.at(-1)!.layout.items.find((item) => item.thread.id === "thread-0")?.snoozed).toBe(
194 + true,
195 + );
196 + await act(async () => root.render(<Probe input={input} tab="chats" />));
197 + const before = "2026-01-01T12:00:00.000Z";
198 + const older = {
199 + before,
200 + beforeMs: Date.parse(before),
201 + counts: new Map([[ProjectId.make("project-test"), 575]]),
202 + };
203 + await act(async () => {
204 + registry.set(
205 + shelfAtom,
206 + new Map([
207 + [
208 + environmentId,
209 + {
210 + older,
211 + pages: { reads: [], frontier: { settledAt: before }, status: "pending" },
212 + },
213 + ],
214 + ]),
215 + );
216 + });
217 + const loading = seen.at(-1)!;
218 + expect(loading.layout.settledCount).toBe(1100);
219 + expect(loading.layout.listedSettledThreads).toHaveLength(0);
220 + expect(loading.layout.items).toHaveLength(150);
221 + expect(loading.olderSettledShelf.isListed(threads[150]!)).toBe(false);
222 + await act(async () => root.render(<Probe input={input} tab="settings" />));
223 + expect(seen.at(-1)!.items).toBe(loading.items);
224 +
225 + await act(async () => {
226 + registry.set(
227 + shelfAtom,
228 + new Map([
229 + [
230 + environmentId,
231 + {
232 + older,
233 + pages: { reads: [], frontier: null, status: "ready" },
234 + },
235 + ],
236 + ]),
237 + );
238 + });
239 + const loaded = seen.at(-1)!;
240 + expect(loaded.layout.settledCount).toBe(1100);
241 + expect(loaded.layout.items).toHaveLength(160);
242 + expect(loaded.olderSettledShelf.isListed(threads[150]!)).toBe(true);
243 + expect(loaded.items).not.toBe(loading.items);
244 +});
apps/mobile/src/features/threads/useThreadListV2.ts
+157 -89
@@ -10,6 +10,7 @@ import {
10 buildThreadListV2ListItems,
11 getThreadListV2OrderedSection,
12 threadListInboxReturns,
13 + threadListV2LayoutTime,
14 } from "./threadListV2";
15 import { computeThreadMoveAvailability } from "./threadOrder";
16
@@ -28,8 +29,8 @@ function useKeySet(newlineSeparatedKeys: string): ReadonlySet<string> {
29 type LayoutInput = Parameters<typeof buildThreadListV2Items>[0];
30
31 /**
31 - * The React Compiler memoizes on the values a callback reads and drops unread entries from a
32 - * dependency list, so the version that marks an expired grace must be read to rebuild the list.
32 + * The React Compiler drops unread dependencies, so pass the expired-grace version through
33 + * this call to keep inbox updates tied to its subscription.
34 */
35 function observeInbox(
36 threads: Parameters<typeof threadListInboxReturns.observe>[0],
@@ -39,9 +40,8 @@ function observeInbox(
40 }
41
42 /**
42 - * Home's and the thread sidebar's thread list. Its result is one value a screen only reads:
43 - * built inline, the list's inputs stayed open to mutation across the screen's other hooks, so
44 - * the React Compiler cached none of it and every render of the screen re-rendered every row.
43 + * Shelf callbacks prevent compiler caching across the whole derivation, so each stage keeps
44 + * its own memo boundary to preserve the list's identity during unrelated navigation renders.
45 */
46 export function useThreadListV2(input: {
47 readonly threads: LayoutInput["threads"];
@@ -67,6 +67,10 @@ export function useThreadListV2(input: {
67 readonly selectedThreadKey: string | null;
68 }) {
69 const { threads, workingShelfEnabled } = input;
70 + const layoutTime = useMemo(
71 + () => threadListV2LayoutTime({ threads, now: input.now, searchQuery: input.searchQuery }),
72 + [threads, input.now, input.searchQuery],
73 + );
74 // A thread can stop working when the threads change, or when its exit grace expires.
75 const inboxVersion = useSyncExternalStore(
76 threadListInboxReturns.subscribe,
@@ -76,104 +80,168 @@ export function useThreadListV2(input: {
80 () => observeInbox(workingShelfEnabled ? threads : null, inboxVersion),
81 [threads, workingShelfEnabled, inboxVersion],
82 );
79 - // Up/down menu availability for every card, computed once per section per
80 - // rebuild (see computeThreadMoveAvailability): per-thread planner calls made
81 - // list construction quadratic, and this list rebuilds on every minute tick.
82 - const sectionAvailability = (section: "pinned" | "active") =>
83 - computeThreadMoveAvailability({
84 - allThreads: threads,
85 - section,
86 - pendingOrder: input.pendingOrder,
87 - reorderableEnvironmentIds:
88 - section === "pinned" ? input.pinReorderEnvironmentIds : input.activeReorderEnvironmentIds,
89 - ordered: getThreadListV2OrderedSection({
90 - threads,
83 + // Compute move availability per section; per-row planning is quadratic.
84 + const moveAvailability = useMemo(() => {
85 + const sectionAvailability = (section: "pinned" | "active") =>
86 + computeThreadMoveAvailability({
87 + allThreads: threads,
88 section,
89 pendingOrder: input.pendingOrder,
93 - now: input.now,
94 - settlementEnvironmentIds: input.settlementEnvironmentIds,
95 - snoozeEnvironmentIds: input.snoozeEnvironmentIds,
96 - queuedThreadKeys: input.queuedThreadKeys,
97 - }),
98 - });
99 - const moveAvailability = new Map([
100 - ...sectionAvailability("pinned"),
101 - ...(workingShelfEnabled ? [] : sectionAvailability("active")),
90 + reorderableEnvironmentIds:
91 + section === "pinned" ? input.pinReorderEnvironmentIds : input.activeReorderEnvironmentIds,
92 + ordered: getThreadListV2OrderedSection({
93 + threads,
94 + section,
95 + pendingOrder: input.pendingOrder,
96 + now: layoutTime,
97 + settlementEnvironmentIds: input.settlementEnvironmentIds,
98 + snoozeEnvironmentIds: input.snoozeEnvironmentIds,
99 + queuedThreadKeys: input.queuedThreadKeys,
100 + }),
101 + });
102 + return new Map([
103 + ...sectionAvailability("pinned"),
104 + ...(workingShelfEnabled ? [] : sectionAvailability("active")),
105 + ]);
106 + }, [
107 + threads,
108 + input.pendingOrder,
109 + input.pinReorderEnvironmentIds,
110 + input.activeReorderEnvironmentIds,
111 + layoutTime,
112 + input.settlementEnvironmentIds,
113 + input.snoozeEnvironmentIds,
114 + input.queuedThreadKeys,
115 + workingShelfEnabled,
116 ]);
117 // Older settled threads load in pages; the shelf lists them only as far as they are loaded.
104 - const scopes = olderSettledScopes(input);
118 + const scopes = useMemo(
119 + () =>
120 + olderSettledScopes({
121 + environmentId: input.environmentId,
122 + projectRefs: input.projectRefs,
123 + settlementEnvironmentIds: input.settlementEnvironmentIds,
124 + }),
125 + [input.environmentId, input.projectRefs, input.settlementEnvironmentIds],
126 + );
127 const olderSettledShelf = useOlderSettledShelf({
128 scopes,
129 expanded: input.settledShelfExpanded,
130 // A search lists only matches, so the shelf would page forever; loaded pages stay.
131 visibleCount: input.searchQuery.trim().length === 0 ? input.settledLimit : 0,
132 });
111 - const layout = buildThreadListV2Items({
112 - pendingOrder: input.pendingOrder,
113 - threads: threads.filter((thread) => thread.archivedAt === null),
114 - environmentId: input.environmentId,
115 - projectRefs: input.projectRefs,
116 - searchQuery: input.searchQuery,
117 - matchedThreadKeys: new Set(input.searchMatches.keys()),
118 - settlementEnvironmentIds: input.settlementEnvironmentIds,
119 - snoozeEnvironmentIds: input.snoozeEnvironmentIds,
120 - queuedThreadKeys: input.queuedThreadKeys,
121 - settledLimit: input.settledLimit,
122 - now: input.now,
123 - workingShelfEnabled,
124 - workingShelfExpanded: input.workingShelfExpanded,
125 - inboxReturnAt: inbox.returnedAt,
126 - isWorking: inbox.isWorking,
127 - snoozedShelfExpanded: input.snoozedShelfExpanded,
128 - settledShelfExpanded: input.settledShelfExpanded,
129 - selectedThreadKey: input.selectedThreadKey,
130 - isListedSettled: olderSettledShelf.isListed,
131 - unloadedSettledCount: olderSettledShelf.unloadedCount(
132 - threads.filter(
133 - (thread) =>
134 - thread.archivedAt === null &&
135 - scopes.some(
136 - (scope) =>
137 - scope.environmentId === thread.environmentId &&
138 - (scope.projectIds === null || scope.projectIds.includes(thread.projectId)),
133 + const { isListed, unloadedCount } = olderSettledShelf;
134 + const layout = useMemo(
135 + () =>
136 + buildThreadListV2Items({
137 + pendingOrder: input.pendingOrder,
138 + threads: threads.filter((thread) => thread.archivedAt === null),
139 + environmentId: input.environmentId,
140 + projectRefs: input.projectRefs,
141 + searchQuery: input.searchQuery,
142 + matchedThreadKeys: new Set(input.searchMatches.keys()),
143 + settlementEnvironmentIds: input.settlementEnvironmentIds,
144 + snoozeEnvironmentIds: input.snoozeEnvironmentIds,
145 + queuedThreadKeys: input.queuedThreadKeys,
146 + settledLimit: input.settledLimit,
147 + now: layoutTime,
148 + workingShelfEnabled,
149 + workingShelfExpanded: input.workingShelfExpanded,
150 + inboxReturnAt: inbox.returnedAt,
151 + isWorking: inbox.isWorking,
152 + snoozedShelfExpanded: input.snoozedShelfExpanded,
153 + settledShelfExpanded: input.settledShelfExpanded,
154 + selectedThreadKey: input.selectedThreadKey,
155 + isListedSettled: isListed,
156 + unloadedSettledCount: unloadedCount(
157 + threads.filter(
158 + (thread) =>
159 + thread.archivedAt === null &&
160 + scopes.some(
161 + (scope) =>
162 + scope.environmentId === thread.environmentId &&
163 + (scope.projectIds === null || scope.projectIds.includes(thread.projectId)),
164 + ),
165 ),
140 - ),
141 - ),
142 - });
166 + ),
167 + }),
168 + [
169 + input.pendingOrder,
170 + threads,
171 + input.environmentId,
172 + input.projectRefs,
173 + input.searchQuery,
174 + input.searchMatches,
175 + input.settlementEnvironmentIds,
176 + input.snoozeEnvironmentIds,
177 + input.queuedThreadKeys,
178 + input.settledLimit,
179 + layoutTime,
180 + workingShelfEnabled,
181 + input.workingShelfExpanded,
182 + inbox.returnedAt,
183 + inbox.isWorking,
184 + input.snoozedShelfExpanded,
185 + input.settledShelfExpanded,
186 + input.selectedThreadKey,
187 + isListed,
188 + unloadedCount,
189 + scopes,
190 + ],
191 + );
192 useOlderSettledShelfGrowth(olderSettledShelf, layout.listedSettledThreads);
193 const contentOnlyThreadKeys = useKeySet([...layout.contentOnlyThreadKeys].sort().join("\n"));
145 - const scopedProjectKeys =
146 - input.projectRefs == null
147 - ? null
148 - : new Set(input.projectRefs.map((ref) => scopedProjectKey(ref.environmentId, ref.projectId)));
149 - const searchQuery = input.searchQuery.trim().toLocaleLowerCase();
150 - const pendingTasks = input.pendingTasks.filter(
151 - (pendingTask) =>
152 - (input.environmentId === null || pendingTask.environmentId === input.environmentId) &&
153 - (scopedProjectKeys === null ||
154 - scopedProjectKeys.has(
155 - scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
156 - )) &&
157 - (searchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(searchQuery)),
194 + const pendingTasks = useMemo(() => {
195 + const scopedProjectKeys =
196 + input.projectRefs == null
197 + ? null
198 + : new Set(
199 + input.projectRefs.map((ref) => scopedProjectKey(ref.environmentId, ref.projectId)),
200 + );
201 + const searchQuery = input.searchQuery.trim().toLocaleLowerCase();
202 + return input.pendingTasks.filter(
203 + (pendingTask) =>
204 + (input.environmentId === null || pendingTask.environmentId === input.environmentId) &&
205 + (scopedProjectKeys === null ||
206 + scopedProjectKeys.has(
207 + scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
208 + )) &&
209 + (searchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(searchQuery)),
210 + );
211 + }, [input.projectRefs, input.searchQuery, input.pendingTasks, input.environmentId]);
212 + const items = useMemo(
213 + () =>
214 + buildThreadListV2ListItems({
215 + items: layout.items,
216 + pendingTasks,
217 + workingCount: layout.workingCount,
218 + workingShelfExpanded: input.workingShelfExpanded,
219 + workingShelfHeaderIndex: layout.workingShelfHeaderIndex,
220 + snoozedCount: layout.snoozedCount,
221 + snoozedShelfExpanded: input.snoozedShelfExpanded,
222 + snoozedShelfHeaderIndex: layout.snoozedShelfHeaderIndex,
223 + settledCount: layout.settledCount,
224 + settledShelfExpanded: input.settledShelfExpanded,
225 + settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
226 + snoozeLabelNow: `${input.now.slice(0, 16)}:00.000Z`,
227 + snoozeEnvironmentIds: input.snoozeEnvironmentIds,
228 + queuedThreadKeys: input.queuedThreadKeys,
229 + moveAvailability,
230 + shelfPreferencesLoading: !input.shelfPreferencesLoaded,
231 + }),
232 + [
233 + layout,
234 + pendingTasks,
235 + input.workingShelfExpanded,
236 + input.snoozedShelfExpanded,
237 + input.settledShelfExpanded,
238 + input.now,
239 + input.snoozeEnvironmentIds,
240 + input.queuedThreadKeys,
241 + moveAvailability,
242 + input.shelfPreferencesLoaded,
243 + ],
244 );
159 - const items = buildThreadListV2ListItems({
160 - items: layout.items,
161 - pendingTasks,
162 - workingCount: layout.workingCount,
163 - workingShelfExpanded: input.workingShelfExpanded,
164 - workingShelfHeaderIndex: layout.workingShelfHeaderIndex,
165 - snoozedCount: layout.snoozedCount,
166 - snoozedShelfExpanded: input.snoozedShelfExpanded,
167 - snoozedShelfHeaderIndex: layout.snoozedShelfHeaderIndex,
168 - settledCount: layout.settledCount,
169 - settledShelfExpanded: input.settledShelfExpanded,
170 - settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
171 - snoozeLabelNow: `${input.now.slice(0, 16)}:00.000Z`,
172 - snoozeEnvironmentIds: input.snoozeEnvironmentIds,
173 - queuedThreadKeys: input.queuedThreadKeys,
174 - moveAvailability,
175 - shelfPreferencesLoading: !input.shelfPreferencesLoaded,
176 - });
245 return { layout, items, contentOnlyThreadKeys, olderSettledShelf };
246 }
247
apps/mobile/src/state/use-thread-outbox.test.ts new
+80
@@ -0,0 +1,80 @@
1 +import { CommandId, EnvironmentId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
2 +import { AtomRegistry } from "effect/reactivity";
3 +import { expect, it, vi } from "vite-plus/test";
4 +
5 +import type { QueuedThreadMessage } from "./thread-outbox-model";
6 +
7 +vi.mock("./thread-outbox", async () => {
8 + const { Atom } = await import("effect/reactivity");
9 + return {
10 + threadOutboxManager: {
11 + queuedMessagesByThreadKeyAtom: Atom.make<
12 + Readonly<Record<string, ReadonlyArray<QueuedThreadMessage>>>
13 + >({}).pipe(Atom.keepAlive),
14 + },
15 + };
16 +});
17 +vi.mock("./atom-registry", () => ({ appAtomRegistry: undefined }));
18 +vi.mock("./shell", () => ({ environmentShell: {} }));
19 +
20 +import { threadOutboxManager } from "./thread-outbox";
21 +import { queuedThreadKeysAtom } from "./use-thread-outbox";
22 +
23 +it("retains queue membership while chat lists are hidden and follows queued messages", () => {
24 + const scheduled = new Set<() => void>();
25 + const registry = AtomRegistry.make({
26 + scheduleTask: (task) => {
27 + scheduled.add(task);
28 + return () => {
29 + scheduled.delete(task);
30 + };
31 + },
32 + });
33 + using _registry = { [Symbol.dispose]: () => registry.dispose() };
34 + const flush = () => {
35 + for (const task of scheduled) {
36 + scheduled.delete(task);
37 + task();
38 + }
39 + };
40 + const release = registry.mount(queuedThreadKeysAtom);
41 + const initial = registry.get(queuedThreadKeysAtom);
42 + expect([...initial]).toEqual([]);
43 + release();
44 + flush();
45 + expect(registry.get(queuedThreadKeysAtom)).toBe(initial);
46 +
47 + const message: QueuedThreadMessage = {
48 + environmentId: EnvironmentId.make("environment-1"),
49 + threadId: ThreadId.make("thread-1"),
50 + messageId: MessageId.make("message-1"),
51 + commandId: CommandId.make("command-1"),
52 + text: "Follow up",
53 + attachments: [],
54 + createdAt: "2026-10-29T12:00:00.000Z",
55 + };
56 + registry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {
57 + "environment-1:thread-1": [message],
58 + "environment-1:new-thread": [
59 + {
60 + ...message,
61 + threadId: ThreadId.make("new-thread"),
62 + creation: {
63 + projectId: ProjectId.make("project-1"),
64 + workspaceMode: "local",
65 + branch: null,
66 + worktreePath: null,
67 + },
68 + },
69 + ],
70 + });
71 + const queued = registry.get(queuedThreadKeysAtom);
72 + expect([...queued]).toEqual(["environment-1:thread-1"]);
73 + const releaseAgain = registry.mount(queuedThreadKeysAtom);
74 + releaseAgain();
75 + flush();
76 + expect(registry.get(queuedThreadKeysAtom)).toBe(queued);
77 +
78 + registry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
79 + expect([...registry.get(queuedThreadKeysAtom)]).toEqual([]);
80 +});
apps/mobile/src/state/use-thread-outbox.ts
+1 -1
@@ -63,7 +63,7 @@ export const queuedThreadKeysAtom = Atom.make((get): ReadonlySet<string> => {
63 }
64 }
65 return keys;
66 -}).pipe(Atom.withLabel("mobile:thread-outbox:queued-thread-keys"));
66 +}).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-outbox:queued-thread-keys"));
67
68 export function useQueuedThreadKeys(): ReadonlySet<string> {
69 return useAtomValue(queuedThreadKeysAtom);
apps/mobile/vite.config.ts
+1
@@ -36,6 +36,7 @@ const reactTests = [
36 "src/state/use-selected-thread-git-state.test.tsx",
37 "src/features/terminal/useTerminalExitNavigation.test.tsx",
38 "src/features/threads/use-thread-list-now.test.tsx",
39 + "src/features/threads/useThreadListV2.test.tsx",
40 "src/features/home/home-list-options.test.tsx",
41 "src/features/workspace/useSearchScrollRestoration.test.tsx",
42 "src/features/connection/ConnectionsNewRouteScreen.test.tsx",