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 {
5 limitRecoveryOwnsSnooze,
6 usageLimitNoticeResetAt,
7} from "@t3tools/client-runtime/state/thread-execution";
8import type { EnvironmentId } from "@t3tools/contracts";
9import {
10 CHATGPT_USAGE_LIMIT_CODE,
11 CHATGPT_USAGE_URL,
12 CHATGPT_WORKSPACE_ADMIN_REQUEST,
13 CHATGPT_WORKSPACE_USAGE_LIMIT_CODE,
14} from "@t3tools/shared/usageLimits";
15import * as Clipboard from "expo-clipboard";
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, useNowAfter } 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 updateMetadata = useAtomCommand(threadEnvironment.updateMetadata);
32 const [pending, setPending] = useState(false);
33 const [error, setError] = useState<string | null>(null);
34 const runId = thread.latestRun?.runId;
35 const recovery = thread.limitRecovery;
36 const stoppedAt = thread.latestRun?.completedAt ?? thread.updatedAt;
37 const snoozedUntilMs = thread.snoozedUntil ? Date.parse(thread.snoozedUntil) : null;
38 const nowMs = useNowAfter(snoozedUntilMs);
39 const resetAt = usageLimitNoticeResetAt({
40 runId,
41 resetAt: thread.runtime?.usageLimitResetAt,
42 stoppedAtMs: Date.parse(stoppedAt),
43 recovery,
44 snoozedUntilMs,
45 nowMs,
46 });
47 const canSchedule =
48 thread.settledOverride !== "settled" &&
49 resetAt !== null &&
50 Date.parse(resetAt) > Date.parse(stoppedAt);
51 const resetPassed = useDeadlinePassed(resetAt === null ? null : Date.parse(resetAt));
52 const scheduled =
53 recovery?.runId === runId && recovery?.resetAt === resetAt && recovery?.autoResume;
54 const displayAt =
55 canSchedule &&
56 scheduled &&
57 resetAt &&
58 thread.snoozedUntil &&
59 Date.parse(thread.snoozedUntil) > Date.parse(resetAt)
60 ? thread.snoozedUntil
61 : resetAt;
62 const [copied, setCopied] = useState(false);
63 const [actionPending, setActionPending] = useState(false);
64 const code = thread.runtime?.lastErrorCode;
65 // OpenAI's partner guidelines specify the ChatGPT notice and its action.
66 const workspaceLimit = code === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE;
67 const chatGptLimit = workspaceLimit || code === CHATGPT_USAGE_LIMIT_CODE;
68 if (
69 thread.runtime?.status !== "failed" ||
70 // Older servers report ChatGPT sharing limits as provider errors.
71 (thread.runtime.lastErrorClass !== "usage_limit" && !chatGptLimit) ||
72 !runId
73 )
74 return null;
75 const resetText = displayAt
76 ? `${canSchedule && scheduled ? "Resumes" : "Resets"} ${new Date(displayAt).toLocaleString(
77 undefined,
78 { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" },
79 )}.`
80 : null;
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("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(cause instanceof Error ? cause.message : "Could not change limit recovery.");
111 }
112 }
113 const action = workspaceLimit
114 ? {
115 label: "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("Could not copy the request. Try again."),
125 )
126 .finally(() => setActionPending(false));
127 },
128 }
129 : {
130 label: "Manage usage",
131 role: "link" as const,
132 run: () => {
133 setError(null);
134 setActionPending(true);
135 void Linking.openURL(CHATGPT_USAGE_URL)
136 .catch(() => setError("Could not open ChatGPT. Go to chatgpt.com → Settings → Usage."))
137 .finally(() => setActionPending(false));
138 },
139 };
140 return (
141 <View
142 accessibilityRole={chatGptLimit ? "alert" : undefined}
143 className="mx-3 mb-2 flex-row gap-2 rounded-xl border border-warning-foreground/25 bg-screen p-3"
144 >
145 {chatGptLimit ? (
146 <View className="pt-0.5">
147 <ProviderIcon provider="codex" size={16} />
148 </View>
149 ) : null}
150 <View className="min-w-0 flex-1 gap-1">
151 {chatGptLimit ? (
152 <Text className="text-sm font-t3-medium text-foreground">
153 ChatGPT usage limit reached
154 </Text>
155 ) : null}
156 <Text
157 className={
158 chatGptLimit ? "text-sm text-foreground-muted" : "text-sm text-warning-foreground"
159 }
160 >
161 {workspaceLimit
162 ? copied
163 ? "Request copied. Send it to your workspace admin."
164 : "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."
165 : chatGptLimit
166 ? (resetText ?? "Review your usage settings in ChatGPT.")
167 : resetText
168 ? `Usage limit reached. ${resetText}`
169 : "Usage limit reached. The provider did not report a reset time. Retry manually when your limit is available."}
170 </Text>
171 {chatGptLimit || canSchedule ? (
172 // The margins cancel the 44pt touch height so the links sit 8pt under the text.
173 <View className="-mb-3 -mt-2 flex-row flex-wrap gap-x-4">
174 {chatGptLimit ? (
175 <RecoveryAction
176 label={action.label}
177 role={action.role}
178 disabled={actionPending}
179 onPress={action.run}
180 />
181 ) : null}
182 {canSchedule ? (
183 <>
184 <RecoveryAction
185 label={scheduled ? "Cancel auto-resume" : "Resume at reset"}
186 disabled={pending}
187 onPress={() => void toggle("resume")}
188 />
189 <RecoveryAction
190 label={snoozed ? "Wake now" : "Snooze until reset"}
191 disabled={pending || (!snoozed && resetPassed)}
192 onPress={() => void toggle("snooze")}
193 />
194 </>
195 ) : null}
196 </View>
197 ) : null}
198 {error ? (
199 <Text accessibilityRole="alert" className="text-sm text-destructive">
200 {error}
201 </Text>
202 ) : null}
203 </View>
204 </View>
205 );
206}
207
208function RecoveryAction(props: {
209 readonly label: string;
210 readonly role?: "button" | "link";
211 readonly disabled: boolean;
212 readonly onPress: () => void;
213}) {
214 return (
215 <Pressable
216 accessibilityRole={props.role ?? "button"}
217 accessibilityState={{ disabled: props.disabled }}
218 disabled={props.disabled}
219 hitSlop={{ left: 8, right: 8 }}
220 onPress={props.onPress}
221 className="min-h-11 justify-center active:opacity-70"
222 >
223 <Text
224 className={
225 props.disabled
226 ? "text-sm font-t3-medium text-foreground-muted"
227 : "text-sm font-t3-medium text-primary"
228 }
229 >
230 {props.label}
231 </Text>
232 </Pressable>
233 );
234}