From f2d27b28692a25a61098970ea5fd2a7598081732 Mon Sep 17 00:00:00 2001 From: merefield Date: Wed, 12 Aug 2026 11:22:17 +0100 Subject: [PATCH 1/5] Add per-session Monitor telemetry --- README.md | 65 ++++--- internal/codex/live_usage.go | 272 ++++++++++++++++++++++++++++-- internal/codex/live_usage_test.go | 212 +++++++++++++++++++++++ internal/ui/model.go | 204 +++++++++++++++++++++- internal/ui/monitor.go | 151 ++++++++++++++++- internal/ui/monitor_test.go | 199 +++++++++++++++++++++- internal/ui/view_test.go | 2 +- internal/version/version.go | 2 +- internal/version/version_test.go | 4 +- main.go | 5 + main_test.go | 2 +- 11 files changed, 1059 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index bd6cae80..ff81d9a0 100644 --- a/README.md +++ b/README.md @@ -55,8 +55,9 @@ It works particularly well in: - Available earned reset credits when present. - Online, refreshing, stale-data, and error states. - A countdown to the next automatic refresh. -- An optional Monitor view that measures token activity observed across local - Codex sessions between Go and Stop, with a live 30-second bar chart. +- 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. - 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. @@ -124,17 +125,18 @@ credential-refresh behavior as the installed Codex CLI. Codexometer deliberately does not: -- read or copy Codex token files; +- read or copy Codex credential/token files; - implement a separate OAuth flow; - store access or refresh tokens; - send credentials to another service; - invoke a model merely to discover quota information. The Monitor additionally reads locally persisted Codex rollout files under -`$CODEX_HOME/sessions` (normally `~/.codex/sessions`). It scans only for -`token_count` telemetry records and decodes only their token totals and -timestamps; message text, reasoning, commands, tool results, and credentials are -ignored and never retained by Codexometer. +`$CODEX_HOME/sessions` (normally `~/.codex/sessions`). It decodes `token_count` +totals and timestamps plus the minimum session metadata needed for grouping: +thread ID, parent thread ID, source classification, working directory, and the +inherited-history boundary. Message text, reasoning, commands, tool results, +and credentials are ignored and never retained by Codexometer. If you use a nonstandard Codex executable, pass it explicitly: @@ -157,7 +159,7 @@ codexometer --codex /path/to/codex | `a` | Arm, then confirm, Run Suite (Benchmark view only) | | `[` / `]`, `Left` / `Right` | Select the previous or next challenge in the active suite | | `f` | Show all, passed, or failed benchmark results | -| `Page Up` / `Page Down` | Scroll through Benchmark result pages | +| `Page Up` / `Page Down` | Scroll Monitor session rows or Benchmark result pages | | `q` | Quit | | `Esc` | Quit | | `Ctrl+C` | Quit | @@ -190,11 +192,18 @@ Select a tab with the mouse, `Tab`, or `Shift+Tab`: 2. **Monitor** — establishes a zero baseline across locally active Codex sessions when you press Start. A large readout follows newly appended token telemetry once per second and shows total observed tokens, elapsed time, and - average rate; clickable Start and Stop controls sit beside it. The full-width - plot adds one thin vertical block bar every 30 seconds for tokens observed in - that interval. New bars enter on the right and push older bars left, and the - Y axis automatically expands or contracts to fit the visible samples. Stop performs - an immediate final local read instead of relying on the latest graph sample. + average rate; clickable Start and Stop controls sit beside it. Below, every + independent root session has a metrics box and its own graph. Spawned-agent + descendants with an explicit Codex parent link are recursively aggregated + into the root row and reported as `ROOT + n AGENTS`. All graphs add one thin + vertical block bar on the same 30-second tick, after a fresh boundary read. + A root discovered part-way 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. 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. 3. **Pie** — clockwise-filled circles rendered on a 2×4 sub-cell Braille canvas for clean curves at any size. 4. **Consumption Pace** — a signed horizontal scale comparing elapsed window @@ -248,6 +257,18 @@ 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, +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 +`UNATTRIBUTED // INTERNAL` row. When Codex records inherited child history, the +Monitor honors its ownership boundary so copied parent telemetry is not counted +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. + ### Deterministic benchmark The Benchmark tab discovers the current account's visible models and their @@ -492,9 +513,9 @@ need Go or Codexometer's source dependencies. ## Versioning Codexometer follows semantic versioning; the current source version is -`v0.3.0`. The Git tag is the release source of truth. Go automatically embeds +`v0.4.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.3.0`; direct source builds fall +`go install github.com/merefield/codexometer@v0.4.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: @@ -507,7 +528,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.3.0" . +go build -ldflags="-s -w -X github.com/merefield/codexometer/internal/version.Fallback=0.4.0" . ``` ## How refresh works @@ -526,10 +547,14 @@ data has already been displayed, Codexometer retains the last snapshot and marks it as stale instead of blanking the dashboard. While the Monitor is recording it checks appended local token telemetry once per -second and rolls the observed deltas into 30-second graph buckets. These reads do -not contact OpenAI or invoke a model. Pressing Stop performs one immediate final -local read and forces complete session discovery, including Codex sessions -resumed from older rollout directories. +second, groups explicit agent descendants under their root, and rolls each +root's observed deltas into synchronized graph buckets. A 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. +Pressing Stop performs one immediate final local read and forces complete +session discovery, including Codex sessions resumed from older rollout +directories. ## Troubleshooting diff --git a/internal/codex/live_usage.go b/internal/codex/live_usage.go index 370ac671..bfdfced5 100644 --- a/internal/codex/live_usage.go +++ b/internal/codex/live_usage.go @@ -10,6 +10,7 @@ import ( "io" "os" "path/filepath" + "sort" "strings" "sync" "time" @@ -27,6 +28,20 @@ type LiveUsageSnapshot struct { TotalTokens int64 LastActivity time.Time SessionCount int + Sessions []LiveUsageSession +} + +// LiveUsageSession is one independently started local Codex session. Token +// usage from explicitly linked spawned descendants is folded into the root. +type LiveUsageSession struct { + ID string + WorkingDirectory string + StartedAt time.Time + TotalTokens int64 + LastActivity time.Time + AgentCount int + Active bool + Unattributed bool } // LiveUsageReader incrementally observes token telemetry written by local Codex @@ -45,13 +60,21 @@ type LiveUsageReader struct { } type rolloutCursor struct { - offset int64 - totalTokens int64 - lastModified time.Time + offset int64 + totalTokens int64 + observedTokens int64 + lastModified time.Time + threadID string + parentThreadID string + workingDirectory string + startedAt time.Time + nonRoot bool + subagentHistoryStartOrdinal *uint64 } type rolloutEvent struct { Timestamp time.Time `json:"timestamp"` + Ordinal *uint64 `json:"ordinal"` Type string `json:"type"` Payload struct { Type string `json:"type"` @@ -63,6 +86,31 @@ type rolloutEvent struct { } `json:"payload"` } +type rolloutMetadata struct { + ID string + ParentThreadID string + WorkingDirectory string + StartedAt time.Time + NonRoot bool + SubagentHistoryStartOrdinal *uint64 +} + +type rolloutMetadataEvent struct { + Timestamp time.Time `json:"timestamp"` + Type string `json:"type"` + Payload json.RawMessage `json:"payload"` +} + +type rolloutMetadataPayload struct { + ID string `json:"id"` + Timestamp time.Time `json:"timestamp"` + ParentThreadID string `json:"parent_thread_id"` + WorkingDirectory string `json:"cwd"` + Source json.RawMessage `json:"source"` + ThreadSource string `json:"thread_source"` + SubagentHistoryStartOrdinal *uint64 `json:"subagent_history_start_ordinal"` +} + // DefaultCodexHome follows the same CODEX_HOME convention as the Codex CLI. func DefaultCodexHome() (string, error) { if configured := strings.TrimSpace(os.Getenv("CODEX_HOME")); configured != "" { @@ -146,14 +194,10 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover return LiveUsageSnapshot{}, fmt.Errorf("read local Codex token telemetry: %w", firstReadErr) } - sessions := 0 - for _, cursor := range r.files { - if now.Sub(cursor.lastModified) <= 5*time.Minute { - sessions++ - } - } + sessions, activeSessions := r.sessionSnapshots(now) return LiveUsageSnapshot{ - TotalTokens: r.totalTokens, LastActivity: r.lastActivity, SessionCount: sessions, + TotalTokens: r.totalTokens, LastActivity: r.lastActivity, + SessionCount: activeSessions, Sessions: sessions, }, nil } @@ -230,7 +274,19 @@ func (r *LiveUsageReader) discover(ctx context.Context, now time.Time, full bool } func (r *LiveUsageReader) addFile(path string, info os.FileInfo) error { - cursor := &rolloutCursor{lastModified: info.ModTime()} + metadata, err := readRolloutMetadata(path) + if err != nil { + return err + } + cursor := &rolloutCursor{ + lastModified: info.ModTime(), + threadID: metadata.ID, + parentThreadID: metadata.ParentThreadID, + workingDirectory: metadata.WorkingDirectory, + startedAt: metadata.StartedAt, + nonRoot: metadata.NonRoot, + subagentHistoryStartOrdinal: metadata.SubagentHistoryStartOrdinal, + } if !r.initialized || !rolloutCreatedAfter(path, r.startedAt) { total, err := latestTokenTotal(path) if err != nil { @@ -274,10 +330,18 @@ 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 total, at, ok := tokenTotal(line); ok { + if total, at, ordinal, ok := tokenTotalRecord(line); ok { + if !tokenRecordIsOwned(ordinal, cursor.subagentHistoryStartOrdinal, at, cursor.nonRoot, cursor.startedAt) { + // Legacy child rollouts copy the parent's cumulative token + // events. Preserve the latest inherited value as the child's + // counter baseline without reporting it as new usage. + cursor.totalTokens = total + continue + } if total >= cursor.totalTokens { delta := total - cursor.totalTokens r.totalTokens += delta + cursor.observedTokens += delta if delta > 0 { if at.IsZero() { at = time.Now() @@ -328,7 +392,7 @@ func latestTokenTotal(path string) (int64, error) { firstComplete = 0 } for index := len(lines) - 1; index >= firstComplete; index-- { - if total, _, ok := tokenTotal(lines[index]); ok { + if total, _, _, ok := tokenTotalRecord(lines[index]); ok { return total, nil } } @@ -338,15 +402,191 @@ func latestTokenTotal(path string) (int64, error) { } func tokenTotal(line []byte) (int64, time.Time, bool) { + total, at, _, ok := tokenTotalRecord(line) + return total, at, ok +} + +func tokenTotalRecord(line []byte) (int64, time.Time, *uint64, bool) { if !bytes.Contains(line, []byte("token_count")) { - return 0, time.Time{}, false + return 0, time.Time{}, nil, false } var event rolloutEvent if json.Unmarshal(line, &event) != nil || event.Type != "event_msg" || event.Payload.Type != "token_count" || event.Payload.Info == nil { - return 0, time.Time{}, false + return 0, time.Time{}, nil, false + } + return event.Payload.Info.TotalTokenUsage.TotalTokens, event.Timestamp, event.Ordinal, true +} + +func tokenRecordIsOwned(ordinal, boundary *uint64, at time.Time, nonRoot bool, startedAt time.Time) bool { + if boundary == nil { + return !nonRoot || startedAt.IsZero() || at.IsZero() || !at.Before(startedAt) + } + return ordinal != nil && *ordinal >= *boundary +} + +func readRolloutMetadata(path string) (rolloutMetadata, error) { + file, err := os.Open(path) + if err != nil { + return rolloutMetadata{}, err + } + defer file.Close() + + reader := bufio.NewReader(file) + for record := 0; record < 64; record++ { + line, readErr := reader.ReadBytes('\n') + if bytes.Contains(line, []byte(`"session_meta"`)) { + var event rolloutMetadataEvent + if json.Unmarshal(bytes.TrimSpace(line), &event) == nil && event.Type == "session_meta" { + var payload rolloutMetadataPayload + if json.Unmarshal(event.Payload, &payload) == nil { + parent, nonRoot := sessionSourceParent(payload.Source) + if payload.ParentThreadID != "" { + parent = payload.ParentThreadID + nonRoot = true + } + if payload.ThreadSource == "subagent" { + nonRoot = true + } + return rolloutMetadata{ + ID: payload.ID, ParentThreadID: parent, + WorkingDirectory: payload.WorkingDirectory, NonRoot: nonRoot, + StartedAt: firstNonZeroTime(payload.Timestamp, event.Timestamp), + SubagentHistoryStartOrdinal: payload.SubagentHistoryStartOrdinal, + }, nil + } + } + } + if readErr != nil { + if errors.Is(readErr, io.EOF) { + break + } + return rolloutMetadata{}, readErr + } + } + return rolloutMetadata{}, nil +} + +func sessionSourceParent(raw json.RawMessage) (string, bool) { + if len(raw) == 0 || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { + return "", false + } + var sourceName string + if json.Unmarshal(raw, &sourceName) == nil { + return "", strings.HasPrefix(sourceName, "subagent") || strings.HasPrefix(sourceName, "internal") + } + var source struct { + Subagent json.RawMessage `json:"subagent"` + Internal json.RawMessage `json:"internal"` + } + if json.Unmarshal(raw, &source) != nil { + return "", false + } + if len(source.Subagent) > 0 { + var subagent struct { + ThreadSpawn *struct { + ParentThreadID string `json:"parent_thread_id"` + } `json:"thread_spawn"` + } + if json.Unmarshal(source.Subagent, &subagent) == nil && subagent.ThreadSpawn != nil { + return subagent.ThreadSpawn.ParentThreadID, true + } + return "", true + } + return "", len(source.Internal) > 0 +} + +const unattributedSessionID = "unattributed" + +func (r *LiveUsageReader) sessionSnapshots(now time.Time) ([]LiveUsageSession, int) { + byID := make(map[string]*rolloutCursor, len(r.files)) + for _, cursor := range r.files { + if cursor.threadID != "" { + byID[cursor.threadID] = cursor + } + } + + groups := make(map[string]*LiveUsageSession) + for _, cursor := range r.files { + active := now.Sub(cursor.lastModified) <= 5*time.Minute + if !active && cursor.observedTokens == 0 { + continue + } + rootID, unattributed := rolloutRoot(cursor, byID) + group := groups[rootID] + if group == nil { + group = &LiveUsageSession{ID: rootID, Unattributed: unattributed} + groups[rootID] = group + } + group.TotalTokens += cursor.observedTokens + group.Active = group.Active || active + if cursor.lastModified.After(group.LastActivity) { + group.LastActivity = cursor.lastModified + } + if group.WorkingDirectory == "" { + group.WorkingDirectory = cursor.workingDirectory + } + if group.StartedAt.IsZero() || !cursor.startedAt.IsZero() && cursor.startedAt.Before(group.StartedAt) { + group.StartedAt = cursor.startedAt + } + if cursor.threadID == rootID { + group.WorkingDirectory = cursor.workingDirectory + group.StartedAt = cursor.startedAt + } else if active || cursor.observedTokens > 0 { + group.AgentCount++ + } + } + + sessions := make([]LiveUsageSession, 0, len(groups)) + activeCount := 0 + for _, session := range groups { + if session.Active { + activeCount++ + } + sessions = append(sessions, *session) + } + sort.Slice(sessions, func(i, j int) bool { + if sessions[i].Active != sessions[j].Active { + return sessions[i].Active + } + if !sessions[i].LastActivity.Equal(sessions[j].LastActivity) { + return sessions[i].LastActivity.After(sessions[j].LastActivity) + } + return sessions[i].ID < sessions[j].ID + }) + return sessions, activeCount +} + +func firstNonZeroTime(times ...time.Time) time.Time { + for _, candidate := range times { + if !candidate.IsZero() { + return candidate + } + } + return time.Time{} +} + +func rolloutRoot(cursor *rolloutCursor, byID map[string]*rolloutCursor) (string, bool) { + if cursor.threadID == "" || cursor.nonRoot && cursor.parentThreadID == "" { + return unattributedSessionID, true + } + current := cursor + seen := make(map[string]bool) + for current.parentThreadID != "" { + if seen[current.threadID] { + return unattributedSessionID, true + } + seen[current.threadID] = true + parent := byID[current.parentThreadID] + if parent == nil { + return unattributedSessionID, true + } + current = parent + } + if current.nonRoot || current.threadID == "" { + return unattributedSessionID, true } - return event.Payload.Info.TotalTokenUsage.TotalTokens, event.Timestamp, true + return current.threadID, false } func rolloutCreatedAfter(path string, start time.Time) bool { diff --git a/internal/codex/live_usage_test.go b/internal/codex/live_usage_test.go index c353e24b..050b68eb 100644 --- a/internal/codex/live_usage_test.go +++ b/internal/codex/live_usage_test.go @@ -2,6 +2,7 @@ package codex import ( "context" + "encoding/json" "fmt" "os" "path/filepath" @@ -206,6 +207,191 @@ func TestLiveUsageReaderKeepsNewestActivityAcrossEvents(t *testing.T) { } } +func TestLiveUsageReaderGroupsSpawnedDescendantsUnderIndependentRoots(t *testing.T) { + home := t.TempDir() + now := time.Now() + created := now.Add(-time.Hour) + paths := map[string]string{ + "root-a": testRolloutPath(t, home, created, "root-a"), + "root-b": testRolloutPath(t, home, created, "root-b"), + "child-a": testRolloutPath(t, home, created, "child-a"), + "nested-a": testRolloutPath(t, home, created, "nested-a"), + "review": testRolloutPath(t, home, created, "review"), + } + writeRollout(t, paths["root-a"], sessionMetaLine("root-a", `"cli"`, "/work/alpha", nil)+"\n"+tokenCountLine(created, 100)+"\n") + writeRollout(t, paths["root-b"], sessionMetaLine("root-b", `"cli"`, "/work/bravo", nil)+"\n"+tokenCountLine(created, 200)+"\n") + writeRollout(t, paths["child-a"], sessionMetaLine("child-a", threadSpawnSource("root-a"), "/work/alpha", nil)+"\n"+tokenCountLine(created, 300)+"\n") + writeRollout(t, paths["nested-a"], sessionMetaLine("nested-a", threadSpawnSource("child-a"), "/work/alpha", nil)+"\n"+tokenCountLine(created, 400)+"\n") + writeRollout(t, paths["review"], sessionMetaLine("review", `{"subagent":"review"}`, "/work/alpha", nil)+"\n"+tokenCountLine(created, 500)+"\n") + + reader, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + if _, err := reader.FetchTokenUsage(context.Background()); err != nil { + t.Fatal(err) + } + for path, total := range map[string]int64{ + paths["root-a"]: 150, paths["root-b"]: 230, paths["child-a"]: 325, + paths["nested-a"]: 410, paths["review"]: 505, + } { + appendRollout(t, path, tokenCountLine(now, total)+"\n") + } + + usage, err := reader.FetchTokenUsage(context.Background()) + if err != nil { + t.Fatal(err) + } + if usage.TotalTokens != 120 || usage.SessionCount != 3 { + t.Fatalf("aggregate usage = %#v; want 120 tokens across three logical roots", usage) + } + byID := make(map[string]LiveUsageSession) + for _, session := range usage.Sessions { + byID[session.ID] = session + } + if got := byID["root-a"]; got.TotalTokens != 85 || got.AgentCount != 2 || got.WorkingDirectory != "/work/alpha" || got.Unattributed { + t.Fatalf("root A grouping = %#v; want root plus two descendants and 85 tokens", got) + } + if got := byID["root-b"]; got.TotalTokens != 30 || got.AgentCount != 0 || got.WorkingDirectory != "/work/bravo" { + t.Fatalf("root B grouping = %#v; want independent 30-token root", got) + } + if got := byID[unattributedSessionID]; got.TotalTokens != 5 || !got.Unattributed { + t.Fatalf("unlinked review grouping = %#v; want explicit unattributed bucket", got) + } +} + +func TestLiveUsageReaderSkipsInheritedChildTokenHistory(t *testing.T) { + home := t.TempDir() + now := time.Now() + rootPath := testRolloutPath(t, home, now.Add(-time.Hour), "parent") + writeRollout(t, rootPath, sessionMetaLine("parent", `"cli"`, "/work/root", nil)+"\n"+tokenCountLine(now.Add(-time.Hour), 100)+"\n") + reader, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + if _, err := reader.FetchTokenUsage(context.Background()); err != nil { + t.Fatal(err) + } + + boundary := uint64(3) + childPath := testRolloutPath(t, home, now.Add(2*time.Second), "child-with-prefix") + writeRollout(t, childPath, + sessionMetaLine("child", threadSpawnSource("parent"), "/work/root", &boundary)+"\n"+ + tokenCountLineWithOrdinal(now, 1_000, 1)+"\n"+ + tokenCountLineWithOrdinal(now.Add(time.Second), 1_200, 3)+"\n") + reader.lastDiscovery = time.Time{} + usage, err := reader.FetchTokenUsage(context.Background()) + if err != nil { + t.Fatal(err) + } + if usage.TotalTokens != 200 || len(usage.Sessions) != 1 || usage.Sessions[0].ID != "parent" || usage.Sessions[0].AgentCount != 1 { + t.Fatalf("inherited child history was double counted or detached: %#v", usage) + } +} + +func TestLiveUsageReaderBaselinesAChildThatInitiallyHasOnlyInheritedHistory(t *testing.T) { + home := t.TempDir() + now := time.Now() + rootPath := testRolloutPath(t, home, now.Add(-time.Hour), "parent-before-monitor") + writeRollout(t, rootPath, sessionMetaLine("parent", `"cli"`, "/work/root", nil)+"\n"+tokenCountLine(now.Add(-time.Hour), 1_000)+"\n") + + boundary := uint64(3) + childPath := testRolloutPath(t, home, now.Add(-time.Minute), "child-before-monitor") + writeRollout(t, childPath, + sessionMetaLine("child", threadSpawnSource("parent"), "/work/root", &boundary)+"\n"+ + tokenCountLineWithOrdinal(now.Add(-time.Hour), 1_000, 1)+"\n") + + reader, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + if _, err := reader.FetchTokenUsage(context.Background()); err != nil { + t.Fatal(err) + } + appendRollout(t, childPath, tokenCountLineWithOrdinal(now, 1_200, 3)+"\n") + + usage, err := reader.FetchTokenUsage(context.Background()) + if err != nil { + t.Fatal(err) + } + if usage.TotalTokens != 200 || len(usage.Sessions) != 1 || usage.Sessions[0].ID != "parent" { + t.Fatalf("first owned child record included inherited history: %#v", usage) + } +} + +func TestLiveUsageReaderUsesLegacyInheritedTotalsOnlyAsChildBaseline(t *testing.T) { + home := t.TempDir() + now := time.Now() + rootPath := testRolloutPath(t, home, now.Add(-time.Hour), "legacy-parent") + writeRollout(t, rootPath, sessionMetaLineAt("legacy-parent", `"cli"`, "/work/root", nil, now.Add(-time.Hour))+"\n"+tokenCountLine(now.Add(-time.Hour), 1_000)+"\n") + reader, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + if _, err := reader.FetchTokenUsage(context.Background()); err != nil { + t.Fatal(err) + } + + childPath := testRolloutPath(t, home, now.Add(2*time.Second), "legacy-child") + writeRollout(t, childPath, + sessionMetaLineAt("legacy-child", threadSpawnSource("legacy-parent"), "/work/root", nil, now)+"\n"+ + tokenCountLine(now.Add(-time.Minute), 1_000)+"\n"+ + tokenCountLine(now.Add(time.Second), 1_200)+"\n") + reader.lastDiscovery = time.Time{} + usage, err := reader.FetchTokenUsage(context.Background()) + if err != nil { + t.Fatal(err) + } + if usage.TotalTokens != 200 || len(usage.Sessions) != 1 || usage.Sessions[0].ID != "legacy-parent" { + t.Fatalf("legacy inherited usage was not treated as a baseline: %#v", usage) + } +} + +func TestSessionSourceParentRecognizesCodexSourceShapes(t *testing.T) { + for _, test := range []struct { + name string + source string + wantParent string + wantAgent bool + }{ + {name: "missing", source: "null"}, + {name: "root", source: `"cli"`}, + {name: "legacy agent string", source: `"subagent_review"`, wantAgent: true}, + {name: "spawned", source: threadSpawnSource("parent-id"), wantParent: "parent-id", wantAgent: true}, + {name: "unlinked review", source: `{"subagent":"review"}`, wantAgent: true}, + {name: "internal", source: `{"internal":"memory_consolidation"}`, wantAgent: true}, + {name: "malformed", source: `{not-json`}, + } { + t.Run(test.name, func(t *testing.T) { + parent, agent := sessionSourceParent(json.RawMessage(test.source)) + if parent != test.wantParent || agent != test.wantAgent { + t.Fatalf("sessionSourceParent(%s) = %q, %v; want %q, %v", test.source, parent, agent, test.wantParent, test.wantAgent) + } + }) + } +} + +func TestRolloutRootRejectsOrphanedAndCyclicAgentLineage(t *testing.T) { + root := &rolloutCursor{threadID: "root"} + child := &rolloutCursor{threadID: "child", parentThreadID: "root", nonRoot: true} + index := map[string]*rolloutCursor{"root": root, "child": child} + if id, unattributed := rolloutRoot(child, index); id != "root" || unattributed { + t.Fatalf("linked child resolved to %q, %v; want root", id, unattributed) + } + + orphan := &rolloutCursor{threadID: "orphan", parentThreadID: "missing", nonRoot: true} + if id, unattributed := rolloutRoot(orphan, index); id != unattributedSessionID || !unattributed { + t.Fatalf("orphan resolved to %q, %v; want unattributed", id, unattributed) + } + + cycleA := &rolloutCursor{threadID: "cycle-a", parentThreadID: "cycle-b", nonRoot: true} + cycleB := &rolloutCursor{threadID: "cycle-b", parentThreadID: "cycle-a", nonRoot: true} + cycleIndex := map[string]*rolloutCursor{"cycle-a": cycleA, "cycle-b": cycleB} + if id, unattributed := rolloutRoot(cycleA, cycleIndex); id != unattributedSessionID || !unattributed { + t.Fatalf("cycle resolved to %q, %v; want unattributed", id, unattributed) + } +} + func TestLiveUsageReaderContinuesPastUnreadableCursor(t *testing.T) { home := t.TempDir() now := time.Now() @@ -288,6 +474,32 @@ func tokenCountLine(at time.Time, total int64) string { ) } +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}}}}`, + at.UTC().Format(time.RFC3339Nano), ordinal, total, + ) +} + +func sessionMetaLine(id, source, cwd string, boundary *uint64) string { + return sessionMetaLineAt(id, source, cwd, boundary, time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC)) +} + +func sessionMetaLineAt(id, source, cwd string, boundary *uint64, at time.Time) string { + boundaryJSON := "null" + if boundary != nil { + boundaryJSON = fmt.Sprintf("%d", *boundary) + } + return fmt.Sprintf( + `{"timestamp":%q,"type":"session_meta","payload":{"id":%q,"timestamp":%q,"cwd":%q,"source":%s,"subagent_history_start_ordinal":%s}}`, + at.UTC().Format(time.RFC3339Nano), id, at.UTC().Format(time.RFC3339Nano), cwd, source, boundaryJSON, + ) +} + +func threadSpawnSource(parent string) string { + return fmt.Sprintf(`{"subagent":{"thread_spawn":{"parent_thread_id":%q,"depth":1}}}`, parent) +} + func testRolloutPath(t *testing.T, home string, created time.Time, suffix string) string { t.Helper() directory := filepath.Join(home, "sessions", created.Format("2006"), created.Format("01"), created.Format("02")) diff --git a/internal/ui/model.go b/internal/ui/model.go index ebd0ed16..b6154a20 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -84,9 +84,12 @@ type Model struct { monitorRequest uint64 monitorFetchActive bool monitorNextSample time.Time + monitorBoundaryDue bool monitorGraphStart int64 monitorLastActivity time.Time monitorSessions int + monitorSessionData []monitorSession + monitorScroll int monitorError string } @@ -113,14 +116,31 @@ type monitorFetchKind int const ( monitorFetchStart monitorFetchKind = iota monitorFetchSample + monitorFetchBoundary monitorFetchStop ) type monitorSample struct { at time.Time + duration time.Duration intervalTokens int64 } +type monitorSession struct { + id string + workingDirectory string + baseline int64 + latest int64 + graphStart int64 + startedAt time.Time + lastActivity time.Time + agentCount int + active bool + displayed bool + unattributed bool + samples []monitorSample +} + type monitorFetchedMsg struct { kind monitorFetchKind sequence uint64 @@ -278,11 +298,19 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { m.scrollBenchmarkPage(1) return m, nil } + if m.meterStyle == styleMonitor { + m.scrollMonitorPage(-1) + return m, nil + } case "pgdown": if m.meterStyle == styleBenchmark { m.scrollBenchmarkPage(-1) return m, nil } + if m.meterStyle == styleMonitor { + m.scrollMonitorPage(1) + return m, nil + } case "p": if m.meterStyle == styleMonitor { return m.pressFooterButton(footerButtonMonitorStop) @@ -309,6 +337,16 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { return m, nil } m.benchmarkSortHovered = false + if m.meterStyle == styleMonitor { + switch message.Button { + case tea.MouseButtonWheelUp: + m.scrollMonitorRows(-1) + return m, nil + case tea.MouseButtonWheelDown: + m.scrollMonitorRows(1) + return m, nil + } + } if m.meterStyle == styleBenchmark { switch message.Button { case tea.MouseButtonWheelUp: @@ -340,9 +378,9 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { if m.monitorState == monitorRunning { now := time.Time(message) if !m.monitorNextSample.IsZero() && !now.Before(m.monitorNextSample) { - delta := max(m.monitorLatest-m.monitorGraphStart, int64(0)) - m.monitorSamples = append(m.monitorSamples, monitorSample{at: now, intervalTokens: delta}) - m.monitorGraphStart = m.monitorLatest + if !m.monitorBoundaryDue { + m.monitorBoundaryDue = true + } for !m.monitorNextSample.After(now) { m.monitorNextSample = m.monitorNextSample.Add(monitorSampleInterval) } @@ -350,7 +388,11 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { if !m.monitorFetchActive { m.monitorRequest++ m.monitorFetchActive = true - commands = append(commands, m.monitorFetch(monitorFetchSample, m.monitorRequest)) + kind := monitorFetchSample + if m.monitorBoundaryDue { + kind = monitorFetchBoundary + } + commands = append(commands, m.monitorFetch(kind, m.monitorRequest)) } } return m, tea.Batch(commands...) @@ -363,7 +405,22 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { return m, nil } m.monitorFetchActive = false - return m.applyMonitorFetch(message) + updated, command := m.applyMonitorFetch(message) + m = updated.(Model) + if message.err == nil && message.kind == monitorFetchBoundary && m.monitorState == monitorRunning { + m.captureMonitorSamples(message.at) + m.monitorBoundaryDue = false + } + if m.monitorState == monitorRunning && m.monitorBoundaryDue && !m.monitorFetchActive && message.kind != monitorFetchBoundary { + m.monitorRequest++ + m.monitorFetchActive = true + boundary := m.monitorFetch(monitorFetchBoundary, m.monitorRequest) + if command == nil { + return m, boundary + } + return m, tea.Batch(command, boundary) + } + return m, command case footerButtonFlashExpiredMsg: if message.sequence == m.flashSequence && message.button == m.flashedButton { m.flashedButton = footerButtonNone @@ -473,6 +530,9 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { m.monitorStartedAt = time.Time{} m.monitorStoppedAt = time.Time{} m.monitorSamples = nil + m.monitorSessionData = nil + m.monitorScroll = 0 + m.monitorBoundaryDue = false m.monitorLastActivity = time.Time{} m.monitorSessions = 0 m.monitorError = "" @@ -838,10 +898,11 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd) m.monitorGraphStart = message.usage.TotalTokens m.monitorStartedAt = message.at m.monitorState = monitorRunning - m.monitorSessions = message.usage.SessionCount + m.startMonitorSessions(message.usage, message.at) + m.monitorSessions = m.visibleMonitorSessionCount() m.monitorError = "" m.monitorNextSample = message.at.Add(monitorSampleInterval) - case monitorFetchSample, monitorFetchStop: + case monitorFetchSample, monitorFetchBoundary, monitorFetchStop: if message.usage.TotalTokens < m.monitorLatest { m.monitorError = "local Codex token counter moved backwards" } else { @@ -849,8 +910,9 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd) m.monitorLastActivity = message.usage.LastActivity } m.monitorLatest = message.usage.TotalTokens - m.monitorSessions = message.usage.SessionCount m.monitorError = "" + m.syncMonitorSessions(message.usage, message.at) + m.monitorSessions = m.visibleMonitorSessionCount() } if message.kind == monitorFetchStop { m.monitorState = monitorStopped @@ -860,6 +922,132 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd) return m, nil } +func (m *Model) startMonitorSessions(usage codex.LiveUsageSnapshot, observedAt time.Time) { + m.monitorSessionData = nil + for _, session := range usage.Sessions { + m.monitorSessionData = append(m.monitorSessionData, monitorSession{ + id: session.ID, workingDirectory: session.WorkingDirectory, + 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, + }) + } + if len(m.monitorSessionData) == 0 && usage.SessionCount > 0 { + m.monitorSessionData = append(m.monitorSessionData, monitorSession{ + id: "local", baseline: usage.TotalTokens, latest: usage.TotalTokens, + graphStart: usage.TotalTokens, startedAt: observedAt, lastActivity: usage.LastActivity, + active: true, displayed: true, unattributed: true, + }) + } +} + +func (m *Model) syncMonitorSessions(usage codex.LiveUsageSnapshot, observedAt time.Time) { + for index := range m.monitorSessionData { + m.monitorSessionData[index].active = false + } + for _, update := range usage.Sessions { + index := m.monitorSessionIndex(update.ID) + if index < 0 { + startedAt := observedAt + if sessionStart := update.StartedAt; !sessionStart.IsZero() && sessionStart.After(m.monitorStartedAt) && sessionStart.Before(observedAt) { + startedAt = sessionStart + } + m.monitorSessionData = append(m.monitorSessionData, monitorSession{ + 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, + unattributed: update.Unattributed, + }) + continue + } + session := &m.monitorSessionData[index] + if update.TotalTokens < session.latest { + m.monitorError = "local Codex session token counter moved backwards" + continue + } + session.latest = update.TotalTokens + session.lastActivity = update.LastActivity + session.agentCount = max(session.agentCount, update.AgentCount) + session.active = update.Active + session.displayed = session.displayed || update.Active || update.TotalTokens > session.baseline + if update.WorkingDirectory != "" { + session.workingDirectory = update.WorkingDirectory + } + } + if len(usage.Sessions) == 0 && len(m.monitorSessionData) == 1 && m.monitorSessionData[0].id == "local" { + session := &m.monitorSessionData[0] + session.latest = usage.TotalTokens + session.lastActivity = usage.LastActivity + session.active = usage.SessionCount > 0 + session.displayed = true + } +} + +func (m *Model) captureMonitorSamples(at time.Time) { + if at.IsZero() { + at = time.Now() + } + start := m.monitorStartedAt + if count := len(m.monitorSamples); count > 0 { + start = m.monitorSamples[count-1].at + } + duration := max(at.Sub(start), time.Duration(0)) + delta := max(m.monitorLatest-m.monitorGraphStart, int64(0)) + m.monitorSamples = append(m.monitorSamples, monitorSample{at: at, duration: duration, intervalTokens: delta}) + m.monitorGraphStart = m.monitorLatest + + for index := range m.monitorSessionData { + session := &m.monitorSessionData[index] + if !session.displayed { + continue + } + start := session.startedAt + if count := len(session.samples); count > 0 { + start = session.samples[count-1].at + } + duration := max(at.Sub(start), time.Duration(0)) + delta := max(session.latest-session.graphStart, int64(0)) + session.samples = append(session.samples, monitorSample{at: at, duration: duration, intervalTokens: delta}) + session.graphStart = session.latest + } +} + +func (m *Model) monitorSessionIndex(id string) int { + for index := range m.monitorSessionData { + if m.monitorSessionData[index].id == id { + return index + } + } + return -1 +} + +func (m Model) visibleMonitorSessionCount() int { + count := 0 + for _, session := range m.monitorSessionData { + if session.displayed { + count++ + } + } + return count +} + +func (m Model) monitorPageSize() int { + dashboard := m.dashboardLayout() + layout := layoutMonitorArea(dashboard.contentWidth, dashboard.meterHeight) + return max(layout.graphHeight/3, 1) +} + +func (m *Model) scrollMonitorPage(direction int) { + m.scrollMonitorRows(direction * m.monitorPageSize()) +} + +func (m *Model) scrollMonitorRows(rows int) { + maximum := max(m.visibleMonitorSessionCount()-m.monitorPageSize(), 0) + m.monitorScroll = min(max(m.monitorScroll+rows, 0), maximum) +} + func secondTick() tea.Cmd { return tea.Tick(time.Second, func(now time.Time) tea.Msg { return secondMsg(now) }) } diff --git a/internal/ui/monitor.go b/internal/ui/monitor.go index 89908171..b297ed2b 100644 --- a/internal/ui/monitor.go +++ b/internal/ui/monitor.go @@ -3,6 +3,7 @@ package ui import ( "fmt" "math" + "path/filepath" "strconv" "strings" "time" @@ -44,7 +45,7 @@ func layoutMonitorArea(width, height int) monitorGeometry { width = max(width, 1) height = max(height, 1) gap := 1 - topHeight := min(max(height/3, 6), 10) + topHeight := min(max(height/5, 5), 8) if height < 10 { topHeight = max(height/2, 3) } @@ -88,7 +89,7 @@ func (m Model) renderMonitorArea(width, height int, colors palette) monitorView stopButton := m.renderMonitorButton(layout.buttonWidths[1], layout.topHeight, stopLabel, footerButtonMonitorStop, m.monitorStopEnabled(), colors) controls := lipgloss.JoinHorizontal(lipgloss.Top, goButton, strings.Repeat(" ", layout.gap), stopButton) top := lipgloss.JoinHorizontal(lipgloss.Top, readout, strings.Repeat(" ", layout.gap), controls) - graph := m.renderMonitorGraph(layout.width, layout.graphHeight, colors) + graph := m.renderMonitorSessions(layout.width, layout.graphHeight, colors) view := lipgloss.JoinVertical(lipgloss.Left, top, strings.Repeat("\n", layout.gap-1)+graph) if padding := layout.height - lipgloss.Height(view); padding > 0 { view += strings.Repeat("\n", padding) @@ -154,7 +155,7 @@ func (m Model) renderMonitorReadout(width, height int, colors palette) string { telemetry := fmt.Sprintf("LOCAL SESSIONS %d // LAST %s AGO", m.monitorSessions, last) lines = append(lines, colors.dimmed().Render(ansi.Truncate(telemetry, innerWidth, ""))) } - return frameSized(width, max(height-2, 1), "SESSION READOUT", strings.Join(lines, "\n"), colors.primary, colors) + return frameSized(width, max(height-2, 1), "MONITOR READOUT", strings.Join(lines, "\n"), colors.primary, colors) } func (m Model) renderMonitorButton(width, height int, label string, id footerButtonID, enabled bool, colors palette) string { @@ -183,10 +184,130 @@ func (m Model) renderMonitorButton(width, height int, label string, id footerBut } func (m Model) renderMonitorGraph(width, height int, colors palette) string { + return m.renderMonitorGraphSamples(width, height, m.monitorSamples, "LOCAL TOKEN BARS", colors) +} + +func (m Model) renderMonitorSessions(width, height int, colors palette) string { + visible := make([]monitorSession, 0, len(m.monitorSessionData)) + for _, session := range m.monitorSessionData { + if session.displayed { + visible = append(visible, session) + } + } + if len(visible) == 0 { + return m.renderMonitorGraph(width, height, colors) + } + + // Every row needs a title, body, and bottom border. When the terminal is too + // short, show a scrollable window and report its position. + visibleCount := len(visible) + rowCount := min(visibleCount, max(height/3, 1)) + start := min(max(m.monitorScroll, 0), max(visibleCount-rowCount, 0)) + visible = visible[start : start+rowCount] + pageLabel := "" + if rowCount < visibleCount { + pageLabel = fmt.Sprintf("ROWS %d-%d/%d", start+1, start+rowCount, visibleCount) + } + rowHeights := distributeSpace(max(height-(rowCount-1), rowCount), rowCount) + rows := make([]string, 0, rowCount) + for index, session := range visible { + rowPageLabel := "" + if index == rowCount-1 { + rowPageLabel = pageLabel + } + rows = append(rows, m.renderMonitorSessionRow(width, rowHeights[index], session, rowPageLabel, colors)) + } + view := strings.Join(rows, "\n") + if padding := height - lipgloss.Height(view); padding > 0 { + view += strings.Repeat("\n", padding) + } + return view +} + +func (m Model) renderMonitorSessionRow(width, height int, session monitorSession, pageLabel string, colors palette) string { + const gap = 1 + if width <= gap+1 { + return m.renderMonitorGraphSamples(width, height, session.samples, "TOKENS", colors) + } + available := max(width-gap, 2) + metricsWidth := max(available/3, 1) + graphWidth := max(available-metricsWidth, 1) + metrics := m.renderMonitorSessionMetrics(metricsWidth, height, session, pageLabel, colors) + title := "TOKEN BARS" + graph := m.renderMonitorGraphSamples(graphWidth, height, session.samples, title, colors) + return lipgloss.JoinHorizontal(lipgloss.Top, metrics, strings.Repeat(" ", gap), graph) +} + +func (m Model) renderMonitorSessionMetrics(width, height int, session monitorSession, pageLabel string, colors palette) string { + title := "SESSION // " + shortSessionID(session.id) + if session.workingDirectory != "" { + title = shortSessionID(session.id) + " // " + strings.ToUpper(filepath.Base(session.workingDirectory)) + } + if session.unattributed { + title = "UNATTRIBUTED // INTERNAL" + } + total := max(session.latest-session.baseline, int64(0)) + elapsed := m.monitorSessionElapsed(session, time.Now()) + rate := int64(0) + if elapsed > 0 { + rate = int64(math.Round(float64(total) / elapsed.Minutes())) + } + status := "IDLE" + if session.active { + status = "ACTIVE" + } + innerWidth := max(width-4, 1) + memberLabel := "ROOT" + if session.agentCount > 0 { + memberLabel = fmt.Sprintf("ROOT + %d %s", session.agentCount, plural(session.agentCount, "AGENT", "AGENTS")) + if lipgloss.Width(status+" // "+memberLabel) > innerWidth { + memberLabel = fmt.Sprintf("%d %s", session.agentCount, plural(session.agentCount, "AGENT", "AGENTS")) + } + } + if session.unattributed { + memberLabel = "UNLINKED ACTIVITY" + } + bodyRows := max(height-2, 1) + lines := []string{colors.label().Render(ansi.Truncate(formatTokens(total)+" TOKENS", innerWidth, ""))} + if bodyRows >= 2 { + lines = append(lines, colors.dimmed().Render(ansi.Truncate(status+" // "+memberLabel, innerWidth, ""))) + } + if bodyRows >= 3 { + lines = append(lines, colors.dimmed().Render(ansi.Truncate("RATE "+formatTokens(rate)+"/MIN", innerWidth, ""))) + } + if bodyRows >= 4 && session.workingDirectory != "" { + lines = append(lines, colors.dimmed().Render(ansi.Truncate("DIR // "+filepath.Base(session.workingDirectory), innerWidth, ""))) + } + if bodyRows >= 5 && !session.lastActivity.IsZero() { + lines = append(lines, colors.dimmed().Render(ansi.Truncate("LAST // "+compactDuration(time.Since(session.lastActivity))+" AGO", innerWidth, ""))) + } + if pageLabel != "" { + 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) +} + +func shortSessionID(id string) string { + if id == "" { + return "UNKNOWN" + } + if len(id) <= 5 { + return strings.ToUpper(id) + } + return strings.ToUpper(id[len(id)-5:]) +} + +func plural(count int, singular, plural string) string { + if count == 1 { + return singular + } + return plural +} + +func (m Model) renderMonitorGraphSamples(width, height int, samples []monitorSample, heading string, colors palette) string { innerWidth := max(width-4, 1) plotHeight := max(height-2, 1) const sampleWidth = 2 // one block-wide bar plus one cell of breathing room - samples := m.monitorSamples visibleSamples := max((innerWidth+1)/sampleWidth, 1) if len(samples) > visibleSamples { samples = samples[len(samples)-visibleSamples:] @@ -196,7 +317,12 @@ func (m Model) renderMonitorGraph(width, height int, colors palette) string { maximum = max(maximum, sample.intervalTokens) } yMax := niceTokenCeiling(maximum) - title := fmt.Sprintf("30 SEC LOCAL TOKEN BARS // AUTO 0-%s", formatCompactTokens(yMax)) + span := monitorSampleInterval + if len(samples) > 0 && samples[len(samples)-1].duration > 0 { + span = samples[len(samples)-1].duration + } + spanSeconds := max(int(math.Ceil(span.Seconds())), 1) + title := fmt.Sprintf("%d SEC %s // AUTO 0-%s", spanSeconds, heading, formatCompactTokens(yMax)) canvas := make([][]rune, plotHeight) for row := range canvas { @@ -302,6 +428,21 @@ func (m Model) monitorElapsed(now time.Time) time.Duration { return end.Sub(m.monitorStartedAt) } +func (m Model) monitorSessionElapsed(session monitorSession, now time.Time) time.Duration { + start := session.startedAt + if start.IsZero() { + start = m.monitorStartedAt + } + end := now + if m.monitorState == monitorStopped && !m.monitorStoppedAt.IsZero() { + end = m.monitorStoppedAt + } + if start.IsZero() || end.Before(start) { + return 0 + } + return end.Sub(start) +} + func (m Model) monitorNextLabel() string { if m.monitorState != monitorRunning || m.monitorNextSample.IsZero() { return "--:--" diff --git a/internal/ui/monitor_test.go b/internal/ui/monitor_test.go index 125eaeea..7ad75cda 100644 --- a/internal/ui/monitor_test.go +++ b/internal/ui/monitor_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "math" + "reflect" "strings" "testing" "time" @@ -51,10 +52,16 @@ func TestMonitorGoSampleAndStopLifecycle(t *testing.T) { if model.monitorLatest != 1_250 || len(model.monitorSamples) != 0 { t.Fatalf("live read should update the readout without prematurely adding a graph bucket: %#v", model.monitorSamples) } - model.monitorFetchActive = true - updated, _ = model.Update(secondMsg(startedAt.Add(30 * time.Second))) + updated, command = model.Update(secondMsg(startedAt.Add(30 * time.Second))) + model = updated.(Model) + if command == nil || !model.monitorBoundaryDue || !model.monitorFetchActive { + t.Fatal("sample boundary did not request fresh telemetry") + } + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchBoundary, sequence: model.monitorRequest, + usage: usageWithTokens(1_250), at: startedAt.Add(30*time.Second + 100*time.Millisecond), + }) model = updated.(Model) - model.monitorFetchActive = false if len(model.monitorSamples) != 1 || model.monitorSamples[0].intervalTokens != 250 { t.Fatalf("30-second graph bucket was not recorded: %#v", model.monitorSamples) } @@ -104,6 +111,185 @@ func TestMonitorTickSamplesOnlyWhileRunningAndIgnoresStaleResults(t *testing.T) } } +func TestMonitorTracksRootSessionsAndSamplesEveryGraphOnOneTick(t *testing.T) { + startedAt := time.Unix(1_000, 0) + model := Model{monitorState: monitorStarting, monitorRequest: 1} + started := codex.LiveUsageSnapshot{ + TotalTokens: 300, SessionCount: 2, + Sessions: []codex.LiveUsageSession{ + {ID: "root-alpha-uuid", WorkingDirectory: "/work/alpha", TotalTokens: 100, AgentCount: 2, Active: true}, + {ID: "root-bravo-uuid", WorkingDirectory: "/work/bravo", TotalTokens: 200, Active: true}, + }, + } + updated, _ := model.Update(monitorFetchedMsg{ + kind: monitorFetchStart, sequence: 1, usage: started, at: startedAt, + }) + model = updated.(Model) + if len(model.monitorSessionData) != 2 || model.monitorSessions != 2 { + t.Fatalf("root session baselines were not established: %#v", model.monitorSessionData) + } + + model.monitorRequest++ + usage := codex.LiveUsageSnapshot{ + TotalTokens: 400, SessionCount: 2, + Sessions: []codex.LiveUsageSession{ + {ID: "root-alpha-uuid", WorkingDirectory: "/work/alpha", TotalTokens: 160, AgentCount: 2, Active: true}, + {ID: "root-bravo-uuid", WorkingDirectory: "/work/bravo", TotalTokens: 240, Active: true}, + }, + } + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchSample, sequence: model.monitorRequest, usage: usage, at: startedAt.Add(29 * time.Second), + }) + model = updated.(Model) + updated, command := model.Update(secondMsg(startedAt.Add(30 * time.Second))) + model = updated.(Model) + if command == nil || !model.monitorFetchActive { + t.Fatal("shared graph boundary did not request fresh telemetry") + } + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchBoundary, sequence: model.monitorRequest, usage: usage, at: startedAt.Add(30 * time.Second), + }) + model = updated.(Model) + if len(model.monitorSessionData[0].samples) != 1 || len(model.monitorSessionData[1].samples) != 1 { + t.Fatalf("session graphs were not sampled together: %#v", model.monitorSessionData) + } + if model.monitorSessionData[0].samples[0].intervalTokens != 60 || model.monitorSessionData[1].samples[0].intervalTokens != 40 { + t.Fatalf("per-root sample deltas were not isolated: %#v", model.monitorSessionData) + } +} + +func TestMonitorAddsANewlyDetectedRootWithoutLosingItsFirstUsage(t *testing.T) { + startedAt := time.Unix(2_000, 0) + model := Model{monitorState: monitorStarting, monitorRequest: 1} + updated, _ := model.Update(monitorFetchedMsg{ + kind: monitorFetchStart, sequence: 1, at: startedAt, + usage: codex.LiveUsageSnapshot{TotalTokens: 100, SessionCount: 1, Sessions: []codex.LiveUsageSession{ + {ID: "existing", TotalTokens: 100, Active: true}, + }}, + }) + model = updated.(Model) + model.monitorRequest++ + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchSample, sequence: model.monitorRequest, at: startedAt.Add(time.Second), + usage: codex.LiveUsageSnapshot{TotalTokens: 150, SessionCount: 2, Sessions: []codex.LiveUsageSession{ + {ID: "existing", TotalTokens: 110, Active: true}, + {ID: "new-root", StartedAt: startedAt.Add(500 * time.Millisecond), TotalTokens: 40, Active: true}, + }}, + }) + model = updated.(Model) + index := model.monitorSessionIndex("new-root") + if index < 0 || model.monitorSessionData[index].baseline != 0 || model.monitorSessionData[index].latest != 40 { + t.Fatalf("new root's first observed usage was lost: %#v", model.monitorSessionData) + } + if got := model.monitorSessionElapsed(model.monitorSessionData[index], startedAt.Add(time.Second)); got != 500*time.Millisecond { + t.Fatalf("new root elapsed time = %s; want its own 500ms lifetime", got) + } + model.captureMonitorSamples(startedAt.Add(time.Second)) + if sample := model.monitorSessionData[index].samples[0]; sample.duration != 500*time.Millisecond || sample.intervalTokens != 40 { + t.Fatalf("new root partial first sample = %#v; want 500ms and 40 tokens", sample) + } +} + +func TestMonitorWaitsForAFreshBoundaryReadWhenOrdinaryFetchIsInFlight(t *testing.T) { + startedAt := time.Unix(3_000, 0) + model := Model{ + monitorState: monitorRunning, monitorStartedAt: startedAt, + monitorNextSample: startedAt.Add(30 * time.Second), monitorFetchActive: true, + monitorRequest: 5, + } + updated, _ := model.Update(secondMsg(startedAt.Add(30 * time.Second))) + model = updated.(Model) + if !model.monitorBoundaryDue || len(model.monitorSamples) != 0 { + t.Fatal("boundary was closed from stale telemetry") + } + + updated, command := model.Update(monitorFetchedMsg{ + kind: monitorFetchSample, sequence: 5, usage: usageWithTokens(100), at: startedAt.Add(30*time.Second + time.Millisecond), + }) + model = updated.(Model) + if command == nil || model.monitorRequest != 6 || !model.monitorFetchActive || len(model.monitorSamples) != 0 { + t.Fatal("ordinary result did not trigger a dedicated boundary read") + } + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchBoundary, sequence: 6, usage: usageWithTokens(125), at: startedAt.Add(30*time.Second + 2*time.Millisecond), + }) + model = updated.(Model) + if len(model.monitorSamples) != 1 || model.monitorSamples[0].intervalTokens != 125 || model.monitorBoundaryDue { + t.Fatalf("fresh boundary result did not close the bucket: %#v", model.monitorSamples) + } +} + +func TestMonitorRendersOneMetricsAndGraphPairPerRootSession(t *testing.T) { + model := Model{ + monitorState: monitorRunning, monitorStartedAt: time.Now().Add(-time.Minute), + monitorSessionData: []monitorSession{ + {id: "019d-alpha-a1b2c", workingDirectory: "/work/alpha", latest: 150, agentCount: 2, active: true, displayed: true, samples: []monitorSample{{intervalTokens: 50}}}, + {id: "019d-bravo-d4e5f", workingDirectory: "/work/bravo", latest: 75, active: true, displayed: true, samples: []monitorSample{{intervalTokens: 25}}}, + }, + } + view := ansi.Strip(model.renderMonitorSessions(116, 24, paletteFor(themeHacker))) + for _, want := range []string{"A1B2C // ALPHA", "D4E5F // BRAVO", "ROOT + 2 AGENTS", "DIR // alpha", "DIR // bravo"} { + if !strings.Contains(view, want) { + t.Errorf("per-root monitor view missing %q:\n%s", want, view) + } + } + if strings.Count(view, "30 SEC TOKEN BARS") != 2 { + t.Fatalf("wanted one graph beside each root metrics box:\n%s", view) + } +} + +func TestMonitorSessionRowsStayInsideResponsiveRectangle(t *testing.T) { + sessions := []monitorSession{ + {id: "root-a", active: true, displayed: true, samples: []monitorSample{{intervalTokens: 10}}}, + {id: "root-b", active: true, displayed: true, samples: []monitorSample{{intervalTokens: 20}}}, + {id: "root-c", active: true, displayed: true, samples: []monitorSample{{intervalTokens: 30}}}, + {id: "root-d", active: true, displayed: true, samples: []monitorSample{{intervalTokens: 40}}}, + } + for _, size := range []struct{ width, height int }{{20, 6}, {40, 9}, {80, 12}, {116, 24}} { + model := Model{monitorState: monitorRunning, monitorSessionData: sessions} + view := model.renderMonitorSessions(size.width, size.height, paletteFor(themeHacker)) + if lipgloss.Width(view) > size.width || lipgloss.Height(view) > size.height { + t.Errorf("session rows overflowed %dx%d: got %dx%d\n%s", size.width, size.height, lipgloss.Width(view), lipgloss.Height(view), ansi.Strip(view)) + } + } + model := Model{monitorState: monitorRunning, monitorSessionData: sessions} + firstPage := ansi.Strip(model.renderMonitorSessions(80, 9, paletteFor(themeHacker))) + if !strings.Contains(firstPage, "ROWS 1-3/4") || strings.Contains(firstPage, "OOT-D") { + t.Fatalf("first constrained page did not expose navigation state:\n%s", firstPage) + } + model.monitorScroll = 1 + secondPage := ansi.Strip(model.renderMonitorSessions(80, 9, paletteFor(themeHacker))) + if !strings.Contains(secondPage, "ROWS 2-4/4") || !strings.Contains(secondPage, "OOT-D") || strings.Contains(secondPage, "OOT-A") { + t.Fatalf("scrolled constrained page did not reveal the final root:\n%s", secondPage) + } +} + +func TestMonitorSessionPagesRespondToKeyboardAndMouse(t *testing.T) { + model := Model{ + meterStyle: styleMonitor, width: 84, height: 24, + monitorSessionData: []monitorSession{ + {id: "a", displayed: true}, {id: "b", displayed: true}, + {id: "c", displayed: true}, {id: "d", displayed: true}, + }, + } + wantLastPage := max(model.visibleMonitorSessionCount()-model.monitorPageSize(), 0) + updated, command := model.Update(tea.KeyMsg{Type: tea.KeyPgDown}) + model = updated.(Model) + if command != nil || model.monitorScroll != wantLastPage { + t.Fatalf("Page Down monitor scroll = %d; want %d", model.monitorScroll, wantLastPage) + } + updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyPgUp}) + model = updated.(Model) + if model.monitorScroll != 0 { + t.Fatalf("Page Up monitor scroll = %d; want 0", model.monitorScroll) + } + updated, _ = model.Update(tea.MouseMsg{Button: tea.MouseButtonWheelDown}) + model = updated.(Model) + if model.monitorScroll != 1 { + t.Fatalf("mouse wheel monitor scroll = %d; want 1", model.monitorScroll) + } +} + func TestMonitorSurfacesUnavailableAndFailedFinalUsage(t *testing.T) { model := Model{meterStyle: styleMonitor, monitorState: monitorStarting, monitorRequest: 1} updated, _ := model.Update(monitorFetchedMsg{ @@ -129,7 +315,7 @@ func TestMonitorFetchUsesConfiguredLocalSource(t *testing.T) { want := codex.LiveUsageSnapshot{TotalTokens: 321, SessionCount: 2} model := New(stubLiveFetcher{usage: want}, time.Minute) message := model.monitorFetch(monitorFetchStart, 7)().(monitorFetchedMsg) - if message.err != nil || message.sequence != 7 || message.usage != want { + if message.err != nil || message.sequence != 7 || !reflect.DeepEqual(message.usage, want) { t.Fatalf("live source result = %#v", message) } @@ -164,11 +350,14 @@ func TestMonitorViewIsResponsiveAndGraphAutoScales(t *testing.T) { } output := model.View() plain := ansi.Strip(output) - for _, want := range []string{"SESSION READOUT", "6,250 TOKENS", "ELAPSED", "(S)TART", "STO(P)", "LOCAL TOKEN BARS", "AUTO 0-10K", "█", "░"} { + for _, want := range []string{"MONITOR READOUT", "6,250 TOKENS", "(S)TART", "STO(P)", "LOCAL TOKEN BARS", "AUTO 0-10K", "█", "░"} { if !strings.Contains(plain, want) { t.Errorf("%dx%d monitor missing %q:\n%s", size.width, size.height, want, plain) } } + if size.height >= 40 && !strings.Contains(plain, "ELAPSED") { + t.Errorf("%dx%d monitor omitted elapsed telemetry despite available height", size.width, size.height) + } if lipgloss.Width(output) > size.width || lipgloss.Height(output) > size.height { t.Errorf("monitor overflowed %dx%d: got %dx%d", size.width, size.height, lipgloss.Width(output), lipgloss.Height(output)) } diff --git a/internal/ui/view_test.go b/internal/ui/view_test.go index f19e978b..0d70a8c3 100644 --- a/internal/ui/view_test.go +++ b/internal/ui/view_test.go @@ -31,7 +31,7 @@ func TestViewRendersEveryThemeAndStyleWithinStandardTerminal(t *testing.T) { t.Errorf("style %d name missing from view", style) } if style == styleMonitor { - if !strings.Contains(output, "SESSION READOUT") || !strings.Contains(output, "30 SEC LOCAL TOKEN BARS") { + if !strings.Contains(output, "MONITOR READOUT") || !strings.Contains(output, "30 SEC LOCAL TOKEN BARS") { t.Errorf("monitor components missing for theme %d", theme) } } else if style == styleBenchmark { diff --git a/internal/version/version.go b/internal/version/version.go index 060a2eee..90a8ed31 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.3.0" +var Fallback = "0.4.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 0627a3fd..7a9377f5 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.3.0" { - t.Fatalf("Current() = %q, want 0.3.0", got) + if got != "0.4.0" { + t.Fatalf("Current() = %q, want 0.4.0", got) } } diff --git a/main.go b/main.go index 5bf7e7a6..d572cf08 100644 --- a/main.go +++ b/main.go @@ -33,8 +33,13 @@ func (d *demoFetcher) FetchTokenUsage(context.Context) (codex.LiveUsageSnapshot, } else { d.lifetimeTokens += 1_234 } + alphaTokens := d.lifetimeTokens * 3 / 5 return 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}, + {ID: "019d-demo-d4e5f", WorkingDirectory: "/projects/bravo", TotalTokens: d.lifetimeTokens - alphaTokens, LastActivity: time.Now(), Active: true}, + }, }, nil } diff --git a/main_test.go b/main_test.go index 9315f14a..69a48573 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.3.0\n" || stderr.Len() != 0 { + if code != 0 || stdout.String() != "codexometer v0.4.0\n" || stderr.Len() != 0 { t.Errorf("flag=%s code=%d stdout=%q stderr=%q", flag, code, stdout.String(), stderr.String()) } } From 9d18422a6f0b47754ce00191988b941892ad7acf Mon Sep 17 00:00:00 2001 From: merefield Date: Wed, 12 Aug 2026 11:34:49 +0100 Subject: [PATCH 2/5] Estimate per-session quota impact --- README.md | 14 ++++ internal/ui/model.go | 144 +++++++++++++++++++++++++++++++++++- internal/ui/monitor.go | 87 +++++++++++++++++++--- internal/ui/monitor_test.go | 82 ++++++++++++++++++++ 4 files changed, 316 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index ff81d9a0..4ad5a61d 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,10 @@ Select a tab with the mouse, `Tab`, or `Shift+Tab`: descendants with an explicit Codex parent link are recursively aggregated into the root row and reported as `ROOT + n AGENTS`. All graphs add one thin vertical block bar on the same 30-second tick, after a fresh boundary read. + The companion readout records each account quota window at Start and tracks + its observed change while recording. Every session row shows its exact share + of locally observed tokens and an explicitly labelled estimate of the first + quota window's movement, apportioned by that share. A root discovered part-way 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 @@ -269,6 +273,16 @@ 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. +The Monitor's per-session quota figure is an estimate, not API attribution. +Codex exposes account-level quota percentages and local per-session token +telemetry separately; it does not report which session consumed each percentage +point. Codexometer therefore multiplies the observed account-wide change by a +session's share of locally observed tokens. Model choice, reasoning effort, +cache behavior, and private backend weighting can make equal token counts affect +quota differently. The UI uses percentage points (`PP`), labels the value +`EST`, marks a late or stale baseline as partial, and refuses to calculate +across a detected quota reset. + ### Deterministic benchmark The Benchmark tab discovers the current account's visible models and their diff --git a/internal/ui/model.go b/internal/ui/model.go index b6154a20..5ae5e53d 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -3,6 +3,7 @@ package ui import ( "context" "errors" + "fmt" "strings" "time" @@ -91,6 +92,8 @@ type Model struct { monitorSessionData []monitorSession monitorScroll int monitorError string + monitorQuotaWindows []monitorQuotaWindow + monitorQuotaError string } type fetchedMsg struct { @@ -141,11 +144,23 @@ type monitorSession struct { samples []monitorSample } +type monitorQuotaWindow struct { + key string + label string + baselineUsed int + latestUsed int + latestReset *int64 + resetDetected bool + partial bool +} + type monitorFetchedMsg struct { kind monitorFetchKind sequence uint64 usage codex.LiveUsageSnapshot err error + quota codex.Snapshot + quotaErr error at time.Time } @@ -371,6 +386,12 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { if message.err == nil { m.snapshot = message.snapshot m.lastRefresh = time.Now() + if m.monitorState == monitorRunning || m.monitorState == monitorStopping { + m.syncMonitorQuotaSnapshot(message.snapshot) + m.monitorQuotaError = "" + } + } else if m.monitorState == monitorRunning || m.monitorState == monitorStopping { + m.monitorQuotaError = message.err.Error() } case secondMsg: m.phase++ @@ -536,6 +557,8 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { m.monitorLastActivity = time.Time{} m.monitorSessions = 0 m.monitorError = "" + m.monitorQuotaWindows = nil + m.monitorQuotaError = "" m.monitorRequest++ m.monitorFetchActive = true return m, m.monitorFetch(monitorFetchStart, m.monitorRequest) @@ -858,14 +881,30 @@ const monitorSampleInterval = 30 * time.Second func (m Model) monitorFetch(kind monitorFetchKind, sequence uint64) tea.Cmd { return func() tea.Msg { + quota := m.snapshot + var quotaErr error + fetchQuota := func() { + if m.fetcher == nil { + return + } + if freshQuota, err := m.fetcher.Fetch(context.Background()); err != nil { + quotaErr = err + } else { + quota = freshQuota + } + } if m.usageFetcher == nil { return monitorFetchedMsg{ - kind: kind, sequence: sequence, err: errors.New("local Codex session telemetry unavailable"), at: time.Now(), + kind: kind, sequence: sequence, err: errors.New("local Codex session telemetry unavailable"), + quota: quota, quotaErr: quotaErr, at: time.Now(), } } var usage codex.LiveUsageSnapshot var err error if kind == monitorFetchStop { + // Read account quota first so the final local telemetry read remains + // the end of the measured token interval. + fetchQuota() if freshFetcher, ok := m.usageFetcher.(FreshTokenUsageFetcher); ok { usage, err = freshFetcher.FetchTokenUsageFresh(context.Background()) } else { @@ -874,8 +913,15 @@ func (m Model) monitorFetch(kind monitorFetchKind, sequence uint64) tea.Cmd { } else { usage, err = m.usageFetcher.FetchTokenUsage(context.Background()) } + observedAt := time.Now() + if kind == monitorFetchStart { + // Establish the local baseline immediately, then obtain the quota + // baseline. Activity while the app-server responds is still counted. + fetchQuota() + } return monitorFetchedMsg{ - kind: kind, sequence: sequence, usage: usage, err: err, at: time.Now(), + kind: kind, sequence: sequence, usage: usage, err: err, + quota: quota, quotaErr: quotaErr, at: observedAt, } } } @@ -898,11 +944,22 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd) m.monitorGraphStart = message.usage.TotalTokens m.monitorStartedAt = message.at m.monitorState = monitorRunning + m.startMonitorQuotaSnapshot(message.quota) + if message.quotaErr != nil { + for index := range m.monitorQuotaWindows { + m.monitorQuotaWindows[index].partial = true + } + } + m.applyMonitorQuotaResult(message) m.startMonitorSessions(message.usage, message.at) m.monitorSessions = m.visibleMonitorSessionCount() m.monitorError = "" m.monitorNextSample = message.at.Add(monitorSampleInterval) case monitorFetchSample, monitorFetchBoundary, monitorFetchStop: + if message.kind == monitorFetchStop { + m.syncMonitorQuotaSnapshot(message.quota) + m.applyMonitorQuotaResult(message) + } if message.usage.TotalTokens < m.monitorLatest { m.monitorError = "local Codex token counter moved backwards" } else { @@ -922,6 +979,89 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd) return m, nil } +func (m *Model) applyMonitorQuotaResult(message monitorFetchedMsg) { + if message.quotaErr != nil { + m.monitorQuotaError = message.quotaErr.Error() + return + } + m.monitorQuotaError = "" + if len(message.quota.Meters()) > 0 { + m.snapshot = message.quota + m.lastRefresh = message.at + m.err = nil + } +} + +func (m *Model) startMonitorQuotaSnapshot(snapshot codex.Snapshot) { + m.monitorQuotaWindows = nil + for _, meter := range snapshot.Meters() { + reset := cloneInt64(meter.Window.ResetsAt) + m.monitorQuotaWindows = append(m.monitorQuotaWindows, monitorQuotaWindow{ + key: monitorQuotaKey(meter), label: monitorQuotaLabel(meter), + baselineUsed: meter.Window.UsedPercent, latestUsed: meter.Window.UsedPercent, + latestReset: reset, + }) + } +} + +func (m *Model) syncMonitorQuotaSnapshot(snapshot codex.Snapshot) { + for _, meter := range snapshot.Meters() { + key := monitorQuotaKey(meter) + index := -1 + for candidate := range m.monitorQuotaWindows { + if m.monitorQuotaWindows[candidate].key == key { + index = candidate + break + } + } + if index < 0 { + m.monitorQuotaWindows = append(m.monitorQuotaWindows, monitorQuotaWindow{ + key: key, label: monitorQuotaLabel(meter), + baselineUsed: meter.Window.UsedPercent, latestUsed: meter.Window.UsedPercent, + latestReset: cloneInt64(meter.Window.ResetsAt), + partial: true, + }) + continue + } + window := &m.monitorQuotaWindows[index] + if !sameOptionalInt64(window.latestReset, meter.Window.ResetsAt) || meter.Window.UsedPercent < window.latestUsed { + window.resetDetected = true + } + window.latestUsed = meter.Window.UsedPercent + window.latestReset = cloneInt64(meter.Window.ResetsAt) + } +} + +func monitorQuotaKey(meter codex.Meter) string { + duration := int64(-1) + if meter.Window.WindowDurationMins != nil { + duration = *meter.Window.WindowDurationMins + } + return meter.Bucket + "\x00" + meter.Name + "\x00" + fmt.Sprint(duration) +} + +func monitorQuotaLabel(meter codex.Meter) string { + if meter.Bucket == "codex" { + return meter.Name + } + return codex.DisplayName(meter.Bucket) + " " + meter.Name +} + +func cloneInt64(value *int64) *int64 { + if value == nil { + return nil + } + copy := *value + return © +} + +func sameOptionalInt64(left, right *int64) bool { + if left == nil || right == nil { + return left == nil && right == nil + } + return *left == *right +} + func (m *Model) startMonitorSessions(usage codex.LiveUsageSnapshot, observedAt time.Time) { m.monitorSessionData = nil for _, session := range usage.Sessions { diff --git a/internal/ui/monitor.go b/internal/ui/monitor.go index b297ed2b..c3e4a5e4 100644 --- a/internal/ui/monitor.go +++ b/internal/ui/monitor.go @@ -143,6 +143,11 @@ func (m Model) renderMonitorReadout(width, height int, colors palette) string { if height >= 6 { lines = append(lines, colors.label().Render(ansi.Truncate(fmt.Sprintf("ELAPSED %s // RATE %s/MIN", formatElapsed(elapsed), formatTokens(rate)), innerWidth, ""))) } + if height >= 5 { + if quota := m.monitorQuotaReadout(); quota != "" { + lines = append(lines, colors.dimmed().Render(ansi.Truncate(quota, innerWidth, ""))) + } + } if height >= 8 && !m.monitorStartedAt.IsZero() { lines = append(lines, colors.dimmed().Render(ansi.Truncate(fmt.Sprintf("START %s // NOW %s", formatTokens(m.monitorBaseline), formatTokens(m.monitorLatest)), innerWidth, ""))) } @@ -268,18 +273,24 @@ func (m Model) renderMonitorSessionMetrics(width, height int, session monitorSes memberLabel = "UNLINKED ACTIVITY" } bodyRows := max(height-2, 1) - lines := []string{colors.label().Render(ansi.Truncate(formatTokens(total)+" TOKENS", innerWidth, ""))} - if bodyRows >= 2 { - lines = append(lines, colors.dimmed().Render(ansi.Truncate(status+" // "+memberLabel, innerWidth, ""))) + share := m.monitorSessionShare(total) + usageLine := fmt.Sprintf("%s TOKENS // %.0f%% LOCAL", formatTokens(total), share*100) + lines := []string{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, ""))) + } } - if bodyRows >= 3 { - lines = append(lines, colors.dimmed().Render(ansi.Truncate("RATE "+formatTokens(rate)+"/MIN", innerWidth, ""))) + if estimate := m.monitorSessionQuotaEstimate(share); estimate != "" { + appendLine(estimate) } - if bodyRows >= 4 && session.workingDirectory != "" { - lines = append(lines, colors.dimmed().Render(ansi.Truncate("DIR // "+filepath.Base(session.workingDirectory), innerWidth, ""))) + appendLine(status + " // " + memberLabel) + appendLine("RATE " + formatTokens(rate) + "/MIN") + if session.workingDirectory != "" { + appendLine("DIR // " + filepath.Base(session.workingDirectory)) } - if bodyRows >= 5 && !session.lastActivity.IsZero() { - lines = append(lines, colors.dimmed().Render(ansi.Truncate("LAST // "+compactDuration(time.Since(session.lastActivity))+" AGO", innerWidth, ""))) + if !session.lastActivity.IsZero() { + appendLine("LAST // " + compactDuration(time.Since(session.lastActivity)) + " AGO") } if pageLabel != "" { lines[len(lines)-1] = colors.dimmed().Render(ansi.Truncate(pageLabel+" // PGUP/PGDN", innerWidth, "")) @@ -287,6 +298,64 @@ func (m Model) renderMonitorSessionMetrics(width, height int, session monitorSes return frameSized(width, max(height-2, 1), title, strings.Join(lines, "\n"), colors.primary, colors) } +func (m Model) monitorRecordedTokens() int64 { + if m.monitorStartedAt.IsZero() || m.monitorLatest < m.monitorBaseline { + return 0 + } + return m.monitorLatest - m.monitorBaseline +} + +func (m Model) monitorSessionShare(tokens int64) float64 { + total := m.monitorRecordedTokens() + if total <= 0 || tokens <= 0 { + return 0 + } + return min(float64(tokens)/float64(total), 1) +} + +func (m Model) monitorQuotaReadout() string { + if m.monitorStartedAt.IsZero() { + return "" + } + if len(m.monitorQuotaWindows) == 0 { + if m.monitorQuotaError != "" { + return "QUOTA USED Δ // UNAVAILABLE" + } + return "QUOTA USED Δ // NO WINDOWS" + } + parts := []string{"QUOTA USED Δ"} + for _, window := range m.monitorQuotaWindows { + value := "RESET" + if !window.resetDetected { + value = fmt.Sprintf("%+dPP", window.latestUsed-window.baselineUsed) + if window.partial { + value += " PARTIAL" + } + } + parts = append(parts, window.label+" "+value) + } + if m.monitorQuotaError != "" { + parts = append(parts, "STALE") + } + return strings.Join(parts, " // ") +} + +func (m Model) monitorSessionQuotaEstimate(share float64) string { + if len(m.monitorQuotaWindows) == 0 { + return "" + } + window := m.monitorQuotaWindows[0] + if window.resetDetected { + return "EST QUOTA // RESET DURING RUN" + } + delta := float64(window.latestUsed-window.baselineUsed) * share + label := window.label + if window.partial { + return "EST " + label + " // PARTIAL" + } + return fmt.Sprintf("EST %s USED %+0.1fPP", label, delta) +} + func shortSessionID(id string) string { if id == "" { return "UNKNOWN" diff --git a/internal/ui/monitor_test.go b/internal/ui/monitor_test.go index 7ad75cda..85910c1d 100644 --- a/internal/ui/monitor_test.go +++ b/internal/ui/monitor_test.go @@ -158,6 +158,81 @@ func TestMonitorTracksRootSessionsAndSamplesEveryGraphOnOneTick(t *testing.T) { } } +func TestMonitorAttributesObservedQuotaMovementByLocalTokenShare(t *testing.T) { + startedAt := time.Unix(1_500, 0) + reset := startedAt.Add(time.Hour).Unix() + model := Model{monitorState: monitorStarting, monitorRequest: 1} + updated, _ := model.Update(monitorFetchedMsg{ + kind: monitorFetchStart, sequence: 1, at: startedAt, + quota: monitorQuotaSnapshot(20, reset), + usage: codex.LiveUsageSnapshot{TotalTokens: 300, SessionCount: 2, Sessions: []codex.LiveUsageSession{ + {ID: "alpha", TotalTokens: 100, Active: true}, + {ID: "bravo", TotalTokens: 200, Active: true}, + }}, + }) + model = updated.(Model) + model.monitorRequest++ + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchSample, sequence: model.monitorRequest, at: startedAt.Add(time.Minute), + usage: codex.LiveUsageSnapshot{TotalTokens: 400, SessionCount: 2, Sessions: []codex.LiveUsageSession{ + {ID: "alpha", TotalTokens: 160, Active: true}, + {ID: "bravo", TotalTokens: 240, Active: true}, + }}, + }) + model = updated.(Model) + updated, _ = model.Update(fetchedMsg{snapshot: monitorQuotaSnapshot(23, reset)}) + model = updated.(Model) + + if got := model.monitorQuotaReadout(); got != "QUOTA USED Δ // 5 HOURS +3PP" { + t.Fatalf("quota companion readout = %q", got) + } + alpha := model.monitorSessionData[model.monitorSessionIndex("alpha")] + bravo := model.monitorSessionData[model.monitorSessionIndex("bravo")] + alphaView := ansi.Strip(model.renderMonitorSessionMetrics(52, 8, alpha, "", paletteFor(themeHacker))) + bravoView := ansi.Strip(model.renderMonitorSessionMetrics(52, 8, bravo, "", paletteFor(themeHacker))) + for view, wants := range map[string][]string{ + alphaView: {"60 TOKENS // 60% LOCAL", "EST 5 HOURS USED +1.8PP"}, + bravoView: {"40 TOKENS // 40% LOCAL", "EST 5 HOURS USED +1.2PP"}, + } { + for _, want := range wants { + if !strings.Contains(view, want) { + t.Errorf("session estimate missing %q:\n%s", want, view) + } + } + } +} + +func TestMonitorDoesNotEstimateAcrossAQuotaReset(t *testing.T) { + startedAt := time.Unix(1_700, 0) + model := Model{monitorState: monitorStarting, monitorRequest: 1} + updated, _ := model.Update(monitorFetchedMsg{ + kind: monitorFetchStart, sequence: 1, at: startedAt, + quota: monitorQuotaSnapshot(80, startedAt.Add(time.Minute).Unix()), + usage: codex.LiveUsageSnapshot{TotalTokens: 100, SessionCount: 1, Sessions: []codex.LiveUsageSession{ + {ID: "alpha", TotalTokens: 100, Active: true}, + }}, + }) + model = updated.(Model) + model.monitorRequest++ + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchSample, sequence: model.monitorRequest, at: startedAt.Add(2 * time.Minute), + usage: codex.LiveUsageSnapshot{TotalTokens: 150, SessionCount: 1, Sessions: []codex.LiveUsageSession{ + {ID: "alpha", TotalTokens: 150, Active: true}, + }}, + }) + model = updated.(Model) + updated, _ = model.Update(fetchedMsg{snapshot: monitorQuotaSnapshot(2, startedAt.Add(6*time.Hour).Unix())}) + model = updated.(Model) + + if got := model.monitorQuotaReadout(); !strings.Contains(got, "5 HOURS RESET") { + t.Fatalf("resetting quota readout = %q", got) + } + estimate := model.monitorSessionQuotaEstimate(1) + if estimate != "EST QUOTA // RESET DURING RUN" { + t.Fatalf("reset-crossing estimate = %q", estimate) + } +} + func TestMonitorAddsANewlyDetectedRootWithoutLosingItsFirstUsage(t *testing.T) { startedAt := time.Unix(2_000, 0) model := Model{monitorState: monitorStarting, monitorRequest: 1} @@ -552,6 +627,13 @@ func usageWithTokens(tokens int64) codex.LiveUsageSnapshot { return codex.LiveUsageSnapshot{TotalTokens: tokens, LastActivity: time.Now(), SessionCount: 1} } +func monitorQuotaSnapshot(used int, reset int64) codex.Snapshot { + duration := int64(300) + return codex.Snapshot{RateLimits: codex.RateLimitSnapshot{ + Primary: &codex.Window{UsedPercent: used, WindowDurationMins: &duration, ResetsAt: &reset}, + }} +} + func graphRightmostBar(graph string) int { rightmost := -1 for index, char := range []rune(graphBarLine(graph)) { From b19559b54cdad9b18c5d3604e1652ca054bd3c16 Mon Sep 17 00:00:00 2001 From: merefield Date: Wed, 12 Aug 2026 11:49:44 +0100 Subject: [PATCH 3/5] Harden quota impact estimates --- README.md | 27 ++++++++--- internal/ui/model.go | 43 +++++++++++----- internal/ui/monitor.go | 52 +++++++++++++++----- internal/ui/monitor_test.go | 97 +++++++++++++++++++++++++++++++++++-- 4 files changed, 183 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 4ad5a61d..1508ce63 100644 --- a/README.md +++ b/README.md @@ -199,8 +199,8 @@ Select a tab with the mouse, `Tab`, or `Shift+Tab`: vertical block bar on the same 30-second tick, after a fresh boundary read. The companion readout records each account quota window at Start and tracks its observed change while recording. Every session row shows its exact share - of locally observed tokens and an explicitly labelled estimate of the first - quota window's movement, apportioned by that share. + of locally observed tokens and an explicitly labelled, local-only estimate + of the first quota window's movement, apportioned by that share. A root discovered part-way 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 @@ -277,11 +277,24 @@ The Monitor's per-session quota figure is an estimate, not API attribution. Codex exposes account-level quota percentages and local per-session token telemetry separately; it does not report which session consumed each percentage point. Codexometer therefore multiplies the observed account-wide change by a -session's share of locally observed tokens. Model choice, reasoning effort, -cache behavior, and private backend weighting can make equal token counts affect -quota differently. The UI uses percentage points (`PP`), labels the value -`EST`, marks a late or stale baseline as partial, and refuses to calculate -across a detected quota reset. +session's share of locally observed tokens. This assumes that no activity from +another computer, cloud session, different `CODEX_HOME`, or otherwise invisible +client changes the account quota during the recording; if it does, its movement +cannot be separated and will contaminate the estimate. Model choice, reasoning +effort, cache behavior, and private backend weighting can also make equal token +counts affect quota differently. + +The UI calls this `EST LOCAL-ONLY`, uses percentage points (`PP`), and never +presents finer precision than the whole-number quota percentage returned by +Codex. `NO INTEGER Δ` means no whole-point movement was observed, not necessarily +zero consumption; a smaller apportioned estimate is shown as `<1PP`. Stale, +missing, late-baseline, and reset-crossing windows do not produce a per-session +number. +Start reads quota before establishing the local token baseline, while Stop reads +local tokens before the final quota snapshot, so the account observation +brackets the local interval. These operations are not atomic, so unrelated +account activity during either short boundary read remains another source of +uncertainty. ### Deterministic benchmark diff --git a/internal/ui/model.go b/internal/ui/model.go index 5ae5e53d..590cf194 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -152,6 +152,7 @@ type monitorQuotaWindow struct { latestReset *int64 resetDetected bool partial bool + stale bool } type monitorFetchedMsg struct { @@ -901,24 +902,27 @@ func (m Model) monitorFetch(kind monitorFetchKind, sequence uint64) tea.Cmd { } var usage codex.LiveUsageSnapshot var err error - if kind == monitorFetchStop { - // Read account quota first so the final local telemetry read remains - // the end of the measured token interval. + if kind == monitorFetchStart { + // Bracket the measured local-token interval inside the account-quota + // interval: quota first at Start, local telemetry first at Stop. fetchQuota() + usage, err = m.usageFetcher.FetchTokenUsage(context.Background()) + } else if kind == monitorFetchStop { if freshFetcher, ok := m.usageFetcher.(FreshTokenUsageFetcher); ok { usage, err = freshFetcher.FetchTokenUsageFresh(context.Background()) } else { usage, err = m.usageFetcher.FetchTokenUsage(context.Background()) } + observedAt := time.Now() + fetchQuota() + return monitorFetchedMsg{ + kind: kind, sequence: sequence, usage: usage, err: err, + quota: quota, quotaErr: quotaErr, at: observedAt, + } } else { usage, err = m.usageFetcher.FetchTokenUsage(context.Background()) } observedAt := time.Now() - if kind == monitorFetchStart { - // Establish the local baseline immediately, then obtain the quota - // baseline. Activity while the app-server responds is still counted. - fetchQuota() - } return monitorFetchedMsg{ kind: kind, sequence: sequence, usage: usage, err: err, quota: quota, quotaErr: quotaErr, at: observedAt, @@ -927,6 +931,12 @@ func (m Model) monitorFetch(kind monitorFetchKind, sequence uint64) tea.Cmd { } func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd) { + if message.kind == monitorFetchStop { + if message.quotaErr == nil { + m.syncMonitorQuotaSnapshot(message.quota) + } + m.applyMonitorQuotaResult(message) + } if message.err != nil { m.monitorError = message.err.Error() if message.kind == monitorFetchStop { @@ -956,10 +966,6 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd) m.monitorError = "" m.monitorNextSample = message.at.Add(monitorSampleInterval) case monitorFetchSample, monitorFetchBoundary, monitorFetchStop: - if message.kind == monitorFetchStop { - m.syncMonitorQuotaSnapshot(message.quota) - m.applyMonitorQuotaResult(message) - } if message.usage.TotalTokens < m.monitorLatest { m.monitorError = "local Codex token counter moved backwards" } else { @@ -987,7 +993,10 @@ func (m *Model) applyMonitorQuotaResult(message monitorFetchedMsg) { m.monitorQuotaError = "" if len(message.quota.Meters()) > 0 { m.snapshot = message.quota - m.lastRefresh = message.at + m.lastRefresh = message.quota.FetchedAt + if m.lastRefresh.IsZero() { + m.lastRefresh = message.at + } m.err = nil } } @@ -1005,8 +1014,10 @@ func (m *Model) startMonitorQuotaSnapshot(snapshot codex.Snapshot) { } func (m *Model) syncMonitorQuotaSnapshot(snapshot codex.Snapshot) { + seen := make(map[string]bool) for _, meter := range snapshot.Meters() { key := monitorQuotaKey(meter) + seen[key] = true index := -1 for candidate := range m.monitorQuotaWindows { if m.monitorQuotaWindows[candidate].key == key { @@ -1029,6 +1040,12 @@ func (m *Model) syncMonitorQuotaSnapshot(snapshot codex.Snapshot) { } window.latestUsed = meter.Window.UsedPercent window.latestReset = cloneInt64(meter.Window.ResetsAt) + window.stale = false + } + for index := range m.monitorQuotaWindows { + if !seen[m.monitorQuotaWindows[index].key] { + m.monitorQuotaWindows[index].stale = true + } } } diff --git a/internal/ui/monitor.go b/internal/ui/monitor.go index c3e4a5e4..826d2faf 100644 --- a/internal/ui/monitor.go +++ b/internal/ui/monitor.go @@ -319,14 +319,16 @@ func (m Model) monitorQuotaReadout() string { } if len(m.monitorQuotaWindows) == 0 { if m.monitorQuotaError != "" { - return "QUOTA USED Δ // UNAVAILABLE" + return "ACCOUNT QUOTA Δ // UNAVAILABLE" } - return "QUOTA USED Δ // NO WINDOWS" + return "ACCOUNT QUOTA Δ // NO WINDOWS" } - parts := []string{"QUOTA USED Δ"} + parts := []string{"ACCOUNT QUOTA Δ"} for _, window := range m.monitorQuotaWindows { value := "RESET" - if !window.resetDetected { + if m.monitorQuotaError != "" || window.stale { + value = "STALE" + } else if !window.resetDetected { value = fmt.Sprintf("%+dPP", window.latestUsed-window.baselineUsed) if window.partial { value += " PARTIAL" @@ -334,9 +336,6 @@ func (m Model) monitorQuotaReadout() string { } parts = append(parts, window.label+" "+value) } - if m.monitorQuotaError != "" { - parts = append(parts, "STALE") - } return strings.Join(parts, " // ") } @@ -345,15 +344,44 @@ func (m Model) monitorSessionQuotaEstimate(share float64) string { return "" } window := m.monitorQuotaWindows[0] + prefix := "EST LOCAL-ONLY " + compactMonitorQuotaLabel(window.label) + if m.monitorError != "" { + return prefix + " // LOCAL STALE" + } + if m.monitorQuotaError != "" || window.stale { + return prefix + " // STALE" + } if window.resetDetected { - return "EST QUOTA // RESET DURING RUN" + return prefix + " // RESET" } - delta := float64(window.latestUsed-window.baselineUsed) * share - label := window.label if window.partial { - return "EST " + label + " // PARTIAL" + return prefix + " // PARTIAL" + } + delta := window.latestUsed - window.baselineUsed + if delta == 0 { + return prefix + " // NO INTEGER Δ" + } + estimate := float64(delta) * share + switch { + case estimate == 0: + return prefix + " 0PP" + case estimate < 1: + return prefix + " <1PP" + default: + return fmt.Sprintf("%s ~%.0fPP", prefix, math.Round(estimate)) + } +} + +func compactMonitorQuotaLabel(label string) string { + for _, unit := range []struct{ suffix, compact string }{ + {" MINUTES", "M"}, {" MINUTE", "M"}, {" HOURS", "H"}, {" HOUR", "H"}, + {" DAYS", "D"}, {" DAY", "D"}, {" WEEKS", "W"}, {" WEEK", "W"}, + } { + if strings.HasSuffix(label, unit.suffix) { + return strings.TrimSuffix(label, unit.suffix) + unit.compact + } } - return fmt.Sprintf("EST %s USED %+0.1fPP", label, delta) + return label } func shortSessionID(id string) string { diff --git a/internal/ui/monitor_test.go b/internal/ui/monitor_test.go index 85910c1d..237803f2 100644 --- a/internal/ui/monitor_test.go +++ b/internal/ui/monitor_test.go @@ -183,7 +183,7 @@ func TestMonitorAttributesObservedQuotaMovementByLocalTokenShare(t *testing.T) { updated, _ = model.Update(fetchedMsg{snapshot: monitorQuotaSnapshot(23, reset)}) model = updated.(Model) - if got := model.monitorQuotaReadout(); got != "QUOTA USED Δ // 5 HOURS +3PP" { + if got := model.monitorQuotaReadout(); got != "ACCOUNT QUOTA Δ // 5 HOURS +3PP" { t.Fatalf("quota companion readout = %q", got) } alpha := model.monitorSessionData[model.monitorSessionIndex("alpha")] @@ -191,8 +191,8 @@ func TestMonitorAttributesObservedQuotaMovementByLocalTokenShare(t *testing.T) { alphaView := ansi.Strip(model.renderMonitorSessionMetrics(52, 8, alpha, "", paletteFor(themeHacker))) bravoView := ansi.Strip(model.renderMonitorSessionMetrics(52, 8, bravo, "", paletteFor(themeHacker))) for view, wants := range map[string][]string{ - alphaView: {"60 TOKENS // 60% LOCAL", "EST 5 HOURS USED +1.8PP"}, - bravoView: {"40 TOKENS // 40% LOCAL", "EST 5 HOURS USED +1.2PP"}, + alphaView: {"60 TOKENS // 60% LOCAL", "EST LOCAL-ONLY 5H ~2PP"}, + bravoView: {"40 TOKENS // 40% LOCAL", "EST LOCAL-ONLY 5H ~1PP"}, } { for _, want := range wants { if !strings.Contains(view, want) { @@ -200,6 +200,14 @@ func TestMonitorAttributesObservedQuotaMovementByLocalTokenShare(t *testing.T) { } } } + model.monitorQuotaWindows[0].latestUsed = 21 + if got := model.monitorSessionQuotaEstimate(0.4); got != "EST LOCAL-ONLY 5H <1PP" { + t.Fatalf("sub-point estimate = %q", got) + } + model.monitorQuotaWindows[0].latestUsed = 20 + if got := model.monitorSessionQuotaEstimate(0.4); got != "EST LOCAL-ONLY 5H // NO INTEGER Δ" { + t.Fatalf("zero integer movement = %q", got) + } } func TestMonitorDoesNotEstimateAcrossAQuotaReset(t *testing.T) { @@ -228,11 +236,71 @@ func TestMonitorDoesNotEstimateAcrossAQuotaReset(t *testing.T) { t.Fatalf("resetting quota readout = %q", got) } estimate := model.monitorSessionQuotaEstimate(1) - if estimate != "EST QUOTA // RESET DURING RUN" { + if estimate != "EST LOCAL-ONLY 5H // RESET" { t.Fatalf("reset-crossing estimate = %q", estimate) } } +func TestMonitorSuppressesStaleAndMissingQuotaEstimates(t *testing.T) { + startedAt := time.Unix(1_800, 0) + reset := startedAt.Add(time.Hour).Unix() + model := Model{monitorState: monitorRunning, monitorStartedAt: startedAt, monitorLatest: 200, monitorBaseline: 100} + model.startMonitorQuotaSnapshot(monitorQuotaSnapshot(20, reset)) + model.monitorQuotaWindows[0].latestUsed = 22 + + updated, _ := model.Update(fetchedMsg{err: errors.New("quota offline")}) + model = updated.(Model) + if got := model.monitorSessionQuotaEstimate(1); got != "EST LOCAL-ONLY 5H // STALE" { + t.Fatalf("failed-refresh estimate = %q", got) + } + if got := model.monitorQuotaReadout(); got != "ACCOUNT QUOTA Δ // 5 HOURS STALE" { + t.Fatalf("failed-refresh account readout = %q", got) + } + + updated, _ = model.Update(fetchedMsg{snapshot: codex.Snapshot{}}) + model = updated.(Model) + if !model.monitorQuotaWindows[0].stale { + t.Fatal("omitted quota window was not marked stale") + } + if got := model.monitorSessionQuotaEstimate(1); got != "EST LOCAL-ONLY 5H // STALE" { + t.Fatalf("missing-window estimate = %q", got) + } + + model.monitorQuotaWindows[0].stale = false + model.monitorState = monitorStopping + model.monitorRequest = 4 + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchStop, sequence: 4, usage: codex.LiveUsageSnapshot{TotalTokens: 200}, + quotaErr: errors.New("final quota offline"), at: startedAt.Add(time.Minute), + }) + model = updated.(Model) + if got := model.monitorSessionQuotaEstimate(1); got != "EST LOCAL-ONLY 5H // STALE" { + t.Fatalf("failed-final estimate = %q", got) + } +} + +func TestMonitorQuotaReadsBracketTheLocalTokenInterval(t *testing.T) { + fetcher := &orderedMonitorFetcher{ + quota: monitorQuotaSnapshot(20, time.Now().Add(time.Hour).Unix()), + usage: codex.LiveUsageSnapshot{TotalTokens: 100}, + } + model := New(fetcher, time.Minute) + if message := model.monitorFetch(monitorFetchStart, 1)().(monitorFetchedMsg); message.err != nil { + t.Fatal(message.err) + } + if want := []string{"quota", "usage"}; !reflect.DeepEqual(fetcher.calls, want) { + t.Fatalf("Start reads = %v; want %v", fetcher.calls, want) + } + + fetcher.calls = nil + if message := model.monitorFetch(monitorFetchStop, 2)().(monitorFetchedMsg); message.err != nil { + t.Fatal(message.err) + } + if want := []string{"usage-fresh", "quota"}; !reflect.DeepEqual(fetcher.calls, want) { + t.Fatalf("Stop reads = %v; want %v", fetcher.calls, want) + } +} + func TestMonitorAddsANewlyDetectedRootWithoutLosingItsFirstUsage(t *testing.T) { startedAt := time.Unix(2_000, 0) model := Model{monitorState: monitorStarting, monitorRequest: 1} @@ -609,6 +677,27 @@ type stubFreshLiveFetcher struct { freshCalls int } +type orderedMonitorFetcher struct { + calls []string + quota codex.Snapshot + usage codex.LiveUsageSnapshot +} + +func (f *orderedMonitorFetcher) Fetch(context.Context) (codex.Snapshot, error) { + f.calls = append(f.calls, "quota") + return f.quota, nil +} + +func (f *orderedMonitorFetcher) FetchTokenUsage(context.Context) (codex.LiveUsageSnapshot, error) { + f.calls = append(f.calls, "usage") + return f.usage, nil +} + +func (f *orderedMonitorFetcher) FetchTokenUsageFresh(context.Context) (codex.LiveUsageSnapshot, error) { + f.calls = append(f.calls, "usage-fresh") + return f.usage, nil +} + func (f *stubFreshLiveFetcher) FetchTokenUsage(context.Context) (codex.LiveUsageSnapshot, error) { f.ordinaryCalls++ return f.ordinary, nil From e006e7e58044b483051735835311a50709e93915 Mon Sep 17 00:00:00 2001 From: merefield Date: Wed, 12 Aug 2026 12:12:45 +0100 Subject: [PATCH 4/5] Add compact response pulse stats --- README.md | 32 ++++++-- internal/codex/live_usage.go | 131 ++++++++++++++++++++++++++---- internal/codex/live_usage_test.go | 76 +++++++++++++++++ internal/ui/model.go | 79 +++++++++++++++++- internal/ui/monitor.go | 63 ++++++++++++++ internal/ui/monitor_test.go | 94 +++++++++++++++++++++ main.go | 23 +++++- 7 files changed, 468 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 1508ce63..14503c9b 100644 --- a/README.md +++ b/README.md @@ -133,10 +133,12 @@ Codexometer deliberately does not: The Monitor additionally reads locally persisted Codex rollout files under `$CODEX_HOME/sessions` (normally `~/.codex/sessions`). It decodes `token_count` -totals and timestamps plus the minimum session metadata needed for grouping: -thread ID, parent thread ID, source classification, working directory, and the -inherited-history boundary. Message text, reasoning, commands, tool results, -and credentials are ignored and never retained by Codexometer. +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 +metadata—reasoning, commands, tool results, and credentials are ignored and +never retained by Codexometer. If you use a nonstandard Codex executable, pass it explicitly: @@ -195,7 +197,9 @@ Select a tab with the mouse, `Tab`, or `Shift+Tab`: average rate; clickable Start and Stop controls sit beside it. Below, every independent root session has a metrics box and its own graph. Spawned-agent descendants with an explicit Codex parent link are recursively aggregated - into the root row and reported as `ROOT + n AGENTS`. All graphs add one thin + into the root row and reported as `ROOT + n AGENTS`. Each row compactly shows + model calls and latest activity, latest/peak time to first token, and + latest/peak output size. All graphs add one thin vertical block bar on the same 30-second tick, after a fresh boundary read. The companion readout records each account quota window at Start and tracks its observed change while recording. Every session row shows its exact share @@ -273,6 +277,14 @@ 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. +`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 +output-token count for the latest such call. `TTFT` comes from the completed +turn's persisted time-to-first-token measurement; older Codex rollouts that do +not contain it display `N/A`. Spawned descendants contribute these pulses to +the same root row as their token activity. + The Monitor's per-session quota figure is an estimate, not API attribution. Codex exposes account-level quota percentages and local per-session token telemetry separately; it does not report which session consumed each percentage @@ -575,10 +587,12 @@ marks it as stale instead of blanking the dashboard. While the Monitor is recording it checks appended local token telemetry once per second, groups explicit agent descendants under their root, and rolls each -root's observed deltas into synchronized graph buckets. A 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. +root's observed deltas into synchronized graph buckets. It also updates the +three compact response-cycle statistics without retaining response content. A +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. Pressing Stop performs one immediate final local read and forces complete session discovery, including Codex sessions resumed from older rollout directories. diff --git a/internal/codex/live_usage.go b/internal/codex/live_usage.go index bfdfced5..61158787 100644 --- a/internal/codex/live_usage.go +++ b/internal/codex/live_usage.go @@ -20,6 +20,7 @@ const ( activeRolloutHorizon = 24 * time.Hour discoveryEvery = 5 * time.Second fullDiscoveryEvery = 5 * time.Minute + telemetryHistoryMax = 4_096 ) // LiveUsageSnapshot is a process-local, monotonically increasing count built @@ -42,6 +43,26 @@ type LiveUsageSession struct { AgentCount int Active bool Unattributed bool + ModelCalls []LiveModelCall + TurnTimings []LiveTurnTiming +} + +// LiveModelCall is the small, content-free usage pulse persisted after one +// upstream model response. +type LiveModelCall struct { + Sequence uint64 + At time.Time + OutputTokens int64 + OutputAvailable bool +} + +// LiveTurnTiming contains the persisted latency measurement for one completed +// Codex turn. Available is false for older rollouts that omit TTFT. +type LiveTurnTiming struct { + Sequence uint64 + At time.Time + TimeToFirstToken time.Duration + Available bool } // LiveUsageReader incrementally observes token telemetry written by local Codex @@ -57,6 +78,7 @@ type LiveUsageReader struct { files map[string]*rolloutCursor totalTokens int64 lastActivity time.Time + nextEventSequence uint64 } type rolloutCursor struct { @@ -70,6 +92,8 @@ type rolloutCursor struct { startedAt time.Time nonRoot bool subagentHistoryStartOrdinal *uint64 + modelCalls []LiveModelCall + turnTimings []LiveTurnTiming } type rolloutEvent struct { @@ -82,10 +106,24 @@ type rolloutEvent struct { TotalTokenUsage struct { TotalTokens int64 `json:"total_tokens"` } `json:"total_token_usage"` + LastTokenUsage struct { + OutputTokens *int64 `json:"output_tokens"` + } `json:"last_token_usage"` } `json:"info"` } `json:"payload"` } +type rolloutTurnEvent struct { + Timestamp time.Time `json:"timestamp"` + Ordinal *uint64 `json:"ordinal"` + Type string `json:"type"` + Payload struct { + Type string `json:"type"` + CompletedAt *int64 `json:"completed_at"` + TimeToFirstTokenMS *int64 `json:"time_to_first_token_ms"` + } `json:"payload"` +} + type rolloutMetadata struct { ID string ParentThreadID string @@ -330,28 +368,46 @@ 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 total, at, ordinal, ok := tokenTotalRecord(line); ok { - if !tokenRecordIsOwned(ordinal, cursor.subagentHistoryStartOrdinal, at, cursor.nonRoot, cursor.startedAt) { + 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 // events. Preserve the latest inherited value as the child's // counter baseline without reporting it as new usage. - cursor.totalTokens = total + cursor.totalTokens = record.total continue } - if total >= cursor.totalTokens { - delta := total - cursor.totalTokens + if record.total >= cursor.totalTokens { + delta := record.total - cursor.totalTokens r.totalTokens += delta cursor.observedTokens += delta if delta > 0 { - if at.IsZero() { - at = time.Now() + if record.at.IsZero() { + record.at = time.Now() + } + if record.at.After(r.lastActivity) { + r.lastActivity = record.at } - if at.After(r.lastActivity) { - r.lastActivity = at + r.nextEventSequence++ + cursor.modelCalls = append(cursor.modelCalls, LiveModelCall{ + Sequence: r.nextEventSequence, At: record.at, OutputTokens: record.outputTokens, + OutputAvailable: record.outputKnown, + }) + if len(cursor.modelCalls) > telemetryHistoryMax { + cursor.modelCalls = append([]LiveModelCall(nil), cursor.modelCalls[len(cursor.modelCalls)-telemetryHistoryMax:]...) } } } - cursor.totalTokens = total + cursor.totalTokens = record.total + } + if timing, available, ordinal, at, ok := turnTimingRecord(line); ok && + tokenRecordIsOwned(ordinal, cursor.subagentHistoryStartOrdinal, at, cursor.nonRoot, cursor.startedAt) { + r.nextEventSequence++ + cursor.turnTimings = append(cursor.turnTimings, LiveTurnTiming{ + Sequence: r.nextEventSequence, At: at, TimeToFirstToken: timing, Available: available, + }) + if len(cursor.turnTimings) > telemetryHistoryMax { + cursor.turnTimings = append([]LiveTurnTiming(nil), cursor.turnTimings[len(cursor.turnTimings)-telemetryHistoryMax:]...) + } } } if readErr != nil { @@ -407,15 +463,56 @@ func tokenTotal(line []byte) (int64, time.Time, bool) { } func tokenTotalRecord(line []byte) (int64, time.Time, *uint64, bool) { + record, ok := tokenUsageRecord(line) + return record.total, record.at, record.ordinal, ok +} + +type rolloutTokenRecord struct { + total int64 + outputTokens int64 + outputKnown bool + at time.Time + ordinal *uint64 +} + +func tokenUsageRecord(line []byte) (rolloutTokenRecord, bool) { if !bytes.Contains(line, []byte("token_count")) { - return 0, time.Time{}, nil, false + return rolloutTokenRecord{}, false } var event rolloutEvent if json.Unmarshal(line, &event) != nil || event.Type != "event_msg" || event.Payload.Type != "token_count" || event.Payload.Info == nil { - return 0, time.Time{}, nil, false + return rolloutTokenRecord{}, false + } + outputTokens := int64(0) + outputKnown := event.Payload.Info.LastTokenUsage.OutputTokens != nil + if outputKnown { + outputTokens = *event.Payload.Info.LastTokenUsage.OutputTokens + } + return rolloutTokenRecord{ + total: event.Payload.Info.TotalTokenUsage.TotalTokens, + outputTokens: outputTokens, outputKnown: outputKnown, + at: event.Timestamp, ordinal: event.Ordinal, + }, true +} + +func turnTimingRecord(line []byte) (time.Duration, bool, *uint64, time.Time, bool) { + if !bytes.Contains(line, []byte("task_complete")) && !bytes.Contains(line, []byte("turn_complete")) { + return 0, false, nil, time.Time{}, false + } + var event rolloutTurnEvent + if json.Unmarshal(line, &event) != nil || event.Type != "event_msg" || + (event.Payload.Type != "task_complete" && event.Payload.Type != "turn_complete") { + return 0, false, nil, time.Time{}, false + } + at := event.Timestamp + if at.IsZero() && event.Payload.CompletedAt != nil { + at = time.Unix(*event.Payload.CompletedAt, 0) + } + if event.Payload.TimeToFirstTokenMS == nil || *event.Payload.TimeToFirstTokenMS < 0 { + return 0, false, event.Ordinal, at, true } - return event.Payload.Info.TotalTokenUsage.TotalTokens, event.Timestamp, event.Ordinal, true + return time.Duration(*event.Payload.TimeToFirstTokenMS) * time.Millisecond, true, event.Ordinal, at, true } func tokenRecordIsOwned(ordinal, boundary *uint64, at time.Time, nonRoot bool, startedAt time.Time) bool { @@ -509,7 +606,7 @@ 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 { + if !active && cursor.observedTokens == 0 && len(cursor.modelCalls) == 0 && len(cursor.turnTimings) == 0 { continue } rootID, unattributed := rolloutRoot(cursor, byID) @@ -519,6 +616,8 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time) ([]LiveUsageSession, i groups[rootID] = group } group.TotalTokens += cursor.observedTokens + group.ModelCalls = append(group.ModelCalls, cursor.modelCalls...) + group.TurnTimings = append(group.TurnTimings, cursor.turnTimings...) group.Active = group.Active || active if cursor.lastModified.After(group.LastActivity) { group.LastActivity = cursor.lastModified @@ -532,7 +631,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 { + } else if active || cursor.observedTokens > 0 || len(cursor.modelCalls) > 0 || len(cursor.turnTimings) > 0 { group.AgentCount++ } } @@ -540,6 +639,8 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time) ([]LiveUsageSession, i sessions := make([]LiveUsageSession, 0, len(groups)) activeCount := 0 for _, session := range groups { + sort.Slice(session.ModelCalls, func(i, j int) bool { return session.ModelCalls[i].Sequence < session.ModelCalls[j].Sequence }) + sort.Slice(session.TurnTimings, func(i, j int) bool { return session.TurnTimings[i].Sequence < session.TurnTimings[j].Sequence }) if session.Active { activeCount++ } diff --git a/internal/codex/live_usage_test.go b/internal/codex/live_usage_test.go index 050b68eb..344f1027 100644 --- a/internal/codex/live_usage_test.go +++ b/internal/codex/live_usage_test.go @@ -207,6 +207,59 @@ func TestLiveUsageReaderKeepsNewestActivityAcrossEvents(t *testing.T) { } } +func TestLiveUsageReaderCapturesContentFreeModelCallAndTurnTimingPulses(t *testing.T) { + home := t.TempDir() + now := time.Now().UTC().Truncate(time.Millisecond) + path := testRolloutPath(t, home, now.Add(-time.Hour), "response-pulses") + writeRollout(t, path, sessionMetaLine("root", `"cli"`, "/work/root", nil)+"\n"+tokenCountLine(now.Add(-time.Hour), 100)+"\n") + reader, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + if _, err := reader.FetchTokenUsage(context.Background()); err != nil { + t.Fatal(err) + } + + appendRollout(t, path, + tokenCountLineWithOutput(now, 150, 2_013)+"\n"+ + turnTimingLine(now.Add(time.Second), 11_600)+"\n"+ + tokenCountLineWithOutput(now.Add(2*time.Second), 225, 842)+"\n"+ + turnTimingLine(now.Add(3*time.Second), 2_400)+"\n") + usage, err := reader.FetchTokenUsage(context.Background()) + if err != nil || len(usage.Sessions) != 1 { + t.Fatalf("pulse telemetry fetch = %#v, %v", usage, err) + } + session := usage.Sessions[0] + if len(session.ModelCalls) != 2 || session.ModelCalls[0].OutputTokens != 2_013 || session.ModelCalls[1].OutputTokens != 842 || + !session.ModelCalls[0].OutputAvailable || !session.ModelCalls[1].OutputAvailable { + t.Fatalf("model-call pulses = %#v", session.ModelCalls) + } + if len(session.TurnTimings) != 2 || session.TurnTimings[0].TimeToFirstToken != 11_600*time.Millisecond || + session.TurnTimings[1].TimeToFirstToken != 2_400*time.Millisecond || + !session.TurnTimings[0].Available || !session.TurnTimings[1].Available { + t.Fatalf("turn timings = %#v", session.TurnTimings) + } + if session.ModelCalls[0].Sequence >= session.TurnTimings[0].Sequence || + session.TurnTimings[0].Sequence >= session.ModelCalls[1].Sequence { + t.Fatalf("telemetry sequence did not preserve rollout order: calls=%#v turns=%#v", session.ModelCalls, session.TurnTimings) + } + + appendRollout(t, path, + tokenCountLine(now.Add(4*time.Second), 250)+"\n"+ + turnTimingUnavailableLine(now.Add(5*time.Second))+"\n") + usage, err = reader.FetchTokenUsage(context.Background()) + if err != nil { + t.Fatal(err) + } + session = usage.Sessions[0] + if len(session.ModelCalls) != 3 || session.ModelCalls[2].OutputAvailable { + t.Fatalf("legacy model call was not retained as unavailable: %#v", session.ModelCalls) + } + if len(session.TurnTimings) != 3 || session.TurnTimings[2].Available { + t.Fatalf("legacy turn timing was not retained as unavailable: %#v", session.TurnTimings) + } +} + func TestLiveUsageReaderGroupsSpawnedDescendantsUnderIndependentRoots(t *testing.T) { home := t.TempDir() now := time.Now() @@ -251,6 +304,8 @@ func TestLiveUsageReaderGroupsSpawnedDescendantsUnderIndependentRoots(t *testing } if got := byID["root-a"]; got.TotalTokens != 85 || got.AgentCount != 2 || got.WorkingDirectory != "/work/alpha" || got.Unattributed { t.Fatalf("root A grouping = %#v; want root plus two descendants and 85 tokens", got) + } else if len(got.ModelCalls) != 3 { + t.Fatalf("root A model calls = %#v; want three root/descendant pulses", got.ModelCalls) } if got := byID["root-b"]; got.TotalTokens != 30 || got.AgentCount != 0 || got.WorkingDirectory != "/work/bravo" { t.Fatalf("root B grouping = %#v; want independent 30-token root", got) @@ -474,6 +529,27 @@ func tokenCountLine(at time.Time, total int64) string { ) } +func tokenCountLineWithOutput(at time.Time, total, output int64) string { + return fmt.Sprintf( + `{"timestamp":%q,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"total_tokens":%d},"last_token_usage":{"output_tokens":%d,"total_tokens":%d}}}}`, + at.UTC().Format(time.RFC3339Nano), total, output, total, + ) +} + +func turnTimingLine(at time.Time, ttftMS int64) string { + return fmt.Sprintf( + `{"timestamp":%q,"type":"event_msg","payload":{"type":"task_complete","completed_at":%d,"duration_ms":12000,"time_to_first_token_ms":%d}}`, + at.UTC().Format(time.RFC3339Nano), at.Unix(), ttftMS, + ) +} + +func turnTimingUnavailableLine(at time.Time) string { + return fmt.Sprintf( + `{"timestamp":%q,"type":"event_msg","payload":{"type":"task_complete","completed_at":%d,"duration_ms":12000}}`, + at.UTC().Format(time.RFC3339Nano), at.Unix(), + ) +} + 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/ui/model.go b/internal/ui/model.go index 590cf194..de36c051 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -142,6 +142,18 @@ type monitorSession struct { displayed bool unattributed bool samples []monitorSample + callSequence uint64 + turnSequence uint64 + modelCalls int + lastCallAt time.Time + latestOutput int64 + peakOutput int64 + latestOutputOK bool + peakOutputOK bool + latestTTFT time.Duration + peakTTFT time.Duration + latestTTFTOK bool + peakTTFTOK bool } type monitorQuotaWindow struct { @@ -1088,6 +1100,8 @@ func (m *Model) startMonitorSessions(usage codex.LiveUsageSnapshot, observedAt t startedAt: observedAt, lastActivity: session.LastActivity, agentCount: session.AgentCount, active: session.Active, displayed: session.Active, unattributed: session.Unattributed, + callSequence: latestModelCallSequence(session.ModelCalls), + turnSequence: latestTurnTimingSequence(session.TurnTimings), }) } if len(m.monitorSessionData) == 0 && usage.SessionCount > 0 { @@ -1110,13 +1124,15 @@ func (m *Model) syncMonitorSessions(usage codex.LiveUsageSnapshot, observedAt ti if sessionStart := update.StartedAt; !sessionStart.IsZero() && sessionStart.After(m.monitorStartedAt) && sessionStart.Before(observedAt) { startedAt = sessionStart } - m.monitorSessionData = append(m.monitorSessionData, monitorSession{ + created := monitorSession{ 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, + active: update.Active, displayed: update.Active || update.TotalTokens > 0 || len(update.ModelCalls) > 0 || len(update.TurnTimings) > 0, unattributed: update.Unattributed, - }) + } + applyMonitorSessionTelemetry(&created, update, m.monitorStartedAt) + m.monitorSessionData = append(m.monitorSessionData, created) continue } session := &m.monitorSessionData[index] @@ -1128,10 +1144,12 @@ 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.displayed = session.displayed || update.Active || update.TotalTokens > session.baseline + session.displayed = session.displayed || update.Active || update.TotalTokens > session.baseline || + len(update.ModelCalls) > 0 || len(update.TurnTimings) > 0 if update.WorkingDirectory != "" { session.workingDirectory = update.WorkingDirectory } + applyMonitorSessionTelemetry(session, update, time.Time{}) } if len(usage.Sessions) == 0 && len(m.monitorSessionData) == 1 && m.monitorSessionData[0].id == "local" { session := &m.monitorSessionData[0] @@ -1142,6 +1160,59 @@ func (m *Model) syncMonitorSessions(usage codex.LiveUsageSnapshot, observedAt ti } } +func applyMonitorSessionTelemetry(session *monitorSession, update codex.LiveUsageSession, since time.Time) { + for _, call := range update.ModelCalls { + if call.Sequence <= session.callSequence { + continue + } + session.callSequence = call.Sequence + if !since.IsZero() && !call.At.IsZero() && call.At.Before(since) { + continue + } + session.modelCalls++ + session.latestOutputOK = call.OutputAvailable + if call.OutputAvailable { + session.latestOutput = max(call.OutputTokens, int64(0)) + session.peakOutput = max(session.peakOutput, session.latestOutput) + session.peakOutputOK = true + } + if call.At.After(session.lastCallAt) { + session.lastCallAt = call.At + } + } + for _, timing := range update.TurnTimings { + if timing.Sequence <= session.turnSequence { + continue + } + session.turnSequence = timing.Sequence + if !since.IsZero() && !timing.At.IsZero() && timing.At.Before(since) { + continue + } + session.latestTTFTOK = timing.Available + if timing.Available { + session.latestTTFT = max(timing.TimeToFirstToken, time.Duration(0)) + session.peakTTFT = max(session.peakTTFT, session.latestTTFT) + session.peakTTFTOK = true + } + } +} + +func latestModelCallSequence(calls []codex.LiveModelCall) uint64 { + var latest uint64 + for _, call := range calls { + latest = max(latest, call.Sequence) + } + return latest +} + +func latestTurnTimingSequence(timings []codex.LiveTurnTiming) uint64 { + var latest uint64 + for _, timing := range timings { + latest = max(latest, timing.Sequence) + } + return latest +} + func (m *Model) captureMonitorSamples(at time.Time) { if at.IsZero() { at = time.Now() diff --git a/internal/ui/monitor.go b/internal/ui/monitor.go index 826d2faf..68d7ea92 100644 --- a/internal/ui/monitor.go +++ b/internal/ui/monitor.go @@ -285,6 +285,9 @@ func (m Model) renderMonitorSessionMetrics(width, height int, session monitorSes appendLine(estimate) } appendLine(status + " // " + memberLabel) + appendLine(formatMonitorCallActivity(session, time.Now())) + appendLine(formatMonitorTTFT(session)) + appendLine(formatMonitorOutput(session)) appendLine("RATE " + formatTokens(rate) + "/MIN") if session.workingDirectory != "" { appendLine("DIR // " + filepath.Base(session.workingDirectory)) @@ -298,6 +301,66 @@ func (m Model) renderMonitorSessionMetrics(width, height int, session monitorSes return frameSized(width, max(height-2, 1), title, strings.Join(lines, "\n"), colors.primary, colors) } +func formatMonitorCallActivity(session monitorSession, now time.Time) string { + last := "--" + if !session.lastCallAt.IsZero() { + last = formatMonitorAge(now.Sub(session.lastCallAt)) + " AGO" + } + return fmt.Sprintf("CALLS %d // LAST %s", session.modelCalls, last) +} + +func formatMonitorTTFT(session monitorSession) string { + latest := "N/A" + if session.latestTTFTOK { + latest = formatMonitorLatency(session.latestTTFT) + } + peak := "N/A" + if session.peakTTFTOK { + peak = formatMonitorLatency(session.peakTTFT) + } + return "TTFT " + latest + " // PEAK " + peak +} + +func formatMonitorOutput(session monitorSession) string { + latest := "N/A" + if session.latestOutputOK { + latest = formatTokens(session.latestOutput) + } + peak := "N/A" + if session.peakOutputOK { + peak = formatTokens(session.peakOutput) + } + return "LAST OUT " + latest + " // PEAK " + peak +} + +func formatMonitorAge(duration time.Duration) string { + if duration < 0 { + duration = 0 + } + seconds := int(math.Ceil(duration.Seconds())) + switch { + case seconds < 60: + return fmt.Sprintf("%dS", seconds) + case seconds < 3600: + return fmt.Sprintf("%dM%02dS", seconds/60, seconds%60) + default: + return fmt.Sprintf("%dH%02dM", seconds/3600, seconds/60%60) + } +} + +func formatMonitorLatency(duration time.Duration) string { + if duration < 0 { + duration = 0 + } + if duration < time.Second { + return fmt.Sprintf("%dMS", duration.Milliseconds()) + } + if duration < time.Minute { + return strings.TrimSuffix(fmt.Sprintf("%.1f", duration.Seconds()), ".0") + "S" + } + return fmt.Sprintf("%dM%02dS", int(duration/time.Minute), int(duration/time.Second)%60) +} + func (m Model) monitorRecordedTokens() int64 { if m.monitorStartedAt.IsZero() || m.monitorLatest < m.monitorBaseline { return 0 diff --git a/internal/ui/monitor_test.go b/internal/ui/monitor_test.go index 237803f2..cd665dc0 100644 --- a/internal/ui/monitor_test.go +++ b/internal/ui/monitor_test.go @@ -158,6 +158,100 @@ func TestMonitorTracksRootSessionsAndSamplesEveryGraphOnOneTick(t *testing.T) { } } +func TestMonitorTracksCompactModelCallOutputAndTTFTStatsSinceStart(t *testing.T) { + startedAt := time.Unix(1_400, 0) + model := Model{monitorState: monitorStarting, monitorRequest: 1} + updated, _ := model.Update(monitorFetchedMsg{ + kind: monitorFetchStart, sequence: 1, at: startedAt, + usage: codex.LiveUsageSnapshot{TotalTokens: 100, SessionCount: 1, Sessions: []codex.LiveUsageSession{{ + ID: "alpha", TotalTokens: 100, Active: true, + ModelCalls: []codex.LiveModelCall{{Sequence: 1, At: startedAt.Add(-time.Second), OutputTokens: 9_999, OutputAvailable: true}}, + TurnTimings: []codex.LiveTurnTiming{{Sequence: 2, At: startedAt.Add(-time.Second), TimeToFirstToken: 20 * time.Second, Available: true}}, + }}}, + }) + model = updated.(Model) + session := model.monitorSessionData[0] + if session.modelCalls != 0 || session.latestTTFTOK { + t.Fatalf("pre-Start response telemetry was not baselined: %#v", session) + } + + model.monitorRequest++ + latestAt := startedAt.Add(52 * time.Second) + usage := codex.LiveUsageSnapshot{TotalTokens: 200, SessionCount: 1, Sessions: []codex.LiveUsageSession{{ + ID: "alpha", TotalTokens: 200, Active: true, + ModelCalls: []codex.LiveModelCall{ + {Sequence: 1, At: startedAt.Add(-time.Second), OutputTokens: 9_999, OutputAvailable: true}, + {Sequence: 3, At: startedAt.Add(40 * time.Second), OutputTokens: 2_013, OutputAvailable: true}, + {Sequence: 4, At: latestAt, OutputTokens: 842, OutputAvailable: true}, + }, + TurnTimings: []codex.LiveTurnTiming{ + {Sequence: 2, At: startedAt.Add(-time.Second), TimeToFirstToken: 20 * time.Second, Available: true}, + {Sequence: 5, At: startedAt.Add(45 * time.Second), TimeToFirstToken: 11_600 * time.Millisecond, Available: true}, + {Sequence: 6, At: latestAt, TimeToFirstToken: 2_400 * time.Millisecond, Available: true}, + }, + }}} + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchSample, sequence: model.monitorRequest, at: startedAt.Add(time.Minute), usage: usage, + }) + model = updated.(Model) + session = model.monitorSessionData[0] + if session.modelCalls != 2 || session.latestOutput != 842 || session.peakOutput != 2_013 { + t.Fatalf("model-call output stats = %#v", session) + } + if !session.latestTTFTOK || !session.peakTTFTOK || session.latestTTFT != 2_400*time.Millisecond || session.peakTTFT != 11_600*time.Millisecond { + t.Fatalf("TTFT stats = %#v", session) + } + if got := formatMonitorCallActivity(session, startedAt.Add(time.Minute)); got != "CALLS 2 // LAST 8S AGO" { + t.Fatalf("call activity = %q", got) + } + if got := formatMonitorTTFT(session); got != "TTFT 2.4S // PEAK 11.6S" { + t.Fatalf("TTFT readout = %q", got) + } + if got := formatMonitorOutput(session); got != "LAST OUT 842 // PEAK 2,013" { + t.Fatalf("output readout = %q", got) + } + partial := session + applyMonitorSessionTelemetry(&partial, codex.LiveUsageSession{ + ModelCalls: []codex.LiveModelCall{{Sequence: 7, At: startedAt.Add(55 * time.Second)}}, + TurnTimings: []codex.LiveTurnTiming{{Sequence: 8, At: startedAt.Add(56 * time.Second)}}, + }, time.Time{}) + if partial.modelCalls != 3 || partial.latestOutputOK || !partial.peakOutputOK { + t.Fatalf("partial output stats = %#v", partial) + } + if partial.latestTTFTOK || !partial.peakTTFTOK { + t.Fatalf("partial TTFT stats = %#v", partial) + } + if got := formatMonitorTTFT(partial); got != "TTFT N/A // PEAK 11.6S" { + t.Fatalf("partial TTFT readout = %q", got) + } + if got := formatMonitorOutput(partial); got != "LAST OUT N/A // PEAK 2,013" { + t.Fatalf("partial output readout = %q", got) + } + card := ansi.Strip(model.renderMonitorSessionMetrics(64, 12, session, "", paletteFor(themeHacker))) + for _, want := range []string{"CALLS 2", "TTFT 2.4S // PEAK 11.6S", "LAST OUT 842 // PEAK 2,013"} { + if !strings.Contains(card, want) { + t.Errorf("session card missing %q:\n%s", want, card) + } + } + + model.monitorRequest++ + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchSample, sequence: model.monitorRequest, at: startedAt.Add(61 * time.Second), usage: usage, + }) + model = updated.(Model) + if model.monitorSessionData[0].modelCalls != 2 { + t.Fatal("replayed response telemetry was counted twice") + } + + legacy := monitorSession{} + if got := formatMonitorTTFT(legacy); got != "TTFT N/A // PEAK N/A" { + t.Fatalf("legacy TTFT readout = %q", got) + } + if got := formatMonitorOutput(legacy); got != "LAST OUT N/A // PEAK N/A" { + t.Fatalf("legacy output readout = %q", got) + } +} + func TestMonitorAttributesObservedQuotaMovementByLocalTokenShare(t *testing.T) { startedAt := time.Unix(1_500, 0) reset := startedAt.Add(time.Hour).Unix() diff --git a/main.go b/main.go index d572cf08..0e58800d 100644 --- a/main.go +++ b/main.go @@ -19,6 +19,11 @@ import ( type demoFetcher struct { mu sync.Mutex lifetimeTokens int64 + eventSequence uint64 + alphaCalls []codex.LiveModelCall + alphaTurns []codex.LiveTurnTiming + bravoCalls []codex.LiveModelCall + bravoTurns []codex.LiveTurnTiming } func (d *demoFetcher) Fetch(context.Context) (codex.Snapshot, error) { @@ -32,13 +37,27 @@ func (d *demoFetcher) FetchTokenUsage(context.Context) (codex.LiveUsageSnapshot, d.lifetimeTokens = 100_000 } else { d.lifetimeTokens += 1_234 + now := time.Now() + d.eventSequence++ + call := codex.LiveModelCall{Sequence: d.eventSequence, At: now, OutputTokens: 420 + int64(d.eventSequence%5)*137, OutputAvailable: true} + d.eventSequence++ + timing := codex.LiveTurnTiming{Sequence: d.eventSequence, At: now, TimeToFirstToken: time.Duration(900+d.eventSequence%7*350) * time.Millisecond, Available: true} + if d.eventSequence/2%2 == 0 { + d.alphaCalls = append(d.alphaCalls, call) + d.alphaTurns = append(d.alphaTurns, timing) + } else { + d.bravoCalls = append(d.bravoCalls, call) + d.bravoTurns = append(d.bravoTurns, timing) + } } alphaTokens := d.lifetimeTokens * 3 / 5 return 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}, - {ID: "019d-demo-d4e5f", WorkingDirectory: "/projects/bravo", TotalTokens: d.lifetimeTokens - alphaTokens, LastActivity: time.Now(), Active: true}, + {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...)}, + {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...)}, }, }, nil } From ebda8e6fbe0ea01d76e0019108f11f972018d587 Mon Sep 17 00:00:00 2001 From: merefield Date: Wed, 12 Aug 2026 12:28:13 +0100 Subject: [PATCH 5/5] Address Monitor review findings --- internal/codex/live_usage.go | 25 ++++++++++++++--------- internal/codex/live_usage_test.go | 19 +++++++++++++++++ internal/ui/model.go | 26 +++++++++++++++++------ internal/ui/monitor_test.go | 34 +++++++++++++++++++++++++++++++ 4 files changed, 88 insertions(+), 16 deletions(-) diff --git a/internal/codex/live_usage.go b/internal/codex/live_usage.go index 61158787..e76ab859 100644 --- a/internal/codex/live_usage.go +++ b/internal/codex/live_usage.go @@ -388,13 +388,10 @@ func (r *LiveUsageReader) consume(path string, cursor *rolloutCursor) error { r.lastActivity = record.at } r.nextEventSequence++ - cursor.modelCalls = append(cursor.modelCalls, LiveModelCall{ + cursor.modelCalls = appendBounded(cursor.modelCalls, LiveModelCall{ Sequence: r.nextEventSequence, At: record.at, OutputTokens: record.outputTokens, OutputAvailable: record.outputKnown, - }) - if len(cursor.modelCalls) > telemetryHistoryMax { - cursor.modelCalls = append([]LiveModelCall(nil), cursor.modelCalls[len(cursor.modelCalls)-telemetryHistoryMax:]...) - } + }, telemetryHistoryMax) } } cursor.totalTokens = record.total @@ -402,12 +399,9 @@ func (r *LiveUsageReader) consume(path string, cursor *rolloutCursor) error { if timing, available, ordinal, at, ok := turnTimingRecord(line); ok && tokenRecordIsOwned(ordinal, cursor.subagentHistoryStartOrdinal, at, cursor.nonRoot, cursor.startedAt) { r.nextEventSequence++ - cursor.turnTimings = append(cursor.turnTimings, LiveTurnTiming{ + cursor.turnTimings = appendBounded(cursor.turnTimings, LiveTurnTiming{ Sequence: r.nextEventSequence, At: at, TimeToFirstToken: timing, Available: available, - }) - if len(cursor.turnTimings) > telemetryHistoryMax { - cursor.turnTimings = append([]LiveTurnTiming(nil), cursor.turnTimings[len(cursor.turnTimings)-telemetryHistoryMax:]...) - } + }, telemetryHistoryMax) } } if readErr != nil { @@ -419,6 +413,17 @@ func (r *LiveUsageReader) consume(path string, cursor *rolloutCursor) error { } } +// 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. +func appendBounded[T any](history []T, value T, limit int) []T { + history = append(history, value) + if limit > 0 && len(history) > limit { + history = history[len(history)-limit:] + } + return history +} + func latestTokenTotal(path string) (int64, error) { file, err := os.Open(path) if err != nil { diff --git a/internal/codex/live_usage_test.go b/internal/codex/live_usage_test.go index 344f1027..3e57eed8 100644 --- a/internal/codex/live_usage_test.go +++ b/internal/codex/live_usage_test.go @@ -59,6 +59,25 @@ func TestLiveUsageReaderBaselinesAndConsumesAppendedTelemetry(t *testing.T) { } } +func TestAppendBoundedRetainsNewestValuesWithoutCopyingOnOverflow(t *testing.T) { + history := make([]int, 3, 4) + copy(history, []int{1, 2, 3}) + firstRetained := &history[1] + + history = appendBounded(history, 4, 3) + if len(history) != 3 || history[0] != 2 || history[1] != 3 || history[2] != 4 { + t.Fatalf("bounded history = %#v; want [2 3 4]", history) + } + if &history[0] != firstRetained { + t.Fatal("bounded history copied its backing array on overflow") + } + + history = appendBounded(history, 5, 3) + if len(history) != 3 || history[0] != 3 || history[1] != 4 || history[2] != 5 { + t.Fatalf("bounded history after reuse = %#v; want [3 4 5]", history) + } +} + func TestLiveUsageReaderHandlesNewOldAndResetSessions(t *testing.T) { home := t.TempDir() now := time.Now() diff --git a/internal/ui/model.go b/internal/ui/model.go index de36c051..cee84bca 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -439,9 +439,9 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { return m, nil } m.monitorFetchActive = false - updated, command := m.applyMonitorFetch(message) + updated, command, accepted := m.applyMonitorFetch(message) m = updated.(Model) - if message.err == nil && message.kind == monitorFetchBoundary && m.monitorState == monitorRunning { + if accepted && message.kind == monitorFetchBoundary && m.monitorState == monitorRunning { m.captureMonitorSamples(message.at) m.monitorBoundaryDue = false } @@ -942,7 +942,7 @@ func (m Model) monitorFetch(kind monitorFetchKind, sequence uint64) tea.Cmd { } } -func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd) { +func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd, bool) { if message.kind == monitorFetchStop { if message.quotaErr == nil { m.syncMonitorQuotaSnapshot(message.quota) @@ -957,8 +957,9 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd) } else if message.kind == monitorFetchStart { m.monitorState = monitorStopped } - return m, nil + return m, nil, false } + accepted := true switch message.kind { case monitorFetchStart: m.monitorBaseline = message.usage.TotalTokens @@ -978,8 +979,9 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd) m.monitorError = "" m.monitorNextSample = message.at.Add(monitorSampleInterval) case monitorFetchSample, monitorFetchBoundary, monitorFetchStop: - if message.usage.TotalTokens < m.monitorLatest { + if m.monitorUsageMovesBackwards(message.usage) { m.monitorError = "local Codex token counter moved backwards" + accepted = false } else { if message.usage.TotalTokens > m.monitorLatest { m.monitorLastActivity = message.usage.LastActivity @@ -994,7 +996,19 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd) m.monitorStoppedAt = message.at } } - return m, nil + return m, nil, accepted +} + +func (m Model) monitorUsageMovesBackwards(usage codex.LiveUsageSnapshot) bool { + if usage.TotalTokens < m.monitorLatest { + return true + } + for _, update := range usage.Sessions { + if index := m.monitorSessionIndex(update.ID); index >= 0 && update.TotalTokens < m.monitorSessionData[index].latest { + return true + } + } + return false } func (m *Model) applyMonitorQuotaResult(message monitorFetchedMsg) { diff --git a/internal/ui/monitor_test.go b/internal/ui/monitor_test.go index cd665dc0..3b1fde27 100644 --- a/internal/ui/monitor_test.go +++ b/internal/ui/monitor_test.go @@ -456,6 +456,40 @@ func TestMonitorWaitsForAFreshBoundaryReadWhenOrdinaryFetchIsInFlight(t *testing } } +func TestMonitorRejectsBackwardsSessionBoundaryAndRetriesNextTick(t *testing.T) { + startedAt := time.Unix(3_100, 0) + model := Model{ + monitorState: monitorRunning, monitorStartedAt: startedAt, + monitorLatest: 100, monitorGraphStart: 100, + monitorNextSample: startedAt.Add(time.Minute), monitorBoundaryDue: true, + monitorFetchActive: true, monitorRequest: 7, + monitorSessionData: []monitorSession{{ + id: "root", baseline: 100, latest: 100, graphStart: 100, + startedAt: startedAt, active: true, displayed: true, + }}, + } + + updated, command := model.Update(monitorFetchedMsg{ + kind: monitorFetchBoundary, sequence: 7, at: startedAt.Add(30 * time.Second), + usage: codex.LiveUsageSnapshot{TotalTokens: 110, Sessions: []codex.LiveUsageSession{{ + ID: "root", TotalTokens: 90, Active: true, + }}}, + }) + model = updated.(Model) + if command != nil || len(model.monitorSamples) != 0 || !model.monitorBoundaryDue { + t.Fatalf("invalid boundary closed its bucket: due=%t samples=%#v command=%v", model.monitorBoundaryDue, model.monitorSamples, command) + } + if model.monitorLatest != 100 || model.monitorSessionData[0].latest != 100 || model.monitorError == "" { + t.Fatalf("invalid boundary mutated accepted telemetry: %#v", model) + } + + updated, command = model.Update(secondMsg(startedAt.Add(31 * time.Second))) + model = updated.(Model) + if command == nil || !model.monitorFetchActive || model.monitorRequest != 8 || !model.monitorBoundaryDue { + t.Fatalf("rejected boundary was not retried on the next tick: %#v", model) + } +} + func TestMonitorRendersOneMetricsAndGraphPairPerRootSession(t *testing.T) { model := Model{ monitorState: monitorRunning, monitorStartedAt: time.Now().Add(-time.Minute),