The best way to control Claude Code, Codex and more from any computer or phone
fix(client): usage-limit Snooze disables at reset even weeks away, via a shared deadline clock (#25005)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 17:24 UTC
03df289735527354a500c8e8cf371c11d4c75d3c
15 files changed
+557
-199
apps/mobile/src/features/threads/UsageLimitRecoveryCard.test.tsx
new
+66
@@ -0,0 +1,66 @@
1
+import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2
+import type { EnvironmentId } from "@t3tools/contracts";
3
+import type { ReactNode } from "react";
4
+import { act } from "react";
5
+import { createRoot } from "react-dom/client";
6
+import { describe, expect, it, vi } from "vite-plus/test";
7
+
8
+type ButtonProps = { label: string; disabled?: boolean; onPress: () => void };
9
+
10
+vi.mock("react-native", () => ({
11
+ View: ({ children }: { children: ReactNode }) => <div>{children}</div>,
12
+}));
13
+vi.mock("../../components/ui/AppText", () => ({
14
+ AppText: ({ children }: { children: ReactNode }) => <span>{children}</span>,
15
+}));
16
+vi.mock("../../components/ui/Button", () => ({
17
+ Button: ({ label, disabled, onPress }: ButtonProps) => (
18
+ <button type="button" disabled={disabled} onClick={onPress}>
19
+ {label}
20
+ </button>
21
+ ),
22
+}));
23
+vi.mock("../../state/threads", () => ({ threadEnvironment: { updateMetadata: {} } }));
24
+vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
25
+
26
+import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard";
27
+
28
+const DAY_MS = 24 * 60 * 60 * 1000;
29
+
30
+function failedThread(resetAt: string): EnvironmentThreadShell {
31
+ return {
32
+ id: "thread-1",
33
+ updatedAt: new Date(0).toISOString(),
34
+ snoozedUntil: null,
35
+ latestRun: { runId: "run-1", completedAt: new Date(0).toISOString() },
36
+ limitRecovery: null,
37
+ runtime: { status: "failed", lastErrorClass: "usage_limit", usageLimitResetAt: resetAt },
38
+ } as unknown as EnvironmentThreadShell;
39
+}
40
+
41
+describe("UsageLimitRecoveryCard", () => {
42
+ it("disables Snooze once a reset more than 24.8 days away passes", () => {
43
+ using _timers = { [Symbol.dispose]: () => vi.useRealTimers() };
44
+ vi.useFakeTimers({ now: 0 });
45
+ const container = document.createElement("div");
46
+ const root = createRoot(container);
47
+ using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
48
+ act(() =>
49
+ root.render(
50
+ <UsageLimitRecoveryCard
51
+ thread={failedThread(new Date(30 * DAY_MS).toISOString())}
52
+ environmentId={"env-1" as EnvironmentId}
53
+ />,
54
+ ),
55
+ );
56
+ const snooze = () =>
57
+ [...container.querySelectorAll("button")].find(
58
+ (button) => button.textContent === "Snooze until reset",
59
+ );
60
+ expect(snooze()?.disabled).toBe(false);
61
+
62
+ act(() => vi.advanceTimersByTime(30 * DAY_MS));
63
+
64
+ expect(snooze()?.disabled).toBe(true);
65
+ });
66
+});
apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx
+3
-18
@@ -4,9 +4,10 @@ import { AsyncResult } from "effect/reactivity";
4
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
5
import type { EnvironmentId } from "@t3tools/contracts";
6
import * as DateTime from "effect/DateTime";
7
-import { useEffect, useState } from "react";
7
+import { useState } from "react";
8
import { View } from "react-native";
9
import { AppText as Text } from "../../components/ui/AppText";
10
+import { useDeadlinePassed } from "../../lib/clock";
11
import { threadEnvironment } from "../../state/threads";
12
import { useAtomCommand } from "../../state/use-atom-command";
13
@@ -24,23 +25,7 @@ export function UsageLimitRecoveryCard({
25
const canSchedule =
26
resetAt !== null &&
27
Date.parse(resetAt) > Date.parse(thread.latestRun?.completedAt ?? thread.updatedAt);
27
- // Use timer-driven state; the compiler can cache render-time clock reads and leave Snooze enabled after reset.
28
- const resetAtMs = resetAt === null ? null : Date.parse(resetAt);
29
- const [resetPassedFor, setResetPassedFor] = useState<number | null>(null);
30
- const resetPassed = resetAtMs !== null && resetPassedFor === resetAtMs;
31
- useEffect(() => {
32
- if (resetAtMs === null || Number.isNaN(resetAtMs)) return;
33
- const flip = () => setResetPassedFor(resetAtMs);
34
- const delay = resetAtMs - Date.now();
35
- if (delay <= 0) {
36
- flip();
37
- return;
38
- }
39
- // Beyond setTimeout's 32-bit range the card re-renders long before then.
40
- if (delay > 2_147_483_647) return;
41
- const timer = setTimeout(flip, delay);
42
- return () => clearTimeout(timer);
43
- }, [resetAtMs]);
28
+ const resetPassed = useDeadlinePassed(resetAt === null ? null : Date.parse(resetAt));
29
const runId = thread.latestRun?.runId;
30
const recovery = thread.limitRecovery;
31
const scheduled =
apps/mobile/src/lib/clock.ts
new
+8
@@ -0,0 +1,8 @@
1
+import { deadlineStore } from "@t3tools/client-runtime/clock";
2
+import { useSyncExternalStore } from "react";
3
+
4
+/** Re-renders once when `deadlineMs` (epoch ms) is reached; `null` never passes. */
5
+export function useDeadlinePassed(deadlineMs: number | null): boolean {
6
+ const store = deadlineStore(deadlineMs);
7
+ return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
8
+}
apps/mobile/src/lib/useDelayedStatus.ts
+15
-9
@@ -1,12 +1,18 @@
1
-import { createDelayedStatus, type ShownStatus } from "@t3tools/client-runtime/delayed-status";
2
-import { useEffect, useState } from "react";
1
+import {
2
+ delayedStatusDeadline,
3
+ shownDelayedStatus,
4
+ stepDelayedStatus,
5
+} from "@t3tools/client-runtime/delayed-status";
6
+import { useState } from "react";
7
+
8
+import { useDeadlinePassed } from "./clock";
9
10
export function useDelayedStatus<A>(key: string, value: A | null): A | null {
5
- const [shown, setShown] = useState<ShownStatus<A> | null>(null);
6
- const [status] = useState(() => createDelayedStatus<A>(setShown));
7
- useEffect(() => () => status.dispose(), [status]);
8
- useEffect(() => {
9
- status.update(key, value);
10
- }, [status, key, value]);
11
- return shown?.key === key ? shown.value : null;
11
+ const [state, setState] = useState(() =>
12
+ stepDelayedStatus<A>(null, { key, value, deadlinePassed: false }, Date.now),
13
+ );
14
+ const deadlinePassed = useDeadlinePassed(delayedStatusDeadline(state));
15
+ const next = stepDelayedStatus(state, { key, value, deadlinePassed }, Date.now);
16
+ if (next !== state) setState(next);
17
+ return shownDelayedStatus(next, key);
18
}
apps/mobile/vite.config.ts
+1
@@ -10,6 +10,7 @@ const reactTests = [
10
"src/components/ui/Dialog.android.test.tsx",
11
"src/features/settings/SettingsServerControlsRouteScreen.test.tsx",
12
"src/features/settings/components/BranchNamingSettings.test.tsx",
13
+ "src/features/threads/UsageLimitRecoveryCard.test.tsx",
14
"src/native/NativeHeaderToolbar.test.tsx",
15
"src/native/useRestingTopOffset.test.tsx",
16
"src/native/useRetryingImageSource.test.tsx",
apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx
+6
-10
@@ -4,8 +4,10 @@ import {
4
type RunId,
5
} from "@t3tools/contracts";
6
import { type TimestampFormat } from "@t3tools/contracts/settings";
7
+import { deadlineStore } from "@t3tools/client-runtime/clock";
8
import { GaugeIcon } from "lucide-react";
8
-import { useEffect, useState } from "react";
9
+import { useState } from "react";
10
+import { useDeadlinePassed } from "../../hooks/useDeadline";
11
import { Button } from "../ui/button";
12
import { formatUpcomingTimestamp } from "../../timestampFormat";
13
import { toastManager } from "../ui/toast";
@@ -39,19 +41,12 @@ export function usageLimitRecoveryBannerItem(props: RecoveryProps): ComposerBann
41
42
function RecoveryActions({ runId, resetAt, recovery, snoozedUntil, onChange }: RecoveryProps) {
43
const [pending, setPending] = useState(false);
42
- const [nowMs, setNowMs] = useState(() => Date.now());
43
- useEffect(() => {
44
- const delay = Date.parse(resetAt ?? "") - Math.max(nowMs, Date.now());
45
- if (!Number.isFinite(delay) || delay <= 0) return;
46
- const timer = window.setTimeout(() => setNowMs(Date.now()), Math.min(delay + 1, 2_147_483_647));
47
- return () => window.clearTimeout(timer);
48
- }, [resetAt, nowMs]);
44
45
const scheduled =
46
recovery?.runId === runId && recovery.resetAt === resetAt && recovery.autoResume;
47
// The server leaves snoozedUntil in place after the timer wakes the thread,
48
// so a snooze whose reset has passed is no longer active.
54
- const resetPassed = Date.parse(resetAt ?? "") <= nowMs;
49
+ const resetPassed = useDeadlinePassed(resetAt === null ? null : Date.parse(resetAt));
50
const snoozed =
51
recovery?.snooze === true &&
52
recovery.runId === runId &&
@@ -68,7 +63,8 @@ function RecoveryActions({ runId, resetAt, recovery, snoozedUntil, onChange }: R
63
title: "Could not snooze thread",
64
description: "The reset time has passed. Retry the thread manually.",
65
});
71
- setNowMs(Date.now());
66
+ // The deadline timer can lag after a throttled tab or sleep; disable now.
67
+ deadlineStore(Date.parse(resetAt)).refresh();
68
return;
69
}
70
setPending(true);
apps/web/src/hooks/useDeadline.ts
new
+8
@@ -0,0 +1,8 @@
1
+import { deadlineStore } from "@t3tools/client-runtime/clock";
2
+import { useSyncExternalStore } from "react";
3
+
4
+/** Re-renders once when `deadlineMs` (epoch ms) is reached; `null` never passes. */
5
+export function useDeadlinePassed(deadlineMs: number | null): boolean {
6
+ const store = deadlineStore(deadlineMs);
7
+ return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
8
+}
apps/web/src/hooks/useDelayedStatus.ts
+15
-9
@@ -1,12 +1,18 @@
1
-import { createDelayedStatus, type ShownStatus } from "@t3tools/client-runtime/delayed-status";
2
-import { useEffect, useState } from "react";
1
+import {
2
+ delayedStatusDeadline,
3
+ shownDelayedStatus,
4
+ stepDelayedStatus,
5
+} from "@t3tools/client-runtime/delayed-status";
6
+import { useState } from "react";
7
+
8
+import { useDeadlinePassed } from "./useDeadline";
9
10
export function useDelayedStatus<A>(key: string, value: A | null): A | null {
5
- const [shown, setShown] = useState<ShownStatus<A> | null>(null);
6
- const [status] = useState(() => createDelayedStatus<A>(setShown));
7
- useEffect(() => () => status.dispose(), [status]);
8
- useEffect(() => {
9
- status.update(key, value);
10
- }, [status, key, value]);
11
- return shown?.key === key ? shown.value : null;
11
+ const [state, setState] = useState(() =>
12
+ stepDelayedStatus<A>(null, { key, value, deadlinePassed: false }, Date.now),
13
+ );
14
+ const deadlinePassed = useDeadlinePassed(delayedStatusDeadline(state));
15
+ const next = stepDelayedStatus(state, { key, value, deadlinePassed }, Date.now);
16
+ if (next !== state) setState(next);
17
+ return shownDelayedStatus(next, key);
18
}
apps/web/src/hooks/useNowMinute.ts
+2
-52
@@ -1,56 +1,6 @@
1
+import { minuteTick } from "@t3tools/client-runtime/clock";
2
import { useSyncExternalStore } from "react";
3
3
-function currentMinute(): string {
4
- return new Date().toISOString().slice(0, 16);
5
-}
6
-
7
-let nowMinute = currentMinute();
8
-let timerId: number | null = null;
9
-let timerIsInterval = false;
10
-const listeners = new Set<() => void>();
11
-
12
-function tick(): void {
13
- const next = currentMinute();
14
- if (next !== nowMinute) {
15
- nowMinute = next;
16
- for (const listener of listeners) listener();
17
- }
18
-}
19
-
20
-function startTimer(): void {
21
- timerIsInterval = false;
22
- timerId = window.setTimeout(
23
- () => {
24
- tick();
25
- timerIsInterval = true;
26
- timerId = window.setInterval(tick, 60_000);
27
- },
28
- 60_000 - (Date.now() % 60_000),
29
- );
30
-}
31
-
32
-function subscribe(listener: () => void): () => void {
33
- if (listeners.size === 0) {
34
- startTimer();
35
- }
36
- listeners.add(listener);
37
- return () => {
38
- listeners.delete(listener);
39
- if (listeners.size === 0 && timerId !== null) {
40
- if (timerIsInterval) window.clearInterval(timerId);
41
- else window.clearTimeout(timerId);
42
- timerId = null;
43
- }
44
- };
45
-}
46
-
47
-function getSnapshot(): string {
48
- if (timerId === null) {
49
- nowMinute = currentMinute();
50
- }
51
- return nowMinute;
52
-}
53
-
4
export function useNowMinute(): string {
55
- return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
5
+ return useSyncExternalStore(minuteTick.subscribe, minuteTick.getSnapshot, minuteTick.getSnapshot);
6
}
apps/web/src/hooks/useNowSecond.ts
+2
-39
@@ -1,43 +1,6 @@
1
+import { secondTick } from "@t3tools/client-runtime/clock";
2
import { useSyncExternalStore } from "react";
3
3
-// Share wall-clock ticks so duration labels repaint in one frame.
4
-
5
-function currentSecond(): number {
6
- return Math.floor(Date.now() / 1000) * 1000;
7
-}
8
-
9
-let nowSecond = currentSecond();
10
-let timerId: number | null = null;
11
-const listeners = new Set<() => void>();
12
-
13
-function scheduleTick(): void {
14
- timerId = window.setTimeout(
15
- () => {
16
- nowSecond = currentSecond();
17
- for (const listener of listeners) listener();
18
- scheduleTick();
19
- },
20
- 1000 - (Date.now() % 1000),
21
- );
22
-}
23
-
24
-function subscribe(listener: () => void): () => void {
25
- if (listeners.size === 0) scheduleTick();
26
- listeners.add(listener);
27
- return () => {
28
- listeners.delete(listener);
29
- if (listeners.size === 0 && timerId !== null) {
30
- window.clearTimeout(timerId);
31
- timerId = null;
32
- }
33
- };
34
-}
35
-
36
-function getSnapshot(): number {
37
- if (timerId === null) nowSecond = currentSecond();
38
- return nowSecond;
39
-}
40
-
4
export function useNowSecond(): number {
42
- return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
5
+ return useSyncExternalStore(secondTick.subscribe, secondTick.getSnapshot, secondTick.getSnapshot);
6
}
packages/client-runtime/package.json
+4
@@ -151,6 +151,10 @@
151
"types": "./src/queuedRunEdit.ts",
152
"default": "./src/queuedRunEdit.ts"
153
},
154
+ "./clock": {
155
+ "types": "./src/clock.ts",
156
+ "default": "./src/clock.ts"
157
+ },
158
"./delayed-status": {
159
"types": "./src/delayedStatus.ts",
160
"default": "./src/delayedStatus.ts"
packages/client-runtime/src/clock.test.ts
new
+140
@@ -0,0 +1,140 @@
1
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
+import { deadlineStore, secondTick } from "./clock.ts";
3
+
4
+describe("deadlineStore", () => {
5
+ afterEach(() => {
6
+ vi.useRealTimers();
7
+ });
8
+
9
+ it("flips once at the deadline and notifies every subscriber from one timer", () => {
10
+ vi.useFakeTimers({ now: 10_000 });
11
+ const store = deadlineStore(10_500);
12
+ const first = vi.fn();
13
+ const second = vi.fn();
14
+ const unsubscribeFirst = store.subscribe(first);
15
+ const unsubscribeSecond = deadlineStore(10_500).subscribe(second);
16
+ expect(vi.getTimerCount()).toBe(1);
17
+ expect(store.getSnapshot()).toBe(false);
18
+
19
+ vi.advanceTimersByTime(499);
20
+ expect(store.getSnapshot()).toBe(false);
21
+ vi.advanceTimersByTime(1);
22
+ expect(store.getSnapshot()).toBe(true);
23
+ expect(first).toHaveBeenCalledTimes(1);
24
+ expect(second).toHaveBeenCalledTimes(1);
25
+ expect(vi.getTimerCount()).toBe(0);
26
+ unsubscribeFirst();
27
+ unsubscribeSecond();
28
+ });
29
+
30
+ it("shares one timer between callers that obtain the deadline before subscribing", () => {
31
+ vi.useFakeTimers({ now: 0 });
32
+ const first = deadlineStore(2_000);
33
+ const second = deadlineStore(2_000);
34
+ const firstListener = vi.fn();
35
+ const secondListener = vi.fn();
36
+ const unsubscribeFirst = first.subscribe(firstListener);
37
+ const unsubscribeSecond = second.subscribe(secondListener);
38
+ expect(vi.getTimerCount()).toBe(1);
39
+
40
+ // A click observing the passed deadline must update every subscriber.
41
+ vi.setSystemTime(5_000);
42
+ first.refresh();
43
+ expect(second.getSnapshot()).toBe(true);
44
+ expect(secondListener).toHaveBeenCalledTimes(1);
45
+ expect(firstListener).toHaveBeenCalledTimes(1);
46
+ unsubscribeFirst();
47
+ unsubscribeSecond();
48
+ });
49
+
50
+ it("re-arms deadlines beyond the 32-bit timer range instead of firing early", () => {
51
+ vi.useFakeTimers({ now: 0 });
52
+ const deadline = 2_147_483_647 + 1_000;
53
+ const store = deadlineStore(deadline);
54
+ const listener = vi.fn();
55
+ const unsubscribe = store.subscribe(listener);
56
+ vi.advanceTimersByTime(2_147_483_647);
57
+ expect(store.getSnapshot()).toBe(false);
58
+ expect(listener).not.toHaveBeenCalled();
59
+ vi.advanceTimersByTime(1_000);
60
+ expect(store.getSnapshot()).toBe(true);
61
+ expect(listener).toHaveBeenCalledTimes(1);
62
+ unsubscribe();
63
+ });
64
+
65
+ it("refresh catches up when the timer runs late", () => {
66
+ vi.useFakeTimers({ now: 0 });
67
+ const store = deadlineStore(2_000);
68
+ const listener = vi.fn();
69
+ const unsubscribe = store.subscribe(listener);
70
+ store.refresh();
71
+ expect(listener).not.toHaveBeenCalled();
72
+ // Wall clock jumps past the deadline without the timer firing (sleep, throttling).
73
+ vi.setSystemTime(5_000);
74
+ expect(store.getSnapshot()).toBe(false);
75
+ store.refresh();
76
+ expect(store.getSnapshot()).toBe(true);
77
+ expect(listener).toHaveBeenCalledTimes(1);
78
+ expect(vi.getTimerCount()).toBe(0);
79
+ unsubscribe();
80
+ });
81
+
82
+ it("stops its timer when the last subscriber leaves", () => {
83
+ vi.useFakeTimers({ now: 0 });
84
+ const store = deadlineStore(1_000);
85
+ const unsubscribe = store.subscribe(vi.fn());
86
+ unsubscribe();
87
+ expect(vi.getTimerCount()).toBe(0);
88
+ vi.advanceTimersByTime(1_000);
89
+ expect(store.getSnapshot()).toBe(true);
90
+ });
91
+
92
+ it("treats a missing or unparseable deadline as never passing", () => {
93
+ vi.useFakeTimers({ now: 0 });
94
+ expect(deadlineStore(null).getSnapshot()).toBe(false);
95
+ const store = deadlineStore(Number.NaN);
96
+ store.subscribe(vi.fn());
97
+ expect(vi.getTimerCount()).toBe(0);
98
+ expect(store.getSnapshot()).toBe(false);
99
+ });
100
+});
101
+
102
+describe("secondTick", () => {
103
+ afterEach(() => {
104
+ vi.useRealTimers();
105
+ });
106
+
107
+ it("advances on wall-clock second boundaries", () => {
108
+ vi.useFakeTimers({ now: 5_250 });
109
+ const listener = vi.fn();
110
+ const unsubscribe = secondTick.subscribe(listener);
111
+ expect(secondTick.getSnapshot()).toBe(5_000);
112
+ vi.advanceTimersByTime(749);
113
+ expect(listener).not.toHaveBeenCalled();
114
+ vi.advanceTimersByTime(1);
115
+ expect(secondTick.getSnapshot()).toBe(6_000);
116
+ expect(listener).toHaveBeenCalledTimes(1);
117
+ unsubscribe();
118
+ expect(vi.getTimerCount()).toBe(0);
119
+ });
120
+
121
+ it("stops ticking when the last subscriber leaves during a tick", () => {
122
+ vi.useFakeTimers({ now: 0 });
123
+ const unsubscribe = secondTick.subscribe(() => unsubscribe());
124
+ vi.advanceTimersByTime(1_000);
125
+ expect(vi.getTimerCount()).toBe(0);
126
+ });
127
+
128
+ it("keeps one timer when a subscriber replaces itself during a tick", () => {
129
+ vi.useFakeTimers({ now: 0 });
130
+ let unsubscribeNext = () => {};
131
+ const unsubscribe = secondTick.subscribe(() => {
132
+ unsubscribe();
133
+ unsubscribeNext = secondTick.subscribe(() => {});
134
+ });
135
+ vi.advanceTimersByTime(1_000);
136
+ expect(vi.getTimerCount()).toBe(1);
137
+ unsubscribeNext();
138
+ expect(vi.getTimerCount()).toBe(0);
139
+ });
140
+});
packages/client-runtime/src/clock.ts
new
+151
@@ -0,0 +1,151 @@
1
+// @effect-diagnostics globalTimers:off globalDate:off - Render clocks for React hooks, outside an Effect runtime.
2
+
3
+/**
4
+ * A `useSyncExternalStore`-shaped clock. Snapshots stay cached between
5
+ * notifications while subscribed, as `useSyncExternalStore` requires.
6
+ */
7
+export interface ClockStore<A> {
8
+ readonly subscribe: (listener: () => void) => () => void;
9
+ readonly getSnapshot: () => A;
10
+}
11
+
12
+// setTimeout fires immediately for delays beyond a signed 32-bit int.
13
+const MAX_TIMEOUT_MS = 2_147_483_647;
14
+
15
+function makeTickStore<A>(read: () => A, periodMs: number): ClockStore<A> {
16
+ let value = read();
17
+ let timer: ReturnType<typeof setTimeout> | undefined;
18
+ const listeners = new Set<() => void>();
19
+
20
+ // Each tick lands on a wall-clock boundary so every subscriber updates in
21
+ // the same frame instead of each drifting on its own phase.
22
+ const schedule = () => {
23
+ timer = setTimeout(
24
+ () => {
25
+ timer = undefined;
26
+ const next = read();
27
+ if (next !== value) {
28
+ value = next;
29
+ for (const listener of listeners) listener();
30
+ }
31
+ // Listeners may unsubscribe (stopping the clock) or resubscribe (arming
32
+ // a fresh timer) while notified; only continue a clock nobody re-armed.
33
+ if (listeners.size > 0 && timer === undefined) schedule();
34
+ },
35
+ periodMs - (Date.now() % periodMs),
36
+ );
37
+ };
38
+
39
+ return {
40
+ subscribe: (listener) => {
41
+ if (listeners.size === 0) {
42
+ value = read();
43
+ schedule();
44
+ }
45
+ listeners.add(listener);
46
+ return () => {
47
+ listeners.delete(listener);
48
+ if (listeners.size === 0) {
49
+ clearTimeout(timer);
50
+ timer = undefined;
51
+ }
52
+ };
53
+ },
54
+ getSnapshot: () => {
55
+ if (timer === undefined) value = read();
56
+ return value;
57
+ },
58
+ };
59
+}
60
+
61
+/** Epoch ms floored to the second, advancing on each wall-clock second. */
62
+export const secondTick: ClockStore<number> = makeTickStore(
63
+ () => Math.floor(Date.now() / 1000) * 1000,
64
+ 1000,
65
+);
66
+
67
+/** ISO timestamp truncated to the minute (`YYYY-MM-DDTHH:mm`). */
68
+export const minuteTick: ClockStore<string> = makeTickStore(
69
+ () => new Date().toISOString().slice(0, 16),
70
+ 60_000,
71
+);
72
+
73
+export interface DeadlineStore extends ClockStore<boolean> {
74
+ /**
75
+ * Re-checks `Date.now()` and notifies if the deadline has passed. For callers
76
+ * that observe the deadline first, e.g. a click after a throttled or slept
77
+ * timer, so the snapshot catches up without waiting for the late timer.
78
+ */
79
+ readonly refresh: () => void;
80
+}
81
+
82
+const neverPassed: DeadlineStore = {
83
+ subscribe: () => () => {},
84
+ getSnapshot: () => false,
85
+ refresh: () => {},
86
+};
87
+
88
+interface DeadlineEntry {
89
+ readonly store: DeadlineStore;
90
+ readonly listeners: Set<() => void>;
91
+ passed: boolean;
92
+ timer: ReturnType<typeof setTimeout> | undefined;
93
+}
94
+
95
+// The single owner of each subscribed deadline. Handles obtained before the
96
+// entry exists join it on subscribe, so they share its timer and notifications.
97
+const deadlines = new Map<number, DeadlineEntry>();
98
+
99
+function passDeadline(entry: DeadlineEntry) {
100
+ clearTimeout(entry.timer);
101
+ entry.timer = undefined;
102
+ entry.passed = true;
103
+ for (const listener of entry.listeners) listener();
104
+}
105
+
106
+function armDeadline(entry: DeadlineEntry, deadlineMs: number) {
107
+ const delay = deadlineMs - Date.now();
108
+ if (delay <= 0) {
109
+ passDeadline(entry);
110
+ return;
111
+ }
112
+ entry.timer = setTimeout(() => armDeadline(entry, deadlineMs), Math.min(delay, MAX_TIMEOUT_MS));
113
+}
114
+
115
+/**
116
+ * Whether `Date.now()` has reached `deadlineMs`. One timer per distinct
117
+ * deadline, shared by its subscribers; once passed the snapshot stays true.
118
+ * Deadlines register only while subscribed, so renders React discards leak nothing.
119
+ * A non-finite deadline never passes.
120
+ */
121
+export function deadlineStore(deadlineMs: number | null): DeadlineStore {
122
+ if (deadlineMs === null || !Number.isFinite(deadlineMs)) return neverPassed;
123
+ const existing = deadlines.get(deadlineMs);
124
+ if (existing !== undefined) return existing.store;
125
+
126
+ const store: DeadlineStore = {
127
+ subscribe: (listener) => {
128
+ let entry = deadlines.get(deadlineMs);
129
+ if (entry === undefined) {
130
+ entry = { store, listeners: new Set(), passed: Date.now() >= deadlineMs, timer: undefined };
131
+ deadlines.set(deadlineMs, entry);
132
+ if (!entry.passed) armDeadline(entry, deadlineMs);
133
+ }
134
+ const joined = entry;
135
+ joined.listeners.add(listener);
136
+ return () => {
137
+ joined.listeners.delete(listener);
138
+ if (joined.listeners.size > 0) return;
139
+ clearTimeout(joined.timer);
140
+ joined.timer = undefined;
141
+ if (deadlines.get(deadlineMs) === joined) deadlines.delete(deadlineMs);
142
+ };
143
+ },
144
+ getSnapshot: () => deadlines.get(deadlineMs)?.passed ?? Date.now() >= deadlineMs,
145
+ refresh: () => {
146
+ const entry = deadlines.get(deadlineMs);
147
+ if (entry !== undefined && !entry.passed && Date.now() >= deadlineMs) passDeadline(entry);
148
+ },
149
+ };
150
+ return store;
151
+}
packages/client-runtime/src/delayedStatus.test.ts
new
+73
@@ -0,0 +1,73 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+import {
3
+ delayedStatusDeadline,
4
+ shownDelayedStatus,
5
+ stepDelayedStatus,
6
+ type DelayedStatusState,
7
+} from "./delayedStatus.ts";
8
+
9
+function step(
10
+ state: DelayedStatusState<string> | null,
11
+ value: string | null,
12
+ now: number,
13
+ key = "thread-1",
14
+) {
15
+ const deadline = state === null ? null : delayedStatusDeadline(state);
16
+ return stepDelayedStatus(
17
+ state,
18
+ { key, value, deadlinePassed: deadline !== null && now >= deadline },
19
+ () => now,
20
+ );
21
+}
22
+
23
+describe("stepDelayedStatus", () => {
24
+ it("shows a status only after it stays set for the show delay", () => {
25
+ const pending = step(null, "syncing", 0);
26
+ expect(delayedStatusDeadline(pending)).toBe(400);
27
+ expect(step(pending, "syncing", 399)).toBe(pending);
28
+ const shown = step(pending, "syncing", 400);
29
+ expect(shownDelayedStatus(shown, "thread-1")).toBe("syncing");
30
+ });
31
+
32
+ it("never shows a status that clears before the show delay", () => {
33
+ const pending = step(null, "syncing", 0);
34
+ const cleared = step(pending, null, 200);
35
+ expect(cleared.phase).toBe("idle");
36
+ expect(delayedStatusDeadline(step(cleared, "syncing", 300))).toBe(700);
37
+ });
38
+
39
+ it("shows the latest value when the show delay passes", () => {
40
+ const pending = step(null, "connecting", 0);
41
+ const changed = step(pending, "syncing", 200);
42
+ expect(changed).toBe(pending);
43
+ expect(shownDelayedStatus(step(changed, "syncing", 400), "thread-1")).toBe("syncing");
44
+ });
45
+
46
+ it("holds a shown status for the minimum visible time after it clears", () => {
47
+ const shown = step(step(null, "syncing", 0), "syncing", 400);
48
+ expect(delayedStatusDeadline(shown)).toBe(800);
49
+ expect(step(shown, null, 500)).toBe(shown);
50
+ expect(step(shown, null, 800).phase).toBe("idle");
51
+ });
52
+
53
+ it("hides immediately once the minimum visible time has passed", () => {
54
+ const shown = step(step(null, "syncing", 0), "syncing", 400);
55
+ expect(step(shown, "syncing", 900)).toBe(shown);
56
+ expect(step(shown, null, 1000).phase).toBe("idle");
57
+ });
58
+
59
+ it("restarts the minimum visible time when the shown value changes", () => {
60
+ const shown = step(step(null, "syncing", 0), "syncing", 400);
61
+ const replaced = step(shown, "replaying", 600);
62
+ expect(shownDelayedStatus(replaced, "thread-1")).toBe("replaying");
63
+ expect(delayedStatusDeadline(replaced)).toBe(1000);
64
+ });
65
+
66
+ it("hides the status and restarts the delay when the key changes", () => {
67
+ const shown = step(step(null, "syncing", 0), "syncing", 400);
68
+ expect(shownDelayedStatus(shown, "thread-2")).toBeNull();
69
+ const other = step(shown, "syncing", 500, "thread-2");
70
+ expect(shownDelayedStatus(other, "thread-2")).toBeNull();
71
+ expect(delayedStatusDeadline(other)).toBe(900);
72
+ });
73
+});
packages/client-runtime/src/delayedStatus.ts
+63
-62
@@ -1,74 +1,75 @@
1
-// @effect-diagnostics globalTimers:off - Display timing for React hooks, outside an Effect runtime.
2
-
1
const STATUS_SHOW_DELAY_MS = 400;
2
const STATUS_MIN_VISIBLE_MS = 400;
3
6
-export interface ShownStatus<A> {
7
- readonly key: string;
8
- readonly value: A;
9
-}
4
+/**
5
+ * A status shows only after it has stayed set for a moment, then stays shown
6
+ * for a minimum time so a quick flicker never flashes on screen.
7
+ * `deadlinePassed` tells whether `delayedStatusDeadline(state)` has been reached.
8
+ */
9
+export type DelayedStatusState<A> =
10
+ | { readonly phase: "idle"; readonly key: string }
11
+ | { readonly phase: "pending"; readonly key: string; readonly showAt: number }
12
+ | {
13
+ readonly phase: "shown";
14
+ readonly key: string;
15
+ readonly value: A;
16
+ readonly holdUntil: number;
17
+ };
18
11
-export interface DelayedStatus<A> {
12
- readonly update: (key: string, value: A | null) => void;
13
- readonly dispose: () => void;
19
+export interface DelayedStatusInput<A> {
20
+ readonly key: string;
21
+ /** Compared by identity, so use strings or other stable values. */
22
+ readonly value: A | null;
23
+ readonly deadlinePassed: boolean;
24
}
25
26
/**
17
- * Values compare by identity, so use strings or other stable values.
27
+ * Returns `state` itself when nothing changes, so it can run on every render.
28
+ * `now` is read only to stamp a new deadline; it is a function so a memoizing
29
+ * caller (the React Compiler) cannot cache a stale clock reading.
30
*/
19
-export function createDelayedStatus<A>(
20
- onChange: (shown: ShownStatus<A> | null) => void,
21
-): DelayedStatus<A> {
22
- let key = "";
23
- let latest: A | null = null;
24
- let shown: A | null = null;
25
- let timer: ReturnType<typeof setTimeout> | undefined;
26
-
27
- const clearTimer = () => {
28
- clearTimeout(timer);
29
- timer = undefined;
30
- };
31
- const hide = () => {
32
- shown = null;
33
- onChange(null);
34
- };
35
- const show = (value: A) => {
36
- shown = value;
37
- onChange({ key, value });
38
- clearTimer();
39
- timer = setTimeout(() => {
40
- timer = undefined;
41
- if (latest === null) hide();
42
- }, STATUS_MIN_VISIBLE_MS);
43
- };
31
+export function stepDelayedStatus<A>(
32
+ state: DelayedStatusState<A> | null,
33
+ { key, value, deadlinePassed }: DelayedStatusInput<A>,
34
+ now: () => number,
35
+): DelayedStatusState<A> {
36
+ const idle = (): DelayedStatusState<A> => ({ phase: "idle", key });
37
+ const pending = (): DelayedStatusState<A> => ({
38
+ phase: "pending",
39
+ key,
40
+ showAt: now() + STATUS_SHOW_DELAY_MS,
41
+ });
42
+ const shown = (shownValue: A): DelayedStatusState<A> => ({
43
+ phase: "shown",
44
+ key,
45
+ value: shownValue,
46
+ holdUntil: now() + STATUS_MIN_VISIBLE_MS,
47
+ });
48
45
- return {
46
- update: (nextKey, value) => {
47
- if (nextKey !== key) {
48
- key = nextKey;
49
- clearTimer();
50
- if (shown !== null) hide();
51
- }
52
- latest = value;
49
+ if (state === null || state.key !== key) return value === null ? idle() : pending();
50
+ switch (state.phase) {
51
+ case "idle":
52
+ return value === null ? state : pending();
53
+ case "pending":
54
+ if (value === null) return idle();
55
+ return deadlinePassed ? shown(value) : state;
56
+ case "shown":
57
+ if (value === null) return deadlinePassed ? idle() : state;
58
+ return value === state.value ? state : shown(value);
59
+ }
60
+}
61
54
- if (shown === null) {
55
- if (value === null) {
56
- clearTimer();
57
- } else if (timer === undefined) {
58
- timer = setTimeout(() => {
59
- timer = undefined;
60
- if (latest !== null) show(latest);
61
- }, STATUS_SHOW_DELAY_MS);
62
- }
63
- return;
64
- }
62
+export function delayedStatusDeadline<A>(state: DelayedStatusState<A>): number | null {
63
+ switch (state.phase) {
64
+ case "idle":
65
+ return null;
66
+ case "pending":
67
+ return state.showAt;
68
+ case "shown":
69
+ return state.holdUntil;
70
+ }
71
+}
72
66
- if (value !== null) {
67
- if (value !== shown) show(value);
68
- } else if (timer === undefined) {
69
- hide();
70
- }
71
- },
72
- dispose: clearTimer,
73
- };
73
+export function shownDelayedStatus<A>(state: DelayedStatusState<A>, key: string): A | null {
74
+ return state.phase === "shown" && state.key === key ? state.value : null;
75
}