Open History to see the last commit
1import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2import type { EnvironmentId } from "@t3tools/contracts";
3import {
4 CHATGPT_USAGE_LIMIT_CODE,
5 CHATGPT_WORKSPACE_USAGE_LIMIT_CODE,
6} from "@t3tools/shared/usageLimits";
7import * as Clipboard from "expo-clipboard";
8import type { ReactNode } from "react";
9import { act } from "react";
10import { createRoot } from "react-dom/client";
11import { describe, expect, it, vi } from "vite-plus/test";
12
13type ButtonProps = { label: string; disabled?: boolean; onPress: () => void };
14
15vi.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 ),
22 View: ({ children }: { children: ReactNode }) => <div>{children}</div>,
23}));
24vi.mock("expo-clipboard", () => ({ setStringAsync: vi.fn() }));
25vi.mock("../../components/ProviderIcon", () => ({ ProviderIcon: () => null }));
26vi.mock("../../components/ui/AppText", () => ({
27 AppText: ({ children }: { children: ReactNode }) => <span>{children}</span>,
28}));
29vi.mock("../../components/ui/Button", () => ({
30 Button: ({ label, disabled, onPress }: ButtonProps) => (
31 <button type="button" disabled={disabled} onClick={onPress}>
32 {label}
33 </button>
34 ),
35}));
36vi.mock("../../state/threads", () => ({ threadEnvironment: { updateMetadata: {} } }));
37vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
38
39import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard";
40
41const DAY_MS = 24 * 60 * 60 * 1000;
42
43function failedThread(
44 resetAt: string | null,
45 lastErrorCode?: string,
46 lastErrorClass = "usage_limit",
47): EnvironmentThreadShell {
48 return {
49 id: "thread-1",
50 updatedAt: new Date(0).toISOString(),
51 snoozedUntil: null,
52 latestRun: { runId: "run-1", completedAt: new Date(0).toISOString() },
53 limitRecovery: null,
54 runtime: { status: "failed", lastErrorClass, lastErrorCode, usageLimitResetAt: resetAt },
55 } as unknown as EnvironmentThreadShell;
56}
57
58describe("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
134 it("disables Snooze once a reset more than 24.8 days away passes", () => {
135 using _timers = { [Symbol.dispose]: () => vi.useRealTimers() };
136 vi.useFakeTimers({ now: 0 });
137 const container = document.createElement("div");
138 const root = createRoot(container);
139 using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
140 act(() =>
141 root.render(
142 <UsageLimitRecoveryCard
143 thread={failedThread(new Date(30 * DAY_MS).toISOString())}
144 environmentId={"env-1" as EnvironmentId}
145 />,
146 ),
147 );
148 const snooze = () =>
149 [...container.querySelectorAll("button")].find(
150 (button) => button.textContent === "Snooze until reset",
151 );
152 expect(snooze()?.disabled).toBe(false);
153
154 act(() => vi.advanceTimersByTime(30 * DAY_MS));
155
156 expect(snooze()?.disabled).toBe(true);
157 });
158});