TypeScript
feat: ChatGPT Business usage limits offer a copyable admin request (#23361)
Julius Marminge6f75bcb374c0
diff --git a/apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsx b/apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsxnew file mode 100644index 00000000000..faebfa5ddf9--- /dev/null+++ b/apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsx@@ -0,0 +1,69 @@+import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";+import {+ CHATGPT_USAGE_LIMIT_CODE,+ CHATGPT_USAGE_URL,+ CHATGPT_WORKSPACE_ADMIN_REQUEST,+ CHATGPT_WORKSPACE_USAGE_LIMIT_CODE,+} from "@t3tools/shared/usageLimits";+import * as Clipboard from "expo-clipboard";+import { useState } from "react";+import { Linking, View } from "react-native";+import { ProviderIcon } from "../../components/ProviderIcon";+import { AppText as Text } from "../../components/ui/AppText";+import { Button } from "../../components/ui/Button";++export function ChatGptUsageLimitNotice({ thread }: { thread: EnvironmentThreadShell }) {+ const [status, setStatus] = useState<"copied" | "copy-failed" | "open-failed" | null>(null);+ const code = thread.runtime?.lastErrorCode;+ const workspaceLimit = code === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE;+ if (thread.runtime?.status !== "failed" || (!workspaceLimit && code !== CHATGPT_USAGE_LIMIT_CODE))+ return null;+ return (+ <View+ accessibilityRole="alert"+ className="mx-3 mb-2 gap-2 rounded-xl border border-border-subtle bg-screen p-3"+ >+ <View className="flex-row items-center gap-2">+ <ProviderIcon provider="codex" size={16} />+ <Text className="text-sm font-t3-medium text-foreground">ChatGPT usage limit reached</Text>+ </View>+ <Text className="text-xs text-foreground-muted">+ {workspaceLimit+ ? status === "copied"+ ? "Request copied. Send it to your workspace admin."+ : "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."+ : "Review your usage settings in ChatGPT."}+ </Text>+ {workspaceLimit ? (+ <Button+ label="Copy request for admin"+ tone="primary"+ onPress={() =>+ void Clipboard.setStringAsync(CHATGPT_WORKSPACE_ADMIN_REQUEST).then(+ () => setStatus("copied"),+ () => setStatus("copy-failed"),+ )+ }+ />+ ) : (+ <Button+ label="Manage usage"+ tone="primary"+ onPress={() =>+ void Linking.openURL(CHATGPT_USAGE_URL).then(+ () => setStatus(null),+ () => setStatus("open-failed"),+ )+ }+ />+ )}+ {status === "copy-failed" || status === "open-failed" ? (+ <Text accessibilityRole="alert" className="text-xs text-destructive">+ {status === "copy-failed"+ ? "Could not copy the request. Try again."+ : "Could not open ChatGPT. Go to chatgpt.com → Settings → Usage."}+ </Text>+ ) : null}+ </View>+ );+}diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex b079dd7ebae..ad6489b1b63 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -12,6 +12,7 @@ import {useThreadShell,} from "../../state/entities";import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard";+import { ChatGptUsageLimitNotice } from "./ChatGptUsageLimitNotice";import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";import {effectiveSnoozed,@@ -1466,6 +1467,10 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetaithread={props.selectedThread}environmentId={props.environmentId}/>+ <ChatGptUsageLimitNotice+ key={`chatgpt-limit:${props.selectedThread.latestRun?.runId}`}+ thread={props.selectedThread}+ />{props.feedbackSubmissions.map((submission) => (<ComposerFeedbackkey={submission.id}diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.tsindex 5f00beb2fbc..840205edfa6 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts@@ -3922,6 +3922,13 @@ describe("CodexAdapterV2 post-settle continuation", () => {notification: false,expectedClass: "provider_error",},+ {+ name: "chatgpt-workspace-limit",+ code: "other",+ details: "subscription_sharing_workplace_individual_usage_limit_exceeded",+ notification: true,+ expectedClass: "provider_error",+ },] as const)("classifies Codex terminal failures from $name evidence", (scenario) =>Effect.scoped(Effect.gen(function* () {@@ -3999,9 +4006,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {message,codexErrorInfo: errorInfo,additionalDetails:- scenario.name === "matching-details"- ? "Detailed provider allowance explanation."- : null,+ "details" in scenario+ ? scenario.details+ : scenario.name === "matching-details"+ ? "Detailed provider allowance explanation."+ : null,},},},@@ -4019,7 +4028,9 @@ describe("CodexAdapterV2 post-settle continuation", () => {...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }),error: {message: scenario.name === "replacement" ? "A different failure." : message,- ...(scenario.notification && scenario.name !== "matching-details"+ ...(scenario.notification &&+ scenario.name !== "matching-details" &&+ !("details" in scenario)? {}: { codexErrorInfo: errorInfo }),},@@ -4101,6 +4112,10 @@ describe("CodexAdapterV2 post-settle continuation", () => {assert.isDefined(item);}if (scenario.name === "retry") assert.equal(terminal.retry?.attempt, 1);+ if (scenario.name === "chatgpt-workspace-limit") {+ assert.equal(terminal.failure.code, scenario.details);+ assert.include(terminal.failure.message, "workspace admin");+ }}).pipe(Effect.provide(Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.tsindex 5c4df98d310..067551ff9a9 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts@@ -14,6 +14,7 @@ import {} from "../../provider/CodexTurnTokenUsage.ts";import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot";import type { CodexEffectiveRuntime } from "../../provider/CodexManagedRuntime.ts";+import { classifyCodexManagedError } from "../../provider/CodexManagedErrors.ts";import {buildCodexInitializeParams,codexAppServerEnvironment,@@ -1134,10 +1135,25 @@ function codexUsageLimitError();}+/**+ * ChatGPT sharing reports its own reason inside Codex's generic turn error, so+ * the code it names replaces Codex's, and clients pick a recovery from it.+ */+function withCodexManagedFailure(+ failure: OrchestrationV2ProviderFailure,+ nativeError: unknown,+): OrchestrationV2ProviderFailure {+ const managed = classifyCodexManagedError(nativeError);+ return managed === undefined+ ? failure+ : { ...failure, message: managed.message, code: managed.code };+}+interface ActiveCodexTurnContext {closedCommandItemIds?: ReadonlySet<string>;latestProviderFailure?: {readonly nativeMessage: string;+ readonly nativeCode: string | null;readonly failure: OrchestrationV2ProviderFailure;};readonly nativeStartReady?: Deferred.Deferred<void>;@@ -1167,6 +1183,7 @@ interface ActiveCodexTurnContext {interface ActiveCodexProviderRetry {readonly nativeMessage: string;+ readonly nativeCode: string | null;readonly retry: OrchestrationV2ProviderRetry;readonly failure: OrchestrationV2ProviderFailure;readonly startedAt: DateTime.Utc;@@ -4563,13 +4580,17 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (if (!payload.willRetry) {context.latestProviderFailure = {nativeMessage: payload.error.message,- failure: makeProviderFailure({- message: payload.error.additionalDetails?.trim() || payload.error.message,- code: notificationCode,- class: codexUsageLimitError(notificationCode, payload.error.codexErrorInfo)- ? "usage_limit"- : "provider_error",- }),+ nativeCode: notificationCode,+ failure: withCodexManagedFailure(+ makeProviderFailure({+ message: payload.error.additionalDetails?.trim() || payload.error.message,+ code: notificationCode,+ class: codexUsageLimitError(notificationCode, payload.error.codexErrorInfo)+ ? "usage_limit"+ : "provider_error",+ }),+ payload.error,+ ),};return;}@@ -4583,24 +4604,28 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (};const code = codexErrorInfoCode(payload.error.codexErrorInfo);const additionalDetails = payload.error.additionalDetails?.trim();- const failure = makeProviderFailure({- message:- additionalDetails === undefined || additionalDetails.length === 0- ? payload.error.message- : additionalDetails,- code,- class: codexUsageLimitError(code, payload.error.codexErrorInfo)- ? "usage_limit"- : code?.startsWith("http") === true || code?.startsWith("responseStream") === true- ? "transport_error"- : "provider_error",- retryable: true,- });+ const failure = withCodexManagedFailure(+ makeProviderFailure({+ message:+ additionalDetails === undefined || additionalDetails.length === 0+ ? payload.error.message+ : additionalDetails,+ code,+ class: codexUsageLimitError(code, payload.error.codexErrorInfo)+ ? "usage_limit"+ : code?.startsWith("http") === true || code?.startsWith("responseStream") === true+ ? "transport_error"+ : "provider_error",+ retryable: true,+ }),+ payload.error,+ );const itemOrdinal =previous?.itemOrdinal ??(yield* resolveItemOrdinal(context, `terminal-failure:${context.providerTurnId}`));const state: ActiveCodexProviderRetry = {nativeMessage: payload.error.message,+ nativeCode: code,retry,failure,startedAt: previous?.startedAt ?? updatedAt,@@ -5656,14 +5681,17 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (previousFailure !== undefined &&(input.failureMessage === undefined ||input.failureMessage === previousFailure.nativeMessage) &&- (failureCode === undefined || failureCode === previousFailure.failure.code) &&+ (failureCode === undefined || failureCode === previousFailure.nativeCode) &&(exhaustionStatus === null || previousFailure.failure.class === failureClass)? previousFailure.failure- : makeProviderFailure({- message: input.failureMessage,- code: failureCode,- class: failureClass,- });+ : withCodexManagedFailure(+ makeProviderFailure({+ message: input.failureMessage,+ code: failureCode,+ class: failureClass,+ }),+ input.failureMessage,+ );return {type: "turn.terminal",driver: CODEX_PROVIDER,diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.tsindex 3fb7c152578..40ff180d274 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -1711,6 +1711,7 @@ type ShellThreadState = {readonly activityRunStartedAt: DateTime.Utc | null;readonly lastError: string | null;readonly lastErrorClass: OrchestrationV2ThreadShell["lastErrorClass"];+ readonly lastErrorCode: OrchestrationV2ThreadShell["lastErrorCode"];readonly usageLimitResetAt: OrchestrationV2ThreadShell["usageLimitResetAt"];readonly pendingRuntimeRequest: OrchestrationV2PendingRuntimeRequestSummary | null;readonly latestUserMessageAt: DateTime.Utc | null;@@ -1866,6 +1867,7 @@ function shellFromState(input: {status: input.state.latestRunStatus,lastError: input.state.lastError,lastErrorClass: input.state.lastErrorClass,+ lastErrorCode: input.state.lastErrorCode,usageLimitResetAt: input.state.usageLimitResetAt,pendingRuntimeRequest: input.state.pendingRuntimeRequest,latestVisibleMessage: null,diff --git a/apps/server/src/provider/CodexManagedErrors.ts b/apps/server/src/provider/CodexManagedErrors.tsindex 9c8fe26bbb6..f2ee114c74f 100644--- a/apps/server/src/provider/CodexManagedErrors.ts+++ b/apps/server/src/provider/CodexManagedErrors.ts@@ -9,6 +9,11 @@ const legacyFailures = {"Your ChatGPT usage limit was reached. Check ChatGPT Usage settings for your available allowance.",revoke: false,},+ subscription_sharing_workplace_individual_usage_limit_exceeded: {+ message:+ "You reached your workspace's limit for using ChatGPT in other apps. Ask your workspace admin to increase it.",+ revoke: false,+ },subscription_sharing_usage_unavailable: {message: "ChatGPT usage is temporarily unavailable. Try again shortly.",revoke: false,diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex d6569293072..a87d1a64f7e 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -816,6 +816,8 @@ export default function ChatView(props: ChatViewProps) {? threadError: null;const [, setThreadErrorBannerDismissTick] = useState(0);+ const threadErrorIsServerRuntimeError =+ localServerError === null && visibleThreadError === serverRuntime?.lastError;const defaultRuntimeMode = resolveProjectSettings(settings, activeThread?.projectId ?? null).settings.defaultRuntimeMode;const runtimeMode =@@ -3235,9 +3237,10 @@ export default function ChatView(props: ChatViewProps) {threadId={activeThread.id}threadError={timelineThreadError}threadErrorClass={- localServerError === null && visibleThreadError === serverRuntime?.lastError- ? (serverRuntime?.lastErrorClass ?? null)- : null+ threadErrorIsServerRuntimeError ? (serverRuntime?.lastErrorClass ?? null) : null+ }+ threadErrorCode={+ threadErrorIsServerRuntimeError ? (serverRuntime?.lastErrorCode ?? null) : null}threadErrorBannerKey={threadErrorBannerKey}setThreadError={setThreadError}diff --git a/apps/web/src/components/chat/ChatBannerLane.tsx b/apps/web/src/components/chat/ChatBannerLane.tsxindex e0af10ea449..41ee46353f9 100644--- a/apps/web/src/components/chat/ChatBannerLane.tsx+++ b/apps/web/src/components/chat/ChatBannerLane.tsx@@ -20,6 +20,7 @@ export function ChatBannerLane(props: {threadId: ThreadId;threadError: string | null;threadErrorClass: OrchestrationV2ProviderFailureClass | null;+ threadErrorCode: string | null;threadErrorBannerKey: string | null;setThreadError: (threadId: ThreadId | null, error: string | null) => void;setThreadErrorBannerDismissTick: Dispatch<SetStateAction<number>>;@@ -32,6 +33,7 @@ export function ChatBannerLane(props: {threadId,threadError,threadErrorClass,+ threadErrorCode,threadErrorBannerKey,setThreadError,setThreadErrorBannerDismissTick,@@ -46,6 +48,7 @@ export function ChatBannerLane(props: {<ThreadErrorBannererror={threadError}errorClass={threadErrorClass}+ errorCode={threadErrorCode}onDismiss={() => {setThreadError(threadId, null);dismissThreadErrorBannerForSession(threadErrorBannerKey);diff --git a/apps/web/src/components/chat/ThreadErrorBanner.tsx b/apps/web/src/components/chat/ThreadErrorBanner.tsxindex 198fbb687c6..0bc3b95b71b 100644--- a/apps/web/src/components/chat/ThreadErrorBanner.tsx+++ b/apps/web/src/components/chat/ThreadErrorBanner.tsx@@ -1,12 +1,31 @@import type { OrchestrationV2ProviderFailureClass } from "@t3tools/contracts";+import {+ CHATGPT_USAGE_LIMIT_CODE,+ CHATGPT_WORKSPACE_ADMIN_REQUEST,+ CHATGPT_WORKSPACE_USAGE_LIMIT_CODE,+} from "@t3tools/shared/usageLimits";import { memo } from "react";+import { writeTextToClipboard } from "../../hooks/useCopyToClipboard";import { Alert, AlertAction, AlertDescription } from "../ui/alert";import { Button } from "../ui/button";+import { toastManager } from "../ui/toast";import { CircleAlertIcon, XIcon } from "lucide-react";import { OpenAI } from "../Icons";import { ChatGptUsageButton } from "../settings/ChatGptUsageButton";import { ExpandableText } from "../settings/ExpandableText";+function copyAdminRequest() {+ void writeTextToClipboard(CHATGPT_WORKSPACE_ADMIN_REQUEST, "admin request").then(+ () =>+ toastManager.add({+ type: "success",+ title: "Request copied",+ description: "Send it to your workspace admin.",+ }),+ () => toastManager.add({ type: "error", title: "Could not copy the request" }),+ );+}+export function getThreadErrorBannerMessage(error: string): string {let payload: unknown;try {@@ -54,36 +73,48 @@ export const ThreadErrorBanner = memo(function ThreadErrorBanner({error,onDismiss,errorClass,- chatGptUsageLimit = false,+ errorCode,}: {error: string | null;errorClass?: OrchestrationV2ProviderFailureClass | null;+ errorCode?: string | null;onDismiss?: () => void;- chatGptUsageLimit?: boolean;}) {if (!error) return null;- const variant = errorClass === "usage_limit" ? "warning" : "error";+ const workspaceLimit = errorCode === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE;+ const chatGptLimit = workspaceLimit || errorCode === CHATGPT_USAGE_LIMIT_CODE;+ const variant = errorClass === "usage_limit" || chatGptLimit ? "warning" : "error";return (<div className="pointer-events-auto mx-auto w-fit max-w-[min(48rem,calc(100%-2rem))] pt-3"><Alert variant={variant} surface="glass" controlAlignment="first-line" data-variant={variant}>- {chatGptUsageLimit ? (+ {chatGptLimit ? (<OpenAI className="size-4 text-foreground!" aria-hidden="true" />) : (<CircleAlertIcon />)}<AlertDescription>- {chatGptUsageLimit ? (+ {chatGptLimit ? (<div className="space-y-1"><p className="font-medium">ChatGPT usage limit reached</p>- <p>Review your usage settings in ChatGPT to continue.</p>+ <p>+ {workspaceLimit+ ? "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."+ : "Review your usage settings in ChatGPT."}+ </p></div>) : (<ExpandableText text={error} collapsedText={getThreadErrorBannerMessage(error)} />)}</AlertDescription>- {(chatGptUsageLimit || onDismiss) && (+ {(chatGptLimit || onDismiss) && (<AlertAction>- {chatGptUsageLimit ? <ChatGptUsageButton variant="default" size="sm" /> : null}+ {workspaceLimit ? (+ <Button variant="default" size="sm" onClick={copyAdminRequest}>+ Copy request for admin+ </Button>+ ) : chatGptLimit ? (+ <ChatGptUsageButton variant="default" size="sm" />+ ) : null}{onDismiss ? (<Button variant="ghost" size="icon-xs" aria-label="Dismiss error" onClick={onDismiss}><XIcon />diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.tsindex ba78e2304d7..042d583c699 100644--- a/packages/client-runtime/src/state/models.ts+++ b/packages/client-runtime/src/state/models.ts@@ -60,6 +60,7 @@ export interface ThreadRuntimeSummary {readonly providerName: string | null;readonly lastError: string | null;readonly lastErrorClass?: OrchestrationV2ProviderFailureClass | null;+ readonly lastErrorCode?: string | null;readonly usageLimitResetAt?: string | null;readonly updatedAt: string;}@@ -185,6 +186,7 @@ function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummaryproviderName: null,lastError: thread.lastError ?? null,lastErrorClass: thread.lastErrorClass ?? null,+ lastErrorCode: thread.lastErrorCode ?? null,usageLimitResetAt: thread.usageLimitResetAt ?? null,updatedAt: iso(thread.updatedAt),};diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex fc211c946ec..881a316f59a 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -1838,6 +1838,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({status: OrchestrationV2ShellThreadStatus,lastError: Schema.optional(Schema.NullOr(Schema.String)),lastErrorClass: Schema.optional(Schema.NullOr(OrchestrationV2ProviderFailureClass)),+ lastErrorCode: Schema.optional(Schema.NullOr(Schema.String)),usageLimitResetAt: Schema.optional(Schema.NullOr(IsoDateTime)),pendingRuntimeRequest: Schema.NullOr(OrchestrationV2PendingRuntimeRequestSummary),latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummary),diff --git a/packages/shared/src/orchestrationV2ThreadError.ts b/packages/shared/src/orchestrationV2ThreadError.tsindex c1e92cc1335..3925a0e6aed 100644--- a/packages/shared/src/orchestrationV2ThreadError.ts+++ b/packages/shared/src/orchestrationV2ThreadError.ts@@ -41,8 +41,8 @@ export function threadErrorSummary(usageLimitResetAt:currentFailure?.class === "usage_limit" ? (currentFailure.resetAt ?? null) : null,lastError: sessionError ?? failure?.message ?? null,- lastErrorClass:- sessionError !== null && sessionError !== failure?.message ? null : (failure?.class ?? null),+ lastErrorClass: currentFailure?.class ?? null,+ lastErrorCode: currentFailure?.code ?? null,};}diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.tsindex fb66d453acd..2208b0a1461 100644--- a/packages/shared/src/usageLimits.ts+++ b/packages/shared/src/usageLimits.ts@@ -18,6 +18,13 @@ const HOUR = 60 * MINUTE;const DAY = 24 * HOUR;export const CHATGPT_USAGE_URL = "https://chatgpt.com/#settings/Usage";+export const CHATGPT_USAGE_LIMIT_CODE = "subscription_sharing_usage_limit_exceeded";+/** A ChatGPT Business admin caps plan use in other apps; only the admin can raise it. */+export const CHATGPT_WORKSPACE_USAGE_LIMIT_CODE =+ "subscription_sharing_workplace_individual_usage_limit_exceeded";+/** OpenAI's partner guidelines fix this wording; the user sends it to their admin themselves. */+export const CHATGPT_WORKSPACE_ADMIN_REQUEST =+ "I've reached the limit for using my ChatGPT plan in T3 Code. Could you increase our workspace's usage limits so I can continue?\n\nGo to admin.openai.com → Workspace → Usage limits. Thank you!";export function usesChatGptSharing(provider: ServerProvider | null | undefined): boolean {return provider?.auth.status === "authenticated" && provider.auth.subscriptionSharing === true;