Skip to content

Commit 8a14762

Browse files
shivamhwpclaudemaria-rcks
authored
fix(mobile): one aligned notice for ChatGPT sharing limits (#31277)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent 01a8db0 commit 8a14762

4 files changed

Lines changed: 200 additions & 103 deletions

File tree

‎apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsx‎

Lines changed: 0 additions & 69 deletions
This file was deleted.

‎apps/mobile/src/features/threads/ThreadDetailScreen.tsx‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entitie
1414
import { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-visits";
1515
import { useChildThreadInputs, useThreadReportedModelSelection } from "../../state/entities";
1616
import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard";
17-
import { ChatGptUsageLimitNotice } from "./ChatGptUsageLimitNotice";
1817
import { useFocusEffect, useNavigation } from "@react-navigation/native";
1918
import {
2019
effectiveSnoozed,
@@ -1618,10 +1617,6 @@ function ThreadDetailBody(
16181617
thread={props.selectedThread}
16191618
environmentId={props.environmentId}
16201619
/>
1621-
<ChatGptUsageLimitNotice
1622-
key={`chatgpt-limit:${props.selectedThread.latestRun?.runId}`}
1623-
thread={props.selectedThread}
1624-
/>
16251620
<ChildThreadApprovals
16261621
threadRef={props.selectedThreadDetailRef}
16271622
maxHeight={pendingUserInputMaxHeight}

‎apps/mobile/src/features/threads/UsageLimitRecoveryCard.test.tsx‎

Lines changed: 94 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
22
import type { EnvironmentId } from "@t3tools/contracts";
3+
import {
4+
CHATGPT_USAGE_LIMIT_CODE,
5+
CHATGPT_WORKSPACE_USAGE_LIMIT_CODE,
6+
} from "@t3tools/shared/usageLimits";
7+
import * as Clipboard from "expo-clipboard";
38
import type { ReactNode } from "react";
49
import { act } from "react";
510
import { createRoot } from "react-dom/client";
@@ -8,8 +13,16 @@ import { describe, expect, it, vi } from "vite-plus/test";
813
type ButtonProps = { label: string; disabled?: boolean; onPress: () => void };
914

1015
vi.mock("react-native", () => ({
16+
Linking: { openURL: vi.fn() },
17+
Pressable: ({ children, disabled, onPress }: ButtonProps & { children: ReactNode }) => (
18+
<button type="button" disabled={disabled} onClick={onPress}>
19+
{children}
20+
</button>
21+
),
1122
View: ({ children }: { children: ReactNode }) => <div>{children}</div>,
1223
}));
24+
vi.mock("expo-clipboard", () => ({ setStringAsync: vi.fn() }));
25+
vi.mock("../../components/ProviderIcon", () => ({ ProviderIcon: () => null }));
1326
vi.mock("../../components/ui/AppText", () => ({
1427
AppText: ({ children }: { children: ReactNode }) => <span>{children}</span>,
1528
}));
@@ -27,18 +40,97 @@ import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard";
2740

2841
const DAY_MS = 24 * 60 * 60 * 1000;
2942

30-
function failedThread(resetAt: string): EnvironmentThreadShell {
43+
function failedThread(
44+
resetAt: string | null,
45+
lastErrorCode?: string,
46+
lastErrorClass = "usage_limit",
47+
): EnvironmentThreadShell {
3148
return {
3249
id: "thread-1",
3350
updatedAt: new Date(0).toISOString(),
3451
snoozedUntil: null,
3552
latestRun: { runId: "run-1", completedAt: new Date(0).toISOString() },
3653
limitRecovery: null,
37-
runtime: { status: "failed", lastErrorClass: "usage_limit", usageLimitResetAt: resetAt },
54+
runtime: { status: "failed", lastErrorClass, lastErrorCode, usageLimitResetAt: resetAt },
3855
} as unknown as EnvironmentThreadShell;
3956
}
4057

4158
describe("UsageLimitRecoveryCard", () => {
59+
// Older servers report ChatGPT sharing limits as provider errors and may store a reset.
60+
it.each([
61+
[CHATGPT_USAGE_LIMIT_CODE, "usage_limit", null, ["Manage usage"]],
62+
[CHATGPT_WORKSPACE_USAGE_LIMIT_CODE, "usage_limit", null, ["Copy request for admin"]],
63+
[CHATGPT_USAGE_LIMIT_CODE, "provider_error", null, ["Manage usage"]],
64+
[
65+
CHATGPT_USAGE_LIMIT_CODE,
66+
"usage_limit",
67+
new Date(DAY_MS).toISOString(),
68+
["Manage usage", "Resume at reset", "Snooze until reset"],
69+
],
70+
])("shows one ChatGPT notice for %s (%s, reset %s)", (code, errorClass, resetAt, actions) => {
71+
const container = document.createElement("div");
72+
const root = createRoot(container);
73+
using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
74+
act(() =>
75+
root.render(
76+
<UsageLimitRecoveryCard
77+
thread={failedThread(resetAt, code, errorClass)}
78+
environmentId={"env-1" as EnvironmentId}
79+
/>,
80+
),
81+
);
82+
expect(container.textContent).toContain("ChatGPT usage limit reached");
83+
expect(container.textContent).not.toContain("did not report a reset time");
84+
expect([...container.querySelectorAll("button")].map((button) => button.textContent)).toEqual(
85+
actions,
86+
);
87+
});
88+
89+
it("drops a failed copy's error once a retry copies the request", async () => {
90+
vi.mocked(Clipboard.setStringAsync)
91+
.mockRejectedValueOnce(new Error("denied"))
92+
.mockResolvedValueOnce(true);
93+
const container = document.createElement("div");
94+
const root = createRoot(container);
95+
using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
96+
act(() =>
97+
root.render(
98+
<UsageLimitRecoveryCard
99+
thread={failedThread(null, CHATGPT_WORKSPACE_USAGE_LIMIT_CODE)}
100+
environmentId={"env-1" as EnvironmentId}
101+
/>,
102+
),
103+
);
104+
const copy = () => container.querySelector("button")!.click();
105+
await act(async () => copy());
106+
expect(container.textContent).toContain("Could not copy the request");
107+
await act(async () => copy());
108+
expect(container.textContent).toContain("Request copied");
109+
expect(container.textContent).not.toContain("Could not copy the request");
110+
});
111+
112+
it("ignores a second copy while the first is still in flight", async () => {
113+
const first = Promise.withResolvers<boolean>();
114+
vi.mocked(Clipboard.setStringAsync).mockReset().mockReturnValueOnce(first.promise);
115+
const container = document.createElement("div");
116+
const root = createRoot(container);
117+
using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
118+
act(() =>
119+
root.render(
120+
<UsageLimitRecoveryCard
121+
thread={failedThread(null, CHATGPT_WORKSPACE_USAGE_LIMIT_CODE)}
122+
environmentId={"env-1" as EnvironmentId}
123+
/>,
124+
),
125+
);
126+
const copy = () => container.querySelector("button")!.click();
127+
act(() => copy());
128+
act(() => copy());
129+
expect(Clipboard.setStringAsync).toHaveBeenCalledTimes(1);
130+
await act(async () => first.resolve(true));
131+
expect(container.textContent).toContain("Request copied");
132+
});
133+
42134
it("disables Snooze once a reset more than 24.8 days away passes", () => {
43135
using _timers = { [Symbol.dispose]: () => vi.useRealTimers() };
44136
vi.useFakeTimers({ now: 0 });

‎apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx‎

Lines changed: 106 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,17 @@ import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"
33
import { AsyncResult } from "effect/reactivity";
44
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
55
import type { EnvironmentId } from "@t3tools/contracts";
6+
import {
7+
CHATGPT_USAGE_LIMIT_CODE,
8+
CHATGPT_USAGE_URL,
9+
CHATGPT_WORKSPACE_ADMIN_REQUEST,
10+
CHATGPT_WORKSPACE_USAGE_LIMIT_CODE,
11+
} from "@t3tools/shared/usageLimits";
612
import * as DateTime from "effect/DateTime";
13+
import * as Clipboard from "expo-clipboard";
714
import { useState } from "react";
8-
import { View } from "react-native";
15+
import { Linking, Pressable, View } from "react-native";
16+
import { ProviderIcon } from "../../components/ProviderIcon";
917
import { AppText as Text } from "../../components/ui/AppText";
1018
import { useDeadlinePassed } from "../../lib/clock";
1119
import { threadEnvironment } from "../../state/threads";
@@ -30,12 +38,22 @@ export function UsageLimitRecoveryCard({
3038
const recovery = thread.limitRecovery;
3139
const scheduled =
3240
recovery?.runId === runId && recovery?.resetAt === resetAt && recovery?.autoResume;
41+
const [copied, setCopied] = useState(false);
42+
const [actionPending, setActionPending] = useState(false);
43+
const code = thread.runtime?.lastErrorCode;
44+
// OpenAI's partner guidelines specify the ChatGPT notice and its action.
45+
const workspaceLimit = code === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE;
46+
const chatGptLimit = workspaceLimit || code === CHATGPT_USAGE_LIMIT_CODE;
3347
if (
3448
thread.runtime?.status !== "failed" ||
35-
thread.runtime.lastErrorClass !== "usage_limit" ||
49+
// Older servers report ChatGPT sharing limits as provider errors.
50+
(thread.runtime.lastErrorClass !== "usage_limit" && !chatGptLimit) ||
3651
!runId
3752
)
3853
return null;
54+
const resetText = resetAt
55+
? `Usage limit resets ${DateTime.toDateUtc(DateTime.makeUnsafe(resetAt)).toLocaleString()}.`
56+
: null;
3957
const snoozed =
4058
recovery?.snooze === true &&
4159
recovery.runId === runId &&
@@ -68,34 +86,95 @@ export function UsageLimitRecoveryCard({
6886
setError(cause instanceof Error ? cause.message : "Could not change limit recovery.");
6987
}
7088
}
89+
const action = workspaceLimit
90+
? {
91+
label: "Copy request for admin",
92+
role: "button" as const,
93+
run: () => {
94+
setError(null);
95+
setCopied(false);
96+
setActionPending(true);
97+
void Clipboard.setStringAsync(CHATGPT_WORKSPACE_ADMIN_REQUEST)
98+
.then(
99+
() => setCopied(true),
100+
() => setError("Could not copy the request. Try again."),
101+
)
102+
.finally(() => setActionPending(false));
103+
},
104+
}
105+
: {
106+
label: "Manage usage",
107+
role: "link" as const,
108+
run: () => {
109+
setError(null);
110+
setActionPending(true);
111+
void Linking.openURL(CHATGPT_USAGE_URL)
112+
.catch(() => setError("Could not open ChatGPT. Go to chatgpt.com → Settings → Usage."))
113+
.finally(() => setActionPending(false));
114+
},
115+
};
71116
return (
72-
<View className="mx-3 mb-2 gap-2 rounded-xl border border-warning-foreground/25 bg-screen p-3">
73-
<Text className="text-sm text-warning-foreground">
74-
{resetAt
75-
? `Usage limit resets ${DateTime.toDateUtc(DateTime.makeUnsafe(resetAt)).toLocaleString()}.`
76-
: "The provider did not report a reset time. Retry manually when your limit is available."}
77-
</Text>
78-
{canSchedule ? (
79-
<View className="flex-row flex-wrap gap-2">
80-
<Button
81-
label={scheduled ? "Cancel auto-resume" : "Resume at reset"}
82-
tone="secondary"
83-
disabled={pending}
84-
onPress={() => void toggle("resume")}
85-
/>
86-
<Button
87-
label={snoozed ? "Wake now" : "Snooze until reset"}
88-
tone="secondary"
89-
disabled={pending || (!snoozed && resetPassed)}
90-
onPress={() => void toggle("snooze")}
91-
/>
117+
<View
118+
accessibilityRole={chatGptLimit ? "alert" : undefined}
119+
className="mx-3 mb-2 flex-row gap-2 rounded-xl border border-warning-foreground/25 bg-screen p-3"
120+
>
121+
{chatGptLimit ? (
122+
<View className="pt-0.5">
123+
<ProviderIcon provider="codex" size={16} />
92124
</View>
93125
) : null}
94-
{error ? (
95-
<Text accessibilityRole="alert" className="text-sm text-destructive">
96-
{error}
97-
</Text>
98-
) : null}
126+
<View className="min-w-0 flex-1 gap-2">
127+
{chatGptLimit ? (
128+
<View className="gap-1">
129+
<Text className="text-sm font-t3-medium text-foreground">
130+
ChatGPT usage limit reached
131+
</Text>
132+
<Text className="text-sm text-foreground-muted">
133+
{workspaceLimit
134+
? copied
135+
? "Request copied. Send it to your workspace admin."
136+
: "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."
137+
: (resetText ?? "Review your usage settings in ChatGPT.")}
138+
</Text>
139+
<Pressable
140+
accessibilityRole={action.role}
141+
accessibilityState={{ disabled: actionPending }}
142+
disabled={actionPending}
143+
hitSlop={14}
144+
className="mt-1 self-start active:opacity-70"
145+
onPress={action.run}
146+
>
147+
<Text className="text-sm font-t3-medium text-primary">{action.label}</Text>
148+
</Pressable>
149+
</View>
150+
) : (
151+
<Text className="text-sm text-warning-foreground">
152+
{resetText ??
153+
"The provider did not report a reset time. Retry manually when your limit is available."}
154+
</Text>
155+
)}
156+
{canSchedule ? (
157+
<View className="flex-row flex-wrap gap-2">
158+
<Button
159+
label={scheduled ? "Cancel auto-resume" : "Resume at reset"}
160+
tone="secondary"
161+
disabled={pending}
162+
onPress={() => void toggle("resume")}
163+
/>
164+
<Button
165+
label={snoozed ? "Wake now" : "Snooze until reset"}
166+
tone="secondary"
167+
disabled={pending || (!snoozed && resetPassed)}
168+
onPress={() => void toggle("snooze")}
169+
/>
170+
</View>
171+
) : null}
172+
{error ? (
173+
<Text accessibilityRole="alert" className="text-sm text-destructive">
174+
{error}
175+
</Text>
176+
) : null}
177+
</View>
99178
</View>
100179
);
101180
}

0 commit comments

Comments
 (0)