Open History to see the last commit
1import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3import { AsyncResult } from "effect/reactivity";
4import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
5import { limitRecoveryOwnsSnooze } from "@t3tools/client-runtime/state/thread-execution";
6import type { EnvironmentId } from "@t3tools/contracts";
7import {
8 CHATGPT_USAGE_LIMIT_CODE,
9 CHATGPT_USAGE_URL,
10 CHATGPT_WORKSPACE_ADMIN_REQUEST,
11 CHATGPT_WORKSPACE_USAGE_LIMIT_CODE,
12} from "@t3tools/shared/usageLimits";
13import * as Clipboard from "expo-clipboard";
14import { T, useGT } from "gt-react-native";
15import { m } from "../../i18n/messages";
16import { useState } from "react";
17import { Linking, Pressable, View } from "react-native";
18import { ProviderIcon } from "../../components/ProviderIcon";
19import { AppText as Text } from "../../components/ui/AppText";
20import { useDeadlinePassed } from "../../lib/clock";
21import { threadEnvironment } from "../../state/threads";
22import { useAtomCommand } from "../../state/use-atom-command";
23
24export function UsageLimitRecoveryCard({
25 thread,
26 environmentId,
27}: {
28 thread: EnvironmentThreadShell;
29 environmentId: EnvironmentId;
30}) {
31 const gt = useGT();
32 const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata);
33 const [pending, setPending] = useState(false);
34 const [error, setError] = useState<string | null>(null);
35 const resetAt = thread.runtime?.usageLimitResetAt ?? null;
36 const canSchedule =
37 thread.settledOverride !== "settled" &&
38 resetAt !== null &&
39 Date.parse(resetAt) > Date.parse(thread.latestRun?.completedAt ?? thread.updatedAt);
40 const resetPassed = useDeadlinePassed(resetAt === null ? null : Date.parse(resetAt));
41 const runId = thread.latestRun?.runId;
42 const recovery = thread.limitRecovery;
43 const scheduled =
44 recovery?.runId === runId && recovery?.resetAt === resetAt && recovery?.autoResume;
45 const displayAt =
46 canSchedule &&
47 scheduled &&
48 resetAt &&
49 thread.snoozedUntil &&
50 Date.parse(thread.snoozedUntil) > Date.parse(resetAt)
51 ? thread.snoozedUntil
52 : resetAt;
53 const [copied, setCopied] = useState(false);
54 const [actionPending, setActionPending] = useState(false);
55 const code = thread.runtime?.lastErrorCode;
56 // OpenAI's partner guidelines specify the ChatGPT notice and its action.
57 const workspaceLimit = code === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE;
58 const chatGptLimit = workspaceLimit || code === CHATGPT_USAGE_LIMIT_CODE;
59 if (
60 thread.runtime?.status !== "failed" ||
61 // Older servers report ChatGPT sharing limits as provider errors.
62 (thread.runtime.lastErrorClass !== "usage_limit" && !chatGptLimit) ||
63 !runId
64 )
65 return null;
66 const resetDate = displayAt
67 ? new Date(displayAt).toLocaleString(undefined, {
68 month: "short",
69 day: "numeric",
70 hour: "numeric",
71 minute: "2-digit",
72 })
73 : null;
74 const resumes = canSchedule && scheduled;
75 const resetText =
76 resetDate === null
77 ? null
78 : resumes
79 ? gt("Resumes {date}.", { date: resetDate })
80 : gt("Resets {date}.", { date: resetDate });
81 const snoozed =
82 limitRecoveryOwnsSnooze({
83 runId,
84 resetAt,
85 recovery,
86 snoozedUntil: thread.snoozedUntil,
87 }) && !resetPassed;
88 async function toggle(action: "resume" | "snooze") {
89 if (!resetAt || !runId || !canSchedule) return;
90 if (action === "snooze" && !snoozed && Date.parse(resetAt) <= Date.now()) {
91 setError(gt("The reset time has passed. Retry the thread manually."));
92 return;
93 }
94 setPending(true);
95 setError(null);
96 const result = await updateMetadata({
97 environmentId,
98 input: {
99 threadId: thread.id,
100 limitRecovery: {
101 runId,
102 resetAt,
103 ...(action === "resume" ? { autoResume: !scheduled } : { snooze: !snoozed }),
104 },
105 },
106 });
107 setPending(false);
108 if (AsyncResult.isFailure(result)) {
109 const cause = squashAtomCommandFailure(result);
110 setError(errorDisplayMessage(cause, m) ?? gt("Could not change limit recovery."));
111 }
112 }
113 const action = workspaceLimit
114 ? {
115 label: gt("Copy request for admin"),
116 role: "button" as const,
117 run: () => {
118 setError(null);
119 setCopied(false);
120 setActionPending(true);
121 void Clipboard.setStringAsync(CHATGPT_WORKSPACE_ADMIN_REQUEST)
122 .then(
123 () => setCopied(true),
124 () => setError(gt("Could not copy the request. Try again.")),
125 )
126 .finally(() => setActionPending(false));
127 },
128 }
129 : {
130 label: gt("Manage usage"),
131 role: "link" as const,
132 run: () => {
133 setError(null);
134 setActionPending(true);
135 void Linking.openURL(CHATGPT_USAGE_URL)
136 .catch(() =>
137 setError(gt("Could not open ChatGPT. Go to chatgpt.com → Settings → Usage.")),
138 )
139 .finally(() => setActionPending(false));
140 },
141 };
142 return (
143 <View
144 accessibilityRole={chatGptLimit ? "alert" : undefined}
145 className="mx-3 mb-2 flex-row gap-2 rounded-xl border border-warning-foreground/25 bg-screen p-3"
146 >
147 {chatGptLimit ? (
148 <View className="pt-0.5">
149 <ProviderIcon provider="codex" size={16} />
150 </View>
151 ) : null}
152 <View className="min-w-0 flex-1 gap-1">
153 {chatGptLimit ? (
154 <Text className="text-sm font-t3-medium text-foreground">
155 <T>ChatGPT usage limit reached</T>
156 </Text>
157 ) : null}
158 <Text
159 className={
160 chatGptLimit ? "text-sm text-foreground-muted" : "text-sm text-warning-foreground"
161 }
162 >
163 {workspaceLimit
164 ? copied
165 ? gt("Request copied. Send it to your workspace admin.")
166 : gt(
167 "You've reached your workspace's limit for using your ChatGPT plan in other apps. Copy a request to ask your workspace admin for increased usage limits.",
168 )
169 : chatGptLimit
170 ? (resetText ?? gt("Review your usage settings in ChatGPT."))
171 : resetDate !== null
172 ? resumes
173 ? gt("Usage limit reached. Resumes {date}.", { date: resetDate })
174 : gt("Usage limit reached. Resets {date}.", { date: resetDate })
175 : gt(
176 "Usage limit reached. The provider did not report a reset time. Retry manually when your limit is available.",
177 )}
178 </Text>
179 {chatGptLimit || canSchedule ? (
180 // The margins cancel the 44pt touch height so the links sit 8pt under the text.
181 <View className="-mb-3 -mt-2 flex-row flex-wrap gap-x-4">
182 {chatGptLimit ? (
183 <RecoveryAction
184 label={action.label}
185 role={action.role}
186 disabled={actionPending}
187 onPress={action.run}
188 />
189 ) : null}
190 {canSchedule ? (
191 <>
192 <RecoveryAction
193 label={scheduled ? gt("Cancel auto-resume") : gt("Resume at reset")}
194 disabled={pending}
195 onPress={() => void toggle("resume")}
196 />
197 <RecoveryAction
198 label={snoozed ? gt("Wake now") : gt("Snooze until reset")}
199 disabled={pending || (!snoozed && resetPassed)}
200 onPress={() => void toggle("snooze")}
201 />
202 </>
203 ) : null}
204 </View>
205 ) : null}
206 {error ? (
207 <Text accessibilityRole="alert" className="text-sm text-destructive">
208 {error}
209 </Text>
210 ) : null}
211 </View>
212 </View>
213 );
214}
215
216function RecoveryAction(props: {
217 readonly label: string;
218 readonly role?: "button" | "link";
219 readonly disabled: boolean;
220 readonly onPress: () => void;
221}) {
222 return (
223 <Pressable
224 accessibilityRole={props.role ?? "button"}
225 accessibilityState={{ disabled: props.disabled }}
226 disabled={props.disabled}
227 hitSlop={{ left: 8, right: 8 }}
228 onPress={props.onPress}
229 className="min-h-11 justify-center active:opacity-70"
230 >
231 <Text
232 className={
233 props.disabled
234 ? "text-sm font-t3-medium text-foreground-muted"
235 : "text-sm font-t3-medium text-primary"
236 }
237 >
238 {props.label}
239 </Text>
240 </Pressable>
241 );
242}