Open History to see the last commit
1import { Button } from "../../components/ui/Button";
2import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3import { AsyncResult } from "effect/reactivity";
4import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
5import type { EnvironmentId } from "@t3tools/contracts";
6import * as DateTime from "effect/DateTime";
7import { useEffect, useState } from "react";
8import { View } from "react-native";
9import { AppText as Text } from "../../components/ui/AppText";
10import { threadEnvironment } from "../../state/threads";
11import { useAtomCommand } from "../../state/use-atom-command";
12
13export function UsageLimitRecoveryCard({
14 thread,
15 environmentId,
16}: {
17 thread: EnvironmentThreadShell;
18 environmentId: EnvironmentId;
19}) {
20 const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata);
21 const [pending, setPending] = useState(false);
22 const [error, setError] = useState<string | null>(null);
23 const resetAt = thread.runtime?.usageLimitResetAt ?? null;
24 const canSchedule =
25 resetAt !== null &&
26 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]);
44 const runId = thread.latestRun?.runId;
45 const recovery = thread.limitRecovery;
46 const scheduled =
47 recovery?.runId === runId && recovery?.resetAt === resetAt && recovery?.autoResume;
48 if (
49 thread.runtime?.status !== "failed" ||
50 thread.runtime.lastErrorClass !== "usage_limit" ||
51 !runId
52 )
53 return null;
54 const snoozed =
55 recovery?.snooze === true &&
56 recovery.runId === runId &&
57 recovery.resetAt === resetAt &&
58 resetAt !== null &&
59 thread.snoozedUntil !== null &&
60 Date.parse(thread.snoozedUntil) === Date.parse(resetAt);
61 async function toggle(action: "resume" | "snooze") {
62 if (!resetAt || !runId || !canSchedule) return;
63 if (action === "snooze" && !snoozed && Date.parse(resetAt) <= Date.now()) {
64 setError("The reset time has passed. Retry the thread manually.");
65 return;
66 }
67 setPending(true);
68 setError(null);
69 const result = await updateMetadata({
70 environmentId,
71 input: {
72 threadId: thread.id,
73 limitRecovery: {
74 runId,
75 resetAt,
76 ...(action === "resume" ? { autoResume: !scheduled } : { snooze: !snoozed }),
77 },
78 },
79 });
80 setPending(false);
81 if (AsyncResult.isFailure(result)) {
82 const cause = squashAtomCommandFailure(result);
83 setError(cause instanceof Error ? cause.message : "Could not change limit recovery.");
84 }
85 }
86 return (
87 <View className="mx-3 mb-2 gap-2 rounded-xl border border-warning-foreground/25 bg-screen p-3">
88 <Text className="text-sm text-warning-foreground">
89 {resetAt
90 ? `Usage limit resets ${DateTime.toDateUtc(DateTime.makeUnsafe(resetAt)).toLocaleString()}.`
91 : "The provider did not report a reset time. Retry manually when your limit is available."}
92 </Text>
93 {canSchedule ? (
94 <View className="flex-row flex-wrap gap-2">
95 <Button
96 label={scheduled ? "Cancel auto-resume" : "Resume at reset"}
97 tone="secondary"
98 disabled={pending}
99 onPress={() => void toggle("resume")}
100 />
101 <Button
102 label={snoozed ? "Wake now" : "Snooze until reset"}
103 tone="secondary"
104 disabled={pending || (!snoozed && resetPassed)}
105 onPress={() => void toggle("snooze")}
106 />
107 </View>
108 ) : null}
109 {error ? (
110 <Text accessibilityRole="alert" className="text-sm text-destructive">
111 {error}
112 </Text>
113 ) : null}
114 </View>
115 );
116}