From b63ea5134df99de76cec011d8b871348c1254161 Mon Sep 17 00:00:00 2001 From: merefield Date: Sun, 23 Aug 2026 11:27:02 +0100 Subject: [PATCH 1/6] ENH: make Monitor always on --- README.md | 82 +++-- internal/codex/daemon_status_unix.go | 74 +++- internal/codex/daemon_status_unix_test.go | 31 ++ internal/ui/model.go | 416 ++++++++++++++++++---- internal/ui/monitor.go | 91 +++-- internal/ui/monitor_test.go | 304 ++++++++++++---- internal/ui/tabs_test.go | 15 +- 7 files changed, 805 insertions(+), 208 deletions(-) diff --git a/README.md b/README.md index 83f58e70..c572f5e9 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,8 @@ It works particularly well in: - Online, refreshing, stale-data, and error states, with the limiting window named in warning states and a celebratory fresh-reset signal at 0% usage. - A countdown to the next automatic refresh. -- An optional Monitor view that measures token activity between Go and Stop. +- An always-on Monitor view that measures local token activity while Codexometer + is running, with Pause/Resume and Reset controls. Each independent local root session gets its own metrics and 30-second graph; explicitly linked spawned agents are included with their root. - Highlighted per-session attention badges. A shared Codex app-server supplies @@ -259,9 +260,9 @@ Set up the recommended arrangement as follows. reconstructed after the fact. No additional Codexometer option is required; it automatically probes the same default socket under `CODEX_HOME`. -5. Leave Codexometer running while you work. Use Monitor Start when you want a - measured interval, and keep unrelated Codex activity quiet while running - Benchmarks if you want the cleanest comparisons. +5. Leave Codexometer running while you work. The Monitor starts automatically; + use Reset when you want a fresh measured interval, and keep unrelated Codex + activity quiet while running Benchmarks if you want the cleanest comparisons. Codexometer subscribes only to thread IDs that are already loaded by the daemon; it does not load unrelated historical sessions. @@ -349,16 +350,16 @@ codexometer --codex /path/to/codex | `Shift+Tab` | Select the previous top-level tab | | `r` | Refresh quota data immediately | | `v` | Cycle the active Quota view | -| `s` | Start recording (Monitor) or open Benchmark Scope | -| `p` | Stop and take a final up-to-date reading (Monitor view only) | +| `s` | Reset the Monitor baseline, or open Benchmark Scope | +| `p` | Pause or resume live monitoring (Monitor view only) | | `b` | Run the selected benchmark scope (Benchmark view only) | | `a` | Arm, then confirm, Run All (Benchmark view only) | -| `x` | Stop the active benchmark suite and retain its incomplete trial | +| `x` | Close the selected Monitor session row, or stop the active benchmark suite and retain its incomplete trial | | `d` | Close the Benchmark Scope screen | | `[` / `]`, `Left` / `Right` | Select the previous or next benchmark suite | | `f` | Show all, passed, or failed benchmark results | | `w` | Cycle Cost, Balanced, and Speed benchmark ranking weights | -| `Up` / `Down` | Select a Benchmark row, or scroll its open detail | +| `Up` / `Down` | Select a Monitor session row or Benchmark row, or scroll open Benchmark detail | | `Enter` / `Space` | Open a selected result, or toggle a Benchmark Scope checkbox | | `c` | Copy the Benchmark result matrix as Markdown, or copy the complete open run detail | | `Page Up` / `Page Down` | Scroll Monitor session rows or Benchmark result pages | @@ -573,19 +574,20 @@ choose one of these four views with its sub-tab or `v`: The other top-level views are: -- **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. Below, every - independent root session has a metrics box and its own graph. Spawned-agent +- **Monitor** — automatically establishes a zero baseline across locally active + Codex sessions when Codexometer starts. A large readout follows newly appended + token telemetry and shows total observed tokens, elapsed time, and average + rate; clickable Pause/Resume and Reset controls sit beside it. Active sessions + are checked once per second and the idle cadence relaxes to five seconds. + 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`. 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 of locally observed - tokens and an explicitly labelled, local-only estimate of the first quota + records each account quota window at the current baseline and tracks its + observed change while monitoring. Every session row shows its exact 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 @@ -610,11 +612,14 @@ The other top-level views are: when tokens, model calls, turn timing, durable activity, or attention moves forward, or when an inactive session becomes active again. An alert already visible when `[×]` is clicked is dismissed with its row; a later new or - changed alert restores it. Starting a new Monitor recording also restores - every dismissed row. + changed alert restores it. Resetting the Monitor also restores every dismissed + row. With the keyboard, `Down` initially selects the top row, `Up` initially + selects the bottom row, subsequent arrow presses move the highlight, and `x` + closes the selected row. 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. + wheel to page through the rows. Pause performs an immediate final local read + instead of relying on the latest graph sample. Resume preserves the recorded + totals while excluding tokens and elapsed time from the paused interval. - **Benchmark** — runs the selected scope from the active Core, Extended, or conditional DigBench suite, or the active suite's complete catalog, against the selected or complete set of compatible model/reasoning-effort pairs. @@ -701,8 +706,8 @@ SESSION` is only an inactivity inference, fresh activity anywhere in the group suppresses a stale sibling's check; definite input and approval are never suppressed this way. -`CALLS` counts upstream model-response cycles observed after Monitor Start, not -complete user turns. A single Codex turn can make several calls while using +`CALLS` counts upstream model-response cycles observed after the current Monitor +baseline, 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 @@ -726,11 +731,11 @@ Codex. `NO INTEGER Δ` means no whole-point movement was observed, not necessari 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. +Starting, resuming, or resetting reads quota before establishing the local token +baseline, while Pause reads local tokens before the final quota snapshot, so the +account observation brackets each monitored segment. These operations are not +atomic, so unrelated account activity during either short boundary read remains +another source of uncertainty. ### Saved presentation preferences @@ -1340,21 +1345,26 @@ interval. Pressing `r` refreshes immediately. If a refresh fails after valid 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, groups explicit agent descendants under their root, and rolls each -root's observed deltas into synchronized graph buckets. It also updates the +The Monitor starts with Codexometer and checks appended local token telemetry +once per second while sessions are active, relaxing to once every five seconds +when none are active. It groups explicit agent descendants under their root and +rolls each 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. -On Unix systems, each read also probes the default shared app-server control -socket. When present, its loaded-thread runtime statuses make attention badges -exact; when absent or unreachable, Codexometer silently uses the local rollout -and writer-lock fallback described above. -Pressing Stop performs one immediate final local read and forces complete +On Unix systems, these reads also probe the default shared app-server control +socket. Exact thread-status results are cached for five seconds to avoid +repeating the same per-thread requests on every active poll. When present, its +loaded-thread runtime statuses make attention badges exact; when absent or +unreachable, Codexometer silently uses the local rollout and writer-lock +fallback described above. Graph history is bounded to the latest 4,096 samples. +Pressing Pause performs one immediate final local read and forces complete session discovery, including Codex sessions resumed from older rollout -directories. +directories. Resume rebases counters so activity during the pause is excluded; +Reset clears the measurement and graphs without changing the paused/running +state. ## Troubleshooting diff --git a/internal/codex/daemon_status_unix.go b/internal/codex/daemon_status_unix.go index 8e6c09ac..08f821f2 100644 --- a/internal/codex/daemon_status_unix.go +++ b/internal/codex/daemon_status_unix.go @@ -16,7 +16,10 @@ import ( "github.com/gorilla/websocket" ) -const daemonStatusTimeout = 2 * time.Second +const ( + daemonStatusTimeout = 2 * time.Second + daemonStatusRefreshEvery = 5 * time.Second +) type daemonStatusProvider struct { socketPath string @@ -29,6 +32,9 @@ type daemonStatusProvider struct { reroutedTurns map[daemonTurnKey]string observations []resolvedModelObservation nextSequence uint64 + lastStatusAt time.Time + statusThreads map[string]struct{} + statuses map[string]sessionRuntimeStatus writeMu sync.Mutex } @@ -53,6 +59,9 @@ func (p *daemonStatusProvider) Fetch(ctx context.Context, threadIDs []string) (s if err := p.ensureConnected(ctx); err != nil { return sessionDaemonSnapshot{}, false } + if snapshot, ok := p.cachedStatusSnapshot(threadIDs, time.Now()); ok { + return snapshot, true + } loaded, err := p.loadedThreads(ctx) if err == nil { @@ -96,15 +105,67 @@ func (p *daemonStatusProvider) Fetch(ctx context.Context, threadIDs []string) (s } p.mu.Lock() - observations := append([]resolvedModelObservation(nil), p.observations...) + p.lastStatusAt = time.Now() + p.statusThreads = stringStructSet(threadIDs) + p.statuses = cloneRuntimeStatuses(statuses) + snapshot := p.statusSnapshotLocked(threadIDs) + p.mu.Unlock() + return snapshot, true +} + +func (p *daemonStatusProvider) cachedStatusSnapshot(threadIDs []string, now time.Time) (sessionDaemonSnapshot, bool) { + p.mu.Lock() + defer p.mu.Unlock() + if p.lastStatusAt.IsZero() || now.Sub(p.lastStatusAt) >= daemonStatusRefreshEvery || !sameStringSet(p.statusThreads, threadIDs) { + return sessionDaemonSnapshot{}, false + } + return p.statusSnapshotLocked(threadIDs), true +} + +func (p *daemonStatusProvider) statusSnapshotLocked(threadIDs []string) sessionDaemonSnapshot { + statuses := make(map[string]sessionRuntimeStatus, len(threadIDs)) + for _, threadID := range threadIDs { + if status, ok := p.statuses[threadID]; ok { + statuses[threadID] = status + } + } subscribed := make(map[string]struct{}, len(p.subscribed)) for threadID := range p.subscribed { subscribed[threadID] = struct{}{} } - p.mu.Unlock() return sessionDaemonSnapshot{ - Statuses: statuses, ModelObservations: observations, SubscribedThreads: subscribed, - }, true + Statuses: statuses, + ModelObservations: append([]resolvedModelObservation(nil), p.observations...), + SubscribedThreads: subscribed, + } +} + +func stringStructSet(values []string) map[string]struct{} { + set := make(map[string]struct{}, len(values)) + for _, value := range values { + set[value] = struct{}{} + } + return set +} + +func sameStringSet(set map[string]struct{}, values []string) bool { + if len(set) != len(values) { + return false + } + for _, value := range values { + if _, ok := set[value]; !ok { + return false + } + } + return true +} + +func cloneRuntimeStatuses(statuses map[string]sessionRuntimeStatus) map[string]sessionRuntimeStatus { + cloned := make(map[string]sessionRuntimeStatus, len(statuses)) + for threadID, status := range statuses { + cloned[threadID] = status + } + return cloned } func (p *daemonStatusProvider) unsubscribeMissing(ctx context.Context, threadIDs []string) { @@ -379,6 +440,9 @@ func (p *daemonStatusProvider) disconnect(connection *websocket.Conn) { } p.subscribed = nil p.reroutedTurns = nil + p.lastStatusAt = time.Time{} + p.statusThreads = nil + p.statuses = nil p.mu.Unlock() if current != nil { _ = current.Close() diff --git a/internal/codex/daemon_status_unix_test.go b/internal/codex/daemon_status_unix_test.go index 320098d7..528c566f 100644 --- a/internal/codex/daemon_status_unix_test.go +++ b/internal/codex/daemon_status_unix_test.go @@ -12,6 +12,7 @@ import ( "path/filepath" "sync/atomic" "testing" + "time" "github.com/gorilla/websocket" ) @@ -43,6 +44,8 @@ func TestDaemonStatusProviderReadsExactThreadStates(t *testing.T) { } upgrader := websocket.Upgrader{} var resumedHistorical atomic.Bool + var loadedCalls atomic.Int64 + var readCalls atomic.Int64 server := &http.Server{Handler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { connection, upgradeErr := upgrader.Upgrade(writer, request, nil) if upgradeErr != nil { @@ -65,6 +68,7 @@ func TestDaemonStatusProviderReadsExactThreadStates(t *testing.T) { case "initialize": _ = connection.WriteJSON(map[string]any{"id": *message.ID, "result": map[string]any{"userAgent": "codex/1.0"}}) case "thread/loaded/list": + loadedCalls.Add(1) _ = connection.WriteJSON(map[string]any{"id": *message.ID, "result": map[string]any{ "data": []string{"working", "approval"}, "nextCursor": nil, }}) @@ -91,6 +95,7 @@ func TestDaemonStatusProviderReadsExactThreadStates(t *testing.T) { }}) } case "thread/read": + readCalls.Add(1) threadID, _ := message.Params["threadId"].(string) status := map[string]any{"type": "active", "activeFlags": []string{}} if threadID == "approval" { @@ -132,6 +137,32 @@ func TestDaemonStatusProviderReadsExactThreadStates(t *testing.T) { if resumedHistorical.Load() { t.Fatal("provider subscribed to a thread that was not already loaded") } + loadedBefore, readsBefore := loadedCalls.Load(), readCalls.Load() + cached, exact := provider.Fetch(context.Background(), []string{"working", "approval", "historical"}) + if !exact || cached.Statuses["working"] != sessionRuntimeWorking { + t.Fatalf("cached daemon statuses = %#v, exact=%v", cached.Statuses, exact) + } + if loadedCalls.Load() != loadedBefore || readCalls.Load() != readsBefore { + t.Fatalf("unchanged thread set repeated daemon RPCs: loaded %d->%d reads %d->%d", loadedBefore, loadedCalls.Load(), readsBefore, readCalls.Load()) + } +} + +func TestDaemonStatusCacheExpiresAndRejectsChangedThreadSets(t *testing.T) { + now := time.Now() + provider := &daemonStatusProvider{ + lastStatusAt: now, statusThreads: stringStructSet([]string{"alpha"}), + statuses: map[string]sessionRuntimeStatus{"alpha": sessionRuntimeWorking}, + subscribed: map[string]struct{}{"alpha": {}}, + } + if snapshot, ok := provider.cachedStatusSnapshot([]string{"alpha"}, now.Add(time.Second)); !ok || snapshot.Statuses["alpha"] != sessionRuntimeWorking { + t.Fatalf("fresh matching cache = %#v, ok=%v", snapshot, ok) + } + if _, ok := provider.cachedStatusSnapshot([]string{"bravo"}, now.Add(time.Second)); ok { + t.Fatal("cache accepted a changed thread set") + } + if _, ok := provider.cachedStatusSnapshot([]string{"alpha"}, now.Add(daemonStatusRefreshEvery)); ok { + t.Fatal("cache remained valid at its refresh boundary") + } } func TestDaemonStatusProviderFallsBackWhenSocketIsMissing(t *testing.T) { diff --git a/internal/ui/model.go b/internal/ui/model.go index 26322e11..45fa2ae4 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -118,6 +118,7 @@ type Model struct { benchmarkDetailCache benchmarkDetailTranscriptCache monitorState monitorState + monitorAutoStart bool monitorStartedAt time.Time monitorStoppedAt time.Time monitorBaseline int64 @@ -125,12 +126,15 @@ type Model struct { monitorSamples []monitorSample monitorRequest uint64 monitorFetchActive bool + monitorNextFetch time.Time + monitorResetPaused bool monitorNextSample time.Time monitorBoundaryDue bool monitorGraphStart int64 monitorLastActivity time.Time monitorSessions int monitorSessionData []monitorSession + monitorSelectedID string monitorDismissed map[string]monitorSessionDismissal monitorDismissHover string monitorDismissFlash string @@ -164,8 +168,10 @@ const ( monitorIdle monitorState = iota monitorStarting monitorRunning - monitorStopping - monitorStopped + monitorPausing + monitorPaused + monitorResuming + monitorResetting ) type monitorFetchKind int @@ -174,7 +180,9 @@ const ( monitorFetchStart monitorFetchKind = iota monitorFetchSample monitorFetchBoundary - monitorFetchStop + monitorFetchPause + monitorFetchResume + monitorFetchReset ) type monitorSample struct { @@ -309,8 +317,8 @@ const ( footerButtonView footerButtonRefresh footerButtonQuit - footerButtonMonitorGo - footerButtonMonitorStop + footerButtonMonitorPause + footerButtonMonitorReset footerButtonBenchmarkPrevious footerButtonBenchmarkNext footerButtonBenchmarkSelected @@ -355,6 +363,7 @@ func New(fetcher Fetcher, refreshEvery time.Duration) Model { model := Model{ fetcher: fetcher, refreshEvery: refreshEvery, + monitorAutoStart: true, loading: true, nextRefresh: time.Now().Add(refreshEvery), benchmarkRankMode: benchmarkRankBalanced, @@ -409,7 +418,7 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { return m.pressFooterButton(footerButtonTheme) case "s": if m.meterView == viewMonitor { - return m.pressFooterButton(footerButtonMonitorGo) + return m.pressFooterButton(footerButtonMonitorReset) } if m.meterView == viewBenchmark && !m.benchmarkScopeOpen && m.benchmarkDetail == nil && len(m.benchmarkPlan.Models) > 0 { updated, command := m.pressFooterButton(footerButtonBenchmarkScope) @@ -418,6 +427,10 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { return next, command } case "x": + if m.meterView == viewMonitor && m.monitorSelectedID != "" { + m.dismissSelectedMonitorSession() + return m, nil + } if m.meterView == viewBenchmark { if m.benchmarkScopeOpen { return m.pressFooterButton(footerButtonBenchmarkClose) @@ -474,6 +487,10 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { return m, nil } case "up": + if m.meterView == viewMonitor { + m.selectMonitorSession(-1) + return m, nil + } if m.meterView == viewBenchmark { if m.benchmarkScopeOpen { m.moveBenchmarkScopeCursor(-1) @@ -485,6 +502,10 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { return m, nil } case "down": + if m.meterView == viewMonitor { + m.selectMonitorSession(1) + return m, nil + } if m.meterView == viewBenchmark { if m.benchmarkScopeOpen { m.moveBenchmarkScopeCursor(1) @@ -555,7 +576,7 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { } case "p": if m.meterView == viewMonitor { - return m.pressFooterButton(footerButtonMonitorStop) + return m.pressFooterButton(footerButtonMonitorPause) } } case tea.MouseMsg: @@ -689,13 +710,24 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { m.quotaAPITelemetryIssue = "LOCAL TELEMETRY UNAVAILABLE" } } - if m.monitorState == monitorRunning || m.monitorState == monitorStopping { + if m.monitorState == monitorRunning || m.monitorState == monitorPausing { m.syncMonitorQuotaSnapshot(message.snapshot) m.monitorQuotaError = "" } - } else if m.monitorState == monitorRunning || m.monitorState == monitorStopping { + } else if m.monitorState == monitorRunning || m.monitorState == monitorPausing { m.monitorQuotaError = message.err.Error() } + if m.monitorAutoStart && m.monitorState == monitorIdle { + m.monitorAutoStart = false + if message.err == nil && message.usageErr == nil && m.usageFetcher != nil { + started, _, _ := m.applyMonitorFetch(monitorFetchedMsg{ + kind: monitorFetchStart, usage: message.usage, quota: message.snapshot, at: message.at, + }) + m = started.(Model) + return m, nil + } + return m.beginMonitorFetch(monitorFetchStart) + } case secondMsg: m.phase++ commands := []tea.Cmd{secondTick()} @@ -709,7 +741,7 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { m.monitorNextSample = m.monitorNextSample.Add(monitorSampleInterval) } } - if !m.monitorFetchActive { + if !m.monitorFetchActive && (m.monitorNextFetch.IsZero() || !now.Before(m.monitorNextFetch)) { m.monitorRequest++ m.monitorFetchActive = true kind := monitorFetchSample @@ -731,6 +763,9 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { m.monitorFetchActive = false updated, command, accepted := m.applyMonitorFetch(message) m = updated.(Model) + if m.monitorState == monitorRunning { + m.monitorNextFetch = message.at.Add(m.monitorPollInterval()) + } if accepted && message.kind == monitorFetchBoundary && m.monitorState == monitorRunning { m.captureMonitorSamples(message.at) m.monitorBoundaryDue = false @@ -922,34 +957,23 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { m.loading = true return m, m.fetch() } - case footerButtonMonitorGo: - if m.meterView == viewMonitor && (m.monitorState == monitorIdle || m.monitorState == monitorStopped) { - m.monitorState = monitorStarting - m.monitorStartedAt = time.Time{} - m.monitorStoppedAt = time.Time{} - m.monitorSamples = nil - m.monitorSessionData = nil - m.monitorDismissed = nil - m.monitorDismissHover = "" - m.monitorDismissFlash = "" - m.monitorDismissSeq++ - m.monitorScroll = 0 - m.monitorBoundaryDue = false - 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) + case footerButtonMonitorPause: + if m.meterView != viewMonitor { + break } - case footerButtonMonitorStop: - if m.meterView == viewMonitor && m.monitorState == monitorRunning { - m.monitorState = monitorStopping - m.monitorRequest++ - m.monitorFetchActive = true - return m, m.monitorFetch(monitorFetchStop, m.monitorRequest) + switch m.monitorState { + case monitorRunning: + m.monitorState = monitorPausing + return m.beginMonitorFetch(monitorFetchPause) + case monitorPaused: + m.monitorState = monitorResuming + return m.beginMonitorFetch(monitorFetchResume) + } + case footerButtonMonitorReset: + if m.meterView == viewMonitor && (m.monitorState == monitorRunning || m.monitorState == monitorPaused) { + m.monitorResetPaused = m.monitorState == monitorPaused + m.monitorState = monitorResetting + return m.beginMonitorFetch(monitorFetchReset) } case footerButtonBenchmarkPrevious: if !m.benchmarkRunActive() { @@ -1760,6 +1784,34 @@ func (m Model) fetch() tea.Cmd { } const monitorSampleInterval = 30 * time.Second +const monitorActivePollInterval = time.Second +const monitorIdlePollInterval = 5 * time.Second +const monitorSampleHistoryMax = 4_096 + +func (m Model) beginMonitorFetch(kind monitorFetchKind) (Model, tea.Cmd) { + switch kind { + case monitorFetchStart: + m.monitorState = monitorStarting + case monitorFetchPause: + m.monitorState = monitorPausing + case monitorFetchResume: + m.monitorState = monitorResuming + case monitorFetchReset: + m.monitorState = monitorResetting + } + m.monitorRequest++ + m.monitorFetchActive = true + return m, m.monitorFetch(kind, m.monitorRequest) +} + +func (m Model) monitorPollInterval() time.Duration { + for _, session := range m.monitorSessionData { + if session.active { + return monitorActivePollInterval + } + } + return monitorIdlePollInterval +} func (m Model) monitorFetch(kind monitorFetchKind, sequence uint64) tea.Cmd { return func() tea.Msg { @@ -1783,12 +1835,13 @@ func (m Model) monitorFetch(kind monitorFetchKind, sequence uint64) tea.Cmd { } var usage codex.LiveUsageSnapshot var err error - if kind == monitorFetchStart { + if kind == monitorFetchStart || kind == monitorFetchResume || kind == monitorFetchReset { // Bracket the measured local-token interval inside the account-quota - // interval: quota first at Start, local telemetry first at Stop. + // interval: quota first when starting a segment, local telemetry first + // when pausing one. fetchQuota() usage, err = m.usageFetcher.FetchTokenUsage(context.Background()) - } else if kind == monitorFetchStop { + } else if kind == monitorFetchPause { if freshFetcher, ok := m.usageFetcher.(FreshTokenUsageFetcher); ok { usage, err = freshFetcher.FetchTokenUsageFresh(context.Background()) } else { @@ -1812,7 +1865,7 @@ func (m Model) monitorFetch(kind monitorFetchKind, sequence uint64) tea.Cmd { } func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd, bool) { - if message.kind == monitorFetchStop { + if message.kind == monitorFetchPause { if message.quotaErr == nil { m.syncMonitorQuotaSnapshot(message.quota) } @@ -1820,34 +1873,41 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd, } if message.err != nil { m.monitorError = message.err.Error() - if message.kind == monitorFetchStop { - m.monitorState = monitorStopped + if message.kind == monitorFetchPause { + m.monitorState = monitorPaused m.monitorStoppedAt = message.at - } else if message.kind == monitorFetchStart { - m.monitorState = monitorStopped + } else if message.kind == monitorFetchStart || message.kind == monitorFetchResume { + m.monitorState = monitorPaused + } else if message.kind == monitorFetchReset { + if m.monitorResetPaused { + m.monitorState = monitorPaused + } else { + m.monitorState = monitorRunning + m.monitorNextFetch = message.at.Add(m.monitorPollInterval()) + } + m.monitorResetPaused = false } return m, nil, false } accepted := true switch message.kind { case monitorFetchStart: - m.monitorBaseline = message.usage.TotalTokens - m.monitorLatest = message.usage.TotalTokens - 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.resetMonitorFromSnapshot(message, false) + case monitorFetchReset: + m.resetMonitorFromSnapshot(message, m.monitorResetPaused) + case monitorFetchResume: + if m.monitorUsageMovesBackwards(message.usage) { + m.monitorError = "local Codex token counter moved backwards" + m.monitorState = monitorPaused + accepted = false + break + } + if message.quotaErr == nil { + m.resumeMonitorQuotaSnapshot(message.quota) } 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: + m.resumeMonitorFromSnapshot(message) + case monitorFetchSample, monitorFetchBoundary, monitorFetchPause: if m.monitorUsageMovesBackwards(message.usage) { m.monitorError = "local Codex token counter moved backwards" accepted = false @@ -1860,14 +1920,134 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd, m.syncMonitorSessions(message.usage, message.at) m.monitorSessions = m.visibleMonitorSessionCount() } - if message.kind == monitorFetchStop { - m.monitorState = monitorStopped + if message.kind == monitorFetchPause { + m.monitorState = monitorPaused m.monitorStoppedAt = message.at + m.monitorNextFetch = time.Time{} } } return m, nil, accepted } +func (m *Model) resetMonitorFromSnapshot(message monitorFetchedMsg, paused bool) { + m.monitorStartedAt = message.at + m.monitorStoppedAt = time.Time{} + m.monitorBaseline = message.usage.TotalTokens + m.monitorLatest = message.usage.TotalTokens + m.monitorGraphStart = message.usage.TotalTokens + m.monitorSamples = nil + m.monitorSessionData = nil + m.monitorSelectedID = "" + m.monitorDismissed = nil + m.monitorDismissHover = "" + m.monitorDismissFlash = "" + m.monitorDismissSeq++ + m.monitorScroll = 0 + m.monitorBoundaryDue = false + m.monitorLastActivity = time.Time{} + m.monitorSessions = 0 + m.monitorError = "" + m.monitorQuotaError = "" + m.startMonitorQuotaSnapshot(message.quota) + if message.quotaErr != nil { + m.monitorQuotaError = message.quotaErr.Error() + for index := range m.monitorQuotaWindows { + m.monitorQuotaWindows[index].partial = true + } + } + m.applyMonitorQuotaResult(message) + m.startMonitorSessions(message.usage, message.at) + m.monitorSessions = m.visibleMonitorSessionCount() + m.monitorResetPaused = false + if paused { + m.monitorState = monitorPaused + m.monitorStoppedAt = message.at + m.monitorNextFetch = time.Time{} + m.monitorNextSample = time.Time{} + return + } + m.monitorState = monitorRunning + m.monitorNextFetch = message.at.Add(m.monitorPollInterval()) + m.monitorNextSample = message.at.Add(monitorSampleInterval) +} + +func (m *Model) resumeMonitorFromSnapshot(message monitorFetchedMsg) { + pausedFor := time.Duration(0) + if !m.monitorStoppedAt.IsZero() && message.at.After(m.monitorStoppedAt) { + pausedFor = message.at.Sub(m.monitorStoppedAt) + m.monitorStartedAt = m.monitorStartedAt.Add(pausedFor) + for index := range m.monitorSamples { + m.monitorSamples[index].at = m.monitorSamples[index].at.Add(pausedFor) + } + } + recorded := m.monitorRecordedTokens() + m.monitorBaseline = message.usage.TotalTokens - recorded + m.monitorLatest = message.usage.TotalTokens + m.monitorGraphStart = message.usage.TotalTokens + m.resumeMonitorSessions(message.usage, message.at, pausedFor) + m.monitorSessions = m.visibleMonitorSessionCount() + m.monitorStoppedAt = time.Time{} + m.monitorState = monitorRunning + m.monitorError = "" + m.monitorBoundaryDue = false + m.monitorNextFetch = message.at.Add(m.monitorPollInterval()) + m.monitorNextSample = message.at.Add(monitorSampleInterval) +} + +func (m *Model) resumeMonitorSessions(usage codex.LiveUsageSnapshot, observedAt time.Time, pausedFor time.Duration) { + updates := make(map[string]codex.LiveUsageSession, len(usage.Sessions)) + for _, update := range usage.Sessions { + updates[update.ID] = update + } + for index := range m.monitorSessionData { + session := &m.monitorSessionData[index] + if pausedFor > 0 { + session.startedAt = session.startedAt.Add(pausedFor) + for sampleIndex := range session.samples { + session.samples[sampleIndex].at = session.samples[sampleIndex].at.Add(pausedFor) + } + } + update, ok := updates[session.id] + if !ok { + session.active = false + session.attention = codex.SessionAttentionNone + continue + } + recorded := max(session.latest-session.baseline, int64(0)) + session.baseline = update.TotalTokens - recorded + session.latest = update.TotalTokens + session.graphStart = update.TotalTokens + session.lastActivity = update.LastActivity + session.agentCount = max(session.agentCount, update.AgentCount) + session.active = update.Active + session.attention = update.Attention + session.callSequence = latestModelCallSequence(update.ModelCalls) + session.turnSequence = latestTurnTimingSequence(update.TurnTimings) + if update.WorkingDirectory != "" { + session.workingDirectory = update.WorkingDirectory + } + if dismissal, ok := m.monitorDismissed[session.id]; ok { + dismissal.latest = session.latest + dismissal.lastActivity = session.lastActivity + dismissal.callSequence = session.callSequence + dismissal.turnSequence = session.turnSequence + dismissal.attention = session.attention + m.monitorDismissed[session.id] = dismissal + } + delete(updates, session.id) + } + for _, update := range updates { + m.monitorSessionData = append(m.monitorSessionData, monitorSession{ + id: update.ID, workingDirectory: update.WorkingDirectory, + baseline: update.TotalTokens, latest: update.TotalTokens, graphStart: update.TotalTokens, + startedAt: observedAt, lastActivity: update.LastActivity, agentCount: update.AgentCount, + active: update.Active, attention: update.Attention, displayed: update.Active, + unattributed: update.Unattributed, callSequence: latestModelCallSequence(update.ModelCalls), + turnSequence: latestTurnTimingSequence(update.TurnTimings), + }) + } +} + func (m Model) monitorUsageMovesBackwards(usage codex.LiveUsageSnapshot) bool { if usage.TotalTokens < m.monitorLatest { return true @@ -1944,6 +2124,45 @@ func (m *Model) syncMonitorQuotaSnapshot(snapshot codex.Snapshot) { } } +// resumeMonitorQuotaSnapshot advances the quota baseline by any change observed +// while polling was paused, preserving only the percentage-point delta already +// recorded by the Monitor. +func (m *Model) resumeMonitorQuotaSnapshot(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 { + 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] + delta := window.latestUsed - window.baselineUsed + if !sameOptionalInt64(window.latestReset, meter.Window.ResetsAt) || meter.Window.UsedPercent < window.latestUsed { + window.resetDetected = true + } + window.baselineUsed = meter.Window.UsedPercent - delta + 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 + } + } +} + func monitorQuotaKey(meter codex.Meter) string { duration := int64(-1) if meter.Window.WindowDurationMins != nil { @@ -2173,7 +2392,7 @@ func (m *Model) captureMonitorSamples(at time.Time) { } 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.monitorSamples = appendMonitorSample(m.monitorSamples, monitorSample{at: at, duration: duration, intervalTokens: delta}) m.monitorGraphStart = m.monitorLatest for index := range m.monitorSessionData { @@ -2187,11 +2406,19 @@ func (m *Model) captureMonitorSamples(at time.Time) { } 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.samples = appendMonitorSample(session.samples, monitorSample{at: at, duration: duration, intervalTokens: delta}) session.graphStart = session.latest } } +func appendMonitorSample(samples []monitorSample, sample monitorSample) []monitorSample { + if len(samples) >= monitorSampleHistoryMax { + copy(samples, samples[len(samples)-monitorSampleHistoryMax+1:]) + samples = samples[:monitorSampleHistoryMax-1] + } + return append(samples, sample) +} + func (m *Model) monitorSessionIndex(id string) int { for index := range m.monitorSessionData { if m.monitorSessionData[index].id == id { @@ -2226,6 +2453,67 @@ func (m *Model) scrollMonitorRows(rows int) { m.monitorScroll = min(max(m.monitorScroll+rows, 0), maximum) } +func (m *Model) selectMonitorSession(direction int) { + visible := make([]string, 0, len(m.monitorSessionData)) + selected := -1 + for _, session := range m.monitorSessionData { + if !m.monitorSessionVisible(session) { + continue + } + if session.id == m.monitorSelectedID { + selected = len(visible) + } + visible = append(visible, session.id) + } + if len(visible) == 0 { + m.monitorSelectedID = "" + return + } + if selected < 0 { + if direction < 0 { + selected = len(visible) - 1 + } else { + selected = 0 + } + } else { + selected = min(max(selected+direction, 0), len(visible)-1) + } + m.monitorSelectedID = visible[selected] + pageSize := max(m.monitorPageSize(), 1) + if selected < m.monitorScroll { + m.monitorScroll = selected + } else if selected >= m.monitorScroll+pageSize { + m.monitorScroll = selected - pageSize + 1 + } +} + +func (m *Model) dismissSelectedMonitorSession() { + visible := make([]string, 0, len(m.monitorSessionData)) + selected := -1 + for _, session := range m.monitorSessionData { + if !m.monitorSessionVisible(session) { + continue + } + if session.id == m.monitorSelectedID { + selected = len(visible) + } + visible = append(visible, session.id) + } + if selected < 0 { + m.monitorSelectedID = "" + return + } + m.dismissMonitorSession(m.monitorSelectedID) + visible = append(visible[:selected], visible[selected+1:]...) + if len(visible) == 0 { + m.monitorSelectedID = "" + return + } + m.monitorSelectedID = visible[min(selected, len(visible)-1)] + maximum := max(len(visible)-max(m.monitorPageSize(), 1), 0) + m.monitorScroll = min(m.monitorScroll, 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 cac96dfb..5fd4a4c0 100644 --- a/internal/ui/monitor.go +++ b/internal/ui/monitor.go @@ -82,16 +82,19 @@ func (m Model) renderMonitorArea(width, height int, colors palette) monitorView layout := layoutMonitorArea(width, height) readout := m.renderMonitorReadout(layout.readoutWidth, layout.topHeight, colors) - goLabel, stopLabel := "(S)TART", "STO(P)" - if layout.buttonWidths[0] < lipgloss.Width(goLabel)+2 { - goLabel = "(S)" + toggleLabel, resetLabel := "(P)AUSE", "RE(S)ET" + if m.monitorState == monitorPaused || m.monitorState == monitorResuming { + toggleLabel = "RESUME (P)" } - if layout.buttonWidths[1] < lipgloss.Width(stopLabel)+2 { - stopLabel = "(P)" + if layout.buttonWidths[0] < lipgloss.Width(toggleLabel)+2 { + toggleLabel = "(P)" } - goButton := m.renderMonitorButton(layout.buttonWidths[0], layout.topHeight, goLabel, footerButtonMonitorGo, m.monitorGoEnabled(), colors) - stopButton := m.renderMonitorButton(layout.buttonWidths[1], layout.topHeight, stopLabel, footerButtonMonitorStop, m.monitorStopEnabled(), colors) - controls := lipgloss.JoinHorizontal(lipgloss.Top, goButton, strings.Repeat(" ", layout.gap), stopButton) + if layout.buttonWidths[1] < lipgloss.Width(resetLabel)+2 { + resetLabel = "(S)" + } + toggleButton := m.renderMonitorButton(layout.buttonWidths[0], layout.topHeight, toggleLabel, footerButtonMonitorPause, m.monitorPauseEnabled(), colors) + resetButton := m.renderMonitorButton(layout.buttonWidths[1], layout.topHeight, resetLabel, footerButtonMonitorReset, m.monitorResetEnabled(), colors) + controls := lipgloss.JoinHorizontal(lipgloss.Top, toggleButton, strings.Repeat(" ", layout.gap), resetButton) top := lipgloss.JoinHorizontal(lipgloss.Top, readout, strings.Repeat(" ", layout.gap), controls) graph := m.renderMonitorSessions(layout.width, layout.graphHeight, colors) view := lipgloss.JoinVertical(lipgloss.Left, top, strings.Repeat("\n", layout.gap-1)+graph) @@ -105,26 +108,27 @@ func (m Model) renderMonitorArea(width, height int, colors palette) monitorView } func (m Model) renderMonitorReadout(width, height int, colors palette) string { - state := "READY" - hint := "PRESS S OR CLICK START // LOCAL SESSIONS" + state := "STARTING" + hint := "INITIALIZING LOCAL SESSION MONITOR" switch m.monitorState { case monitorStarting: - state, hint = "ZEROING COUNTER", "SCANNING LOCAL CODEX TELEMETRY" + state, hint = "STARTING", "SCANNING LOCAL CODEX TELEMETRY" case monitorRunning: - state, hint = "RECORDING ●", fmt.Sprintf("LIVE LOCAL SESSIONS %d // P OR CLICK STOP", m.monitorSessions) - case monitorStopping: - state, hint = "FINAL SYNC", "READING APPENDED TOKEN TELEMETRY" - case monitorStopped: - state, hint = "STOPPED", fmt.Sprintf("FINAL CONSUMPTION // LOCAL SESSIONS %d", m.monitorSessions) + state, hint = "MONITORING ●", fmt.Sprintf("LIVE LOCAL SESSIONS %d // P TO PAUSE", m.monitorSessions) + case monitorPausing: + state, hint = "PAUSING", "READING FINAL APPENDED TOKEN TELEMETRY" + case monitorPaused: + state, hint = "PAUSED", fmt.Sprintf("LOCAL SESSIONS %d // P TO RESUME", m.monitorSessions) + case monitorResuming: + state, hint = "RESUMING", "REBASING AFTER PAUSED ACTIVITY" + case monitorResetting: + state, hint = "RESETTING", "ESTABLISHING A FRESH BASELINE" } if m.monitorError != "" { state, hint = "NO TOKEN SIGNAL", m.monitorError } - total := int64(0) - if !m.monitorStartedAt.IsZero() && m.monitorLatest >= m.monitorBaseline { - total = m.monitorLatest - m.monitorBaseline - } + total := m.monitorRecordedTokens() elapsed := m.monitorElapsed(time.Now()) rate := int64(0) if elapsed > 0 { @@ -242,13 +246,17 @@ func (m Model) monitorSessionPage(height int) ([]monitorSession, []int, string) } func (m Model) renderMonitorSessionRow(width, height int, session monitorSession, pageLabel string, colors palette) string { + rowColors := colors + if session.id == m.monitorSelectedID { + rowColors.primary = colors.accent + } metricsWidth, graphWidth, ok := monitorSessionColumnWidths(width) if !ok { - return m.renderMonitorGraphSamples(width, height, session.samples, "TOKENS", colors) + return m.renderMonitorGraphSamples(width, height, session.samples, "TOKENS", rowColors) } - metrics := m.renderMonitorSessionMetrics(metricsWidth, height, session, pageLabel, colors) + metrics := m.renderMonitorSessionMetrics(metricsWidth, height, session, pageLabel, rowColors) title := "TOKEN BARS" - graph := m.renderMonitorGraphSamples(graphWidth, height, session.samples, title, colors) + graph := m.renderMonitorGraphSamples(graphWidth, height, session.samples, title, rowColors) return lipgloss.JoinHorizontal(lipgloss.Top, metrics, " ", graph) } @@ -328,7 +336,7 @@ func (m Model) renderMonitorSessionMetrics(width, height int, session monitorSes lines[len(lines)-1] = colors.dimmed().Render(ansi.Truncate(pageLabel+" // PGUP/PGDN", innerWidth, "")) } borderColor := colors.primary - if session.attention != codex.SessionAttentionNone { + if session.attention != codex.SessionAttentionNone && session.id != m.monitorSelectedID { borderColor = colors.warning } action := "" @@ -339,14 +347,21 @@ func (m Model) renderMonitorSessionMetrics(width, height int, session monitorSes } func (m Model) renderMonitorSessionDismiss(id string, colors palette) string { + label := monitorDismissLabel + if m.monitorSelectedID == id { + label = "[X]" + } style := lipgloss.NewStyle().Foreground(colors.dim).Background(colors.background) + if m.monitorSelectedID == id { + style = style.Bold(true).Foreground(colors.accent) + } if m.monitorDismissHover == id { style = style.Bold(true).Foreground(colors.accent) } if m.monitorDismissFlash == id { style = style.Bold(true).Foreground(colors.background).Background(colors.primary) } - return style.Render(monitorDismissLabel) + return style.Render(label) } func monitorSessionDismissRect(metricsWidth, rowY int) (monitorRect, bool) { @@ -569,9 +584,9 @@ func (m Model) renderMonitorGraphSamples(width, height int, samples []monitorSam } if len(samples) == 0 { message := "WAITING FOR FIRST SAMPLE" - if m.monitorState == monitorIdle { - message = "PRESS START TO ARM RECORDER" - } else if m.monitorState == monitorStopped { + if m.monitorState == monitorIdle || m.monitorState == monitorStarting { + message = "STARTING MONITOR" + } else if m.monitorState == monitorPaused { message = "NO COMPLETE 30 SEC SAMPLE" } message = ansi.Truncate(message, innerWidth, "") @@ -636,11 +651,11 @@ func (m Model) monitorButtonAt(x, y int) footerButtonID { dashboard := m.dashboardLayout() area := layoutMonitorArea(dashboard.contentWidth, dashboard.meterHeight) localX, localY := x-2, y-dashboard.meterY - if m.monitorGoEnabled() && area.goRect.contains(localX, localY) { - return footerButtonMonitorGo + if m.monitorPauseEnabled() && area.goRect.contains(localX, localY) { + return footerButtonMonitorPause } - if m.monitorStopEnabled() && area.stopRect.contains(localX, localY) { - return footerButtonMonitorStop + if m.monitorResetEnabled() && area.stopRect.contains(localX, localY) { + return footerButtonMonitorReset } return footerButtonNone } @@ -672,12 +687,12 @@ func (m Model) monitorSessionDismissAt(x, y int) (string, bool) { return "", false } -func (m Model) monitorGoEnabled() bool { - return m.monitorState == monitorIdle || m.monitorState == monitorStopped +func (m Model) monitorPauseEnabled() bool { + return m.monitorState == monitorRunning || m.monitorState == monitorPaused } -func (m Model) monitorStopEnabled() bool { - return m.monitorState == monitorRunning +func (m Model) monitorResetEnabled() bool { + return m.monitorState == monitorRunning || m.monitorState == monitorPaused } func (m Model) monitorElapsed(now time.Time) time.Duration { @@ -685,7 +700,7 @@ func (m Model) monitorElapsed(now time.Time) time.Duration { return 0 } end := now - if m.monitorState == monitorStopped && !m.monitorStoppedAt.IsZero() { + if m.monitorState == monitorPaused && !m.monitorStoppedAt.IsZero() { end = m.monitorStoppedAt } if end.Before(m.monitorStartedAt) { @@ -700,7 +715,7 @@ func (m Model) monitorSessionElapsed(session monitorSession, now time.Time) time start = m.monitorStartedAt } end := now - if m.monitorState == monitorStopped && !m.monitorStoppedAt.IsZero() { + if m.monitorState == monitorPaused && !m.monitorStoppedAt.IsZero() { end = m.monitorStoppedAt } if start.IsZero() || end.Before(start) { diff --git a/internal/ui/monitor_test.go b/internal/ui/monitor_test.go index bcc00248..85090434 100644 --- a/internal/ui/monitor_test.go +++ b/internal/ui/monitor_test.go @@ -16,33 +16,20 @@ import ( "github.com/merefield/codexometer/internal/codex" ) -func TestMonitorGoSampleAndStopLifecycle(t *testing.T) { +func TestMonitorAutoStartPauseResumeAndResetLifecycle(t *testing.T) { baseline := int64(1_000) model := New(stubLiveFetcher{stubFetcher: stubFetcher{snapshot: codex.DemoSnapshot()}}, time.Minute) model.snapshot = codex.DemoSnapshot() model.loading = false model.meterView = viewMonitor - - updated, command := model.Update(key('s')) - model = updated.(Model) - if command == nil || model.monitorState != monitorStarting || model.flashedButton != footerButtonMonitorGo { - t.Fatalf("Go did not arm monitor: state=%d flash=%d command=%v", model.monitorState, model.flashedButton, command) - } - flashed := model.renderMonitorButton(14, 6, "(S)TART", footerButtonMonitorGo, model.monitorGoEnabled(), paletteFor(themeHacker)) - wantFlash := lipgloss.NewStyle().Bold(true).Foreground(paletteFor(themeHacker).background).Background(paletteFor(themeHacker).primary).Render("(S)TART") - if !strings.Contains(flashed, wantFlash) { - t.Fatal("Start hotkey did not visibly pulse after entering the starting state") - } - sequence := model.monitorRequest startedAt := time.Unix(100, 0) - updated, command = model.Update(monitorFetchedMsg{ - kind: monitorFetchStart, sequence: sequence, usage: usageWithTokens(baseline), at: startedAt, + updated, command := model.Update(fetchedMsg{ + snapshot: codex.DemoSnapshot(), usage: usageWithTokens(baseline), at: startedAt, }) model = updated.(Model) - if model.monitorState != monitorRunning || model.monitorBaseline != baseline || command != nil { - t.Fatalf("baseline was not established: %#v", model) + if command != nil || model.monitorState != monitorRunning || model.monitorBaseline != baseline { + t.Fatalf("Monitor did not auto-start from the initial refresh: %#v", model) } - model.monitorRequest++ updated, _ = model.Update(monitorFetchedMsg{ kind: monitorFetchSample, sequence: model.monitorRequest, @@ -68,21 +55,119 @@ func TestMonitorGoSampleAndStopLifecycle(t *testing.T) { updated, command = model.Update(key('p')) model = updated.(Model) - if command == nil || model.monitorState != monitorStopping || model.flashedButton != footerButtonMonitorStop { - t.Fatalf("Stop did not request final sync: state=%d flash=%d command=%v", model.monitorState, model.flashedButton, command) + if command == nil || model.monitorState != monitorPausing || model.flashedButton != footerButtonMonitorPause { + t.Fatalf("Pause did not request final sync: state=%d flash=%d command=%v", model.monitorState, model.flashedButton, command) } - stopSequence := model.monitorRequest + pauseSequence := model.monitorRequest updated, _ = model.Update(monitorFetchedMsg{ - kind: monitorFetchStop, sequence: stopSequence, + kind: monitorFetchPause, sequence: pauseSequence, usage: usageWithTokens(1_400), at: startedAt.Add(45 * time.Second), }) model = updated.(Model) - if model.monitorState != monitorStopped || model.monitorLatest-model.monitorBaseline != 400 { + if model.monitorState != monitorPaused || model.monitorRecordedTokens() != 400 { t.Fatalf("final usage was not recorded: state=%d total=%d", model.monitorState, model.monitorLatest-model.monitorBaseline) } if len(model.monitorSamples) != 1 { t.Fatalf("partial final interval was incorrectly plotted as a 30-second bucket: %#v", model.monitorSamples) } + + updated, command = model.Update(key('p')) + model = updated.(Model) + if command == nil || model.monitorState != monitorResuming { + t.Fatalf("Resume did not request a fresh baseline: state=%d command=%v", model.monitorState, command) + } + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchResume, sequence: model.monitorRequest, + usage: usageWithTokens(1_600), at: startedAt.Add(75 * time.Second), + }) + model = updated.(Model) + if model.monitorState != monitorRunning || model.monitorRecordedTokens() != 400 { + t.Fatalf("Resume counted paused activity: state=%d total=%d", model.monitorState, model.monitorRecordedTokens()) + } + + updated, command = model.Update(key('s')) + model = updated.(Model) + if command == nil || model.monitorState != monitorResetting || model.flashedButton != footerButtonMonitorReset { + t.Fatalf("Reset did not request a fresh baseline: state=%d flash=%d", model.monitorState, model.flashedButton) + } + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchReset, sequence: model.monitorRequest, + usage: usageWithTokens(1_700), quota: codex.DemoSnapshot(), at: startedAt.Add(80 * time.Second), + }) + model = updated.(Model) + if model.monitorState != monitorRunning || model.monitorRecordedTokens() != 0 || len(model.monitorSamples) != 0 { + t.Fatalf("Reset did not clear the running measurement: %#v", model) + } +} + +func TestMonitorResetPreservesPausedState(t *testing.T) { + startedAt := time.Unix(500, 0) + model := Model{ + meterView: viewMonitor, monitorState: monitorPaused, + monitorStartedAt: startedAt, monitorStoppedAt: startedAt.Add(time.Minute), + monitorBaseline: 100, monitorLatest: 250, + monitorSamples: []monitorSample{{intervalTokens: 150}}, + } + updated, command := model.Update(key('s')) + model = updated.(Model) + if command == nil || model.monitorState != monitorResetting || !model.monitorResetPaused { + t.Fatalf("paused Reset was not armed correctly: %#v", model) + } + resetAt := startedAt.Add(2 * time.Minute) + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchReset, sequence: model.monitorRequest, + usage: usageWithTokens(500), at: resetAt, + }) + model = updated.(Model) + if model.monitorState != monitorPaused || model.monitorRecordedTokens() != 0 || + !model.monitorStoppedAt.Equal(resetAt) || !model.monitorNextFetch.IsZero() || len(model.monitorSamples) != 0 { + t.Fatalf("paused Reset changed run state or retained history: %#v", model) + } +} + +func TestMonitorFailedResetRestoresPreviousRunState(t *testing.T) { + now := time.Unix(700, 0) + for _, test := range []struct { + name string + paused bool + want monitorState + }{ + {name: "running", want: monitorRunning}, + {name: "paused", paused: true, want: monitorPaused}, + } { + t.Run(test.name, func(t *testing.T) { + model := Model{ + monitorState: monitorResetting, monitorRequest: 1, + monitorResetPaused: test.paused, monitorFetchActive: true, + } + updated, _ := model.Update(monitorFetchedMsg{ + kind: monitorFetchReset, sequence: 1, err: errors.New("telemetry offline"), at: now, + }) + model = updated.(Model) + if model.monitorState != test.want || model.monitorResetPaused { + t.Fatalf("failed Reset state = %d, reset-paused=%t; want %d, false", model.monitorState, model.monitorResetPaused, test.want) + } + }) + } +} + +func TestMonitorRejectedResumeDoesNotRebaseQuota(t *testing.T) { + now := time.Unix(800, 0) + model := Model{ + monitorState: monitorResuming, monitorRequest: 1, + monitorLatest: 200, + monitorQuotaWindows: []monitorQuotaWindow{{ + key: "primary", baselineUsed: 10, latestUsed: 12, + }}, + } + updated, _ := model.Update(monitorFetchedMsg{ + kind: monitorFetchResume, sequence: 1, usage: usageWithTokens(100), + quota: monitorQuotaSnapshot(30, now.Add(time.Hour).Unix()), at: now, + }) + model = updated.(Model) + if model.monitorState != monitorPaused || model.monitorQuotaWindows[0].baselineUsed != 10 || model.monitorQuotaWindows[0].latestUsed != 12 { + t.Fatalf("rejected Resume changed quota state: %#v", model.monitorQuotaWindows) + } } func TestMonitorTickSamplesOnlyWhileRunningAndIgnoresStaleResults(t *testing.T) { @@ -172,7 +257,7 @@ func TestMonitorTracksCompactModelCallOutputAndTTFTStatsSinceStart(t *testing.T) model = updated.(Model) session := model.monitorSessionData[0] if session.modelCalls != 0 || session.latestTTFTOK { - t.Fatalf("pre-Start response telemetry was not baselined: %#v", session) + t.Fatalf("pre-baseline response telemetry was not excluded: %#v", session) } model.monitorRequest++ @@ -361,10 +446,10 @@ func TestMonitorSuppressesStaleAndMissingQuotaEstimates(t *testing.T) { } model.monitorQuotaWindows[0].stale = false - model.monitorState = monitorStopping + model.monitorState = monitorPausing model.monitorRequest = 4 updated, _ = model.Update(monitorFetchedMsg{ - kind: monitorFetchStop, sequence: 4, usage: codex.LiveUsageSnapshot{TotalTokens: 200}, + kind: monitorFetchPause, sequence: 4, usage: codex.LiveUsageSnapshot{TotalTokens: 200}, quotaErr: errors.New("final quota offline"), at: startedAt.Add(time.Minute), }) model = updated.(Model) @@ -383,15 +468,15 @@ func TestMonitorQuotaReadsBracketTheLocalTokenInterval(t *testing.T) { t.Fatal(message.err) } if want := []string{"quota", "usage"}; !reflect.DeepEqual(fetcher.calls, want) { - t.Fatalf("Start reads = %v; want %v", fetcher.calls, want) + t.Fatalf("initial baseline reads = %v; want %v", fetcher.calls, want) } fetcher.calls = nil - if message := model.monitorFetch(monitorFetchStop, 2)().(monitorFetchedMsg); message.err != nil { + if message := model.monitorFetch(monitorFetchPause, 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) + t.Fatalf("Pause reads = %v; want %v", fetcher.calls, want) } } @@ -727,17 +812,17 @@ func TestMonitorSurfacesUnavailableAndFailedFinalUsage(t *testing.T) { kind: monitorFetchStart, sequence: 1, err: errors.New("local telemetry unavailable"), at: time.Now(), }) model = updated.(Model) - if model.monitorState != monitorStopped || !strings.Contains(model.monitorError, "local telemetry unavailable") { + if model.monitorState != monitorPaused || !strings.Contains(model.monitorError, "local telemetry unavailable") { t.Fatalf("missing usage was not surfaced: %#v", model) } - model.monitorState = monitorStopping + model.monitorState = monitorPausing model.monitorRequest = 2 updated, _ = model.Update(monitorFetchedMsg{ - kind: monitorFetchStop, sequence: 2, err: errors.New("offline"), at: time.Now(), + kind: monitorFetchPause, sequence: 2, err: errors.New("offline"), at: time.Now(), }) model = updated.(Model) - if model.monitorState != monitorStopped || model.monitorError != "offline" { + if model.monitorState != monitorPaused || model.monitorError != "offline" { t.Fatalf("failed final sync was not surfaced: %#v", model) } } @@ -757,14 +842,14 @@ func TestMonitorFetchUsesConfiguredLocalSource(t *testing.T) { } } -func TestMonitorStopUsesFreshLocalSourceWhenAvailable(t *testing.T) { +func TestMonitorPauseUsesFreshLocalSourceWhenAvailable(t *testing.T) { fetcher := &stubFreshLiveFetcher{ stubFetcher: stubFetcher{snapshot: codex.DemoSnapshot()}, ordinary: codex.LiveUsageSnapshot{TotalTokens: 100}, fresh: codex.LiveUsageSnapshot{TotalTokens: 175}, } model := New(fetcher, time.Minute) - message := model.monitorFetch(monitorFetchStop, 9)().(monitorFetchedMsg) + message := model.monitorFetch(monitorFetchPause, 9)().(monitorFetchedMsg) if message.err != nil || message.usage.TotalTokens != 175 || fetcher.freshCalls != 1 || fetcher.ordinaryCalls != 0 { t.Fatalf("final read did not use fresh discovery: message=%#v fetcher=%#v", message, fetcher) } @@ -781,7 +866,7 @@ func TestMonitorViewIsResponsiveAndGraphAutoScales(t *testing.T) { } output := model.render() plain := ansi.Strip(output) - for _, want := range []string{"MONITOR READOUT", "6,250 TOKENS", "(S)TART", "STO(P)", "LOCAL TOKEN BARS", "AUTO 0-10K", "█", "░"} { + for _, want := range []string{"MONITOR READOUT", "6,250 TOKENS", "(P)AUSE", "RE(S)ET", "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) } @@ -802,8 +887,8 @@ func TestMonitorRecordingLampPulsesBetweenDarkAndBrightRed(t *testing.T) { bright := model.renderMonitorReadout(60, 8, colors) model.phase = 1 dark := model.renderMonitorReadout(60, 8, colors) - wantBright := lipgloss.NewStyle().Bold(true).Foreground(colors.danger).Render("RECORDING ●") - wantDark := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#7A2633")).Render("RECORDING ●") + wantBright := lipgloss.NewStyle().Bold(true).Foreground(colors.danger).Render("MONITORING ●") + wantDark := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#7A2633")).Render("MONITORING ●") if !strings.Contains(bright, wantBright) || !strings.Contains(dark, wantDark) || ansi.Strip(bright) != ansi.Strip(dark) { t.Fatal("recording lamp did not pulse red intensity while keeping a stable label") } @@ -842,7 +927,7 @@ func TestMonitorSessionProminentlyDistinguishesAttentionReason(t *testing.T) { func TestMonitorLargeButtonsAreClickableAcrossTheirBoxes(t *testing.T) { model := Model{ snapshot: codex.DemoSnapshot(), width: 100, height: 36, - meterView: viewMonitor, monitorState: monitorIdle, + meterView: viewMonitor, monitorState: monitorRunning, } colors := paletteFor(model.theme) dashboard := model.dashboardLayout() @@ -857,7 +942,7 @@ func TestMonitorLargeButtonsAreClickableAcrossTheirBoxes(t *testing.T) { for _, test := range []struct { rect monitorRect want footerButtonID - }{{geometry.goRect, footerButtonMonitorGo}, {geometry.stopRect, footerButtonNone}} { + }{{geometry.goRect, footerButtonMonitorPause}, {geometry.stopRect, footerButtonMonitorReset}} { // Hit an otherwise blank spot inside the large box, not merely its label. x := originX + test.rect.x + 1 y := originY + test.rect.y + 1 @@ -865,27 +950,17 @@ func TestMonitorLargeButtonsAreClickableAcrossTheirBoxes(t *testing.T) { t.Errorf("button hit = %d, want %d at %d,%d", got, test.want, x, y) } } - model.monitorState = monitorRunning - stopX := originX + geometry.stopRect.x + 1 - stopY := originY + geometry.stopRect.y + 1 hoverX := originX + geometry.goRect.x + 1 hoverY := originY + geometry.goRect.y + 1 - if got := model.monitorButtonAt(stopX, stopY); got != footerButtonMonitorStop { - t.Errorf("enabled Stop button hit = %d, want %d", got, footerButtonMonitorStop) - } - if got := model.monitorButtonAt(hoverX, hoverY); got != footerButtonNone { - t.Errorf("disabled Start button hit = %d, want none", got) - } - model.monitorState = monitorIdle updated, command := model.Update(tea.MouseMotionMsg{X: hoverX, Y: hoverY}) model = updated.(Model) - if command != nil || model.hoveredButton != footerButtonMonitorGo { - t.Fatal("hovering the Go box did not select it") + if command != nil || model.hoveredButton != footerButtonMonitorPause { + t.Fatal("hovering the Pause box did not select it") } - hovered := model.renderMonitorButton(14, 6, "(S)TART", footerButtonMonitorGo, true, colors) - wantHover := lipgloss.NewStyle().Bold(true).Foreground(colors.accent).Background(colors.background).Render("(S)TART") + hovered := model.renderMonitorButton(14, 6, "(P)AUSE", footerButtonMonitorPause, true, colors) + wantHover := lipgloss.NewStyle().Bold(true).Foreground(colors.accent).Background(colors.background).Render("(P)AUSE") if !strings.Contains(hovered, wantHover) { - t.Fatal("hovering the Go box did not highlight its label") + t.Fatal("hovering the Pause box did not highlight its label") } updated, command = model.Update(tea.MouseClickMsg{ @@ -893,8 +968,8 @@ func TestMonitorLargeButtonsAreClickableAcrossTheirBoxes(t *testing.T) { Button: tea.MouseLeft, }) model = updated.(Model) - if command == nil || model.monitorState != monitorStarting { - t.Fatal("clicking the Go box did not start the monitor") + if command == nil || model.monitorState != monitorPausing { + t.Fatal("clicking the Pause box did not pause the monitor") } } @@ -909,7 +984,7 @@ func TestMonitorHeaderComponentsHonorAllocatedDimensions(t *testing.T) { } for index, width := range geometry.buttonWidths { - button := model.renderMonitorButton(width, geometry.topHeight, "BUTTON", footerButtonMonitorGo, true, colors) + button := model.renderMonitorButton(width, geometry.topHeight, "BUTTON", footerButtonMonitorPause, true, colors) if gotWidth, gotHeight := lipgloss.Width(button), lipgloss.Height(button); gotWidth != width || gotHeight != geometry.topHeight { t.Errorf("%dx%d button %d rendered %dx%d, want %dx%d", size.width, size.height, index, gotWidth, gotHeight, width, geometry.topHeight) } @@ -919,7 +994,10 @@ func TestMonitorHeaderComponentsHonorAllocatedDimensions(t *testing.T) { func TestMonitorButtonBoxesMatchEnabledHitSurfacesAcrossSizes(t *testing.T) { for _, size := range []struct{ width, height int }{{40, 16}, {40, 24}, {60, 24}, {100, 36}, {160, 45}} { - for _, state := range []monitorState{monitorIdle, monitorRunning} { + for _, state := range []monitorState{ + monitorIdle, monitorStarting, monitorRunning, monitorPausing, + monitorPaused, monitorResuming, monitorResetting, + } { model := Model{ snapshot: codex.DemoSnapshot(), width: size.width, height: size.height, meterView: viewMonitor, monitorState: state, @@ -931,8 +1009,8 @@ func TestMonitorButtonBoxesMatchEnabledHitSurfacesAcrossSizes(t *testing.T) { id footerButtonID enabled bool }{ - {geometry.goRect, footerButtonMonitorGo, model.monitorGoEnabled()}, - {geometry.stopRect, footerButtonMonitorStop, model.monitorStopEnabled()}, + {geometry.goRect, footerButtonMonitorPause, model.monitorPauseEnabled()}, + {geometry.stopRect, footerButtonMonitorReset, model.monitorResetEnabled()}, } { want := footerButtonNone if button.enabled { @@ -981,6 +1059,110 @@ func TestMonitorGraphUsesVerticalGranularBars(t *testing.T) { } } +func TestMonitorPollingAdaptsToSessionActivity(t *testing.T) { + startedAt := time.Unix(3_000, 0) + model := Model{ + monitorState: monitorRunning, monitorStartedAt: startedAt, + monitorNextFetch: startedAt.Add(time.Second), monitorNextSample: startedAt.Add(time.Minute), + monitorSessionData: []monitorSession{{id: "active", active: true, displayed: true}}, + } + updated, _ := model.Update(secondMsg(startedAt.Add(500 * time.Millisecond))) + model = updated.(Model) + if model.monitorFetchActive { + t.Fatal("active Monitor polled before its one-second deadline") + } + updated, _ = model.Update(secondMsg(startedAt.Add(time.Second))) + model = updated.(Model) + if !model.monitorFetchActive { + t.Fatal("active Monitor did not poll at its one-second deadline") + } + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchSample, sequence: model.monitorRequest, + usage: codex.LiveUsageSnapshot{}, at: startedAt.Add(time.Second), + }) + model = updated.(Model) + if want := startedAt.Add(6 * time.Second); !model.monitorNextFetch.Equal(want) { + t.Fatalf("inactive Monitor next poll = %s, want %s", model.monitorNextFetch, want) + } + updated, _ = model.Update(secondMsg(startedAt.Add(2 * time.Second))) + model = updated.(Model) + if model.monitorFetchActive { + t.Fatal("inactive Monitor retained the one-second polling cadence") + } + updated, _ = model.Update(secondMsg(startedAt.Add(6 * time.Second))) + model = updated.(Model) + if !model.monitorFetchActive { + t.Fatal("inactive Monitor did not poll at its five-second deadline") + } +} + +func TestMonitorSampleHistoryIsBounded(t *testing.T) { + samples := make([]monitorSample, monitorSampleHistoryMax) + for index := range samples { + samples[index].intervalTokens = int64(index) + } + samples = appendMonitorSample(samples, monitorSample{intervalTokens: 9_999}) + if len(samples) != monitorSampleHistoryMax { + t.Fatalf("bounded history length = %d, want %d", len(samples), monitorSampleHistoryMax) + } + if samples[0].intervalTokens != 1 || samples[len(samples)-1].intervalTokens != 9_999 { + t.Fatalf("bounded history retained wrong range: first=%d last=%d", samples[0].intervalTokens, samples[len(samples)-1].intervalTokens) + } +} + +func TestMonitorKeyboardSelectsHighlightsAndClosesSessions(t *testing.T) { + model := Model{ + snapshot: codex.DemoSnapshot(), width: 100, height: 36, + meterView: viewMonitor, monitorState: monitorRunning, monitorStartedAt: time.Now(), + monitorSessionData: []monitorSession{ + {id: "alpha", active: true, displayed: true}, + {id: "bravo", active: true, displayed: true}, + {id: "charlie", active: true, displayed: true}, + }, + } + updated, _ := model.Update(specialKey(tea.KeyDown)) + model = updated.(Model) + if model.monitorSelectedID != "alpha" { + t.Fatalf("first Down selected %q, want alpha", model.monitorSelectedID) + } + updated, _ = model.Update(specialKey(tea.KeyDown)) + model = updated.(Model) + if model.monitorSelectedID != "bravo" { + t.Fatalf("second Down selected %q, want bravo", model.monitorSelectedID) + } + updated, _ = model.Update(specialKey(tea.KeyUp)) + model = updated.(Model) + if model.monitorSelectedID != "alpha" { + t.Fatalf("Up selected %q, want alpha", model.monitorSelectedID) + } + + colors := paletteFor(themeHacker) + selected := model.renderMonitorSessionRow(80, 8, model.monitorSessionData[0], "", colors) + if !strings.Contains(ansi.Strip(selected), "[X]") { + t.Fatal("keyboard-selected Monitor row did not expose its X close shortcut") + } + model.monitorSelectedID = "" + unselected := model.renderMonitorSessionRow(80, 8, model.monitorSessionData[0], "", colors) + if selected == unselected { + t.Fatal("keyboard-selected Monitor row did not receive a distinct highlight") + } + + model.monitorSelectedID = "alpha" + updated, _ = model.Update(key('x')) + model = updated.(Model) + if model.monitorSelectedID != "bravo" || model.visibleMonitorSessionCount() != 2 { + t.Fatalf("X did not close alpha and advance selection: selected=%q visible=%d", model.monitorSelectedID, model.visibleMonitorSessionCount()) + } + + model.monitorDismissed = nil + model.monitorSelectedID = "" + updated, _ = model.Update(specialKey(tea.KeyUp)) + model = updated.(Model) + if model.monitorSelectedID != "charlie" { + t.Fatalf("first Up selected %q, want bottom row charlie", model.monitorSelectedID) + } +} + func TestMonitorFormattingAndScaleHelpers(t *testing.T) { for input, want := range map[int64]string{0: "0", 999: "999", 1_000: "1,000", -1_234_567: "-1,234,567", math.MinInt64: "-9,223,372,036,854,775,808"} { if got := formatTokens(input); got != want { diff --git a/internal/ui/tabs_test.go b/internal/ui/tabs_test.go index 2aa3fff0..fd807185 100644 --- a/internal/ui/tabs_test.go +++ b/internal/ui/tabs_test.go @@ -175,7 +175,7 @@ func TestQuotaStyleIsRememberedAcrossMainTabNavigation(t *testing.T) { } } -func TestVSelectsQuotaViewAndSOnlyStartsMonitor(t *testing.T) { +func TestVSelectsQuotaViewAndMonitorShortcutsStayScoped(t *testing.T) { model := Model{meterView: viewBars} for _, want := range []meterViewID{viewConsumptionPace, viewPie, viewFuel, viewBars} { updated, command := model.Update(key('v')) @@ -191,11 +191,18 @@ func TestVSelectsQuotaViewAndSOnlyStartsMonitor(t *testing.T) { t.Fatal("S changed the Quota view") } - model = Model{meterView: viewMonitor, monitorState: monitorIdle} + model = Model{meterView: viewMonitor, monitorState: monitorRunning} updated, command = model.Update(key('s')) model = updated.(Model) - if command == nil || model.monitorState != monitorStarting || model.flashedButton != footerButtonMonitorGo { - t.Fatalf("Monitor S did not start: state=%d flash=%d", model.monitorState, model.flashedButton) + if command == nil || model.monitorState != monitorResetting || model.flashedButton != footerButtonMonitorReset { + t.Fatalf("Monitor S did not reset: state=%d flash=%d", model.monitorState, model.flashedButton) + } + + model = Model{meterView: viewMonitor, monitorState: monitorRunning} + updated, command = model.Update(key('p')) + model = updated.(Model) + if command == nil || model.monitorState != monitorPausing || model.flashedButton != footerButtonMonitorPause { + t.Fatalf("Monitor P did not pause: state=%d flash=%d", model.monitorState, model.flashedButton) } model = Model{meterView: viewBenchmark} From 958d308faaa08066a0befc413ad591ee82e622ea Mon Sep 17 00:00:00 2001 From: merefield Date: Sun, 23 Aug 2026 11:39:13 +0100 Subject: [PATCH 2/6] ENH: show Monitor activity status --- README.md | 10 +++-- internal/codex/live_usage.go | 36 +++++++++++++----- internal/codex/live_usage_test.go | 28 ++++++++++++++ internal/ui/model.go | 62 ++++++++++++++++++------------- internal/ui/monitor.go | 10 ++--- internal/ui/monitor_test.go | 13 ++++--- internal/ui/tabs.go | 38 ++++++++++++------- internal/ui/tabs_test.go | 46 ++++++++++++++++++----- internal/ui/theme.go | 6 +++ main.go | 1 + 10 files changed, 177 insertions(+), 73 deletions(-) diff --git a/README.md b/README.md index c572f5e9..2ff14107 100644 --- a/README.md +++ b/README.md @@ -579,9 +579,13 @@ The other top-level views are: token telemetry and shows total observed tokens, elapsed time, and average rate; clickable Pause/Resume and Reset controls sit beside it. Active sessions are checked once per second and the idle cadence relaxes to five seconds. - 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`. Each row compactly shows + The Monitor tab light and status label pulse between the current theme's + highlight and dim colors while the shared app server is working, remain green + while it is reachable but idle, and turn red when it is unreachable. They + remain dim while paused or when app-server health is unavailable. 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`. 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 diff --git a/internal/codex/live_usage.go b/internal/codex/live_usage.go index dc46f1f2..01919aa0 100644 --- a/internal/codex/live_usage.go +++ b/internal/codex/live_usage.go @@ -29,14 +29,17 @@ const ( // totals increase monotonically; APIEqPendingCalls is an instantaneous count // kept separate until daemon model resolution or requested-model fallback. type LiveUsageSnapshot struct { - TotalTokens int64 - LastActivity time.Time - SessionCount int - Sessions []LiveUsageSession - APIEqUSD float64 - APIEqPricedCalls int64 - APIEqUnpricedCalls int64 - APIEqPendingCalls int64 + TotalTokens int64 + LastActivity time.Time + SessionCount int + Sessions []LiveUsageSession + AppServerStatusKnown bool + AppServerUp bool + AppServerWorking bool + APIEqUSD float64 + APIEqPricedCalls int64 + APIEqUnpricedCalls int64 + APIEqPendingCalls int64 } // LiveUsageSession is one independently started local Codex session. Token @@ -286,7 +289,7 @@ func (r *LiveUsageReader) FetchTokenUsage(ctx context.Context) (LiveUsageSnapsho } // FetchTokenUsageFresh forces a complete session discovery before consuming -// telemetry. The Monitor uses this for its final Stop reading so a recently +// telemetry. The Monitor uses this for its final Pause reading so a recently // resumed rollout in an older date directory cannot be missed. func (r *LiveUsageReader) FetchTokenUsageFresh(ctx context.Context) (LiveUsageSnapshot, error) { return r.fetchTokenUsage(ctx, true) @@ -312,10 +315,20 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover } exactStatuses := map[string]sessionRuntimeStatus(nil) + appServerStatusKnown := r.statusProvider != nil + appServerUp := false + appServerWorking := false r.daemonSubscribedThreads = nil if r.statusProvider != nil { if daemonSnapshot, exact := r.statusProvider.Fetch(ctx, r.observedThreadIDs(now)); exact { + appServerUp = true exactStatuses = daemonSnapshot.Statuses + for _, status := range exactStatuses { + if status == sessionRuntimeWorking { + appServerWorking = true + break + } + } r.ingestResolvedModelObservations(daemonSnapshot.ModelObservations) r.daemonSubscribedThreads = daemonSnapshot.SubscribedThreads } @@ -352,7 +365,10 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover return LiveUsageSnapshot{ TotalTokens: r.totalTokens, LastActivity: r.lastActivity, SessionCount: activeSessions, Sessions: sessions, - APIEqUSD: r.apiEqUSD, APIEqPricedCalls: r.apiEqPricedCalls, + AppServerStatusKnown: appServerStatusKnown, + AppServerUp: appServerUp, + AppServerWorking: appServerWorking, + APIEqUSD: r.apiEqUSD, APIEqPricedCalls: r.apiEqPricedCalls, APIEqUnpricedCalls: r.apiEqUnknownCalls, APIEqPendingCalls: int64(len(r.pendingModelResolutions)), }, nil diff --git a/internal/codex/live_usage_test.go b/internal/codex/live_usage_test.go index 1a074dba..ba0af12d 100644 --- a/internal/codex/live_usage_test.go +++ b/internal/codex/live_usage_test.go @@ -695,14 +695,42 @@ type stubSessionStatusProvider struct { statuses map[string]sessionRuntimeStatus observations []resolvedModelObservation subscribed map[string]struct{} + unavailable bool } func (s stubSessionStatusProvider) Fetch(context.Context, []string) (sessionDaemonSnapshot, bool) { + if s.unavailable { + return sessionDaemonSnapshot{}, false + } return sessionDaemonSnapshot{ Statuses: s.statuses, ModelObservations: s.observations, SubscribedThreads: s.subscribed, }, true } +func TestLiveUsageReaderReportsAppServerHealthAndWork(t *testing.T) { + home := t.TempDir() + now := time.Now() + path := testRolloutPath(t, home, now, "health-thread") + writeRollout(t, path, sessionMetaLine("health-thread", `"cli"`, "/work/health", nil)+"\n") + reader, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + reader.statusProvider = stubSessionStatusProvider{ + statuses: map[string]sessionRuntimeStatus{"health-thread": sessionRuntimeWorking}, + } + working, err := reader.FetchTokenUsage(context.Background()) + if err != nil || !working.AppServerStatusKnown || !working.AppServerUp || !working.AppServerWorking { + t.Fatalf("working app-server health = %#v, %v", working, err) + } + + reader.statusProvider = stubSessionStatusProvider{unavailable: true} + down, err := reader.FetchTokenUsage(context.Background()) + if err != nil || !down.AppServerStatusKnown || down.AppServerUp || down.AppServerWorking { + t.Fatalf("unreachable app-server health = %#v, %v", down, err) + } +} + func TestLiveUsageReaderPropagatesWaitingAgentToRoot(t *testing.T) { home := t.TempDir() now := time.Now() diff --git a/internal/ui/model.go b/internal/ui/model.go index 45fa2ae4..c4fc74af 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -117,32 +117,35 @@ type Model struct { benchmarkDetailScroll int benchmarkDetailCache benchmarkDetailTranscriptCache - monitorState monitorState - monitorAutoStart bool - monitorStartedAt time.Time - monitorStoppedAt time.Time - monitorBaseline int64 - monitorLatest int64 - monitorSamples []monitorSample - monitorRequest uint64 - monitorFetchActive bool - monitorNextFetch time.Time - monitorResetPaused bool - monitorNextSample time.Time - monitorBoundaryDue bool - monitorGraphStart int64 - monitorLastActivity time.Time - monitorSessions int - monitorSessionData []monitorSession - monitorSelectedID string - monitorDismissed map[string]monitorSessionDismissal - monitorDismissHover string - monitorDismissFlash string - monitorDismissSeq uint64 - monitorScroll int - monitorError string - monitorQuotaWindows []monitorQuotaWindow - monitorQuotaError string + monitorState monitorState + monitorAutoStart bool + monitorStartedAt time.Time + monitorStoppedAt time.Time + monitorBaseline int64 + monitorLatest int64 + monitorSamples []monitorSample + monitorRequest uint64 + monitorFetchActive bool + monitorNextFetch time.Time + monitorResetPaused bool + monitorNextSample time.Time + monitorBoundaryDue bool + monitorGraphStart int64 + monitorLastActivity time.Time + monitorSessions int + monitorSessionData []monitorSession + monitorAppServerKnown bool + monitorAppServerUp bool + monitorAppServerWorking bool + monitorSelectedID string + monitorDismissed map[string]monitorSessionDismissal + monitorDismissHover string + monitorDismissFlash string + monitorDismissSeq uint64 + monitorScroll int + monitorError string + monitorQuotaWindows []monitorQuotaWindow + monitorQuotaError string quotaAPIAnchors map[string]quotaAPIAnchor quotaAPIEvidence []quotaAPISample @@ -1889,6 +1892,7 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd, } return m, nil, false } + m.syncMonitorAppServerStatus(message.usage) accepted := true switch message.kind { case monitorFetchStart: @@ -1929,6 +1933,12 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd, return m, nil, accepted } +func (m *Model) syncMonitorAppServerStatus(usage codex.LiveUsageSnapshot) { + m.monitorAppServerKnown = usage.AppServerStatusKnown + m.monitorAppServerUp = usage.AppServerUp + m.monitorAppServerWorking = usage.AppServerWorking +} + func (m *Model) resetMonitorFromSnapshot(message monitorFetchedMsg, paused bool) { m.monitorStartedAt = message.at m.monitorStoppedAt = time.Time{} diff --git a/internal/ui/monitor.go b/internal/ui/monitor.go index 5fd4a4c0..dfb2dbff 100644 --- a/internal/ui/monitor.go +++ b/internal/ui/monitor.go @@ -136,11 +136,11 @@ func (m Model) renderMonitorReadout(width, height int, colors palette) string { } stateColor := colors.primary - if m.monitorState == monitorRunning && m.monitorError == "" { - stateColor = lipgloss.Color("#7A2633") - if m.phase%2 == 0 { - stateColor = colors.danger - } + if m.monitorState == monitorRunning { + stateColor = m.monitorIndicatorColor(colors) + } + if m.monitorError != "" { + stateColor = colors.danger } innerWidth := max(width-4, 1) lines := []string{ diff --git a/internal/ui/monitor_test.go b/internal/ui/monitor_test.go index 85090434..4000a7b2 100644 --- a/internal/ui/monitor_test.go +++ b/internal/ui/monitor_test.go @@ -880,17 +880,20 @@ func TestMonitorViewIsResponsiveAndGraphAutoScales(t *testing.T) { } } -func TestMonitorRecordingLampPulsesBetweenDarkAndBrightRed(t *testing.T) { +func TestMonitorLabelUsesTheSharedActivityIndicatorColor(t *testing.T) { colors := paletteFor(themeHacker) - model := Model{monitorState: monitorRunning, monitorStartedAt: time.Now()} + model := Model{ + monitorState: monitorRunning, monitorStartedAt: time.Now(), + monitorAppServerKnown: true, monitorAppServerUp: true, monitorAppServerWorking: true, + } model.phase = 0 bright := model.renderMonitorReadout(60, 8, colors) model.phase = 1 dark := model.renderMonitorReadout(60, 8, colors) - wantBright := lipgloss.NewStyle().Bold(true).Foreground(colors.danger).Render("MONITORING ●") - wantDark := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#7A2633")).Render("MONITORING ●") + wantBright := lipgloss.NewStyle().Bold(true).Foreground(colors.accent).Render("MONITORING ●") + wantDark := lipgloss.NewStyle().Bold(true).Foreground(colors.dim).Render("MONITORING ●") if !strings.Contains(bright, wantBright) || !strings.Contains(dark, wantDark) || ansi.Strip(bright) != ansi.Strip(dark) { - t.Fatal("recording lamp did not pulse red intensity while keeping a stable label") + t.Fatal("Monitor label did not share the theme activity pulse while keeping stable text") } } diff --git a/internal/ui/tabs.go b/internal/ui/tabs.go index 7c495850..110134cb 100644 --- a/internal/ui/tabs.go +++ b/internal/ui/tabs.go @@ -61,12 +61,12 @@ func responsiveTabLabels(width int, tiers [][]string) ([]string, string) { return labels, separator } -func mainTabLayout(width int, recording bool) ([]mainTab, string) { +func mainTabLayout(width int, showMonitorLight bool) ([]mainTab, string) { monitorFull := "╭ MONITOR ╮" monitorCompact := "╭MON╮" monitorMinimal := "[M]" microMonitor := "M" - if recording { + if showMonitorLight { monitorFull = "╭ MONITOR ●╮" monitorCompact = "╭MON●╮" monitorMinimal = "[M●]" @@ -162,8 +162,7 @@ func mainTabForView(view meterViewID) mainTabID { } func (m Model) renderMainTabs(width int, colors palette) string { - recording := m.monitorState == monitorRunning - tabs, separator := mainTabLayout(width, recording) + tabs, separator := mainTabLayout(width, true) parts := make([]string, 0, len(tabs)) used := 0 for _, tab := range tabs { @@ -171,7 +170,7 @@ func (m Model) renderMainTabs(width int, colors palette) string { hovered := m.mainTabHovered && tab.tab == m.hoveredMainTab flashed := m.viewFlashing && tab.tab == mainTabForView(m.flashedView) base, background := tabAppearance(active, hovered, flashed, colors) - parts = append(parts, renderViewTabLabel(tab.label, base, background, recording && tab.tab == mainTabMonitor, m.phase, colors)) + parts = append(parts, renderViewTabLabel(tab.label, base, background, tab.tab == mainTabMonitor, m.monitorIndicatorColor(colors))) used += tab.width } if len(parts) > 1 { @@ -216,21 +215,32 @@ func tabAppearance(active, hovered, flashed bool, colors palette) (lipgloss.Styl return lipgloss.NewStyle().Foreground(foreground).Background(background).Bold(bold), background } -func renderViewTabLabel(label string, base lipgloss.Style, background imagecolor.Color, recording bool, phase int, colors palette) string { - if !recording || !strings.Contains(label, "●") { +func renderViewTabLabel(label string, base lipgloss.Style, background imagecolor.Color, monitorLight bool, lightColor imagecolor.Color) string { + if !monitorLight || !strings.Contains(label, "●") { return base.Render(label) } pieces := strings.SplitN(label, "●", 2) - dotColor := recordingDotColor(phase, colors) - dot := lipgloss.NewStyle().Bold(true).Foreground(dotColor).Background(background).Render("●") + dot := lipgloss.NewStyle().Bold(true).Foreground(lightColor).Background(background).Render("●") return base.Render(pieces[0]) + dot + base.Render(pieces[1]) } -func recordingDotColor(phase int, colors palette) imagecolor.Color { - if phase%2 == 0 { - return colors.danger +func (m Model) monitorIndicatorColor(colors palette) imagecolor.Color { + if m.monitorState != monitorRunning { + return colors.dim } - return lipgloss.Color("#7A2633") + if m.monitorAppServerWorking { + if m.phase%2 == 0 { + return colors.accent + } + return colors.dim + } + if !m.monitorAppServerKnown { + return colors.dim + } + if m.monitorAppServerUp { + return colors.success + } + return colors.danger } func (m Model) mainTabAt(x, y int) (mainTabID, bool) { @@ -242,7 +252,7 @@ func (m Model) mainTabAt(x, y int) (mainTabID, bool) { return mainTabQuota, false } localX := x - 2 - tabs, _ := mainTabLayout(layout.contentWidth, m.monitorState == monitorRunning) + tabs, _ := mainTabLayout(layout.contentWidth, true) for _, tab := range tabs { if localX >= tab.x && localX < tab.x+tab.width { return tab.tab, true diff --git a/internal/ui/tabs_test.go b/internal/ui/tabs_test.go index fd807185..146c103b 100644 --- a/internal/ui/tabs_test.go +++ b/internal/ui/tabs_test.go @@ -19,11 +19,11 @@ func TestMainTabsChooseResponsiveLabels(t *testing.T) { }{ {width: 100, want: "BENCHMARK"}, {width: 22, want: "QTA"}, - {width: 9, want: "[M]"}, - {width: 3, want: "M"}, + {width: 9, want: "●"}, + {width: 3, want: "●"}, } { t.Run(test.want, func(t *testing.T) { - tabs, _ := mainTabLayout(test.width, false) + tabs, _ := mainTabLayout(test.width, true) if len(tabs) != int(mainTabCount) { t.Fatalf("width %d displayed %d main tabs, want %d", test.width, len(tabs), mainTabCount) } @@ -78,7 +78,7 @@ func TestMainTabsSupportHoverClickAndPulse(t *testing.T) { model.snapshot = codex.DemoSnapshot() model.loading = false model.width, model.height = 100, 30 - tabs, _ := mainTabLayout(model.contentWidth(), false) + tabs, _ := mainTabLayout(model.contentWidth(), true) target := tabs[mainTabMonitor] mouse := tea.MouseMotionMsg{ X: 2 + target.x + target.width/2, @@ -132,7 +132,7 @@ func TestEveryRenderedTabCellIsClickableAcrossWidths(t *testing.T) { for _, width := range []int{8, 12, 20, 40, 45, 60, 80, 100, 160} { model := Model{snapshot: codex.DemoSnapshot(), width: width, height: 24} layout := model.dashboardLayout() - mainTabs, _ := mainTabLayout(layout.contentWidth, false) + mainTabs, _ := mainTabLayout(layout.contentWidth, true) for _, tab := range mainTabs { for offset := 0; offset < tab.width; offset++ { if got, ok := model.mainTabAt(2+tab.x+offset, layout.tabsY); !ok || got != tab.tab { @@ -241,18 +241,44 @@ func TestQuotaSubTabsOnlyRenderAndHitTestWithinQuota(t *testing.T) { } } -func TestMonitorMainTabShowsPulsingRecordingDotWhileQuotaIsActive(t *testing.T) { - model := Model{meterView: viewBars, monitorState: monitorRunning} +func TestMonitorIndicatorUsesActivityAndAppServerHealth(t *testing.T) { + model := Model{ + meterView: viewBars, monitorState: monitorRunning, + monitorAppServerKnown: true, monitorAppServerUp: true, monitorAppServerWorking: true, + } colors := paletteFor(themeHacker) model.phase = 0 bright := model.renderMainTabs(100, colors) model.phase = 1 dark := model.renderMainTabs(100, colors) if !strings.Contains(ansi.Strip(bright), "●") { - t.Fatal("recording tab did not retain a pulsing dot away from the Monitor view") + t.Fatal("Monitor tab did not retain its status light away from the Monitor view") + } + if model.monitorIndicatorColor(colors) != colors.dim { + t.Fatal("working indicator did not alternate to the theme's dim color") + } + model.phase = 0 + if model.monitorIndicatorColor(colors) != colors.accent { + t.Fatal("working indicator did not alternate to the theme's highlight color") + } + model.monitorAppServerWorking = false + if model.monitorIndicatorColor(colors) != colors.success { + t.Fatal("idle app server indicator was not steady green") + } + model.monitorAppServerUp = false + if model.monitorIndicatorColor(colors) != colors.danger { + t.Fatal("unreachable app server indicator was not steady red") + } + model.monitorAppServerKnown = false + if model.monitorIndicatorColor(colors) != colors.dim { + t.Fatal("unknown app server status was not shown as dim") } - if recordingDotColor(0, colors) == recordingDotColor(1, colors) { - t.Fatal("recording tab dot does not alternate between bright and dark red") + model.monitorState = monitorPaused + model.monitorAppServerKnown = true + model.monitorAppServerUp = true + model.monitorAppServerWorking = true + if model.monitorIndicatorColor(colors) != colors.dim { + t.Fatal("paused Monitor presented stale app-server health as current") } if lipgloss.Width(bright) != 100 || lipgloss.Width(dark) != 100 { t.Fatalf("tab rail did not fill its responsive width: bright=%d dark=%d", lipgloss.Width(bright), lipgloss.Width(dark)) diff --git a/internal/ui/theme.go b/internal/ui/theme.go index 9f12ea80..b41e859a 100644 --- a/internal/ui/theme.go +++ b/internal/ui/theme.go @@ -74,6 +74,7 @@ type palette struct { primary imagecolor.Color dim imagecolor.Color accent imagecolor.Color + success imagecolor.Color warning imagecolor.Color danger imagecolor.Color background imagecolor.Color @@ -87,6 +88,7 @@ func paletteFor(theme themeID) palette { primary: lipgloss.Color("#FFB454"), dim: lipgloss.Color("#8A5428"), accent: lipgloss.Color("#FFD38A"), + success: lipgloss.Color("#67D391"), warning: lipgloss.Color("#FF8A3D"), danger: lipgloss.Color("#FF5F56"), background: lipgloss.Color("#1A0E05"), @@ -97,6 +99,7 @@ func paletteFor(theme themeID) palette { primary: lipgloss.Color("#76B7E5"), dim: lipgloss.Color("#425B76"), accent: lipgloss.Color("#B7E3FF"), + success: lipgloss.Color("#57D68D"), warning: lipgloss.Color("#E8C46A"), danger: lipgloss.Color("#FF6B83"), background: lipgloss.Color("#08111B"), @@ -107,6 +110,7 @@ func paletteFor(theme themeID) palette { primary: lipgloss.Color("#C084FC"), dim: lipgloss.Color("#68428F"), accent: lipgloss.Color("#F0ABFC"), + success: lipgloss.Color("#65D98B"), warning: lipgloss.Color("#F9A8D4"), danger: lipgloss.Color("#FF668F"), background: lipgloss.Color("#12081C"), @@ -117,6 +121,7 @@ func paletteFor(theme themeID) palette { primary: lipgloss.Color("#A970FF"), dim: lipgloss.Color("#6840A6"), accent: lipgloss.Color("#D0A7FF"), + success: lipgloss.Color("#62D990"), warning: lipgloss.Color("#8F7CFF"), danger: lipgloss.Color("#FF668F"), background: lipgloss.Color("#180D29"), @@ -127,6 +132,7 @@ func paletteFor(theme themeID) palette { primary: lipgloss.Color("#57FF8A"), dim: lipgloss.Color("#238F4A"), accent: lipgloss.Color("#67E8F9"), + success: lipgloss.Color("#00C853"), warning: lipgloss.Color("#FFCA58"), danger: lipgloss.Color("#FF5F6D"), background: lipgloss.Color("#07130B"), diff --git a/main.go b/main.go index b37ea973..f760d6c9 100644 --- a/main.go +++ b/main.go @@ -101,6 +101,7 @@ func (d *demoFetcher) FetchTokenUsage(context.Context) (codex.LiveUsageSnapshot, return codex.LiveUsageSnapshot{ TotalTokens: d.lifetimeTokens, APIEqUSD: d.apiEqUSD, APIEqPricedCalls: d.apiEqCalls, LastActivity: time.Now(), SessionCount: 2, + AppServerStatusKnown: true, AppServerUp: true, AppServerWorking: true, Sessions: []codex.LiveUsageSession{ {ID: "019d-demo-a1b2c", WorkingDirectory: "/projects/alpha", TotalTokens: alphaTokens, LastActivity: time.Now(), AgentCount: 2, Active: true, Attention: codex.SessionAttentionApproval, ModelCalls: append([]codex.LiveModelCall(nil), d.alphaCalls...), TurnTimings: append([]codex.LiveTurnTiming(nil), d.alphaTurns...)}, From c4ed980ba6dc5f1457669bfb79ad18437c6638e4 Mon Sep 17 00:00:00 2001 From: merefield Date: Sun, 23 Aug 2026 11:40:39 +0100 Subject: [PATCH 3/6] TWEAK: use green Monitor activity pulse --- README.md | 6 +++--- internal/ui/monitor_test.go | 6 +++--- internal/ui/tabs.go | 4 ++-- internal/ui/tabs_test.go | 8 ++++---- internal/ui/theme.go | 6 ++++++ 5 files changed, 18 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 2ff14107..5e09b77c 100644 --- a/README.md +++ b/README.md @@ -579,9 +579,9 @@ The other top-level views are: token telemetry and shows total observed tokens, elapsed time, and average rate; clickable Pause/Resume and Reset controls sit beside it. Active sessions are checked once per second and the idle cadence relaxes to five seconds. - The Monitor tab light and status label pulse between the current theme's - highlight and dim colors while the shared app server is working, remain green - while it is reachable but idle, and turn red when it is unreachable. They + The Monitor tab light and status label pulse between bright and dim green + while the shared app server is working, remain steady green while it is + reachable but idle, and turn red when it is unreachable. They remain dim while paused or when app-server health is unavailable. Below, every independent root session has a metrics box and its own graph. Spawned-agent descendants with an explicit Codex parent link are recursively diff --git a/internal/ui/monitor_test.go b/internal/ui/monitor_test.go index 4000a7b2..2944ea90 100644 --- a/internal/ui/monitor_test.go +++ b/internal/ui/monitor_test.go @@ -890,10 +890,10 @@ func TestMonitorLabelUsesTheSharedActivityIndicatorColor(t *testing.T) { bright := model.renderMonitorReadout(60, 8, colors) model.phase = 1 dark := model.renderMonitorReadout(60, 8, colors) - wantBright := lipgloss.NewStyle().Bold(true).Foreground(colors.accent).Render("MONITORING ●") - wantDark := lipgloss.NewStyle().Bold(true).Foreground(colors.dim).Render("MONITORING ●") + wantBright := lipgloss.NewStyle().Bold(true).Foreground(colors.success).Render("MONITORING ●") + wantDark := lipgloss.NewStyle().Bold(true).Foreground(colors.successDim).Render("MONITORING ●") if !strings.Contains(bright, wantBright) || !strings.Contains(dark, wantDark) || ansi.Strip(bright) != ansi.Strip(dark) { - t.Fatal("Monitor label did not share the theme activity pulse while keeping stable text") + t.Fatal("Monitor label did not share the green activity pulse while keeping stable text") } } diff --git a/internal/ui/tabs.go b/internal/ui/tabs.go index 110134cb..187f6523 100644 --- a/internal/ui/tabs.go +++ b/internal/ui/tabs.go @@ -230,9 +230,9 @@ func (m Model) monitorIndicatorColor(colors palette) imagecolor.Color { } if m.monitorAppServerWorking { if m.phase%2 == 0 { - return colors.accent + return colors.success } - return colors.dim + return colors.successDim } if !m.monitorAppServerKnown { return colors.dim diff --git a/internal/ui/tabs_test.go b/internal/ui/tabs_test.go index 146c103b..2e5f34ec 100644 --- a/internal/ui/tabs_test.go +++ b/internal/ui/tabs_test.go @@ -254,12 +254,12 @@ func TestMonitorIndicatorUsesActivityAndAppServerHealth(t *testing.T) { if !strings.Contains(ansi.Strip(bright), "●") { t.Fatal("Monitor tab did not retain its status light away from the Monitor view") } - if model.monitorIndicatorColor(colors) != colors.dim { - t.Fatal("working indicator did not alternate to the theme's dim color") + if model.monitorIndicatorColor(colors) != colors.successDim { + t.Fatal("working indicator did not alternate to dim green") } model.phase = 0 - if model.monitorIndicatorColor(colors) != colors.accent { - t.Fatal("working indicator did not alternate to the theme's highlight color") + if model.monitorIndicatorColor(colors) != colors.success { + t.Fatal("working indicator did not alternate to bright green") } model.monitorAppServerWorking = false if model.monitorIndicatorColor(colors) != colors.success { diff --git a/internal/ui/theme.go b/internal/ui/theme.go index b41e859a..8e20ef90 100644 --- a/internal/ui/theme.go +++ b/internal/ui/theme.go @@ -75,6 +75,7 @@ type palette struct { dim imagecolor.Color accent imagecolor.Color success imagecolor.Color + successDim imagecolor.Color warning imagecolor.Color danger imagecolor.Color background imagecolor.Color @@ -89,6 +90,7 @@ func paletteFor(theme themeID) palette { dim: lipgloss.Color("#8A5428"), accent: lipgloss.Color("#FFD38A"), success: lipgloss.Color("#67D391"), + successDim: lipgloss.Color("#285B3B"), warning: lipgloss.Color("#FF8A3D"), danger: lipgloss.Color("#FF5F56"), background: lipgloss.Color("#1A0E05"), @@ -100,6 +102,7 @@ func paletteFor(theme themeID) palette { dim: lipgloss.Color("#425B76"), accent: lipgloss.Color("#B7E3FF"), success: lipgloss.Color("#57D68D"), + successDim: lipgloss.Color("#25583D"), warning: lipgloss.Color("#E8C46A"), danger: lipgloss.Color("#FF6B83"), background: lipgloss.Color("#08111B"), @@ -111,6 +114,7 @@ func paletteFor(theme themeID) palette { dim: lipgloss.Color("#68428F"), accent: lipgloss.Color("#F0ABFC"), success: lipgloss.Color("#65D98B"), + successDim: lipgloss.Color("#28583A"), warning: lipgloss.Color("#F9A8D4"), danger: lipgloss.Color("#FF668F"), background: lipgloss.Color("#12081C"), @@ -122,6 +126,7 @@ func paletteFor(theme themeID) palette { dim: lipgloss.Color("#6840A6"), accent: lipgloss.Color("#D0A7FF"), success: lipgloss.Color("#62D990"), + successDim: lipgloss.Color("#28583C"), warning: lipgloss.Color("#8F7CFF"), danger: lipgloss.Color("#FF668F"), background: lipgloss.Color("#180D29"), @@ -133,6 +138,7 @@ func paletteFor(theme themeID) palette { dim: lipgloss.Color("#238F4A"), accent: lipgloss.Color("#67E8F9"), success: lipgloss.Color("#00C853"), + successDim: lipgloss.Color("#006B2D"), warning: lipgloss.Color("#FFCA58"), danger: lipgloss.Color("#FF5F6D"), background: lipgloss.Color("#07130B"), From d6a0b36e9e75cca691fe6b0aaf7524a5d471375d Mon Sep 17 00:00:00 2001 From: merefield Date: Sun, 23 Aug 2026 11:52:00 +0100 Subject: [PATCH 4/6] FIX: initialize Monitor on recovered Resume --- internal/ui/model.go | 4 ++++ internal/ui/monitor_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/internal/ui/model.go b/internal/ui/model.go index c4fc74af..66940ff7 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -1906,6 +1906,10 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd, accepted = false break } + if m.monitorStartedAt.IsZero() { + m.resetMonitorFromSnapshot(message, false) + break + } if message.quotaErr == nil { m.resumeMonitorQuotaSnapshot(message.quota) } diff --git a/internal/ui/monitor_test.go b/internal/ui/monitor_test.go index 2944ea90..a488ce8d 100644 --- a/internal/ui/monitor_test.go +++ b/internal/ui/monitor_test.go @@ -170,6 +170,37 @@ func TestMonitorRejectedResumeDoesNotRebaseQuota(t *testing.T) { } } +func TestMonitorResumeAfterFailedStartEstablishesFreshBaseline(t *testing.T) { + failedAt := time.Unix(900, 0) + model := Model{meterView: viewMonitor, monitorState: monitorStarting, monitorRequest: 1} + updated, _ := model.Update(monitorFetchedMsg{ + kind: monitorFetchStart, sequence: 1, err: errors.New("telemetry offline"), at: failedAt, + }) + model = updated.(Model) + if model.monitorState != monitorPaused || !model.monitorStartedAt.IsZero() { + t.Fatalf("failed Start state = %#v", model) + } + + updated, command := model.Update(key('p')) + model = updated.(Model) + if command == nil || model.monitorState != monitorResuming { + t.Fatalf("Resume was not started after failed Start: %#v", model) + } + resumedAt := failedAt.Add(time.Minute) + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchResume, sequence: model.monitorRequest, + usage: usageWithTokens(500), quota: codex.DemoSnapshot(), at: resumedAt, + }) + model = updated.(Model) + if model.monitorState != monitorRunning || !model.monitorStartedAt.Equal(resumedAt) || + model.monitorBaseline != 500 || model.monitorRecordedTokens() != 0 { + t.Fatalf("Resume did not establish a fresh baseline: %#v", model) + } + if elapsed := model.monitorElapsed(resumedAt.Add(time.Second)); elapsed != time.Second { + t.Fatalf("elapsed after recovered Resume = %s, want 1s", elapsed) + } +} + func TestMonitorTickSamplesOnlyWhileRunningAndIgnoresStaleResults(t *testing.T) { model := New(stubLiveFetcher{stubFetcher: stubFetcher{snapshot: codex.DemoSnapshot()}}, time.Minute) model.meterView = viewMonitor From 66551083800010467ab2bfa66861995380358bb2 Mon Sep 17 00:00:00 2001 From: merefield Date: Sun, 23 Aug 2026 11:59:22 +0100 Subject: [PATCH 5/6] FIX: derive Monitor status from live sessions --- README.md | 8 +++--- internal/codex/live_usage.go | 45 ++++++++++++++++++++----------- internal/codex/live_usage_test.go | 40 ++++++++++++++++++++++----- internal/ui/model.go | 16 +++++------ internal/ui/monitor_test.go | 2 +- internal/ui/tabs.go | 6 ++--- internal/ui/tabs_test.go | 24 ++++++++--------- main.go | 2 +- 8 files changed, 93 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index 5e09b77c..c2d3499a 100644 --- a/README.md +++ b/README.md @@ -580,9 +580,11 @@ The other top-level views are: rate; clickable Pause/Resume and Reset controls sit beside it. Active sessions are checked once per second and the idle cadence relaxes to five seconds. The Monitor tab light and status label pulse between bright and dim green - while the shared app server is working, remain steady green while it is - reachable but idle, and turn red when it is unreachable. They - remain dim while paused or when app-server health is unavailable. Below, + while any local Codex session holds its writer lock or the shared app server + reports work, remain steady green while the server is reachable but idle, + and turn red only when local runtime health is observable and no Codex + runtime is alive. They remain dim while paused or when runtime health cannot + be established. 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`. Each row compactly shows diff --git a/internal/codex/live_usage.go b/internal/codex/live_usage.go index 01919aa0..de29028b 100644 --- a/internal/codex/live_usage.go +++ b/internal/codex/live_usage.go @@ -29,17 +29,17 @@ const ( // totals increase monotonically; APIEqPendingCalls is an instantaneous count // kept separate until daemon model resolution or requested-model fallback. type LiveUsageSnapshot struct { - TotalTokens int64 - LastActivity time.Time - SessionCount int - Sessions []LiveUsageSession - AppServerStatusKnown bool - AppServerUp bool - AppServerWorking bool - APIEqUSD float64 - APIEqPricedCalls int64 - APIEqUnpricedCalls int64 - APIEqPendingCalls int64 + TotalTokens int64 + LastActivity time.Time + SessionCount int + Sessions []LiveUsageSession + CodexStatusKnown bool + CodexUp bool + CodexWorking bool + APIEqUSD float64 + APIEqPricedCalls int64 + APIEqUnpricedCalls int64 + APIEqPendingCalls int64 } // LiveUsageSession is one independently started local Codex session. Token @@ -315,7 +315,6 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover } exactStatuses := map[string]sessionRuntimeStatus(nil) - appServerStatusKnown := r.statusProvider != nil appServerUp := false appServerWorking := false r.daemonSubscribedThreads = nil @@ -362,18 +361,32 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover liveWriters, writerLocksSupported := r.liveWriterThreads() sessions, activeSessions := r.sessionSnapshots(now, liveWriters, writerLocksSupported, exactStatuses) + codexStatusKnown, codexUp, codexWorking := codexRuntimeHealth( + appServerUp, appServerWorking, len(liveWriters) > 0, writerLocksSupported, + ) return LiveUsageSnapshot{ TotalTokens: r.totalTokens, LastActivity: r.lastActivity, SessionCount: activeSessions, Sessions: sessions, - AppServerStatusKnown: appServerStatusKnown, - AppServerUp: appServerUp, - AppServerWorking: appServerWorking, - APIEqUSD: r.apiEqUSD, APIEqPricedCalls: r.apiEqPricedCalls, + CodexStatusKnown: codexStatusKnown, + CodexUp: codexUp, + CodexWorking: codexWorking, + APIEqUSD: r.apiEqUSD, APIEqPricedCalls: r.apiEqPricedCalls, APIEqUnpricedCalls: r.apiEqUnknownCalls, APIEqPendingCalls: int64(len(r.pendingModelResolutions)), }, nil } +// codexRuntimeHealth combines the optional shared app-server heartbeat with +// locally held writer locks. A held lock represents a live Codex session, so it +// is both a health and activity signal. An unavailable optional socket alone is +// not evidence that Codex is down. +func codexRuntimeHealth(appServerUp, appServerWorking, liveWriter, writerLocksSupported bool) (known, up, working bool) { + working = appServerWorking || liveWriter + up = appServerUp || working + known = up || writerLocksSupported + return known, up, working +} + func (r *LiveUsageReader) observedThreadIDs(now time.Time) []string { seen := make(map[string]struct{}, len(r.files)) threadIDs := make([]string, 0, len(r.files)) diff --git a/internal/codex/live_usage_test.go b/internal/codex/live_usage_test.go index ba0af12d..e27b41d3 100644 --- a/internal/codex/live_usage_test.go +++ b/internal/codex/live_usage_test.go @@ -453,6 +453,9 @@ func TestLiveUsageReaderUsesOpenWriterAndCompletedTurnForInputWait(t *testing.T) if err != nil || len(usage.Sessions) != 1 || usage.Sessions[0].Attention != SessionAttentionInput { t.Fatalf("open completed CLI = %#v, %v; want input needed", usage, err) } + if !usage.CodexStatusKnown || !usage.CodexUp || !usage.CodexWorking { + t.Fatalf("held writer lock did not report live Codex activity: %#v", usage) + } appendRollout(t, path, attentionEventLine(now.Add(time.Second), "task_started", nil)+"\n") usage, err = reader.FetchTokenUsage(context.Background()) @@ -470,6 +473,9 @@ func TestLiveUsageReaderUsesOpenWriterAndCompletedTurnForInputWait(t *testing.T) if err != nil || usage.Sessions[0].Attention != SessionAttentionNone { t.Fatalf("closed CLI = %#v, %v; want no attention", usage, err) } + if !usage.CodexStatusKnown || usage.CodexUp || usage.CodexWorking { + t.Fatalf("released final writer lock did not report an observable stopped runtime: %#v", usage) + } } func TestSessionAttentionUsesExactDaemonStatusBeforeFallback(t *testing.T) { @@ -707,7 +713,7 @@ func (s stubSessionStatusProvider) Fetch(context.Context, []string) (sessionDaem }, true } -func TestLiveUsageReaderReportsAppServerHealthAndWork(t *testing.T) { +func TestLiveUsageReaderReportsCodexHealthAndWork(t *testing.T) { home := t.TempDir() now := time.Now() path := testRolloutPath(t, home, now, "health-thread") @@ -720,14 +726,36 @@ func TestLiveUsageReaderReportsAppServerHealthAndWork(t *testing.T) { statuses: map[string]sessionRuntimeStatus{"health-thread": sessionRuntimeWorking}, } working, err := reader.FetchTokenUsage(context.Background()) - if err != nil || !working.AppServerStatusKnown || !working.AppServerUp || !working.AppServerWorking { - t.Fatalf("working app-server health = %#v, %v", working, err) + if err != nil || !working.CodexStatusKnown || !working.CodexUp || !working.CodexWorking { + t.Fatalf("working Codex health = %#v, %v", working, err) } reader.statusProvider = stubSessionStatusProvider{unavailable: true} - down, err := reader.FetchTokenUsage(context.Background()) - if err != nil || !down.AppServerStatusKnown || down.AppServerUp || down.AppServerWorking { - t.Fatalf("unreachable app-server health = %#v, %v", down, err) + unknown, err := reader.FetchTokenUsage(context.Background()) + if err != nil || unknown.CodexStatusKnown || unknown.CodexUp || unknown.CodexWorking { + t.Fatalf("unobservable Codex health = %#v, %v", unknown, err) + } +} + +func TestCodexRuntimeHealthCombinesAppServerAndWriterLocks(t *testing.T) { + tests := []struct { + name string + appUp, appWorking, liveWriter, locksSupported bool + wantKnown, wantUp, wantWorking bool + }{ + {"working app server", true, true, false, false, true, true, true}, + {"idle app server", true, false, false, false, true, true, false}, + {"live writer without app server", false, false, true, true, true, true, true}, + {"observable without live runtime", false, false, false, true, true, false, false}, + {"unobservable", false, false, false, false, false, false, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + known, up, working := codexRuntimeHealth(tt.appUp, tt.appWorking, tt.liveWriter, tt.locksSupported) + if known != tt.wantKnown || up != tt.wantUp || working != tt.wantWorking { + t.Fatalf("health = (%t, %t, %t), want (%t, %t, %t)", known, up, working, tt.wantKnown, tt.wantUp, tt.wantWorking) + } + }) } } diff --git a/internal/ui/model.go b/internal/ui/model.go index 66940ff7..2217a015 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -134,9 +134,9 @@ type Model struct { monitorLastActivity time.Time monitorSessions int monitorSessionData []monitorSession - monitorAppServerKnown bool - monitorAppServerUp bool - monitorAppServerWorking bool + monitorCodexStatusKnown bool + monitorCodexUp bool + monitorCodexWorking bool monitorSelectedID string monitorDismissed map[string]monitorSessionDismissal monitorDismissHover string @@ -1892,7 +1892,7 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd, } return m, nil, false } - m.syncMonitorAppServerStatus(message.usage) + m.syncMonitorCodexStatus(message.usage) accepted := true switch message.kind { case monitorFetchStart: @@ -1937,10 +1937,10 @@ func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd, return m, nil, accepted } -func (m *Model) syncMonitorAppServerStatus(usage codex.LiveUsageSnapshot) { - m.monitorAppServerKnown = usage.AppServerStatusKnown - m.monitorAppServerUp = usage.AppServerUp - m.monitorAppServerWorking = usage.AppServerWorking +func (m *Model) syncMonitorCodexStatus(usage codex.LiveUsageSnapshot) { + m.monitorCodexStatusKnown = usage.CodexStatusKnown + m.monitorCodexUp = usage.CodexUp + m.monitorCodexWorking = usage.CodexWorking } func (m *Model) resetMonitorFromSnapshot(message monitorFetchedMsg, paused bool) { diff --git a/internal/ui/monitor_test.go b/internal/ui/monitor_test.go index a488ce8d..0660934f 100644 --- a/internal/ui/monitor_test.go +++ b/internal/ui/monitor_test.go @@ -915,7 +915,7 @@ func TestMonitorLabelUsesTheSharedActivityIndicatorColor(t *testing.T) { colors := paletteFor(themeHacker) model := Model{ monitorState: monitorRunning, monitorStartedAt: time.Now(), - monitorAppServerKnown: true, monitorAppServerUp: true, monitorAppServerWorking: true, + monitorCodexStatusKnown: true, monitorCodexUp: true, monitorCodexWorking: true, } model.phase = 0 bright := model.renderMonitorReadout(60, 8, colors) diff --git a/internal/ui/tabs.go b/internal/ui/tabs.go index 187f6523..8fc6dccb 100644 --- a/internal/ui/tabs.go +++ b/internal/ui/tabs.go @@ -228,16 +228,16 @@ func (m Model) monitorIndicatorColor(colors palette) imagecolor.Color { if m.monitorState != monitorRunning { return colors.dim } - if m.monitorAppServerWorking { + if m.monitorCodexWorking { if m.phase%2 == 0 { return colors.success } return colors.successDim } - if !m.monitorAppServerKnown { + if !m.monitorCodexStatusKnown { return colors.dim } - if m.monitorAppServerUp { + if m.monitorCodexUp { return colors.success } return colors.danger diff --git a/internal/ui/tabs_test.go b/internal/ui/tabs_test.go index 2e5f34ec..a56d906b 100644 --- a/internal/ui/tabs_test.go +++ b/internal/ui/tabs_test.go @@ -241,10 +241,10 @@ func TestQuotaSubTabsOnlyRenderAndHitTestWithinQuota(t *testing.T) { } } -func TestMonitorIndicatorUsesActivityAndAppServerHealth(t *testing.T) { +func TestMonitorIndicatorUsesCodexActivityAndHealth(t *testing.T) { model := Model{ meterView: viewBars, monitorState: monitorRunning, - monitorAppServerKnown: true, monitorAppServerUp: true, monitorAppServerWorking: true, + monitorCodexStatusKnown: true, monitorCodexUp: true, monitorCodexWorking: true, } colors := paletteFor(themeHacker) model.phase = 0 @@ -261,24 +261,24 @@ func TestMonitorIndicatorUsesActivityAndAppServerHealth(t *testing.T) { if model.monitorIndicatorColor(colors) != colors.success { t.Fatal("working indicator did not alternate to bright green") } - model.monitorAppServerWorking = false + model.monitorCodexWorking = false if model.monitorIndicatorColor(colors) != colors.success { - t.Fatal("idle app server indicator was not steady green") + t.Fatal("idle Codex indicator was not steady green") } - model.monitorAppServerUp = false + model.monitorCodexUp = false if model.monitorIndicatorColor(colors) != colors.danger { - t.Fatal("unreachable app server indicator was not steady red") + t.Fatal("stopped Codex indicator was not steady red") } - model.monitorAppServerKnown = false + model.monitorCodexStatusKnown = false if model.monitorIndicatorColor(colors) != colors.dim { - t.Fatal("unknown app server status was not shown as dim") + t.Fatal("unknown Codex status was not shown as dim") } model.monitorState = monitorPaused - model.monitorAppServerKnown = true - model.monitorAppServerUp = true - model.monitorAppServerWorking = true + model.monitorCodexStatusKnown = true + model.monitorCodexUp = true + model.monitorCodexWorking = true if model.monitorIndicatorColor(colors) != colors.dim { - t.Fatal("paused Monitor presented stale app-server health as current") + t.Fatal("paused Monitor presented stale Codex health as current") } if lipgloss.Width(bright) != 100 || lipgloss.Width(dark) != 100 { t.Fatalf("tab rail did not fill its responsive width: bright=%d dark=%d", lipgloss.Width(bright), lipgloss.Width(dark)) diff --git a/main.go b/main.go index f760d6c9..f036bee0 100644 --- a/main.go +++ b/main.go @@ -101,7 +101,7 @@ func (d *demoFetcher) FetchTokenUsage(context.Context) (codex.LiveUsageSnapshot, return codex.LiveUsageSnapshot{ TotalTokens: d.lifetimeTokens, APIEqUSD: d.apiEqUSD, APIEqPricedCalls: d.apiEqCalls, LastActivity: time.Now(), SessionCount: 2, - AppServerStatusKnown: true, AppServerUp: true, AppServerWorking: true, + CodexStatusKnown: true, CodexUp: true, CodexWorking: true, Sessions: []codex.LiveUsageSession{ {ID: "019d-demo-a1b2c", WorkingDirectory: "/projects/alpha", TotalTokens: alphaTokens, LastActivity: time.Now(), AgentCount: 2, Active: true, Attention: codex.SessionAttentionApproval, ModelCalls: append([]codex.LiveModelCall(nil), d.alphaCalls...), TurnTimings: append([]codex.LiveTurnTiming(nil), d.alphaTurns...)}, From 7014de9bf33901c05c830d6ad84f724cfe9e3d9c Mon Sep 17 00:00:00 2001 From: merefield Date: Sun, 23 Aug 2026 12:23:13 +0100 Subject: [PATCH 6/6] FIX: distinguish Monitor waiting activity --- README.md | 12 ++++----- internal/codex/live_usage.go | 33 ++++++++++++------------ internal/codex/live_usage_test.go | 42 +++++++++++++++++++++++-------- internal/ui/model.go | 9 +++++++ internal/ui/tabs.go | 6 +++++ internal/ui/tabs_test.go | 17 +++++++++++++ internal/ui/theme.go | 6 +++++ 7 files changed, 92 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index c2d3499a..da415036 100644 --- a/README.md +++ b/README.md @@ -579,12 +579,12 @@ The other top-level views are: token telemetry and shows total observed tokens, elapsed time, and average rate; clickable Pause/Resume and Reset controls sit beside it. Active sessions are checked once per second and the idle cadence relaxes to five seconds. - The Monitor tab light and status label pulse between bright and dim green - while any local Codex session holds its writer lock or the shared app server - reports work, remain steady green while the server is reachable but idle, - and turn red only when local runtime health is observable and no Codex - runtime is alive. They remain dim while paused or when runtime health cannot - be established. Below, + The Monitor tab light and status label pulse between bright and dim amber + whenever any session needs input, approval, or a check. With nothing waiting, + they pulse green while at least one session is working and remain steady green + while the Codex runtime is healthy but idle. They turn red only when local + runtime health is observable and Codex is down, and remain dim while paused + or when runtime health cannot be established. 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`. Each row compactly shows diff --git a/internal/codex/live_usage.go b/internal/codex/live_usage.go index de29028b..ba0e7931 100644 --- a/internal/codex/live_usage.go +++ b/internal/codex/live_usage.go @@ -316,18 +316,11 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover exactStatuses := map[string]sessionRuntimeStatus(nil) appServerUp := false - appServerWorking := false r.daemonSubscribedThreads = nil if r.statusProvider != nil { if daemonSnapshot, exact := r.statusProvider.Fetch(ctx, r.observedThreadIDs(now)); exact { appServerUp = true exactStatuses = daemonSnapshot.Statuses - for _, status := range exactStatuses { - if status == sessionRuntimeWorking { - appServerWorking = true - break - } - } r.ingestResolvedModelObservations(daemonSnapshot.ModelObservations) r.daemonSubscribedThreads = daemonSnapshot.SubscribedThreads } @@ -360,9 +353,9 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover } liveWriters, writerLocksSupported := r.liveWriterThreads() - sessions, activeSessions := r.sessionSnapshots(now, liveWriters, writerLocksSupported, exactStatuses) + sessions, activeSessions, sessionWorking := r.sessionSnapshots(now, liveWriters, writerLocksSupported, exactStatuses) codexStatusKnown, codexUp, codexWorking := codexRuntimeHealth( - appServerUp, appServerWorking, len(liveWriters) > 0, writerLocksSupported, + appServerUp, len(liveWriters) > 0, sessionWorking, writerLocksSupported, ) return LiveUsageSnapshot{ TotalTokens: r.totalTokens, LastActivity: r.lastActivity, @@ -377,12 +370,13 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover } // codexRuntimeHealth combines the optional shared app-server heartbeat with -// locally held writer locks. A held lock represents a live Codex session, so it -// is both a health and activity signal. An unavailable optional socket alone is -// not evidence that Codex is down. -func codexRuntimeHealth(appServerUp, appServerWorking, liveWriter, writerLocksSupported bool) (known, up, working bool) { - working = appServerWorking || liveWriter - up = appServerUp || working +// locally held writer locks and reconciled session state. A held lock +// establishes that Codex is healthy without implying that its session is +// working. An unavailable optional socket alone is not evidence that Codex is +// down. +func codexRuntimeHealth(appServerUp, liveWriter, sessionWorking, writerLocksSupported bool) (known, up, working bool) { + working = sessionWorking + up = appServerUp || liveWriter || working known = up || writerLocksSupported return known, up, working } @@ -1107,7 +1101,7 @@ func (r *LiveUsageReader) liveWriterThreads() (map[string]struct{}, bool) { return live, true } -func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string]struct{}, writerLocksSupported bool, exactStatuses map[string]sessionRuntimeStatus) ([]LiveUsageSession, int) { +func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string]struct{}, writerLocksSupported bool, exactStatuses map[string]sessionRuntimeStatus) ([]LiveUsageSession, int, bool) { byID := make(map[string]*rolloutCursor, len(r.files)) for _, cursor := range r.files { if cursor.threadID != "" { @@ -1117,12 +1111,14 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string groups := make(map[string]*LiveUsageSession) groupHasFreshActivity := make(map[string]bool) + groupWorking := make(map[string]bool) for _, cursor := range r.files { quietFor := now.Sub(cursor.lastModified) active := quietFor <= 5*time.Minute _, writerActive := liveWriters[cursor.threadID] exactStatus, exact := exactStatuses[cursor.threadID] exactWorking := exact && exactStatus == sessionRuntimeWorking + localWorking := !exact && writerActive && cursor.attention == sessionAttentionWorking attention := sessionAttention(cursor.attention, writerActive, writerLocksSupported, quietFor, exactStatus, exact) if !active && !exactWorking && attention == SessionAttentionNone && cursor.observedTokens == 0 && len(cursor.modelCalls) == 0 && len(cursor.turnTimings) == 0 { continue @@ -1138,6 +1134,7 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string group.TurnTimings = append(group.TurnTimings, cursor.turnTimings...) group.Active = group.Active || active || exactWorking || attention != SessionAttentionNone group.Attention = mergeSessionAttention(group.Attention, attention) + groupWorking[rootID] = groupWorking[rootID] || exactWorking || localWorking // CHECK SESSION is only an inactivity inference. A freshly writing // member—or an authoritatively working daemon thread—means the grouped // root is demonstrably active, even if a linked child was left quiet @@ -1162,6 +1159,7 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string sessions := make([]LiveUsageSession, 0, len(groups)) activeCount := 0 + anyWorking := false for _, session := range groups { if session.Attention == SessionAttentionCheck && groupHasFreshActivity[session.ID] { session.Attention = SessionAttentionNone @@ -1171,6 +1169,7 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string if session.Active { activeCount++ } + anyWorking = anyWorking || groupWorking[session.ID] sessions = append(sessions, *session) } sort.Slice(sessions, func(i, j int) bool { @@ -1182,7 +1181,7 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string } return sessions[i].ID < sessions[j].ID }) - return sessions, activeCount + return sessions, activeCount, anyWorking } func sessionAttention(state sessionAttentionState, writerActive, writerLocksSupported bool, quietFor time.Duration, exactStatus sessionRuntimeStatus, exact bool) SessionAttention { diff --git a/internal/codex/live_usage_test.go b/internal/codex/live_usage_test.go index e27b41d3..803a387f 100644 --- a/internal/codex/live_usage_test.go +++ b/internal/codex/live_usage_test.go @@ -453,8 +453,8 @@ func TestLiveUsageReaderUsesOpenWriterAndCompletedTurnForInputWait(t *testing.T) if err != nil || len(usage.Sessions) != 1 || usage.Sessions[0].Attention != SessionAttentionInput { t.Fatalf("open completed CLI = %#v, %v; want input needed", usage, err) } - if !usage.CodexStatusKnown || !usage.CodexUp || !usage.CodexWorking { - t.Fatalf("held writer lock did not report live Codex activity: %#v", usage) + if !usage.CodexStatusKnown || !usage.CodexUp || usage.CodexWorking { + t.Fatalf("waiting writer lock did not report healthy idle Codex: %#v", usage) } appendRollout(t, path, attentionEventLine(now.Add(time.Second), "task_started", nil)+"\n") @@ -462,12 +462,18 @@ func TestLiveUsageReaderUsesOpenWriterAndCompletedTurnForInputWait(t *testing.T) if err != nil || usage.Sessions[0].Attention != SessionAttentionNone { t.Fatalf("open active CLI = %#v, %v; want no attention", usage, err) } + if !usage.CodexWorking { + t.Fatalf("working writer lifecycle did not report Codex activity: %#v", usage) + } appendRollout(t, path, attentionEventLine(now.Add(2*time.Second), "task_complete", nil)+"\n") usage, err = reader.FetchTokenUsage(context.Background()) if err != nil || usage.Sessions[0].Attention != SessionAttentionInput { t.Fatalf("second completed turn = %#v, %v; want input needed", usage, err) } + if usage.CodexWorking { + t.Fatalf("waiting writer lifecycle continued to report Codex activity: %#v", usage) + } release() usage, err = reader.FetchTokenUsage(context.Background()) if err != nil || usage.Sessions[0].Attention != SessionAttentionNone { @@ -539,10 +545,13 @@ func TestSessionSnapshotsSuppressesQuietChildCheckWhileGroupIsActive(t *testing. }} writers := map[string]struct{}{"root": {}, "child": {}} - sessions, active := reader.sessionSnapshots(now, writers, true, nil) + sessions, active, working := reader.sessionSnapshots(now, writers, true, nil) if len(sessions) != 1 || active != 1 { t.Fatalf("grouped sessions = %#v, active %d; want one active root", sessions, active) } + if !working { + t.Fatal("fresh working root did not mark the group as working") + } if got := sessions[0].Attention; got != SessionAttentionNone { t.Fatalf("fresh root inherited quiet child's uncertain attention = %v", got) } @@ -563,10 +572,13 @@ func TestSessionSnapshotsExactWorkingStatusSuppressesGroupedFallback(t *testing. writers := map[string]struct{}{"root": {}, "child": {}} statuses := map[string]sessionRuntimeStatus{"root": sessionRuntimeWorking} - sessions, active := reader.sessionSnapshots(now, writers, true, statuses) + sessions, active, working := reader.sessionSnapshots(now, writers, true, statuses) if len(sessions) != 1 || active != 1 { t.Fatalf("daemon-working group = %#v, active %d; want one active root", sessions, active) } + if !working { + t.Fatal("exact daemon status did not mark the group as working") + } if got := sessions[0].Attention; got != SessionAttentionNone { t.Fatalf("daemon-working root inherited quiet child's fallback = %v", got) } @@ -730,6 +742,15 @@ func TestLiveUsageReaderReportsCodexHealthAndWork(t *testing.T) { t.Fatalf("working Codex health = %#v, %v", working, err) } + reader.statusProvider = stubSessionStatusProvider{ + statuses: map[string]sessionRuntimeStatus{"health-thread": sessionRuntimeInput}, + } + waiting, err := reader.FetchTokenUsage(context.Background()) + if err != nil || !waiting.CodexStatusKnown || !waiting.CodexUp || waiting.CodexWorking || + len(waiting.Sessions) != 1 || waiting.Sessions[0].Attention != SessionAttentionInput { + t.Fatalf("waiting Codex health = %#v, %v", waiting, err) + } + reader.statusProvider = stubSessionStatusProvider{unavailable: true} unknown, err := reader.FetchTokenUsage(context.Background()) if err != nil || unknown.CodexStatusKnown || unknown.CodexUp || unknown.CodexWorking { @@ -739,19 +760,20 @@ func TestLiveUsageReaderReportsCodexHealthAndWork(t *testing.T) { func TestCodexRuntimeHealthCombinesAppServerAndWriterLocks(t *testing.T) { tests := []struct { - name string - appUp, appWorking, liveWriter, locksSupported bool - wantKnown, wantUp, wantWorking bool + name string + appUp, liveWriter, sessionWorking, locksSupported bool + wantKnown, wantUp, wantWorking bool }{ - {"working app server", true, true, false, false, true, true, true}, + {"working app server session", true, false, true, false, true, true, true}, {"idle app server", true, false, false, false, true, true, false}, - {"live writer without app server", false, false, true, true, true, true, true}, + {"waiting writer without app server", false, true, false, true, true, true, false}, + {"working writer without app server", false, true, true, true, true, true, true}, {"observable without live runtime", false, false, false, true, true, false, false}, {"unobservable", false, false, false, false, false, false, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - known, up, working := codexRuntimeHealth(tt.appUp, tt.appWorking, tt.liveWriter, tt.locksSupported) + known, up, working := codexRuntimeHealth(tt.appUp, tt.liveWriter, tt.sessionWorking, tt.locksSupported) if known != tt.wantKnown || up != tt.wantUp || working != tt.wantWorking { t.Fatalf("health = (%t, %t, %t), want (%t, %t, %t)", known, up, working, tt.wantKnown, tt.wantUp, tt.wantWorking) } diff --git a/internal/ui/model.go b/internal/ui/model.go index 2217a015..3926c6e0 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -1943,6 +1943,15 @@ func (m *Model) syncMonitorCodexStatus(usage codex.LiveUsageSnapshot) { m.monitorCodexWorking = usage.CodexWorking } +func (m Model) monitorHasVisibleWaitingSession() bool { + for _, session := range m.monitorSessionData { + if m.monitorSessionVisible(session) && session.attention != codex.SessionAttentionNone { + return true + } + } + return false +} + func (m *Model) resetMonitorFromSnapshot(message monitorFetchedMsg, paused bool) { m.monitorStartedAt = message.at m.monitorStoppedAt = time.Time{} diff --git a/internal/ui/tabs.go b/internal/ui/tabs.go index 8fc6dccb..9396bd52 100644 --- a/internal/ui/tabs.go +++ b/internal/ui/tabs.go @@ -228,6 +228,12 @@ func (m Model) monitorIndicatorColor(colors palette) imagecolor.Color { if m.monitorState != monitorRunning { return colors.dim } + if m.monitorHasVisibleWaitingSession() { + if m.phase%2 == 0 { + return colors.warning + } + return colors.warningDim + } if m.monitorCodexWorking { if m.phase%2 == 0 { return colors.success diff --git a/internal/ui/tabs_test.go b/internal/ui/tabs_test.go index a56d906b..57c385ad 100644 --- a/internal/ui/tabs_test.go +++ b/internal/ui/tabs_test.go @@ -261,6 +261,23 @@ func TestMonitorIndicatorUsesCodexActivityAndHealth(t *testing.T) { if model.monitorIndicatorColor(colors) != colors.success { t.Fatal("working indicator did not alternate to bright green") } + model.monitorSessionData = []monitorSession{{ + id: "waiting", displayed: true, active: true, attention: codex.SessionAttentionInput, + }} + if model.monitorIndicatorColor(colors) != colors.warning { + t.Fatal("visible waiting session did not take precedence with bright amber") + } + model.phase = 1 + if model.monitorIndicatorColor(colors) != colors.warningDim { + t.Fatal("waiting indicator did not alternate to dim amber") + } + model.monitorDismissed = map[string]monitorSessionDismissal{"waiting": {}} + model.phase = 0 + if model.monitorIndicatorColor(colors) != colors.success { + t.Fatal("dismissed waiting session continued to override working green") + } + model.monitorSessionData = nil + model.monitorDismissed = nil model.monitorCodexWorking = false if model.monitorIndicatorColor(colors) != colors.success { t.Fatal("idle Codex indicator was not steady green") diff --git a/internal/ui/theme.go b/internal/ui/theme.go index 8e20ef90..0dbc49a0 100644 --- a/internal/ui/theme.go +++ b/internal/ui/theme.go @@ -77,6 +77,7 @@ type palette struct { success imagecolor.Color successDim imagecolor.Color warning imagecolor.Color + warningDim imagecolor.Color danger imagecolor.Color background imagecolor.Color } @@ -92,6 +93,7 @@ func paletteFor(theme themeID) palette { success: lipgloss.Color("#67D391"), successDim: lipgloss.Color("#285B3B"), warning: lipgloss.Color("#FF8A3D"), + warningDim: lipgloss.Color("#713817"), danger: lipgloss.Color("#FF5F56"), background: lipgloss.Color("#1A0E05"), } @@ -104,6 +106,7 @@ func paletteFor(theme themeID) palette { success: lipgloss.Color("#57D68D"), successDim: lipgloss.Color("#25583D"), warning: lipgloss.Color("#E8C46A"), + warningDim: lipgloss.Color("#6D5B2F"), danger: lipgloss.Color("#FF6B83"), background: lipgloss.Color("#08111B"), } @@ -116,6 +119,7 @@ func paletteFor(theme themeID) palette { success: lipgloss.Color("#65D98B"), successDim: lipgloss.Color("#28583A"), warning: lipgloss.Color("#F9A8D4"), + warningDim: lipgloss.Color("#754C63"), danger: lipgloss.Color("#FF668F"), background: lipgloss.Color("#12081C"), } @@ -128,6 +132,7 @@ func paletteFor(theme themeID) palette { success: lipgloss.Color("#62D990"), successDim: lipgloss.Color("#28583C"), warning: lipgloss.Color("#8F7CFF"), + warningDim: lipgloss.Color("#493F80"), danger: lipgloss.Color("#FF668F"), background: lipgloss.Color("#180D29"), } @@ -140,6 +145,7 @@ func paletteFor(theme themeID) palette { success: lipgloss.Color("#00C853"), successDim: lipgloss.Color("#006B2D"), warning: lipgloss.Color("#FFCA58"), + warningDim: lipgloss.Color("#765D26"), danger: lipgloss.Color("#FF5F6D"), background: lipgloss.Color("#07130B"), }