Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsageLimitRecoveryCard.tsx

253 lines9.0 KB

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