Files
t3code/apps/server/src/provider/Layers/codexUsageLimits.test.ts
T
1641b4aba5 feat(usage): redeem Codex reset credits from the Limits tab (#9534)
Follow-up to #9507, carrying over the reset-credit redemption from #9421.

Codex grants a reset credit when it has rate-limited an account unfairly (`"Thanks for using Codex! You've been granted one free rate limit reset."`). Redeeming one clears the current 5h/weekly windows. The Limits tab now shows how many are banked and when the next expires, with a confirmed **Use a reset credit** action.

## How it works

- `ServerProviderUsageLimits.resetCredits` carries the count and soonest expiry; the Codex probe reads it from the same `account/rateLimits/read` it already makes.
- `ProviderInstance.consumeResetCredit` is a new optional hook — account-level, so it sits beside `refreshModels` rather than on the thread-routed adapter. The Codex driver implements it over a short-lived app-server (via `withCodexAppServerClient`, factored out of the status and skills probes which duplicated the setup), then re-probes.
- Single-flight per instance with one idempotency key kept until Codex reports an outcome, so a retry after a timeout does not open a second attempt.
- New `provider.consumeResetCredit` RPC under the operate scope; the outcome (`reset` / `nothingToReset` / `noCredit` / `alreadyRedeemed`) is shown inline.

Only Codex reports credits today. A provider without the hook gets a clear "does not bank reset credits" error; one without credits shows nothing.

## Screenshots

The local Codex row with one banked credit (the same account via the CLIProxyAPI hub above it shows no credit, as expected — the hub does not relay them):

![Limits tab with the Codex row showing "1 reset credit banked · next expires in 16d 22h" and a "Use a reset credit" button](https://gh-file-drop-api-prod-mi5fy3sowv63ufte.pinglabs.workers.dev/f/2897db5e357f12b3/credits-tab.png)

Close-up of the row:

![Codex row: Weekly 25% used bar, then "1 reset credit banked · next expires in 16d 22h" with the "Use a reset credit" button](https://gh-file-drop-api-prod-mi5fy3sowv63ufte.pinglabs.workers.dev/f/0e80f9114cab8f36/credits-row.png)

Clicking it opens the confirmation; nothing is sent until **Use credit**:

![Confirm dialog: "Use a reset credit? This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone." with Cancel and Use credit](https://gh-file-drop-api-prod-mi5fy3sowv63ufte.pinglabs.workers.dev/f/dc728580889ef1fe/credits-confirm.png)

## Verification

- Mapper tests for the credit summary; provider, contract, and Usage page suites pass; typecheck clean.
- Verified against a real Codex Pro account holding one credit: summary and expiry render, the confirm dialog opens. **Not redeemed** — that would spend the credit.

Written by Claude Fable 5 via Claude Code; design and single-flight approach from @StiensWout's #9421.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Redemption spends real account credits over a new RPC; correctness depends on per-account locking and idempotency, though disabled instances and non-Codex providers are rejected explicitly.
> 
> **Overview**
> Adds **end-to-end redemption of banked Codex rate-limit reset credits** from the Limits UI on web and mobile, backed by a new operate-scoped `provider.consumeResetCredit` RPC.
> 
> **Contracts and server:** `ServerProviderUsageLimits` can include `resetCredits` (count + next expiry). Codex probes attach that from `account/rateLimits/read`. Optional `ProviderInstance.consumeResetCredit` is implemented for Codex via a scoped app-server call to `account/rateLimitResetCredit/consume`, then a limits refresh. `CodexResetCreditCoordinator` serializes redemptions per Codex account directory, reuses one idempotency key until Codex returns an outcome, and times out hung requests. `withCodexAppServerClient` is extracted so status, skills, and redemption share the same short-lived app-server setup.
> 
> **Clients:** Limits rows show banked credits and a confirmed **Use a reset credit** action that calls `serverEnvironment.consumeResetCredit` and surfaces outcomes (`reset`, `nothingToReset`, etc.) or errors.
> 
> **Web usage sources (same PR):** Adding/removing CLIProxyAPI hubs and the add dialog target a **selected connected environment** (with picker when several are connected), gated by operate access—not only the primary environment.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 98f32e60852dca1d38c94335b3ed7aac8c4b895e. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->


Co-authored-by: Wout Stiens <[email protected]>
Co-authored-by: Claude Code <[email protected]>
2026-09-03 19:14:29 -07:00

132 lines
3.8 KiB
TypeScript

import * as CodexErrors from "effect-codex-app-server/errors";
import { describe, expect, it } from "vite-plus/test";
import {
codexRateLimitsFailureMessage,
codexRateLimitsToLimits,
codexRateLimitsToUpdate,
codexResetCreditsToContract,
} from "./codexUsageLimits.ts";
const checkedAt = "2026-07-18T10:00:00.000Z";
describe("codexRateLimitsToLimits", () => {
it("maps primary and secondary onto the session and weekly windows", () => {
expect(
codexRateLimitsToLimits({
checkedAt,
snapshot: {
planType: "plus",
primary: { usedPercent: 12, resetsAt: 1_784_000_000, windowDurationMins: 300 },
secondary: { usedPercent: 47, resetsAt: 1_784_500_000, windowDurationMins: 10080 },
},
}),
).toEqual({
checkedAt,
windows: [
{
id: "primary",
kind: "session",
label: "Session",
usedPercent: 12,
windowDurationMins: 300,
resetsAt: "2026-07-14T03:33:20.000Z",
},
{
id: "secondary",
kind: "weekly",
label: "Weekly",
usedPercent: 47,
windowDurationMins: 10080,
resetsAt: "2026-07-19T22:26:40.000Z",
},
],
});
});
it("treats a lone duration-less primary as monthly on Free and Go", () => {
expect(
codexRateLimitsToLimits({
checkedAt,
snapshot: { planType: "free", primary: { usedPercent: 80, resetsAt: null } },
}).windows,
).toEqual([
{
id: "primary",
kind: "monthly",
label: "Monthly",
usedPercent: 80,
windowDurationMins: 43_200,
},
]);
});
});
describe("codexRateLimitsToUpdate", () => {
it("carries only the windows the notification names", () => {
expect(
codexRateLimitsToUpdate({
secondary: { usedPercent: 51, windowDurationMins: 10080 },
}),
).toEqual({
windows: [
{
id: "secondary",
kind: "weekly",
label: "Weekly",
usedPercent: 51,
windowDurationMins: 10080,
},
],
});
expect(codexRateLimitsToUpdate({ planType: "plus" })).toBeUndefined();
});
});
describe("codexRateLimitsFailureMessage", () => {
it("keeps the JSON-RPC code and nothing else from a request failure", () => {
expect(
codexRateLimitsFailureMessage(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage:
"failed to fetch codex rate limits: GET https://chatgpt.com/backend-api/wham/usage failed: 401 Unauthorized",
}),
),
).toBe("Codex could not read usage (JSON-RPC -32603).");
});
it("phrases a dead process differently from a bad answer", () => {
expect(
codexRateLimitsFailureMessage(new CodexErrors.CodexAppServerProcessExitedError({ code: 1 })),
).toBe("Codex exited before it could report usage.");
});
});
describe("codexResetCreditsToContract", () => {
it("counts available credits and reports the soonest expiry", () => {
expect(
codexResetCreditsToContract({
availableCount: 2,
credits: [
{ status: "available", expiresAt: 1_784_500_000 },
{ status: "redeemed", expiresAt: 1_700_000_000 },
{ status: "available", expiresAt: 1_784_000_000 },
],
}),
).toEqual({ availableCount: 2, nextExpiresAt: "2026-07-14T03:33:20.000Z" });
expect(codexResetCreditsToContract({ availableCount: 0 })).toEqual({ availableCount: 0 });
expect(codexResetCreditsToContract(null)).toBeUndefined();
});
it("rides along on the probe's limits", () => {
expect(
codexRateLimitsToLimits({
checkedAt,
snapshot: { primary: { usedPercent: 5, windowDurationMins: 300 } },
resetCredits: { availableCount: 1 },
}).resetCredits,
).toEqual({ availableCount: 1 });
});
});