Skip to content
TypeScript

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

Alex0366a1943673
diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx
index 5ac49af24a4..66be9a586ac 100644
--- a/apps/mobile/src/features/home/HomeScreen.tsx
+++ b/apps/mobile/src/features/home/HomeScreen.tsx
@@ -13,7 +13,7 @@ import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-gro
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
-import { use, useEffect, useRef, useState, type ComponentProps } from "react";
+import { use, useEffect, useMemo, useRef, useState, type ComponentProps } from "react";
import {
Platform,
ScrollView,
@@ -362,11 +362,16 @@ export function HomeScreen(props: HomeScreenProps) {
onScrollBeginDrag: handleScrollBeginDrag,
});
- const projectScopes = buildHomeProjectScopes({
- projects: props.projects,
- environmentId: props.selectedEnvironmentId,
- projectGroupingMode: props.projectGroupingMode,
- });
+ const { projects, selectedEnvironmentId, projectGroupingMode } = props;
+ const projectScopes = useMemo(
+ () =>
+ buildHomeProjectScopes({
+ projects,
+ environmentId: selectedEnvironmentId,
+ projectGroupingMode,
+ }),
+ [projects, selectedEnvironmentId, projectGroupingMode],
+ );
const hasSearchQuery = props.searchQuery.trim().length > 0;
const projectByKey = (() => {
const map = new Map<string, EnvironmentProject>();
diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts
index 61280bad84e..4c2b35ed6f9 100644
--- a/apps/mobile/src/features/threads/threadListV2.ts
+++ b/apps/mobile/src/features/threads/threadListV2.ts
@@ -168,6 +168,27 @@ export function nextSnoozeWakeAfter(
return next;
}
+// Outside search, the clock only changes list membership/order at snooze deadlines.
+export function threadListV2LayoutTime(input: {
+ readonly threads: ReadonlyArray<{ readonly snoozedUntil?: string | null }>;
+ readonly now: string;
+ readonly searchQuery: string;
+}) {
+ if (input.searchQuery !== "") return input.now;
+ const nowMs = Date.parse(input.now);
+ if (!Number.isFinite(nowMs)) return input.now;
+ let previousWakeAt: number | undefined;
+ let nextWakeAt: number | undefined;
+ for (const thread of input.threads) {
+ if (thread.snoozedUntil == null) continue;
+ const wakeAt = Date.parse(thread.snoozedUntil);
+ if (!Number.isFinite(wakeAt)) continue;
+ if (wakeAt <= nowMs) previousWakeAt = Math.max(previousWakeAt ?? wakeAt, wakeAt);
+ else nextWakeAt = Math.min(nextWakeAt ?? wakeAt, wakeAt);
+ }
+ return new Date(previousWakeAt ?? (nextWakeAt === undefined ? 0 : nextWakeAt - 1)).toISOString();
+}
+
export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
diff --git a/apps/mobile/src/features/threads/useThreadListV2.test.tsx b/apps/mobile/src/features/threads/useThreadListV2.test.tsx
new file mode 100644
index 00000000000..7eac8955efa
--- /dev/null
+++ b/apps/mobile/src/features/threads/useThreadListV2.test.tsx
@@ -0,0 +1,244 @@
+import { act, useLayoutEffect } from "react";
+import { createRoot } from "react-dom/client";
+import { RegistryContext } from "@effect/atom-react";
+import type { OlderSettledShelfEnvironment } from "@t3tools/client-runtime/state/threads";
+import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
+import * as DateTime from "effect/DateTime";
+import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
+import { Atom, AtomRegistry } from "effect/reactivity";
+import { expect, it, vi } from "vite-plus/test";
+
+import { olderSettledThreads } from "../../state/threads";
+import { makeRawThreadShell } from "../../test-fixtures";
+import { useThreadListV2 } from "./useThreadListV2";
+
+vi.mock("../../state/threads", () => ({
+ olderSettledThreads: { shelfAtom: vi.fn() },
+ threadFamilies: { mountRows: () => () => {} },
+}));
+vi.mock("../../state/atom-registry", () => ({ appAtomRegistry: undefined }));
+
+it("reuses a large thread list across tab renders and updates when its inputs change", async () => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ using _globals = { [Symbol.dispose]: () => vi.unstubAllGlobals() };
+ const shelfAtom = Atom.make<ReadonlyMap<EnvironmentId, OlderSettledShelfEnvironment>>(new Map());
+ vi.mocked(olderSettledThreads.shelfAtom).mockReturnValue(shelfAtom);
+ const registry = AtomRegistry.make();
+ using _registry = { [Symbol.dispose]: () => registry.dispose() };
+ const environmentId = EnvironmentId.make("environment-1");
+ const otherEnvironmentId = EnvironmentId.make("environment-2");
+ const threads = Array.from({ length: 1200 }, (_, index) =>
+ presentThreadShell(
+ index % 2 === 0 ? environmentId : otherEnvironmentId,
+ makeRawThreadShell({
+ id: ThreadId.make(`thread-${index}`),
+ title: `Thread ${index}`,
+ settledOverride: index < 150 ? "active" : "settled",
+ settledAt: index < 150 ? null : DateTime.makeUnsafe("2026-01-01T00:00:00.000Z"),
+ }),
+ ),
+ );
+ const environmentIds = new Set([environmentId, otherEnvironmentId]);
+ const input: Parameters<typeof useThreadListV2>[0] = {
+ threads,
+ pendingTasks: [],
+ environmentId: null,
+ projectRefs: null,
+ searchQuery: "",
+ searchMatches: new Map(),
+ settlementEnvironmentIds: environmentIds,
+ snoozeEnvironmentIds: environmentIds,
+ pinReorderEnvironmentIds: environmentIds,
+ activeReorderEnvironmentIds: environmentIds,
+ queuedThreadKeys: new Set(),
+ settledLimit: 10,
+ now: "2026-01-02T00:00:00.000Z",
+ pendingOrder: null,
+ shelfPreferencesLoaded: true,
+ workingShelfEnabled: true,
+ workingShelfExpanded: false,
+ snoozedShelfExpanded: false,
+ settledShelfExpanded: true,
+ selectedThreadKey: null,
+ };
+ const seen: Array<ReturnType<typeof useThreadListV2>> = [];
+ function Probe(props: { input: typeof input; tab: string }) {
+ return (
+ <RegistryContext value={registry}>
+ <ListProbe {...props} />
+ </RegistryContext>
+ );
+ }
+ function ListProbe(props: { input: typeof input; tab: string }) {
+ const result = useThreadListV2(props.input);
+ useLayoutEffect(() => {
+ seen.push(result);
+ });
+ return <div>{props.tab}</div>;
+ }
+
+ const root = createRoot(document.createElement("div"));
+ using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
+ await act(async () => root.render(<Probe input={{ ...input }} tab="chats" />));
+ const initial = seen.at(-1)!;
+ expect(initial.layout.items).toHaveLength(160);
+ expect(initial.layout.settledCount).toBe(1050);
+
+ for (const tab of ["pullRequests", "chats", "settings", "chats"]) {
+ await act(async () => root.render(<Probe input={{ ...input }} tab={tab} />));
+ expect(seen.at(-1)!.olderSettledShelf.isListed).toBe(initial.olderSettledShelf.isListed);
+ expect(seen.at(-1)!.olderSettledShelf.unloadedCount).toBe(
+ initial.olderSettledShelf.unloadedCount,
+ );
+ expect(seen.at(-1)!.layout).toBe(initial.layout);
+ expect(seen.at(-1)!.items).toBe(initial.items);
+ }
+
+ const nextMinute = { ...input, now: "2026-01-02T00:01:00.000Z" };
+ await act(async () => root.render(<Probe input={nextMinute} tab="chats" />));
+ expect(seen.at(-1)!.layout).toBe(initial.layout);
+ expect(seen.at(-1)!.items).not.toBe(initial.items);
+ expect(seen.at(-1)!.items.find((item) => item.type === "v2-thread")).toMatchObject({
+ snoozePresetMinute: nextMinute.now,
+ });
+
+ await act(async () => root.render(<Probe input={{ ...input, environmentId }} tab="chats" />));
+ expect(seen.at(-1)!.layout.items).toHaveLength(85);
+ expect(seen.at(-1)!.layout.settledCount).toBe(525);
+ expect(
+ seen.at(-1)!.layout.items.every((item) => item.thread.environmentId === environmentId),
+ ).toBe(true);
+
+ const queuedThreadKeys = new Set([`${environmentId}:thread-150`]);
+ await act(async () => root.render(<Probe input={{ ...input, queuedThreadKeys }} tab="chats" />));
+ const queued = seen.at(-1)!;
+ expect(queued.layout.items).toHaveLength(161);
+ expect(queued.layout.settledCount).toBe(1049);
+ expect(
+ queued.items.find((item) => item.type === "v2-thread" && item.item.thread.id === "thread-150"),
+ ).toMatchObject({ hasQueuedMessages: true, item: { variant: "card" } });
+
+ await act(async () => root.render(<Probe input={{ ...input, settledLimit: 35 }} tab="chats" />));
+ expect(seen.at(-1)!.layout.items).toHaveLength(185);
+
+ const updatedThreads = threads.map((thread) =>
+ thread.id === "thread-0" ? { ...thread, title: "Updated title" } : thread,
+ );
+ await act(async () =>
+ root.render(<Probe input={{ ...input, threads: updatedThreads }} tab="chats" />),
+ );
+ expect(
+ seen.at(-1)!.layout.items.find((item) => item.thread.id === "thread-0")?.thread.title,
+ ).toBe("Updated title");
+
+ await act(async () =>
+ root.render(
+ <Probe
+ input={{ ...input, threads: updatedThreads, searchQuery: "Updated title" }}
+ tab="chats"
+ />,
+ ),
+ );
+ expect(seen.at(-1)!.layout.items.map((item) => item.thread.title)).toEqual(["Updated title"]);
+ const search = seen.at(-1)!;
+ await act(async () =>
+ root.render(
+ <Probe
+ input={{ ...nextMinute, threads: updatedThreads, searchQuery: "Updated title" }}
+ tab="chats"
+ />,
+ ),
+ );
+ expect(seen.at(-1)!.layout).not.toBe(search.layout);
+ expect(seen.at(-1)!.layout.items.map((item) => item.thread.title)).toEqual(["Updated title"]);
+
+ const clockThreads = threads.map((thread) =>
+ thread.id === "thread-0" ? { ...thread, snoozedUntil: "2026-01-02T00:00:30.000Z" } : thread,
+ );
+ const clockInput = { ...input, threads: clockThreads, snoozedShelfExpanded: true };
+ await act(async () => root.render(<Probe input={clockInput} tab="chats" />));
+ const beforeClock = seen.at(-1)!;
+ expect(beforeClock.layout.snoozedCount).toBe(1);
+ expect(beforeClock.layout.items.find((item) => item.thread.id === "thread-0")?.snoozed).toBe(
+ true,
+ );
+ await act(async () => root.render(<Probe input={clockInput} tab="settings" />));
+ expect(seen.at(-1)!.items).toBe(beforeClock.items);
+
+ await act(async () =>
+ root.render(<Probe input={{ ...clockInput, now: "2026-01-02T00:00:10.000Z" }} tab="chats" />),
+ );
+ expect(seen.at(-1)!.layout).toBe(beforeClock.layout);
+ expect(seen.at(-1)!.layout.snoozedCount).toBe(1);
+
+ await act(async () =>
+ root.render(<Probe input={{ ...clockInput, now: "2026-01-02T00:01:00.000Z" }} tab="chats" />),
+ );
+ const afterClock = seen.at(-1)!;
+ expect(afterClock.items).not.toBe(beforeClock.items);
+ expect(afterClock.layout.snoozedCount).toBe(0);
+ expect(afterClock.layout.items.find((item) => item.thread.id === "thread-0")?.snoozed).toBe(
+ false,
+ );
+ await act(async () =>
+ root.render(<Probe input={{ ...clockInput, now: "2026-01-02T00:02:00.000Z" }} tab="chats" />),
+ );
+ expect(seen.at(-1)!.layout).toBe(afterClock.layout);
+ expect(seen.at(-1)!.items).not.toBe(afterClock.items);
+
+ await act(async () =>
+ root.render(<Probe input={{ ...clockInput, now: "2026-01-02T00:00:20.000Z" }} tab="chats" />),
+ );
+ expect(seen.at(-1)!.layout.snoozedCount).toBe(1);
+ expect(seen.at(-1)!.layout.items.find((item) => item.thread.id === "thread-0")?.snoozed).toBe(
+ true,
+ );
+ await act(async () => root.render(<Probe input={input} tab="chats" />));
+ const before = "2026-01-01T12:00:00.000Z";
+ const older = {
+ before,
+ beforeMs: Date.parse(before),
+ counts: new Map([[ProjectId.make("project-test"), 575]]),
+ };
+ await act(async () => {
+ registry.set(
+ shelfAtom,
+ new Map([
+ [
+ environmentId,
+ {
+ older,
+ pages: { reads: [], frontier: { settledAt: before }, status: "pending" },
+ },
+ ],
+ ]),
+ );
+ });
+ const loading = seen.at(-1)!;
+ expect(loading.layout.settledCount).toBe(1100);
+ expect(loading.layout.listedSettledThreads).toHaveLength(0);
+ expect(loading.layout.items).toHaveLength(150);
+ expect(loading.olderSettledShelf.isListed(threads[150]!)).toBe(false);
+ await act(async () => root.render(<Probe input={input} tab="settings" />));
+ expect(seen.at(-1)!.items).toBe(loading.items);
+
+ await act(async () => {
+ registry.set(
+ shelfAtom,
+ new Map([
+ [
+ environmentId,
+ {
+ older,
+ pages: { reads: [], frontier: null, status: "ready" },
+ },
+ ],
+ ]),
+ );
+ });
+ const loaded = seen.at(-1)!;
+ expect(loaded.layout.settledCount).toBe(1100);
+ expect(loaded.layout.items).toHaveLength(160);
+ expect(loaded.olderSettledShelf.isListed(threads[150]!)).toBe(true);
+ expect(loaded.items).not.toBe(loading.items);
+});
diff --git a/apps/mobile/src/features/threads/useThreadListV2.ts b/apps/mobile/src/features/threads/useThreadListV2.ts
index 1a0c67062fe..fcf1048d2b6 100644
--- a/apps/mobile/src/features/threads/useThreadListV2.ts
+++ b/apps/mobile/src/features/threads/useThreadListV2.ts
@@ -10,6 +10,7 @@ import {
buildThreadListV2ListItems,
getThreadListV2OrderedSection,
threadListInboxReturns,
+ threadListV2LayoutTime,
} from "./threadListV2";
import { computeThreadMoveAvailability } from "./threadOrder";
@@ -28,8 +29,8 @@ function useKeySet(newlineSeparatedKeys: string): ReadonlySet<string> {
type LayoutInput = Parameters<typeof buildThreadListV2Items>[0];
/**
- * The React Compiler memoizes on the values a callback reads and drops unread entries from a
- * dependency list, so the version that marks an expired grace must be read to rebuild the list.
+ * The React Compiler drops unread dependencies, so pass the expired-grace version through
+ * this call to keep inbox updates tied to its subscription.
*/
function observeInbox(
threads: Parameters<typeof threadListInboxReturns.observe>[0],
@@ -39,9 +40,8 @@ function observeInbox(
}
/**
- * Home's and the thread sidebar's thread list. Its result is one value a screen only reads:
- * built inline, the list's inputs stayed open to mutation across the screen's other hooks, so
- * the React Compiler cached none of it and every render of the screen re-rendered every row.
+ * Shelf callbacks prevent compiler caching across the whole derivation, so each stage keeps
+ * its own memo boundary to preserve the list's identity during unrelated navigation renders.
*/
export function useThreadListV2(input: {
readonly threads: LayoutInput["threads"];
@@ -67,6 +67,10 @@ export function useThreadListV2(input: {
readonly selectedThreadKey: string | null;
}) {
const { threads, workingShelfEnabled } = input;
+ const layoutTime = useMemo(
+ () => threadListV2LayoutTime({ threads, now: input.now, searchQuery: input.searchQuery }),
+ [threads, input.now, input.searchQuery],
+ );
// A thread can stop working when the threads change, or when its exit grace expires.
const inboxVersion = useSyncExternalStore(
threadListInboxReturns.subscribe,
@@ -76,104 +80,168 @@ export function useThreadListV2(input: {
() => observeInbox(workingShelfEnabled ? threads : null, inboxVersion),
[threads, workingShelfEnabled, inboxVersion],
);
- // Up/down menu availability for every card, computed once per section per
- // rebuild (see computeThreadMoveAvailability): per-thread planner calls made
- // list construction quadratic, and this list rebuilds on every minute tick.
- const sectionAvailability = (section: "pinned" | "active") =>
- computeThreadMoveAvailability({
- allThreads: threads,
- section,
- pendingOrder: input.pendingOrder,
- reorderableEnvironmentIds:
- section === "pinned" ? input.pinReorderEnvironmentIds : input.activeReorderEnvironmentIds,
- ordered: getThreadListV2OrderedSection({
- threads,
+ // Compute move availability per section; per-row planning is quadratic.
+ const moveAvailability = useMemo(() => {
+ const sectionAvailability = (section: "pinned" | "active") =>
+ computeThreadMoveAvailability({
+ allThreads: threads,
section,
pendingOrder: input.pendingOrder,
- now: input.now,
- settlementEnvironmentIds: input.settlementEnvironmentIds,
- snoozeEnvironmentIds: input.snoozeEnvironmentIds,
- queuedThreadKeys: input.queuedThreadKeys,
- }),
- });
- const moveAvailability = new Map([
- ...sectionAvailability("pinned"),
- ...(workingShelfEnabled ? [] : sectionAvailability("active")),
+ reorderableEnvironmentIds:
+ section === "pinned" ? input.pinReorderEnvironmentIds : input.activeReorderEnvironmentIds,
+ ordered: getThreadListV2OrderedSection({
+ threads,
+ section,
+ pendingOrder: input.pendingOrder,
+ now: layoutTime,
+ settlementEnvironmentIds: input.settlementEnvironmentIds,
+ snoozeEnvironmentIds: input.snoozeEnvironmentIds,
+ queuedThreadKeys: input.queuedThreadKeys,
+ }),
+ });
+ return new Map([
+ ...sectionAvailability("pinned"),
+ ...(workingShelfEnabled ? [] : sectionAvailability("active")),
+ ]);
+ }, [
+ threads,
+ input.pendingOrder,
+ input.pinReorderEnvironmentIds,
+ input.activeReorderEnvironmentIds,
+ layoutTime,
+ input.settlementEnvironmentIds,
+ input.snoozeEnvironmentIds,
+ input.queuedThreadKeys,
+ workingShelfEnabled,
]);
// Older settled threads load in pages; the shelf lists them only as far as they are loaded.
- const scopes = olderSettledScopes(input);
+ const scopes = useMemo(
+ () =>
+ olderSettledScopes({
+ environmentId: input.environmentId,
+ projectRefs: input.projectRefs,
+ settlementEnvironmentIds: input.settlementEnvironmentIds,
+ }),
+ [input.environmentId, input.projectRefs, input.settlementEnvironmentIds],
+ );
const olderSettledShelf = useOlderSettledShelf({
scopes,
expanded: input.settledShelfExpanded,
// A search lists only matches, so the shelf would page forever; loaded pages stay.
visibleCount: input.searchQuery.trim().length === 0 ? input.settledLimit : 0,
});
- const layout = buildThreadListV2Items({
- pendingOrder: input.pendingOrder,
- threads: threads.filter((thread) => thread.archivedAt === null),
- environmentId: input.environmentId,
- projectRefs: input.projectRefs,
- searchQuery: input.searchQuery,
- matchedThreadKeys: new Set(input.searchMatches.keys()),
- settlementEnvironmentIds: input.settlementEnvironmentIds,
- snoozeEnvironmentIds: input.snoozeEnvironmentIds,
- queuedThreadKeys: input.queuedThreadKeys,
- settledLimit: input.settledLimit,
- now: input.now,
- workingShelfEnabled,
- workingShelfExpanded: input.workingShelfExpanded,
- inboxReturnAt: inbox.returnedAt,
- isWorking: inbox.isWorking,
- snoozedShelfExpanded: input.snoozedShelfExpanded,
- settledShelfExpanded: input.settledShelfExpanded,
- selectedThreadKey: input.selectedThreadKey,
- isListedSettled: olderSettledShelf.isListed,
- unloadedSettledCount: olderSettledShelf.unloadedCount(
- threads.filter(
- (thread) =>
- thread.archivedAt === null &&
- scopes.some(
- (scope) =>
- scope.environmentId === thread.environmentId &&
- (scope.projectIds === null || scope.projectIds.includes(thread.projectId)),
+ const { isListed, unloadedCount } = olderSettledShelf;
+ const layout = useMemo(
+ () =>
+ buildThreadListV2Items({
+ pendingOrder: input.pendingOrder,
+ threads: threads.filter((thread) => thread.archivedAt === null),
+ environmentId: input.environmentId,
+ projectRefs: input.projectRefs,
+ searchQuery: input.searchQuery,
+ matchedThreadKeys: new Set(input.searchMatches.keys()),
+ settlementEnvironmentIds: input.settlementEnvironmentIds,
+ snoozeEnvironmentIds: input.snoozeEnvironmentIds,
+ queuedThreadKeys: input.queuedThreadKeys,
+ settledLimit: input.settledLimit,
+ now: layoutTime,
+ workingShelfEnabled,
+ workingShelfExpanded: input.workingShelfExpanded,
+ inboxReturnAt: inbox.returnedAt,
+ isWorking: inbox.isWorking,
+ snoozedShelfExpanded: input.snoozedShelfExpanded,
+ settledShelfExpanded: input.settledShelfExpanded,
+ selectedThreadKey: input.selectedThreadKey,
+ isListedSettled: isListed,
+ unloadedSettledCount: unloadedCount(
+ threads.filter(
+ (thread) =>
+ thread.archivedAt === null &&
+ scopes.some(
+ (scope) =>
+ scope.environmentId === thread.environmentId &&
+ (scope.projectIds === null || scope.projectIds.includes(thread.projectId)),
+ ),
),
- ),
- ),
- });
+ ),
+ }),
+ [
+ input.pendingOrder,
+ threads,
+ input.environmentId,
+ input.projectRefs,
+ input.searchQuery,
+ input.searchMatches,
+ input.settlementEnvironmentIds,
+ input.snoozeEnvironmentIds,
+ input.queuedThreadKeys,
+ input.settledLimit,
+ layoutTime,
+ workingShelfEnabled,
+ input.workingShelfExpanded,
+ inbox.returnedAt,
+ inbox.isWorking,
+ input.snoozedShelfExpanded,
+ input.settledShelfExpanded,
+ input.selectedThreadKey,
+ isListed,
+ unloadedCount,
+ scopes,
+ ],
+ );
useOlderSettledShelfGrowth(olderSettledShelf, layout.listedSettledThreads);
const contentOnlyThreadKeys = useKeySet([...layout.contentOnlyThreadKeys].sort().join("\n"));
- const scopedProjectKeys =
- input.projectRefs == null
- ? null
- : new Set(input.projectRefs.map((ref) => scopedProjectKey(ref.environmentId, ref.projectId)));
- const searchQuery = input.searchQuery.trim().toLocaleLowerCase();
- const pendingTasks = input.pendingTasks.filter(
- (pendingTask) =>
- (input.environmentId === null || pendingTask.environmentId === input.environmentId) &&
- (scopedProjectKeys === null ||
- scopedProjectKeys.has(
- scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
- )) &&
- (searchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(searchQuery)),
+ const pendingTasks = useMemo(() => {
+ const scopedProjectKeys =
+ input.projectRefs == null
+ ? null
+ : new Set(
+ input.projectRefs.map((ref) => scopedProjectKey(ref.environmentId, ref.projectId)),
+ );
+ const searchQuery = input.searchQuery.trim().toLocaleLowerCase();
+ return input.pendingTasks.filter(
+ (pendingTask) =>
+ (input.environmentId === null || pendingTask.environmentId === input.environmentId) &&
+ (scopedProjectKeys === null ||
+ scopedProjectKeys.has(
+ scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
+ )) &&
+ (searchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(searchQuery)),
+ );
+ }, [input.projectRefs, input.searchQuery, input.pendingTasks, input.environmentId]);
+ const items = useMemo(
+ () =>
+ buildThreadListV2ListItems({
+ items: layout.items,
+ pendingTasks,
+ workingCount: layout.workingCount,
+ workingShelfExpanded: input.workingShelfExpanded,
+ workingShelfHeaderIndex: layout.workingShelfHeaderIndex,
+ snoozedCount: layout.snoozedCount,
+ snoozedShelfExpanded: input.snoozedShelfExpanded,
+ snoozedShelfHeaderIndex: layout.snoozedShelfHeaderIndex,
+ settledCount: layout.settledCount,
+ settledShelfExpanded: input.settledShelfExpanded,
+ settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
+ snoozeLabelNow: `${input.now.slice(0, 16)}:00.000Z`,
+ snoozeEnvironmentIds: input.snoozeEnvironmentIds,
+ queuedThreadKeys: input.queuedThreadKeys,
+ moveAvailability,
+ shelfPreferencesLoading: !input.shelfPreferencesLoaded,
+ }),
+ [
+ layout,
+ pendingTasks,
+ input.workingShelfExpanded,
+ input.snoozedShelfExpanded,
+ input.settledShelfExpanded,
+ input.now,
+ input.snoozeEnvironmentIds,
+ input.queuedThreadKeys,
+ moveAvailability,
+ input.shelfPreferencesLoaded,
+ ],
);
- const items = buildThreadListV2ListItems({
- items: layout.items,
- pendingTasks,
- workingCount: layout.workingCount,
- workingShelfExpanded: input.workingShelfExpanded,
- workingShelfHeaderIndex: layout.workingShelfHeaderIndex,
- snoozedCount: layout.snoozedCount,
- snoozedShelfExpanded: input.snoozedShelfExpanded,
- snoozedShelfHeaderIndex: layout.snoozedShelfHeaderIndex,
- settledCount: layout.settledCount,
- settledShelfExpanded: input.settledShelfExpanded,
- settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
- snoozeLabelNow: `${input.now.slice(0, 16)}:00.000Z`,
- snoozeEnvironmentIds: input.snoozeEnvironmentIds,
- queuedThreadKeys: input.queuedThreadKeys,
- moveAvailability,
- shelfPreferencesLoading: !input.shelfPreferencesLoaded,
- });
return { layout, items, contentOnlyThreadKeys, olderSettledShelf };
}
diff --git a/apps/mobile/src/state/use-thread-outbox.test.ts b/apps/mobile/src/state/use-thread-outbox.test.ts
new file mode 100644
index 00000000000..ac4f6542f67
--- /dev/null
+++ b/apps/mobile/src/state/use-thread-outbox.test.ts
@@ -0,0 +1,80 @@
+import { CommandId, EnvironmentId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
+import { AtomRegistry } from "effect/reactivity";
+import { expect, it, vi } from "vite-plus/test";
+
+import type { QueuedThreadMessage } from "./thread-outbox-model";
+
+vi.mock("./thread-outbox", async () => {
+ const { Atom } = await import("effect/reactivity");
+ return {
+ threadOutboxManager: {
+ queuedMessagesByThreadKeyAtom: Atom.make<
+ Readonly<Record<string, ReadonlyArray<QueuedThreadMessage>>>
+ >({}).pipe(Atom.keepAlive),
+ },
+ };
+});
+vi.mock("./atom-registry", () => ({ appAtomRegistry: undefined }));
+vi.mock("./shell", () => ({ environmentShell: {} }));
+
+import { threadOutboxManager } from "./thread-outbox";
+import { queuedThreadKeysAtom } from "./use-thread-outbox";
+
+it("retains queue membership while chat lists are hidden and follows queued messages", () => {
+ const scheduled = new Set<() => void>();
+ const registry = AtomRegistry.make({
+ scheduleTask: (task) => {
+ scheduled.add(task);
+ return () => {
+ scheduled.delete(task);
+ };
+ },
+ });
+ using _registry = { [Symbol.dispose]: () => registry.dispose() };
+ const flush = () => {
+ for (const task of scheduled) {
+ scheduled.delete(task);
+ task();
+ }
+ };
+ const release = registry.mount(queuedThreadKeysAtom);
+ const initial = registry.get(queuedThreadKeysAtom);
+ expect([...initial]).toEqual([]);
+ release();
+ flush();
+ expect(registry.get(queuedThreadKeysAtom)).toBe(initial);
+
+ const message: QueuedThreadMessage = {
+ environmentId: EnvironmentId.make("environment-1"),
+ threadId: ThreadId.make("thread-1"),
+ messageId: MessageId.make("message-1"),
+ commandId: CommandId.make("command-1"),
+ text: "Follow up",
+ attachments: [],
+ createdAt: "2026-10-29T12:00:00.000Z",
+ };
+ registry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {
+ "environment-1:thread-1": [message],
+ "environment-1:new-thread": [
+ {
+ ...message,
+ threadId: ThreadId.make("new-thread"),
+ creation: {
+ projectId: ProjectId.make("project-1"),
+ workspaceMode: "local",
+ branch: null,
+ worktreePath: null,
+ },
+ },
+ ],
+ });
+ const queued = registry.get(queuedThreadKeysAtom);
+ expect([...queued]).toEqual(["environment-1:thread-1"]);
+ const releaseAgain = registry.mount(queuedThreadKeysAtom);
+ releaseAgain();
+ flush();
+ expect(registry.get(queuedThreadKeysAtom)).toBe(queued);
+
+ registry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
+ expect([...registry.get(queuedThreadKeysAtom)]).toEqual([]);
+});
diff --git a/apps/mobile/src/state/use-thread-outbox.ts b/apps/mobile/src/state/use-thread-outbox.ts
index a1128cbd08b..caffa99f8cf 100644
--- a/apps/mobile/src/state/use-thread-outbox.ts
+++ b/apps/mobile/src/state/use-thread-outbox.ts
@@ -63,7 +63,7 @@ export const queuedThreadKeysAtom = Atom.make((get): ReadonlySet<string> => {
}
}
return keys;
-}).pipe(Atom.withLabel("mobile:thread-outbox:queued-thread-keys"));
+}).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-outbox:queued-thread-keys"));
export function useQueuedThreadKeys(): ReadonlySet<string> {
return useAtomValue(queuedThreadKeysAtom);
diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts
index b64dc1c4e2a..2c4e89318c6 100644
--- a/apps/mobile/vite.config.ts
+++ b/apps/mobile/vite.config.ts
@@ -36,6 +36,7 @@ const reactTests = [
"src/state/use-selected-thread-git-state.test.tsx",
"src/features/terminal/useTerminalExitNavigation.test.tsx",
"src/features/threads/use-thread-list-now.test.tsx",
+ "src/features/threads/useThreadListV2.test.tsx",
"src/features/home/home-list-options.test.tsx",
"src/features/workspace/useSearchScrollRestoration.test.tsx",
"src/features/connection/ConnectionsNewRouteScreen.test.tsx",