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, 14:30 UTC
fix(mobile): a held thread move retires when a snooze wakes, even with no list open (#25809)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 27, 2026 at 02:13 UTC
03be432a5d8de7201cf46ca94100b45f4893278c
10 files changed
+177
-85
apps/mobile/src/features/home/HomeScreen.tsx
+3
-24
@@ -12,7 +12,6 @@ import {
12
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
13
import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
14
import { useAtomValue } from "@effect/atom-react";
15
-import { useFocusEffect } from "@react-navigation/native";
15
import { use, useEffect, useRef, useState, type ComponentProps } from "react";
16
import {
17
Platform,
@@ -51,6 +50,7 @@ import { useThreadSearch } from "../../state/queries";
50
import { requestThreadMessageJump } from "../threads/threadMessageJump";
51
import { useThreadListSearchMatches } from "../threads/useThreadListSearchMatches";
52
import { useThreadListV2 } from "../threads/useThreadListV2";
53
+import { useThreadListNow } from "../threads/use-thread-list-now";
54
import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
55
import { usePendingThreadOrder } from "../../state/thread-order";
56
import { threadListEnvironmentsAtom } from "../../state/server";
@@ -423,15 +423,7 @@ export function HomeScreen(props: HomeScreenProps) {
423
toggleSnoozedShelf,
424
toggleWorkingShelf,
425
} = useThreadListV2ShelfPreferences();
426
- // Keep time in state; the compiler would cache a render-time new Date().
427
- const [now, setNow] = useState(() => new Date().toISOString());
428
- const nowMinute = now.slice(0, 16);
429
- const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
430
- useFocusEffect(() => {
431
- setNow(new Date().toISOString());
432
- const id = setInterval(() => setNow(new Date().toISOString()), 60_000);
433
- return () => clearInterval(id);
434
- });
426
+ const now = useThreadListNow(props.threads);
427
const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
428
const {
429
providersByEnvironmentId,
@@ -445,7 +437,7 @@ export function HomeScreen(props: HomeScreenProps) {
437
titleRegenerationEnvironmentIds,
438
} = listEnvironments;
439
const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId);
448
- const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick);
440
+ const pendingOrder = usePendingThreadOrder();
441
const {
442
layout: threadListV2Layout,
443
items: threadListV2Items,
@@ -473,19 +465,6 @@ export function HomeScreen(props: HomeScreenProps) {
465
settledShelfExpanded,
466
selectedThreadKey,
467
});
476
- const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
477
- useEffect(() => {
478
- if (nextSnoozeWakeAt === null) return;
479
- const wakeAtMs = Date.parse(nextSnoozeWakeAt);
480
- if (Number.isNaN(wakeAtMs)) return;
481
- const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
482
- const id = setTimeout(() => {
483
- setNow(new Date().toISOString());
484
- bumpSnoozeWakeTick((tick) => tick + 1);
485
- }, delayMs);
486
- return () => clearTimeout(id);
487
- // 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.
488
- }, [nextSnoozeWakeAt, snoozeWakeTick]);
468
// Called as `props.onSelectThread(...)`, the compiler would cache this handler on the whole
469
// props object, which is new on every render of Home's parent.
470
const { onSelectThread } = props;
apps/mobile/src/features/threads/ThreadArrangementSheet.tsx
+2
-15
@@ -36,6 +36,7 @@ import {
36
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
37
threadListInboxReturns,
38
} from "./threadListV2";
39
+import { useThreadListNow } from "./use-thread-list-now";
40
import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
41
42
const ROW_HEIGHT = 56;
@@ -168,7 +169,7 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) {
169
const dropBusy = useAtomValue(threadDropBusyAtom);
170
const { moveThread } = useThreadListActions();
171
const { workingShelfEnabled } = useThreadListV2ShelfPreferences();
171
- const [now, setNow] = useState(() => new Date().toISOString());
172
+ const now = useThreadListNow(threads);
173
const [expanded, setExpanded] = useState({ snoozed: false, settled: false });
174
const [settledVisibleCount, setSettledVisibleCount] = useState(
175
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
@@ -179,20 +180,6 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) {
180
expanded: expanded.settled,
181
visibleCount: settledVisibleCount,
182
});
182
- useEffect(() => {
183
- const wakeAt = Math.min(
184
- ...threads.flatMap((thread) => {
185
- const at = Date.parse(thread.snoozedUntil ?? "");
186
- return at > Date.parse(now) ? [at] : [];
187
- }),
188
- );
189
- if (!Number.isFinite(wakeAt)) return;
190
- const timer = setTimeout(
191
- () => setNow(new Date().toISOString()),
192
- Math.min(Math.max(0, wakeAt - Date.now()) + 1, 2_147_483_647),
193
- );
194
- return () => clearTimeout(timer);
195
- }, [threads, now]);
183
const sections = useMemo(() => {
184
const shared = {
185
threads,
apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+3
-24
@@ -30,6 +30,7 @@ import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
30
import { useProjects, useNavigationThreadShells } from "../../state/entities";
31
import { useThreadSearch } from "../../state/queries";
32
import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
33
+import { useThreadListNow } from "./use-thread-list-now";
34
import { usePendingThreadOrder } from "../../state/thread-order";
35
import { threadListEnvironmentsAtom } from "../../state/server";
36
import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
@@ -269,16 +270,7 @@ function ThreadNavigationSidebarPane(
270
toggleSnoozedShelf,
271
toggleWorkingShelf,
272
} = useThreadListV2ShelfPreferences();
272
- // Keep time in state; the compiler would cache a render-time new Date().
273
- const [now, setNow] = useState(() => new Date().toISOString());
274
- const nowMinute = now.slice(0, 16);
275
- const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
276
- useEffect(() => {
277
- // oxlint-disable-next-line react/set-state-in-effect -- Refreshes the minute clock when the minute interval starts.
278
- setNow(new Date().toISOString());
279
- const id = setInterval(() => setNow(new Date().toISOString()), 60_000);
280
- return () => clearInterval(id);
281
- }, []);
273
+ const now = useThreadListNow(threads);
274
const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
275
const {
276
providersByEnvironmentId,
@@ -292,7 +284,7 @@ function ThreadNavigationSidebarPane(
284
titleRegenerationEnvironmentIds,
285
} = listEnvironments;
286
const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId);
295
- const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick);
287
+ const pendingOrder = usePendingThreadOrder();
288
const {
289
layout: threadListV2Layout,
290
items: threadListV2Items,
@@ -320,19 +312,6 @@ function ThreadNavigationSidebarPane(
312
settledShelfExpanded,
313
selectedThreadKey: props.selectedThreadKey ?? null,
314
});
323
- const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
324
- useEffect(() => {
325
- if (nextSnoozeWakeAt === null) return;
326
- const wakeAtMs = Date.parse(nextSnoozeWakeAt);
327
- if (Number.isNaN(wakeAtMs)) return;
328
- const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
329
- const id = setTimeout(() => {
330
- setNow(new Date().toISOString());
331
- bumpSnoozeWakeTick((tick) => tick + 1);
332
- }, delayMs);
333
- return () => clearTimeout(id);
334
- // 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.
335
- }, [nextSnoozeWakeAt, snoozeWakeTick]);
315
const listItems: readonly SidebarListItem[] =
316
settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0
317
? [
apps/mobile/src/features/threads/threadListV2.ts
+14
@@ -140,6 +140,20 @@ export function resolveThreadListV2SnoozeGateExpiryMs(
140
return messageAtMs + QUEUED_TURN_START_GRACE_MS;
141
}
142
143
+/** The earliest `snoozedUntil` strictly after `nowMs`, in epoch ms. */
144
+export function nextSnoozeWakeAfter(
145
+ threads: ReadonlyArray<{ readonly snoozedUntil?: string | null }>,
146
+ nowMs: number,
147
+): number | null {
148
+ let next: number | null = null;
149
+ for (const thread of threads) {
150
+ if (thread.snoozedUntil == null) continue;
151
+ const wakeAtMs = Date.parse(thread.snoozedUntil);
152
+ if (wakeAtMs > nowMs && (next === null || wakeAtMs < next)) next = wakeAtMs;
153
+ }
154
+ return next;
155
+}
156
+
157
export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
158
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
159
apps/mobile/src/features/threads/use-thread-list-now.test.tsx
new
+32
@@ -0,0 +1,32 @@
1
+import { act, useLayoutEffect } from "react";
2
+import { createRoot } from "react-dom/client";
3
+import { expect, it, vi } from "vite-plus/test";
4
+
5
+import { useThreadListNow } from "./use-thread-list-now";
6
+
7
+const MINUTE_MS = Date.UTC(2026, 9, 27, 12, 0);
8
+const iso = (secondsIntoMinute: number) =>
9
+ new Date(MINUTE_MS + secondsIntoMinute * 1000).toISOString();
10
+
11
+it("wakes for each snooze that expires within the same minute", async () => {
12
+ using _timers = { [Symbol.dispose]: () => vi.useRealTimers() };
13
+ vi.useFakeTimers({ now: MINUTE_MS + 10_000 });
14
+ const threads = [{ snoozedUntil: iso(30) }, { snoozedUntil: iso(40) }];
15
+ const seen: string[] = [];
16
+ function Probe() {
17
+ const now = useThreadListNow(threads);
18
+ useLayoutEffect(() => {
19
+ seen.push(now);
20
+ });
21
+ return null;
22
+ }
23
+
24
+ const root = createRoot(document.createElement("div"));
25
+ await act(async () => root.render(<Probe />));
26
+ await act(async () => vi.advanceTimersByTime(20_000));
27
+ expect(seen.at(-1)).toBe(iso(30));
28
+
29
+ await act(async () => vi.advanceTimersByTime(10_000));
30
+ expect(seen.at(-1)).toBe(iso(40));
31
+ act(() => root.unmount());
32
+});
apps/mobile/src/features/threads/use-thread-list-now.ts
new
+24
@@ -0,0 +1,24 @@
1
+import { useState } from "react";
2
+
3
+import { useNowAfter, useNowMinuteMs } from "../../lib/clock";
4
+import { nextSnoozeWakeAfter } from "./threadListV2";
5
+
6
+/**
7
+ * The thread list's clock as an ISO timestamp. It advances on each wall-clock
8
+ * minute and the moment any snooze expires, so the list re-partitions on time
9
+ * instead of on the next minute tick. Waking on every snoozed thread, not just
10
+ * the ones the list shows as snoozed, only costs an extra render.
11
+ */
12
+export function useThreadListNow(
13
+ threads: ReadonlyArray<{ readonly snoozedUntil?: string | null }>,
14
+): string {
15
+ const minuteMs = useNowMinuteMs();
16
+ // The latest time returned. The next wake is searched after it, not after
17
+ // the floored minute, so a second snooze expiring later in the same minute
18
+ // arms its own wake instead of waiting for the next minute tick.
19
+ const [latestMs, setLatestMs] = useState(minuteMs);
20
+ const afterWakeMs = useNowAfter(nextSnoozeWakeAfter(threads, Math.max(minuteMs, latestMs)));
21
+ const nowMs = Math.max(minuteMs, afterWakeMs, latestMs);
22
+ if (nowMs !== latestMs) setLatestMs(nowMs);
23
+ return new Date(nowMs).toISOString();
24
+}
apps/mobile/src/lib/clock.ts
+6
-7
@@ -13,13 +13,12 @@ export function useDeadlinePassed(deadlineMs: number | null): boolean {
13
*/
14
export function useNowAfter(deadlineMs: number | null): number {
15
const passed = useDeadlinePassed(deadlineMs);
16
- const [snapshot, setSnapshot] = useState(() => ({ deadlineMs, passed, nowMs: Date.now() }));
17
- if (snapshot.deadlineMs !== deadlineMs || snapshot.passed !== passed) {
18
- // oxlint-disable-next-line react/purity -- Re-reads the clock only in the render-phase adjustment that runs when the deadline changes or passes.
19
- const next = { deadlineMs, passed, nowMs: Date.now() };
20
- setSnapshot(next);
21
- return next.nowMs;
22
- }
16
+ const readNow = () => ({ deadlineMs, passed, nowMs: Date.now() });
17
+ const [snapshot, setSnapshot] = useState(readNow);
18
+ // The clock is read inside the updater: the compiler caches a bare
19
+ // `Date.now()` in render once per instance, so a later adjustment would reuse
20
+ // the first reading. React discards this render and re-runs with the update.
21
+ if (snapshot.deadlineMs !== deadlineMs || snapshot.passed !== passed) setSnapshot(readNow);
22
return snapshot.nowMs;
23
}
24
apps/mobile/src/state/thread-order.test.ts
+51
@@ -11,6 +11,7 @@ import {
11
getPendingThreadOrder,
12
pendingThreadOrderAtom,
13
} from "./thread-order";
14
+import { environmentServerConfigsAtom } from "./server";
15
import { environmentThreadShells } from "./threads";
16
17
vi.mock("./atom-registry", async () => {
@@ -30,6 +31,9 @@ vi.mock("./use-thread-outbox", async () => {
31
return { queuedThreadKeysAtom: Atom.make(new Set<string>()).pipe(Atom.keepAlive) };
32
});
33
34
+type ServerConfigs = Atom.Type<typeof environmentServerConfigsAtom>;
35
+type ServerConfig = ServerConfigs extends ReadonlyMap<EnvironmentId, infer Config> ? Config : never;
36
+const configsAtom = environmentServerConfigsAtom as Atom.Writable<ServerConfigs, ServerConfigs>;
37
const shellsAtom = environmentThreadShells.threadShellsAtom as Atom.Writable<
38
readonly EnvironmentThreadShell[],
39
readonly EnvironmentThreadShell[]
@@ -113,4 +117,51 @@ describe("shared mobile pending move", () => {
117
appAtomRegistry.set(shellsAtom, rows);
118
expect(getPendingThreadOrder()).toBeNull();
119
});
120
+
121
+ it("retires the hold when a snooze expiry changes the section without a shell event", () => {
122
+ vi.useFakeTimers();
123
+ try {
124
+ vi.setSystemTime(new Date("2026-06-01T03:00:00.000Z"));
125
+ const { rows, start } = fixture();
126
+ // Only the snooze capability matters to the section filter; afterEach's
127
+ // registry reset restores the empty configs.
128
+ const config = { environment: { capabilities: { threadSnooze: true } } } as ServerConfig;
129
+ appAtomRegistry.set(configsAtom, new Map([[EnvironmentId.make("env"), config]]));
130
+ const snoozed = makeThreadShellFixture({
131
+ id: ThreadId.make("c"),
132
+ environmentId: EnvironmentId.make("env"),
133
+ createdAt: "2026-06-01T00:00:00.000Z",
134
+ snoozedUntil: "2026-06-01T03:00:05.000Z",
135
+ });
136
+ appAtomRegistry.set(shellsAtom, [...rows, snoozed]);
137
+ start();
138
+ expect(getPendingThreadOrder()).not.toBeNull();
139
+
140
+ vi.advanceTimersByTime(5_000);
141
+
142
+ expect(appAtomRegistry.get(pendingThreadOrderAtom)).toBeNull();
143
+ } finally {
144
+ vi.useRealTimers();
145
+ }
146
+ });
147
+
148
+ it("tears down a superseded hold's clocks when another hold begins", () => {
149
+ vi.useFakeTimers();
150
+ try {
151
+ vi.setSystemTime(new Date("2026-06-01T03:00:00.000Z"));
152
+ const { rows, start } = fixture();
153
+ const snoozed = makeThreadShellFixture({
154
+ id: ThreadId.make("c"),
155
+ environmentId: EnvironmentId.make("env"),
156
+ createdAt: "2026-06-01T00:00:00.000Z",
157
+ snoozedUntil: "2026-06-01T04:00:00.000Z",
158
+ });
159
+ appAtomRegistry.set(shellsAtom, [...rows, snoozed]);
160
+ start();
161
+ start().cancel();
162
+ expect(vi.getTimerCount()).toBe(0);
163
+ } finally {
164
+ vi.useRealTimers();
165
+ }
166
+ });
167
});
apps/mobile/src/state/thread-order.ts
+41
-15
@@ -1,12 +1,15 @@
1
import { useAtomValue } from "@effect/atom-react";
2
-import { useEffect } from "react";
2
+import { deadlineStore, minuteTick } from "@t3tools/client-runtime/clock";
3
import { Atom } from "effect/reactivity";
4
5
import {
6
reconcilePendingThreadOrder,
7
type PendingThreadOrder,
8
} from "../features/threads/threadOrder";
9
-import { getThreadListV2OrderedSection } from "../features/threads/threadListV2";
9
+import {
10
+ getThreadListV2OrderedSection,
11
+ nextSnoozeWakeAfter,
12
+} from "../features/threads/threadListV2";
13
import { appAtomRegistry } from "./atom-registry";
14
import { environmentServerConfigsAtom } from "./server";
15
import { environmentThreadShells } from "./threads";
@@ -20,17 +23,14 @@ export const pendingThreadOrderAtom = Atom.make<PendingThreadOrder | null>(null)
23
Atom.keepAlive,
24
);
25
23
-export function usePendingThreadOrder(nowMinute: string, snoozeWakeTick: number) {
24
- const pending = useAtomValue(pendingThreadOrderAtom);
25
- // Clock-driven wakes can change membership without shell events; retire order holds and re-enable moves then.
26
- useEffect(() => {
27
- getPendingThreadOrder();
28
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Clock ticks re-evaluate the external pending-order snapshot even without a shell event.
29
- }, [nowMinute, snoozeWakeTick]);
30
- return pending;
26
+export function usePendingThreadOrder() {
27
+ return useAtomValue(pendingThreadOrderAtom);
28
}
29
30
let refreshPendingOrder: (() => void) | undefined;
31
+// Only one hold is live at a time; starting another tears down the previous
32
+// hold's subscriptions so its clocks and listeners do not outlive it.
33
+let teardownPendingOrder: (() => void) | undefined;
34
35
export function getPendingThreadOrder(): PendingThreadOrder | null {
36
refreshPendingOrder?.();
@@ -39,10 +39,24 @@ export function getPendingThreadOrder(): PendingThreadOrder | null {
39
40
export function beginPendingThreadOrder(pending: PendingThreadOrder) {
41
const unsubscribers: (() => void)[] = [];
42
+ // A timed wake can change section membership without a shell event, so the
43
+ // hold also re-checks on each minute and at the next snooze expiry.
44
+ let wake: { readonly atMs: number | null; readonly unsubscribe: () => void } | null = null;
45
+ const armWake = (atMs: number | null) => {
46
+ if (wake?.atMs === atMs) return;
47
+ wake?.unsubscribe();
48
+ wake = { atMs, unsubscribe: deadlineStore(atMs).subscribe(refresh) };
49
+ };
50
+ const teardown = () => {
51
+ for (const unsubscribe of unsubscribers.splice(0)) unsubscribe();
52
+ wake?.unsubscribe();
53
+ wake = null;
54
+ };
55
const cancel = () => {
56
if (refreshPendingOrder !== refresh) return;
57
refreshPendingOrder = undefined;
45
- for (const unsubscribe of unsubscribers) unsubscribe();
58
+ teardownPendingOrder = undefined;
59
+ teardown();
60
appAtomRegistry.set(pendingThreadOrderAtom, null);
61
};
62
const refresh = () => {
@@ -50,10 +64,12 @@ export function beginPendingThreadOrder(pending: PendingThreadOrder) {
64
const current = appAtomRegistry.get(pendingThreadOrderAtom);
65
if (current === null) return;
66
const configs = appAtomRegistry.get(environmentServerConfigsAtom);
67
+ const threads = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
68
+ const nowMs = Date.now();
69
const ordered = getThreadListV2OrderedSection({
54
- threads: appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
70
+ threads,
71
section: current.section,
56
- now: new Date().toISOString(),
72
+ now: new Date(nowMs).toISOString(),
73
queuedThreadKeys: appAtomRegistry.get(queuedThreadKeysAtom),
74
settlementEnvironmentIds: new Set(
75
[...configs].flatMap(([id, config]) =>
@@ -67,15 +83,25 @@ export function beginPendingThreadOrder(pending: PendingThreadOrder) {
83
),
84
});
85
const next = reconcilePendingThreadOrder(current, ordered);
70
- if (next === null) cancel();
71
- else if (next !== current) appAtomRegistry.set(pendingThreadOrderAtom, next);
86
+ if (next === null) {
87
+ cancel();
88
+ return;
89
+ }
90
+ if (next !== current) appAtomRegistry.set(pendingThreadOrderAtom, next);
91
+ armWake(nextSnoozeWakeAfter(threads, nowMs));
92
};
93
+ teardownPendingOrder?.();
94
refreshPendingOrder = refresh;
95
+ teardownPendingOrder = teardown;
96
appAtomRegistry.set(pendingThreadOrderAtom, pending);
97
unsubscribers.push(
98
appAtomRegistry.subscribe(environmentThreadShells.threadShellsAtom, refresh),
99
appAtomRegistry.subscribe(environmentServerConfigsAtom, refresh),
100
appAtomRegistry.subscribe(queuedThreadKeysAtom, refresh),
101
+ minuteTick.subscribe(refresh),
102
+ );
103
+ armWake(
104
+ nextSnoozeWakeAfter(appAtomRegistry.get(environmentThreadShells.threadShellsAtom), Date.now()),
105
);
106
return {
107
isPending: () => {
apps/mobile/vite.config.ts
+1
@@ -25,6 +25,7 @@ const reactTests = [
25
"src/state/queries.debounce.test.tsx",
26
"src/state/use-selected-thread-git-actions.test.tsx",
27
"src/features/terminal/useTerminalExitNavigation.test.tsx",
28
+ "src/features/threads/use-thread-list-now.test.tsx",
29
];
30
31
const sourceRoot = `${normalizePath(NodeURL.fileURLToPath(new URL("./src", import.meta.url)))}/`;