Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1267,6 +1267,7 @@ deterministic PASS/FAIL verifier.
--demo use simulated quota data
--inline render inline instead of using the alternate screen
--refresh DURATION refresh interval (default: 1m)
--reset-threshold PERCENT show available resets at this consumption level (0-100; default: 80)
-v, --version print the version and exit
```

Expand All @@ -1283,6 +1284,31 @@ codexometer --inline
codexometer --codex ~/bin/codex
```

## Redeeming a banked quota reset

On the Quota tab, `[ RESET // N ]` appears at the top right when a recent
quota reading reports available banked resets, the account is verified, and
at least one displayed quota window is **80% consumed or higher**.
Set another threshold with `./codexometer --reset-threshold 60` (whole percentages
from 0 to 100). For testing, `./codexometer --reset-threshold 0` bypasses the
consumption threshold; an available credit and verified, fresh account data
are still required. The default is 80 when the flag is omitted.
It moves below the main tabs on narrow terminals. Click once to reveal
`[ CONFIRM RESET ]`, then click again within ten seconds to redeem one reset.
`Esc` or changing tabs cancels confirmation. Redemption refreshes eligible
quota windows and changes the weekly reset schedule; it does not add quota
on top of the existing allowance.

Codexometer uses the prevailing Codex login and the
[official app-server](https://learn.chatgpt.com/docs/app-server#8-earned-rate-limit-resets-chatgpt)
`account/rateLimitResetCredit/consume` method. A shared daemon is not required.
Older servers that do not report reset availability leave the button hidden.
The button is disabled during submission, and quota/count data is fetched
again afterward. If the result is uncertain, `[ RETRY RESET ]` repeats the
same attempt identifier, with another confirmation, to avoid consuming a second
reset. Keep Codexometer open to retain that retry identifier. Check Codex's
Usage page before attempting another reset after restarting the application.

## Release builds

GoReleaser builds Linux, macOS, and Windows archives for AMD64 and ARM64 with
Expand Down
49 changes: 48 additions & 1 deletion internal/codex/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,25 @@ type rpcResponse struct {
// Fetch starts a short-lived app-server, performs the initialization handshake,
// reads the authenticated account limits, and shuts the server down again.
func (c Client) Fetch(ctx context.Context) (Snapshot, error) {
return c.fetch(ctx, nil)
}

type resetAttempt struct {
key, account, outcome string
}

// ConsumeReset uses the prevailing account, checking that it is the account
// whose quota the user confirmed. Callers must reuse key after uncertain errors.
func (c Client) ConsumeReset(ctx context.Context, key, account string) (string, error) {
if strings.TrimSpace(key) == "" || account == "" {
return "", errors.New("reset requires an attempt key and verified account")
}
attempt := &resetAttempt{key: key, account: account}
_, err := c.fetch(ctx, attempt)
return attempt.outcome, err
}

func (c Client) fetch(ctx context.Context, reset *resetAttempt) (Snapshot, error) {
binary := c.Binary
if binary == "" {
binary = "codex"
Expand All @@ -81,7 +100,7 @@ func (c Client) Fetch(ctx context.Context) (Snapshot, error) {
return Snapshot{}, fmt.Errorf("open Codex output: %w", err)
}

var stderr strings.Builder
var stderr lockedBuffer
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
if errors.Is(err, exec.ErrNotFound) || errors.Is(err, os.ErrNotExist) {
Expand Down Expand Up @@ -128,6 +147,34 @@ func (c Client) Fetch(ctx context.Context) (Snapshot, error) {
if accountResult, accountErr := responseFor(decoder, 2); accountErr == nil {
accountFingerprint = fingerprintAccount(accountResult)
}
if reset != nil {
if accountFingerprint == "" || accountFingerprint != reset.account {
return Snapshot{}, errors.New("Codex account changed or could not be verified; reset not submitted")
}
if err := encoder.Encode(map[string]any{
"method": "account/rateLimitResetCredit/consume", "id": 4,
"params": map[string]any{"idempotencyKey": reset.key},
}); err != nil {
return Snapshot{}, fmt.Errorf("send Codex quota reset request: %w", err)
}
result, err := responseFor(decoder, 4)
if err != nil {
return Snapshot{}, withServerError("read Codex quota reset response", err, stderr.String())
}
var response struct {
Outcome string `json:"outcome"`
}
if err := json.Unmarshal(result, &response); err != nil {
return Snapshot{}, fmt.Errorf("decode Codex quota reset response: %w", err)
}
switch response.Outcome {
case "reset", "alreadyRedeemed", "nothingToReset", "noCredit":
reset.outcome = response.Outcome
return Snapshot{}, nil
default:
return Snapshot{}, fmt.Errorf("unrecognized reset outcome %q", response.Outcome)
}
}
if err := encoder.Encode(map[string]any{
"method": "account/rateLimits/read",
"id": 3,
Expand Down
78 changes: 78 additions & 0 deletions internal/codex/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,25 @@ func runFakeAppServer() {
continue
}
switch request.Method {
case "account/rateLimitResetCredit/consume":
switch os.Getenv("CODEXOMETER_FAKE_RESET_ERROR") {
case "rpc":
fmt.Fprintln(os.Stderr, "reset service unavailable")
_ = encoder.Encode(map[string]any{"id": *request.ID, "error": map[string]any{"code": -32000, "message": "reset rejected"}})
continue
case "decode":
_ = encoder.Encode(map[string]any{"id": *request.ID, "result": map[string]any{"outcome": 123}})
continue
}
var params struct {
Key string `json:"idempotencyKey"`
}
if json.Unmarshal(request.Params, &params) != nil || params.Key != "test-attempt" {
_ = encoder.Encode(map[string]any{"id": *request.ID, "error": map[string]any{"code": -32602, "message": "invalid attempt"}})
continue
}
outcome := os.Getenv("CODEXOMETER_FAKE_RESET_OUTCOME")
_ = encoder.Encode(map[string]any{"id": *request.ID, "result": map[string]any{"outcome": outcome}})
case "initialize":
if os.Getenv("CODEXOMETER_FAKE_EXPECT_BENCHMARK_LOGIN") == "1" {
args := strings.Join(os.Args, " ")
Expand Down Expand Up @@ -187,3 +206,62 @@ func runFakeAppServer() {
}
}
}

func TestConsumeResetAccountBindingAndOutcomes(t *testing.T) {
t.Setenv("CODEXOMETER_FAKE_APP_SERVER", "1")
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
c := Client{Binary: executable}
snapshot, err := c.Fetch(context.Background())
if err != nil {
t.Fatal(err)
}
for _, outcome := range []string{"reset", "alreadyRedeemed", "nothingToReset", "noCredit"} {
t.Setenv("CODEXOMETER_FAKE_RESET_OUTCOME", outcome)
got, err := c.ConsumeReset(context.Background(), "test-attempt", snapshot.AccountFingerprint)
if err != nil || got != outcome {
t.Fatalf("%s: %q %v", outcome, got, err)
}
}
if _, err := c.ConsumeReset(context.Background(), "test-attempt", "different-account"); err == nil {
t.Fatal("account mismatch accepted")
}
if _, err := c.ConsumeReset(context.Background(), "", snapshot.AccountFingerprint); err == nil {
t.Fatal("empty key accepted")
}
t.Setenv("CODEXOMETER_FAKE_RESET_OUTCOME", "future-outcome")
if _, err := c.ConsumeReset(context.Background(), "test-attempt", snapshot.AccountFingerprint); err == nil {
t.Fatal("unknown outcome accepted")
}
t.Setenv("CODEXOMETER_FAKE_ACCOUNT_ERROR", "1")
if _, err := c.ConsumeReset(context.Background(), "test-attempt", snapshot.AccountFingerprint); err == nil {
t.Fatal("unverified account accepted")
}
}

func TestConsumeResetErrorsHaveContext(t *testing.T) {
t.Setenv("CODEXOMETER_FAKE_APP_SERVER", "1")
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
c := Client{Binary: executable}
snapshot, err := c.Fetch(context.Background())
if err != nil {
t.Fatal(err)
}
for _, test := range []struct{ mode, want string }{
{"rpc", "read Codex quota reset response"}, {"decode", "decode Codex quota reset response"},
} {
t.Setenv("CODEXOMETER_FAKE_RESET_ERROR", test.mode)
_, err := c.ConsumeReset(context.Background(), "test-attempt", snapshot.AccountFingerprint)
if err == nil || !strings.Contains(err.Error(), test.want) {
t.Fatalf("%s: %v", test.mode, err)
}
if test.mode == "rpc" && !strings.Contains(err.Error(), "reset rejected") {
t.Fatalf("RPC cause lost: %v", err)
}
}
}
Loading