Skip to content

Commit 03df289

Browse files
fix(client): usage-limit Snooze disables at reset even weeks away, via a shared deadline clock (#25005)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 65822d8 commit 03df289

15 files changed

Lines changed: 557 additions & 199 deletions
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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‎

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@ import { AsyncResult } from "effect/reactivity";
44
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
55
import type { EnvironmentId } from "@t3tools/contracts";
66
import * as DateTime from "effect/DateTime";
7-
import { useEffect, useState } from "react";
7+
import { useState } from "react";
88
import { View } from "react-native";
99
import { AppText as Text } from "../../components/ui/AppText";
10+
import { useDeadlinePassed } from "../../lib/clock";
1011
import { threadEnvironment } from "../../state/threads";
1112
import { useAtomCommand } from "../../state/use-atom-command";
1213

@@ -24,23 +25,7 @@ export function UsageLimitRecoveryCard({
2425
const canSchedule =
2526
resetAt !== null &&
2627
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));
4429
const runId = thread.latestRun?.runId;
4530
const recovery = thread.limitRecovery;
4631
const scheduled =

‎apps/mobile/src/lib/clock.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
}
Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -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";
39

410
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);
1218
}

‎apps/mobile/vite.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ const reactTests = [
1010
"src/components/ui/Dialog.android.test.tsx",
1111
"src/features/settings/SettingsServerControlsRouteScreen.test.tsx",
1212
"src/features/settings/components/BranchNamingSettings.test.tsx",
13+
"src/features/threads/UsageLimitRecoveryCard.test.tsx",
1314
"src/native/NativeHeaderToolbar.test.tsx",
1415
"src/native/useRestingTopOffset.test.tsx",
1516
"src/native/useRetryingImageSource.test.tsx",

‎apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@ import {
44
type RunId,
55
} from "@t3tools/contracts";
66
import { type TimestampFormat } from "@t3tools/contracts/settings";
7+
import { deadlineStore } from "@t3tools/client-runtime/clock";
78
import { GaugeIcon } from "lucide-react";
8-
import { useEffect, useState } from "react";
9+
import { useState } from "react";
10+
import { useDeadlinePassed } from "../../hooks/useDeadline";
911
import { Button } from "../ui/button";
1012
import { formatUpcomingTimestamp } from "../../timestampFormat";
1113
import { toastManager } from "../ui/toast";
@@ -39,19 +41,12 @@ export function usageLimitRecoveryBannerItem(props: RecoveryProps): ComposerBann
3941

4042
function RecoveryActions({ runId, resetAt, recovery, snoozedUntil, onChange }: RecoveryProps) {
4143
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]);
4944

5045
const scheduled =
5146
recovery?.runId === runId && recovery.resetAt === resetAt && recovery.autoResume;
5247
// The server leaves snoozedUntil in place after the timer wakes the thread,
5348
// 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));
5550
const snoozed =
5651
recovery?.snooze === true &&
5752
recovery.runId === runId &&
@@ -68,7 +63,8 @@ function RecoveryActions({ runId, resetAt, recovery, snoozedUntil, onChange }: R
6863
title: "Could not snooze thread",
6964
description: "The reset time has passed. Retry the thread manually.",
7065
});
71-
setNowMs(Date.now());
66+
// The deadline timer can lag after a throttled tab or sleep; disable now.
67+
deadlineStore(Date.parse(resetAt)).refresh();
7268
return;
7369
}
7470
setPending(true);

‎apps/web/src/hooks/useDeadline.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
}
Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -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";
39

410
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);
1218
}

‎apps/web/src/hooks/useNowMinute.ts‎

Lines changed: 2 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,6 @@
1+
import { minuteTick } from "@t3tools/client-runtime/clock";
12
import { useSyncExternalStore } from "react";
23

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-
544
export function useNowMinute(): string {
55-
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
5+
return useSyncExternalStore(minuteTick.subscribe, minuteTick.getSnapshot, minuteTick.getSnapshot);
566
}

‎apps/web/src/hooks/useNowSecond.ts‎

Lines changed: 2 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,6 @@
1+
import { secondTick } from "@t3tools/client-runtime/clock";
12
import { useSyncExternalStore } from "react";
23

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-
414
export function useNowSecond(): number {
42-
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
5+
return useSyncExternalStore(secondTick.subscribe, secondTick.getSnapshot, secondTick.getSnapshot);
436
}

0 commit comments

Comments
 (0)