Open History to see the last commit
1import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2import { AsyncResult } from "effect/reactivity";
3import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4import type { EnvironmentId } from "@t3tools/contracts";
5import * as DateTime from "effect/DateTime";
6import { useEffect, useState } from "react";
7import { Pressable, View } from "react-native";
8import { AppText as Text } from "../../components/ui/AppText";
9import { threadEnvironment } from "../../state/threads";
10import { useAtomCommand } from "../../state/use-atom-command";
11
12export function UsageLimitRecoveryCard({
13 thread,
14 environmentId,
15}: {
16 thread: EnvironmentThreadShell;
17 environmentId: EnvironmentId;
18}) {
19 const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata);
20 const [pending, setPending] = useState(false);
21 const [error, setError] = useState<string | null>(null);
22 const resetAt = thread.runtime?.usageLimitResetAt ?? null;
23 const canSchedule =
24 resetAt !== null &&
25 Date.parse(resetAt) > Date.parse(thread.latestRun?.completedAt ?? thread.updatedAt);
26 // Whether the reset already passed is state a timer flips at resetAt: the
27 // compiler caches render output on its inputs, so reading the clock during
28 // render would leave the snooze button enabled after the reset.
29 const resetAtMs = resetAt === null ? null : Date.parse(resetAt);
30 const [resetPassedFor, setResetPassedFor] = useState<number | null>(null);
31 const resetPassed = resetAtMs !== null && resetPassedFor === resetAtMs;
32 useEffect(() => {
33 if (resetAtMs === null || Number.isNaN(resetAtMs)) return;
34 const flip = () => setResetPassedFor(resetAtMs);
35 const delay = resetAtMs - Date.now();
36 if (delay <= 0) {
37 flip();
38 return;
39 }
40 // Beyond setTimeout's 32-bit range the card re-renders long before then.
41 if (delay > 2_147_483_647) return;
42 const timer = setTimeout(flip, delay);
43 return () => clearTimeout(timer);
44 }, [resetAtMs]);
45 const runId = thread.latestRun?.runId;
46 const recovery = thread.limitRecovery;
47 const scheduled =
48 recovery?.runId === runId && recovery?.resetAt === resetAt && recovery?.autoResume;
49 if (
50 thread.runtime?.status !== "failed" ||
51 thread.runtime.lastErrorClass !== "usage_limit" ||
52 !runId
53 )
54 return null;
55 const snoozed =
56 recovery?.snooze === true &&
57 recovery.runId === runId &&
58 recovery.resetAt === resetAt &&
59 resetAt !== null &&
60 thread.snoozedUntil !== null &&
61 Date.parse(thread.snoozedUntil) === Date.parse(resetAt);
62 async function toggle(action: "resume" | "snooze") {
63 if (!resetAt || !runId || !canSchedule) return;
64 if (action === "snooze" && !snoozed && Date.parse(resetAt) <= Date.now()) {
65 setError("The reset time has passed. Retry the thread manually.");
66 return;
67 }
68 setPending(true);
69 setError(null);
70 const result = await updateMetadata({
71 environmentId,
72 input: {
73 threadId: thread.id,
74 limitRecovery: {
75 runId,
76 resetAt,
77 ...(action === "resume" ? { autoResume: !scheduled } : { snooze: !snoozed }),
78 },
79 },
80 });
81 setPending(false);
82 if (AsyncResult.isFailure(result)) {
83 const cause = squashAtomCommandFailure(result);
84 setError(cause instanceof Error ? cause.message : "Could not change limit recovery.");
85 }
86 }
87 return (
88 <View className="mx-3 mb-2 gap-2 rounded-xl border border-warning-foreground/25 bg-screen p-3">
89 <Text className="text-sm text-warning-foreground">
90 {resetAt
91 ? `Usage limit resets ${DateTime.toDateUtc(DateTime.makeUnsafe(resetAt)).toLocaleString()}.`
92 : "The provider did not report a reset time. Retry manually when your limit is available."}
93 </Text>
94 {canSchedule ? (
95 <View className="flex-row flex-wrap gap-2">
96 <Pressable
97 accessibilityRole="button"
98 disabled={pending}
99 onPress={() => void toggle("resume")}
100 className="self-start rounded-lg bg-subtle px-3 py-2 active:opacity-70"
101 >
102 <Text className="text-sm text-foreground">
103 {scheduled ? "Cancel auto-resume" : "Resume at reset"}
104 </Text>
105 </Pressable>
106 <Pressable
107 accessibilityRole="button"
108 disabled={pending || (!snoozed && resetPassed)}
109 onPress={() => void toggle("snooze")}
110 className="self-start rounded-lg bg-subtle px-3 py-2 active:opacity-70"
111 >
112 <Text className="text-sm text-foreground">
113 {snoozed ? "Wake now" : "Snooze until reset"}
114 </Text>
115 </Pressable>
116 </View>
117 ) : null}
118 {error ? (
119 <Text accessibilityRole="alert" className="text-sm text-destructive">
120 {error}
121 </Text>
122 ) : null}
123 </View>
124 );
125}