Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import * as TestClock from "effect/testing/TestClock";
5import { HttpClient, HttpClientResponse } from "effect/unstable/http";
6
7import { creditRedeemRequestId, makeCliproxyApi } from "./cliproxyApi.ts";
8
9const config = {
10 kind: "cliproxy",
11 url: "http://hub.test:8317",
12 managementKey: "management-secret",
13 enabled: true,
14} as const;
15const accounts = [
16 {
17 id: "first.json",
18 auth_index: "a",
19 provider: "codex",
20 email: "first@example.com",
21 id_token: { chatgpt_account_id: "account-a" },
22 },
23 {
24 id: "second.json",
25 auth_index: "b",
26 provider: "codex",
27 email: "second@example.com",
28 id_token: { chatgpt_account_id: "account-b" },
29 },
30];
31const credit = (id: string, expires_at = "2099-01-01T00:00:00Z") => ({
32 id,
33 expires_at,
34 status: "available",
35 reset_type: "codex_rate_limits",
36});
37const RequestBody = Schema.Struct({
38 auth_index: Schema.String,
39 method: Schema.optional(Schema.String),
40 url: Schema.optional(Schema.String),
41 header: Schema.optional(Schema.Record(Schema.String, Schema.String)),
42 data: Schema.optional(Schema.String),
43});
44type RequestBody = typeof RequestBody.Type;
45const decodeRequest = Schema.decodeUnknownSync(Schema.fromJsonString(RequestBody));
46const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
47
48function fixture(
49 options: {
50 accounts?: Array<(typeof accounts)[number] & { disabled?: boolean }>;
51 upstream?: (request: RequestBody) => { status: number; body: unknown };
52 cooldownStatus?: number;
53 } = {},
54) {
55 const requests: Array<{ path: string; body?: RequestBody }> = [];
56 const http = HttpClient.make((request) =>
57 Effect.sync(() => {
58 expect(request.headers.authorization).toBe("Bearer management-secret");
59 const path = new URL(request.url).pathname;
60 const body =
61 request.body._tag === "Uint8Array"
62 ? decodeRequest(new TextDecoder().decode(request.body.body))
63 : undefined;
64 requests.push({ path, ...(body ? { body } : {}) });
65 if (path.endsWith("/auth-files"))
66 return HttpClientResponse.fromWeb(
67 request,
68 Response.json({ files: options.accounts ?? accounts }),
69 );
70 if (path.endsWith("/reset-quota"))
71 return HttpClientResponse.fromWeb(
72 request,
73 Response.json({}, { status: options.cooldownStatus ?? 200 }),
74 );
75 expect(path).toBe("/v0/management/api-call");
76 expect(body?.header?.Authorization).toBe("Bearer $TOKEN$");
77 const upstream = options.upstream?.(body!) ?? {
78 status: 200,
79 body: body?.url?.endsWith("/consume")
80 ? { code: "reset" }
81 : body?.url?.endsWith("/rate-limit-reset-credits")
82 ? {
83 credits: [
84 credit("later", "2099-02-01T00:00:00Z"),
85 credit("first"),
86 credit("expired", "2000-01-01T00:00:00Z"),
87 { ...credit("used"), status: "redeemed" },
88 ],
89 }
90 : {
91 plan_type: "pro",
92 rate_limit: {
93 secondary_window: {
94 used_percent: 78,
95 reset_at: 4070908800,
96 limit_window_seconds: 604800,
97 },
98 },
99 },
100 };
101 return HttpClientResponse.fromWeb(
102 request,
103 Response.json({ status_code: upstream.status, body: encodeJson(upstream.body) }),
104 );
105 }),
106 );
107 return {
108 requests,
109 api: makeCliproxyApi.pipe(Effect.provideService(HttpClient.HttpClient, http)),
110 };
111}
112
113describe("CLIProxyAPI built-in management API", () => {
114 it.effect(
115 "reads both accounts and their earliest unexpired credits without plugin endpoints",
116 () =>
117 Effect.gen(function* () {
118 yield* TestClock.setTime(1788710400000);
119 const test = fixture();
120 const api = yield* test.api;
121 const result = yield* api.readAccounts(config);
122 expect(result.map((account) => account.usageLimits.resetCredits)).toEqual([
123 { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
124 { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
125 ]);
126 expect(result[0]?.usageLimits.windows).toMatchObject([
127 { id: "secondary", usedPercent: 78, kind: "weekly" },
128 ]);
129 const calls = test.requests.filter((request) => request.body?.url);
130 expect(calls.map((request) => request.body?.auth_index).sort()).toEqual([
131 "a",
132 "a",
133 "b",
134 "b",
135 ]);
136 expect(
137 calls.find((request) => request.body?.auth_index === "b")?.body?.header?.[
138 "Chatgpt-Account-Id"
139 ],
140 ).toBe("account-b");
141 }),
142 );
143
144 it.effect("keeps usage when the credits endpoint fails", () =>
145 Effect.gen(function* () {
146 const test = fixture({
147 upstream: (request) =>
148 request.url?.endsWith("rate-limit-reset-credits")
149 ? { status: 503, body: { token: "do-not-publish" } }
150 : { status: 200, body: { rate_limit: { primary_window: { used_percent: 12 } } } },
151 });
152 const api = yield* test.api;
153 const result = yield* api.readAccounts(config);
154 expect(result[0]?.usageLimits.windows[0]?.usedPercent).toBe(12);
155 expect(result[0]?.usageLimits.resetCredits).toBeUndefined();
156 }),
157 );
158
159 it.effect("isolates a failed account and never publishes upstream error bodies", () =>
160 Effect.gen(function* () {
161 const test = fixture({
162 upstream: (request) =>
163 request.auth_index === "a"
164 ? { status: 401, body: { token: "do-not-publish" } }
165 : {
166 status: 200,
167 body: request.url?.endsWith("rate-limit-reset-credits")
168 ? { credits: [] }
169 : { rate_limit: { primary_window: { used_percent: 12 } } },
170 },
171 });
172 const api = yield* test.api;
173 const result = yield* api.readAccounts(config);
174 expect(result[0]?.usageLimits.unavailable?.reason).toBe("probeFailed");
175 expect(result[1]?.usageLimits.windows[0]?.usedPercent).toBe(12);
176 expect(encodeJson(result)).not.toContain("do-not-publish");
177 }),
178 );
179
180 it.effect("maps Claude scoped windows without a scheduler plugin", () =>
181 Effect.gen(function* () {
182 const test = fixture({
183 accounts: [{ ...accounts[0]!, provider: "claude" }],
184 upstream: () => ({
185 status: 200,
186 body: {
187 five_hour: { utilization: 10, resets_at: null },
188 seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" },
189 limits: [
190 {
191 kind: "weekly_scoped",
192 percent: 80,
193 resets_at: null,
194 scope: { model: { display_name: "Fable" } },
195 },
196 ],
197 },
198 }),
199 });
200 const api = yield* test.api;
201 const result = yield* api.readAccounts(config);
202 expect(
203 result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
204 ).toEqual([
205 ["five_hour", 10],
206 ["seven_day", 50],
207 ["seven_day_fable", 80],
208 ]);
209 }),
210 );
211
212 it.effect("pins redemption to the displayed credit and clears only that account's cooldown", () =>
213 Effect.gen(function* () {
214 const test = fixture();
215 const api = yield* test.api;
216 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
217 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
218 const redemptions = test.requests.filter((request) =>
219 request.body?.url?.endsWith("/consume"),
220 );
221 expect(redemptions).toHaveLength(2);
222 expect(redemptions[0]?.body?.data).toBe(redemptions[1]?.body?.data);
223 expect(redemptions[0]?.body?.data).toBe(
224 encodeJson({
225 redeem_request_id: creditRedeemRequestId("account-b", "credit-b"),
226 credit_id: "credit-b",
227 }),
228 );
229 expect(
230 test.requests
231 .filter((request) => request.path.endsWith("/reset-quota"))
232 .map((request) => request.body?.auth_index),
233 ).toEqual(["b", "b"]);
234 }),
235 );
236
237 it.effect.each([
238 ["nothing_to_reset", "nothingToReset"],
239 ["no_credit", "noCredit"],
240 ["already_redeemed", "alreadyRedeemed"],
241 ] as const)("reports %s accurately", ([code, outcome]) =>
242 Effect.gen(function* () {
243 const test = fixture({ upstream: () => ({ status: 200, body: { code } }) });
244 const api = yield* test.api;
245 expect(yield* api.consume(config, "first.json", "credit")).toEqual({ outcome });
246 expect(test.requests.some((request) => request.path.endsWith("/reset-quota"))).toBe(
247 code === "already_redeemed",
248 );
249 }),
250 );
251
252 it.effect("reports redemption success even if cooldown clearing fails", () =>
253 Effect.gen(function* () {
254 const api = yield* fixture({ cooldownStatus: 404 }).api;
255 const result = yield* api.consume(config, "first.json", "credit");
256 expect(result.outcome).toBe("reset");
257 expect(result.warning).toContain("cooldown");
258 }),
259 );
260
261 it.effect("skips disabled accounts and rejects redemption on them", () =>
262 Effect.gen(function* () {
263 const test = fixture({ accounts: [{ ...accounts[0]!, disabled: true }] });
264 const api = yield* test.api;
265 expect(yield* api.readAccounts(config)).toEqual([]);
266 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
267 "Failure",
268 );
269 expect(test.requests.every((request) => request.path.endsWith("/auth-files"))).toBe(true);
270 }),
271 );
272
273 it.effect("keeps the same redemption id after an uncertain upstream failure", () =>
274 Effect.gen(function* () {
275 let attempts = 0;
276 const test = fixture({
277 upstream: () =>
278 ++attempts === 1
279 ? { status: 503, body: {} }
280 : { status: 200, body: { code: "already_redeemed" } },
281 });
282 const api = yield* test.api;
283 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
284 "Failure",
285 );
286 expect(yield* api.consume(config, "first.json", "credit")).toEqual({
287 outcome: "alreadyRedeemed",
288 });
289 const data = test.requests
290 .filter((request) => request.body?.url?.endsWith("/consume"))
291 .map((request) => request.body?.data);
292 expect(data[0]).toBe(data[1]);
293 expect(test.requests.filter((request) => request.path.endsWith("/reset-quota"))).toHaveLength(
294 1,
295 );
296 }),
297 );
298
299 it.effect("rejects unknown accounts without forwarding a redemption", () =>
300 Effect.gen(function* () {
301 const test = fixture();
302 const api = yield* test.api;
303 const result = yield* api.consume(config, "missing.json", "credit").pipe(Effect.result);
304 expect(result._tag).toBe("Failure");
305 expect(test.requests).toHaveLength(1);
306 }),
307 );
308});