Skip to content
TypeScript

fix(mobile): a held thread move retires when a snooze wakes, even with no list open (#25809)

Julius Marminge03be432a5d8d
diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx
index e9a71f2c253..37de121c31f 100644
--- a/apps/mobile/src/features/home/HomeScreen.tsx
+++ b/apps/mobile/src/features/home/HomeScreen.tsx
@@ -12,7 +12,6 @@ import {
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
-import { useFocusEffect } from "@react-navigation/native";
import { use, useEffect, useRef, useState, type ComponentProps } from "react";
import {
Platform,
@@ -51,6 +50,7 @@ import { useThreadSearch } from "../../state/queries";
import { requestThreadMessageJump } from "../threads/threadMessageJump";
import { useThreadListSearchMatches } from "../threads/useThreadListSearchMatches";
import { useThreadListV2 } from "../threads/useThreadListV2";
+import { useThreadListNow } from "../threads/use-thread-list-now";
import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
import { usePendingThreadOrder } from "../../state/thread-order";
import { threadListEnvironmentsAtom } from "../../state/server";
@@ -423,15 +423,7 @@ export function HomeScreen(props: HomeScreenProps) {
toggleSnoozedShelf,
toggleWorkingShelf,
} = useThreadListV2ShelfPreferences();
- // Keep time in state; the compiler would cache a render-time new Date().
- const [now, setNow] = useState(() => new Date().toISOString());
- const nowMinute = now.slice(0, 16);
- const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
- useFocusEffect(() => {
- setNow(new Date().toISOString());
- const id = setInterval(() => setNow(new Date().toISOString()), 60_000);
- return () => clearInterval(id);
- });
+ const now = useThreadListNow(props.threads);
const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
const {
providersByEnvironmentId,
@@ -445,7 +437,7 @@ export function HomeScreen(props: HomeScreenProps) {
titleRegenerationEnvironmentIds,
} = listEnvironments;
const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId);
- const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick);
+ const pendingOrder = usePendingThreadOrder();
const {
layout: threadListV2Layout,
items: threadListV2Items,
@@ -473,19 +465,6 @@ export function HomeScreen(props: HomeScreenProps) {
settledShelfExpanded,
selectedThreadKey,
});
- const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
- useEffect(() => {
- if (nextSnoozeWakeAt === null) return;
- const wakeAtMs = Date.parse(nextSnoozeWakeAt);
- if (Number.isNaN(wakeAtMs)) return;
- const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
- const id = setTimeout(() => {
- setNow(new Date().toISOString());
- bumpSnoozeWakeTick((tick) => tick + 1);
- }, delayMs);
- return () => clearTimeout(id);
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- snoozeWakeTick re-arms clamped timers even when the wake date exceeds 32-bit setTimeout and stays unchanged.
- }, [nextSnoozeWakeAt, snoozeWakeTick]);
// Called as `props.onSelectThread(...)`, the compiler would cache this handler on the whole
// props object, which is new on every render of Home's parent.
const { onSelectThread } = props;
diff --git a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx
index ff8865e166b..2fbb2b52520 100644
--- a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx
+++ b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx
@@ -36,6 +36,7 @@ import {
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
threadListInboxReturns,
} from "./threadListV2";
+import { useThreadListNow } from "./use-thread-list-now";
import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
const ROW_HEIGHT = 56;
@@ -168,7 +169,7 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) {
const dropBusy = useAtomValue(threadDropBusyAtom);
const { moveThread } = useThreadListActions();
const { workingShelfEnabled } = useThreadListV2ShelfPreferences();
- const [now, setNow] = useState(() => new Date().toISOString());
+ const now = useThreadListNow(threads);
const [expanded, setExpanded] = useState({ snoozed: false, settled: false });
const [settledVisibleCount, setSettledVisibleCount] = useState(
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
@@ -179,20 +180,6 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) {
expanded: expanded.settled,
visibleCount: settledVisibleCount,
});
- useEffect(() => {
- const wakeAt = Math.min(
- ...threads.flatMap((thread) => {
- const at = Date.parse(thread.snoozedUntil ?? "");
- return at > Date.parse(now) ? [at] : [];
- }),
- );
- if (!Number.isFinite(wakeAt)) return;
- const timer = setTimeout(
- () => setNow(new Date().toISOString()),
- Math.min(Math.max(0, wakeAt - Date.now()) + 1, 2_147_483_647),
- );
- return () => clearTimeout(timer);
- }, [threads, now]);
const sections = useMemo(() => {
const shared = {
threads,
diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
index ce5ad0b6e8f..cd2499e2969 100644
--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
@@ -30,6 +30,7 @@ import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
import { useProjects, useNavigationThreadShells } from "../../state/entities";
import { useThreadSearch } from "../../state/queries";
import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
+import { useThreadListNow } from "./use-thread-list-now";
import { usePendingThreadOrder } from "../../state/thread-order";
import { threadListEnvironmentsAtom } from "../../state/server";
import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
@@ -269,16 +270,7 @@ function ThreadNavigationSidebarPane(
toggleSnoozedShelf,
toggleWorkingShelf,
} = useThreadListV2ShelfPreferences();
- // Keep time in state; the compiler would cache a render-time new Date().
- const [now, setNow] = useState(() => new Date().toISOString());
- const nowMinute = now.slice(0, 16);
- const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
- useEffect(() => {
- // oxlint-disable-next-line react/set-state-in-effect -- Refreshes the minute clock when the minute interval starts.
- setNow(new Date().toISOString());
- const id = setInterval(() => setNow(new Date().toISOString()), 60_000);
- return () => clearInterval(id);
- }, []);
+ const now = useThreadListNow(threads);
const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
const {
providersByEnvironmentId,
@@ -292,7 +284,7 @@ function ThreadNavigationSidebarPane(
titleRegenerationEnvironmentIds,
} = listEnvironments;
const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId);
- const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick);
+ const pendingOrder = usePendingThreadOrder();
const {
layout: threadListV2Layout,
items: threadListV2Items,
@@ -320,19 +312,6 @@ function ThreadNavigationSidebarPane(
settledShelfExpanded,
selectedThreadKey: props.selectedThreadKey ?? null,
});
- const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
- useEffect(() => {
- if (nextSnoozeWakeAt === null) return;
- const wakeAtMs = Date.parse(nextSnoozeWakeAt);
- if (Number.isNaN(wakeAtMs)) return;
- const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
- const id = setTimeout(() => {
- setNow(new Date().toISOString());
- bumpSnoozeWakeTick((tick) => tick + 1);
- }, delayMs);
- return () => clearTimeout(id);
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- snoozeWakeTick re-arms clamped timers even when the wake date exceeds 32-bit setTimeout and stays unchanged.
- }, [nextSnoozeWakeAt, snoozeWakeTick]);
const listItems: readonly SidebarListItem[] =
settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0
? [
diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts
index d72ab913dec..9adc18e7174 100644
--- a/apps/mobile/src/features/threads/threadListV2.ts
+++ b/apps/mobile/src/features/threads/threadListV2.ts
@@ -140,6 +140,20 @@ export function resolveThreadListV2SnoozeGateExpiryMs(
return messageAtMs + QUEUED_TURN_START_GRACE_MS;
}
+/** The earliest `snoozedUntil` strictly after `nowMs`, in epoch ms. */
+export function nextSnoozeWakeAfter(
+ threads: ReadonlyArray<{ readonly snoozedUntil?: string | null }>,
+ nowMs: number,
+): number | null {
+ let next: number | null = null;
+ for (const thread of threads) {
+ if (thread.snoozedUntil == null) continue;
+ const wakeAtMs = Date.parse(thread.snoozedUntil);
+ if (wakeAtMs > nowMs && (next === null || wakeAtMs < next)) next = wakeAtMs;
+ }
+ return next;
+}
+
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/use-thread-list-now.test.tsx b/apps/mobile/src/features/threads/use-thread-list-now.test.tsx
new file mode 100644
index 00000000000..ac4e9ce0c6d
--- /dev/null
+++ b/apps/mobile/src/features/threads/use-thread-list-now.test.tsx
@@ -0,0 +1,32 @@
+import { act, useLayoutEffect } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it, vi } from "vite-plus/test";
+
+import { useThreadListNow } from "./use-thread-list-now";
+
+const MINUTE_MS = Date.UTC(2026, 9, 27, 12, 0);
+const iso = (secondsIntoMinute: number) =>
+ new Date(MINUTE_MS + secondsIntoMinute * 1000).toISOString();
+
+it("wakes for each snooze that expires within the same minute", async () => {
+ using _timers = { [Symbol.dispose]: () => vi.useRealTimers() };
+ vi.useFakeTimers({ now: MINUTE_MS + 10_000 });
+ const threads = [{ snoozedUntil: iso(30) }, { snoozedUntil: iso(40) }];
+ const seen: string[] = [];
+ function Probe() {
+ const now = useThreadListNow(threads);
+ useLayoutEffect(() => {
+ seen.push(now);
+ });
+ return null;
+ }
+
+ const root = createRoot(document.createElement("div"));
+ await act(async () => root.render(<Probe />));
+ await act(async () => vi.advanceTimersByTime(20_000));
+ expect(seen.at(-1)).toBe(iso(30));
+
+ await act(async () => vi.advanceTimersByTime(10_000));
+ expect(seen.at(-1)).toBe(iso(40));
+ act(() => root.unmount());
+});
diff --git a/apps/mobile/src/features/threads/use-thread-list-now.ts b/apps/mobile/src/features/threads/use-thread-list-now.ts
new file mode 100644
index 00000000000..4a17a7fe843
--- /dev/null
+++ b/apps/mobile/src/features/threads/use-thread-list-now.ts
@@ -0,0 +1,24 @@
+import { useState } from "react";
+
+import { useNowAfter, useNowMinuteMs } from "../../lib/clock";
+import { nextSnoozeWakeAfter } from "./threadListV2";
+
+/**
+ * The thread list's clock as an ISO timestamp. It advances on each wall-clock
+ * minute and the moment any snooze expires, so the list re-partitions on time
+ * instead of on the next minute tick. Waking on every snoozed thread, not just
+ * the ones the list shows as snoozed, only costs an extra render.
+ */
+export function useThreadListNow(
+ threads: ReadonlyArray<{ readonly snoozedUntil?: string | null }>,
+): string {
+ const minuteMs = useNowMinuteMs();
+ // The latest time returned. The next wake is searched after it, not after
+ // the floored minute, so a second snooze expiring later in the same minute
+ // arms its own wake instead of waiting for the next minute tick.
+ const [latestMs, setLatestMs] = useState(minuteMs);
+ const afterWakeMs = useNowAfter(nextSnoozeWakeAfter(threads, Math.max(minuteMs, latestMs)));
+ const nowMs = Math.max(minuteMs, afterWakeMs, latestMs);
+ if (nowMs !== latestMs) setLatestMs(nowMs);
+ return new Date(nowMs).toISOString();
+}
diff --git a/apps/mobile/src/lib/clock.ts b/apps/mobile/src/lib/clock.ts
index 6d33a93148c..58dc38cfd5f 100644
--- a/apps/mobile/src/lib/clock.ts
+++ b/apps/mobile/src/lib/clock.ts
@@ -13,13 +13,12 @@ export function useDeadlinePassed(deadlineMs: number | null): boolean {
*/
export function useNowAfter(deadlineMs: number | null): number {
const passed = useDeadlinePassed(deadlineMs);
- const [snapshot, setSnapshot] = useState(() => ({ deadlineMs, passed, nowMs: Date.now() }));
- if (snapshot.deadlineMs !== deadlineMs || snapshot.passed !== passed) {
- // oxlint-disable-next-line react/purity -- Re-reads the clock only in the render-phase adjustment that runs when the deadline changes or passes.
- const next = { deadlineMs, passed, nowMs: Date.now() };
- setSnapshot(next);
- return next.nowMs;
- }
+ const readNow = () => ({ deadlineMs, passed, nowMs: Date.now() });
+ const [snapshot, setSnapshot] = useState(readNow);
+ // The clock is read inside the updater: the compiler caches a bare
+ // `Date.now()` in render once per instance, so a later adjustment would reuse
+ // the first reading. React discards this render and re-runs with the update.
+ if (snapshot.deadlineMs !== deadlineMs || snapshot.passed !== passed) setSnapshot(readNow);
return snapshot.nowMs;
}
diff --git a/apps/mobile/src/state/thread-order.test.ts b/apps/mobile/src/state/thread-order.test.ts
index cf5a59b052b..6c8bec1454b 100644
--- a/apps/mobile/src/state/thread-order.test.ts
+++ b/apps/mobile/src/state/thread-order.test.ts
@@ -11,6 +11,7 @@ import {
getPendingThreadOrder,
pendingThreadOrderAtom,
} from "./thread-order";
+import { environmentServerConfigsAtom } from "./server";
import { environmentThreadShells } from "./threads";
vi.mock("./atom-registry", async () => {
@@ -30,6 +31,9 @@ vi.mock("./use-thread-outbox", async () => {
return { queuedThreadKeysAtom: Atom.make(new Set<string>()).pipe(Atom.keepAlive) };
});
+type ServerConfigs = Atom.Type<typeof environmentServerConfigsAtom>;
+type ServerConfig = ServerConfigs extends ReadonlyMap<EnvironmentId, infer Config> ? Config : never;
+const configsAtom = environmentServerConfigsAtom as Atom.Writable<ServerConfigs, ServerConfigs>;
const shellsAtom = environmentThreadShells.threadShellsAtom as Atom.Writable<
readonly EnvironmentThreadShell[],
readonly EnvironmentThreadShell[]
@@ -113,4 +117,51 @@ describe("shared mobile pending move", () => {
appAtomRegistry.set(shellsAtom, rows);
expect(getPendingThreadOrder()).toBeNull();
});
+
+ it("retires the hold when a snooze expiry changes the section without a shell event", () => {
+ vi.useFakeTimers();
+ try {
+ vi.setSystemTime(new Date("2026-06-01T03:00:00.000Z"));
+ const { rows, start } = fixture();
+ // Only the snooze capability matters to the section filter; afterEach's
+ // registry reset restores the empty configs.
+ const config = { environment: { capabilities: { threadSnooze: true } } } as ServerConfig;
+ appAtomRegistry.set(configsAtom, new Map([[EnvironmentId.make("env"), config]]));
+ const snoozed = makeThreadShellFixture({
+ id: ThreadId.make("c"),
+ environmentId: EnvironmentId.make("env"),
+ createdAt: "2026-06-01T00:00:00.000Z",
+ snoozedUntil: "2026-06-01T03:00:05.000Z",
+ });
+ appAtomRegistry.set(shellsAtom, [...rows, snoozed]);
+ start();
+ expect(getPendingThreadOrder()).not.toBeNull();
+
+ vi.advanceTimersByTime(5_000);
+
+ expect(appAtomRegistry.get(pendingThreadOrderAtom)).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("tears down a superseded hold's clocks when another hold begins", () => {
+ vi.useFakeTimers();
+ try {
+ vi.setSystemTime(new Date("2026-06-01T03:00:00.000Z"));
+ const { rows, start } = fixture();
+ const snoozed = makeThreadShellFixture({
+ id: ThreadId.make("c"),
+ environmentId: EnvironmentId.make("env"),
+ createdAt: "2026-06-01T00:00:00.000Z",
+ snoozedUntil: "2026-06-01T04:00:00.000Z",
+ });
+ appAtomRegistry.set(shellsAtom, [...rows, snoozed]);
+ start();
+ start().cancel();
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
});
diff --git a/apps/mobile/src/state/thread-order.ts b/apps/mobile/src/state/thread-order.ts
index e17ab7231c6..730797dac1b 100644
--- a/apps/mobile/src/state/thread-order.ts
+++ b/apps/mobile/src/state/thread-order.ts
@@ -1,12 +1,15 @@
import { useAtomValue } from "@effect/atom-react";
-import { useEffect } from "react";
+import { deadlineStore, minuteTick } from "@t3tools/client-runtime/clock";
import { Atom } from "effect/reactivity";
import {
reconcilePendingThreadOrder,
type PendingThreadOrder,
} from "../features/threads/threadOrder";
-import { getThreadListV2OrderedSection } from "../features/threads/threadListV2";
+import {
+ getThreadListV2OrderedSection,
+ nextSnoozeWakeAfter,
+} from "../features/threads/threadListV2";
import { appAtomRegistry } from "./atom-registry";
import { environmentServerConfigsAtom } from "./server";
import { environmentThreadShells } from "./threads";
@@ -20,17 +23,14 @@ export const pendingThreadOrderAtom = Atom.make<PendingThreadOrder | null>(null)
Atom.keepAlive,
);
-export function usePendingThreadOrder(nowMinute: string, snoozeWakeTick: number) {
- const pending = useAtomValue(pendingThreadOrderAtom);
- // Clock-driven wakes can change membership without shell events; retire order holds and re-enable moves then.
- useEffect(() => {
- getPendingThreadOrder();
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Clock ticks re-evaluate the external pending-order snapshot even without a shell event.
- }, [nowMinute, snoozeWakeTick]);
- return pending;
+export function usePendingThreadOrder() {
+ return useAtomValue(pendingThreadOrderAtom);
}
let refreshPendingOrder: (() => void) | undefined;
+// Only one hold is live at a time; starting another tears down the previous
+// hold's subscriptions so its clocks and listeners do not outlive it.
+let teardownPendingOrder: (() => void) | undefined;
export function getPendingThreadOrder(): PendingThreadOrder | null {
refreshPendingOrder?.();
@@ -39,10 +39,24 @@ export function getPendingThreadOrder(): PendingThreadOrder | null {
export function beginPendingThreadOrder(pending: PendingThreadOrder) {
const unsubscribers: (() => void)[] = [];
+ // A timed wake can change section membership without a shell event, so the
+ // hold also re-checks on each minute and at the next snooze expiry.
+ let wake: { readonly atMs: number | null; readonly unsubscribe: () => void } | null = null;
+ const armWake = (atMs: number | null) => {
+ if (wake?.atMs === atMs) return;
+ wake?.unsubscribe();
+ wake = { atMs, unsubscribe: deadlineStore(atMs).subscribe(refresh) };
+ };
+ const teardown = () => {
+ for (const unsubscribe of unsubscribers.splice(0)) unsubscribe();
+ wake?.unsubscribe();
+ wake = null;
+ };
const cancel = () => {
if (refreshPendingOrder !== refresh) return;
refreshPendingOrder = undefined;
- for (const unsubscribe of unsubscribers) unsubscribe();
+ teardownPendingOrder = undefined;
+ teardown();
appAtomRegistry.set(pendingThreadOrderAtom, null);
};
const refresh = () => {
@@ -50,10 +64,12 @@ export function beginPendingThreadOrder(pending: PendingThreadOrder) {
const current = appAtomRegistry.get(pendingThreadOrderAtom);
if (current === null) return;
const configs = appAtomRegistry.get(environmentServerConfigsAtom);
+ const threads = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
+ const nowMs = Date.now();
const ordered = getThreadListV2OrderedSection({
- threads: appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
+ threads,
section: current.section,
- now: new Date().toISOString(),
+ now: new Date(nowMs).toISOString(),
queuedThreadKeys: appAtomRegistry.get(queuedThreadKeysAtom),
settlementEnvironmentIds: new Set(
[...configs].flatMap(([id, config]) =>
@@ -67,15 +83,25 @@ export function beginPendingThreadOrder(pending: PendingThreadOrder) {
),
});
const next = reconcilePendingThreadOrder(current, ordered);
- if (next === null) cancel();
- else if (next !== current) appAtomRegistry.set(pendingThreadOrderAtom, next);
+ if (next === null) {
+ cancel();
+ return;
+ }
+ if (next !== current) appAtomRegistry.set(pendingThreadOrderAtom, next);
+ armWake(nextSnoozeWakeAfter(threads, nowMs));
};
+ teardownPendingOrder?.();
refreshPendingOrder = refresh;
+ teardownPendingOrder = teardown;
appAtomRegistry.set(pendingThreadOrderAtom, pending);
unsubscribers.push(
appAtomRegistry.subscribe(environmentThreadShells.threadShellsAtom, refresh),
appAtomRegistry.subscribe(environmentServerConfigsAtom, refresh),
appAtomRegistry.subscribe(queuedThreadKeysAtom, refresh),
+ minuteTick.subscribe(refresh),
+ );
+ armWake(
+ nextSnoozeWakeAfter(appAtomRegistry.get(environmentThreadShells.threadShellsAtom), Date.now()),
);
return {
isPending: () => {
diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts
index e1509e98e11..28c1aeee58b 100644
--- a/apps/mobile/vite.config.ts
+++ b/apps/mobile/vite.config.ts
@@ -25,6 +25,7 @@ const reactTests = [
"src/state/queries.debounce.test.tsx",
"src/state/use-selected-thread-git-actions.test.tsx",
"src/features/terminal/useTerminalExitNavigation.test.tsx",
+ "src/features/threads/use-thread-list-now.test.tsx",
];
const sourceRoot = `${normalizePath(NodeURL.fileURLToPath(new URL("./src", import.meta.url)))}/`;