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

UsageLimitRecoveryBanner.tsx

155 lines5.6 KB

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