Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import { expect, it } from "@effect/vitest";
3import {
4 ProviderDriverKind,
5 SecretProviderId,
6 ServerConfigStreamEvent,
7 UsageLimitSourceId,
8 type ServerProviderUsageWindow,
9 type UsageLimitSourceSnapshot,
10} from "@t3tools/contracts";
11import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Fiber from "effect/Fiber";
15import * as Layer from "effect/Layer";
16import * as Schema from "effect/Schema";
17import * as Stream from "effect/Stream";
18import * as TestClock from "effect/testing/TestClock";
19import { HttpClient, HttpClientResponse } from "effect/http";
20
21import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
22import * as ServerSettings from "../serverSettings.ts";
23import * as UsageLimitSources from "./UsageLimitSources.ts";
24
25const encodeConfigEvent = Schema.encodeSync(ServerConfigStreamEvent);
26
27it.effect("keeps malformed source URLs encodable for config subscribers", () =>
28 Effect.gen(function* () {
29 const sources = yield* UsageLimitSources.make;
30 yield* sources.refresh;
31 const snapshots = yield* sources.current;
32 expect(snapshots.map((source) => source.label)).toEqual([
33 "local-hub",
34 "opaque-hub",
35 "Named hub",
36 "hub.test:8317",
37 "Usage limit source",
38 ]);
39 // Only an http(s) hub URL names an endpoint an agent can be sent to.
40 expect(snapshots.map((source) => source.origin)).toEqual([
41 undefined,
42 undefined,
43 undefined,
44 "https://hub.test:8317",
45 undefined,
46 ]);
47 expect(snapshots[3]?.endpoint).toBe("https://hub.test:8317/team-a");
48 expect(() =>
49 encodeConfigEvent({
50 version: 1,
51 type: "usageLimitSourcesUpdated",
52 payload: { sources: snapshots },
53 }),
54 ).not.toThrow();
55 expect(snapshots.every((source) => source.error === "No management key configured.")).toBe(
56 true,
57 );
58 }).pipe(
59 Effect.provide([
60 Layer.succeed(SecretResolver.SecretResolver, {
61 label: (provider) => Effect.succeed(provider),
62 read: (references) => Effect.succeed(references.map(() => undefined)),
63 invalidate: () => Effect.void,
64 }),
65 ServerSettings.layerTest({
66 usageLimitSources: {
67 [UsageLimitSourceId.make("local-hub")]: {
68 kind: "cliproxy",
69 url: "localhost:8317",
70 managementKey: "",
71 enabled: true,
72 },
73 [UsageLimitSourceId.make("opaque-hub")]: {
74 kind: "cliproxy",
75 url: "file:///tmp/hub",
76 managementKey: "",
77 enabled: true,
78 },
79 [UsageLimitSourceId.make("named-hub")]: {
80 kind: "cliproxy",
81 url: "localhost:8317",
82 label: "Named hub",
83 managementKey: "",
84 enabled: true,
85 },
86 [UsageLimitSourceId.make("valid-hub")]: {
87 kind: "cliproxy",
88 url: "https://hub.test:8317/team-a/management.html",
89 managementKey: "",
90 enabled: true,
91 },
92 [UsageLimitSourceId.make(" ")]: {
93 kind: "cliproxy",
94 url: "localhost:8317",
95 managementKey: "",
96 enabled: true,
97 },
98 },
99 }),
100 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
101 shouldRunScopeWork: () => Effect.succeed(false),
102 }),
103 Layer.succeed(
104 HttpClient.HttpClient,
105 HttpClient.make(() => Effect.die("Unexpected network request")),
106 ),
107 NodeCrypto.layer,
108 ]),
109 ),
110);
111
112it.effect("publishes validated HTTP quotas as display-only accounts", () => {
113 const window = { id: "monthly", kind: "monthly", label: "Monthly", usedPercent: 35 };
114 const accounts = [
115 { id: "account", label: "External plan", providerInstanceId: "work-codex", windows: [window] },
116 ];
117 let usedPercent = 35;
118 let oversized = false;
119 const client = HttpClient.make((request, url) =>
120 Effect.sync(() => {
121 expect(url.href).toBe("https://quota.test/v1");
122 expect(request.headers.authorization).toBe("Bearer test-token");
123 return HttpClientResponse.fromWeb(
124 request,
125 new Response(
126 new ReadableStream({
127 start(controller) {
128 controller.enqueue(
129 new TextEncoder().encode(
130 JSON.stringify({
131 version: 1,
132 accounts: [{ ...accounts[0], windows: [{ ...window, usedPercent }] }],
133 }),
134 ),
135 );
136 if (oversized) controller.enqueue(new Uint8Array(1024 * 1024).fill(32));
137 controller.close();
138 },
139 }),
140 ),
141 );
142 }),
143 );
144 return Effect.gen(function* () {
145 const sources = yield* UsageLimitSources.make;
146 yield* sources.refresh;
147 const [snapshot] = yield* sources.current;
148 expect(snapshot).toMatchObject({ kind: "http", accounts: [], quotaAccounts: accounts });
149 expect(snapshot?.origin).toBeUndefined();
150 usedPercent = 101;
151 yield* sources.refresh;
152 const [failed] = yield* sources.current;
153 expect(failed).toMatchObject({ accounts: [], error: "Could not read the HTTP quota source." });
154 expect(failed?.quotaAccounts).toBeUndefined();
155 usedPercent = 35;
156 oversized = true;
157 yield* sources.refresh;
158 expect((yield* sources.current)[0]).toMatchObject({
159 accounts: [],
160 error: "Could not read the HTTP quota source.",
161 });
162 }).pipe(
163 Effect.provide([
164 Layer.succeed(SecretResolver.SecretResolver, {
165 label: (provider) => Effect.succeed(provider),
166 read: (references) => Effect.succeed(references.map(() => undefined)),
167 invalidate: () => Effect.void,
168 }),
169 ServerSettings.layerTest({
170 usageLimitSources: {
171 [UsageLimitSourceId.make("quota")]: {
172 kind: "http",
173 url: "https://quota.test/v1",
174 managementKey: "test-token",
175 enabled: true,
176 },
177 },
178 }),
179 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
180 shouldRunScopeWork: () => Effect.succeed(false),
181 }),
182 Layer.succeed(HttpClient.HttpClient, client),
183 NodeCrypto.layer,
184 ]),
185 );
186});
187
188it.effect("reads a management key from its secret provider", () => {
189 const authorizations: Array<string | undefined> = [];
190 const keySource = (reference: string) => ({
191 provider: SecretProviderId.make("homelab"),
192 reference,
193 });
194 return Effect.gen(function* () {
195 const sources = yield* UsageLimitSources.make;
196 const snapshots = yield* sources.streamChanges.pipe(
197 Stream.filter((next) => next.length > 0),
198 Stream.runHead,
199 Effect.flatMap(Effect.fromOption),
200 );
201 expect(snapshots.map(({ id, error }) => ({ id, error }))).toEqual([
202 { id: "resolved-hub", error: undefined },
203 {
204 id: "unresolved-hub",
205 error: "Could not read the management key from its secret provider.",
206 },
207 ]);
208 expect(authorizations).toEqual(["Bearer resolved-key"]);
209 }).pipe(
210 Effect.provide([
211 ServerSettings.layerTest({
212 usageLimitSources: {
213 [UsageLimitSourceId.make("resolved-hub")]: {
214 kind: "cliproxy",
215 url: "https://resolved.test",
216 managementKey: keySource("cliproxy#key"),
217 enabled: true,
218 },
219 [UsageLimitSourceId.make("unresolved-hub")]: {
220 kind: "cliproxy",
221 url: "https://unresolved.test",
222 managementKey: keySource("missing#key"),
223 enabled: true,
224 },
225 },
226 }),
227 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
228 shouldRunScopeWork: () => Effect.succeed(false),
229 }),
230 Layer.succeed(SecretResolver.SecretResolver, {
231 label: (provider) => Effect.succeed(provider),
232 read: (references) =>
233 Effect.succeed(
234 references.map((reference) =>
235 reference.reference === "cliproxy#key" ? "resolved-key" : undefined,
236 ),
237 ),
238 invalidate: () => Effect.void,
239 }),
240 Layer.succeed(
241 HttpClient.HttpClient,
242 HttpClient.make((request) =>
243 Effect.sync(() => {
244 authorizations.push(request.headers.authorization);
245 return HttpClientResponse.fromWeb(request, Response.json({ files: [] }));
246 }),
247 ),
248 ),
249 NodeCrypto.layer,
250 ]),
251 );
252});
253
254it.effect("keeps an account's last good reading when the hub's next read of it is refused", () => {
255 let refused = true;
256 let workspace = "account-a";
257 let listsIdentity = true;
258 const readAccount = Effect.gen(function* () {
259 const sources = yield* UsageLimitSources.make;
260 return Effect.gen(function* () {
261 yield* sources.refresh;
262 const [source] = yield* sources.current;
263 return source?.accounts[0]?.usageLimits;
264 });
265 });
266 return Effect.gen(function* () {
267 const read = yield* readAccount;
268 // Nothing to keep yet: the account stays listed as unreadable.
269 expect(yield* read).toMatchObject({ windows: [], unavailable: { reason: "probeFailed" } });
270 refused = false;
271 const good = yield* read;
272 expect(good?.windows.map((window) => window.usedPercent)).toEqual([78]);
273 expect(good?.unavailable).toBeUndefined();
274 refused = true;
275 expect(yield* read).toEqual(good);
276 // The same auth file now holds another login, whose reading is unknown.
277 workspace = "account-b";
278 expect(yield* read).toMatchObject({ windows: [], unavailable: { reason: "probeFailed" } });
279 // A file that lists no login cannot show whether the next one is the same.
280 listsIdentity = false;
281 refused = false;
282 yield* read;
283 refused = true;
284 expect(yield* read).toMatchObject({ windows: [], unavailable: { reason: "probeFailed" } });
285 }).pipe(
286 Effect.provide([
287 ServerSettings.layerTest({
288 usageLimitSources: {
289 [UsageLimitSourceId.make("hub")]: {
290 kind: "cliproxy",
291 url: "http://hub.test:8317",
292 managementKey: "management-secret",
293 enabled: true,
294 },
295 },
296 }),
297 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
298 shouldRunScopeWork: () => Effect.succeed(false),
299 }),
300 Layer.succeed(SecretResolver.SecretResolver, {
301 label: (provider) => Effect.succeed(provider),
302 read: (references) => Effect.succeed(references.map(() => undefined)),
303 invalidate: () => Effect.void,
304 }),
305 Layer.succeed(
306 HttpClient.HttpClient,
307 HttpClient.make((request) =>
308 Effect.sync(() => {
309 if (new URL(request.url).pathname.endsWith("/auth-files")) {
310 return HttpClientResponse.fromWeb(
311 request,
312 Response.json({
313 files: [
314 {
315 id: "first.json",
316 auth_index: "a",
317 provider: "codex",
318 ...(listsIdentity
319 ? {
320 email: "first@example.com",
321 id_token: { chatgpt_account_id: workspace },
322 }
323 : {}),
324 },
325 ],
326 }),
327 );
328 }
329 const usage = {
330 plan_type: "pro",
331 rate_limit: {
332 secondary_window: {
333 used_percent: 78,
334 reset_at: 4070908800,
335 limit_window_seconds: 604800,
336 },
337 },
338 };
339 return HttpClientResponse.fromWeb(
340 request,
341 Response.json(
342 refused
343 ? { status_code: 429, body: "{}" }
344 : { status_code: 200, body: JSON.stringify(usage) },
345 ),
346 );
347 }),
348 ),
349 ),
350 NodeCrypto.layer,
351 ]),
352 );
353});
354
355const NOW = Date.parse("2026-11-13T12:00:00.000Z");
356const at = (hours: number) => DateTime.formatIso(DateTime.makeUnsafe(NOW + hours * 3_600_000));
357const spent = (id: string, hours: number): ServerProviderUsageWindow => ({
358 id,
359 kind: "weekly",
360 label: id,
361 usedPercent: 100,
362 resetsAt: at(hours),
363});
364const hub = (
365 accounts: ReadonlyArray<{
366 driver?: string;
367 models?: ReadonlyArray<string>;
368 windows?: ReadonlyArray<ServerProviderUsageWindow>;
369 unavailable?: true;
370 }>,
371): UsageLimitSourceSnapshot => ({
372 id: UsageLimitSourceId.make("hub"),
373 kind: "cliproxy",
374 label: "hub",
375 checkedAt: at(0),
376 accounts: accounts.map((account, index) => ({
377 id: `account-${index}`,
378 driver: ProviderDriverKind.make(account.driver ?? "claudeAgent"),
379 ...(account.models ? { models: account.models } : {}),
380 usageLimits: {
381 checkedAt: at(0),
382 windows: account.windows ?? [],
383 ...(account.unavailable ? { unavailable: { reason: "probeFailed" as const } } : {}),
384 },
385 })),
386});
387
388it.each([
389 {
390 name: "earliest refill when every account is spent, each at its latest spent window",
391 accounts: [
392 { windows: [spent("five_hour", 1), spent("seven_day", 3)] },
393 { windows: [spent("five_hour", 2)] },
394 { driver: "codex", windows: [] },
395 ],
396 model: "claude-haiku-5-5",
397 expected: at(2),
398 },
399 {
400 name: "unknown while an account still has room",
401 accounts: [{ windows: [spent("five_hour", 1)] }, { windows: [] }],
402 model: "claude-haiku-5-5",
403 expected: null,
404 },
405 {
406 name: "unknown while an account could not be read",
407 accounts: [{ windows: [spent("five_hour", 1)] }, { unavailable: true as const }],
408 model: "claude-haiku-5-5",
409 expected: null,
410 },
411 {
412 name: "unknown when a spent window has no reset or already reset",
413 accounts: [{ windows: [{ ...spent("five_hour", 1), resetsAt: undefined }] }],
414 model: "claude-haiku-5-5",
415 expected: null,
416 },
417 {
418 name: "a model-scoped weekly window blocks only its own model",
419 accounts: [{ windows: [spent("seven_day_fable", 5)] }],
420 model: "claude-haiku-5-5",
421 expected: null,
422 },
423 {
424 name: "a model-scoped weekly window blocks its own model",
425 accounts: [{ windows: [spent("seven_day_fable", 5)] }],
426 model: "claude-fable-5-2",
427 expected: at(5),
428 },
429 {
430 name: "no account of the driver",
431 accounts: [{ driver: "codex", windows: [spent("five_hour", 1)] }],
432 model: "claude-haiku-5-5",
433 expected: null,
434 },
435 // regression: #30778 only the accounts the hub routes the model to can refill it
436 {
437 name: "an account of another driver the hub routes the model to counts",
438 accounts: [
439 { driver: "codex", models: ["gpt-5.6-sol"], windows: [spent("five_hour", 3)] },
440 { models: ["claude-sonnet-4-6"], windows: [] },
441 ],
442 model: "gpt-5.6-sol",
443 expected: at(3),
444 },
445 {
446 name: "an account that lists no models is left out of an alias",
447 accounts: [{ windows: [spent("five_hour", 1)] }, { models: [], windows: [] }],
448 model: "opus",
449 expected: at(1),
450 },
451 {
452 name: "a spent Gemini quota does not hold back Claude on Antigravity",
453 accounts: [
454 {
455 driver: "antigravity",
456 models: ["claude-opus-4-6-thinking"],
457 windows: [spent("3p-5h", 1), spent("gemini-5h", 24)],
458 },
459 ],
460 model: "claude-opus-4-6-thinking",
461 expected: at(1),
462 },
463 {
464 name: "a hub thinking suffix routes by its base model",
465 accounts: [
466 { driver: "codex", models: ["gpt-5.2"], windows: [spent("five_hour", 3)] },
467 { models: ["claude-sonnet-4-6"], windows: [] },
468 ],
469 model: "gpt-5.2(high)",
470 expected: at(3),
471 },
472 {
473 name: "a prefixed Gemini model is held back by the Gemini quota",
474 accounts: [
475 {
476 driver: "antigravity",
477 models: ["ag/gemini-3.1-pro-high"],
478 windows: [spent("3p-5h", 1), spent("gemini-5h", 24)],
479 },
480 ],
481 model: "ag/gemini-3.1-pro-high",
482 expected: at(24),
483 },
484 {
485 name: "an alias of unknown family is held back by every Antigravity quota",
486 accounts: [{ driver: "antigravity", models: ["fast"], windows: [spent("gemini-5h", 24)] }],
487 model: "fast",
488 expected: at(24),
489 },
490 {
491 name: "an own-driver account whose model list was unread still counts",
492 accounts: [
493 { windows: [spent("five_hour", 1)] },
494 {
495 driver: "antigravity",
496 models: ["claude-sonnet-4-6"],
497 windows: [spent("3p-5h", 8)],
498 },
499 ],
500 model: "claude-sonnet-4-6",
501 expected: at(1),
502 },
503 {
504 name: "an Argon model waits only for the Argon quota",
505 accounts: [
506 {
507 driver: "antigravity",
508 models: ["gemini-4-argon-high"],
509 windows: [spent("gemini-argon-5h", 2), spent("gemini-carbon-weekly", 96)],
510 },
511 ],
512 model: "gemini-4-argon-high",
513 expected: at(2),
514 },
515])("hub pool reset: $name", ({ accounts, model, expected }) => {
516 expect(
517 UsageLimitSources.hubPoolResetAt(
518 [hub(accounts)],
519 ProviderDriverKind.make("claudeAgent"),
520 model,
521 NOW,
522 ),
523 ).toBe(expected);
524});
525
526it.effect("the reset fallback refreshes its hub, and a stalled hub cannot hold the failure", () =>
527 Effect.gen(function* () {
528 yield* TestClock.setTime(NOW);
529 const roomLeft = { ...hub([{ windows: [spent("five_hour", 2)] }]), origin: "http://hub.test" };
530 const cached = {
531 ...roomLeft,
532 accounts: roomLeft.accounts.map((account) => ({
533 ...account,
534 usageLimits: {
535 ...account.usageLimits,
536 windows: account.usageLimits.windows.map((window) => ({ ...window, usedPercent: 99 })),
537 },
538 })),
539 };
540 let current: ReadonlyArray<UsageLimitSourceSnapshot> = [cached];
541 let refresh: Effect.Effect<void> = Effect.sync(() => {
542 current = [roomLeft];
543 });
544 const lookup = UsageLimitSources.UsageLimitResetFallback.pipe(
545 Effect.flatMap((fallback) =>
546 fallback.resetAt(ProviderDriverKind.make("claudeAgent"), "http://hub.test", null),
547 ),
548 Effect.provide(
549 UsageLimitSources.layerResetFallback.pipe(
550 Layer.provide(
551 Layer.mock(UsageLimitSources.UsageLimitSources)({
552 current: Effect.sync(() => current),
553 refresh: Effect.suspend(() => refresh),
554 }),
555 ),
556 ),
557 ),
558 );
559 // The last poll saw room; the account was spent after it.
560 expect(yield* lookup).toBe(at(2));
561 current = [cached];
562 refresh = Effect.never;
563 const stalled = yield* Effect.forkChild(lookup);
564 yield* TestClock.adjust("5 seconds");
565 expect(yield* Fiber.join(stalled)).toBeNull();
566 }),
567);