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

UsageLimitRecoveryBanner.tsx

189 lines6.4 KB

1import { T, msg, useGT } from "gt-react";
2import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3import { m, type MessageResolver } from "~/i18n/messages";
4import {
5 type OrchestrationV2LimitRecovery,
6 type OrchestrationV2LimitRecoveryUpdate,
7 type RunId,
8} from "@t3tools/contracts";
9import { type TimestampFormat } from "@t3tools/contracts/settings";
10import { deadlineStore } from "@t3tools/client-runtime/clock";
11import { limitRecoveryOwnsSnooze } from "@t3tools/client-runtime/state/thread-execution";
12import {
13 CHATGPT_USAGE_LIMIT_CODE,
14 CHATGPT_WORKSPACE_USAGE_LIMIT_CODE,
15} from "@t3tools/shared/usageLimits";
16import { GaugeIcon } from "lucide-react";
17import { useState } from "react";
18import { useDeadlinePassed } from "../../hooks/useDeadline";
19import { OpenAI } from "../Icons";
20import { ChatGptUsageButton } from "../settings/ChatGptUsageButton";
21import { Button, InlineButton } from "../ui/button";
22import { formatUpcomingTimestamp } from "../../timestampFormat";
23import { toastManager } from "../ui/toast";
24import type { ComposerBannerStackItem } from "./ComposerBannerStack";
25import { copyAdminRequest } from "./ThreadErrorBanner";
26​
27type RecoveryProps = {
28 runId: RunId;
29 errorCode: string | null;
30 resetAt: string | null;
31 stoppedAt: string;
32 settled: boolean;
33 requestPending: boolean;
34 snoozedUntil: string | null;
35 recovery: OrchestrationV2LimitRecovery | null;
36 timestampFormat: TimestampFormat;
37 onChange: (recovery: OrchestrationV2LimitRecoveryUpdate) => Promise<void>;
38};
39​
40export function usageLimitRecoveryBannerItem(
41 props: RecoveryProps,
42 resolve: MessageResolver = m,
43): ComposerBannerStackItem {
44 const {
45 runId,
46 errorCode,
47 resetAt,
48 stoppedAt,
49 settled,
50 requestPending,
51 recovery,
52 snoozedUntil,
53 timestampFormat,
54 } = props;
55 // The server refuses recovery changes while a request is pending.
56 const canSchedule =
57 !settled && !requestPending && resetAt !== null && Date.parse(resetAt) > Date.parse(stoppedAt);
58 const resumes =
59 canSchedule && recovery?.runId === runId && recovery.resetAt === resetAt && recovery.autoResume;
60 const workspaceLimit = errorCode === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE;
61 const chatGptLimit = workspaceLimit || errorCode === CHATGPT_USAGE_LIMIT_CODE;
62 const recoveryActions = canSchedule ? (
63 <RecoveryActions key={`${runId}:${resetAt}`} {...props} />
64 ) : null;
65 const displayAt =
66 resumes && resetAt && snoozedUntil && Date.parse(snoozedUntil) > Date.parse(resetAt)
67 ? snoozedUntil
68 : resetAt;
69 const resetDescription = displayAt
70 ? resumes
71 ? resolve(
72 msg("Resumes {time}", {
73 time: formatUpcomingTimestamp(
74 displayAt,
75 timestampFormat,
76 undefined,
77 undefined,
78 resolve,
79 ),
80 }),
81 )
82 : resolve(
83 msg("Resets {time}", {
84 time: formatUpcomingTimestamp(
85 displayAt,
86 timestampFormat,
87 undefined,
88 undefined,
89 resolve,
90 ),
91 }),
92 )
93 : resolve(msg("Reset time unavailable; retry manually"));
94 if (!chatGptLimit) {
95 return {
96 id: `usage-limit-recovery:${runId}`,
97 variant: "warning",
98 group: "environment",
99 icon: <GaugeIcon />,
100 title: resolve(msg("Usage limit reached")),
101 description: resetDescription,
102 actions: recoveryActions,
103 };
104 }
105 // OpenAI's partner guidelines specify this ChatGPT notice and its actions.
106 return {
107 id: `usage-limit-recovery:${runId}`,
108 variant: "warning",
109 group: "environment",
110 icon: <OpenAI aria-hidden="true" />,
111 title: resolve(msg("ChatGPT usage limit reached")),
112 description: workspaceLimit
113 ? resolve(
114 msg("You've reached your workspace's limit for using your ChatGPT plan in other apps."),
115 )
116 : resetDescription,
117 actions: (
118 <>
119 {recoveryActions}
120 {workspaceLimit ? (
121 <Button size="xs" variant="ghost" onClick={copyAdminRequest}>
122 <T>Copy request for admin</T>
123 </Button>
124 ) : (
125 <ChatGptUsageButton size="xs" variant="ghost" />
126 )}
127 </>
128 ),
129 };
131​
132function RecoveryActions({ runId, resetAt, recovery, snoozedUntil, onChange }: RecoveryProps) {
133 const gt = useGT();
134 const [pending, setPending] = useState(false);
135​
136 const scheduled =
137 recovery?.runId === runId && recovery.resetAt === resetAt && recovery.autoResume;
138 // The server leaves snoozedUntil in place after the timer wakes the thread,
139 // so a snooze whose reset has passed is no longer active.
140 const resetPassed = useDeadlinePassed(resetAt === null ? null : Date.parse(resetAt));
141 const snoozed =
142 limitRecoveryOwnsSnooze({ runId, resetAt, recovery, snoozedUntil }) && !resetPassed;
143 async function toggle(action: "resume" | "snooze") {
144 if (resetAt === null) return;
145 if (action === "snooze" && !snoozed && Date.parse(resetAt) <= Date.now()) {
146 toastManager.add({
147 type: "error",
148 title: m(msg("Could not snooze thread")),
149 description: m(msg("The reset time has passed. Retry the thread manually.")),
150 });
151 // The deadline timer can lag after a throttled tab or sleep; disable now.
152 deadlineStore(Date.parse(resetAt)).refresh();
153 return;
154 }
155 setPending(true);
156 try {
157 await onChange({
158 runId,
159 resetAt,
160 ...(action === "resume" ? { autoResume: !scheduled } : { snooze: !snoozed }),
161 });
162 } catch (cause) {
163 toastManager.add({
164 type: "error",
165 title:
166 action === "resume"
167 ? m(msg("Could not change auto-resume"))
168 : m(msg("Could not snooze thread")),
169 description: thrownErrorMessage(cause, m) ?? m(msg("An error occurred.")),
170 });
171 }
172 setPending(false);
173 }
174 // Inline errors would widen the actions column and crush the title.
175 return (
176 <span className="flex flex-wrap items-center gap-x-3 gap-y-1 px-1">
177 <InlineButton touchTarget="padded" disabled={pending} onClick={() => void toggle("resume")}>
178 {pending ? gt("Saving...") : scheduled ? gt("Cancel auto-resume") : gt("Resume at reset")}
179 </InlineButton>
180 <InlineButton
181 touchTarget="padded"
182 disabled={pending || (!snoozed && resetPassed)}
183 onClick={() => void toggle("snooze")}
184 >
185 {pending ? gt("Saving...") : snoozed ? gt("Wake now") : gt("Snooze until reset")}
186 </InlineButton>
187 </span>
188 );