TypeScript
fix(mobile): one aligned notice for ChatGPT sharing limits (#31277)
shivam8a14762c9093
diff --git a/apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsx b/apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsxdeleted file mode 100644index faebfa5ddf9..00000000000--- a/apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsx+++ /dev/null@@ -1,69 +0,0 @@-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 be338a76a0b..c7a37b2938f 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -14,7 +14,6 @@ import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entitieimport { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-visits";import { useChildThreadInputs, useThreadReportedModelSelection } from "../../state/entities";import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard";-import { ChatGptUsageLimitNotice } from "./ChatGptUsageLimitNotice";import { useFocusEffect, useNavigation } from "@react-navigation/native";import {effectiveSnoozed,@@ -1618,10 +1617,6 @@ function ThreadDetailBody(thread={props.selectedThread}environmentId={props.environmentId}/>- <ChatGptUsageLimitNotice- key={`chatgpt-limit:${props.selectedThread.latestRun?.runId}`}- thread={props.selectedThread}- /><ChildThreadApprovalsthreadRef={props.selectedThreadDetailRef}maxHeight={pendingUserInputMaxHeight}diff --git a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.test.tsx b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.test.tsxindex 59210f74273..92dd11f67b3 100644--- a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.test.tsx+++ b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.test.tsx@@ -1,5 +1,10 @@import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";import type { EnvironmentId } from "@t3tools/contracts";+import {+ CHATGPT_USAGE_LIMIT_CODE,+ CHATGPT_WORKSPACE_USAGE_LIMIT_CODE,+} from "@t3tools/shared/usageLimits";+import * as Clipboard from "expo-clipboard";import type { ReactNode } from "react";import { act } from "react";import { createRoot } from "react-dom/client";@@ -8,8 +13,16 @@ import { describe, expect, it, vi } from "vite-plus/test";type ButtonProps = { label: string; disabled?: boolean; onPress: () => void };vi.mock("react-native", () => ({+ Linking: { openURL: vi.fn() },+ Pressable: ({ children, disabled, onPress }: ButtonProps & { children: ReactNode }) => (+ <button type="button" disabled={disabled} onClick={onPress}>+ {children}+ </button>+ ),View: ({ children }: { children: ReactNode }) => <div>{children}</div>,}));+vi.mock("expo-clipboard", () => ({ setStringAsync: vi.fn() }));+vi.mock("../../components/ProviderIcon", () => ({ ProviderIcon: () => null }));vi.mock("../../components/ui/AppText", () => ({AppText: ({ children }: { children: ReactNode }) => <span>{children}</span>,}));@@ -27,18 +40,97 @@ import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard";const DAY_MS = 24 * 60 * 60 * 1000;-function failedThread(resetAt: string): EnvironmentThreadShell {+function failedThread(+ resetAt: string | null,+ lastErrorCode?: string,+ lastErrorClass = "usage_limit",+): EnvironmentThreadShell {return {id: "thread-1",updatedAt: new Date(0).toISOString(),snoozedUntil: null,latestRun: { runId: "run-1", completedAt: new Date(0).toISOString() },limitRecovery: null,- runtime: { status: "failed", lastErrorClass: "usage_limit", usageLimitResetAt: resetAt },+ runtime: { status: "failed", lastErrorClass, lastErrorCode, usageLimitResetAt: resetAt },} as unknown as EnvironmentThreadShell;}describe("UsageLimitRecoveryCard", () => {+ // Older servers report ChatGPT sharing limits as provider errors and may store a reset.+ it.each([+ [CHATGPT_USAGE_LIMIT_CODE, "usage_limit", null, ["Manage usage"]],+ [CHATGPT_WORKSPACE_USAGE_LIMIT_CODE, "usage_limit", null, ["Copy request for admin"]],+ [CHATGPT_USAGE_LIMIT_CODE, "provider_error", null, ["Manage usage"]],+ [+ CHATGPT_USAGE_LIMIT_CODE,+ "usage_limit",+ new Date(DAY_MS).toISOString(),+ ["Manage usage", "Resume at reset", "Snooze until reset"],+ ],+ ])("shows one ChatGPT notice for %s (%s, reset %s)", (code, errorClass, resetAt, actions) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };+ act(() =>+ root.render(+ <UsageLimitRecoveryCard+ thread={failedThread(resetAt, code, errorClass)}+ environmentId={"env-1" as EnvironmentId}+ />,+ ),+ );+ expect(container.textContent).toContain("ChatGPT usage limit reached");+ expect(container.textContent).not.toContain("did not report a reset time");+ expect([...container.querySelectorAll("button")].map((button) => button.textContent)).toEqual(+ actions,+ );+ });++ it("drops a failed copy's error once a retry copies the request", async () => {+ vi.mocked(Clipboard.setStringAsync)+ .mockRejectedValueOnce(new Error("denied"))+ .mockResolvedValueOnce(true);+ const container = document.createElement("div");+ const root = createRoot(container);+ using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };+ act(() =>+ root.render(+ <UsageLimitRecoveryCard+ thread={failedThread(null, CHATGPT_WORKSPACE_USAGE_LIMIT_CODE)}+ environmentId={"env-1" as EnvironmentId}+ />,+ ),+ );+ const copy = () => container.querySelector("button")!.click();+ await act(async () => copy());+ expect(container.textContent).toContain("Could not copy the request");+ await act(async () => copy());+ expect(container.textContent).toContain("Request copied");+ expect(container.textContent).not.toContain("Could not copy the request");+ });++ it("ignores a second copy while the first is still in flight", async () => {+ const first = Promise.withResolvers<boolean>();+ vi.mocked(Clipboard.setStringAsync).mockReset().mockReturnValueOnce(first.promise);+ const container = document.createElement("div");+ const root = createRoot(container);+ using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };+ act(() =>+ root.render(+ <UsageLimitRecoveryCard+ thread={failedThread(null, CHATGPT_WORKSPACE_USAGE_LIMIT_CODE)}+ environmentId={"env-1" as EnvironmentId}+ />,+ ),+ );+ const copy = () => container.querySelector("button")!.click();+ act(() => copy());+ act(() => copy());+ expect(Clipboard.setStringAsync).toHaveBeenCalledTimes(1);+ await act(async () => first.resolve(true));+ expect(container.textContent).toContain("Request copied");+ });+it("disables Snooze once a reset more than 24.8 days away passes", () => {using _timers = { [Symbol.dispose]: () => vi.useRealTimers() };vi.useFakeTimers({ now: 0 });diff --git a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsxindex 791dc2ab5d8..27fece0272b 100644--- a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx+++ b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx@@ -3,9 +3,17 @@ import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"import { AsyncResult } from "effect/reactivity";import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";import type { EnvironmentId } from "@t3tools/contracts";+import {+ CHATGPT_USAGE_LIMIT_CODE,+ CHATGPT_USAGE_URL,+ CHATGPT_WORKSPACE_ADMIN_REQUEST,+ CHATGPT_WORKSPACE_USAGE_LIMIT_CODE,+} from "@t3tools/shared/usageLimits";import * as DateTime from "effect/DateTime";+import * as Clipboard from "expo-clipboard";import { useState } from "react";-import { View } from "react-native";+import { Linking, Pressable, View } from "react-native";+import { ProviderIcon } from "../../components/ProviderIcon";import { AppText as Text } from "../../components/ui/AppText";import { useDeadlinePassed } from "../../lib/clock";import { threadEnvironment } from "../../state/threads";@@ -30,12 +38,22 @@ export function UsageLimitRecoveryCard({const recovery = thread.limitRecovery;const scheduled =recovery?.runId === runId && recovery?.resetAt === resetAt && recovery?.autoResume;+ const [copied, setCopied] = useState(false);+ const [actionPending, setActionPending] = useState(false);+ const code = thread.runtime?.lastErrorCode;+ // OpenAI's partner guidelines specify the ChatGPT notice and its action.+ const workspaceLimit = code === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE;+ const chatGptLimit = workspaceLimit || code === CHATGPT_USAGE_LIMIT_CODE;if (thread.runtime?.status !== "failed" ||- thread.runtime.lastErrorClass !== "usage_limit" ||+ // Older servers report ChatGPT sharing limits as provider errors.+ (thread.runtime.lastErrorClass !== "usage_limit" && !chatGptLimit) ||!runId)return null;+ const resetText = resetAt+ ? `Usage limit resets ${DateTime.toDateUtc(DateTime.makeUnsafe(resetAt)).toLocaleString()}.`+ : null;const snoozed =recovery?.snooze === true &&recovery.runId === runId &&@@ -68,34 +86,95 @@ export function UsageLimitRecoveryCard({setError(cause instanceof Error ? cause.message : "Could not change limit recovery.");}}+ const action = workspaceLimit+ ? {+ label: "Copy request for admin",+ role: "button" as const,+ run: () => {+ setError(null);+ setCopied(false);+ setActionPending(true);+ void Clipboard.setStringAsync(CHATGPT_WORKSPACE_ADMIN_REQUEST)+ .then(+ () => setCopied(true),+ () => setError("Could not copy the request. Try again."),+ )+ .finally(() => setActionPending(false));+ },+ }+ : {+ label: "Manage usage",+ role: "link" as const,+ run: () => {+ setError(null);+ setActionPending(true);+ void Linking.openURL(CHATGPT_USAGE_URL)+ .catch(() => setError("Could not open ChatGPT. Go to chatgpt.com → Settings → Usage."))+ .finally(() => setActionPending(false));+ },+ };return (- <View className="mx-3 mb-2 gap-2 rounded-xl border border-warning-foreground/25 bg-screen p-3">- <Text className="text-sm text-warning-foreground">- {resetAt- ? `Usage limit resets ${DateTime.toDateUtc(DateTime.makeUnsafe(resetAt)).toLocaleString()}.`- : "The provider did not report a reset time. Retry manually when your limit is available."}- </Text>- {canSchedule ? (- <View className="flex-row flex-wrap gap-2">- <Button- label={scheduled ? "Cancel auto-resume" : "Resume at reset"}- tone="secondary"- disabled={pending}- onPress={() => void toggle("resume")}- />- <Button- label={snoozed ? "Wake now" : "Snooze until reset"}- tone="secondary"- disabled={pending || (!snoozed && resetPassed)}- onPress={() => void toggle("snooze")}- />+ <View+ accessibilityRole={chatGptLimit ? "alert" : undefined}+ className="mx-3 mb-2 flex-row gap-2 rounded-xl border border-warning-foreground/25 bg-screen p-3"+ >+ {chatGptLimit ? (+ <View className="pt-0.5">+ <ProviderIcon provider="codex" size={16} /></View>) : null}- {error ? (- <Text accessibilityRole="alert" className="text-sm text-destructive">- {error}- </Text>- ) : null}+ <View className="min-w-0 flex-1 gap-2">+ {chatGptLimit ? (+ <View className="gap-1">+ <Text className="text-sm font-t3-medium text-foreground">+ ChatGPT usage limit reached+ </Text>+ <Text className="text-sm text-foreground-muted">+ {workspaceLimit+ ? 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."+ : (resetText ?? "Review your usage settings in ChatGPT.")}+ </Text>+ <Pressable+ accessibilityRole={action.role}+ accessibilityState={{ disabled: actionPending }}+ disabled={actionPending}+ hitSlop={14}+ className="mt-1 self-start active:opacity-70"+ onPress={action.run}+ >+ <Text className="text-sm font-t3-medium text-primary">{action.label}</Text>+ </Pressable>+ </View>+ ) : (+ <Text className="text-sm text-warning-foreground">+ {resetText ??+ "The provider did not report a reset time. Retry manually when your limit is available."}+ </Text>+ )}+ {canSchedule ? (+ <View className="flex-row flex-wrap gap-2">+ <Button+ label={scheduled ? "Cancel auto-resume" : "Resume at reset"}+ tone="secondary"+ disabled={pending}+ onPress={() => void toggle("resume")}+ />+ <Button+ label={snoozed ? "Wake now" : "Snooze until reset"}+ tone="secondary"+ disabled={pending || (!snoozed && resetPassed)}+ onPress={() => void toggle("snooze")}+ />+ </View>+ ) : null}+ {error ? (+ <Text accessibilityRole="alert" className="text-sm text-destructive">+ {error}+ </Text>+ ) : null}+ </View></View>);}