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 // Whether the reset already passed is state a timer flips at resetAt: the
28 // compiler caches render output on its inputs, so reading the clock during
29 // render would leave the snooze button enabled after the reset.
30 const resetAtMs = resetAt === null ? null : Date.parse(resetAt);
31 const [resetPassedFor, setResetPassedFor] = useState<number | null>(null);
32 const resetPassed = resetAtMs !== null && resetPassedFor === resetAtMs;
33 useEffect(() => {
34 if (resetAtMs === null || Number.isNaN(resetAtMs)) return;
35 const flip = () => setResetPassedFor(resetAtMs);
36 const delay = resetAtMs - Date.now();
37 if (delay <= 0) {
38 flip();
39 return;
40 }
41 // Beyond setTimeout's 32-bit range the card re-renders long before then.
42 if (delay > 2_147_483_647) return;
43 const timer = setTimeout(flip, delay);
44 return () => clearTimeout(timer);
45 }, [resetAtMs]);
46 const runId = thread.latestRun?.runId;
47 const recovery = thread.limitRecovery;
48 const scheduled =
49 recovery?.runId === runId && recovery?.resetAt === resetAt && recovery?.autoResume;
50 if (
51 thread.runtime?.status !== "failed" ||
52 thread.runtime.lastErrorClass !== "usage_limit" ||
53 !runId
54 )
55 return null;
56 const snoozed =
57 recovery?.snooze === true &&
58 recovery.runId === runId &&
59 recovery.resetAt === resetAt &&
60 resetAt !== null &&
61 thread.snoozedUntil !== null &&
62 Date.parse(thread.snoozedUntil) === Date.parse(resetAt);
63 async function toggle(action: "resume" | "snooze") {
64 if (!resetAt || !runId || !canSchedule) return;
65 if (action === "snooze" && !snoozed && Date.parse(resetAt) <= Date.now()) {
66 setError("The reset time has passed. Retry the thread manually.");
67 return;
68 }
69 setPending(true);
70 setError(null);
71 const result = await updateMetadata({
72 environmentId,
73 input: {
74 threadId: thread.id,
75 limitRecovery: {
76 runId,
77 resetAt,
78 ...(action === "resume" ? { autoResume: !scheduled } : { snooze: !snoozed }),
79 },
80 },
81 });
82 setPending(false);
83 if (AsyncResult.isFailure(result)) {
84 const cause = squashAtomCommandFailure(result);
85 setError(cause instanceof Error ? cause.message : "Could not change limit recovery.");
86 }
87 }
88 return (
89 <View className="mx-3 mb-2 gap-2 rounded-xl border border-warning-foreground/25 bg-screen p-3">
90 <Text className="text-sm text-warning-foreground">
91 {resetAt
92 ? `Usage limit resets ${DateTime.toDateUtc(DateTime.makeUnsafe(resetAt)).toLocaleString()}.`
93 : "The provider did not report a reset time. Retry manually when your limit is available."}
94 </Text>
95 {canSchedule ? (
96 <View className="flex-row flex-wrap gap-2">
97 <Button
98 label={scheduled ? "Cancel auto-resume" : "Resume at reset"}
99 tone="secondary"
100 disabled={pending}
101 onPress={() => void toggle("resume")}
102 />
103 <Button
104 label={snoozed ? "Wake now" : "Snooze until reset"}
105 tone="secondary"
106 disabled={pending || (!snoozed && resetPassed)}
107 onPress={() => void toggle("snooze")}
108 />
109 </View>
110 ) : null}
111 {error ? (
112 <Text accessibilityRole="alert" className="text-sm text-destructive">
113 {error}
114 </Text>
115 ) : null}
116 </View>
117 );
118}