From 5cf875e9e5c51e39402e28982ba54145fe4812e6 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 5 Sep 2026 09:54:50 +0100 Subject: [PATCH 1/4] FEAT: redeem banked quota resets with confirmation --- README.md | 20 ++++ internal/codex/client.go | 47 ++++++++ internal/codex/client_test.go | 44 ++++++++ internal/ui/model.go | 114 ++++++++++++++----- internal/ui/quota_reset.go | 125 ++++++++++++++++++++ internal/ui/quota_reset_test.go | 194 ++++++++++++++++++++++++++++++++ internal/ui/tabs.go | 12 +- internal/ui/view.go | 3 + 8 files changed, 527 insertions(+), 32 deletions(-) create mode 100644 internal/ui/quota_reset.go create mode 100644 internal/ui/quota_reset_test.go diff --git a/README.md b/README.md index 63af5a06..a29e6f9d 100644 --- a/README.md +++ b/README.md @@ -1283,6 +1283,26 @@ 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 and the account is verified. +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 diff --git a/internal/codex/client.go b/internal/codex/client.go index 62b297ee..b5647fad 100644 --- a/internal/codex/client.go +++ b/internal/codex/client.go @@ -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" @@ -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{}, err + } + result, err := responseFor(decoder, 4) + if err != nil { + return Snapshot{}, err + } + var response struct { + Outcome string `json:"outcome"` + } + if err := json.Unmarshal(result, &response); err != nil { + return Snapshot{}, 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, diff --git a/internal/codex/client_test.go b/internal/codex/client_test.go index a3e42b0b..587bef69 100644 --- a/internal/codex/client_test.go +++ b/internal/codex/client_test.go @@ -133,6 +133,16 @@ func runFakeAppServer() { continue } switch request.Method { + case "account/rateLimitResetCredit/consume": + var params struct { + Key string `json:"idempotencyKey"` + } + if json.Unmarshal(request.Params, ¶ms) != 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, " ") @@ -187,3 +197,37 @@ 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") + } +} diff --git a/internal/ui/model.go b/internal/ui/model.go index 8aa321ec..e80f02bf 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -41,35 +41,40 @@ type BenchmarkTaskProvider interface { } type Model struct { - fetcher Fetcher - usageFetcher TokenUsageFetcher - refreshEvery time.Duration - snapshot codex.Snapshot - err error - width int - height int - inline bool - loading bool - lastRefresh time.Time - nextRefresh time.Time - phase int - theme themeID - meterView meterViewID - quotaMeterView meterViewID - hoveredMainTab mainTabID - mainTabHovered bool - hoveredView meterViewID - viewHovered bool - flashedView meterViewID - viewFlashing bool - viewSequence uint64 - hoveredButton footerButtonID - flashedButton footerButtonID - flashSequence uint64 - benchmarkRunner BenchmarkRunner - benchmarkScopedRunner ScopedBenchmarkRunner - preferenceStore PreferenceStore - appVersion string + resetHovered bool + resetBusy bool + resetKey, resetAccount, resetNotice string + resetConfirmUntil time.Time + resetRevision uint64 + fetcher Fetcher + usageFetcher TokenUsageFetcher + refreshEvery time.Duration + snapshot codex.Snapshot + err error + width int + height int + inline bool + loading bool + lastRefresh time.Time + nextRefresh time.Time + phase int + theme themeID + meterView meterViewID + quotaMeterView meterViewID + hoveredMainTab mainTabID + mainTabHovered bool + hoveredView meterViewID + viewHovered bool + flashedView meterViewID + viewFlashing bool + viewSequence uint64 + hoveredButton footerButtonID + flashedButton footerButtonID + flashSequence uint64 + benchmarkRunner BenchmarkRunner + benchmarkScopedRunner ScopedBenchmarkRunner + preferenceStore PreferenceStore + appVersion string benchmarkState benchmarkState benchmarkResults []codex.BenchmarkResult @@ -156,6 +161,7 @@ type Model struct { } type fetchedMsg struct { + resetRevision uint64 snapshot codex.Snapshot err error usage codex.LiveUsageSnapshot @@ -401,6 +407,23 @@ func (m Model) Init() tea.Cmd { func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { switch message := message.(type) { + case quotaResetResult: + m.resetBusy = false + if message.err != nil { + m.resetNotice = "Reset unconfirmed: " + message.err.Error() + ". Retry uses the same attempt." + } else { + m.resetKey, m.resetAccount = "", "" + switch message.outcome { + case "reset", "alreadyRedeemed": + m.resetNotice = "Quota reset. Refreshing limits…" + case "nothingToReset": + m.resetNotice = "Nothing eligible to reset; credit was not consumed." + case "noCredit": + m.resetNotice = "No reset credits available." + } + } + m.loading = true + return m, m.fetch() case tea.KeyPressMsg: if m.meterView == viewBenchmark && m.benchmarkScopeOpen { m.benchmarkScopeKeyboard = true @@ -410,6 +433,11 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { m.cancelBenchmark() return m, tea.Quit case "esc": + if !m.resetConfirmUntil.IsZero() || (m.meterView.isQuota() && m.resetNotice != "" && !m.resetBusy) { + m.resetConfirmUntil = time.Time{} + m.resetNotice = "" + return m, nil + } if m.meterView == viewBenchmark && m.benchmarkScopeOpen { m.cancelBenchmarkScope() return m, nil @@ -588,6 +616,10 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { case tea.MouseMsg: mouse := message.Mouse() _, clicked := message.(tea.MouseClickMsg) + m.resetHovered = m.resetAt(mouse.X, mouse.Y) + if m.resetAt(mouse.X, mouse.Y) && clicked && mouse.Button == tea.MouseLeft { + return m.pressQuotaReset() + } if m.meterView == viewBenchmark && m.benchmarkScopeOpen { m.benchmarkScopeKeyboard = false } @@ -701,6 +733,12 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { m.height = message.Height m.prepareBenchmarkDetailTranscript() case fetchedMsg: + if m.resetBusy || message.resetRevision != m.resetRevision { + return m, nil + } + if message.err == nil && m.resetNotice == "Quota reset. Refreshing limits…" { + m.resetNotice = "Quota reset. Limits refreshed." + } m.loading = false m.err = message.err if message.err == nil { @@ -738,6 +776,10 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { return m.beginMonitorFetch(monitorFetchStart) } case secondMsg: + if !m.resetConfirmUntil.IsZero() && time.Now().After(m.resetConfirmUntil) { + m.resetConfirmUntil = time.Time{} + m.resetNotice = "" + } m.phase++ commands := []tea.Cmd{secondTick()} if m.monitorState == monitorRunning { @@ -909,6 +951,10 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { } func (m Model) pressViewTab(view meterViewID) (tea.Model, tea.Cmd) { + m.resetConfirmUntil = time.Time{} + if !m.resetBusy { + m.resetNotice = "" + } if view < viewBars || view >= viewCount { return m, nil } @@ -1150,9 +1196,13 @@ func (m Model) dashboardLayout() dashboardGeometry { if m.meterView.isQuota() { tabsHeight++ } + if m.resetOwnRow(contentWidth) { + tabsHeight++ + } const framedErrorHeight = 3 const footerHeight = 2 extraHeight := 0 + extraHeight += m.resetNoticeHeight(contentWidth) if m.err != nil { extraHeight += framedErrorHeight } @@ -1172,6 +1222,9 @@ func (m Model) dashboardLayout() dashboardGeometry { quotaTabsY := -1 if m.meterView.isQuota() { quotaTabsY = tabsY + 1 + if m.resetOwnRow(contentWidth) { + quotaTabsY++ + } } meterY := tabsY + tabsHeight + extraHeight meterHeight := max(contentHeight-headerHeight-statusHeight-tabsHeight-extraHeight-footerHeight, 1) @@ -1787,7 +1840,8 @@ func (m Model) fetch() tea.Cmd { } snapshot, err := m.fetcher.Fetch(context.Background()) message := fetchedMsg{ - snapshot: snapshot, err: err, at: time.Now(), + resetRevision: m.resetRevision, + snapshot: snapshot, err: err, at: time.Now(), benchmarkQuotaRevision: m.benchmarkQuotaAccounting.revision, } if err == nil && m.usageFetcher != nil { diff --git a/internal/ui/quota_reset.go b/internal/ui/quota_reset.go new file mode 100644 index 00000000..83db3c71 --- /dev/null +++ b/internal/ui/quota_reset.go @@ -0,0 +1,125 @@ +package ui + +import ( + "context" + "crypto/rand" + "fmt" + "time" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" +) + +type resetConsumer interface { + ConsumeReset(context.Context, string, string) (string, error) +} + +func (m Model) renderResetButton(label string, colors palette) string { + style := colors.label() + if m.resetHovered && !m.resetBusy { + style = style.Foreground(colors.background).Background(colors.primary) + } + return style.Render(label) +} + +type quotaResetResult struct { + outcome string + err error +} + +func (m Model) renderResetNotice(width int) string { + c := paletteFor(m.theme) + return frame(width, "QUOTA RESET", c.label().Render(ansi.Hardwrap(m.resetNotice, max(width-4, 1), true)), c.primary, c) +} + +func (m Model) resetNoticeHeight(width int) int { + if !m.meterView.isQuota() || m.resetNotice == "" { + return 0 + } + return lipgloss.Height(m.renderResetNotice(width)) +} + +func (m Model) resetLabel() string { + if !m.meterView.isQuota() { + return "" + } + if m.resetBusy { + return "[ RESETTING… ]" + } + if !m.resetConfirmUntil.IsZero() { + return "[ CONFIRM RESET ]" + } + if m.resetKey != "" { + return "[ RETRY RESET ]" + } + _, supported := m.fetcher.(resetConsumer) + if !supported || m.loading || m.err != nil || m.snapshot.AccountFingerprint == "" || + m.snapshot.RateLimitResetCredits == nil || m.snapshot.RateLimitResetCredits.AvailableCount <= 0 || + m.snapshot.FetchedAt.IsZero() || time.Since(m.snapshot.FetchedAt) > 2*m.refreshEvery { + return "" + } + return fmt.Sprintf("[ RESET // %d ]", m.snapshot.RateLimitResetCredits.AvailableCount) +} + +// Reserve the same horizontal span for rendering and hit testing. +func (m Model) resetLayout(width int) (int, string) { + label := m.resetLabel() + if label == "" || width < lipgloss.Width(label)+12 { + return width, "" + } + return width - lipgloss.Width(label) - 1, label +} + +func (m Model) resetAt(x, y int) bool { + g := m.dashboardLayout() + w, label := m.resetLayout(g.contentWidth) + if m.resetOwnRow(g.contentWidth) { + label = m.resetLabel() + return y == g.tabsY+1 && x >= 2+max(g.contentWidth-lipgloss.Width(label), 0) && x < 2+g.contentWidth + } + return label != "" && !(m.loading && len(m.snapshot.Meters()) == 0) && y == g.tabsY && x >= 2+w+1 && x < 2+g.contentWidth +} + +func (m Model) resetOwnRow(width int) bool { + label := m.resetLabel() + return label != "" && width < lipgloss.Width(label)+12 +} + +func (m Model) pressQuotaReset() (tea.Model, tea.Cmd) { + if m.resetBusy || m.resetLabel() == "" { + return m, nil + } + if m.resetConfirmUntil.IsZero() || time.Now().After(m.resetConfirmUntil) { + if m.resetKey == "" { + m.resetAccount = m.snapshot.AccountFingerprint + } + m.resetConfirmUntil = time.Now().Add(10 * time.Second) + m.resetNotice = "Use one reset? Refreshes eligible quota and changes the weekly reset schedule. Click CONFIRM; Esc cancels." + return m, nil + } + m.resetConfirmUntil = time.Time{} + if m.resetAccount != m.snapshot.AccountFingerprint { + m.resetNotice = "Account changed; reset cancelled." + return m, nil + } + if m.resetKey == "" { + var id [16]byte + if _, err := rand.Read(id[:]); err != nil { + m.resetNotice = err.Error() + return m, nil + } + id[6] = (id[6] & 15) | 64 + id[8] = (id[8] & 63) | 128 + m.resetKey = fmt.Sprintf("%x-%x-%x-%x-%x", id[:4], id[4:6], id[6:8], id[8:10], id[10:]) + } + m.resetBusy = true + m.resetRevision++ + m.resetNotice = "Resetting quota…" + consumer := m.fetcher.(resetConsumer) + key, account := m.resetKey, m.resetAccount + return m, func() tea.Msg { + outcome, err := consumer.ConsumeReset(context.Background(), key, account) + return quotaResetResult{outcome, err} + } +} diff --git a/internal/ui/quota_reset_test.go b/internal/ui/quota_reset_test.go new file mode 100644 index 00000000..e9730ae9 --- /dev/null +++ b/internal/ui/quota_reset_test.go @@ -0,0 +1,194 @@ +package ui + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" + "github.com/merefield/codexometer/internal/codex" +) + +type resetFake struct { + stubFetcher + keys []string + err error +} + +func (f *resetFake) ConsumeReset(_ context.Context, key, account string) (string, error) { + f.keys = append(f.keys, key) + return "reset", f.err +} +func resetModel() (Model, *resetFake) { + f := &resetFake{} + m := New(f, time.Minute) + m.width, m.height, m.loading = 100, 40, false + m.snapshot = codex.Snapshot{AccountFingerprint: "account", FetchedAt: time.Now(), RateLimitResetCredits: &codex.ResetCredits{AvailableCount: 2}, RateLimits: codex.RateLimitSnapshot{Primary: &codex.Window{UsedPercent: 70}}} + f.snapshot = m.snapshot + return m, f +} + +func TestQuotaResetConfirmationAndRetry(t *testing.T) { + m, f := resetModel() + u, cmd := m.pressQuotaReset() + m = u.(Model) + if cmd != nil || len(f.keys) != 0 || m.resetConfirmUntil.IsZero() { + t.Fatal("first press submitted reset") + } + u, cmd = m.pressQuotaReset() + m = u.(Model) + if cmd == nil || !m.resetBusy { + t.Fatal("confirmation did not submit") + } + if _, duplicate := m.pressQuotaReset(); duplicate != nil { + t.Fatal("duplicate submission") + } + f.err = errors.New("connection lost") + u, _ = m.Update(cmd()) + m = u.(Model) + first := f.keys[0] + u, _ = m.pressQuotaReset() + m = u.(Model) + u, cmd = m.pressQuotaReset() + m = u.(Model) + f.err = nil + u, refresh := m.Update(cmd()) + m = u.(Model) + if len(f.keys) != 2 || f.keys[1] != first || m.resetKey != "" || refresh == nil { + t.Fatal("retry lost idempotency or refresh") + } +} + +func TestQuotaResetCancelAndAccountChange(t *testing.T) { + m, _ := resetModel() + u, _ := m.pressQuotaReset() + m = u.(Model) + u, cmd := m.Update(tea.KeyPressMsg{Code: tea.KeyEscape}) + m = u.(Model) + if cmd != nil || !m.resetConfirmUntil.IsZero() { + t.Fatal("escape did not cancel") + } + u, _ = m.pressQuotaReset() + m = u.(Model) + m.snapshot.AccountFingerprint = "other" + if _, cmd := m.pressQuotaReset(); cmd != nil { + t.Fatal("account change submitted reset") + } + m, _ = resetModel() + u, _ = m.pressQuotaReset() + m = u.(Model) + u, _ = m.pressMainTab(mainTabMonitor) + m = u.(Model) + if !m.resetConfirmUntil.IsZero() || m.resetLabel() != "" { + t.Fatal("tab change retained confirmation") + } +} + +func TestQuotaResetVisibilityAndStaleFetch(t *testing.T) { + m, _ := resetModel() + m.snapshot.RateLimitResetCredits.AvailableCount = 0 + if m.resetLabel() != "" { + t.Fatal("zero credits visible") + } + m.snapshot.RateLimitResetCredits.AvailableCount = 2 + m.snapshot.FetchedAt = time.Now().Add(-time.Hour) + if m.resetLabel() != "" { + t.Fatal("stale credits visible") + } + m, _ = resetModel() + m.resetRevision = 1 + u, _ := m.Update(fetchedMsg{snapshot: codex.Snapshot{}}) + if u.(Model).snapshot.AccountFingerprint != "account" { + t.Fatal("old fetch replaced current quota") + } +} + +func TestQuotaResetRenderedHitSurfaces(t *testing.T) { + for _, width := range []int{24, 36, 60, 100, 180} { + for _, state := range []string{"ready", "confirm", "busy", "retry"} { + m, _ := resetModel() + m.width = width + switch state { + case "confirm": + m.resetConfirmUntil = time.Now().Add(time.Second) + case "busy": + m.resetBusy = true + case "retry": + m.resetKey = "attempt" + } + g := m.dashboardLayout() + lines := strings.Split(ansi.Strip(m.renderMainTabs(g.contentWidth, paletteFor(m.theme))), "\n") + for row, line := range lines { + if lipgloss.Width(line) > g.contentWidth { + t.Fatalf("overflow %d %s: %q", width, state, line) + } + index := strings.Index(line, m.resetLabel()) + if index < 0 { + continue + } + x := lipgloss.Width(line[:index]) + 2 + for offset := 0; offset < lipgloss.Width(m.resetLabel()); offset++ { + if !m.resetAt(x+offset, g.tabsY+row) { + t.Fatalf("miss %d %s at %d", width, state, offset) + } + if _, overlap := m.mainTabAt(x+offset, g.tabsY+row); overlap { + t.Fatal("tab overlap") + } + } + if m.resetAt(x-1, g.tabsY+row) || m.resetAt(2+g.contentWidth, g.tabsY+row) { + t.Fatal("hit outside button") + } + } + } + } +} + +func TestQuotaResetClicksAndSurroundingControls(t *testing.T) { + for _, width := range []int{28, 60, 100, 180} { + m, f := resetModel() + m.width = width + for press := 0; press < 2; press++ { + lines := strings.Split(ansi.Strip(m.render()), "\n") + found := false + for y, line := range lines { + index := strings.Index(line, m.resetLabel()) + if index < 0 { + continue + } + found = true + x := lipgloss.Width(line[:index]) + u, cmd := m.Update(tea.MouseClickMsg{X: x, Y: y, Button: tea.MouseLeft}) + m = u.(Model) + if press == 0 && cmd != nil { + t.Fatal("first click redeemed") + } + if press == 1 { + if cmd == nil { + t.Fatal("second click missed") + } + cmd() + } + break + } + if !found { + t.Fatalf("missing rendered button width %d", width) + } + g := m.dashboardLayout() + for y, line := range strings.Split(ansi.Strip(m.render()), "\n") { + if index := strings.Index(line, "[ (T)HEME ]"); index >= 0 { + x := lipgloss.Width(line[:index]) + if y != g.footerY+1 || m.footerButtonAt(x, y) != footerButtonTheme { + t.Fatal("reset notice displaced footer clicks") + } + } + } + } + if len(f.keys) != 1 { + t.Fatal("wrong number of redemptions") + } + } +} diff --git a/internal/ui/tabs.go b/internal/ui/tabs.go index 9396bd52..c9648bd4 100644 --- a/internal/ui/tabs.go +++ b/internal/ui/tabs.go @@ -162,7 +162,8 @@ func mainTabForView(view meterViewID) mainTabID { } func (m Model) renderMainTabs(width int, colors palette) string { - tabs, separator := mainTabLayout(width, true) + tabWidth, resetLabel := m.resetLayout(width) + tabs, separator := mainTabLayout(tabWidth, true) parts := make([]string, 0, len(tabs)) used := 0 for _, tab := range tabs { @@ -176,6 +177,12 @@ func (m Model) renderMainTabs(width int, colors palette) string { if len(parts) > 1 { used += (len(parts) - 1) * len(separator) } + if resetLabel != "" { + return strings.Join(parts, colors.dimmed().Render(separator)) + strings.Repeat(" ", max(tabWidth-used+1, 0)) + m.renderResetButton(resetLabel, colors) + } + if m.resetOwnRow(width) { + return strings.Join(parts, colors.dimmed().Render(separator)) + "\n" + joinRight("", m.renderResetButton(m.resetLabel(), colors), width) + } return strings.Join(parts, colors.dimmed().Render(separator)) + strings.Repeat(" ", max(width-used, 0)) } @@ -258,7 +265,8 @@ func (m Model) mainTabAt(x, y int) (mainTabID, bool) { return mainTabQuota, false } localX := x - 2 - tabs, _ := mainTabLayout(layout.contentWidth, true) + tabWidth, _ := m.resetLayout(layout.contentWidth) + tabs, _ := mainTabLayout(tabWidth, true) for _, tab := range tabs { if localX >= tab.x && localX < tab.x+tab.width { return tab.tab, true diff --git a/internal/ui/view.go b/internal/ui/view.go index 943f252f..87764799 100644 --- a/internal/ui/view.go +++ b/internal/ui/view.go @@ -46,6 +46,9 @@ func (m Model) render() string { errorView := renderError(contentWidth, m.err, colors) parts = append(parts, errorView) } + if m.meterView.isQuota() && m.resetNotice != "" { + parts = append(parts, m.renderResetNotice(contentWidth)) + } meters := m.snapshot.Meters() if m.meterView.isQuota() { meters = m.quotaMetersWithInsights(contentWidth) From 9d283231d662e27fde38f91ef7780dd3c2bc2fc1 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 5 Sep 2026 10:00:32 +0100 Subject: [PATCH 2/4] FEAT: show quota reset at 80 percent consumption --- README.md | 6 +++++- internal/ui/model.go | 1 + internal/ui/quota_reset.go | 15 +++++++++++++++ internal/ui/quota_reset_test.go | 33 ++++++++++++++++++++++++++++++++- main.go | 8 +++++--- main_test.go | 12 ++++++------ 6 files changed, 64 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index a29e6f9d..7fa60754 100644 --- a/README.md +++ b/README.md @@ -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) +--always-show-reset show available resets even below 80% consumption -v, --version print the version and exit ``` @@ -1286,7 +1287,10 @@ 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 and the account is verified. +quota reading reports available banked resets, the account is verified, and +at least one displayed quota window is **80% consumed or higher**. +For testing, `./codexometer --always-show-reset` bypasses the consumption +threshold; an available credit and verified, fresh account data are still required. 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 diff --git a/internal/ui/model.go b/internal/ui/model.go index e80f02bf..fd62fa98 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -41,6 +41,7 @@ type BenchmarkTaskProvider interface { } type Model struct { + alwaysShowReset bool resetHovered bool resetBusy bool resetKey, resetAccount, resetNotice string diff --git a/internal/ui/quota_reset.go b/internal/ui/quota_reset.go index 83db3c71..ae8539d8 100644 --- a/internal/ui/quota_reset.go +++ b/internal/ui/quota_reset.go @@ -15,6 +15,9 @@ type resetConsumer interface { ConsumeReset(context.Context, string, string) (string, error) } +// SetAlwaysShowReset bypasses the consumption threshold, not credit availability. +func (m *Model) SetAlwaysShowReset(always bool) { m.alwaysShowReset = always } + func (m Model) renderResetButton(label string, colors palette) string { style := colors.label() if m.resetHovered && !m.resetBusy { @@ -59,6 +62,18 @@ func (m Model) resetLabel() string { m.snapshot.FetchedAt.IsZero() || time.Since(m.snapshot.FetchedAt) > 2*m.refreshEvery { return "" } + if !m.alwaysShowReset { + eligible := false + for _, meter := range m.snapshot.Meters() { + if meter.Window.UsedPercent >= 80 { + eligible = true + break + } + } + if !eligible { + return "" + } + } return fmt.Sprintf("[ RESET // %d ]", m.snapshot.RateLimitResetCredits.AvailableCount) } diff --git a/internal/ui/quota_reset_test.go b/internal/ui/quota_reset_test.go index e9730ae9..dad50bd8 100644 --- a/internal/ui/quota_reset_test.go +++ b/internal/ui/quota_reset_test.go @@ -27,7 +27,7 @@ func resetModel() (Model, *resetFake) { f := &resetFake{} m := New(f, time.Minute) m.width, m.height, m.loading = 100, 40, false - m.snapshot = codex.Snapshot{AccountFingerprint: "account", FetchedAt: time.Now(), RateLimitResetCredits: &codex.ResetCredits{AvailableCount: 2}, RateLimits: codex.RateLimitSnapshot{Primary: &codex.Window{UsedPercent: 70}}} + m.snapshot = codex.Snapshot{AccountFingerprint: "account", FetchedAt: time.Now(), RateLimitResetCredits: &codex.ResetCredits{AvailableCount: 2}, RateLimits: codex.RateLimitSnapshot{Primary: &codex.Window{UsedPercent: 80}}} f.snapshot = m.snapshot return m, f } @@ -63,6 +63,37 @@ func TestQuotaResetConfirmationAndRetry(t *testing.T) { } } +func TestQuotaResetConsumptionThresholdAndOverride(t *testing.T) { + for _, used := range []int{0, 79, 80, 100} { + m, _ := resetModel() + m.snapshot.RateLimits.Primary.UsedPercent = used + if visible := m.resetLabel() != ""; visible != (used >= 80) { + t.Fatalf("used %d visibility %v", used, visible) + } + m.SetAlwaysShowReset(true) + if m.resetLabel() == "" { + t.Fatalf("override hidden at %d", used) + } + m.snapshot.RateLimitResetCredits.AvailableCount = 0 + if m.resetLabel() != "" { + t.Fatal("override invented available credit") + } + } + m, _ := resetModel() + m.snapshot.RateLimits.Primary.UsedPercent = 10 + m.snapshot.RateLimits.Secondary = &codex.Window{UsedPercent: 80} + if m.resetLabel() == "" { + t.Fatal("secondary window threshold ignored") + } + m.snapshot.RateLimitsByLimitID = map[string]codex.RateLimitSnapshot{ + "one": {Primary: &codex.Window{UsedPercent: 20}}, + "two": {Primary: &codex.Window{UsedPercent: 80}}, + } + if m.resetLabel() == "" { + t.Fatal("additional quota bucket threshold ignored") + } +} + func TestQuotaResetCancelAndAccountChange(t *testing.T) { m, _ := resetModel() u, _ := m.pressQuotaReset() diff --git a/main.go b/main.go index f036bee0..4d2afec7 100644 --- a/main.go +++ b/main.go @@ -197,7 +197,7 @@ type dependencies struct { checkAuth func(context.Context, string) (codex.Snapshot, error) listDigBenchGames func(context.Context, string) ([]string, error) runDigBench func(context.Context, string, string, string, codex.DigBenchOptions) (codex.DigBenchResult, error) - startUI func(ui.Fetcher, time.Duration, bool) error + startUI func(ui.Fetcher, time.Duration, bool, bool) error } func defaultDependencies() dependencies { @@ -224,6 +224,7 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { refresh = flags.Duration("refresh", time.Minute, "quota refresh interval") demo = flags.Bool("demo", false, "show the UI with simulated quota data") inline = flags.Bool("inline", false, "render inline instead of using the alternate screen") + alwaysShowReset = flags.Bool("always-show-reset", false, "show available quota reset credits below 80% consumption") checkAuth = flags.Bool("check-auth", false, "verify access to the current Codex login and exit") digBenchGame = flags.String("digbench-game", "", "run one experimental DigBench game and exit") digBenchModel = flags.String("digbench-model", "gpt-5.6-sol", "Codex model for --digbench-game") @@ -321,7 +322,7 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { fetcher = &demoFetcher{} } - if err := deps.startUI(fetcher, *refresh, *inline); err != nil { + if err := deps.startUI(fetcher, *refresh, *inline, *alwaysShowReset); err != nil { fmt.Fprintln(stderr, "codexometer:", err) return 1 } @@ -437,12 +438,13 @@ func formatDigBenchResult(result codex.DigBenchResult) string { return line } -func startUI(fetcher ui.Fetcher, refresh time.Duration, inline bool) error { +func startUI(fetcher ui.Fetcher, refresh time.Duration, inline, alwaysShowReset bool) error { model := ui.New(fetcher, refresh) if store, storeErr := ui.NewDefaultPreferenceStore(); storeErr == nil { model = ui.NewWithPreferences(fetcher, refresh, store) } model.SetInline(inline) + model.SetAlwaysShowReset(alwaysShowReset) _, err := tea.NewProgram(model).Run() return err } diff --git a/main_test.go b/main_test.go index 56bcb5ca..7783dbd3 100644 --- a/main_test.go +++ b/main_test.go @@ -81,9 +81,9 @@ func TestRunStartsDemoWithSelectedOptions(t *testing.T) { var stdout, stderr bytes.Buffer called := false deps := dependencies{ - startUI: func(fetcher ui.Fetcher, refresh time.Duration, inline bool) error { + startUI: func(fetcher ui.Fetcher, refresh time.Duration, inline, alwaysShowReset bool) error { called = true - if refresh != 30*time.Second || !inline { + if refresh != 30*time.Second || !inline || !alwaysShowReset { t.Fatalf("refresh=%s inline=%v", refresh, inline) } usageFetcher, ok := fetcher.(ui.TokenUsageFetcher) @@ -117,7 +117,7 @@ func TestRunStartsDemoWithSelectedOptions(t *testing.T) { return nil }, } - code := run([]string{"--demo", "--inline", "--refresh", "30s"}, &stdout, &stderr, deps) + code := run([]string{"--demo", "--inline", "--refresh", "30s", "--always-show-reset"}, &stdout, &stderr, deps) if code != 0 || !called { t.Fatalf("code=%d called=%v stderr=%q", code, called, stderr.String()) } @@ -132,7 +132,7 @@ func sameDemoAccounting(left, right codex.LiveUsageSnapshot) bool { func TestRunReportsUIError(t *testing.T) { var stdout, stderr bytes.Buffer deps := dependencies{ - startUI: func(ui.Fetcher, time.Duration, bool) error { return errors.New("terminal unavailable") }, + startUI: func(ui.Fetcher, time.Duration, bool, bool) error { return errors.New("terminal unavailable") }, } code := run(nil, &stdout, &stderr, deps) if code != 1 || !strings.Contains(stderr.String(), "terminal unavailable") { @@ -223,7 +223,7 @@ func TestRunPassesOpenAIAPIKeyToUIBenchmarks(t *testing.T) { t.Setenv("OPENAI_API_KEY", "openai-secret") var stdout, stderr bytes.Buffer deps := dependencies{ - startUI: func(fetcher ui.Fetcher, _ time.Duration, _ bool) error { + startUI: func(fetcher ui.Fetcher, _ time.Duration, _ bool, _ bool) error { client, ok := fetcher.(codex.Client) if !ok || client.BenchmarkAPIKey != "openai-secret" { t.Fatalf("benchmark API key was not attached to Codex client") @@ -249,7 +249,7 @@ func TestRunPassesDigBenchTokenToUIWithoutLeavingItInEnvironment(t *testing.T) { } return []string{"P-2", "P-1", "P-2"}, nil }, - startUI: func(fetcher ui.Fetcher, _ time.Duration, _ bool) error { + startUI: func(fetcher ui.Fetcher, _ time.Duration, _ bool, _ bool) error { client, ok := fetcher.(codex.Client) if !ok || client.DigBenchToken != "digbench-secret" { t.Fatalf("DigBench token was not attached to Codex client") From 4ea32bdef624f5910446ef6a2d1d4f9e99bb60c7 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 5 Sep 2026 10:02:30 +0100 Subject: [PATCH 3/4] FEAT: configure reset visibility threshold --- README.md | 8 +++--- internal/ui/model.go | 3 ++- internal/ui/quota_reset.go | 9 ++++--- internal/ui/quota_reset_test.go | 14 ++++++++++- main.go | 14 +++++++---- main_test.go | 44 ++++++++++++++++++++++++++++----- 6 files changed, 72 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 7fa60754..50385c9c 100644 --- a/README.md +++ b/README.md @@ -1267,7 +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) ---always-show-reset show available resets even below 80% consumption +--reset-threshold PERCENT show available resets at this consumption level (0-100; default: 80) -v, --version print the version and exit ``` @@ -1289,8 +1289,10 @@ codexometer --codex ~/bin/codex 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**. -For testing, `./codexometer --always-show-reset` bypasses the consumption -threshold; an available credit and verified, fresh account data are still required. +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 diff --git a/internal/ui/model.go b/internal/ui/model.go index fd62fa98..f2230dec 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -41,7 +41,7 @@ type BenchmarkTaskProvider interface { } type Model struct { - alwaysShowReset bool + resetThreshold int resetHovered bool resetBusy bool resetKey, resetAccount, resetNotice string @@ -373,6 +373,7 @@ func New(fetcher Fetcher, refreshEvery time.Duration) Model { refreshEvery = time.Minute } model := Model{ + resetThreshold: 80, fetcher: fetcher, refreshEvery: refreshEvery, monitorAutoStart: true, diff --git a/internal/ui/quota_reset.go b/internal/ui/quota_reset.go index ae8539d8..38e21488 100644 --- a/internal/ui/quota_reset.go +++ b/internal/ui/quota_reset.go @@ -15,8 +15,9 @@ type resetConsumer interface { ConsumeReset(context.Context, string, string) (string, error) } -// SetAlwaysShowReset bypasses the consumption threshold, not credit availability. -func (m *Model) SetAlwaysShowReset(always bool) { m.alwaysShowReset = always } +// SetResetThreshold sets the consumed percentage required to offer a reset. +// Zero bypasses consumption checks, but still requires an available credit. +func (m *Model) SetResetThreshold(percent int) { m.resetThreshold = min(max(percent, 0), 100) } func (m Model) renderResetButton(label string, colors palette) string { style := colors.label() @@ -62,10 +63,10 @@ func (m Model) resetLabel() string { m.snapshot.FetchedAt.IsZero() || time.Since(m.snapshot.FetchedAt) > 2*m.refreshEvery { return "" } - if !m.alwaysShowReset { + if m.resetThreshold > 0 { eligible := false for _, meter := range m.snapshot.Meters() { - if meter.Window.UsedPercent >= 80 { + if meter.Window.UsedPercent >= m.resetThreshold { eligible = true break } diff --git a/internal/ui/quota_reset_test.go b/internal/ui/quota_reset_test.go index dad50bd8..26880523 100644 --- a/internal/ui/quota_reset_test.go +++ b/internal/ui/quota_reset_test.go @@ -64,13 +64,25 @@ func TestQuotaResetConfirmationAndRetry(t *testing.T) { } func TestQuotaResetConsumptionThresholdAndOverride(t *testing.T) { + for _, threshold := range []int{1, 35, 60, 100} { + m, _ := resetModel() + m.SetResetThreshold(threshold) + m.snapshot.RateLimits.Primary.UsedPercent = threshold - 1 + if m.resetLabel() != "" { + t.Fatalf("visible below %d", threshold) + } + m.snapshot.RateLimits.Primary.UsedPercent = threshold + if m.resetLabel() == "" { + t.Fatalf("hidden at %d", threshold) + } + } for _, used := range []int{0, 79, 80, 100} { m, _ := resetModel() m.snapshot.RateLimits.Primary.UsedPercent = used if visible := m.resetLabel() != ""; visible != (used >= 80) { t.Fatalf("used %d visibility %v", used, visible) } - m.SetAlwaysShowReset(true) + m.SetResetThreshold(0) if m.resetLabel() == "" { t.Fatalf("override hidden at %d", used) } diff --git a/main.go b/main.go index 4d2afec7..8e431171 100644 --- a/main.go +++ b/main.go @@ -197,7 +197,7 @@ type dependencies struct { checkAuth func(context.Context, string) (codex.Snapshot, error) listDigBenchGames func(context.Context, string) ([]string, error) runDigBench func(context.Context, string, string, string, codex.DigBenchOptions) (codex.DigBenchResult, error) - startUI func(ui.Fetcher, time.Duration, bool, bool) error + startUI func(ui.Fetcher, time.Duration, bool, int) error } func defaultDependencies() dependencies { @@ -224,7 +224,7 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { refresh = flags.Duration("refresh", time.Minute, "quota refresh interval") demo = flags.Bool("demo", false, "show the UI with simulated quota data") inline = flags.Bool("inline", false, "render inline instead of using the alternate screen") - alwaysShowReset = flags.Bool("always-show-reset", false, "show available quota reset credits below 80% consumption") + resetThreshold = flags.Int("reset-threshold", 80, "quota consumption percentage required to show reset (0-100; 0 always shows available resets)") checkAuth = flags.Bool("check-auth", false, "verify access to the current Codex login and exit") digBenchGame = flags.String("digbench-game", "", "run one experimental DigBench game and exit") digBenchModel = flags.String("digbench-model", "gpt-5.6-sol", "Codex model for --digbench-game") @@ -242,6 +242,10 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { fmt.Fprintln(stdout, "codexometer "+version.Current()) return 0 } + if *resetThreshold < 0 || *resetThreshold > 100 { + fmt.Fprintln(stderr, "codexometer: --reset-threshold must be between 0 and 100") + return 2 + } // Capture credentials for the benchmark components, then remove them before // any path that can launch Codex. This keeps auth checks and quota reads on // the user's prevailing Codex login instead of leaking or implicitly using a @@ -322,7 +326,7 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { fetcher = &demoFetcher{} } - if err := deps.startUI(fetcher, *refresh, *inline, *alwaysShowReset); err != nil { + if err := deps.startUI(fetcher, *refresh, *inline, *resetThreshold); err != nil { fmt.Fprintln(stderr, "codexometer:", err) return 1 } @@ -438,13 +442,13 @@ func formatDigBenchResult(result codex.DigBenchResult) string { return line } -func startUI(fetcher ui.Fetcher, refresh time.Duration, inline, alwaysShowReset bool) error { +func startUI(fetcher ui.Fetcher, refresh time.Duration, inline bool, resetThreshold int) error { model := ui.New(fetcher, refresh) if store, storeErr := ui.NewDefaultPreferenceStore(); storeErr == nil { model = ui.NewWithPreferences(fetcher, refresh, store) } model.SetInline(inline) - model.SetAlwaysShowReset(alwaysShowReset) + model.SetResetThreshold(resetThreshold) _, err := tea.NewProgram(model).Run() return err } diff --git a/main_test.go b/main_test.go index 7783dbd3..82054e3d 100644 --- a/main_test.go +++ b/main_test.go @@ -77,13 +77,45 @@ func TestRunAuthCheckScrubsBenchmarkCredentialsBeforeLaunchingCodex(t *testing.T } } +func TestResetThresholdOption(t *testing.T) { + for _, test := range []struct { + value string + want, code int + }{ + {"", 80, 0}, {"0", 0, 0}, {"100", 100, 0}, + {"-1", 0, 2}, {"101", 0, 2}, {"abc", 0, 2}, {"80.5", 0, 2}, + } { + t.Run(test.value, func(t *testing.T) { + var stdout, stderr bytes.Buffer + called := false + deps := dependencies{startUI: func(_ ui.Fetcher, _ time.Duration, _ bool, threshold int) error { + called = true + if threshold != test.want { + t.Fatalf("threshold %d, want %d", threshold, test.want) + } + return nil + }} + args := []string{"--demo"} + if test.value != "" { + args = append(args, "--reset-threshold", test.value) + } + if code := run(args, &stdout, &stderr, deps); code != test.code { + t.Fatalf("code %d: %s", code, stderr.String()) + } + if called != (test.code == 0) { + t.Fatal("invalid threshold launched UI") + } + }) + } +} + func TestRunStartsDemoWithSelectedOptions(t *testing.T) { var stdout, stderr bytes.Buffer called := false deps := dependencies{ - startUI: func(fetcher ui.Fetcher, refresh time.Duration, inline, alwaysShowReset bool) error { + startUI: func(fetcher ui.Fetcher, refresh time.Duration, inline bool, resetThreshold int) error { called = true - if refresh != 30*time.Second || !inline || !alwaysShowReset { + if refresh != 30*time.Second || !inline || resetThreshold != 35 { t.Fatalf("refresh=%s inline=%v", refresh, inline) } usageFetcher, ok := fetcher.(ui.TokenUsageFetcher) @@ -117,7 +149,7 @@ func TestRunStartsDemoWithSelectedOptions(t *testing.T) { return nil }, } - code := run([]string{"--demo", "--inline", "--refresh", "30s", "--always-show-reset"}, &stdout, &stderr, deps) + code := run([]string{"--demo", "--inline", "--refresh", "30s", "--reset-threshold", "35"}, &stdout, &stderr, deps) if code != 0 || !called { t.Fatalf("code=%d called=%v stderr=%q", code, called, stderr.String()) } @@ -132,7 +164,7 @@ func sameDemoAccounting(left, right codex.LiveUsageSnapshot) bool { func TestRunReportsUIError(t *testing.T) { var stdout, stderr bytes.Buffer deps := dependencies{ - startUI: func(ui.Fetcher, time.Duration, bool, bool) error { return errors.New("terminal unavailable") }, + startUI: func(ui.Fetcher, time.Duration, bool, int) error { return errors.New("terminal unavailable") }, } code := run(nil, &stdout, &stderr, deps) if code != 1 || !strings.Contains(stderr.String(), "terminal unavailable") { @@ -223,7 +255,7 @@ func TestRunPassesOpenAIAPIKeyToUIBenchmarks(t *testing.T) { t.Setenv("OPENAI_API_KEY", "openai-secret") var stdout, stderr bytes.Buffer deps := dependencies{ - startUI: func(fetcher ui.Fetcher, _ time.Duration, _ bool, _ bool) error { + startUI: func(fetcher ui.Fetcher, _ time.Duration, _ bool, _ int) error { client, ok := fetcher.(codex.Client) if !ok || client.BenchmarkAPIKey != "openai-secret" { t.Fatalf("benchmark API key was not attached to Codex client") @@ -249,7 +281,7 @@ func TestRunPassesDigBenchTokenToUIWithoutLeavingItInEnvironment(t *testing.T) { } return []string{"P-2", "P-1", "P-2"}, nil }, - startUI: func(fetcher ui.Fetcher, _ time.Duration, _ bool, _ bool) error { + startUI: func(fetcher ui.Fetcher, _ time.Duration, _ bool, _ int) error { client, ok := fetcher.(codex.Client) if !ok || client.DigBenchToken != "digbench-secret" { t.Fatalf("DigBench token was not attached to Codex client") From bff42f09da0a94d9651729f5b02656d9100b2f93 Mon Sep 17 00:00:00 2001 From: merefield Date: Sat, 5 Sep 2026 10:22:58 +0100 Subject: [PATCH 4/4] FIX: harden reset capability checks and error reporting --- internal/codex/client.go | 8 ++++---- internal/codex/client_test.go | 34 +++++++++++++++++++++++++++++++++ internal/ui/quota_reset.go | 9 +++++++-- internal/ui/quota_reset_test.go | 20 +++++++++++++++++++ 4 files changed, 65 insertions(+), 6 deletions(-) diff --git a/internal/codex/client.go b/internal/codex/client.go index b5647fad..6c2f23d6 100644 --- a/internal/codex/client.go +++ b/internal/codex/client.go @@ -100,7 +100,7 @@ func (c Client) fetch(ctx context.Context, reset *resetAttempt) (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) { @@ -155,17 +155,17 @@ func (c Client) fetch(ctx context.Context, reset *resetAttempt) (Snapshot, error "method": "account/rateLimitResetCredit/consume", "id": 4, "params": map[string]any{"idempotencyKey": reset.key}, }); err != nil { - return Snapshot{}, err + return Snapshot{}, fmt.Errorf("send Codex quota reset request: %w", err) } result, err := responseFor(decoder, 4) if err != nil { - return Snapshot{}, err + 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{}, err + return Snapshot{}, fmt.Errorf("decode Codex quota reset response: %w", err) } switch response.Outcome { case "reset", "alreadyRedeemed", "nothingToReset", "noCredit": diff --git a/internal/codex/client_test.go b/internal/codex/client_test.go index 587bef69..2c1180e6 100644 --- a/internal/codex/client_test.go +++ b/internal/codex/client_test.go @@ -134,6 +134,15 @@ func runFakeAppServer() { } 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"` } @@ -231,3 +240,28 @@ func TestConsumeResetAccountBindingAndOutcomes(t *testing.T) { 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) + } + } +} diff --git a/internal/ui/quota_reset.go b/internal/ui/quota_reset.go index 38e21488..cdac6933 100644 --- a/internal/ui/quota_reset.go +++ b/internal/ui/quota_reset.go @@ -106,6 +106,12 @@ func (m Model) pressQuotaReset() (tea.Model, tea.Cmd) { if m.resetBusy || m.resetLabel() == "" { return m, nil } + consumer, supported := m.fetcher.(resetConsumer) + if !supported { + m.resetConfirmUntil = time.Time{} + m.resetNotice = "Reset unavailable: this quota source does not support redemption. No reset submitted." + return m, nil + } if m.resetConfirmUntil.IsZero() || time.Now().After(m.resetConfirmUntil) { if m.resetKey == "" { m.resetAccount = m.snapshot.AccountFingerprint @@ -122,7 +128,7 @@ func (m Model) pressQuotaReset() (tea.Model, tea.Cmd) { if m.resetKey == "" { var id [16]byte if _, err := rand.Read(id[:]); err != nil { - m.resetNotice = err.Error() + m.resetNotice = "Could not generate a reset request ID; no reset submitted: " + err.Error() return m, nil } id[6] = (id[6] & 15) | 64 @@ -132,7 +138,6 @@ func (m Model) pressQuotaReset() (tea.Model, tea.Cmd) { m.resetBusy = true m.resetRevision++ m.resetNotice = "Resetting quota…" - consumer := m.fetcher.(resetConsumer) key, account := m.resetKey, m.resetAccount return m, func() tea.Msg { outcome, err := consumer.ConsumeReset(context.Background(), key, account) diff --git a/internal/ui/quota_reset_test.go b/internal/ui/quota_reset_test.go index 26880523..582fc1f8 100644 --- a/internal/ui/quota_reset_test.go +++ b/internal/ui/quota_reset_test.go @@ -63,6 +63,26 @@ func TestQuotaResetConfirmationAndRetry(t *testing.T) { } } +func TestQuotaResetUnsupportedFetcherDuringConfirmationOrRetry(t *testing.T) { + for _, retry := range []bool{false, true} { + m, _ := resetModel() + m.fetcher = stubFetcher{} + m.resetConfirmUntil = time.Now().Add(time.Second) + m.resetAccount = m.snapshot.AccountFingerprint + if retry { + m.resetKey = "previous-attempt" + } + u, cmd := m.pressQuotaReset() + got := u.(Model) + if cmd != nil || got.resetBusy || !got.resetConfirmUntil.IsZero() || !strings.Contains(got.resetNotice, "does not support redemption") { + t.Fatal("unsupported fetcher did not cancel safely") + } + if got.resetKey != m.resetKey { + t.Fatal("lost uncertain attempt ID") + } + } +} + func TestQuotaResetConsumptionThresholdAndOverride(t *testing.T) { for _, threshold := range []int{1, 35, 60, 100} { m, _ := resetModel()