The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 2 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 3 | import { describe, expect, it } from "@effect/vitest"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Schema from "effect/Schema"; |
| 6 | import * as TestClock from "effect/testing/TestClock"; |
| 7 | import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"; |
| 8 | |
| 9 | import { makeCliproxyApi } from "./cliproxyApi.ts"; |
| 10 | |
| 11 | const config = { |
| 12 | kind: "cliproxy", |
| 13 | url: "http://hub.test:8317", |
| 14 | managementKey: "management-secret", |
| 15 | enabled: true, |
| 16 | } as const; |
| 17 | const accounts = [ |
| 18 | { |
| 19 | id: "first.json", |
| 20 | auth_index: "a", |
| 21 | provider: "codex", |
| 22 | email: "first@example.com", |
| 23 | id_token: { chatgpt_account_id: "account-a" }, |
| 24 | }, |
| 25 | { |
| 26 | id: "second.json", |
| 27 | auth_index: "b", |
| 28 | provider: "codex", |
| 29 | email: "second@example.com", |
| 30 | id_token: { chatgpt_account_id: "account-b" }, |
| 31 | }, |
| 32 | ]; |
| 33 | const credit = (id: string, expires_at = "2099-01-01T00:00:00Z") => ({ |
| 34 | id, |
| 35 | expires_at, |
| 36 | status: "available", |
| 37 | reset_type: "codex_rate_limits", |
| 38 | }); |
| 39 | const RequestBody = Schema.Struct({ |
| 40 | auth_index: Schema.String, |
| 41 | method: Schema.optional(Schema.String), |
| 42 | url: Schema.optional(Schema.String), |
| 43 | header: Schema.optional(Schema.Record(Schema.String, Schema.String)), |
| 44 | data: Schema.optional(Schema.String), |
| 45 | }); |
| 46 | type RequestBody = typeof RequestBody.Type; |
| 47 | const decodeRequest = Schema.decodeUnknownSync(Schema.fromJsonString(RequestBody)); |
| 48 | const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); |
| 49 | |
| 50 | function fixture( |
| 51 | options: { |
| 52 | accounts?: Array<{ |
| 53 | id: string; |
| 54 | auth_index: string; |
| 55 | provider: string; |
| 56 | email?: string; |
| 57 | disabled?: boolean; |
| 58 | project_id?: string; |
| 59 | id_token?: { chatgpt_account_id: string; plan_type?: string; chatgpt_plan_type?: string }; |
| 60 | }>; |
| 61 | upstream?: (request: RequestBody) => { status: number; body: unknown }; |
| 62 | cooldownStatus?: number; |
| 63 | models?: (name: string) => Response; |
| 64 | } = {}, |
| 65 | ) { |
| 66 | const requests: Array<{ path: string; body?: RequestBody }> = []; |
| 67 | const http = HttpClient.make((request) => |
| 68 | Effect.sync(() => { |
| 69 | expect(request.headers.authorization).toBe("Bearer management-secret"); |
| 70 | const path = new URL(request.url).pathname; |
| 71 | const body = |
| 72 | request.body._tag === "Uint8Array" |
| 73 | ? decodeRequest(new TextDecoder().decode(request.body.body)) |
| 74 | : undefined; |
| 75 | requests.push({ path, ...(body ? { body } : {}) }); |
| 76 | if (path.endsWith("/auth-files/models")) |
| 77 | return HttpClientResponse.fromWeb( |
| 78 | request, |
| 79 | options.models?.(new URL(request.url).searchParams.get("name")!) ?? |
| 80 | Response.json({}, { status: 404 }), |
| 81 | ); |
| 82 | if (path.endsWith("/auth-files")) |
| 83 | return HttpClientResponse.fromWeb( |
| 84 | request, |
| 85 | Response.json({ files: options.accounts ?? accounts }), |
| 86 | ); |
| 87 | if (path.endsWith("/reset-quota")) |
| 88 | return HttpClientResponse.fromWeb( |
| 89 | request, |
| 90 | Response.json({}, { status: options.cooldownStatus ?? 200 }), |
| 91 | ); |
| 92 | expect(path).toMatch(/\/v0\/management\/api-call$/); |
| 93 | expect(body?.header?.Authorization).toBe("Bearer $TOKEN$"); |
| 94 | const upstream = options.upstream?.(body!) ?? { |
| 95 | status: 200, |
| 96 | body: body?.url?.endsWith("/consume") |
| 97 | ? { code: "reset" } |
| 98 | : body?.url?.endsWith("/rate-limit-reset-credits") |
| 99 | ? { |
| 100 | credits: [ |
| 101 | credit("later", "2099-02-01T00:00:00Z"), |
| 102 | credit("first"), |
| 103 | credit("expired", "2000-01-01T00:00:00Z"), |
| 104 | { ...credit("used"), status: "redeemed" }, |
| 105 | ], |
| 106 | } |
| 107 | : { |
| 108 | plan_type: "pro", |
| 109 | rate_limit: { |
| 110 | secondary_window: { |
| 111 | used_percent: 78, |
| 112 | reset_at: 4070908800, |
| 113 | limit_window_seconds: 604800, |
| 114 | }, |
| 115 | }, |
| 116 | }, |
| 117 | }; |
| 118 | return HttpClientResponse.fromWeb( |
| 119 | request, |
| 120 | Response.json({ status_code: upstream.status, body: encodeJson(upstream.body) }), |
| 121 | ); |
| 122 | }), |
| 123 | ); |
| 124 | return { |
| 125 | requests, |
| 126 | api: makeCliproxyApi.pipe( |
| 127 | Effect.provideService(HttpClient.HttpClient, http), |
| 128 | Effect.provide(NodeCrypto.layer), |
| 129 | ), |
| 130 | }; |
| 131 | } |
| 132 | |
| 133 | const unreachableHub = ( |
| 134 | fail: ( |
| 135 | request: Parameters<Parameters<typeof HttpClient.make>[0]>[0], |
| 136 | ) => HttpClientError.HttpClientError, |
| 137 | ) => |
| 138 | makeCliproxyApi.pipe( |
| 139 | Effect.provideService( |
| 140 | HttpClient.HttpClient, |
| 141 | HttpClient.make((request) => Effect.fail(fail(request))), |
| 142 | ), |
| 143 | Effect.provide(NodeCrypto.layer), |
| 144 | ); |
| 145 | |
| 146 | describe("CLIProxyAPI hub failures", () => { |
| 147 | it.effect("names the TLS code when the hub's certificate is not trusted", () => |
| 148 | Effect.gen(function* () { |
| 149 | const api = yield* unreachableHub( |
| 150 | (request) => |
| 151 | new HttpClientError.HttpClientError({ |
| 152 | reason: new HttpClientError.TransportError({ |
| 153 | request, |
| 154 | // Node's fetch wraps the TLS error, which carries the code, in a generic TypeError. |
| 155 | cause: new TypeError("fetch failed", { |
| 156 | cause: Object.assign(new Error("unable to get local issuer certificate"), { |
| 157 | code: "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", |
| 158 | }), |
| 159 | }), |
| 160 | }), |
| 161 | }), |
| 162 | ); |
| 163 | const error = yield* Effect.flip(api.readAccounts(config)); |
| 164 | expect(error.detail).toContain("UNABLE_TO_GET_ISSUER_CERT_LOCALLY"); |
| 165 | expect(error.detail).toContain("NODE_EXTRA_CA_CERTS"); |
| 166 | }), |
| 167 | ); |
| 168 | |
| 169 | // regression: #18168 Limits hub failures name their TLS, HTTP, or timeout cause |
| 170 | it.effect("ignores a transport code that is not a short Node error code", () => |
| 171 | Effect.gen(function* () { |
| 172 | const api = yield* unreachableHub( |
| 173 | (request) => |
| 174 | new HttpClientError.HttpClientError({ |
| 175 | reason: new HttpClientError.TransportError({ |
| 176 | request, |
| 177 | cause: Object.assign(new Error("odd"), { code: "X".repeat(200) }), |
| 178 | }), |
| 179 | }), |
| 180 | ); |
| 181 | const error = yield* Effect.flip(api.readAccounts(config)); |
| 182 | expect(error.detail).toBe("The hub management request failed."); |
| 183 | }), |
| 184 | ); |
| 185 | |
| 186 | it.effect("names the status, not the body, when the hub rejects the request", () => |
| 187 | Effect.gen(function* () { |
| 188 | const test = HttpClient.make((request) => |
| 189 | Effect.succeed( |
| 190 | HttpClientResponse.fromWeb( |
| 191 | request, |
| 192 | Response.json({ error: "management-secret is wrong" }, { status: 401 }), |
| 193 | ), |
| 194 | ), |
| 195 | ); |
| 196 | const api = yield* makeCliproxyApi.pipe( |
| 197 | Effect.provideService(HttpClient.HttpClient, test), |
| 198 | Effect.provide(NodeCrypto.layer), |
| 199 | ); |
| 200 | const error = yield* Effect.flip(api.readAccounts(config)); |
| 201 | expect(error.detail).toContain("401"); |
| 202 | expect(error.detail).not.toContain("management-secret"); |
| 203 | }), |
| 204 | ); |
| 205 | }); |
| 206 | |
| 207 | describe("CLIProxyAPI built-in management API", () => { |
| 208 | it.effect( |
| 209 | "reads both accounts and their earliest unexpired credits without plugin endpoints", |
| 210 | () => |
| 211 | Effect.gen(function* () { |
| 212 | yield* TestClock.setTime(1788710400000); |
| 213 | const test = fixture(); |
| 214 | const api = yield* test.api; |
| 215 | const result = yield* api.readAccounts(config); |
| 216 | expect(result.map((account) => account.usageLimits.resetCredits)).toEqual([ |
| 217 | { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" }, |
| 218 | { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" }, |
| 219 | ]); |
| 220 | expect(result[0]?.usageLimits.windows).toMatchObject([ |
| 221 | { id: "secondary", usedPercent: 78, kind: "weekly" }, |
| 222 | ]); |
| 223 | const calls = test.requests.filter((request) => request.body?.url); |
| 224 | expect(calls.map((request) => request.body?.auth_index).sort()).toEqual([ |
| 225 | "a", |
| 226 | "a", |
| 227 | "b", |
| 228 | "b", |
| 229 | ]); |
| 230 | expect( |
| 231 | calls.find((request) => request.body?.auth_index === "b")?.body?.header?.[ |
| 232 | "Chatgpt-Account-Id" |
| 233 | ], |
| 234 | ).toBe("account-b"); |
| 235 | }), |
| 236 | ); |
| 237 | |
| 238 | it.effect("names the models the hub routes to each account, when the hub lists them", () => |
| 239 | Effect.gen(function* () { |
| 240 | const test = fixture({ |
| 241 | accounts: [...accounts, { ...accounts[1]!, id: "third.json", auth_index: "c" }], |
| 242 | models: (name) => |
| 243 | name === "first.json" |
| 244 | ? Response.json({ models: [{ id: "gpt-5.6-sol" }, { id: " " }] }) |
| 245 | : name === "third.json" |
| 246 | ? Response.json({ models: [] }) |
| 247 | : Response.json({}, { status: 404 }), |
| 248 | }); |
| 249 | const api = yield* test.api; |
| 250 | const result = yield* api.readAccounts(config); |
| 251 | expect(result.map((account) => account.models)).toEqual([["gpt-5.6-sol"], undefined, []]); |
| 252 | expect(result[1]?.usageLimits.windows).toHaveLength(1); |
| 253 | }), |
| 254 | ); |
| 255 | |
| 256 | it.effect("resolves a missing usage plan from current, then legacy, token plans", () => |
| 257 | Effect.gen(function* () { |
| 258 | const test = fixture({ |
| 259 | accounts: [ |
| 260 | { ...accounts[0]!, id_token: { chatgpt_account_id: "account-a", plan_type: "free" } }, |
| 261 | { |
| 262 | ...accounts[1]!, |
| 263 | id_token: { |
| 264 | chatgpt_account_id: "account-b", |
| 265 | plan_type: "go", |
| 266 | chatgpt_plan_type: "plus", |
| 267 | }, |
| 268 | }, |
| 269 | { |
| 270 | ...accounts[1]!, |
| 271 | id: "third.json", |
| 272 | auth_index: "c", |
| 273 | id_token: { chatgpt_account_id: "account-c", chatgpt_plan_type: "free" }, |
| 274 | }, |
| 275 | ], |
| 276 | upstream: (request) => ({ |
| 277 | status: 200, |
| 278 | body: { |
| 279 | ...(request.auth_index === "a" ? { plan_type: "plus" } : {}), |
| 280 | rate_limit: { primary_window: { used_percent: 12 } }, |
| 281 | }, |
| 282 | }), |
| 283 | }); |
| 284 | const api = yield* test.api; |
| 285 | const result = yield* api.readAccounts(config); |
| 286 | expect(result.map((account) => [account.plan, account.usageLimits.windows[0]?.kind])).toEqual( |
| 287 | [ |
| 288 | ["ChatGPT Plus Subscription", "session"], |
| 289 | ["ChatGPT Go Subscription", "monthly"], |
| 290 | ["ChatGPT Free Subscription", "monthly"], |
| 291 | ], |
| 292 | ); |
| 293 | }), |
| 294 | ); |
| 295 | |
| 296 | it.effect.each([ |
| 297 | "https://tools.test/cliproxy", |
| 298 | "https://tools.test/cliproxy/", |
| 299 | "https://tools.test/cliproxy/management.html", |
| 300 | "https://tools.test/cliproxy/management.html/", |
| 301 | "https://tools.test/cliproxy/MANAGEMENT.HTML", |
| 302 | "https://tools.test/cliproxy/management.html?tab=accounts", |
| 303 | "https://tools.test/cliproxy/management.html#accounts", |
| 304 | "https://tools.test/cliproxy/management.html/?tab=accounts", |
| 305 | "https://tools.test/cliproxy/management.html/#accounts", |
| 306 | ])("keeps the path of a hub served under a prefix: %s", (url) => |
| 307 | Effect.gen(function* () { |
| 308 | const test = fixture(); |
| 309 | const api = yield* test.api; |
| 310 | yield* api.readAccounts({ ...config, url }); |
| 311 | expect(test.requests.length).toBeGreaterThan(0); |
| 312 | expect( |
| 313 | test.requests.every((request) => request.path.startsWith("/cliproxy/v0/management/")), |
| 314 | ).toBe(true); |
| 315 | }), |
| 316 | ); |
| 317 | |
| 318 | it.effect("preserves a hub path that only ends with the panel filename", () => |
| 319 | Effect.gen(function* () { |
| 320 | const test = fixture(); |
| 321 | const api = yield* test.api; |
| 322 | yield* api.readAccounts({ ...config, url: "https://tools.test/team-management.html" }); |
| 323 | expect(test.requests.length).toBeGreaterThan(0); |
| 324 | expect( |
| 325 | test.requests.every((request) => |
| 326 | request.path.startsWith("/team-management.html/v0/management/"), |
| 327 | ), |
| 328 | ).toBe(true); |
| 329 | }), |
| 330 | ); |
| 331 | |
| 332 | it.effect("keeps usage when the credits endpoint fails", () => |
| 333 | Effect.gen(function* () { |
| 334 | const test = fixture({ |
| 335 | upstream: (request) => |
| 336 | request.url?.endsWith("rate-limit-reset-credits") |
| 337 | ? { status: 503, body: { token: "do-not-publish" } } |
| 338 | : { status: 200, body: { rate_limit: { primary_window: { used_percent: 12 } } } }, |
| 339 | }); |
| 340 | const api = yield* test.api; |
| 341 | const result = yield* api.readAccounts(config); |
| 342 | expect(result[0]?.usageLimits.windows[0]?.usedPercent).toBe(12); |
| 343 | expect(result[0]?.usageLimits.resetCredits).toBeUndefined(); |
| 344 | }), |
| 345 | ); |
| 346 | |
| 347 | it.effect("isolates a failed account and never publishes upstream error bodies", () => |
| 348 | Effect.gen(function* () { |
| 349 | const test = fixture({ |
| 350 | upstream: (request) => |
| 351 | request.auth_index === "a" |
| 352 | ? { status: 401, body: { token: "do-not-publish" } } |
| 353 | : { |
| 354 | status: 200, |
| 355 | body: request.url?.endsWith("rate-limit-reset-credits") |
| 356 | ? { credits: [] } |
| 357 | : { rate_limit: { primary_window: { used_percent: 12 } } }, |
| 358 | }, |
| 359 | }); |
| 360 | const api = yield* test.api; |
| 361 | const result = yield* api.readAccounts(config); |
| 362 | expect(result[0]?.usageLimits.unavailable?.reason).toBe("probeFailed"); |
| 363 | expect(result[1]?.usageLimits.windows[0]?.usedPercent).toBe(12); |
| 364 | expect(encodeJson(result)).not.toContain("do-not-publish"); |
| 365 | }), |
| 366 | ); |
| 367 | |
| 368 | it.effect("maps Claude scoped windows without a scheduler plugin", () => |
| 369 | Effect.gen(function* () { |
| 370 | const test = fixture({ |
| 371 | accounts: [{ ...accounts[0]!, provider: "claude" }], |
| 372 | // The usage endpoint answers 429 to requests without a Claude Code user agent. |
| 373 | upstream: (request) => ({ |
| 374 | status: request.header?.["User-Agent"]?.startsWith("claude-code/") ? 200 : 429, |
| 375 | body: { |
| 376 | five_hour: { utilization: 10, resets_at: null }, |
| 377 | seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" }, |
| 378 | limits: [ |
| 379 | { |
| 380 | kind: "weekly_scoped", |
| 381 | percent: 80, |
| 382 | resets_at: null, |
| 383 | scope: { model: { display_name: "Fable" } }, |
| 384 | }, |
| 385 | ], |
| 386 | }, |
| 387 | }), |
| 388 | }); |
| 389 | const api = yield* test.api; |
| 390 | const result = yield* api.readAccounts(config); |
| 391 | expect( |
| 392 | result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]), |
| 393 | ).toEqual([ |
| 394 | ["five_hour", 10], |
| 395 | ["seven_day", 50], |
| 396 | ["seven_day_fable", 80], |
| 397 | ]); |
| 398 | }), |
| 399 | ); |
| 400 | |
| 401 | it.effect.each([ |
| 402 | { |
| 403 | name: "spend budget", |
| 404 | budget: { |
| 405 | spend: { |
| 406 | enabled: true, |
| 407 | used: { amount_minor: 4_631, currency: "USD", exponent: 2 }, |
| 408 | limit: { amount_minor: 50_000, currency: "USD", exponent: 2 }, |
| 409 | }, |
| 410 | }, |
| 411 | }, |
| 412 | { |
| 413 | name: "extra usage", |
| 414 | budget: { |
| 415 | extra_usage: { |
| 416 | is_enabled: true, |
| 417 | used_credits: 4_631, |
| 418 | monthly_limit: 50_000, |
| 419 | utilization: 9, |
| 420 | }, |
| 421 | }, |
| 422 | }, |
| 423 | ])("keeps Claude monthly spend from $name beside rolling windows", ({ budget }) => |
| 424 | Effect.gen(function* () { |
| 425 | const test = fixture({ |
| 426 | accounts: [{ ...accounts[0]!, provider: "claude" }], |
| 427 | upstream: () => ({ |
| 428 | status: 200, |
| 429 | body: { five_hour: { utilization: 10, resets_at: null }, ...budget }, |
| 430 | }), |
| 431 | }); |
| 432 | const result = yield* (yield* test.api).readAccounts(config); |
| 433 | expect( |
| 434 | result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]), |
| 435 | ).toEqual([ |
| 436 | ["five_hour", 10], |
| 437 | ["monthly_spend", expect.closeTo(9.262, 10)], |
| 438 | ]); |
| 439 | }), |
| 440 | ); |
| 441 | |
| 442 | it.effect("omits disabled Claude budgets without losing rolling windows", () => |
| 443 | Effect.gen(function* () { |
| 444 | const test = fixture({ |
| 445 | accounts: [{ ...accounts[0]!, provider: "claude" }], |
| 446 | upstream: () => ({ |
| 447 | status: 200, |
| 448 | body: { |
| 449 | five_hour: { utilization: 10, resets_at: null }, |
| 450 | spend: { enabled: false, used: null, limit: null }, |
| 451 | extra_usage: { |
| 452 | is_enabled: false, |
| 453 | used_credits: null, |
| 454 | monthly_limit: null, |
| 455 | utilization: null, |
| 456 | }, |
| 457 | }, |
| 458 | }), |
| 459 | }); |
| 460 | const result = yield* (yield* test.api).readAccounts(config); |
| 461 | expect(result[0]?.usageLimits.windows.map((window) => window.id)).toEqual(["five_hour"]); |
| 462 | }), |
| 463 | ); |
| 464 | |
| 465 | it.effect("keeps a Claude account whose window reports no utilization", () => |
| 466 | Effect.gen(function* () { |
| 467 | const test = fixture({ |
| 468 | accounts: [{ ...accounts[0]!, provider: "claude" }], |
| 469 | upstream: () => ({ |
| 470 | status: 200, |
| 471 | body: { |
| 472 | five_hour: { utilization: null, resets_at: null }, |
| 473 | seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" }, |
| 474 | }, |
| 475 | }), |
| 476 | }); |
| 477 | const result = yield* (yield* test.api).readAccounts(config); |
| 478 | expect(result[0]?.usageLimits.unavailable).toBeUndefined(); |
| 479 | expect( |
| 480 | result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]), |
| 481 | ).toEqual([["seven_day", 50]]); |
| 482 | }), |
| 483 | ); |
| 484 | |
| 485 | const antigravitySummary = { |
| 486 | buckets: [ |
| 487 | { |
| 488 | bucketId: "gemini-weekly", |
| 489 | window: "weekly", |
| 490 | remainingFraction: 0.75, |
| 491 | resetTime: "2099-01-01T00:00:00Z", |
| 492 | }, |
| 493 | ], |
| 494 | }; |
| 495 | |
| 496 | it.effect("reads an xAI account as Grok with Grok CLI headers", () => |
| 497 | Effect.gen(function* () { |
| 498 | const test = fixture({ |
| 499 | accounts: [{ id: "xai.json", auth_index: "x", provider: "xai", email: "x@example.com" }], |
| 500 | upstream: () => ({ |
| 501 | status: 200, |
| 502 | body: { |
| 503 | config: { |
| 504 | creditUsagePercent: 40, |
| 505 | currentPeriod: { type: "USAGE_PERIOD_TYPE_WEEKLY", end: "2099-01-01T00:00:00Z" }, |
| 506 | }, |
| 507 | }, |
| 508 | }), |
| 509 | }); |
| 510 | const [account] = yield* (yield* test.api).readAccounts(config); |
| 511 | expect(account).toMatchObject({ driver: "grok", email: "x@example.com" }); |
| 512 | expect(account?.usageLimits.windows).toMatchObject([ |
| 513 | { id: "subscription", kind: "weekly", usedPercent: 40 }, |
| 514 | ]); |
| 515 | const call = test.requests.find((request) => request.body?.url)?.body; |
| 516 | expect(call?.method).toBe("GET"); |
| 517 | expect(call?.url).toBe("https://cli-chat-proxy.grok.com/v1/billing?format=credits"); |
| 518 | expect(call?.header).toMatchObject({ |
| 519 | "x-xai-token-auth": "xai-grok-cli", |
| 520 | "x-grok-client-version": expect.any(String), |
| 521 | "User-Agent": expect.stringMatching(/^grok-cli\//), |
| 522 | }); |
| 523 | }), |
| 524 | ); |
| 525 | |
| 526 | it.effect("reads an Antigravity summary and keys the account by its Google ID", () => |
| 527 | Effect.gen(function* () { |
| 528 | const test = fixture({ |
| 529 | accounts: [ |
| 530 | { |
| 531 | id: "antigravity-g@example.com.json", |
| 532 | auth_index: "g", |
| 533 | provider: "antigravity", |
| 534 | email: "g@example.com", |
| 535 | project_id: "project-7", |
| 536 | }, |
| 537 | ], |
| 538 | upstream: (request) => ({ |
| 539 | status: 200, |
| 540 | body: request.url?.endsWith("/userinfo") ? { id: "google-42" } : antigravitySummary, |
| 541 | }), |
| 542 | }); |
| 543 | const [account] = yield* (yield* test.api).readAccounts(config); |
| 544 | expect(account?.driver).toBe("antigravity"); |
| 545 | expect(account?.email).toBeUndefined(); |
| 546 | expect(account?.usageLimits.credentialFingerprint).toBe( |
| 547 | // sha256("google-account\0google-42"), as a local Antigravity probe reports it. |
| 548 | "136d4952771fd67a3600053f37492cbd05828712e0b1c89ebab03d4c22ab6554", |
| 549 | ); |
| 550 | expect(account?.usageLimits.windows).toMatchObject([ |
| 551 | { id: "gemini-weekly", kind: "weekly", usedPercent: 25 }, |
| 552 | ]); |
| 553 | const summary = test.requests.find((request) => request.body?.method === "POST")?.body; |
| 554 | expect(summary?.url).toBe( |
| 555 | "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary", |
| 556 | ); |
| 557 | expect(summary?.data).toBe(encodeJson({ project: "project-7" })); |
| 558 | expect(summary).toMatchObject({ |
| 559 | auth_index: "g", |
| 560 | method: "POST", |
| 561 | header: { |
| 562 | Authorization: "Bearer $TOKEN$", |
| 563 | "Content-Type": "application/json", |
| 564 | "User-Agent": |
| 565 | "antigravity/hub/2.24.0 (aidev_client; os_type=linux; arch=x64; cl=963137146)", |
| 566 | }, |
| 567 | }); |
| 568 | const identityCalls = test.requests.filter((request) => |
| 569 | request.body?.url?.endsWith("/userinfo"), |
| 570 | ); |
| 571 | expect(identityCalls).toHaveLength(1); |
| 572 | expect(identityCalls[0]?.body).toMatchObject({ |
| 573 | method: "GET", |
| 574 | url: "https://www.googleapis.com/oauth2/v2/userinfo", |
| 575 | header: { Authorization: "Bearer $TOKEN$" }, |
| 576 | }); |
| 577 | }).pipe( |
| 578 | Effect.provideService(HostProcess.Platform, "linux"), |
| 579 | Effect.provideService(HostProcess.Architecture, "x64"), |
| 580 | ), |
| 581 | ); |
| 582 | |
| 583 | it.effect("keeps Antigravity limits and listing email when its identity read fails", () => |
| 584 | Effect.gen(function* () { |
| 585 | const test = fixture({ |
| 586 | accounts: [ |
| 587 | { |
| 588 | id: "antigravity.json", |
| 589 | auth_index: "g", |
| 590 | provider: "antigravity", |
| 591 | email: "g@example.com", |
| 592 | project_id: "project-7", |
| 593 | }, |
| 594 | ], |
| 595 | upstream: (request) => |
| 596 | request.url?.endsWith("/userinfo") |
| 597 | ? { status: 403, body: { error: "denied" } } |
| 598 | : { |
| 599 | status: 200, |
| 600 | body: antigravitySummary, |
| 601 | }, |
| 602 | }); |
| 603 | const result = yield* (yield* test.api).readAccounts(config); |
| 604 | expect(result).toHaveLength(1); |
| 605 | const [account] = result; |
| 606 | expect(account).toMatchObject({ driver: "antigravity", email: "g@example.com" }); |
| 607 | expect(account?.usageLimits.credentialFingerprint).toBeUndefined(); |
| 608 | expect(account?.usageLimits.unavailable).toBeUndefined(); |
| 609 | expect(account?.usageLimits.windows).toMatchObject([ |
| 610 | { id: "gemini-weekly", kind: "weekly", usedPercent: 25 }, |
| 611 | ]); |
| 612 | }), |
| 613 | ); |
| 614 | |
| 615 | it.effect.each([ |
| 616 | { name: "a refused xAI call", provider: "xai", status: 403, body: { error: "denied" } }, |
| 617 | { name: "a malformed xAI answer", provider: "xai", status: 200, body: { config: "x" } }, |
| 618 | { name: "a refused Antigravity call", provider: "antigravity", status: 401, body: {} }, |
| 619 | { name: "a malformed Antigravity answer", provider: "antigravity", status: 200, body: [] }, |
| 620 | { name: "an empty Antigravity summary", provider: "antigravity", status: 200, body: {} }, |
| 621 | ])("reports $name as unreadable", ({ provider, status, body }) => |
| 622 | Effect.gen(function* () { |
| 623 | const test = fixture({ |
| 624 | accounts: [{ id: `${provider}.json`, auth_index: "a", provider, project_id: "project-7" }], |
| 625 | upstream: () => ({ status, body }), |
| 626 | }); |
| 627 | const [account] = yield* (yield* test.api).readAccounts(config); |
| 628 | expect(account?.usageLimits.unavailable?.reason).toBe("probeFailed"); |
| 629 | }), |
| 630 | ); |
| 631 | |
| 632 | it.effect.each([undefined, "", " "])( |
| 633 | "rejects a missing or blank Antigravity project (%s) before upstream calls", |
| 634 | (project_id) => |
| 635 | Effect.gen(function* () { |
| 636 | const test = fixture({ |
| 637 | accounts: [ |
| 638 | { |
| 639 | id: "antigravity.json", |
| 640 | auth_index: "a", |
| 641 | provider: "antigravity", |
| 642 | ...(project_id === undefined ? {} : { project_id }), |
| 643 | }, |
| 644 | ], |
| 645 | }); |
| 646 | const [account] = yield* (yield* test.api).readAccounts(config); |
| 647 | expect(account?.usageLimits.unavailable?.reason).toBe("probeFailed"); |
| 648 | expect(test.requests.map((request) => request.path)).not.toContain( |
| 649 | "/v0/management/api-call", |
| 650 | ); |
| 651 | }), |
| 652 | ); |
| 653 | |
| 654 | it.effect("skips accounts of providers the hub table does not know", () => |
| 655 | Effect.gen(function* () { |
| 656 | const test = fixture({ |
| 657 | accounts: [ |
| 658 | { id: "kiro.json", auth_index: "k", provider: "kiro", email: "k@example.com" }, |
| 659 | { ...accounts[0]!, provider: "claude" }, |
| 660 | ], |
| 661 | upstream: () => ({ status: 200, body: { five_hour: { utilization: 1, resets_at: null } } }), |
| 662 | }); |
| 663 | const result = yield* (yield* test.api).readAccounts(config); |
| 664 | expect(result.map((account) => account.driver)).toEqual(["claudeAgent"]); |
| 665 | expect(test.requests.map((request) => request.body?.auth_index)).not.toContain("k"); |
| 666 | }), |
| 667 | ); |
| 668 | |
| 669 | it.effect("pins redemption to the displayed credit and clears only that account's cooldown", () => |
| 670 | Effect.gen(function* () { |
| 671 | const test = fixture(); |
| 672 | const api = yield* test.api; |
| 673 | expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" }); |
| 674 | expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" }); |
| 675 | const redemptions = test.requests.filter((request) => |
| 676 | request.body?.url?.endsWith("/consume"), |
| 677 | ); |
| 678 | expect(redemptions).toHaveLength(2); |
| 679 | expect(redemptions[0]?.body?.data).toBe(redemptions[1]?.body?.data); |
| 680 | expect(redemptions[0]?.body?.data).toBe( |
| 681 | encodeJson({ |
| 682 | redeem_request_id: "519d5243-011a-5b7b-91f3-44d85f095705", |
| 683 | credit_id: "credit-b", |
| 684 | }), |
| 685 | ); |
| 686 | expect( |
| 687 | test.requests |
| 688 | .filter((request) => request.path.endsWith("/reset-quota")) |
| 689 | .map((request) => request.body?.auth_index), |
| 690 | ).toEqual(["b", "b"]); |
| 691 | }), |
| 692 | ); |
| 693 | |
| 694 | it.effect("reports redemption success even if cooldown clearing fails", () => |
| 695 | Effect.gen(function* () { |
| 696 | const api = yield* fixture({ cooldownStatus: 404 }).api; |
| 697 | const result = yield* api.consume(config, "first.json", "credit"); |
| 698 | expect(result.outcome).toBe("reset"); |
| 699 | expect(result.warning).toContain("cooldown"); |
| 700 | }), |
| 701 | ); |
| 702 | |
| 703 | it.effect("skips disabled accounts and rejects redemption on them", () => |
| 704 | Effect.gen(function* () { |
| 705 | const test = fixture({ accounts: [{ ...accounts[0]!, disabled: true }] }); |
| 706 | const api = yield* test.api; |
| 707 | expect(yield* api.readAccounts(config)).toEqual([]); |
| 708 | expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe( |
| 709 | "Failure", |
| 710 | ); |
| 711 | expect(test.requests.every((request) => request.path.endsWith("/auth-files"))).toBe(true); |
| 712 | }), |
| 713 | ); |
| 714 | |
| 715 | it.effect("keeps the same redemption id after an uncertain upstream failure", () => |
| 716 | Effect.gen(function* () { |
| 717 | let attempts = 0; |
| 718 | const test = fixture({ |
| 719 | upstream: () => |
| 720 | ++attempts === 1 |
| 721 | ? { status: 503, body: {} } |
| 722 | : { status: 200, body: { code: "already_redeemed" } }, |
| 723 | }); |
| 724 | const api = yield* test.api; |
| 725 | expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe( |
| 726 | "Failure", |
| 727 | ); |
| 728 | expect(yield* api.consume(config, "first.json", "credit")).toEqual({ |
| 729 | outcome: "alreadyRedeemed", |
| 730 | }); |
| 731 | const data = test.requests |
| 732 | .filter((request) => request.body?.url?.endsWith("/consume")) |
| 733 | .map((request) => request.body?.data); |
| 734 | expect(data[0]).toBe(data[1]); |
| 735 | expect(test.requests.filter((request) => request.path.endsWith("/reset-quota"))).toHaveLength( |
| 736 | 1, |
| 737 | ); |
| 738 | }), |
| 739 | ); |
| 740 | |
| 741 | it.effect("rejects unknown accounts without forwarding a redemption", () => |
| 742 | Effect.gen(function* () { |
| 743 | const test = fixture(); |
| 744 | const api = yield* test.api; |
| 745 | const result = yield* api.consume(config, "missing.json", "credit").pipe(Effect.result); |
| 746 | expect(result._tag).toBe("Failure"); |
| 747 | expect(test.requests).toHaveLength(1); |
| 748 | }), |
| 749 | ); |
| 750 | }); |