From d045393be01e3ba92bd50a60dfc937ae8fcdeb24 Mon Sep 17 00:00:00 2001 From: merefield Date: Thu, 13 Aug 2026 10:18:07 +0100 Subject: [PATCH 1/4] Expand quota insight and monitor attention --- README.md | 105 +++++++++++++++----- internal/codex/client_test.go | 16 ++- internal/codex/live_usage.go | 110 ++++++++++++++++++++- internal/codex/live_usage_test.go | 116 ++++++++++++++++++++++ internal/codex/types.go | 68 ++++++++++++- internal/codex/types_test.go | 40 ++++++-- internal/ui/meters.go | 144 +++++++++++++++++++++++++-- internal/ui/meters_test.go | 51 ++++++++++ internal/ui/model.go | 30 +++++- internal/ui/monitor.go | 20 +++- internal/ui/monitor_test.go | 18 ++++ internal/ui/preferences.go | 159 ++++++++++++++++++++++++++++++ internal/ui/preferences_test.go | 77 +++++++++++++++ internal/ui/quota_status.go | 123 ++++++++++++++++++++--- internal/ui/quota_status_test.go | 51 +++++++++- internal/ui/view.go | 29 ++++-- internal/ui/view_test.go | 28 ++++-- internal/version/version.go | 2 +- internal/version/version_test.go | 4 +- main.go | 8 +- main_test.go | 4 +- 21 files changed, 1103 insertions(+), 100 deletions(-) create mode 100644 internal/ui/preferences.go create mode 100644 internal/ui/preferences_test.go diff --git a/README.md b/README.md index 66044697..cad930b0 100644 --- a/README.md +++ b/README.md @@ -45,19 +45,24 @@ It works particularly well in: ## What it shows -- Every rate-limit bucket and window returned by the current Codex account. +- Every rate-limit bucket and window returned by the current Codex account, + plus the effective monthly credit limit when supplied. - Used and free percentages for each window. - The duration of each window, such as five hours or one week. - A live countdown and local clock time for each reset. -- On every style, a separate reset-cycle gauge comparing elapsed window time +- On every Quota view, a separate reset-cycle gauge comparing elapsed window time with quota consumed. It uses the same active colour as its quota meter. - The current ChatGPT plan when Codex supplies it. +- Spend-control hard stops and available account-credit balance when supplied. - Available earned reset credits when present. -- Online, refreshing, stale-data, and error states. +- Online, refreshing, stale-data, and error states, with the limiting window + named in warning states and a celebratory fresh-reset signal at 0% usage. - A countdown to the next automatic refresh. - An optional Monitor view that measures token activity between Go and Stop. Each independent local root session gets its own metrics and 30-second graph; explicitly linked spawned agents are included with their root. +- A highlighted `AWAITING YOU` Monitor badge when a root or linked agent emits + an explicit blocking input or approval request. - An opt-in deterministic coding benchmark comparing every visible Codex model and supported reasoning effort by correctness, elapsed time, token use, and estimated standard API-equivalent cost. @@ -195,7 +200,9 @@ The Monitor additionally reads locally persisted Codex rollout files under totals, last-response output counts, timestamps, and content-free turn timing, plus the minimum session metadata needed for grouping: thread ID, parent thread ID, source classification, working directory, and the inherited-history -boundary. Message text—including the final response carried beside timing +boundary. It also reads lifecycle event names and blocking flags to identify an +explicit unresolved input or approval request. Message text—including the final +response carried beside timing metadata—reasoning, commands, tool results, and credentials are ignored and never retained by Codexometer. @@ -236,26 +243,32 @@ only while Quota is active. Move the pointer over a tab or button to highlight it, or click it to activate it. Controls pulse briefly when activated by mouse or keyboard. The keyboard assignments remain available in terminals without mouse support. Theme and tab changes are immediate and do not trigger a network -refresh. +refresh. Theme, Quota view, benchmark result filter, and benchmark ranking +weight are restored on the next launch. ### Quota health signal The top-right signal keeps `ONLINE` in the selected theme color while its dot -and quota-health label use fixed semantic colors: +and quota-health label use fixed semantic colors. Warning labels identify the +meter responsible, for example `5 HOURS // WATCH`, `MONTHLY // NEAR`, or +`SPEND // EXHAUSTED`: +- green `RESET FRESH // GO!` — every returned meter currently reports 0% used; - green `QUOTA CLEAR` — consumption is keeping pace with, or trailing, elapsed window time; - blue `QUOTA WATCH` — the current average burn rate would exhaust at least one quota window before it resets; - amber `LIMIT NEAR` — excess pace projects exhaustion within the first quarter of the time still remaining, or no more than 5% remains while over pace; -- red `QUOTA EXHAUSTED` — a window is at 100% or Codex explicitly reports its - rate limit reached. +- red `QUOTA EXHAUSTED` — a window is at 100%, Codex explicitly reports its + rate limit reached, or account spend control reports a hard stop. -Codexometer reports the worst state among all returned quota windows. If reset -timing is unavailable, it conservatively falls back to remaining capacity: -Watch at 20% and Near at 5%. Scanning and stale-signal states take precedence -while quota health cannot be evaluated reliably. +Codexometer reports the worst state among all returned rolling windows and the +effective monthly credit limit. If reset timing or cycle duration is +unavailable, it conservatively falls back to remaining capacity: Watch at 20% +and Near at 5%. The monthly limit supplies a reset time but no cycle start, so +Codexometer never invents monthly elapsed progress. Scanning and stale-signal +states take precedence while quota health cannot be evaluated reliably. For each window with valid duration and reset data, Codexometer calculates: @@ -268,13 +281,14 @@ For each window with valid duration and reset data, Codexometer calculates: It then applies these rules in severity order: -1. **Exhausted** if `usedPercent` is 100 or Codex explicitly reports that a - rate limit has been reached. -2. **Clear** if `U <= E`: quota consumption is no further advanced than the +1. **Exhausted** if `usedPercent` is 100, Codex explicitly reports that a rate + limit has been reached, or `spendControlReached` is true. +2. **Fresh** if every returned used percentage is zero. +3. **Clear** if `U <= E`: quota consumption is no further advanced than the reset cycle. -3. **Limit Near** when over pace and either no more than 5% quota remains, or +4. **Limit Near** when over pace and either no more than 5% quota remains, or projected exhaustion is within the first 25% of the time remaining to reset. -4. **Watch** for every other over-pace window (`U > E`). +5. **Watch** for every other over-pace window (`U > E`). This means 10% remaining can correctly stay Clear when less than 10% of the window remains: quota is low, but reset is closer than exhaustion at the @@ -307,7 +321,9 @@ choose one of these four views with its sub-tab or `v`: for clean curves at any size. 3. **Consumption Pace** — a signed horizontal scale comparing elapsed window time with quota consumed. Positive headroom means consumption is behind - elapsed time; a negative deficit means quota is being used too quickly. + elapsed time; a negative deficit means quota is being used too quickly. A + clearly labelled linear projection reports `SAFE THROUGH RESET` or estimates + how long remains until exhaustion and how early that is relative to reset. 4. **Fuel Tank** — a reverse gauge whose bright segment shows remaining range and whose dark segment shows consumed capacity, labelled from Empty to Full; one full-width tank appears per row. Its reset-cycle comparison also drains @@ -332,6 +348,10 @@ The other top-level views are: through an interval gets an honestly labelled partial first bar and its rate uses that root's own observed lifetime. New bars enter on the right, older bars move left, and each Y axis automatically rescales to its visible samples. + A root or linked child with a persisted blocking `request_user_input`, + permission, or approval event receives an amber `AWAITING YOU` badge and + border until a definite response, continuation, or completion event arrives. + Generic inactivity is never treated as a request for attention. When the terminal cannot fit every root, use Page Up, Page Down, or the mouse wheel to page through the rows. Stop performs an immediate final local read instead of relying on the latest graph sample. @@ -348,7 +368,8 @@ returned by Codex. Header, status, errors, footer, and meter grid divide the available rectangle proportionally. Bars, Consumption Pace, and Fuel Tank flow one meter per row. Codexometer does not hardcode the currently returned window set: it renders every primary and secondary window from every limit bucket, -including a 300-minute window as `5 HOURS`. When more windows arrive, +including a 300-minute window as `5 HOURS`, plus an effective monthly credit +limit when present. When more limits arrive, horizontal views remove decorative row gaps before compressing the cards, while Pie adds rows or columns only when each radial card retains a useful width. Meter rows always use identical heights; indivisible spare rows become quiet @@ -357,11 +378,18 @@ Pie uses at least two columns when multiple limits exist, adding rows when that preserves more radial detail and adding columns when the terminal is wide enough. Consumption Pace calculates `elapsed window % - quota used %`, placing under-budget consumption on the positive side and over-budget consumption on -the negative side. Every style also shows a `RESET CYCLE` comparison: +the negative side. Its linear projection assumes the average burn observed +since the calculated cycle start continues unchanged: remaining time is +`elapsed time × (1 - U) / U`. It reports safe when the resulting exhaustion +time falls at or after reset, and hides the projection when timing is +insufficient. This is a trend estimate, not a backend forecast. Every Quota view +also shows a `RESET CYCLE` comparison: its label and countdown occupy one line, while its progress bar occupies a separate line with the same width and active colour as the main visualization. Its percentage is elapsed time from the calculated window start -(`reset - duration`) to the next reset. Every visualization +(`reset - duration`) to the next reset. When Codex supplies a monthly reset but +not a cycle start, the card says `CYCLE START UNAVAILABLE`, shows the known +countdown, and leaves the comparison bar unfilled. Every visualization receives its card's remaining width and height, and resizing the terminal immediately reflows and rescales it. The underlying values and reset information never change with presentation. @@ -383,9 +411,11 @@ for a model response, not token-by-token while a response is streaming. Raw toke counts also do not reveal or reproduce the backend's quota-weighting rules, so they should not be converted directly into the percentage gauges. -Session rows represent recently active rollout roots, not a guaranteed list of -currently open terminal processes. Two independent CLI tabs have different root -thread IDs and therefore remain separate rows. `thread_spawn` descendants, +Session rows represent recently active rollout roots plus explicit unresolved +input/approval waits observed within the 24-hour rollout horizon, not a +guaranteed list of currently open terminal processes. Two independent CLI tabs +have different root thread IDs and therefore remain separate rows. +`thread_spawn` descendants, including nested descendants, are folded into their root by following persisted parent IDs. Review, compact, or other internal work that lacks an explicit parent is never guessed onto a root; if observed, it appears in an @@ -395,6 +425,12 @@ twice. Legacy spawned-agent rollouts without an ordinal boundary are separated at the child session timestamp: inherited cumulative totals establish the child counter baseline but are not reported as new usage. +Attention detection reads only content-free lifecycle metadata: event type, +blocking flag, ordinal, and timestamp. It does not retain the input question, +approval text, response, or conversation content. A linked child's attention +state is folded into its root so one remote Monitor row identifies the CLI +session that needs intervention. + `CALLS` counts upstream model-response cycles observed after Monitor Start, not complete user turns. A single Codex turn can make several calls while using tools or progressing through an agent loop. `LAST OUT` is the provider-reported @@ -426,6 +462,21 @@ brackets the local interval. These operations are not atomic, so unrelated account activity during either short boundary read remains another source of uncertainty. +### Saved presentation preferences + +Codexometer stores only the selected theme, Quota view, benchmark filter, and +benchmark ranking weight. No quota snapshot, session telemetry, benchmark +result, message content, or credential is written. The small JSON file uses the +platform-standard user configuration directory: + +- Linux: `$XDG_CONFIG_HOME/codexometer/preferences.json`, normally + `~/.config/codexometer/preferences.json`; +- macOS: `~/Library/Application Support/codexometer/preferences.json`; +- Windows: `%AppData%\codexometer\preferences.json`. + +Missing, unreadable, or malformed preferences never prevent startup; +Codexometer falls back to its safe defaults. + ### Deterministic benchmark The Benchmark tab discovers the current account's visible models and their @@ -721,9 +772,9 @@ need Go or Codexometer's source dependencies. ## Versioning Codexometer follows semantic versioning; the current source version is -`v0.5.0`. The Git tag is the release source of truth. Go automatically embeds +`v0.6.0`. The Git tag is the release source of truth. Go automatically embeds that tag in binaries built with -`go install github.com/merefield/codexometer@v0.5.0`; direct source builds fall +`go install github.com/merefield/codexometer@v0.6.0`; direct source builds fall back to the maintained value in `internal/version/version.go`. Both forms report the embedded version and exit without starting the interface: @@ -736,7 +787,7 @@ codexometer --version Release automation can override the source-build fallback without editing code: ```sh -go build -ldflags="-s -w -X github.com/merefield/codexometer/internal/version.Fallback=0.5.0" . +go build -ldflags="-s -w -X github.com/merefield/codexometer/internal/version.Fallback=0.6.0" . ``` ## How refresh works diff --git a/internal/codex/client_test.go b/internal/codex/client_test.go index ad6d7969..d0831e07 100644 --- a/internal/codex/client_test.go +++ b/internal/codex/client_test.go @@ -30,9 +30,16 @@ func TestFetchUsesAppServerHandshakeAndDecodesSnapshot(t *testing.T) { t.Fatal(err) } meters := snapshot.Meters() - if len(meters) != 2 || meters[0].Window.UsedPercent != 42 || meters[1].Window.UsedPercent != 5 { + if len(meters) != 3 || meters[0].Window.UsedPercent != 42 || meters[1].Window.UsedPercent != 5 || + meters[2].Kind != MeterIndividualLimit || meters[2].Window.UsedPercent != 32 { t.Fatalf("unexpected fetched meters: %#v", meters) } + if snapshot.RateLimits.SpendControlReached == nil || *snapshot.RateLimits.SpendControlReached { + t.Fatalf("spend-control state was not decoded: %#v", snapshot.RateLimits) + } + if credits, ok := snapshot.CreditStatus(); !ok || credits.Balance == nil || *credits.Balance != "17000" { + t.Fatalf("credit status was not decoded: %#v, %v", credits, ok) + } if snapshot.FetchedAt.IsZero() { t.Fatal("fetch time was not recorded") } @@ -114,8 +121,11 @@ func runFakeAppServer() { "id": *request.ID, "result": map[string]any{ "rateLimits": map[string]any{ - "primary": map[string]any{"usedPercent": 42, "windowDurationMins": 300}, - "secondary": map[string]any{"usedPercent": 5, "windowDurationMins": 10_080}, + "primary": map[string]any{"usedPercent": 42, "windowDurationMins": 300}, + "secondary": map[string]any{"usedPercent": 5, "windowDurationMins": 10_080}, + "individualLimit": map[string]any{"limit": "25000", "used": "8000", "remainingPercent": 68, "resetsAt": 1_800_000_000}, + "spendControlReached": false, + "credits": map[string]any{"hasCredits": true, "unlimited": false, "balance": "17000"}, }, }, }) diff --git a/internal/codex/live_usage.go b/internal/codex/live_usage.go index e76ab859..04af47e8 100644 --- a/internal/codex/live_usage.go +++ b/internal/codex/live_usage.go @@ -42,6 +42,7 @@ type LiveUsageSession struct { LastActivity time.Time AgentCount int Active bool + AwaitingInput bool Unattributed bool ModelCalls []LiveModelCall TurnTimings []LiveTurnTiming @@ -94,8 +95,17 @@ type rolloutCursor struct { subagentHistoryStartOrdinal *uint64 modelCalls []LiveModelCall turnTimings []LiveTurnTiming + attention sessionAttentionState } +type sessionAttentionState int + +const ( + sessionAttentionUnknown sessionAttentionState = iota + sessionAttentionWorking + sessionAttentionAwaiting +) + type rolloutEvent struct { Timestamp time.Time `json:"timestamp"` Ordinal *uint64 `json:"ordinal"` @@ -124,6 +134,16 @@ type rolloutTurnEvent struct { } `json:"payload"` } +type rolloutAttentionEvent struct { + Timestamp time.Time `json:"timestamp"` + Ordinal *uint64 `json:"ordinal"` + Type string `json:"type"` + Payload struct { + Type string `json:"type"` + IsBlocking *bool `json:"isBlocking"` + } `json:"payload"` +} + type rolloutMetadata struct { ID string ParentThreadID string @@ -325,6 +345,13 @@ func (r *LiveUsageReader) addFile(path string, info os.FileInfo) error { nonRoot: metadata.NonRoot, subagentHistoryStartOrdinal: metadata.SubagentHistoryStartOrdinal, } + if time.Since(info.ModTime()) <= activeRolloutHorizon { + attention, err := latestSessionAttention(path, cursor) + if err != nil { + return err + } + cursor.attention = attention + } if !r.initialized || !rolloutCreatedAfter(path, r.startedAt) { total, err := latestTokenTotal(path) if err != nil { @@ -355,6 +382,11 @@ func (r *LiveUsageReader) consume(path string, cursor *rolloutCursor) error { } cursor.offset = info.Size() cursor.totalTokens = total + attention, attentionErr := latestSessionAttention(path, cursor) + if attentionErr != nil { + return attentionErr + } + cursor.attention = attention return nil } if info.Size() == cursor.offset { @@ -368,6 +400,10 @@ func (r *LiveUsageReader) consume(path string, cursor *rolloutCursor) error { line, readErr := reader.ReadBytes('\n') if len(line) > 0 && line[len(line)-1] == '\n' { cursor.offset += int64(len(line)) + if attention, ordinal, at, ok := sessionAttentionRecord(line); ok && + tokenRecordIsOwned(ordinal, cursor.subagentHistoryStartOrdinal, at, cursor.nonRoot, cursor.startedAt) { + cursor.attention = attention + } if record, ok := tokenUsageRecord(line); ok { if !tokenRecordIsOwned(record.ordinal, cursor.subagentHistoryStartOrdinal, record.at, cursor.nonRoot, cursor.startedAt) { // Legacy child rollouts copy the parent's cumulative token @@ -413,6 +449,72 @@ func (r *LiveUsageReader) consume(path string, cursor *rolloutCursor) error { } } +func latestSessionAttention(path string, cursor *rolloutCursor) (sessionAttentionState, error) { + file, err := os.Open(path) + if err != nil { + return sessionAttentionUnknown, err + } + defer file.Close() + info, err := file.Stat() + if err != nil { + return sessionAttentionUnknown, err + } + const chunkSize = int64(64 * 1024) + position := info.Size() + var carry []byte + for position > 0 { + readSize := min(chunkSize, position) + position -= readSize + chunk := make([]byte, int(readSize)) + if _, err := file.ReadAt(chunk, position); err != nil && !errors.Is(err, io.EOF) { + return sessionAttentionUnknown, err + } + data := make([]byte, 0, len(chunk)+len(carry)) + data = append(data, chunk...) + data = append(data, carry...) + lines := bytes.Split(data, []byte{'\n'}) + firstComplete := 1 + if position == 0 { + firstComplete = 0 + } + for index := len(lines) - 1; index >= firstComplete; index-- { + attention, ordinal, at, ok := sessionAttentionRecord(lines[index]) + if ok && tokenRecordIsOwned(ordinal, cursor.subagentHistoryStartOrdinal, at, cursor.nonRoot, cursor.startedAt) { + return attention, nil + } + } + carry = append(carry[:0], lines[0]...) + } + return sessionAttentionUnknown, nil +} + +func sessionAttentionRecord(line []byte) (sessionAttentionState, *uint64, time.Time, bool) { + if !bytes.Contains(line, []byte(`"event_msg"`)) && !bytes.Contains(line, []byte(`"response_item"`)) { + return sessionAttentionUnknown, nil, time.Time{}, false + } + var event rolloutAttentionEvent + if json.Unmarshal(line, &event) != nil { + return sessionAttentionUnknown, nil, time.Time{}, false + } + if event.Type == "response_item" && event.Payload.Type == "function_call_output" { + return sessionAttentionWorking, event.Ordinal, event.Timestamp, true + } + if event.Type != "event_msg" { + return sessionAttentionUnknown, nil, time.Time{}, false + } + switch event.Payload.Type { + case "request_user_input": + if event.Payload.IsBlocking == nil || *event.Payload.IsBlocking { + return sessionAttentionAwaiting, event.Ordinal, event.Timestamp, true + } + case "exec_approval_request", "apply_patch_approval_request", "request_permissions", "elicitation_request": + return sessionAttentionAwaiting, event.Ordinal, event.Timestamp, true + case "task_complete", "turn_complete", "task_started", "turn_started", "user_message", "exec_command_begin", "dynamic_tool_call_response": + return sessionAttentionWorking, event.Ordinal, event.Timestamp, true + } + return sessionAttentionUnknown, nil, time.Time{}, false +} + // appendBounded keeps insertion order while discarding the oldest values. The // reslice reuses the existing backing array until its remaining capacity is // exhausted, avoiding a full allocation and copy for every value after limit. @@ -611,7 +713,8 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time) ([]LiveUsageSession, i groups := make(map[string]*LiveUsageSession) for _, cursor := range r.files { active := now.Sub(cursor.lastModified) <= 5*time.Minute - if !active && cursor.observedTokens == 0 && len(cursor.modelCalls) == 0 && len(cursor.turnTimings) == 0 { + awaitingInput := now.Sub(cursor.lastModified) <= activeRolloutHorizon && cursor.attention == sessionAttentionAwaiting + if !active && !awaitingInput && cursor.observedTokens == 0 && len(cursor.modelCalls) == 0 && len(cursor.turnTimings) == 0 { continue } rootID, unattributed := rolloutRoot(cursor, byID) @@ -623,7 +726,8 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time) ([]LiveUsageSession, i group.TotalTokens += cursor.observedTokens group.ModelCalls = append(group.ModelCalls, cursor.modelCalls...) group.TurnTimings = append(group.TurnTimings, cursor.turnTimings...) - group.Active = group.Active || active + group.Active = group.Active || active || awaitingInput + group.AwaitingInput = group.AwaitingInput || awaitingInput if cursor.lastModified.After(group.LastActivity) { group.LastActivity = cursor.lastModified } @@ -636,7 +740,7 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time) ([]LiveUsageSession, i if cursor.threadID == rootID { group.WorkingDirectory = cursor.workingDirectory group.StartedAt = cursor.startedAt - } else if active || cursor.observedTokens > 0 || len(cursor.modelCalls) > 0 || len(cursor.turnTimings) > 0 { + } else if active || awaitingInput || cursor.observedTokens > 0 || len(cursor.modelCalls) > 0 || len(cursor.turnTimings) > 0 { group.AgentCount++ } } diff --git a/internal/codex/live_usage_test.go b/internal/codex/live_usage_test.go index 3e57eed8..5b4c8ef5 100644 --- a/internal/codex/live_usage_test.go +++ b/internal/codex/live_usage_test.go @@ -279,6 +279,104 @@ func TestLiveUsageReaderCapturesContentFreeModelCallAndTurnTimingPulses(t *testi } } +func TestLiveUsageReaderTracksDefiniteAwaitingUserLifecycle(t *testing.T) { + home := t.TempDir() + now := time.Now() + path := testRolloutPath(t, home, now.Add(-time.Hour), "attention") + blocking := true + writeRollout(t, path, + sessionMetaLine("attention", `"cli"`, "/work/attention", nil)+"\n"+ + attentionEventLine(now, "request_user_input", &blocking)+"\n") + reader, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + usage, err := reader.FetchTokenUsage(context.Background()) + if err != nil || len(usage.Sessions) != 1 || !usage.Sessions[0].AwaitingInput { + t.Fatalf("startup blocking attention = %#v, %v; want awaiting user", usage, err) + } + + appendRollout(t, path, attentionEventLine(now.Add(time.Second), "task_started", nil)+"\n") + usage, err = reader.FetchTokenUsage(context.Background()) + if err != nil || usage.Sessions[0].AwaitingInput { + t.Fatalf("started turn attention = %#v, %v; want working", usage, err) + } + + nonBlocking := false + appendRollout(t, path, attentionEventLine(now.Add(2*time.Second), "request_user_input", &nonBlocking)+"\n") + usage, err = reader.FetchTokenUsage(context.Background()) + if err != nil || usage.Sessions[0].AwaitingInput { + t.Fatalf("non-blocking input request changed attention: %#v, %v", usage, err) + } + + appendRollout(t, path, attentionEventLine(now.Add(3*time.Second), "request_user_input", &blocking)+"\n") + usage, err = reader.FetchTokenUsage(context.Background()) + if err != nil || !usage.Sessions[0].AwaitingInput { + t.Fatalf("blocking input request attention = %#v, %v; want awaiting", usage, err) + } + + appendRollout(t, path, responseItemLine(now.Add(4*time.Second), "function_call_output")+"\n") + usage, err = reader.FetchTokenUsage(context.Background()) + if err != nil || usage.Sessions[0].AwaitingInput { + t.Fatalf("input response did not clear attention: %#v, %v", usage, err) + } + + appendRollout(t, path, + attentionEventLine(now.Add(5*time.Second), "request_user_input", &blocking)+"\n"+ + attentionEventLine(now.Add(6*time.Second), "task_complete", nil)+"\n") + usage, err = reader.FetchTokenUsage(context.Background()) + if err != nil || usage.Sessions[0].AwaitingInput { + t.Fatalf("turn completion did not clear attention: %#v, %v", usage, err) + } +} + +func TestLiveUsageReaderPropagatesWaitingAgentToRoot(t *testing.T) { + home := t.TempDir() + now := time.Now() + created := now.Add(-time.Hour) + rootPath := testRolloutPath(t, home, created, "attention-root") + childPath := testRolloutPath(t, home, created, "attention-child") + writeRollout(t, rootPath, + sessionMetaLine("attention-root", `"cli"`, "/work/root", nil)+"\n"+ + attentionEventLine(now, "task_started", nil)+"\n") + writeRollout(t, childPath, + sessionMetaLine("attention-child", threadSpawnSource("attention-root"), "/work/root", nil)+"\n"+ + attentionEventLine(now, "exec_approval_request", nil)+"\n") + reader, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + usage, err := reader.FetchTokenUsage(context.Background()) + if err != nil || len(usage.Sessions) != 1 { + t.Fatalf("grouped attention fetch = %#v, %v", usage, err) + } + if session := usage.Sessions[0]; session.ID != "attention-root" || session.AgentCount != 1 || !session.AwaitingInput { + t.Fatalf("waiting child was not propagated to root: %#v", session) + } +} + +func TestLiveUsageReaderKeepsExplicitInputRequestVisibleBeyondRecentActivity(t *testing.T) { + home := t.TempDir() + now := time.Now() + waitingAt := now.Add(-10 * time.Minute) + path := testRolloutPath(t, home, now.Add(-time.Hour), "long-wait") + blocking := true + writeRollout(t, path, + sessionMetaLine("long-wait", `"cli"`, "/work/waiting", nil)+"\n"+ + attentionEventLine(waitingAt, "request_user_input", &blocking)+"\n") + if err := os.Chtimes(path, waitingAt, waitingAt); err != nil { + t.Fatal(err) + } + reader, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + usage, err := reader.FetchTokenUsage(context.Background()) + if err != nil || usage.SessionCount != 1 || len(usage.Sessions) != 1 || !usage.Sessions[0].AwaitingInput { + t.Fatalf("long-wait attention = %#v, %v; want visible awaiting session", usage, err) + } +} + func TestLiveUsageReaderGroupsSpawnedDescendantsUnderIndependentRoots(t *testing.T) { home := t.TempDir() now := time.Now() @@ -569,6 +667,24 @@ func turnTimingUnavailableLine(at time.Time) string { ) } +func attentionEventLine(at time.Time, eventType string, blocking *bool) string { + blockingJSON := "" + if blocking != nil { + blockingJSON = fmt.Sprintf(`,"isBlocking":%t`, *blocking) + } + return fmt.Sprintf( + `{"timestamp":%q,"type":"event_msg","payload":{"type":%q%s}}`, + at.UTC().Format(time.RFC3339Nano), eventType, blockingJSON, + ) +} + +func responseItemLine(at time.Time, itemType string) string { + return fmt.Sprintf( + `{"timestamp":%q,"type":"response_item","payload":{"type":%q}}`, + at.UTC().Format(time.RFC3339Nano), itemType, + ) +} + func tokenCountLineWithOrdinal(at time.Time, total int64, ordinal uint64) string { return fmt.Sprintf( `{"timestamp":%q,"ordinal":%d,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"total_tokens":%d}}}}`, diff --git a/internal/codex/types.go b/internal/codex/types.go index 6958300a..920e2efb 100644 --- a/internal/codex/types.go +++ b/internal/codex/types.go @@ -50,11 +50,20 @@ type ResetCredits struct { } type Meter struct { - Bucket string - Name string - Window Window + Bucket string + Name string + Window Window + Kind MeterKind + Details string } +type MeterKind int + +const ( + MeterQuotaWindow MeterKind = iota + MeterIndividualLimit +) + // Meters flattens every returned limit bucket and window into display order. func (s Snapshot) Meters() []Meter { buckets := s.RateLimitsByLimitID @@ -76,7 +85,7 @@ func (s Snapshot) Meters() []Meter { return keys[i] < keys[j] }) - meters := make([]Meter, 0, len(keys)*2) + meters := make([]Meter, 0, len(keys)*3) for _, key := range keys { bucket := buckets[key] name := key @@ -89,10 +98,61 @@ func (s Snapshot) Meters() []Meter { if bucket.Secondary != nil { meters = append(meters, Meter{Bucket: name, Name: windowName(*bucket.Secondary), Window: *bucket.Secondary}) } + if bucket.IndividualLimit != nil { + limit := bucket.IndividualLimit + var reset *int64 + if limit.ResetsAt > 0 { + value := limit.ResetsAt + reset = &value + } + details := "" + if strings.TrimSpace(limit.Used) != "" && strings.TrimSpace(limit.Limit) != "" { + details = fmt.Sprintf("%s OF %s CREDITS USED", strings.TrimSpace(limit.Used), strings.TrimSpace(limit.Limit)) + } + meters = append(meters, Meter{ + Bucket: name, + Name: "MONTHLY CREDIT LIMIT", + Window: Window{UsedPercent: 100 - limit.RemainingPercent, ResetsAt: reset}, + Kind: MeterIndividualLimit, + Details: details, + }) + } } return meters } +// CreditStatus returns the first meaningful account credit balance, preferring +// the primary Codex bucket when the server returns multiple limit buckets. +func (s Snapshot) CreditStatus() (Credits, bool) { + if len(s.RateLimitsByLimitID) == 0 { + return meaningfulCredits(s.RateLimits.Credits) + } + if bucket, ok := s.RateLimitsByLimitID["codex"]; ok { + if credits, ok := meaningfulCredits(bucket.Credits); ok { + return credits, true + } + } + keys := make([]string, 0, len(s.RateLimitsByLimitID)) + for key := range s.RateLimitsByLimitID { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + if credits, ok := meaningfulCredits(s.RateLimitsByLimitID[key].Credits); ok { + return credits, true + } + } + return meaningfulCredits(s.RateLimits.Credits) +} + +func meaningfulCredits(credits *Credits) (Credits, bool) { + hasBalance := credits != nil && credits.Balance != nil && strings.TrimSpace(*credits.Balance) != "" + if credits == nil || (!credits.HasCredits && !credits.Unlimited && !hasBalance) { + return Credits{}, false + } + return *credits, true +} + func windowName(window Window) string { if window.WindowDurationMins == nil { return "QUOTA WINDOW" diff --git a/internal/codex/types_test.go b/internal/codex/types_test.go index 25ebc40e..6bb2189d 100644 --- a/internal/codex/types_test.go +++ b/internal/codex/types_test.go @@ -16,7 +16,9 @@ func TestMetersIncludesEveryBucketAndWindow(t *testing.T) { }, "codex": { "primary": {"usedPercent": 42, "windowDurationMins": 300}, - "secondary": {"usedPercent": 5, "windowDurationMins": 10080} + "secondary": {"usedPercent": 5, "windowDurationMins": 10080}, + "individualLimit": {"limit": "25000", "used": "8000", "remainingPercent": 68, "resetsAt": 987654}, + "credits": {"hasCredits": true, "unlimited": false, "balance": "17000"} } } }`) @@ -27,8 +29,8 @@ func TestMetersIncludesEveryBucketAndWindow(t *testing.T) { } meters := snapshot.Meters() - if len(meters) != 3 { - t.Fatalf("got %d meters, want 3", len(meters)) + if len(meters) != 4 { + t.Fatalf("got %d meters, want 4", len(meters)) } if meters[0].Bucket != "codex" || meters[0].Name != "5 HOURS" || meters[0].Window.UsedPercent != 42 { t.Fatalf("unexpected primary meter: %#v", meters[0]) @@ -36,10 +38,34 @@ func TestMetersIncludesEveryBucketAndWindow(t *testing.T) { if meters[1].Name != "1 WEEK" { t.Fatalf("unexpected secondary name: %q", meters[1].Name) } - if meters[2].Bucket != "codex_other" || meters[2].Name != "30 MINUTES" || - meters[2].Window.WindowDurationMins == nil || *meters[2].Window.WindowDurationMins != 30 || - meters[2].Window.ResetsAt == nil || *meters[2].Window.ResetsAt != 123456 { - t.Fatalf("unexpected additional meter: %#v", meters[2]) + if meters[2].Kind != MeterIndividualLimit || meters[2].Name != "MONTHLY CREDIT LIMIT" || + meters[2].Window.UsedPercent != 32 || meters[2].Window.ResetsAt == nil || *meters[2].Window.ResetsAt != 987654 || + meters[2].Details != "8000 OF 25000 CREDITS USED" { + t.Fatalf("unexpected individual-limit meter: %#v", meters[2]) + } + if meters[3].Bucket != "codex_other" || meters[3].Name != "30 MINUTES" || + meters[3].Window.WindowDurationMins == nil || *meters[3].Window.WindowDurationMins != 30 || + meters[3].Window.ResetsAt == nil || *meters[3].Window.ResetsAt != 123456 { + t.Fatalf("unexpected additional meter: %#v", meters[3]) + } + credits, ok := snapshot.CreditStatus() + if !ok || credits.Balance == nil || *credits.Balance != "17000" { + t.Fatalf("unexpected credit status: %#v, %v", credits, ok) + } +} + +func TestCreditStatusFallsBackDeterministicallyAndIgnoresEmptyData(t *testing.T) { + balance := "42" + snapshot := Snapshot{RateLimitsByLimitID: map[string]RateLimitSnapshot{ + "zeta": {Credits: &Credits{HasCredits: true, Balance: &balance}}, + "alpha": {}, + }} + credits, ok := snapshot.CreditStatus() + if !ok || credits.Balance == nil || *credits.Balance != balance { + t.Fatalf("credit fallback = %#v, %v", credits, ok) + } + if _, ok := (Snapshot{}).CreditStatus(); ok { + t.Fatal("empty snapshot reported credits") } } diff --git a/internal/ui/meters.go b/internal/ui/meters.go index 203f8fba..05c49991 100644 --- a/internal/ui/meters.go +++ b/internal/ui/meters.go @@ -161,13 +161,16 @@ func renderMeterArea(width, height int, meter codex.Meter, style meterStyleID, c visualHeight := 0 if height > 0 { bodyHeight = max(height-2, 1) - visualHeight = max(bodyHeight-3, 1) + chromeHeight := 3 + if meter.Details != "" { + chromeHeight++ + } + visualHeight = max(bodyHeight-chromeHeight, 1) } now := time.Now() visual := renderVisualizationSized(innerWidth, visualHeight, used, style, color, colors) if style == styleConsumptionPace { - pace, available := consumptionPace(meter.Window, now) - visual = renderConsumptionPaceSized(innerWidth, visualHeight, pace, available, colors) + visual = renderConsumptionPaceMeterSized(innerWidth, visualHeight, meter.Window, now, colors) } gaugeWidth := min(max(lipgloss.Width(visual), 1), innerWidth) resetGauge := renderResetGauge(innerWidth, gaugeWidth, meter.Window, now, reset, color, colors) @@ -175,7 +178,11 @@ func renderMeterArea(width, height int, meter codex.Meter, style meterStyleID, c gaugeWidth = max(innerWidth-6, 1) resetGauge = renderReverseResetGauge(innerWidth, gaugeWidth, meter.Window, now, reset, color, colors) } - bodyParts := []string{stats, visual, resetGauge} + bodyParts := []string{stats} + if meter.Details != "" { + bodyParts = append(bodyParts, colors.dimmed().Render(ansi.Truncate(meter.Details, innerWidth, ""))) + } + bodyParts = append(bodyParts, visual, resetGauge) if height > 0 && bodyHeight < 4 { switch bodyHeight { case 1: @@ -186,13 +193,19 @@ func renderMeterArea(width, height int, meter codex.Meter, style meterStyleID, c resetLine := strings.Split(resetGauge, "\n")[0] bodyParts = []string{stats, visual, resetLine} } + } else if height > 0 && bodyHeight == 4 && meter.Details != "" { + resetLine := strings.Split(resetGauge, "\n")[0] + bodyParts = []string{stats, colors.dimmed().Render(ansi.Truncate(meter.Details, innerWidth, "")), visual, resetLine} } body := strings.Join(bodyParts, "\n") title := meter.Name if meter.Bucket != "codex" { title = codex.DisplayName(meter.Bucket) + " // " + title } - title = ansi.Truncate(title+" LOOP", max(innerWidth-4, 1), "") + if meter.Kind == codex.MeterQuotaWindow { + title += " LOOP" + } + title = ansi.Truncate(title, max(innerWidth-4, 1), "") frameHeight := 0 if height > 0 { frameHeight = max(height-2, 1) @@ -212,7 +225,11 @@ func renderResetGaugeWithOptions(width, gaugeWidth int, window codex.Window, now gaugeWidth = min(max(gaugeWidth, 1), max(width, 1)) progress, ok := resetProgress(window, now) if !ok { - label := colors.dimmed().Render(ansi.Truncate("RESET CYCLE // RESET DATA UNAVAILABLE", width, "")) + message := "RESET CYCLE // RESET DATA UNAVAILABLE" + if window.ResetsAt != nil { + message = "CYCLE START UNAVAILABLE // " + resetLabel + } + label := colors.dimmed().Render(ansi.Truncate(message, width, "")) bar := lipgloss.NewStyle().Foreground(colors.dim).Render(strings.Repeat("░", gaugeWidth)) return label + "\n" + lipgloss.PlaceHorizontal(width, alignment, bar) } @@ -399,6 +416,16 @@ func radialCanvasSize(width, height, legendWidth int) (int, int) { } func renderConsumptionPaceSized(width, height, pace int, available bool, colors palette) string { + return renderConsumptionPaceWithProjectionSized(width, height, pace, available, "", colors) +} + +func renderConsumptionPaceMeterSized(width, height int, window codex.Window, now time.Time, colors palette) string { + pace, available := consumptionPace(window, now) + projection := formatConsumptionProjection(consumptionProjectionFor(window, now)) + return renderConsumptionPaceWithProjectionSized(width, height, pace, available, projection, colors) +} + +func renderConsumptionPaceWithProjectionSized(width, height, pace int, available bool, projection string, colors palette) string { width = max(width, 1) pace = min(max(pace, -100), 100) center := (width - 1) / 2 @@ -431,6 +458,9 @@ func renderConsumptionPaceSized(width, height, pace int, available bool, colors labels := colors.dimmed().Render(paceScaleLabels(width)) lines := []string{caption, labels, axis, status} + if projection != "" { + lines = append(lines, colors.dimmed().Render(ansi.Truncate(projection, width, ""))) + } if height <= 0 { height = len(lines) } @@ -438,13 +468,111 @@ func renderConsumptionPaceSized(width, height, pace int, available bool, colors case 1: lines = lines[2:3] case 2: - lines = lines[2:] + lines = lines[2:4] case 3: - lines = lines[1:] + if projection != "" { + lines = lines[2:] + } else { + lines = lines[1:] + } + case 4: + if projection != "" { + lines = lines[1:] + } } return lipgloss.Place(width, height, lipgloss.Center, lipgloss.Center, strings.Join(lines, "\n")) } +type consumptionProjectionKind int + +const ( + consumptionProjectionUnavailable consumptionProjectionKind = iota + consumptionProjectionNoBurn + consumptionProjectionSafe + consumptionProjectionEarly + consumptionProjectionExhausted +) + +type consumptionProjection struct { + kind consumptionProjectionKind + timeToExhaustion time.Duration + earlyBy time.Duration + projectedRemaining int +} + +func consumptionProjectionFor(window codex.Window, now time.Time) consumptionProjection { + if window.WindowDurationMins == nil || window.ResetsAt == nil || *window.WindowDurationMins <= 0 { + return consumptionProjection{kind: consumptionProjectionUnavailable} + } + duration := time.Duration(*window.WindowDurationMins) * time.Minute + resetAt := time.Unix(*window.ResetsAt, 0) + elapsed := now.Sub(resetAt.Add(-duration)) + if elapsed <= 0 || elapsed >= duration { + return consumptionProjection{kind: consumptionProjectionUnavailable} + } + used := min(max(window.UsedPercent, 0), 100) + if used == 0 { + return consumptionProjection{kind: consumptionProjectionNoBurn} + } + if used >= 100 { + return consumptionProjection{kind: consumptionProjectionExhausted} + } + timeToExhaustion := time.Duration(float64(elapsed) * float64(100-used) / float64(used)) + exhaustsAt := now.Add(timeToExhaustion) + if !exhaustsAt.Before(resetAt) { + projectedUsed := float64(used) * float64(duration) / float64(elapsed) + projectedRemaining := int(math.Round(100 - projectedUsed)) + return consumptionProjection{ + kind: consumptionProjectionSafe, + timeToExhaustion: timeToExhaustion, + projectedRemaining: min(max(projectedRemaining, 0), 100), + } + } + return consumptionProjection{ + kind: consumptionProjectionEarly, + timeToExhaustion: timeToExhaustion, + earlyBy: resetAt.Sub(exhaustsAt), + } +} + +func formatConsumptionProjection(projection consumptionProjection) string { + switch projection.kind { + case consumptionProjectionNoBurn: + return "LINEAR PROJECTION // NO BURN YET" + case consumptionProjectionSafe: + return fmt.Sprintf("LINEAR PROJECTION // SAFE THROUGH RESET // ~%d%% LEFT", projection.projectedRemaining) + case consumptionProjectionEarly: + return fmt.Sprintf("LINEAR PROJECTION // LIMIT IN ~%s // %s EARLY", + projectionDuration(projection.timeToExhaustion), projectionDuration(projection.earlyBy)) + case consumptionProjectionExhausted: + return "LINEAR PROJECTION // LIMIT REACHED" + default: + return "" + } +} + +func projectionDuration(duration time.Duration) string { + if duration < time.Minute { + return "<1M" + } + minutes := int(math.Round(duration.Minutes())) + days := minutes / (24 * 60) + hours := minutes / 60 % 24 + remainingMinutes := minutes % 60 + switch { + case days > 0 && hours > 0: + return fmt.Sprintf("%dD %dH", days, hours) + case days > 0: + return fmt.Sprintf("%dD", days) + case hours > 0 && remainingMinutes > 0: + return fmt.Sprintf("%dH %dM", hours, remainingMinutes) + case hours > 0: + return fmt.Sprintf("%dH", hours) + default: + return fmt.Sprintf("%dM", remainingMinutes) + } +} + func paceAxis(width, center, marker, pace int, available bool, markerColor lipgloss.Color, colors palette) string { if width < 3 { value := "?" diff --git a/internal/ui/meters_test.go b/internal/ui/meters_test.go index 65ad8b3d..a8d3633e 100644 --- a/internal/ui/meters_test.go +++ b/internal/ui/meters_test.go @@ -152,6 +152,57 @@ func TestConsumptionPaceComparesElapsedTimeWithUsage(t *testing.T) { } } +func TestConsumptionProjectionDistinguishesSafeEarlyAndUnavailable(t *testing.T) { + duration := int64(100) + reset := time.Unix(20_000, 0) + now := reset.Add(-50 * time.Minute) + window := codex.Window{UsedPercent: 25, WindowDurationMins: &duration, ResetsAt: ptr(reset.Unix())} + projection := consumptionProjectionFor(window, now) + if projection.kind != consumptionProjectionSafe || projection.projectedRemaining != 50 { + t.Fatalf("safe projection = %#v, want 50%% remaining", projection) + } + if label := formatConsumptionProjection(projection); !strings.Contains(label, "SAFE THROUGH RESET") || !strings.Contains(label, "~50% LEFT") { + t.Fatalf("safe projection label = %q", label) + } + + window.UsedPercent = 75 + projection = consumptionProjectionFor(window, now) + if projection.kind != consumptionProjectionEarly || projection.timeToExhaustion < 16*time.Minute || projection.timeToExhaustion > 17*time.Minute || + projection.earlyBy < 33*time.Minute || projection.earlyBy > 34*time.Minute { + t.Fatalf("early projection = %#v, want limit in about 17m and 33m early", projection) + } + if label := formatConsumptionProjection(projection); !strings.Contains(label, "LIMIT IN ~17M") || !strings.Contains(label, "33M EARLY") { + t.Fatalf("early projection label = %q", label) + } + + window.UsedPercent = 0 + if label := formatConsumptionProjection(consumptionProjectionFor(window, now)); !strings.Contains(label, "NO BURN YET") { + t.Fatalf("zero-burn projection label = %q", label) + } + if label := formatConsumptionProjection(consumptionProjectionFor(codex.Window{UsedPercent: 25}, now)); label != "" { + t.Fatalf("unavailable projection was displayed: %q", label) + } +} + +func TestMonthlyCreditMeterShowsDetailsWithoutInventingCycleProgress(t *testing.T) { + colors := paletteFor(themeHacker) + reset := time.Now().Add(14 * 24 * time.Hour).Unix() + meter := codex.Meter{ + Bucket: "codex", Name: "MONTHLY CREDIT LIMIT", Kind: codex.MeterIndividualLimit, + Details: "8000 OF 25000 CREDITS USED", + Window: codex.Window{UsedPercent: 32, ResetsAt: &reset}, + } + output := ansi.Strip(renderMeterArea(80, 18, meter, styleBars, colors)) + for _, want := range []string{"MONTHLY CREDIT LIMIT", "USED 32%", "8000 OF 25000 CREDITS USED", "CYCLE START UNAVAILABLE", "RESET T-"} { + if !strings.Contains(output, want) { + t.Errorf("monthly meter missing %q:\n%s", want, output) + } + } + if strings.Contains(output, "MONTHLY CREDIT LIMIT LOOP") || strings.Contains(output, "RESET CYCLE 0%") { + t.Fatalf("monthly meter invented a rolling cycle:\n%s", output) + } +} + func ptr[T any](value T) *T { return &value } func TestFuelTankReachesEmptyEndState(t *testing.T) { diff --git a/internal/ui/model.go b/internal/ui/model.go index 53bbaacb..2e1f862f 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -55,6 +55,7 @@ type Model struct { flashedButton footerButtonID flashSequence uint64 benchmarkRunner BenchmarkRunner + preferenceStore PreferenceStore benchmarkState benchmarkState benchmarkResults []codex.BenchmarkResult @@ -142,6 +143,7 @@ type monitorSession struct { lastActivity time.Time agentCount int active bool + awaitingInput bool displayed bool unattributed bool samples []monitorSample @@ -555,6 +557,7 @@ func (m Model) pressStyleTab(style meterStyleID) (tea.Model, tea.Cmd) { if style.isQuota() { m.quotaMeterStyle = style } + m.persistPreferences() m.styleSequence++ m.flashedStyle = style m.styleFlashing = true @@ -592,10 +595,12 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { switch button { case footerButtonTheme: m.theme = m.theme.next() + m.persistPreferences() case footerButtonView: if m.meterStyle.isQuota() { m.meterStyle = m.meterStyle.nextQuota() m.quotaMeterStyle = m.meterStyle + m.persistPreferences() } case footerButtonRefresh: if !m.loading { @@ -715,6 +720,7 @@ type dashboardGeometry struct { meterHeight int meterY int footerY int + headerSpacer bool } func (m Model) dashboardLayout() dashboardGeometry { @@ -732,7 +738,7 @@ func (m Model) dashboardLayout() dashboardGeometry { if contentWidth < 64 { headerHeight = 2 } - const statusHeight = 1 + statusHeight := 1 tabsHeight := 1 if m.meterStyle.isQuota() { tabsHeight++ @@ -743,9 +749,18 @@ func (m Model) dashboardLayout() dashboardGeometry { if m.err != nil { extraHeight += framedErrorHeight } - if len(m.snapshot.Meters()) == 0 { + meters := m.snapshot.Meters() + if len(meters) == 0 { extraHeight += framedErrorHeight } + if (m.meterStyle == styleBars || m.meterStyle == styleConsumptionPace || m.meterStyle == styleFuel) && len(meters) > 0 { + minimumMeterHeight := len(meters) * 3 + meterHeightWithSpacer := contentHeight - headerHeight - statusHeight - tabsHeight - extraHeight - footerHeight + meterHeightWithoutSpacer := meterHeightWithSpacer + statusHeight + if meterHeightWithSpacer < minimumMeterHeight && meterHeightWithoutSpacer >= minimumMeterHeight { + statusHeight = 0 + } + } tabsY := 1 + headerHeight + statusHeight quotaTabsY := -1 if m.meterStyle.isQuota() { @@ -764,6 +779,7 @@ func (m Model) dashboardLayout() dashboardGeometry { meterHeight: meterHeight, meterY: meterY, footerY: footerY, + headerSpacer: statusHeight > 0, } } @@ -844,6 +860,7 @@ func (m Model) benchmarkTasks() []codex.BenchmarkTask { func (m *Model) setBenchmarkFilter(filter benchmarkResultFilter) { m.benchmarkFilter = filter m.benchmarkScroll = 0 + m.persistPreferences() } func (m *Model) setBenchmarkRankMode(mode benchmarkRankMode) { @@ -852,6 +869,7 @@ func (m *Model) setBenchmarkRankMode(mode benchmarkRankMode) { } m.benchmarkRankMode = mode m.benchmarkScroll = 0 + m.persistPreferences() } func benchmarkRankButton(mode benchmarkRankMode) footerButtonID { @@ -1185,7 +1203,8 @@ func (m *Model) startMonitorSessions(usage codex.LiveUsageSnapshot, observedAt t baseline: session.TotalTokens, latest: session.TotalTokens, graphStart: session.TotalTokens, startedAt: observedAt, lastActivity: session.LastActivity, agentCount: session.AgentCount, - active: session.Active, displayed: session.Active, unattributed: session.Unattributed, + active: session.Active, awaitingInput: session.AwaitingInput, + displayed: session.Active, unattributed: session.Unattributed, callSequence: latestModelCallSequence(session.ModelCalls), turnSequence: latestTurnTimingSequence(session.TurnTimings), }) @@ -1202,6 +1221,7 @@ func (m *Model) startMonitorSessions(usage codex.LiveUsageSnapshot, observedAt t func (m *Model) syncMonitorSessions(usage codex.LiveUsageSnapshot, observedAt time.Time) { for index := range m.monitorSessionData { m.monitorSessionData[index].active = false + m.monitorSessionData[index].awaitingInput = false } for _, update := range usage.Sessions { index := m.monitorSessionIndex(update.ID) @@ -1214,7 +1234,8 @@ func (m *Model) syncMonitorSessions(usage codex.LiveUsageSnapshot, observedAt ti id: update.ID, workingDirectory: update.WorkingDirectory, latest: update.TotalTokens, graphStart: 0, startedAt: startedAt, lastActivity: update.LastActivity, agentCount: update.AgentCount, - active: update.Active, displayed: update.Active || update.TotalTokens > 0 || len(update.ModelCalls) > 0 || len(update.TurnTimings) > 0, + active: update.Active, awaitingInput: update.AwaitingInput, + displayed: update.Active || update.TotalTokens > 0 || len(update.ModelCalls) > 0 || len(update.TurnTimings) > 0, unattributed: update.Unattributed, } applyMonitorSessionTelemetry(&created, update, m.monitorStartedAt) @@ -1230,6 +1251,7 @@ func (m *Model) syncMonitorSessions(usage codex.LiveUsageSnapshot, observedAt ti session.lastActivity = update.LastActivity session.agentCount = max(session.agentCount, update.AgentCount) session.active = update.Active + session.awaitingInput = update.AwaitingInput session.displayed = session.displayed || update.Active || update.TotalTokens > session.baseline || len(update.ModelCalls) > 0 || len(update.TurnTimings) > 0 if update.WorkingDirectory != "" { diff --git a/internal/ui/monitor.go b/internal/ui/monitor.go index 68d7ea92..56a07f7b 100644 --- a/internal/ui/monitor.go +++ b/internal/ui/monitor.go @@ -261,6 +261,9 @@ func (m Model) renderMonitorSessionMetrics(width, height int, session monitorSes if session.active { status = "ACTIVE" } + if session.awaitingInput { + status = "AWAITING" + } innerWidth := max(width-4, 1) memberLabel := "ROOT" if session.agentCount > 0 { @@ -275,7 +278,14 @@ func (m Model) renderMonitorSessionMetrics(width, height int, session monitorSes bodyRows := max(height-2, 1) share := m.monitorSessionShare(total) usageLine := fmt.Sprintf("%s TOKENS // %.0f%% LOCAL", formatTokens(total), share*100) - lines := []string{colors.label().Render(ansi.Truncate(usageLine, innerWidth, ""))} + lines := make([]string, 0, bodyRows) + if session.awaitingInput { + badge := lipgloss.NewStyle().Bold(true).Foreground(colors.background).Background(colors.warning) + lines = append(lines, badge.Render(ansi.Truncate(" ● AWAITING YOU ", innerWidth, ""))) + } + if len(lines) < bodyRows { + lines = append(lines, colors.label().Render(ansi.Truncate(usageLine, innerWidth, ""))) + } appendLine := func(value string) { if len(lines) < bodyRows { lines = append(lines, colors.dimmed().Render(ansi.Truncate(value, innerWidth, ""))) @@ -295,10 +305,14 @@ func (m Model) renderMonitorSessionMetrics(width, height int, session monitorSes if !session.lastActivity.IsZero() { appendLine("LAST // " + compactDuration(time.Since(session.lastActivity)) + " AGO") } - if pageLabel != "" { + if pageLabel != "" && (!session.awaitingInput || len(lines) > 1) { lines[len(lines)-1] = colors.dimmed().Render(ansi.Truncate(pageLabel+" // PGUP/PGDN", innerWidth, "")) } - return frameSized(width, max(height-2, 1), title, strings.Join(lines, "\n"), colors.primary, colors) + borderColor := colors.primary + if session.awaitingInput { + borderColor = colors.warning + } + return frameSized(width, max(height-2, 1), title, strings.Join(lines, "\n"), borderColor, colors) } func formatMonitorCallActivity(session monitorSession, now time.Time) string { diff --git a/internal/ui/monitor_test.go b/internal/ui/monitor_test.go index 3b1fde27..279b39a8 100644 --- a/internal/ui/monitor_test.go +++ b/internal/ui/monitor_test.go @@ -649,6 +649,24 @@ func TestMonitorRecordingLampPulsesBetweenDarkAndBrightRed(t *testing.T) { } } +func TestMonitorSessionProminentlyHighlightsAwaitingUser(t *testing.T) { + colors := paletteFor(themeHacker) + model := Model{monitorState: monitorRunning, monitorStartedAt: time.Now().Add(-time.Minute)} + session := monitorSession{ + id: "019d-attention", workingDirectory: "/work/attention", startedAt: time.Now().Add(-time.Minute), + baseline: 100, latest: 250, active: true, awaitingInput: true, + } + output := model.renderMonitorSessionMetrics(42, 10, session, "", colors) + plain := ansi.Strip(output) + if !strings.Contains(plain, "● AWAITING YOU") || !strings.Contains(plain, "AWAITING // ROOT") { + t.Fatalf("awaiting session was not prominently labelled:\n%s", plain) + } + wantBadge := lipgloss.NewStyle().Bold(true).Foreground(colors.background).Background(colors.warning).Render(" ● AWAITING YOU ") + if !strings.Contains(output, wantBadge) { + t.Fatal("awaiting label was not highlighted with the warning treatment") + } +} + func TestMonitorLargeButtonsAreClickableAcrossTheirBoxes(t *testing.T) { model := Model{ snapshot: codex.DemoSnapshot(), width: 100, height: 36, diff --git a/internal/ui/preferences.go b/internal/ui/preferences.go new file mode 100644 index 00000000..9cd574f9 --- /dev/null +++ b/internal/ui/preferences.go @@ -0,0 +1,159 @@ +package ui + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "time" +) + +// Preferences contains the small set of presentation choices that survive +// between runs. Operational state and fetched account data are never stored. +type Preferences struct { + Theme string `json:"theme,omitempty"` + QuotaView string `json:"quotaView,omitempty"` + BenchmarkFilter string `json:"benchmarkFilter,omitempty"` + BenchmarkRank string `json:"benchmarkRank,omitempty"` +} + +type PreferenceStore interface { + Load() (Preferences, error) + Save(Preferences) error +} + +type FilePreferenceStore struct { + Path string +} + +func NewDefaultPreferenceStore() (FilePreferenceStore, error) { + directory, err := os.UserConfigDir() + if err != nil { + return FilePreferenceStore{}, err + } + return FilePreferenceStore{Path: filepath.Join(directory, "codexometer", "preferences.json")}, nil +} + +func (s FilePreferenceStore) Load() (Preferences, error) { + data, err := os.ReadFile(s.Path) + if errors.Is(err, os.ErrNotExist) { + return Preferences{}, nil + } + if err != nil { + return Preferences{}, err + } + var preferences Preferences + if err := json.Unmarshal(data, &preferences); err != nil { + return Preferences{}, err + } + return preferences, nil +} + +func (s FilePreferenceStore) Save(preferences Preferences) error { + data, err := json.MarshalIndent(preferences, "", " ") + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(s.Path), 0o700); err != nil { + return err + } + return os.WriteFile(s.Path, append(data, '\n'), 0o600) +} + +func NewWithPreferences(fetcher Fetcher, refreshEvery time.Duration, store PreferenceStore) Model { + model := New(fetcher, refreshEvery) + model.preferenceStore = store + if store == nil { + return model + } + preferences, err := store.Load() + if err == nil { + model.applyPreferences(preferences) + } + return model +} + +func (m *Model) applyPreferences(preferences Preferences) { + if theme, ok := themePreferenceIDs[preferences.Theme]; ok { + m.theme = theme + } + if style, ok := quotaViewPreferenceIDs[preferences.QuotaView]; ok { + m.meterStyle = style + m.quotaMeterStyle = style + } + if filter, ok := benchmarkFilterPreferenceIDs[preferences.BenchmarkFilter]; ok { + m.benchmarkFilter = filter + } + if rank, ok := benchmarkRankPreferenceIDs[preferences.BenchmarkRank]; ok { + m.benchmarkRankMode = rank + } +} + +func (m Model) persistPreferences() { + if m.preferenceStore == nil { + return + } + _ = m.preferenceStore.Save(Preferences{ + Theme: themePreferenceNames[m.theme], + QuotaView: quotaViewPreferenceNames[m.selectedQuotaStyle()], + BenchmarkFilter: benchmarkFilterPreferenceNames[m.benchmarkFilter], + BenchmarkRank: benchmarkRankPreferenceNames[m.benchmarkRankMode], + }) +} + +var themePreferenceNames = map[themeID]string{ + themeHacker: "hacker", themeRust: "rust", themeBlueSteel: "blue-steel", + themeUltraviolet: "ultraviolet", themeNightshade: "nightshade", +} + +var themePreferenceIDs = reverseThemePreferences(themePreferenceNames) + +func reverseThemePreferences(values map[themeID]string) map[string]themeID { + reversed := make(map[string]themeID, len(values)) + for id, value := range values { + reversed[value] = id + } + return reversed +} + +var quotaViewPreferenceNames = map[meterStyleID]string{ + styleBars: "bars", stylePie: "pie", styleConsumptionPace: "consumption-pace", styleFuel: "fuel-tank", +} + +var quotaViewPreferenceIDs = reverseStylePreferences(quotaViewPreferenceNames) + +func reverseStylePreferences(values map[meterStyleID]string) map[string]meterStyleID { + reversed := make(map[string]meterStyleID, len(values)) + for id, value := range values { + reversed[value] = id + } + return reversed +} + +var benchmarkFilterPreferenceNames = map[benchmarkResultFilter]string{ + benchmarkFilterAll: "all", benchmarkFilterPass: "pass", benchmarkFilterFail: "fail", +} + +var benchmarkFilterPreferenceIDs = reverseFilterPreferences(benchmarkFilterPreferenceNames) + +func reverseFilterPreferences(values map[benchmarkResultFilter]string) map[string]benchmarkResultFilter { + reversed := make(map[string]benchmarkResultFilter, len(values)) + for id, value := range values { + reversed[value] = id + } + return reversed +} + +var benchmarkRankPreferenceNames = map[benchmarkRankMode]string{ + benchmarkRankBalanced: "balanced", benchmarkRankCost: "cost", benchmarkRankSpeed: "speed", +} + +var benchmarkRankPreferenceIDs = reverseRankPreferences(benchmarkRankPreferenceNames) + +func reverseRankPreferences(values map[benchmarkRankMode]string) map[string]benchmarkRankMode { + reversed := make(map[string]benchmarkRankMode, len(values)) + for id, value := range values { + reversed[value] = id + } + return reversed +} diff --git a/internal/ui/preferences_test.go b/internal/ui/preferences_test.go new file mode 100644 index 00000000..079dac61 --- /dev/null +++ b/internal/ui/preferences_test.go @@ -0,0 +1,77 @@ +package ui + +import ( + "errors" + "path/filepath" + "testing" + "time" +) + +type memoryPreferenceStore struct { + preferences Preferences + loadErr error + saves []Preferences +} + +func (s *memoryPreferenceStore) Load() (Preferences, error) { + return s.preferences, s.loadErr +} + +func (s *memoryPreferenceStore) Save(preferences Preferences) error { + s.preferences = preferences + s.saves = append(s.saves, preferences) + return nil +} + +func TestPreferencesRestoreAndPersistPresentationChoices(t *testing.T) { + store := &memoryPreferenceStore{preferences: Preferences{ + Theme: "nightshade", QuotaView: "fuel-tank", BenchmarkFilter: "fail", BenchmarkRank: "cost", + }} + model := NewWithPreferences(nil, time.Minute, store) + if model.theme != themeNightshade || model.meterStyle != styleFuel || model.quotaMeterStyle != styleFuel || + model.benchmarkFilter != benchmarkFilterFail || model.benchmarkRankMode != benchmarkRankCost { + t.Fatalf("preferences were not restored: %#v", model) + } + + updated, _ := model.Update(key('t')) + model = updated.(Model) + updated, _ = model.Update(key('v')) + model = updated.(Model) + model.setBenchmarkFilter(benchmarkFilterPass) + model.setBenchmarkRankMode(benchmarkRankSpeed) + if len(store.saves) != 4 { + t.Fatalf("preference saves = %d, want one for each presentation change", len(store.saves)) + } + last := store.saves[len(store.saves)-1] + if last.Theme != "hacker" || last.QuotaView != "bars" || last.BenchmarkFilter != "pass" || last.BenchmarkRank != "speed" { + t.Fatalf("persisted preferences = %#v", last) + } +} + +func TestInvalidOrUnreadablePreferencesKeepSafeDefaults(t *testing.T) { + for _, store := range []*memoryPreferenceStore{ + {preferences: Preferences{Theme: "missing", QuotaView: "rotary", BenchmarkFilter: "maybe", BenchmarkRank: "tokens"}}, + {loadErr: errors.New("broken config")}, + } { + model := NewWithPreferences(nil, time.Minute, store) + if model.theme != themeHacker || model.meterStyle != styleBars || model.benchmarkFilter != benchmarkFilterAll || + model.benchmarkRankMode != benchmarkRankBalanced { + t.Fatalf("invalid preferences changed defaults: %#v", model) + } + } +} + +func TestFilePreferenceStoreRoundTripAndMissingFile(t *testing.T) { + store := FilePreferenceStore{Path: filepath.Join(t.TempDir(), "nested", "preferences.json")} + if preferences, err := store.Load(); err != nil || preferences != (Preferences{}) { + t.Fatalf("missing preference file = %#v, %v", preferences, err) + } + want := Preferences{Theme: "rust", QuotaView: "pie", BenchmarkFilter: "pass", BenchmarkRank: "balanced"} + if err := store.Save(want); err != nil { + t.Fatal(err) + } + got, err := store.Load() + if err != nil || got != want { + t.Fatalf("preference round trip = %#v, %v; want %#v", got, err, want) + } +} diff --git a/internal/ui/quota_status.go b/internal/ui/quota_status.go index e26f5626..6f676ecb 100644 --- a/internal/ui/quota_status.go +++ b/internal/ui/quota_status.go @@ -1,6 +1,9 @@ package ui import ( + "sort" + "strconv" + "strings" "time" "github.com/charmbracelet/lipgloss" @@ -12,6 +15,7 @@ type quotaHealth int const ( quotaHealthUnknown quotaHealth = iota + quotaHealthFresh quotaHealthClear quotaHealthWatch quotaHealthNear @@ -21,6 +25,7 @@ const ( func (h quotaHealth) label() string { return [...]string{ "QUOTA UNKNOWN", + "RESET FRESH // GO!", "QUOTA CLEAR", "QUOTA WATCH", "LIMIT NEAR", @@ -31,6 +36,7 @@ func (h quotaHealth) label() string { func (h quotaHealth) compactLabel() string { return [...]string{ "UNKNOWN", + "FRESH // GO!", "CLEAR", "WATCH", "NEAR", @@ -40,7 +46,7 @@ func (h quotaHealth) compactLabel() string { func (h quotaHealth) color(colors palette) lipgloss.Color { switch h { - case quotaHealthClear: + case quotaHealthFresh, quotaHealthClear: return lipgloss.Color("#57FF8A") case quotaHealthWatch: return lipgloss.Color("#67B7FF") @@ -53,19 +59,54 @@ func (h quotaHealth) color(colors palette) lipgloss.Color { } } -func snapshotQuotaHealth(snapshot codex.Snapshot, now time.Time) quotaHealth { - if snapshotReportsLimitReached(snapshot) { - return quotaHealthExhausted +type quotaSignal struct { + health quotaHealth + cause string +} + +func (s quotaSignal) label() string { + if s.health == quotaHealthFresh || s.health == quotaHealthUnknown || s.cause == "" { + return s.health.label() + } + return s.cause + " // " + s.health.compactLabel() +} + +func (s quotaSignal) compactLabel() string { + if s.health == quotaHealthFresh || s.health == quotaHealthUnknown || s.cause == "" { + return s.health.compactLabel() + } + return compactQuotaCause(s.cause) + " " + s.health.compactLabel() +} + +func snapshotQuotaSignal(snapshot codex.Snapshot, now time.Time) quotaSignal { + if cause, reached := snapshotLimitReachedCause(snapshot); reached { + return quotaSignal{health: quotaHealthExhausted, cause: cause} } meters := snapshot.Meters() if len(meters) == 0 { - return quotaHealthUnknown + return quotaSignal{health: quotaHealthUnknown} } health := quotaHealthClear + cause := "" + allZero := true for _, meter := range meters { - health = max(health, windowQuotaHealth(meter.Window, now)) + if meter.Window.UsedPercent != 0 { + allZero = false + } + candidate := windowQuotaHealth(meter.Window, now) + if candidate > health { + health = candidate + cause = meterQuotaCause(meter) + } } - return health + if allZero { + return quotaSignal{health: quotaHealthFresh} + } + return quotaSignal{health: health, cause: cause} +} + +func snapshotQuotaHealth(snapshot codex.Snapshot, now time.Time) quotaHealth { + return snapshotQuotaSignal(snapshot, now).health } func windowQuotaHealth(window codex.Window, now time.Time) quotaHealth { @@ -110,17 +151,67 @@ func quotaHealthWithoutPace(used int) quotaHealth { } } -func snapshotReportsLimitReached(snapshot codex.Snapshot) bool { - reached := func(limit codex.RateLimitSnapshot) bool { - return limit.RateLimitReachedType != nil && *limit.RateLimitReachedType != "" +func snapshotLimitReachedCause(snapshot codex.Snapshot) (string, bool) { + reached := func(limit codex.RateLimitSnapshot, fallback string) (string, bool) { + if limit.SpendControlReached != nil && *limit.SpendControlReached { + return "SPEND", true + } + if limit.RateLimitReachedType == nil || *limit.RateLimitReachedType == "" { + return "", false + } + switch *limit.RateLimitReachedType { + case "workspace_owner_credits_depleted", "workspace_member_credits_depleted": + return "CREDITS", true + case "workspace_owner_usage_limit_reached", "workspace_member_usage_limit_reached": + return "SPEND", true + default: + return fallback, true + } } - if reached(snapshot.RateLimits) { - return true + if cause, ok := reached(snapshot.RateLimits, "QUOTA"); ok { + return cause, true } - for _, limit := range snapshot.RateLimitsByLimitID { - if reached(limit) { - return true + keys := make([]string, 0, len(snapshot.RateLimitsByLimitID)) + for key := range snapshot.RateLimitsByLimitID { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + limit := snapshot.RateLimitsByLimitID[key] + fallback := codex.DisplayName(key) + if limit.LimitName != nil && *limit.LimitName != "" { + fallback = codex.DisplayName(*limit.LimitName) + } + if cause, ok := reached(limit, fallback); ok { + return cause, true } } - return false + return "", false +} + +func meterQuotaCause(meter codex.Meter) string { + if meter.Kind == codex.MeterIndividualLimit { + return "MONTHLY" + } + if meter.Bucket == "codex" { + return meter.Name + } + return codex.DisplayName(meter.Bucket) + " " + meter.Name +} + +func compactQuotaCause(cause string) string { + fields := strings.Fields(cause) + if len(fields) == 2 { + if value, err := strconv.Atoi(fields[0]); err == nil { + unit := map[string]string{"MINUTE": "M", "MINUTES": "M", "HOUR": "H", "HOURS": "H", "DAY": "D", "DAYS": "D", "WEEK": "W", "WEEKS": "W"}[fields[1]] + if unit != "" { + return strconv.Itoa(value) + unit + } + } + } + runes := []rune(cause) + if len(runes) > 12 { + return string(runes[:12]) + } + return cause } diff --git a/internal/ui/quota_status_test.go b/internal/ui/quota_status_test.go index bbb20e59..557e9055 100644 --- a/internal/ui/quota_status_test.go +++ b/internal/ui/quota_status_test.go @@ -59,6 +59,9 @@ func TestSnapshotQuotaHealthUsesWorstWindowAndExplicitLimitSignal(t *testing.T) if got := snapshotQuotaHealth(snapshot, now); got != quotaHealthWatch { t.Fatalf("worst-window health = %s, want %s", got.label(), quotaHealthWatch.label()) } + if signal := snapshotQuotaSignal(snapshot, now); signal.cause != "100 MINUTES" { + t.Fatalf("worst-window cause = %q, want 100 MINUTES", signal.cause) + } reached := "primary" snapshot.RateLimits.RateLimitReachedType = &reached @@ -66,11 +69,37 @@ func TestSnapshotQuotaHealthUsesWorstWindowAndExplicitLimitSignal(t *testing.T) t.Fatalf("explicit reached health = %s, want %s", got.label(), quotaHealthExhausted.label()) } + spendReached := true + snapshot.RateLimits.RateLimitReachedType = nil + snapshot.RateLimits.SpendControlReached = &spendReached + if signal := snapshotQuotaSignal(snapshot, now); signal.health != quotaHealthExhausted || signal.cause != "SPEND" { + t.Fatalf("spend-control signal = %#v, want SPEND exhausted", signal) + } + if got := snapshotQuotaHealth(codex.Snapshot{}, now); got != quotaHealthUnknown { t.Fatalf("empty snapshot health = %s, want %s", got.label(), quotaHealthUnknown.label()) } } +func TestSnapshotQuotaSignalIncludesMonthlyLimitAndFreshReset(t *testing.T) { + now := time.Date(2026, time.August, 12, 12, 0, 0, 0, time.UTC) + reset := now.Add(14 * 24 * time.Hour).Unix() + snapshot := codex.Snapshot{RateLimits: codex.RateLimitSnapshot{ + IndividualLimit: &codex.IndividualLimit{Limit: "100", Used: "90", RemainingPercent: 10, ResetsAt: reset}, + }} + if signal := snapshotQuotaSignal(snapshot, now); signal.health != quotaHealthWatch || signal.cause != "MONTHLY" { + t.Fatalf("monthly limit signal = %#v, want MONTHLY watch", signal) + } + + duration := int64(300) + snapshot = codex.Snapshot{RateLimits: codex.RateLimitSnapshot{ + Primary: &codex.Window{UsedPercent: 0, WindowDurationMins: &duration, ResetsAt: &reset}, + }} + if signal := snapshotQuotaSignal(snapshot, now); signal.health != quotaHealthFresh || signal.label() != "RESET FRESH // GO!" { + t.Fatalf("zero-consumption signal = %#v, want fresh reset", signal) + } +} + func TestQuotaHealthUsesSemanticSignalColors(t *testing.T) { colors := paletteFor(themeNightshade) for _, test := range []struct { @@ -78,6 +107,7 @@ func TestQuotaHealthUsesSemanticSignalColors(t *testing.T) { want lipgloss.Color }{ {quotaHealthClear, lipgloss.Color("#57FF8A")}, + {quotaHealthFresh, lipgloss.Color("#57FF8A")}, {quotaHealthWatch, lipgloss.Color("#67B7FF")}, {quotaHealthNear, lipgloss.Color("#FFB454")}, {quotaHealthExhausted, lipgloss.Color("#FF5F6D")}, @@ -97,9 +127,9 @@ func TestQuotaSignalLabelsRemainResponsive(t *testing.T) { width int want string }{ - {width: 80, want: "● ONLINE // QUOTA WATCH"}, - {width: 40, want: "● ON // WATCH"}, - {width: 20, want: "● WATCH"}, + {width: 80, want: "● ONLINE // 100 MINUTES // WATCH"}, + {width: 40, want: "● ON // 100M WATCH"}, + {width: 20, want: "● 100M WATCH"}, } { got := ansi.Strip(model.renderSignalStatus(test.width, colors)) if got != test.want { @@ -111,6 +141,21 @@ func TestQuotaSignalLabelsRemainResponsive(t *testing.T) { } } +func TestFreshResetSignalIsFunAndResponsive(t *testing.T) { + duration := int64(60) + reset := time.Now().Add(time.Hour).Unix() + model := Model{snapshot: codex.Snapshot{RateLimits: codex.RateLimitSnapshot{ + Primary: &codex.Window{UsedPercent: 0, WindowDurationMins: &duration, ResetsAt: &reset}, + }}} + colors := paletteFor(themeHacker) + for _, width := range []int{20, 40, 80} { + status := ansi.Strip(model.renderSignalStatus(width, colors)) + if !strings.Contains(status, "FRESH") || !strings.Contains(status, "GO!") { + t.Errorf("width %d fresh status is not celebratory: %q", width, status) + } + } +} + func quotaHealthTestWindow(now time.Time, used, elapsedPercent int) codex.Window { durationMinutes := int64(100) remainingMinutes := int64(100 - elapsedPercent) diff --git a/internal/ui/view.go b/internal/ui/view.go index 2b4d2728..2e2235d5 100644 --- a/internal/ui/view.go +++ b/internal/ui/view.go @@ -26,7 +26,10 @@ func (m Model) View() string { if m.loading && len(m.snapshot.Meters()) == 0 { parts = append(parts, renderBoot(contentWidth, m.phase, colors)) } else { - parts = append(parts, strings.Repeat(" ", contentWidth), m.renderMainTabs(contentWidth, colors)) + if layout.headerSpacer { + parts = append(parts, strings.Repeat(" ", contentWidth)) + } + parts = append(parts, m.renderMainTabs(contentWidth, colors)) if m.meterStyle.isQuota() { parts = append(parts, m.renderQuotaStyleTabs(contentWidth, colors)) } @@ -95,16 +98,18 @@ func (m Model) renderSignalStatus(width int, colors palette) string { if m.err != nil { return renderColoredSignal("STALE SIGNAL", colors.warning) } - health := snapshotQuotaHealth(m.snapshot, time.Now()) - semantic := lipgloss.NewStyle().Bold(true).Foreground(health.color(colors)) + signal := snapshotQuotaSignal(m.snapshot, time.Now()) + semantic := lipgloss.NewStyle().Bold(true).Foreground(signal.health.color(colors)) online := lipgloss.NewStyle().Bold(true).Foreground(colors.primary) if width < 24 { - return semantic.Render("● " + health.compactLabel()) + return semantic.Render(ansi.Truncate("● "+signal.compactLabel(), width, "")) } if width < 48 { - return semantic.Render("●") + online.Render(" ON // ") + semantic.Render(health.compactLabel()) + label := ansi.Truncate(signal.compactLabel(), max(width-8, 1), "") + return semantic.Render("●") + online.Render(" ON // ") + semantic.Render(label) } - return semantic.Render("●") + online.Render(" ONLINE // ") + semantic.Render(health.label()) + label := ansi.Truncate(signal.label(), max(width-12, 1), "") + return semantic.Render("●") + online.Render(" ONLINE // ") + semantic.Render(label) } func renderColoredSignal(label string, color lipgloss.Color) string { @@ -135,7 +140,17 @@ func (m Model) renderFooter(width int, colors palette) string { if m.snapshot.RateLimitResetCredits != nil && m.snapshot.RateLimitResetCredits.AvailableCount > 0 { left += fmt.Sprintf(" // RESET TOKENS %d", m.snapshot.RateLimitResetCredits.AvailableCount) } - status := left + if credits, ok := m.snapshot.CreditStatus(); ok { + switch { + case credits.Unlimited: + left += " // CREDITS UNLIMITED" + case credits.Balance != nil && strings.TrimSpace(*credits.Balance) != "": + left += " // CREDITS " + strings.TrimSpace(*credits.Balance) + case credits.HasCredits: + left += " // CREDITS AVAILABLE" + } + } + status := ansi.Truncate(left, width, "") buttons, separator := footerButtonLayoutWithTheme(width, colors.name, m.meterStyle.isQuota()) controls := make([]string, 0, len(buttons)) for _, button := range buttons { diff --git a/internal/ui/view_test.go b/internal/ui/view_test.go index b5eed381..7458b6a4 100644 --- a/internal/ui/view_test.go +++ b/internal/ui/view_test.go @@ -70,7 +70,7 @@ func TestViewReflowsAcrossTerminalDimensions(t *testing.T) { } } -func TestQuotaViewsAccommodateReintroducedFiveHourAndAdditionalWindows(t *testing.T) { +func TestQuotaViewsAccommodateFiveHourAdditionalAndMonthlyLimits(t *testing.T) { now := time.Now() window := func(used int, durationMinutes int64) *codex.Window { reset := now.Add(time.Duration(durationMinutes/2) * time.Minute).Unix() @@ -78,8 +78,9 @@ func TestQuotaViewsAccommodateReintroducedFiveHourAndAdditionalWindows(t *testin } snapshot := codex.Snapshot{RateLimitsByLimitID: map[string]codex.RateLimitSnapshot{ "codex": { - Primary: window(35, 300), - Secondary: window(48, 10_080), + Primary: window(35, 300), + Secondary: window(48, 10_080), + IndividualLimit: &codex.IndividualLimit{Limit: "25000", Used: "8000", RemainingPercent: 68, ResetsAt: now.Add(14 * 24 * time.Hour).Unix()}, }, "spark": { LimitName: ptr("spark"), @@ -87,7 +88,7 @@ func TestQuotaViewsAccommodateReintroducedFiveHourAndAdditionalWindows(t *testin Secondary: window(70, 1_440), }, }} - if meters := snapshot.Meters(); len(meters) != 4 || meters[0].Name != "5 HOURS" { + if meters := snapshot.Meters(); len(meters) != 5 || meters[0].Name != "5 HOURS" || meters[2].Name != "MONTHLY CREDIT LIMIT" { t.Fatalf("restored snapshot produced meters %#v", meters) } @@ -99,13 +100,13 @@ func TestQuotaViewsAccommodateReintroducedFiveHourAndAdditionalWindows(t *testin } output := ansi.Strip(model.View()) if got := lipgloss.Width(output); got > size.width { - t.Errorf("%s with four windows at %dx%d rendered width %d", style.name(), size.width, size.height, got) + t.Errorf("%s with five limits at %dx%d rendered width %d", style.name(), size.width, size.height, got) } if got := lipgloss.Height(output); got > size.height { - t.Errorf("%s with four windows at %dx%d rendered height %d:\n%s", style.name(), size.width, size.height, got, output) + t.Errorf("%s with five limits at %dx%d rendered height %d:\n%s", style.name(), size.width, size.height, got, output) } if size.width >= 80 { - for _, title := range []string{"5 HOURS LOOP", "1 WEEK LOOP", "SPARK // 1 HOUR LOOP", "SPARK // 1 DAY LOOP"} { + for _, title := range []string{"5 HOURS LOOP", "1 WEEK LOOP", "MONTHLY CREDIT LIMIT", "SPARK // 1 HOUR LOOP", "SPARK // 1 DAY LOOP"} { if !strings.Contains(output, title) { t.Errorf("%s at %dx%d omitted %q:\n%s", style.name(), size.width, size.height, title, output) } @@ -130,7 +131,7 @@ func TestStatusAndFooterKeepOnlyEssentialMetadata(t *testing.T) { headerLines := strings.Split(header, "\n") firstLine := headerLines[0] status := ansi.Strip(model.renderSignalStatus(100, colors)) - if !strings.HasSuffix(firstLine, status) || !strings.Contains(status, "● ONLINE // QUOTA ") { + if !strings.HasSuffix(firstLine, status) || !strings.Contains(status, "● ONLINE // 5 HOURS // ") { t.Fatalf("online status is not at the top right of the header: %q", firstLine) } if !strings.HasSuffix(headerLines[len(headerLines)-1], "ACCOUNT // PLUS") { @@ -146,6 +147,17 @@ func TestStatusAndFooterKeepOnlyEssentialMetadata(t *testing.T) { } } +func TestFooterShowsAvailableAccountCredits(t *testing.T) { + balance := "17000" + snapshot := codex.DemoSnapshot() + snapshot.RateLimits.Credits = &codex.Credits{HasCredits: true, Balance: &balance} + model := Model{snapshot: snapshot, nextRefresh: time.Now().Add(time.Minute), meterStyle: styleBars} + footer := ansi.Strip(model.renderFooter(100, paletteFor(themeHacker))) + if !strings.Contains(footer, "CREDITS 17000") { + t.Fatalf("account credit balance missing from footer: %q", footer) + } +} + func TestFrameTitlesAreIntegratedIntoBorderInsteadOfButtonBrackets(t *testing.T) { colors := paletteFor(themeHacker) output := ansi.Strip(frameSized(36, 3, "SESSION READOUT", "BODY", colors.primary, colors)) diff --git a/internal/version/version.go b/internal/version/version.go index bec6f45f..082f4c57 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -11,7 +11,7 @@ import ( // checkout. Release automation may override it with: // // -X github.com/merefield/codexometer/internal/version.Fallback=1.2.3 -var Fallback = "0.5.0" +var Fallback = "0.6.0" // Current returns the module version embedded by Go for tagged installs, or // Fallback for ordinary source builds. The leading tag prefix is omitted so diff --git a/internal/version/version_test.go b/internal/version/version_test.go index e4a6556a..99f84096 100644 --- a/internal/version/version_test.go +++ b/internal/version/version_test.go @@ -4,8 +4,8 @@ import "testing" func TestCurrentReportsMaintainedFallbackForSourceBuild(t *testing.T) { got := Current() - if got != "0.5.0" { - t.Fatalf("Current() = %q, want 0.5.0", got) + if got != "0.6.0" { + t.Fatalf("Current() = %q, want 0.6.0", got) } } diff --git a/main.go b/main.go index 0e58800d..35860b88 100644 --- a/main.go +++ b/main.go @@ -145,7 +145,7 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { fmt.Fprintln(stderr, "Codex auth check failed:", err) return 1 } - fmt.Fprintf(stdout, "Codex auth OK // %d quota window(s) online\n", len(snapshot.Meters())) + fmt.Fprintf(stdout, "Codex auth OK // %d limit meter(s) online\n", len(snapshot.Meters())) return 0 } @@ -170,6 +170,10 @@ func startUI(fetcher ui.Fetcher, refresh time.Duration, inline bool) error { if !inline { options = append(options, tea.WithAltScreen()) } - _, err := tea.NewProgram(ui.New(fetcher, refresh), options...).Run() + model := ui.New(fetcher, refresh) + if store, storeErr := ui.NewDefaultPreferenceStore(); storeErr == nil { + model = ui.NewWithPreferences(fetcher, refresh, store) + } + _, err := tea.NewProgram(model, options...).Run() return err } diff --git a/main_test.go b/main_test.go index cbdf2f4b..84130dcc 100644 --- a/main_test.go +++ b/main_test.go @@ -16,7 +16,7 @@ func TestRunVersion(t *testing.T) { for _, flag := range []string{"-v", "--version"} { var stdout, stderr bytes.Buffer code := run([]string{flag}, &stdout, &stderr, dependencies{}) - if code != 0 || stdout.String() != "codexometer v0.5.0\n" || stderr.Len() != 0 { + if code != 0 || stdout.String() != "codexometer v0.6.0\n" || stderr.Len() != 0 { t.Errorf("flag=%s code=%d stdout=%q stderr=%q", flag, code, stdout.String(), stderr.String()) } } @@ -38,7 +38,7 @@ func TestRunAuthCheckSuccessAndFailure(t *testing.T) { }, } code := run([]string{"--check-auth", "--codex", "/custom/codex"}, &stdout, &stderr, deps) - if code != 0 || !strings.Contains(stdout.String(), "2 quota window(s) online") { + if code != 0 || !strings.Contains(stdout.String(), "2 limit meter(s) online") { t.Fatalf("code=%d stdout=%q stderr=%q", code, stdout.String(), stderr.String()) } From 55e451f9a00dc5f7cee0726eb7bd5f0205659038 Mon Sep 17 00:00:00 2001 From: merefield Date: Thu, 13 Aug 2026 12:53:51 +0100 Subject: [PATCH 2/4] Harden benchmark pricing and monitor attention --- README.md | 144 ++++++++++++++++---- go.mod | 3 +- go.sum | 2 + internal/codex/benchmark.go | 44 ++++++ internal/codex/benchmark_test.go | 43 ++++++ internal/codex/daemon_status.go | 36 +++++ internal/codex/daemon_status_other.go | 5 + internal/codex/daemon_status_test.go | 23 ++++ internal/codex/daemon_status_unix.go | 112 ++++++++++++++++ internal/codex/daemon_status_unix_test.go | 88 ++++++++++++ internal/codex/filelock_unix.go | 28 ++++ internal/codex/filelock_unix_test.go | 30 +++++ internal/codex/filelock_windows.go | 37 +++++ internal/codex/filelock_windows_test.go | 31 +++++ internal/codex/live_usage.go | 156 +++++++++++++++++++--- internal/codex/live_usage_test.go | 142 ++++++++++++++++++-- internal/ui/model.go | 10 +- internal/ui/monitor.go | 36 ++++- internal/ui/monitor_test.go | 34 +++-- internal/ui/view.go | 26 +++- internal/ui/view_test.go | 46 +++++++ main.go | 4 +- 22 files changed, 1004 insertions(+), 76 deletions(-) create mode 100644 internal/codex/daemon_status.go create mode 100644 internal/codex/daemon_status_other.go create mode 100644 internal/codex/daemon_status_test.go create mode 100644 internal/codex/daemon_status_unix.go create mode 100644 internal/codex/daemon_status_unix_test.go create mode 100644 internal/codex/filelock_unix.go create mode 100644 internal/codex/filelock_unix_test.go create mode 100644 internal/codex/filelock_windows.go create mode 100644 internal/codex/filelock_windows_test.go diff --git a/README.md b/README.md index cad930b0..f5bdf964 100644 --- a/README.md +++ b/README.md @@ -61,8 +61,10 @@ It works particularly well in: - An optional Monitor view that measures token activity between Go and Stop. Each independent local root session gets its own metrics and 30-second graph; explicitly linked spawned agents are included with their root. -- A highlighted `AWAITING YOU` Monitor badge when a root or linked agent emits - an explicit blocking input or approval request. +- Highlighted per-session attention badges. A shared Codex app-server supplies + exact `INPUT NEEDED` and `APPROVAL NEEDED` states. Without it, a completed + open turn is definite `INPUT NEEDED`; an otherwise active session with no + rollout activity for three minutes is cautiously labelled `CHECK SESSION`. - An opt-in deterministic coding benchmark comparing every visible Codex model and supported reasoning effort by correctness, elapsed time, token use, and estimated standard API-equivalent cost. @@ -180,6 +182,63 @@ Preview all UI features using simulated quota data: codexometer --demo ``` +## Shared Codex daemon for precise Monitor status + +Codexometer works without a shared server, but its `CHECK SESSION` fallback +cannot distinguish every long-running local tool from a prompt. On Unix +systems, a current standalone Codex installation can instead run one shared +app-server daemon. Every CLI connected to that daemon exposes its live +per-thread `waitingOnApproval` and `waitingOnUserInput` flags, allowing the +Monitor to show definite `APPROVAL NEEDED` and `INPUT NEEDED` badges. + +Start the managed daemon and confirm that it is ready: + +```sh +codex app-server daemon start +codex app-server daemon version +``` + +Then launch each Codex CLI terminal against its default Unix control socket: + +```sh +codex --remote unix:// +``` + +Run that client command in every terminal tab or pane that should share the +daemon. Start Codexometer normally in another terminal: + +```sh +codexometer +``` + +No Codexometer option is required. While Monitor is recording, Codexometer +automatically probes the same default socket under `CODEX_HOME` and uses exact +runtime status for threads loaded there. Sessions belonging to ordinary, +non-daemon Codex processes continue to use the local rollout and writer-lock +fallback. + +Manage or stop the daemon with: + +```sh +codex app-server daemon restart +codex app-server daemon stop +``` + +The managed daemon lifecycle is currently experimental, Unix-only, and expects +the standalone Codex installation. The app-server also supports a local +WebSocket listener, including on Windows: + +```sh +codex app-server --listen ws://127.0.0.1:4500 +codex --remote ws://127.0.0.1:4500 +``` + +Plain WebSockets should be used only on localhost or through an SSH tunnel. +Codexometer currently auto-detects only the default Unix daemon socket, so +WebSocket-connected sessions use its fallback attention detection for now. See +the official [Codex app-server documentation](https://developers.openai.com/codex/app-server) +for custom socket paths, secure remote connections, and authentication. + ## Authentication and privacy Codexometer starts `codex app-server` as a short-lived child process and asks @@ -201,8 +260,10 @@ totals, last-response output counts, timestamps, and content-free turn timing, plus the minimum session metadata needed for grouping: thread ID, parent thread ID, source classification, working directory, and the inherited-history boundary. It also reads lifecycle event names and blocking flags to identify an -explicit unresolved input or approval request. Message text—including the final -response carried beside timing +explicit unresolved input or approval request. To distinguish an open CLI +waiting at its prompt from a closed historical session, it inspects the lock +state—not the contents—of Codex's per-thread writer lock. Message text—including +the final response carried beside timing metadata—reasoning, commands, tool results, and credentials are ignored and never retained by Codexometer. @@ -348,10 +409,19 @@ The other top-level views are: through an interval gets an honestly labelled partial first bar and its rate uses that root's own observed lifetime. New bars enter on the right, older bars move left, and each Y axis automatically rescales to its visible samples. - A root or linked child with a persisted blocking `request_user_input`, - permission, or approval event receives an amber `AWAITING YOU` badge and - border until a definite response, continuation, or completion event arrives. - Generic inactivity is never treated as a request for attention. + An open root or linked child whose latest durable lifecycle event says its + turn completed receives an amber `INPUT NEEDED` badge and border until a new + turn starts or the CLI closes. When Codexometer finds the default shared + Codex app-server socket, it reads the server's per-thread runtime status and + uses the exact `waitingOnApproval` and `waitingOnUserInput` flags for + `APPROVAL NEEDED` and `INPUT NEEDED`. If no shared server is available, an + otherwise active open session with no new token or rollout activity for three + minutes receives `CHECK SESSION`: a deliberately uncertain prompt that can + also mean a long-running local tool. Any subsequent activity clears it. + Codexometer never guesses `APPROVAL NEEDED` from inactivity. Closing the CLI + releases its per-thread writer lock and clears every attention badge. + A session already included in the current Monitor recording can remain as an + `IDLE` historical row so its completed metrics and graph are not discarded. When the terminal cannot fit every root, use Page Up, Page Down, or the mouse wheel to page through the rows. Stop performs an immediate final local read instead of relying on the latest graph sample. @@ -411,10 +481,10 @@ for a model response, not token-by-token while a response is streaming. Raw toke counts also do not reveal or reproduce the backend's quota-weighting rules, so they should not be converted directly into the percentage gauges. -Session rows represent recently active rollout roots plus explicit unresolved -input/approval waits observed within the 24-hour rollout horizon, not a -guaranteed list of currently open terminal processes. Two independent CLI tabs -have different root thread IDs and therefore remain separate rows. +Session rows represent recently active rollout roots plus open CLI sessions +waiting for input, not a guaranteed list of every terminal process. Two +independent CLI tabs have different root thread IDs and therefore remain +separate rows. `thread_spawn` descendants, including nested descendants, are folded into their root by following persisted parent IDs. Review, compact, or other internal work that lacks an explicit @@ -425,11 +495,17 @@ twice. Legacy spawned-agent rollouts without an ordinal boundary are separated at the child session timestamp: inherited cumulative totals establish the child counter baseline but are not reported as new usage. -Attention detection reads only content-free lifecycle metadata: event type, -blocking flag, ordinal, and timestamp. It does not retain the input question, -approval text, response, or conversation content. A linked child's attention -state is folded into its root so one remote Monitor row identifies the CLI -session that needs intervention. +Attention detection reads only content-free lifecycle metadata, per-thread +writer-lock state, and—when available—the shared app-server's runtime thread +status. A held writer lock plus a completed turn reliably identifies an open +CLI waiting at its prompt. Without a shared server, three minutes without any +new rollout-file activity produces only `CHECK SESSION`, because persisted data +cannot distinguish an approval wait from every long-running local tool. The +Monitor does not retain the input question, approval text, response, or +conversation content. A linked child's attention state is folded into its root +so one remote Monitor row identifies the CLI session that needs intervention. +A definite approval signal takes precedence, then definite input, then the +inferred check state when linked members have mixed states. `CALLS` counts upstream model-response cycles observed after Monitor Start, not complete user turns. A single Codex turn can make several calls while using @@ -646,7 +722,10 @@ for an unknown model or a token class whose price was not published when the release was built. Codexometer does not inherit or guess such a price. Pricing can change after a binary is released; consult the [official OpenAI API pricing page](https://developers.openai.com/api/docs/pricing) -for current values. +for current values. The rates compiled into this version were retrieved from +that page on **2026-08-13**; the Benchmark footer displays both the retrieval +date and a terminal hyperlink to the source so stale embedded pricing is +visible while interpreting results. The figures are useful for comparing these particular observed trials, but they have important limitations: @@ -696,8 +775,8 @@ is: | **P2** | Reduce cache-order bias with balanced warm-ups, randomized ordering, or repeated trials | Open | | **P2** | Report a cache-neutral comparison alongside the observed cached cost | Open | | **P2** | Price mixed-model reroutes from a response-to-model association | Open; the current raw event does not expose that association | -| **P2** | Record pricing-table provenance and make stale compiled pricing conspicuous | Open | -| **P2** | Add explicit compatibility diagnostics for future experimental-event schema changes | Partial; automatic cumulative fallback is already implemented | +| **P2** | Record pricing-table provenance and make stale compiled pricing conspicuous | Complete; the Benchmark footer shows its source and retrieval date | +| **P2** | Add explicit compatibility diagnostics for future experimental-event schema changes | Complete for usage objects; unknown token fields fail closed and older servers retain the cumulative fallback | Future accounting changes should preserve these rules: @@ -711,9 +790,10 @@ Future accounting changes should preserve these rules: measurement problem must not change the deterministic Starlark verdict. - Prefer exact response telemetry only when response IDs are present and unique; retain the cumulative path for compatible older app-servers. -- Do not infer prices for unknown models or unpublished token classes. Update - the compiled table only from published OpenAI pricing and record its source - and effective date when provenance support is added. +- Do not infer prices for unknown models or unpublished token classes. Unknown + usage fields must make costing unavailable. Update the compiled table only + from published OpenAI pricing, and update its source retrieval date at the + same time. - Treat any tool-use item as a benchmark protocol violation. Text-token pricing alone cannot represent separately priced or externally executed work. - Cover missing fields, invalid invariants, integer overflow, duplicate events, @@ -813,6 +893,10 @@ bucket closes only after the boundary telemetry read completes; its heading reports the actual observed duration when scheduling or first-session detection makes it shorter or longer than 30 seconds. These reads do not contact OpenAI or invoke a model. +On Unix systems, each read also probes the default shared app-server control +socket. When present, its loaded-thread runtime statuses make attention badges +exact; when absent or unreachable, Codexometer silently uses the local rollout +and writer-lock fallback described above. Pressing Stop performs one immediate final local read and forces complete session discovery, including Codex sessions resumed from older rollout directories. @@ -859,6 +943,20 @@ other machines are not visible. Usage is generally appended after a model response reports its token totals, so a currently streaming response may not appear until its next telemetry event. +## Roadmap + +- **Observed quota capacity** — investigate an experimental Monitor estimate + inspired by [CPA Codex Helper](https://github.com/disaeye/CPA-codex-helper). + By comparing locally observed token and API-equivalent usage with movement in + an account quota percentage, Codexometer could estimate the full capacity of + a quota window. Any implementation should report a range, sample count, and + confidence level; require several percentage points of clean observation; + and reject intervals that cross a reset. It must remain clearly labelled as + an observed workload estimate—not a contractual token allowance, account + balance, subscription value, or bill—because account activity outside the + local `CODEX_HOME`, percentage rounding, model and reasoning mix, caching, and + private backend quota weighting can all affect the result. + ## Development Format, test, and vet the project: diff --git a/go.mod b/go.mod index 697cdd23..9fd45410 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,9 @@ require ( github.com/charmbracelet/bubbletea v1.2.4 github.com/charmbracelet/lipgloss v1.0.0 github.com/charmbracelet/x/ansi v0.4.5 + github.com/gorilla/websocket v1.5.3 go.starlark.net v0.0.0-20260708150628-5395d018f003 + golang.org/x/sys v0.42.0 ) require ( @@ -22,6 +24,5 @@ require ( github.com/muesli/termenv v0.15.2 // indirect github.com/rivo/uniseg v0.4.7 // indirect golang.org/x/sync v0.9.0 // indirect - golang.org/x/sys v0.42.0 // indirect golang.org/x/text v0.3.8 // indirect ) diff --git a/go.sum b/go.sum index a9de0a96..f2552ce5 100644 --- a/go.sum +++ b/go.sum @@ -12,6 +12,8 @@ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= diff --git a/internal/codex/benchmark.go b/internal/codex/benchmark.go index bf86c8f0..a9e12a8f 100644 --- a/internal/codex/benchmark.go +++ b/internal/codex/benchmark.go @@ -11,6 +11,7 @@ import ( "math" "os" "os/exec" + "sort" "strings" "sync" "time" @@ -26,6 +27,12 @@ const ( benchmarkCodeLimit = 64 * 1024 benchmarkStepLimit = 250_000 benchmarkHardStepLimit = 2_000_000 + + // BenchmarkPricingSourceURL and BenchmarkPricingRetrievedOn identify the + // published rates compiled into this release. Keep both in sync whenever + // standardAPIPrices changes. + BenchmarkPricingSourceURL = "https://developers.openai.com/api/docs/pricing" + BenchmarkPricingRetrievedOn = "2026-08-13" ) // BenchmarkUsage is the app-server token breakdown for one isolated turn. @@ -36,6 +43,40 @@ type BenchmarkUsage struct { CacheWriteInputTokens int64 `json:"cacheWriteInputTokens"` OutputTokens int64 `json:"outputTokens"` ReasoningOutputTokens int64 `json:"reasoningOutputTokens"` + schemaIssue string +} + +// UnmarshalJSON records unknown fields instead of silently discarding them. +// A future app-server token class may be billable, so costing must remain +// unavailable until Codexometer knows how to account for it. +func (u *BenchmarkUsage) UnmarshalJSON(data []byte) error { + type wireUsage BenchmarkUsage + var decoded wireUsage + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + known := map[string]struct{}{ + "totalTokens": {}, "inputTokens": {}, "cachedInputTokens": {}, + "cacheWriteInputTokens": {}, "outputTokens": {}, "reasoningOutputTokens": {}, + } + unknown := make([]string, 0) + for name := range fields { + if _, ok := known[name]; !ok { + unknown = append(unknown, name) + } + } + sort.Strings(unknown) + *u = BenchmarkUsage(decoded) + if len(unknown) == 1 { + u.schemaIssue = "unknown usage field: " + unknown[0] + } else if len(unknown) > 1 { + u.schemaIssue = "unknown usage fields: " + strings.Join(unknown, ", ") + } + return nil } // BenchmarkUsageSource identifies the telemetry used for a benchmark result. @@ -859,6 +900,9 @@ func (u *BenchmarkUsage) add(other BenchmarkUsage) string { } func validateBenchmarkUsage(usage BenchmarkUsage) string { + if usage.schemaIssue != "" { + return usage.schemaIssue + } fields := []struct { name string value int64 diff --git a/internal/codex/benchmark_test.go b/internal/codex/benchmark_test.go index 6daaaa6d..d3e51f14 100644 --- a/internal/codex/benchmark_test.go +++ b/internal/codex/benchmark_test.go @@ -563,6 +563,49 @@ func TestValidateBenchmarkUsageInvariants(t *testing.T) { } } +func TestBenchmarkUsageRejectsUnknownTokenFields(t *testing.T) { + var usage BenchmarkUsage + input := `{ + "totalTokens": 130, + "inputTokens": 100, + "cachedInputTokens": 20, + "cacheWriteInputTokens": 10, + "outputTokens": 30, + "reasoningOutputTokens": 15, + "vectorTokens": 2, + "audioTokens": 1 + }` + if err := json.Unmarshal([]byte(input), &usage); err != nil { + t.Fatalf("decode usage: %v", err) + } + want := "unknown usage fields: audioTokens, vectorTokens" + if issue := validateBenchmarkUsage(usage); issue != want { + t.Fatalf("usage issue = %q, want %q", issue, want) + } + if _, known, issue := estimateAPICostWithIssue("gpt-5.6-sol", usage); known || !strings.Contains(issue, want) { + t.Fatalf("unknown token fields received a cost: known=%v issue=%q", known, issue) + } + + state := newBenchmarkTelemetry() + state.recordCumulative(usage) + var result BenchmarkResult + state.apply(&result) + if result.UsageKnown || !strings.Contains(result.UsageIssue, want) { + t.Fatalf("unknown token fields did not fail telemetry closed: %#v", result) + } +} + +func TestBenchmarkUsageAcceptsDocumentedTokenFields(t *testing.T) { + var usage BenchmarkUsage + input := `{"totalTokens":130,"inputTokens":100,"cachedInputTokens":20,"cacheWriteInputTokens":10,"outputTokens":30,"reasoningOutputTokens":15}` + if err := json.Unmarshal([]byte(input), &usage); err != nil { + t.Fatalf("decode usage: %v", err) + } + if issue := validateBenchmarkUsage(usage); issue != "" { + t.Fatalf("documented usage fields rejected: %s", issue) + } +} + func TestExperimentalAPIUnsupported(t *testing.T) { for _, test := range []struct { err error diff --git a/internal/codex/daemon_status.go b/internal/codex/daemon_status.go new file mode 100644 index 00000000..474c7264 --- /dev/null +++ b/internal/codex/daemon_status.go @@ -0,0 +1,36 @@ +package codex + +import "context" + +type sessionRuntimeStatus int + +const ( + sessionRuntimeUnknown sessionRuntimeStatus = iota + sessionRuntimeWorking + sessionRuntimeIdle + sessionRuntimeInput + sessionRuntimeApproval +) + +type sessionStatusProvider interface { + Fetch(context.Context, []string) (map[string]sessionRuntimeStatus, bool) +} + +func parseSessionRuntimeStatus(kind string, flags []string) sessionRuntimeStatus { + if kind == "idle" { + return sessionRuntimeIdle + } + if kind != "active" { + return sessionRuntimeUnknown + } + status := sessionRuntimeWorking + for _, flag := range flags { + switch flag { + case "waitingOnApproval": + return sessionRuntimeApproval + case "waitingOnUserInput": + status = sessionRuntimeInput + } + } + return status +} diff --git a/internal/codex/daemon_status_other.go b/internal/codex/daemon_status_other.go new file mode 100644 index 00000000..336eff8a --- /dev/null +++ b/internal/codex/daemon_status_other.go @@ -0,0 +1,5 @@ +//go:build !unix + +package codex + +func newSessionStatusProvider(string) sessionStatusProvider { return nil } diff --git a/internal/codex/daemon_status_test.go b/internal/codex/daemon_status_test.go new file mode 100644 index 00000000..468f7cb9 --- /dev/null +++ b/internal/codex/daemon_status_test.go @@ -0,0 +1,23 @@ +package codex + +import "testing" + +func TestParseSessionRuntimeStatus(t *testing.T) { + tests := []struct { + kind string + flags []string + want sessionRuntimeStatus + }{ + {"idle", nil, sessionRuntimeIdle}, + {"active", nil, sessionRuntimeWorking}, + {"active", []string{"waitingOnUserInput"}, sessionRuntimeInput}, + {"active", []string{"waitingOnApproval"}, sessionRuntimeApproval}, + {"active", []string{"waitingOnUserInput", "waitingOnApproval"}, sessionRuntimeApproval}, + {"notLoaded", nil, sessionRuntimeUnknown}, + } + for _, test := range tests { + if got := parseSessionRuntimeStatus(test.kind, test.flags); got != test.want { + t.Errorf("parseSessionRuntimeStatus(%q, %v) = %v; want %v", test.kind, test.flags, got, test.want) + } + } +} diff --git a/internal/codex/daemon_status_unix.go b/internal/codex/daemon_status_unix.go new file mode 100644 index 00000000..b99a7790 --- /dev/null +++ b/internal/codex/daemon_status_unix.go @@ -0,0 +1,112 @@ +//go:build unix + +package codex + +import ( + "context" + "encoding/json" + "net" + "net/http" + "path/filepath" + "time" + + "github.com/gorilla/websocket" +) + +const daemonStatusTimeout = 2 * time.Second + +type daemonStatusProvider struct { + socketPath string +} + +func newSessionStatusProvider(codexHome string) sessionStatusProvider { + return daemonStatusProvider{socketPath: filepath.Join(codexHome, "app-server-control", "app-server-control.sock")} +} + +func (p daemonStatusProvider) Fetch(ctx context.Context, threadIDs []string) (map[string]sessionRuntimeStatus, bool) { + dialer := websocket.Dialer{ + HandshakeTimeout: daemonStatusTimeout, + NetDialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{Timeout: daemonStatusTimeout}).DialContext(ctx, "unix", p.socketPath) + }, + } + connection, response, err := dialer.DialContext(ctx, "ws://localhost/", http.Header{}) + if response != nil && response.Body != nil { + _ = response.Body.Close() + } + if err != nil { + return nil, false + } + defer connection.Close() + setDaemonDeadline := func() { + deadline := time.Now().Add(daemonStatusTimeout) + _ = connection.SetReadDeadline(deadline) + _ = connection.SetWriteDeadline(deadline) + } + setDaemonDeadline() + + requestID := int64(1) + var initialized struct { + UserAgent string `json:"userAgent"` + } + if err := daemonRequest(connection, requestID, "initialize", map[string]any{ + "clientInfo": map[string]string{"name": "codexometer", "title": "Codexometer", "version": "monitor"}, + }, &initialized); err != nil { + return nil, false + } + if err := connection.WriteJSON(map[string]any{"method": "initialized", "params": map[string]any{}}); err != nil { + return nil, false + } + + statuses := make(map[string]sessionRuntimeStatus, len(threadIDs)) + for _, threadID := range threadIDs { + setDaemonDeadline() + requestID++ + var result struct { + Thread struct { + ID string `json:"id"` + Status struct { + Type string `json:"type"` + ActiveFlags []string `json:"activeFlags"` + } `json:"status"` + } `json:"thread"` + } + if err := daemonRequest(connection, requestID, "thread/read", map[string]any{ + "threadId": threadID, "includeTurns": false, + }, &result); err != nil { + continue + } + status := parseSessionRuntimeStatus(result.Thread.Status.Type, result.Thread.Status.ActiveFlags) + if status != sessionRuntimeUnknown { + statuses[threadID] = status + } + } + return statuses, true +} + +func daemonRequest(connection *websocket.Conn, id int64, method string, params any, target any) error { + if err := connection.WriteJSON(map[string]any{"id": id, "method": method, "params": params}); err != nil { + return err + } + for { + var envelope struct { + ID *int64 `json:"id"` + Result json.RawMessage `json:"result"` + Error json.RawMessage `json:"error"` + } + if err := connection.ReadJSON(&envelope); err != nil { + return err + } + if envelope.ID == nil || *envelope.ID != id { + continue + } + if len(envelope.Error) > 0 && string(envelope.Error) != "null" { + return &daemonResponseError{payload: string(envelope.Error)} + } + return json.Unmarshal(envelope.Result, target) + } +} + +type daemonResponseError struct{ payload string } + +func (e *daemonResponseError) Error() string { return e.payload } diff --git a/internal/codex/daemon_status_unix_test.go b/internal/codex/daemon_status_unix_test.go new file mode 100644 index 00000000..023412c1 --- /dev/null +++ b/internal/codex/daemon_status_unix_test.go @@ -0,0 +1,88 @@ +//go:build unix + +package codex + +import ( + "context" + "encoding/json" + "errors" + "net" + "net/http" + "os" + "path/filepath" + "testing" + + "github.com/gorilla/websocket" +) + +func TestDaemonStatusProviderReadsExactThreadStates(t *testing.T) { + socketPath := filepath.Join(t.TempDir(), "app-server.sock") + listener, err := net.Listen("unix", socketPath) + if err != nil { + if errors.Is(err, os.ErrPermission) { + t.Skip("sandbox does not permit Unix-domain socket listeners") + } + t.Fatal(err) + } + upgrader := websocket.Upgrader{} + server := &http.Server{Handler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + connection, upgradeErr := upgrader.Upgrade(writer, request, nil) + if upgradeErr != nil { + return + } + defer connection.Close() + for { + var message struct { + ID *int64 `json:"id"` + Method string `json:"method"` + Params map[string]any `json:"params"` + } + if readErr := connection.ReadJSON(&message); readErr != nil { + return + } + if message.ID == nil { + continue + } + switch message.Method { + case "initialize": + _ = connection.WriteJSON(map[string]any{"id": *message.ID, "result": map[string]any{"userAgent": "codex/1.0"}}) + case "thread/read": + threadID, _ := message.Params["threadId"].(string) + status := map[string]any{"type": "active", "activeFlags": []string{}} + if threadID == "approval" { + status["activeFlags"] = []string{"waitingOnApproval"} + } + _ = connection.WriteJSON(map[string]any{"id": *message.ID, "result": map[string]any{ + "thread": map[string]any{"id": threadID, "status": status}, + }}) + } + } + })} + done := make(chan struct{}) + go func() { + _ = server.Serve(listener) + close(done) + }() + t.Cleanup(func() { + _ = server.Close() + <-done + }) + + provider := daemonStatusProvider{socketPath: socketPath} + statuses, exact := provider.Fetch(context.Background(), []string{"working", "approval"}) + if !exact { + t.Fatal("shared daemon was not detected") + } + if statuses["working"] != sessionRuntimeWorking || statuses["approval"] != sessionRuntimeApproval { + t.Fatalf("exact daemon statuses = %#v", statuses) + } +} + +func TestDaemonStatusProviderFallsBackWhenSocketIsMissing(t *testing.T) { + provider := daemonStatusProvider{socketPath: filepath.Join(t.TempDir(), "missing.sock")} + statuses, exact := provider.Fetch(context.Background(), []string{"thread"}) + if exact || statuses != nil { + encoded, _ := json.Marshal(statuses) + t.Fatalf("missing daemon = exact %v statuses %s", exact, encoded) + } +} diff --git a/internal/codex/filelock_unix.go b/internal/codex/filelock_unix.go new file mode 100644 index 00000000..4c1d7e6f --- /dev/null +++ b/internal/codex/filelock_unix.go @@ -0,0 +1,28 @@ +//go:build !windows + +package codex + +import ( + "errors" + "os" + + "golang.org/x/sys/unix" +) + +func fileLockHeld(path string) (bool, error) { + file, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + return false, err + } + defer file.Close() + if err := unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { + if errors.Is(err, unix.EWOULDBLOCK) || errors.Is(err, unix.EAGAIN) { + return true, nil + } + return false, err + } + if err := unix.Flock(int(file.Fd()), unix.LOCK_UN); err != nil { + return false, err + } + return false, nil +} diff --git a/internal/codex/filelock_unix_test.go b/internal/codex/filelock_unix_test.go new file mode 100644 index 00000000..f82856c4 --- /dev/null +++ b/internal/codex/filelock_unix_test.go @@ -0,0 +1,30 @@ +//go:build !windows + +package codex + +import ( + "os" + "testing" + + "golang.org/x/sys/unix" +) + +func holdTestFileLock(t *testing.T, path string) func() { + t.Helper() + file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + t.Fatal(err) + } + if err := unix.Flock(int(file.Fd()), unix.LOCK_EX); err != nil { + file.Close() + t.Fatal(err) + } + return func() { + if err := unix.Flock(int(file.Fd()), unix.LOCK_UN); err != nil { + t.Errorf("unlock test writer: %v", err) + } + if err := file.Close(); err != nil { + t.Errorf("close test writer: %v", err) + } + } +} diff --git a/internal/codex/filelock_windows.go b/internal/codex/filelock_windows.go new file mode 100644 index 00000000..79b3616f --- /dev/null +++ b/internal/codex/filelock_windows.go @@ -0,0 +1,37 @@ +//go:build windows + +package codex + +import ( + "errors" + "os" + + "golang.org/x/sys/windows" +) + +func fileLockHeld(path string) (bool, error) { + file, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + return false, err + } + defer file.Close() + overlapped := new(windows.Overlapped) + err = windows.LockFileEx( + windows.Handle(file.Fd()), + windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, + 0, + 1, + 0, + overlapped, + ) + if err != nil { + if errors.Is(err, windows.ERROR_LOCK_VIOLATION) { + return true, nil + } + return false, err + } + if err := windows.UnlockFileEx(windows.Handle(file.Fd()), 0, 1, 0, overlapped); err != nil { + return false, err + } + return false, nil +} diff --git a/internal/codex/filelock_windows_test.go b/internal/codex/filelock_windows_test.go new file mode 100644 index 00000000..6a9cff3d --- /dev/null +++ b/internal/codex/filelock_windows_test.go @@ -0,0 +1,31 @@ +//go:build windows + +package codex + +import ( + "os" + "testing" + + "golang.org/x/sys/windows" +) + +func holdTestFileLock(t *testing.T, path string) func() { + t.Helper() + file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + t.Fatal(err) + } + overlapped := new(windows.Overlapped) + if err := windows.LockFileEx(windows.Handle(file.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, overlapped); err != nil { + file.Close() + t.Fatal(err) + } + return func() { + if err := windows.UnlockFileEx(windows.Handle(file.Fd()), 0, 1, 0, overlapped); err != nil { + t.Errorf("unlock test writer: %v", err) + } + if err := file.Close(); err != nil { + t.Errorf("close test writer: %v", err) + } + } +} diff --git a/internal/codex/live_usage.go b/internal/codex/live_usage.go index 04af47e8..7036a6ba 100644 --- a/internal/codex/live_usage.go +++ b/internal/codex/live_usage.go @@ -17,10 +17,11 @@ import ( ) const ( - activeRolloutHorizon = 24 * time.Hour - discoveryEvery = 5 * time.Second - fullDiscoveryEvery = 5 * time.Minute - telemetryHistoryMax = 4_096 + activeRolloutHorizon = 24 * time.Hour + discoveryEvery = 5 * time.Second + fullDiscoveryEvery = 5 * time.Minute + telemetryHistoryMax = 4_096 + fallbackAttentionAfter = 3 * time.Minute ) // LiveUsageSnapshot is a process-local, monotonically increasing count built @@ -42,12 +43,24 @@ type LiveUsageSession struct { LastActivity time.Time AgentCount int Active bool - AwaitingInput bool + Attention SessionAttention Unattributed bool ModelCalls []LiveModelCall TurnTimings []LiveTurnTiming } +// SessionAttention describes why a local Codex session may need the user. +// Input and approval are definite signals; Check is deliberately cautious and +// means only that an open fallback-observed session has remained quiet. +type SessionAttention int + +const ( + SessionAttentionNone SessionAttention = iota + SessionAttentionInput + SessionAttentionApproval + SessionAttentionCheck +) + // LiveModelCall is the small, content-free usage pulse persisted after one // upstream model response. type LiveModelCall struct { @@ -69,7 +82,9 @@ type LiveTurnTiming struct { // LiveUsageReader incrementally observes token telemetry written by local Codex // sessions. It never interprets message, reasoning, command, or tool contents. type LiveUsageReader struct { - SessionsRoot string + SessionsRoot string + WriterLocksRoot string + statusProvider sessionStatusProvider mu sync.Mutex initialized bool @@ -103,7 +118,9 @@ type sessionAttentionState int const ( sessionAttentionUnknown sessionAttentionState = iota sessionAttentionWorking - sessionAttentionAwaiting + sessionAttentionIdle + sessionAttentionInput + sessionAttentionApproval ) type rolloutEvent struct { @@ -191,7 +208,11 @@ func NewLiveUsageReader(codexHome string) (*LiveUsageReader, error) { return nil, err } } - return &LiveUsageReader{SessionsRoot: filepath.Join(codexHome, "sessions")}, nil + return &LiveUsageReader{ + SessionsRoot: filepath.Join(codexHome, "sessions"), + WriterLocksRoot: filepath.Join(codexHome, "thread-writer-locks"), + statusProvider: newSessionStatusProvider(codexHome), + }, nil } // FetchTokenUsage discovers active rollout files and consumes only complete, @@ -252,13 +273,34 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover return LiveUsageSnapshot{}, fmt.Errorf("read local Codex token telemetry: %w", firstReadErr) } - sessions, activeSessions := r.sessionSnapshots(now) + liveWriters, writerLocksSupported := r.liveWriterThreads() + exactStatuses := map[string]sessionRuntimeStatus(nil) + if r.statusProvider != nil { + exactStatuses, _ = r.statusProvider.Fetch(ctx, r.observedThreadIDs()) + } + sessions, activeSessions := r.sessionSnapshots(now, liveWriters, writerLocksSupported, exactStatuses) return LiveUsageSnapshot{ TotalTokens: r.totalTokens, LastActivity: r.lastActivity, SessionCount: activeSessions, Sessions: sessions, }, nil } +func (r *LiveUsageReader) observedThreadIDs() []string { + seen := make(map[string]struct{}, len(r.files)) + threadIDs := make([]string, 0, len(r.files)) + for _, cursor := range r.files { + if cursor.threadID == "" { + continue + } + if _, ok := seen[cursor.threadID]; ok { + continue + } + seen[cursor.threadID] = struct{}{} + threadIDs = append(threadIDs, cursor.threadID) + } + return threadIDs +} + func (r *LiveUsageReader) initialize(ctx context.Context, now time.Time) error { r.startedAt = now r.files = make(map[string]*rolloutCursor) @@ -505,11 +547,13 @@ func sessionAttentionRecord(line []byte) (sessionAttentionState, *uint64, time.T switch event.Payload.Type { case "request_user_input": if event.Payload.IsBlocking == nil || *event.Payload.IsBlocking { - return sessionAttentionAwaiting, event.Ordinal, event.Timestamp, true + return sessionAttentionInput, event.Ordinal, event.Timestamp, true } case "exec_approval_request", "apply_patch_approval_request", "request_permissions", "elicitation_request": - return sessionAttentionAwaiting, event.Ordinal, event.Timestamp, true - case "task_complete", "turn_complete", "task_started", "turn_started", "user_message", "exec_command_begin", "dynamic_tool_call_response": + return sessionAttentionApproval, event.Ordinal, event.Timestamp, true + case "task_complete", "turn_complete": + return sessionAttentionIdle, event.Ordinal, event.Timestamp, true + case "task_started", "turn_started", "user_message", "exec_command_begin", "dynamic_tool_call_response": return sessionAttentionWorking, event.Ordinal, event.Timestamp, true } return sessionAttentionUnknown, nil, time.Time{}, false @@ -702,7 +746,29 @@ func sessionSourceParent(raw json.RawMessage) (string, bool) { const unattributedSessionID = "unattributed" -func (r *LiveUsageReader) sessionSnapshots(now time.Time) ([]LiveUsageSession, int) { +func (r *LiveUsageReader) liveWriterThreads() (map[string]struct{}, bool) { + entries, err := os.ReadDir(r.WriterLocksRoot) + if err != nil { + return nil, false + } + live := make(map[string]struct{}) + for _, entry := range entries { + if entry.IsDir() || entry.Name() == ".coordination.lock" { + continue + } + threadID, ok := strings.CutSuffix(entry.Name(), ".lock") + if !ok || threadID == "" { + continue + } + held, err := fileLockHeld(filepath.Join(r.WriterLocksRoot, entry.Name())) + if err == nil && held { + live[threadID] = struct{}{} + } + } + return live, true +} + +func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string]struct{}, writerLocksSupported bool, exactStatuses map[string]sessionRuntimeStatus) ([]LiveUsageSession, int) { byID := make(map[string]*rolloutCursor, len(r.files)) for _, cursor := range r.files { if cursor.threadID != "" { @@ -713,8 +779,10 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time) ([]LiveUsageSession, i groups := make(map[string]*LiveUsageSession) for _, cursor := range r.files { active := now.Sub(cursor.lastModified) <= 5*time.Minute - awaitingInput := now.Sub(cursor.lastModified) <= activeRolloutHorizon && cursor.attention == sessionAttentionAwaiting - if !active && !awaitingInput && cursor.observedTokens == 0 && len(cursor.modelCalls) == 0 && len(cursor.turnTimings) == 0 { + _, writerActive := liveWriters[cursor.threadID] + exactStatus, exact := exactStatuses[cursor.threadID] + attention := sessionAttention(cursor.attention, writerActive, writerLocksSupported, now.Sub(cursor.lastModified), exactStatus, exact) + if !active && attention == SessionAttentionNone && cursor.observedTokens == 0 && len(cursor.modelCalls) == 0 && len(cursor.turnTimings) == 0 { continue } rootID, unattributed := rolloutRoot(cursor, byID) @@ -726,8 +794,8 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time) ([]LiveUsageSession, i group.TotalTokens += cursor.observedTokens group.ModelCalls = append(group.ModelCalls, cursor.modelCalls...) group.TurnTimings = append(group.TurnTimings, cursor.turnTimings...) - group.Active = group.Active || active || awaitingInput - group.AwaitingInput = group.AwaitingInput || awaitingInput + group.Active = group.Active || active || attention != SessionAttentionNone + group.Attention = mergeSessionAttention(group.Attention, attention) if cursor.lastModified.After(group.LastActivity) { group.LastActivity = cursor.lastModified } @@ -740,7 +808,7 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time) ([]LiveUsageSession, i if cursor.threadID == rootID { group.WorkingDirectory = cursor.workingDirectory group.StartedAt = cursor.startedAt - } else if active || awaitingInput || cursor.observedTokens > 0 || len(cursor.modelCalls) > 0 || len(cursor.turnTimings) > 0 { + } else if active || attention != SessionAttentionNone || cursor.observedTokens > 0 || len(cursor.modelCalls) > 0 || len(cursor.turnTimings) > 0 { group.AgentCount++ } } @@ -767,6 +835,58 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time) ([]LiveUsageSession, i return sessions, activeCount } +func sessionAttention(state sessionAttentionState, writerActive, writerLocksSupported bool, quietFor time.Duration, exactStatus sessionRuntimeStatus, exact bool) SessionAttention { + if exact { + switch exactStatus { + case sessionRuntimeApproval: + return SessionAttentionApproval + case sessionRuntimeInput: + return SessionAttentionInput + } + // A status supplied by the shared daemon is authoritative. In + // particular, an active thread without a waiting flag must not age into + // the fallback inactivity warning while a local tool is still running. + return SessionAttentionNone + } + if writerLocksSupported && !writerActive { + return SessionAttentionNone + } + switch state { + case sessionAttentionIdle: + if writerActive { + return SessionAttentionInput + } + case sessionAttentionInput: + return SessionAttentionInput + case sessionAttentionApproval: + return SessionAttentionApproval + } + if writerLocksSupported && writerActive && quietFor >= fallbackAttentionAfter { + return SessionAttentionCheck + } + return SessionAttentionNone +} + +func mergeSessionAttention(current, next SessionAttention) SessionAttention { + if sessionAttentionPriority(next) > sessionAttentionPriority(current) { + return next + } + return current +} + +func sessionAttentionPriority(attention SessionAttention) int { + switch attention { + case SessionAttentionApproval: + return 3 + case SessionAttentionInput: + return 2 + case SessionAttentionCheck: + return 1 + default: + return 0 + } +} + func firstNonZeroTime(times ...time.Time) time.Time { for _, candidate := range times { if !candidate.IsZero() { diff --git a/internal/codex/live_usage_test.go b/internal/codex/live_usage_test.go index 5b4c8ef5..ef94d0d1 100644 --- a/internal/codex/live_usage_test.go +++ b/internal/codex/live_usage_test.go @@ -292,32 +292,32 @@ func TestLiveUsageReaderTracksDefiniteAwaitingUserLifecycle(t *testing.T) { t.Fatal(err) } usage, err := reader.FetchTokenUsage(context.Background()) - if err != nil || len(usage.Sessions) != 1 || !usage.Sessions[0].AwaitingInput { + if err != nil || len(usage.Sessions) != 1 || usage.Sessions[0].Attention != SessionAttentionInput { t.Fatalf("startup blocking attention = %#v, %v; want awaiting user", usage, err) } appendRollout(t, path, attentionEventLine(now.Add(time.Second), "task_started", nil)+"\n") usage, err = reader.FetchTokenUsage(context.Background()) - if err != nil || usage.Sessions[0].AwaitingInput { + if err != nil || usage.Sessions[0].Attention != SessionAttentionNone { t.Fatalf("started turn attention = %#v, %v; want working", usage, err) } nonBlocking := false appendRollout(t, path, attentionEventLine(now.Add(2*time.Second), "request_user_input", &nonBlocking)+"\n") usage, err = reader.FetchTokenUsage(context.Background()) - if err != nil || usage.Sessions[0].AwaitingInput { + if err != nil || usage.Sessions[0].Attention != SessionAttentionNone { t.Fatalf("non-blocking input request changed attention: %#v, %v", usage, err) } appendRollout(t, path, attentionEventLine(now.Add(3*time.Second), "request_user_input", &blocking)+"\n") usage, err = reader.FetchTokenUsage(context.Background()) - if err != nil || !usage.Sessions[0].AwaitingInput { + if err != nil || usage.Sessions[0].Attention != SessionAttentionInput { t.Fatalf("blocking input request attention = %#v, %v; want awaiting", usage, err) } appendRollout(t, path, responseItemLine(now.Add(4*time.Second), "function_call_output")+"\n") usage, err = reader.FetchTokenUsage(context.Background()) - if err != nil || usage.Sessions[0].AwaitingInput { + if err != nil || usage.Sessions[0].Attention != SessionAttentionNone { t.Fatalf("input response did not clear attention: %#v, %v", usage, err) } @@ -325,11 +325,137 @@ func TestLiveUsageReaderTracksDefiniteAwaitingUserLifecycle(t *testing.T) { attentionEventLine(now.Add(5*time.Second), "request_user_input", &blocking)+"\n"+ attentionEventLine(now.Add(6*time.Second), "task_complete", nil)+"\n") usage, err = reader.FetchTokenUsage(context.Background()) - if err != nil || usage.Sessions[0].AwaitingInput { + if err != nil || usage.Sessions[0].Attention != SessionAttentionNone { t.Fatalf("turn completion did not clear attention: %#v, %v", usage, err) } } +func TestLiveUsageReaderUsesOpenWriterAndCompletedTurnForInputWait(t *testing.T) { + home := t.TempDir() + now := time.Now() + threadID := "open-idle" + path := testRolloutPath(t, home, now.Add(-time.Hour), threadID) + writeRollout(t, path, + sessionMetaLine(threadID, `"cli"`, "/work/open", nil)+"\n"+ + attentionEventLine(now, "task_complete", nil)+"\n") + locks := filepath.Join(home, "thread-writer-locks") + if err := os.MkdirAll(locks, 0o755); err != nil { + t.Fatal(err) + } + release := holdTestFileLock(t, filepath.Join(locks, threadID+".lock")) + + reader, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + usage, err := reader.FetchTokenUsage(context.Background()) + if err != nil || len(usage.Sessions) != 1 || usage.Sessions[0].Attention != SessionAttentionInput { + t.Fatalf("open completed CLI = %#v, %v; want input needed", usage, err) + } + + appendRollout(t, path, attentionEventLine(now.Add(time.Second), "task_started", nil)+"\n") + usage, err = reader.FetchTokenUsage(context.Background()) + if err != nil || usage.Sessions[0].Attention != SessionAttentionNone { + t.Fatalf("open active CLI = %#v, %v; want no attention", usage, err) + } + + appendRollout(t, path, attentionEventLine(now.Add(2*time.Second), "task_complete", nil)+"\n") + usage, err = reader.FetchTokenUsage(context.Background()) + if err != nil || usage.Sessions[0].Attention != SessionAttentionInput { + t.Fatalf("second completed turn = %#v, %v; want input needed", usage, err) + } + release() + usage, err = reader.FetchTokenUsage(context.Background()) + if err != nil || usage.Sessions[0].Attention != SessionAttentionNone { + t.Fatalf("closed CLI = %#v, %v; want no attention", usage, err) + } +} + +func TestSessionAttentionUsesExactDaemonStatusBeforeFallback(t *testing.T) { + tests := []struct { + name string + status sessionRuntimeStatus + want SessionAttention + }{ + {"working", sessionRuntimeWorking, SessionAttentionNone}, + {"input", sessionRuntimeInput, SessionAttentionInput}, + {"approval", sessionRuntimeApproval, SessionAttentionApproval}, + {"idle", sessionRuntimeIdle, SessionAttentionNone}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := sessionAttention(sessionAttentionWorking, true, true, 20*time.Minute, test.status, true) + if got != test.want { + t.Fatalf("attention = %v; want %v", got, test.want) + } + }) + } + if got := sessionAttention(sessionAttentionIdle, true, true, time.Hour, sessionRuntimeIdle, true); got != SessionAttentionNone { + t.Fatalf("exact idle session attention = %v; want none", got) + } +} + +func TestSessionAttentionFallbackChecksOnlyOpenQuietSessions(t *testing.T) { + if got := sessionAttention(sessionAttentionWorking, true, true, fallbackAttentionAfter-time.Second, sessionRuntimeUnknown, false); got != SessionAttentionNone { + t.Fatalf("early quiet session attention = %v; want none", got) + } + if got := sessionAttention(sessionAttentionWorking, true, true, fallbackAttentionAfter, sessionRuntimeUnknown, false); got != SessionAttentionCheck { + t.Fatalf("quiet session attention = %v; want check", got) + } + if got := sessionAttention(sessionAttentionWorking, false, true, time.Hour, sessionRuntimeUnknown, false); got != SessionAttentionNone { + t.Fatalf("closed quiet session attention = %v; want none", got) + } + if got := sessionAttention(sessionAttentionIdle, true, true, 0, sessionRuntimeUnknown, false); got != SessionAttentionInput { + t.Fatalf("durably completed session attention = %v; want input", got) + } +} + +func TestSessionAttentionMergePrefersDefiniteSignals(t *testing.T) { + if got := mergeSessionAttention(SessionAttentionCheck, SessionAttentionInput); got != SessionAttentionInput { + t.Fatalf("input did not replace inferred check: %v", got) + } + if got := mergeSessionAttention(SessionAttentionApproval, SessionAttentionCheck); got != SessionAttentionApproval { + t.Fatalf("inferred check replaced approval: %v", got) + } +} + +func TestLiveUsageReaderUsesPerThreadExactStatuses(t *testing.T) { + home := t.TempDir() + now := time.Now() + for _, threadID := range []string{"working", "approval"} { + path := testRolloutPath(t, home, now, threadID) + writeRollout(t, path, + sessionMetaLine(threadID, `"cli"`, "/work/"+threadID, nil)+"\n"+ + attentionEventLine(now, "task_started", nil)+"\n") + } + reader, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + reader.statusProvider = stubSessionStatusProvider{statuses: map[string]sessionRuntimeStatus{ + "working": sessionRuntimeWorking, "approval": sessionRuntimeApproval, + }} + usage, err := reader.FetchTokenUsage(context.Background()) + if err != nil || len(usage.Sessions) != 2 { + t.Fatalf("exact status fetch = %#v, %v", usage, err) + } + got := make(map[string]SessionAttention) + for _, session := range usage.Sessions { + got[session.ID] = session.Attention + } + if got["working"] != SessionAttentionNone || got["approval"] != SessionAttentionApproval { + t.Fatalf("per-thread exact attention = %#v", got) + } +} + +type stubSessionStatusProvider struct { + statuses map[string]sessionRuntimeStatus +} + +func (s stubSessionStatusProvider) Fetch(context.Context, []string) (map[string]sessionRuntimeStatus, bool) { + return s.statuses, true +} + func TestLiveUsageReaderPropagatesWaitingAgentToRoot(t *testing.T) { home := t.TempDir() now := time.Now() @@ -350,7 +476,7 @@ func TestLiveUsageReaderPropagatesWaitingAgentToRoot(t *testing.T) { if err != nil || len(usage.Sessions) != 1 { t.Fatalf("grouped attention fetch = %#v, %v", usage, err) } - if session := usage.Sessions[0]; session.ID != "attention-root" || session.AgentCount != 1 || !session.AwaitingInput { + if session := usage.Sessions[0]; session.ID != "attention-root" || session.AgentCount != 1 || session.Attention != SessionAttentionApproval { t.Fatalf("waiting child was not propagated to root: %#v", session) } } @@ -372,7 +498,7 @@ func TestLiveUsageReaderKeepsExplicitInputRequestVisibleBeyondRecentActivity(t * t.Fatal(err) } usage, err := reader.FetchTokenUsage(context.Background()) - if err != nil || usage.SessionCount != 1 || len(usage.Sessions) != 1 || !usage.Sessions[0].AwaitingInput { + if err != nil || usage.SessionCount != 1 || len(usage.Sessions) != 1 || usage.Sessions[0].Attention != SessionAttentionInput { t.Fatalf("long-wait attention = %#v, %v; want visible awaiting session", usage, err) } } diff --git a/internal/ui/model.go b/internal/ui/model.go index 2e1f862f..b34d5c6e 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -143,7 +143,7 @@ type monitorSession struct { lastActivity time.Time agentCount int active bool - awaitingInput bool + attention codex.SessionAttention displayed bool unattributed bool samples []monitorSample @@ -1203,7 +1203,7 @@ func (m *Model) startMonitorSessions(usage codex.LiveUsageSnapshot, observedAt t baseline: session.TotalTokens, latest: session.TotalTokens, graphStart: session.TotalTokens, startedAt: observedAt, lastActivity: session.LastActivity, agentCount: session.AgentCount, - active: session.Active, awaitingInput: session.AwaitingInput, + active: session.Active, attention: session.Attention, displayed: session.Active, unattributed: session.Unattributed, callSequence: latestModelCallSequence(session.ModelCalls), turnSequence: latestTurnTimingSequence(session.TurnTimings), @@ -1221,7 +1221,7 @@ func (m *Model) startMonitorSessions(usage codex.LiveUsageSnapshot, observedAt t func (m *Model) syncMonitorSessions(usage codex.LiveUsageSnapshot, observedAt time.Time) { for index := range m.monitorSessionData { m.monitorSessionData[index].active = false - m.monitorSessionData[index].awaitingInput = false + m.monitorSessionData[index].attention = codex.SessionAttentionNone } for _, update := range usage.Sessions { index := m.monitorSessionIndex(update.ID) @@ -1234,7 +1234,7 @@ func (m *Model) syncMonitorSessions(usage codex.LiveUsageSnapshot, observedAt ti id: update.ID, workingDirectory: update.WorkingDirectory, latest: update.TotalTokens, graphStart: 0, startedAt: startedAt, lastActivity: update.LastActivity, agentCount: update.AgentCount, - active: update.Active, awaitingInput: update.AwaitingInput, + active: update.Active, attention: update.Attention, displayed: update.Active || update.TotalTokens > 0 || len(update.ModelCalls) > 0 || len(update.TurnTimings) > 0, unattributed: update.Unattributed, } @@ -1251,7 +1251,7 @@ func (m *Model) syncMonitorSessions(usage codex.LiveUsageSnapshot, observedAt ti session.lastActivity = update.LastActivity session.agentCount = max(session.agentCount, update.AgentCount) session.active = update.Active - session.awaitingInput = update.AwaitingInput + session.attention = update.Attention session.displayed = session.displayed || update.Active || update.TotalTokens > session.baseline || len(update.ModelCalls) > 0 || len(update.TurnTimings) > 0 if update.WorkingDirectory != "" { diff --git a/internal/ui/monitor.go b/internal/ui/monitor.go index 56a07f7b..a493ffc2 100644 --- a/internal/ui/monitor.go +++ b/internal/ui/monitor.go @@ -10,6 +10,8 @@ import ( "github.com/charmbracelet/lipgloss" "github.com/charmbracelet/x/ansi" + + "github.com/merefield/codexometer/internal/codex" ) type monitorRect struct { @@ -261,8 +263,8 @@ func (m Model) renderMonitorSessionMetrics(width, height int, session monitorSes if session.active { status = "ACTIVE" } - if session.awaitingInput { - status = "AWAITING" + if session.attention != codex.SessionAttentionNone { + status = monitorAttentionStatus(session.attention) } innerWidth := max(width-4, 1) memberLabel := "ROOT" @@ -279,9 +281,9 @@ func (m Model) renderMonitorSessionMetrics(width, height int, session monitorSes share := m.monitorSessionShare(total) usageLine := fmt.Sprintf("%s TOKENS // %.0f%% LOCAL", formatTokens(total), share*100) lines := make([]string, 0, bodyRows) - if session.awaitingInput { + if session.attention != codex.SessionAttentionNone { badge := lipgloss.NewStyle().Bold(true).Foreground(colors.background).Background(colors.warning) - lines = append(lines, badge.Render(ansi.Truncate(" ● AWAITING YOU ", innerWidth, ""))) + lines = append(lines, badge.Render(ansi.Truncate(" ● "+monitorAttentionLabel(session.attention)+" ", innerWidth, ""))) } if len(lines) < bodyRows { lines = append(lines, colors.label().Render(ansi.Truncate(usageLine, innerWidth, ""))) @@ -305,16 +307,38 @@ func (m Model) renderMonitorSessionMetrics(width, height int, session monitorSes if !session.lastActivity.IsZero() { appendLine("LAST // " + compactDuration(time.Since(session.lastActivity)) + " AGO") } - if pageLabel != "" && (!session.awaitingInput || len(lines) > 1) { + if pageLabel != "" && (session.attention == codex.SessionAttentionNone || len(lines) > 1) { lines[len(lines)-1] = colors.dimmed().Render(ansi.Truncate(pageLabel+" // PGUP/PGDN", innerWidth, "")) } borderColor := colors.primary - if session.awaitingInput { + if session.attention != codex.SessionAttentionNone { borderColor = colors.warning } return frameSized(width, max(height-2, 1), title, strings.Join(lines, "\n"), borderColor, colors) } +func monitorAttentionLabel(attention codex.SessionAttention) string { + switch attention { + case codex.SessionAttentionApproval: + return "APPROVAL NEEDED" + case codex.SessionAttentionCheck: + return "CHECK SESSION" + default: + return "INPUT NEEDED" + } +} + +func monitorAttentionStatus(attention codex.SessionAttention) string { + switch attention { + case codex.SessionAttentionApproval: + return "APPROVAL" + case codex.SessionAttentionCheck: + return "CHECK" + default: + return "INPUT" + } +} + func formatMonitorCallActivity(session monitorSession, now time.Time) string { last := "--" if !session.lastCallAt.IsZero() { diff --git a/internal/ui/monitor_test.go b/internal/ui/monitor_test.go index 279b39a8..d88f73dc 100644 --- a/internal/ui/monitor_test.go +++ b/internal/ui/monitor_test.go @@ -649,21 +649,33 @@ func TestMonitorRecordingLampPulsesBetweenDarkAndBrightRed(t *testing.T) { } } -func TestMonitorSessionProminentlyHighlightsAwaitingUser(t *testing.T) { +func TestMonitorSessionProminentlyDistinguishesAttentionReason(t *testing.T) { colors := paletteFor(themeHacker) model := Model{monitorState: monitorRunning, monitorStartedAt: time.Now().Add(-time.Minute)} - session := monitorSession{ + base := monitorSession{ id: "019d-attention", workingDirectory: "/work/attention", startedAt: time.Now().Add(-time.Minute), - baseline: 100, latest: 250, active: true, awaitingInput: true, + baseline: 100, latest: 250, active: true, } - output := model.renderMonitorSessionMetrics(42, 10, session, "", colors) - plain := ansi.Strip(output) - if !strings.Contains(plain, "● AWAITING YOU") || !strings.Contains(plain, "AWAITING // ROOT") { - t.Fatalf("awaiting session was not prominently labelled:\n%s", plain) - } - wantBadge := lipgloss.NewStyle().Bold(true).Foreground(colors.background).Background(colors.warning).Render(" ● AWAITING YOU ") - if !strings.Contains(output, wantBadge) { - t.Fatal("awaiting label was not highlighted with the warning treatment") + for _, test := range []struct { + attention codex.SessionAttention + badge string + status string + }{ + {codex.SessionAttentionInput, "INPUT NEEDED", "INPUT // ROOT"}, + {codex.SessionAttentionApproval, "APPROVAL NEEDED", "APPROVAL // ROOT"}, + {codex.SessionAttentionCheck, "CHECK SESSION", "CHECK // ROOT"}, + } { + session := base + session.attention = test.attention + output := model.renderMonitorSessionMetrics(42, 10, session, "", colors) + plain := ansi.Strip(output) + if !strings.Contains(plain, "● "+test.badge) || !strings.Contains(plain, test.status) { + t.Fatalf("attention session was not distinctly labelled:\n%s", plain) + } + wantBadge := lipgloss.NewStyle().Bold(true).Foreground(colors.background).Background(colors.warning).Render(" ● " + test.badge + " ") + if !strings.Contains(output, wantBadge) { + t.Fatalf("%s label was not highlighted with the warning treatment", test.badge) + } } } diff --git a/internal/ui/view.go b/internal/ui/view.go index 2e2235d5..4c05a873 100644 --- a/internal/ui/view.go +++ b/internal/ui/view.go @@ -150,7 +150,10 @@ func (m Model) renderFooter(width int, colors palette) string { left += " // CREDITS AVAILABLE" } } - status := ansi.Truncate(left, width, "") + status := colors.dimmed().Render(ansi.Truncate(left, width, "")) + if m.meterStyle == styleBenchmark { + status = renderBenchmarkPricingFooter(status, width, colors) + } buttons, separator := footerButtonLayoutWithTheme(width, colors.name, m.meterStyle.isQuota()) controls := make([]string, 0, len(buttons)) for _, button := range buttons { @@ -162,7 +165,26 @@ func (m Model) renderFooter(width int, colors palette) string { } theme := colors.dimmed().Render(fmt.Sprintf("THEME // %s", colors.name)) controlRow := joinRight(strings.Join(controls, separator), theme, width) - return colors.dimmed().Render(status) + "\n" + controlRow + return status + "\n" + controlRow +} + +func renderBenchmarkPricingFooter(left string, width int, colors palette) string { + const minimumWidth = 80 + if width < minimumWidth { + return left + } + label := "PRICES RETRIEVED " + codex.BenchmarkPricingRetrievedOn + " // OPENAI.COM" + center := pricingHyperlink(label, colors) + start := (width - lipgloss.Width(center)) / 2 + if lipgloss.Width(left)+2 > start { + return left + } + return left + strings.Repeat(" ", start-lipgloss.Width(left)) + center +} + +func pricingHyperlink(label string, colors palette) string { + styled := colors.dimmed().Underline(true).Render(label) + return ansi.SetHyperlink(codex.BenchmarkPricingSourceURL) + styled + ansi.ResetHyperlink() } func footerButtonAppearance(colors palette, hovered, flashed bool) lipgloss.Style { diff --git a/internal/ui/view_test.go b/internal/ui/view_test.go index 7458b6a4..b7fb12f5 100644 --- a/internal/ui/view_test.go +++ b/internal/ui/view_test.go @@ -158,6 +158,52 @@ func TestFooterShowsAvailableAccountCredits(t *testing.T) { } } +func TestBenchmarkFooterCentersPricingProvenanceOnlyOnBenchmark(t *testing.T) { + colors := paletteFor(themeHacker) + model := Model{nextRefresh: time.Now().Add(time.Minute), meterStyle: styleBenchmark} + raw := model.renderFooter(100, colors) + if !strings.Contains(raw, codex.BenchmarkPricingSourceURL) { + t.Fatalf("benchmark footer does not contain pricing hyperlink: %q", raw) + } + firstLine := strings.Split(ansi.Strip(raw), "\n")[0] + label := "PRICES RETRIEVED " + codex.BenchmarkPricingRetrievedOn + " // OPENAI.COM" + start := strings.Index(firstLine, label) + if start < 0 { + t.Fatalf("benchmark footer does not contain pricing provenance: %q", firstLine) + } + center := start + len(label)/2 + if center < 49 || center > 51 { + t.Fatalf("pricing provenance center = %d, want terminal center 50: %q", center, firstLine) + } + + for _, style := range []meterStyleID{styleBars, styleMonitor} { + model.meterStyle = style + footer := model.renderFooter(100, colors) + if strings.Contains(footer, codex.BenchmarkPricingSourceURL) || strings.Contains(ansi.Strip(footer), codex.BenchmarkPricingRetrievedOn) { + t.Fatalf("pricing provenance leaked into %s footer: %q", style.name(), footer) + } + } +} + +func TestBenchmarkPricingFooterRemainsResponsive(t *testing.T) { + model := Model{nextRefresh: time.Now().Add(time.Minute), meterStyle: styleBenchmark} + for _, width := range []int{12, 24, 40, 60, 79, 80, 100} { + footer := model.renderFooter(width, paletteFor(themeHacker)) + for line, value := range strings.Split(footer, "\n") { + if got := lipgloss.Width(value); got > width { + t.Errorf("width %d line %d rendered at %d: %q", width, line, got, ansi.Strip(value)) + } + } + hasPricing := strings.Contains(footer, codex.BenchmarkPricingSourceURL) + if width < 80 && hasPricing { + t.Errorf("width %d unexpectedly showed pricing provenance", width) + } + if width >= 80 && !hasPricing { + t.Errorf("width %d omitted responsive pricing provenance", width) + } + } +} + func TestFrameTitlesAreIntegratedIntoBorderInsteadOfButtonBrackets(t *testing.T) { colors := paletteFor(themeHacker) output := ansi.Strip(frameSized(36, 3, "SESSION READOUT", "BODY", colors.primary, colors)) diff --git a/main.go b/main.go index 35860b88..9b751d6f 100644 --- a/main.go +++ b/main.go @@ -55,9 +55,9 @@ func (d *demoFetcher) FetchTokenUsage(context.Context) (codex.LiveUsageSnapshot, TotalTokens: d.lifetimeTokens, LastActivity: time.Now(), SessionCount: 2, Sessions: []codex.LiveUsageSession{ {ID: "019d-demo-a1b2c", WorkingDirectory: "/projects/alpha", TotalTokens: alphaTokens, LastActivity: time.Now(), AgentCount: 2, Active: true, - ModelCalls: append([]codex.LiveModelCall(nil), d.alphaCalls...), TurnTimings: append([]codex.LiveTurnTiming(nil), d.alphaTurns...)}, + Attention: codex.SessionAttentionApproval, ModelCalls: append([]codex.LiveModelCall(nil), d.alphaCalls...), TurnTimings: append([]codex.LiveTurnTiming(nil), d.alphaTurns...)}, {ID: "019d-demo-d4e5f", WorkingDirectory: "/projects/bravo", TotalTokens: d.lifetimeTokens - alphaTokens, LastActivity: time.Now(), Active: true, - ModelCalls: append([]codex.LiveModelCall(nil), d.bravoCalls...), TurnTimings: append([]codex.LiveTurnTiming(nil), d.bravoTurns...)}, + Attention: codex.SessionAttentionInput, ModelCalls: append([]codex.LiveModelCall(nil), d.bravoCalls...), TurnTimings: append([]codex.LiveTurnTiming(nil), d.bravoTurns...)}, }, }, nil } From e0cbc38084cf83ab3dc984a86f16c65abc577dc0 Mon Sep 17 00:00:00 2001 From: merefield Date: Thu, 13 Aug 2026 13:17:03 +0100 Subject: [PATCH 3/4] Fix macOS daemon socket test path --- internal/codex/daemon_status_unix_test.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/internal/codex/daemon_status_unix_test.go b/internal/codex/daemon_status_unix_test.go index 023412c1..79c5acc6 100644 --- a/internal/codex/daemon_status_unix_test.go +++ b/internal/codex/daemon_status_unix_test.go @@ -16,7 +16,23 @@ import ( ) func TestDaemonStatusProviderReadsExactThreadStates(t *testing.T) { - socketPath := filepath.Join(t.TempDir(), "app-server.sock") + // Darwin limits Unix-domain socket paths to roughly 104 bytes. Go's + // descriptive t.TempDir path can exceed that before the socket name is + // appended, so reserve a short unique name directly under the system temp + // directory instead. + socketFile, err := os.CreateTemp("", "cxm-*.sock") + if err != nil { + t.Fatal(err) + } + socketPath := socketFile.Name() + if err := socketFile.Close(); err != nil { + t.Fatal(err) + } + if err := os.Remove(socketPath); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Remove(socketPath) }) + listener, err := net.Listen("unix", socketPath) if err != nil { if errors.Is(err, os.ErrPermission) { From 8dc13ee5a138a8e2004d44fb5adbacb5a416159e Mon Sep 17 00:00:00 2001 From: merefield Date: Thu, 13 Aug 2026 13:28:26 +0100 Subject: [PATCH 4/4] Constrain file locking to supported platforms --- internal/codex/filelock_other.go | 11 +++++++++++ internal/codex/filelock_other_test.go | 20 ++++++++++++++++++++ internal/codex/filelock_unix.go | 4 +++- internal/codex/filelock_unix_test.go | 2 +- internal/codex/filelock_windows.go | 2 ++ internal/codex/live_usage.go | 3 +++ 6 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 internal/codex/filelock_other.go create mode 100644 internal/codex/filelock_other_test.go diff --git a/internal/codex/filelock_other.go b/internal/codex/filelock_other.go new file mode 100644 index 00000000..1e57f200 --- /dev/null +++ b/internal/codex/filelock_other.go @@ -0,0 +1,11 @@ +//go:build !unix && !windows + +package codex + +import "errors" + +const fileLockSupported = false + +func fileLockHeld(string) (bool, error) { + return false, errors.ErrUnsupported +} diff --git a/internal/codex/filelock_other_test.go b/internal/codex/filelock_other_test.go new file mode 100644 index 00000000..a4a8770d --- /dev/null +++ b/internal/codex/filelock_other_test.go @@ -0,0 +1,20 @@ +//go:build !unix && !windows + +package codex + +import "testing" + +func holdTestFileLock(t *testing.T, _ string) func() { + t.Helper() + t.Skip("writer-lock probing is unsupported on this platform") + return func() {} +} + +func TestFileLockFallbackReportsUnsupported(t *testing.T) { + if fileLockSupported { + t.Fatal("fallback unexpectedly reports file-lock support") + } + if _, err := fileLockHeld("unused"); err == nil { + t.Fatal("fallback file-lock probe unexpectedly succeeded") + } +} diff --git a/internal/codex/filelock_unix.go b/internal/codex/filelock_unix.go index 4c1d7e6f..e67fef99 100644 --- a/internal/codex/filelock_unix.go +++ b/internal/codex/filelock_unix.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build unix package codex @@ -9,6 +9,8 @@ import ( "golang.org/x/sys/unix" ) +const fileLockSupported = true + func fileLockHeld(path string) (bool, error) { file, err := os.OpenFile(path, os.O_RDWR, 0) if err != nil { diff --git a/internal/codex/filelock_unix_test.go b/internal/codex/filelock_unix_test.go index f82856c4..86628ca6 100644 --- a/internal/codex/filelock_unix_test.go +++ b/internal/codex/filelock_unix_test.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build unix package codex diff --git a/internal/codex/filelock_windows.go b/internal/codex/filelock_windows.go index 79b3616f..78be635a 100644 --- a/internal/codex/filelock_windows.go +++ b/internal/codex/filelock_windows.go @@ -9,6 +9,8 @@ import ( "golang.org/x/sys/windows" ) +const fileLockSupported = true + func fileLockHeld(path string) (bool, error) { file, err := os.OpenFile(path, os.O_RDWR, 0) if err != nil { diff --git a/internal/codex/live_usage.go b/internal/codex/live_usage.go index 7036a6ba..bb934193 100644 --- a/internal/codex/live_usage.go +++ b/internal/codex/live_usage.go @@ -747,6 +747,9 @@ func sessionSourceParent(raw json.RawMessage) (string, bool) { const unattributedSessionID = "unattributed" func (r *LiveUsageReader) liveWriterThreads() (map[string]struct{}, bool) { + if !fileLockSupported { + return nil, false + } entries, err := os.ReadDir(r.WriterLocksRoot) if err != nil { return nil, false