diff --git a/README.md b/README.md index a2b943a1..b4369f9b 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,53 @@ Once a release has been published, Go users can install directly: go install github.com/merefield/codexometer@latest ``` +`go install` places the executable in `GOBIN` when that setting is non-empty; +otherwise it uses the `bin` directory under `GOPATH` (normally +`$HOME/go/bin`). That directory must be on `PATH` to run `codexometer` from any +working directory. + +On macOS or Linux, find the directory Go used: + +```sh +go_bin="$(go env GOBIN)" +if [ -z "$go_bin" ]; then go_bin="$(go env GOPATH)/bin"; fi +printf '%s\n' "$go_bin" +``` + +Add the printed directory to your shell configuration. For a default Go setup, +add this line to `~/.zshrc` on macOS with Zsh, or `~/.bashrc` on Linux with +Bash: + +```sh +export PATH="$PATH:$HOME/go/bin" +``` + +Restart the terminal, or reload the relevant file with `source ~/.zshrc` or +`source ~/.bashrc`. + +On Windows, PowerShell can discover Go's install directory and add it to the +current user's persistent `Path` without requiring administrator access: + +```powershell +$goBin = go env GOBIN +if (-not $goBin) { $goBin = Join-Path (go env GOPATH) "bin" } +$userPath = [Environment]::GetEnvironmentVariable("Path", "User") +if (($userPath -split ";") -notcontains $goBin) { + $newUserPath = if ($userPath) { "$userPath;$goBin" } else { $goBin } + [Environment]::SetEnvironmentVariable("Path", $newUserPath, "User") +} +``` + +Open a new terminal after changing the Windows `Path`. Confirm the command is +available everywhere: + +```sh +codexometer --version +``` + +On macOS/Linux, `command -v codexometer` shows the resolved executable. In +PowerShell, use `Get-Command codexometer`. + To build the current checkout: ```sh @@ -92,8 +139,20 @@ cd codexometer go build -trimpath -ldflags="-s -w" -o codexometer . ``` -Then move `codexometer` somewhere on your `PATH`, or run it directly from the -project directory. +On Windows, use `-o codexometer.exe` instead. The compiled executable is +standalone and does not require Go at runtime. Run it from the project directory +as `./codexometer` (or `.\codexometer.exe` in PowerShell), or copy it into any +directory already on `PATH`. A common per-user option on macOS/Linux is: + +```sh +mkdir -p "$HOME/.local/bin" +install -m 0755 codexometer "$HOME/.local/bin/codexometer" +``` + +If you use that location, ensure `$HOME/.local/bin` is also included in `PATH` +using the same shell-configuration steps above. On Windows, a directory such as +`$HOME\bin` can be created, added to the user `Path`, and used for +`codexometer.exe`. ## Quick start @@ -151,10 +210,10 @@ codexometer --codex /path/to/codex | Key | Action | | --- | --- | | `t` | Cycle color themes | -| `Tab` | Select the next meter-style tab | -| `Shift+Tab` | Select the previous meter-style tab | +| `Tab` | Select the next top-level tab: Quota, Monitor, or Benchmark | +| `Shift+Tab` | Select the previous top-level tab | | `r` | Refresh quota data immediately | -| `s` | Start recording (Monitor view only) | +| `s` | Cycle presentation style in Quota; start recording in Monitor | | `p` | Stop and take a final up-to-date reading (Monitor view only) | | `b` | Run the selected challenge (Benchmark view only) | | `a` | Arm, then confirm, Run All (Benchmark view only) | @@ -166,13 +225,64 @@ codexometer --codex /path/to/codex | `Esc` | Quit | | `Ctrl+C` | Quit | -The responsive tab rail below the account status selects meter styles by mouse, -`Tab`, or `Shift+Tab`; labels condense automatically as the terminal narrows. -The footer presents the remaining actions as clickable buttons. Move the pointer -over a tab or button to highlight it, or click it to activate it. Controls pulse -briefly when activated by mouse or keyboard. The keyboard assignments remain -available in terminals without mouse support. Theme and tab changes are -immediate and do not trigger a network refresh. +The responsive top rail below the account status selects Quota, Monitor, or +Benchmark by mouse, `Tab`, or `Shift+Tab`. Quota adds a second rail for Bars, +Pie, Consumption Pace, and Fuel Tank; select these with the mouse or cycle them +with `s`. Codexometer remembers the selected Quota presentation when you leave +and return. Both rails condense automatically as the terminal narrows. +The footer presents the remaining actions as clickable buttons, including Style +only while Quota is active. Move the pointer over a tab or button to highlight +it, or click it to activate it. Controls pulse briefly when activated by mouse +or keyboard. The keyboard assignments remain available in terminals without +mouse support. Theme and tab changes are immediate and do not trigger a network +refresh. + +### Quota health signal + +The top-right signal keeps `ONLINE` in the selected theme color while its dot +and quota-health label use fixed semantic colors: + +- green `QUOTA CLEAR` — consumption is keeping pace with, or trailing, elapsed + window time; +- blue `QUOTA WATCH` — the current average burn rate would exhaust at least one + quota window before it resets; +- amber `LIMIT NEAR` — excess pace projects exhaustion within the first quarter + of the time still remaining, or no more than 5% remains while over pace; +- red `QUOTA EXHAUSTED` — a window is at 100% or Codex explicitly reports its + rate limit reached. + +Codexometer reports the worst state among all returned quota windows. If reset +timing is unavailable, it conservatively falls back to remaining capacity: +Watch at 20% and Near at 5%. Scanning and stale-signal states take precedence +while quota health cannot be evaluated reliably. + +For each window with valid duration and reset data, Codexometer calculates: + +- `U`, the used quota fraction (`usedPercent / 100`); +- `E`, the elapsed window fraction, using `reset time - window duration` as the + window start; +- remaining quota `1 - U` and remaining time `1 - E`; +- projected time to exhaustion, as a fraction of the complete window: + `E × (1 - U) / U`. + +It then applies these rules in severity order: + +1. **Exhausted** if `usedPercent` is 100 or Codex explicitly reports that a + rate limit has been reached. +2. **Clear** if `U <= E`: quota consumption is no further advanced than the + reset cycle. +3. **Limit Near** when over pace and either no more than 5% quota remains, or + projected exhaustion is within the first 25% of the time remaining to reset. +4. **Watch** for every other over-pace window (`U > E`). + +This means 10% remaining can correctly stay Clear when less than 10% of the +window remains: quota is low, but reset is closer than exhaustion at the +observed average pace. Conversely, a window with plenty remaining can reach +Watch or Limit Near if it is being consumed very early and projects exhaustion +well before reset. Percentages are clamped to 0–100 before classification. If +duration or reset data is missing or invalid, pace cannot be calculated, so the +fallback is Clear above 20% remaining, Watch at 20% or less, Limit Near at 5% +or less, and Exhausted at 0%. ## Themes @@ -186,53 +296,60 @@ Press `t` to cycle: The default remains the original green hacker-terminal presentation. -## Meter styles +## Views and quota presentations -Select a tab with the mouse, `Tab`, or `Shift+Tab`: +The top-level tabs are **Quota**, **Monitor**, and **Benchmark**. Within Quota, +choose one of these four presentations with its sub-tab or `s`: 1. **Bars** — chunky quota bars, with one full-width rate-limit window per row. -2. **Monitor** — establishes a zero baseline across locally active Codex - sessions when you press Start. A large readout follows newly appended token - telemetry once per second and shows total observed tokens, elapsed time, and - average rate; clickable Start and Stop controls sit beside it. 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 window's movement, apportioned by that share. - A root discovered part-way through an interval gets an honestly labelled - partial first bar and its rate uses that root's own observed lifetime. New - bars enter on the right, older bars move left, and each Y axis automatically - rescales to its visible samples. When the terminal cannot fit every root, - use Page Up, Page Down, or the mouse wheel to page through the rows. Stop - performs an immediate final local read instead of relying on the latest - graph sample. -3. **Pie** — clockwise-filled circles rendered on a 2×4 sub-cell Braille canvas +2. **Pie** — clockwise-filled circles rendered on a 2×4 sub-cell Braille canvas for clean curves at any size. -4. **Consumption Pace** — a signed horizontal scale comparing elapsed window +3. **Consumption Pace** — a signed horizontal scale comparing elapsed window time with quota consumed. Positive headroom means consumption is behind elapsed time; a negative deficit means quota is being used too quickly. -5. **Fuel Tank** — a reverse gauge whose bright segment shows remaining range +4. **Fuel Tank** — a reverse gauge whose bright segment shows remaining range and whose dark segment shows consumed capacity, labelled from Empty to Full; one full-width tank appears per row. Its reset-cycle comparison also drains backward and aligns exactly with the tank's first and last inner cells. -6. **Benchmark** — runs a selected hermetic coding challenge, or the complete - challenge catalog, against every visible model and each reasoning effort - that model advertises. Results arrive sequentially in a ranked table with - task, pass/fail, wall time, tokens, and estimated standard API-equivalent cost. - Filter the table to all, passed, or failed trials. Scroll a long result matrix - with Page Up, Page Down, or the mouse wheel. Click any column-heading button - to sort by that field; click it again to reverse the order. + +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 + 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 + window's movement, apportioned by that share. A root discovered part-way + through an interval gets an honestly labelled partial first bar and its rate + uses that root's own observed lifetime. New bars enter on the right, older + bars move left, and each Y axis automatically rescales to its visible samples. + When the terminal cannot fit every root, use Page Up, Page Down, or the mouse + wheel to page through the rows. Stop performs an immediate final local read + instead of relying on the latest graph sample. +- **Benchmark** — runs a selected hermetic coding challenge, or the complete + challenge catalog, against every visible model and each reasoning effort + that model advertises. Results arrive sequentially in a ranked table with + task, pass/fail, wall time, tokens, and estimated standard API-equivalent cost. + Filter the table to all, passed, or failed trials. Scroll a long result matrix + with Page Up, Page Down, or the mouse wheel. Click any column-heading button + to sort by that field; click it again to reverse the order. The layout responds to both terminal dimensions and the number of rate limits returned by Codex. Header, status, errors, footer, and meter grid divide the available rectangle proportionally. Bars, Consumption Pace, and Fuel Tank flow -one meter per row. +one meter per row. Codexometer does not hardcode the currently returned window +set: it renders every primary and secondary window from every limit bucket, +including a 300-minute window as `5 HOURS`. When more windows arrive, +horizontal views remove decorative row gaps before compressing the cards, while +Pie adds rows or columns only when each radial card retains a useful width. Meter rows always use identical heights; indivisible spare rows become quiet space above the footer instead of stretching one quota block more than another. Pie uses at least two columns when multiple limits exist, adding rows when that @@ -676,8 +793,8 @@ selected font includes block, arrow, and emoji glyphs. ### The terminal is too small Codexometer adapts its header and meter widths, but rich gauges need enough -rows to display every quota window. Increase the pane height or use `Tab` to -return to the compact default bar style. +rows to display every quota window. Increase the pane height or press `s` in +Quota to return to the compact default bar style. ### Monitor remains at zero diff --git a/internal/ui/meters.go b/internal/ui/meters.go index fb18d730..3904f171 100644 --- a/internal/ui/meters.go +++ b/internal/ui/meters.go @@ -25,14 +25,20 @@ func renderMeterGrid(width, height int, meters []codex.Meter, style meterStyleID if len(meters) == 0 { return "" } - const gap = 1 + const columnGap = 1 columns := meterGridColumns(width, height, len(meters), style) rows := (len(meters) + columns - 1) / columns - columnWidths := distributeSpace(width-(columns-1)*gap, columns) + rowGap := 1 + // A framed meter needs at least its title, body, and bottom border. Drop the + // decorative blank row before shrinking cards below that useful minimum. + if height < rows*3+(rows-1)*rowGap { + rowGap = 0 + } + columnWidths := distributeSpace(width-(columns-1)*columnGap, columns) // Keep every meter card exactly the same height. Any indivisible remainder is // left below the grid, immediately above the footer, rather than making the // first card's visualization taller than the others. - rowHeight := max((height-(rows-1)*gap)/rows, 1) + rowHeight := max((height-(rows-1)*rowGap)/rows, 1) renderedRows := make([]string, 0, rows) for row := 0; row < rows; row++ { @@ -40,7 +46,7 @@ func renderMeterGrid(width, height int, meters []codex.Meter, style meterStyleID for column := 0; column < columns; column++ { meterIndex := row*columns + column if column > 0 { - pieces = append(pieces, strings.Repeat(" ", gap)) + pieces = append(pieces, strings.Repeat(" ", columnGap)) } if meterIndex < len(meters) { pieces = append(pieces, renderMeterArea(columnWidths[column], rowHeight, meters[meterIndex], style, colors)) @@ -50,7 +56,7 @@ func renderMeterGrid(width, height int, meters []codex.Meter, style meterStyleID } renderedRows = append(renderedRows, lipgloss.JoinHorizontal(lipgloss.Top, pieces...)) } - grid := strings.Join(renderedRows, "\n\n") + grid := strings.Join(renderedRows, strings.Repeat("\n", rowGap+1)) if padding := height - lipgloss.Height(grid); padding > 0 { grid += strings.Repeat("\n", padding) } @@ -62,12 +68,18 @@ func meterGridColumns(width, height, meterCount int, style meterStyleID) int { return 1 } minimumColumns := 1 + maximumColumns := meterCount if isRadialStyle(style) && meterCount > 1 { minimumColumns = 2 + // Below this width the circular canvas and title both become ambiguous. + // Retain at least two columns, then add more only when each card remains + // meaningfully readable. + const minimumRadialCardWidth = 28 + maximumColumns = min(meterCount, max(width/minimumRadialCardWidth, minimumColumns)) } bestColumns := minimumColumns bestDetail := -1 - for columns := minimumColumns; columns <= meterCount; columns++ { + for columns := minimumColumns; columns <= maximumColumns; columns++ { rows := (meterCount + columns - 1) / columns cellWidth := max((width-(columns-1))/columns, 1) cellHeight := max((height-(rows-1))/rows, 1) @@ -133,6 +145,7 @@ func renderMeterArea(width, height int, meter codex.Meter, style meterStyleID, c stats = usedText } } + stats = ansi.Truncate(stats, innerWidth, "") reset := "RESET DATA UNAVAILABLE" if meter.Window.ResetsAt != nil { diff --git a/internal/ui/model.go b/internal/ui/model.go index a4f611f7..cc57f5a6 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -43,6 +43,9 @@ type Model struct { phase int theme themeID meterStyle meterStyleID + quotaMeterStyle meterStyleID + hoveredMainTab mainTabID + mainTabHovered bool hoveredStyle meterStyleID styleHovered bool flashedStyle meterStyleID @@ -233,6 +236,7 @@ type footerButtonID int const ( footerButtonNone footerButtonID = iota footerButtonTheme + footerButtonStyle footerButtonRefresh footerButtonQuit footerButtonMonitorGo @@ -261,6 +265,13 @@ var footerButtonDefinitions = []footerButton{ {id: footerButtonQuit, label: "[ (Q)UIT ]", compact: "[Q]"}, } +var quotaFooterButtonDefinitions = []footerButton{ + {id: footerButtonTheme, label: "[ (T)HEME ]", compact: "[T]"}, + {id: footerButtonStyle, label: "[ (S)TYLE ]", compact: "[S]"}, + {id: footerButtonRefresh, label: "[ (R)EFRESH ]", compact: "[R]"}, + {id: footerButtonQuit, label: "[ (Q)UIT ]", compact: "[Q]"}, +} + func New(fetcher Fetcher, refreshEvery time.Duration) Model { if refreshEvery <= 0 { refreshEvery = time.Minute @@ -295,13 +306,16 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { case "t": return m.pressFooterButton(footerButtonTheme) case "s": + if m.meterStyle.isQuota() { + return m.pressFooterButton(footerButtonStyle) + } if m.meterStyle == styleMonitor { return m.pressFooterButton(footerButtonMonitorGo) } case "tab": - return m.pressStyleTab(m.meterStyle.next()) + return m.pressMainTab(m.currentMainTab().next()) case "shift+tab": - return m.pressStyleTab(m.meterStyle.previous()) + return m.pressMainTab(m.currentMainTab().previous()) case "r": return m.pressFooterButton(footerButtonRefresh) case "q": @@ -355,7 +369,18 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { } } case tea.MouseMsg: - if style, ok := m.styleTabAt(message.X, message.Y); ok { + if tab, ok := m.mainTabAt(message.X, message.Y); ok { + m.mainTabHovered = true + m.hoveredMainTab = tab + m.styleHovered = false + m.hoveredButton = footerButtonNone + if message.Button == tea.MouseButtonLeft && message.Action == tea.MouseActionPress { + return m.pressMainTab(tab) + } + return m, nil + } + m.mainTabHovered = false + if style, ok := m.quotaStyleTabAt(message.X, message.Y); ok { m.styleHovered = true m.hoveredStyle = style m.hoveredButton = footerButtonNone @@ -526,6 +551,9 @@ func (m Model) pressStyleTab(style meterStyleID) (tea.Model, tea.Cmd) { return m, nil } m.meterStyle = style + if style.isQuota() { + m.quotaMeterStyle = style + } m.styleSequence++ m.flashedStyle = style m.styleFlashing = true @@ -563,6 +591,11 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { switch button { case footerButtonTheme: m.theme = m.theme.next() + case footerButtonStyle: + if m.meterStyle.isQuota() { + m.meterStyle = m.meterStyle.nextQuota() + m.quotaMeterStyle = m.meterStyle + } case footerButtonRefresh: if !m.loading { m.loading = true @@ -663,7 +696,7 @@ func (m Model) footerButtonAt(x, y int) footerButtonID { return footerButtonNone } localX := x - 2 - buttons, separator := footerButtonLayoutWithTheme(layout.contentWidth, paletteFor(m.theme).name) + buttons, separator := footerButtonLayoutWithTheme(layout.contentWidth, paletteFor(m.theme).name, m.meterStyle.isQuota()) buttonX := 0 for _, button := range buttons { if localX >= buttonX && localX < buttonX+len(button.label) { @@ -677,6 +710,7 @@ func (m Model) footerButtonAt(x, y int) footerButtonID { type dashboardGeometry struct { contentWidth int tabsY int + quotaTabsY int meterHeight int meterY int footerY int @@ -698,7 +732,10 @@ func (m Model) dashboardLayout() dashboardGeometry { headerHeight = 2 } const statusHeight = 1 - const tabsHeight = 1 + tabsHeight := 1 + if m.meterStyle.isQuota() { + tabsHeight++ + } const framedErrorHeight = 3 const footerHeight = 2 extraHeight := 0 @@ -709,6 +746,10 @@ func (m Model) dashboardLayout() dashboardGeometry { extraHeight += framedErrorHeight } tabsY := 1 + headerHeight + statusHeight + quotaTabsY := -1 + if m.meterStyle.isQuota() { + quotaTabsY = tabsY + 1 + } meterY := tabsY + tabsHeight + extraHeight meterHeight := max(contentHeight-headerHeight-statusHeight-tabsHeight-extraHeight-footerHeight, 1) footerY := meterY @@ -718,6 +759,7 @@ func (m Model) dashboardLayout() dashboardGeometry { return dashboardGeometry{ contentWidth: contentWidth, tabsY: tabsY, + quotaTabsY: quotaTabsY, meterHeight: meterHeight, meterY: meterY, footerY: footerY, @@ -867,9 +909,13 @@ func (m Model) contentWidth() int { return max(width-4, 1) } -func footerButtonLayout(width int) ([]footerButton, string) { - buttons := make([]footerButton, len(footerButtonDefinitions)) - copy(buttons, footerButtonDefinitions) +func footerButtonLayout(width int, quota bool) ([]footerButton, string) { + definitions := footerButtonDefinitions + if quota { + definitions = quotaFooterButtonDefinitions + } + buttons := make([]footerButton, len(definitions)) + copy(buttons, definitions) separator := " " total := len(separator) * (len(buttons) - 1) for _, button := range buttons { @@ -885,13 +931,13 @@ func footerButtonLayout(width int) ([]footerButton, string) { return buttons, separator } -func footerButtonLayoutWithTheme(width int, themeName string) ([]footerButton, string) { +func footerButtonLayoutWithTheme(width int, themeName string, quota bool) ([]footerButton, string) { themeWidth := len("THEME // ") + len(themeName) available := width - themeWidth - 1 if available <= 0 { return nil, " " } - buttons, separator := footerButtonLayout(available) + buttons, separator := footerButtonLayout(available, quota) visible := buttons[:0] used := 0 for _, button := range buttons { diff --git a/internal/ui/model_test.go b/internal/ui/model_test.go index 776f8106..9032e617 100644 --- a/internal/ui/model_test.go +++ b/internal/ui/model_test.go @@ -39,24 +39,19 @@ func TestThemeHotkeyCyclesAndWraps(t *testing.T) { } } -func TestTabCyclesStylesAndShiftTabMovesBack(t *testing.T) { +func TestTabCyclesMainTabsAndShiftTabMovesBack(t *testing.T) { model := New(nil, time.Minute) - for want := styleMonitor; want < styleCount; want++ { + for _, want := range []meterStyleID{styleMonitor, styleBenchmark, styleBars} { updated, _ := model.Update(tea.KeyMsg{Type: tea.KeyTab}) model = updated.(Model) if model.meterStyle != want { t.Fatalf("got meter style %d, want %d", model.meterStyle, want) } } - updated, _ := model.Update(tea.KeyMsg{Type: tea.KeyTab}) - model = updated.(Model) - if model.meterStyle != styleBars { - t.Fatalf("meter style did not wrap: got %d", model.meterStyle) - } - updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyShiftTab}) + updated, _ := model.Update(tea.KeyMsg{Type: tea.KeyShiftTab}) model = updated.(Model) if model.meterStyle != styleBenchmark { - t.Fatalf("reverse style navigation got %d, want %d", model.meterStyle, styleBenchmark) + t.Fatalf("reverse main-tab navigation got %d, want %d", model.meterStyle, styleBenchmark) } } @@ -178,6 +173,12 @@ func TestFooterButtonsSupportHoverAndMouseClicks(t *testing.T) { t.Fatalf("theme click selected theme=%d flash=%d, want theme=%d flash=%d", model.theme, model.flashedButton, themeRust, footerButtonTheme) } + updated, command = model.Update(footerMouseMessage(t, model, footerButtonStyle, tea.MouseActionPress)) + model = updated.(Model) + if command == nil || model.meterStyle != stylePie || model.flashedButton != footerButtonStyle { + t.Fatalf("style click selected style=%d flash=%d", model.meterStyle, model.flashedButton) + } + updated, command = model.Update(footerMouseMessage(t, model, footerButtonRefresh, tea.MouseActionPress)) model = updated.(Model) if !model.loading || command == nil { @@ -191,6 +192,22 @@ func TestFooterButtonsSupportHoverAndMouseClicks(t *testing.T) { } } +func TestStyleFooterButtonOnlyExistsOnQuota(t *testing.T) { + for _, style := range []meterStyleID{styleMonitor, styleBenchmark} { + model := Model{snapshot: codex.DemoSnapshot(), width: 100, height: 30, meterStyle: style} + if _, ok := footerButtonByID(model, footerButtonStyle); ok { + t.Fatalf("%s footer exposed the Style button", style.name()) + } + for y := 0; y < model.height; y++ { + for x := 0; x < model.width; x++ { + if got := model.footerButtonAt(x, y); got == footerButtonStyle { + t.Fatalf("%s exposed hidden Style hit target at %d,%d", style.name(), x, y) + } + } + } + } +} + func TestFooterHitGeometryMatchesRenderedButtonsAcrossSizes(t *testing.T) { for _, test := range []struct { name string @@ -204,6 +221,7 @@ func TestFooterHitGeometryMatchesRenderedButtonsAcrossSizes(t *testing.T) { {name: "large error", width: 120, height: 40, withError: true}, {name: "empty quota", width: 80, height: 24, empty: true}, {name: "empty monitor", width: 80, height: 24, empty: true, style: styleMonitor}, + {name: "benchmark", width: 100, height: 30, style: styleBenchmark}, } { t.Run(test.name, func(t *testing.T) { model := New(stubFetcher{snapshot: codex.DemoSnapshot()}, time.Minute) @@ -218,7 +236,9 @@ func TestFooterHitGeometryMatchesRenderedButtonsAcrossSizes(t *testing.T) { model.err = errors.New("stale quota signal") } layout := model.dashboardLayout() - for _, id := range []footerButtonID{footerButtonTheme, footerButtonRefresh, footerButtonQuit} { + buttons, _ := footerButtonLayoutWithTheme(layout.contentWidth, paletteFor(model.theme).name, model.meterStyle.isQuota()) + for _, visible := range buttons { + id := visible.id mouse := footerMouseMessage(t, model, id, tea.MouseActionMotion) if mouse.Y != layout.footerY+1 { t.Errorf("rendered footer y=%d, calculated y=%d", mouse.Y, layout.footerY+1) @@ -279,7 +299,7 @@ func TestFooterButtonHotkeyFlashesAndLatestPulseWins(t *testing.T) { } func TestFooterButtonLabelsEmbedHotkeysWithPadding(t *testing.T) { - buttons, separator := footerButtonLayout(100) + buttons, separator := footerButtonLayout(100, false) want := []string{"[ (T)HEME ]", "[ (R)EFRESH ]", "[ (Q)UIT ]"} if separator != " " || len(buttons) != len(want) { t.Fatalf("unexpected full footer layout: separator=%q buttons=%#v", separator, buttons) @@ -290,7 +310,7 @@ func TestFooterButtonLabelsEmbedHotkeysWithPadding(t *testing.T) { } } - compact, separator := footerButtonLayout(20) + compact, separator := footerButtonLayout(20, false) if separator != " " { t.Fatalf("compact separator = %q, want one space", separator) } @@ -299,22 +319,35 @@ func TestFooterButtonLabelsEmbedHotkeysWithPadding(t *testing.T) { t.Errorf("compact button %d label = %q, want %q", index, compact[index].label, label) } } + + quota, separator := footerButtonLayout(100, true) + quotaWant := []string{"[ (T)HEME ]", "[ (S)TYLE ]", "[ (R)EFRESH ]", "[ (Q)UIT ]"} + if separator != " " || len(quota) != len(quotaWant) { + t.Fatalf("unexpected Quota footer layout: separator=%q buttons=%#v", separator, quota) + } + for index, label := range quotaWant { + if quota[index].label != label { + t.Errorf("Quota button %d label = %q, want %q", index, quota[index].label, label) + } + } } func TestFooterLayoutNeverHitTestsControlsTruncatedByTheme(t *testing.T) { for _, themeName := range []string{"HACKER", "BLUE STEEL", "ULTRAVIOLET"} { for width := 1; width <= 60; width++ { - buttons, separator := footerButtonLayoutWithTheme(width, themeName) - controlsWidth := 0 - for index, button := range buttons { - if index > 0 { - controlsWidth += len(separator) + for _, quota := range []bool{false, true} { + buttons, separator := footerButtonLayoutWithTheme(width, themeName, quota) + controlsWidth := 0 + for index, button := range buttons { + if index > 0 { + controlsWidth += len(separator) + } + controlsWidth += len(button.label) + } + available := max(width-len("THEME // ")-len(themeName)-1, 0) + if controlsWidth > available { + t.Fatalf("theme=%q width=%d quota=%v exposes %d cells of controls in %d available cells", themeName, width, quota, controlsWidth, available) } - controlsWidth += len(button.label) - } - available := max(width-len("THEME // ")-len(themeName)-1, 0) - if controlsWidth > available { - t.Fatalf("theme=%q width=%d exposes %d cells of controls in %d available cells", themeName, width, controlsWidth, available) } } } @@ -336,7 +369,7 @@ func footerMouseMessage(t *testing.T, model Model, id footerButtonID, action tea } func footerButtonByID(model Model, id footerButtonID) (footerButton, bool) { - buttons, _ := footerButtonLayoutWithTheme(model.contentWidth(), paletteFor(model.theme).name) + buttons, _ := footerButtonLayoutWithTheme(model.contentWidth(), paletteFor(model.theme).name, model.meterStyle.isQuota()) for _, button := range buttons { if button.id == id { return button, true diff --git a/internal/ui/quota_status.go b/internal/ui/quota_status.go new file mode 100644 index 00000000..e26f5626 --- /dev/null +++ b/internal/ui/quota_status.go @@ -0,0 +1,126 @@ +package ui + +import ( + "time" + + "github.com/charmbracelet/lipgloss" + + "github.com/merefield/codexometer/internal/codex" +) + +type quotaHealth int + +const ( + quotaHealthUnknown quotaHealth = iota + quotaHealthClear + quotaHealthWatch + quotaHealthNear + quotaHealthExhausted +) + +func (h quotaHealth) label() string { + return [...]string{ + "QUOTA UNKNOWN", + "QUOTA CLEAR", + "QUOTA WATCH", + "LIMIT NEAR", + "QUOTA EXHAUSTED", + }[h] +} + +func (h quotaHealth) compactLabel() string { + return [...]string{ + "UNKNOWN", + "CLEAR", + "WATCH", + "NEAR", + "EXHAUSTED", + }[h] +} + +func (h quotaHealth) color(colors palette) lipgloss.Color { + switch h { + case quotaHealthClear: + return lipgloss.Color("#57FF8A") + case quotaHealthWatch: + return lipgloss.Color("#67B7FF") + case quotaHealthNear: + return lipgloss.Color("#FFB454") + case quotaHealthExhausted: + return lipgloss.Color("#FF5F6D") + default: + return colors.dim + } +} + +func snapshotQuotaHealth(snapshot codex.Snapshot, now time.Time) quotaHealth { + if snapshotReportsLimitReached(snapshot) { + return quotaHealthExhausted + } + meters := snapshot.Meters() + if len(meters) == 0 { + return quotaHealthUnknown + } + health := quotaHealthClear + for _, meter := range meters { + health = max(health, windowQuotaHealth(meter.Window, now)) + } + return health +} + +func windowQuotaHealth(window codex.Window, now time.Time) quotaHealth { + used := min(max(window.UsedPercent, 0), 100) + if used >= 100 { + return quotaHealthExhausted + } + if window.WindowDurationMins == nil || window.ResetsAt == nil || *window.WindowDurationMins <= 0 { + return quotaHealthWithoutPace(used) + } + + duration := time.Duration(*window.WindowDurationMins) * time.Minute + resetAt := time.Unix(*window.ResetsAt, 0) + elapsedDuration := now.Sub(resetAt.Add(-duration)) + if elapsedDuration <= 0 || elapsedDuration >= duration || used == 0 { + return quotaHealthWithoutPace(used) + } + + elapsed := float64(elapsedDuration) / float64(duration) + usedFraction := float64(used) / 100 + if usedFraction <= elapsed { + return quotaHealthClear + } + + remainingQuota := 1 - usedFraction + remainingTime := 1 - elapsed + timeToExhaustion := elapsed * remainingQuota / usedFraction + if remainingQuota <= 0.05 || timeToExhaustion <= remainingTime*0.25 { + return quotaHealthNear + } + return quotaHealthWatch +} + +func quotaHealthWithoutPace(used int) quotaHealth { + switch { + case used >= 95: + return quotaHealthNear + case used >= 80: + return quotaHealthWatch + default: + return quotaHealthClear + } +} + +func snapshotReportsLimitReached(snapshot codex.Snapshot) bool { + reached := func(limit codex.RateLimitSnapshot) bool { + return limit.RateLimitReachedType != nil && *limit.RateLimitReachedType != "" + } + if reached(snapshot.RateLimits) { + return true + } + for _, limit := range snapshot.RateLimitsByLimitID { + if reached(limit) { + return true + } + } + return false +} diff --git a/internal/ui/quota_status_test.go b/internal/ui/quota_status_test.go new file mode 100644 index 00000000..bbb20e59 --- /dev/null +++ b/internal/ui/quota_status_test.go @@ -0,0 +1,119 @@ +package ui + +import ( + "strings" + "testing" + "time" + + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + + "github.com/merefield/codexometer/internal/codex" +) + +func TestWindowQuotaHealthUsesBurnPaceAgainstResetProgress(t *testing.T) { + now := time.Date(2026, time.August, 12, 12, 0, 0, 0, time.UTC) + for _, test := range []struct { + name string + used int + elapsedPct int + want quotaHealth + }{ + {name: "clear with ample quota", used: 20, elapsedPct: 50, want: quotaHealthClear}, + {name: "clear when low quota matches late reset", used: 90, elapsedPct: 95, want: quotaHealthClear}, + {name: "watch when low quota is burning too quickly", used: 85, elapsedPct: 80, want: quotaHealthWatch}, + {name: "near when projected exhaustion is much earlier than reset", used: 40, elapsedPct: 10, want: quotaHealthNear}, + {name: "near when less than five percent remains at excess pace", used: 96, elapsedPct: 90, want: quotaHealthNear}, + {name: "exhausted", used: 100, elapsedPct: 99, want: quotaHealthExhausted}, + } { + t.Run(test.name, func(t *testing.T) { + window := quotaHealthTestWindow(now, test.used, test.elapsedPct) + if got := windowQuotaHealth(window, now); got != test.want { + t.Fatalf("health = %s, want %s", got.label(), test.want.label()) + } + }) + } +} + +func TestWindowQuotaHealthFallsBackToRemainingQuotaWithoutTiming(t *testing.T) { + for _, test := range []struct { + used int + want quotaHealth + }{ + {used: 79, want: quotaHealthClear}, + {used: 80, want: quotaHealthWatch}, + {used: 95, want: quotaHealthNear}, + {used: 100, want: quotaHealthExhausted}, + } { + if got := windowQuotaHealth(codex.Window{UsedPercent: test.used}, time.Now()); got != test.want { + t.Errorf("used %d health = %s, want %s", test.used, got.label(), test.want.label()) + } + } +} + +func TestSnapshotQuotaHealthUsesWorstWindowAndExplicitLimitSignal(t *testing.T) { + now := time.Date(2026, time.August, 12, 12, 0, 0, 0, time.UTC) + clearWindow := quotaHealthTestWindow(now, 20, 50) + watchWindow := quotaHealthTestWindow(now, 85, 80) + snapshot := codex.Snapshot{RateLimits: codex.RateLimitSnapshot{Primary: &clearWindow, Secondary: &watchWindow}} + if got := snapshotQuotaHealth(snapshot, now); got != quotaHealthWatch { + t.Fatalf("worst-window health = %s, want %s", got.label(), quotaHealthWatch.label()) + } + + reached := "primary" + snapshot.RateLimits.RateLimitReachedType = &reached + if got := snapshotQuotaHealth(snapshot, now); got != quotaHealthExhausted { + t.Fatalf("explicit reached health = %s, want %s", got.label(), quotaHealthExhausted.label()) + } + + if got := snapshotQuotaHealth(codex.Snapshot{}, now); got != quotaHealthUnknown { + t.Fatalf("empty snapshot health = %s, want %s", got.label(), quotaHealthUnknown.label()) + } +} + +func TestQuotaHealthUsesSemanticSignalColors(t *testing.T) { + colors := paletteFor(themeNightshade) + for _, test := range []struct { + health quotaHealth + want lipgloss.Color + }{ + {quotaHealthClear, lipgloss.Color("#57FF8A")}, + {quotaHealthWatch, lipgloss.Color("#67B7FF")}, + {quotaHealthNear, lipgloss.Color("#FFB454")}, + {quotaHealthExhausted, lipgloss.Color("#FF5F6D")}, + } { + if got := test.health.color(colors); got != test.want { + t.Errorf("%s color = %q, want %q", test.health.label(), got, test.want) + } + } +} + +func TestQuotaSignalLabelsRemainResponsive(t *testing.T) { + now := time.Now() + window := quotaHealthTestWindow(now, 85, 80) + model := Model{snapshot: codex.Snapshot{RateLimits: codex.RateLimitSnapshot{Primary: &window}}} + colors := paletteFor(themeUltraviolet) + for _, test := range []struct { + width int + want string + }{ + {width: 80, want: "● ONLINE // QUOTA WATCH"}, + {width: 40, want: "● ON // WATCH"}, + {width: 20, want: "● WATCH"}, + } { + got := ansi.Strip(model.renderSignalStatus(test.width, colors)) + if got != test.want { + t.Errorf("width %d status = %q, want %q", test.width, got, test.want) + } + if strings.Contains(got, "EXHAUSTED") { + t.Errorf("width %d rendered the wrong health label: %q", test.width, got) + } + } +} + +func quotaHealthTestWindow(now time.Time, used, elapsedPercent int) codex.Window { + durationMinutes := int64(100) + remainingMinutes := int64(100 - elapsedPercent) + reset := now.Add(time.Duration(remainingMinutes) * time.Minute).Unix() + return codex.Window{UsedPercent: used, WindowDurationMins: &durationMinutes, ResetsAt: &reset} +} diff --git a/internal/ui/tabs.go b/internal/ui/tabs.go index ae34c301..0ac06789 100644 --- a/internal/ui/tabs.go +++ b/internal/ui/tabs.go @@ -3,9 +3,34 @@ package ui import ( "strings" + tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" ) +type mainTabID int + +const ( + mainTabQuota mainTabID = iota + mainTabMonitor + mainTabBenchmark + mainTabCount +) + +func (t mainTabID) next() mainTabID { + return (t + 1) % mainTabCount +} + +func (t mainTabID) previous() mainTabID { + return (t - 1 + mainTabCount) % mainTabCount +} + +type mainTab struct { + tab mainTabID + label string + x int + width int +} + type styleTab struct { style meterStyleID label string @@ -13,23 +38,7 @@ type styleTab struct { width int } -func styleTabLayout(width int, recording bool) ([]styleTab, string) { - monitorFull := "╭ MONITOR ╮" - monitorCompact := "╭MON╮" - monitorMinimal := "[M]" - microMonitor := "M" - if recording { - monitorFull = "╭ MONITOR ●╮" - monitorCompact = "╭MON●╮" - monitorMinimal = "[M●]" - microMonitor = "●" - } - tiers := [][]string{ - {"╭ BARS ╮", monitorFull, "╭ PIE ╮", "╭ CONSUMPTION PACE ╮", "╭ FUEL TANK ╮", "╭ BENCHMARK ╮"}, - {"╭BAR╮", monitorCompact, "╭PIE╮", "╭PACE╮", "╭FUEL╮", "╭TEST╮"}, - {"[B]", monitorMinimal, "[P]", "[C]", "[F]", "[X]"}, - {"B", microMonitor, "P", "C", "F", "X"}, - } +func responsiveTabLabels(width int, tiers [][]string) ([]string, string) { separator := "" labels := tiers[len(tiers)-1] for _, candidate := range tiers { @@ -48,45 +57,138 @@ func styleTabLayout(width int, recording bool) ([]styleTab, string) { break } } + return labels, separator +} - tabs := make([]styleTab, 0, styleCount) +func mainTabLayout(width int, recording bool) ([]mainTab, string) { + monitorFull := "╭ MONITOR ╮" + monitorCompact := "╭MON╮" + monitorMinimal := "[M]" + microMonitor := "M" + if recording { + monitorFull = "╭ MONITOR ●╮" + monitorCompact = "╭MON●╮" + monitorMinimal = "[M●]" + microMonitor = "●" + } + labels, separator := responsiveTabLabels(width, [][]string{ + {"╭ QUOTA ╮", monitorFull, "╭ BENCHMARK ╮"}, + {"╭QTA╮", monitorCompact, "╭TEST╮"}, + {"[Q]", monitorMinimal, "[B]"}, + {"Q", microMonitor, "B"}, + }) + + tabs := make([]mainTab, 0, mainTabCount) x := 0 - for style, label := range labels { + for tab, label := range labels { tabWidth := lipgloss.Width(label) if x+tabWidth > width { break } - tabs = append(tabs, styleTab{style: meterStyleID(style), label: label, x: x, width: tabWidth}) + tabs = append(tabs, mainTab{tab: mainTabID(tab), label: label, x: x, width: tabWidth}) x += tabWidth + len(separator) } return tabs, separator } -func (m Model) renderStyleTabs(width int, colors palette) string { +func quotaStyleTabLayout(width int) ([]styleTab, string) { + labels, separator := responsiveTabLabels(width, [][]string{ + {"╭ BARS ╮", "╭ PIE ╮", "╭ CONSUMPTION PACE ╮", "╭ FUEL TANK ╮"}, + {"╭BAR╮", "╭PIE╮", "╭PACE╮", "╭FUEL╮"}, + {"[B]", "[P]", "[C]", "[F]"}, + {"B", "P", "C", "F"}, + }) + + tabs := make([]styleTab, 0, len(quotaStyleOrder)) + x := 0 + for index, label := range labels { + tabWidth := lipgloss.Width(label) + if x+tabWidth > width { + break + } + tabs = append(tabs, styleTab{style: quotaStyleOrder[index], label: label, x: x, width: tabWidth}) + x += tabWidth + len(separator) + } + return tabs, separator +} + +func (m Model) currentMainTab() mainTabID { + switch m.meterStyle { + case styleMonitor: + return mainTabMonitor + case styleBenchmark: + return mainTabBenchmark + default: + return mainTabQuota + } +} + +func (m Model) selectedQuotaStyle() meterStyleID { + if m.meterStyle.isQuota() { + return m.meterStyle + } + if m.quotaMeterStyle.isQuota() { + return m.quotaMeterStyle + } + return styleBars +} + +func (m Model) pressMainTab(tab mainTabID) (tea.Model, tea.Cmd) { + if m.meterStyle.isQuota() { + m.quotaMeterStyle = m.meterStyle + } + switch tab { + case mainTabQuota: + return m.pressStyleTab(m.selectedQuotaStyle()) + case mainTabMonitor: + return m.pressStyleTab(styleMonitor) + case mainTabBenchmark: + return m.pressStyleTab(styleBenchmark) + default: + return m, nil + } +} + +func mainTabForStyle(style meterStyleID) mainTabID { + switch style { + case styleMonitor: + return mainTabMonitor + case styleBenchmark: + return mainTabBenchmark + default: + return mainTabQuota + } +} + +func (m Model) renderMainTabs(width int, colors palette) string { recording := m.monitorState == monitorRunning - tabs, separator := styleTabLayout(width, recording) + tabs, separator := mainTabLayout(width, recording) + parts := make([]string, 0, len(tabs)) + used := 0 + for _, tab := range tabs { + active := tab.tab == m.currentMainTab() + hovered := m.mainTabHovered && tab.tab == m.hoveredMainTab + flashed := m.styleFlashing && tab.tab == mainTabForStyle(m.flashedStyle) + base, background := tabAppearance(active, hovered, flashed, colors) + parts = append(parts, renderStyleTabLabel(tab.label, base, background, recording && tab.tab == mainTabMonitor, m.phase, colors)) + used += tab.width + } + if len(parts) > 1 { + used += (len(parts) - 1) * len(separator) + } + return strings.Join(parts, colors.dimmed().Render(separator)) + strings.Repeat(" ", max(width-used, 0)) +} + +func (m Model) renderQuotaStyleTabs(width int, colors palette) string { + tabs, separator := quotaStyleTabLayout(width) parts := make([]string, 0, len(tabs)) used := 0 for _, tab := range tabs { active := tab.style == m.meterStyle hovered := m.styleHovered && tab.style == m.hoveredStyle flashed := m.styleFlashing && tab.style == m.flashedStyle - foreground, background := colors.dim, colors.background - bold := false - if active { - foreground, background, bold = colors.background, colors.primary, true - } - if hovered { - foreground, bold = colors.accent, true - if active { - foreground, background = colors.background, colors.accent - } - } - if flashed { - foreground, background, bold = colors.background, colors.accent, true - } - base := lipgloss.NewStyle().Foreground(foreground).Background(background).Bold(bold) - parts = append(parts, renderStyleTabLabel(tab.label, base, background, recording && tab.style == styleMonitor, m.phase, colors)) + base, _ := tabAppearance(active, hovered, flashed, colors) + parts = append(parts, base.Render(tab.label)) used += tab.width } if len(parts) > 1 { @@ -95,6 +197,24 @@ func (m Model) renderStyleTabs(width int, colors palette) string { return strings.Join(parts, colors.dimmed().Render(separator)) + strings.Repeat(" ", max(width-used, 0)) } +func tabAppearance(active, hovered, flashed bool, colors palette) (lipgloss.Style, lipgloss.Color) { + foreground, background := colors.dim, colors.background + bold := false + if active { + foreground, background, bold = colors.background, colors.primary, true + } + if hovered { + foreground, bold = colors.accent, true + if active { + foreground, background = colors.background, colors.accent + } + } + if flashed { + foreground, background, bold = colors.background, colors.accent, true + } + return lipgloss.NewStyle().Foreground(foreground).Background(background).Bold(bold), background +} + func renderStyleTabLabel(label string, base lipgloss.Style, background lipgloss.Color, recording bool, phase int, colors palette) string { if !recording || !strings.Contains(label, "●") { return base.Render(label) @@ -112,16 +232,34 @@ func recordingDotColor(phase int, colors palette) lipgloss.Color { return lipgloss.Color("#7A2633") } -func (m Model) styleTabAt(x, y int) (meterStyleID, bool) { +func (m Model) mainTabAt(x, y int) (mainTabID, bool) { if x < 0 || y < 0 || (m.loading && len(m.snapshot.Meters()) == 0) { - return styleBars, false + return mainTabQuota, false } layout := m.dashboardLayout() if y != layout.tabsY { + return mainTabQuota, false + } + localX := x - 2 + tabs, _ := mainTabLayout(layout.contentWidth, m.monitorState == monitorRunning) + for _, tab := range tabs { + if localX >= tab.x && localX < tab.x+tab.width { + return tab.tab, true + } + } + return mainTabQuota, false +} + +func (m Model) quotaStyleTabAt(x, y int) (meterStyleID, bool) { + if x < 0 || y < 0 || !m.meterStyle.isQuota() || (m.loading && len(m.snapshot.Meters()) == 0) { + return styleBars, false + } + layout := m.dashboardLayout() + if y != layout.quotaTabsY { return styleBars, false } localX := x - 2 - tabs, _ := styleTabLayout(layout.contentWidth, m.monitorState == monitorRunning) + tabs, _ := quotaStyleTabLayout(layout.contentWidth) for _, tab := range tabs { if localX >= tab.x && localX < tab.x+tab.width { return tab.style, true diff --git a/internal/ui/tabs_test.go b/internal/ui/tabs_test.go index 8a8400a6..a2b015d0 100644 --- a/internal/ui/tabs_test.go +++ b/internal/ui/tabs_test.go @@ -12,20 +12,49 @@ import ( "github.com/merefield/codexometer/internal/codex" ) -func TestStyleTabsChooseResponsiveLabels(t *testing.T) { +func TestMainTabsChooseResponsiveLabels(t *testing.T) { + for _, test := range []struct { + width int + want string + }{ + {width: 100, want: "BENCHMARK"}, + {width: 22, want: "QTA"}, + {width: 9, want: "[M]"}, + {width: 3, want: "M"}, + } { + t.Run(test.want, func(t *testing.T) { + tabs, _ := mainTabLayout(test.width, false) + if len(tabs) != int(mainTabCount) { + t.Fatalf("width %d displayed %d main tabs, want %d", test.width, len(tabs), mainTabCount) + } + var labels strings.Builder + for _, tab := range tabs { + labels.WriteString(tab.label) + if tab.x+tab.width > test.width { + t.Fatalf("tab %q overflows width %d", tab.label, test.width) + } + } + if !strings.Contains(labels.String(), test.want) { + t.Fatalf("width %d labels %q do not contain %q", test.width, labels.String(), test.want) + } + }) + } +} + +func TestQuotaStyleTabsChooseResponsiveLabels(t *testing.T) { for _, test := range []struct { width int want string }{ {width: 100, want: "CONSUMPTION PACE"}, - {width: 44, want: "MON"}, - {width: 19, want: "[M]"}, - {width: 9, want: "M"}, + {width: 28, want: "PACE"}, + {width: 12, want: "[C]"}, + {width: 4, want: "C"}, } { t.Run(test.want, func(t *testing.T) { - tabs, _ := styleTabLayout(test.width, false) - if len(tabs) != int(styleCount) { - t.Fatalf("width %d displayed %d tabs, want %d", test.width, len(tabs), styleCount) + tabs, _ := quotaStyleTabLayout(test.width) + if len(tabs) != len(quotaStyleOrder) { + t.Fatalf("width %d displayed %d quota tabs, want %d", test.width, len(tabs), len(quotaStyleOrder)) } var labels strings.Builder for _, tab := range tabs { @@ -41,13 +70,13 @@ func TestStyleTabsChooseResponsiveLabels(t *testing.T) { } } -func TestStyleTabsSupportHoverClickAndPulse(t *testing.T) { +func TestMainTabsSupportHoverClickAndPulse(t *testing.T) { model := New(stubFetcher{snapshot: codex.DemoSnapshot()}, time.Minute) model.snapshot = codex.DemoSnapshot() model.loading = false model.width, model.height = 100, 30 - tabs, _ := styleTabLayout(model.contentWidth(), false) - target := tabs[stylePie] + tabs, _ := mainTabLayout(model.contentWidth(), false) + target := tabs[mainTabMonitor] mouse := tea.MouseMsg{ X: 2 + target.x + target.width/2, Y: model.dashboardLayout().tabsY, @@ -56,6 +85,33 @@ func TestStyleTabsSupportHoverClickAndPulse(t *testing.T) { } updated, command := model.Update(mouse) model = updated.(Model) + if command != nil || !model.mainTabHovered || model.hoveredMainTab != mainTabMonitor { + t.Fatalf("monitor hover was not recorded: hovered=%v tab=%d", model.mainTabHovered, model.hoveredMainTab) + } + + mouse.Action = tea.MouseActionPress + updated, command = model.Update(mouse) + model = updated.(Model) + if command == nil || model.meterStyle != styleMonitor || !model.styleFlashing || model.flashedStyle != styleMonitor { + t.Fatalf("monitor click did not select and pulse: style=%d flashing=%v", model.meterStyle, model.styleFlashing) + } +} + +func TestQuotaStyleTabsSupportHoverClickAndPulse(t *testing.T) { + model := New(stubFetcher{snapshot: codex.DemoSnapshot()}, time.Minute) + model.snapshot = codex.DemoSnapshot() + model.loading = false + model.width, model.height = 100, 30 + tabs, _ := quotaStyleTabLayout(model.contentWidth()) + target := tabs[1] + mouse := tea.MouseMsg{ + X: 2 + target.x + target.width/2, + Y: model.dashboardLayout().quotaTabsY, + Button: tea.MouseButtonLeft, + Action: tea.MouseActionMotion, + } + updated, command := model.Update(mouse) + model = updated.(Model) if command != nil || !model.styleHovered || model.hoveredStyle != stylePie { t.Fatalf("pie hover was not recorded: hovered=%v style=%d", model.styleHovered, model.hoveredStyle) } @@ -63,8 +119,8 @@ func TestStyleTabsSupportHoverClickAndPulse(t *testing.T) { mouse.Action = tea.MouseActionPress updated, command = model.Update(mouse) model = updated.(Model) - if command == nil || model.meterStyle != stylePie || !model.styleFlashing || model.flashedStyle != stylePie { - t.Fatalf("pie click did not select and pulse: style=%d flashing=%v", model.meterStyle, model.styleFlashing) + if command == nil || model.meterStyle != stylePie || model.quotaMeterStyle != stylePie || !model.styleFlashing || model.flashedStyle != stylePie { + t.Fatalf("pie click did not select, remember, and pulse: style=%d remembered=%d flashing=%v", model.meterStyle, model.quotaMeterStyle, model.styleFlashing) } updated, _ = model.Update(styleTabFlashExpiredMsg{style: stylePie, sequence: model.styleSequence}) model = updated.(Model) @@ -74,27 +130,112 @@ func TestStyleTabsSupportHoverClickAndPulse(t *testing.T) { } func TestEveryRenderedTabCellIsClickableAcrossWidths(t *testing.T) { - for _, width := range []int{40, 45, 60, 80, 100, 160} { + 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() - tabs, _ := styleTabLayout(layout.contentWidth, false) - for _, tab := range tabs { + mainTabs, _ := mainTabLayout(layout.contentWidth, false) + 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 { + t.Errorf("width %d main tab %q cell %d hit (%d,%v)", width, tab.label, offset, got, ok) + } + } + } + quotaTabs, _ := quotaStyleTabLayout(layout.contentWidth) + for _, tab := range quotaTabs { for offset := 0; offset < tab.width; offset++ { - if got, ok := model.styleTabAt(2+tab.x+offset, layout.tabsY); !ok || got != tab.style { - t.Errorf("width %d tab %q cell %d hit (%d,%v)", width, tab.label, offset, got, ok) + if got, ok := model.quotaStyleTabAt(2+tab.x+offset, layout.quotaTabsY); !ok || got != tab.style { + t.Errorf("width %d quota tab %q cell %d hit (%d,%v)", width, tab.label, offset, got, ok) + } + } + } + } +} + +func TestQuotaStyleIsRememberedAcrossMainTabNavigation(t *testing.T) { + model := Model{meterStyle: stylePie} + updated, _ := model.Update(tea.KeyMsg{Type: tea.KeyTab}) + model = updated.(Model) + if model.meterStyle != styleMonitor { + t.Fatalf("Tab selected %s, want Monitor", model.meterStyle.name()) + } + updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyTab}) + model = updated.(Model) + if model.meterStyle != styleBenchmark { + t.Fatalf("second Tab selected %s, want Benchmark", model.meterStyle.name()) + } + updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyTab}) + model = updated.(Model) + if model.meterStyle != stylePie { + t.Fatalf("return to Quota selected %s, want remembered Pie", model.meterStyle.name()) + } + updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyShiftTab}) + model = updated.(Model) + if model.meterStyle != styleBenchmark { + t.Fatalf("Shift+Tab selected %s, want Benchmark", model.meterStyle.name()) + } +} + +func TestSIsContextualStyleAndMonitorStartHotkey(t *testing.T) { + model := Model{meterStyle: styleBars} + for _, want := range []meterStyleID{stylePie, styleConsumptionPace, styleFuel, styleBars} { + updated, command := model.Update(key('s')) + model = updated.(Model) + if command == nil || model.meterStyle != want || model.quotaMeterStyle != want || model.flashedButton != footerButtonStyle { + t.Fatalf("S selected style=%d remembered=%d flash=%d, want style=%d", model.meterStyle, model.quotaMeterStyle, model.flashedButton, want) + } + } + + model = Model{meterStyle: styleMonitor, monitorState: monitorIdle} + 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) + } + + model = Model{meterStyle: styleBenchmark} + updated, command = model.Update(key('s')) + model = updated.(Model) + if command != nil || model.meterStyle != styleBenchmark || model.flashedButton != footerButtonNone { + t.Fatal("S changed state in Benchmark") + } +} + +func TestQuotaSubTabsOnlyRenderAndHitTestWithinQuota(t *testing.T) { + colors := paletteFor(themeHacker) + for _, style := range []meterStyleID{styleBars, styleMonitor, styleBenchmark} { + model := Model{snapshot: codex.DemoSnapshot(), width: 100, height: 30, meterStyle: style} + output := ansi.Strip(model.View()) + layout := model.dashboardLayout() + if style.isQuota() { + if layout.quotaTabsY < 0 || !strings.Contains(output, "CONSUMPTION PACE") { + t.Fatalf("Quota did not render its sub-tab rail:\n%s", output) + } + continue + } + if layout.quotaTabsY != -1 || strings.Contains(output, "CONSUMPTION PACE") { + t.Fatalf("%s exposed Quota sub-tabs", style.name()) + } + for y := 0; y < model.height; y++ { + for x := 0; x < model.width; x++ { + if _, ok := model.quotaStyleTabAt(x, y); ok { + t.Fatalf("%s exposed hidden Quota sub-tab hit target at %d,%d", style.name(), x, y) } } } + if lipgloss.Width(model.renderMainTabs(model.contentWidth(), colors)) != model.contentWidth() { + t.Fatalf("%s main tab rail did not fill available width", style.name()) + } } } -func TestMonitorTabShowsPulsingRecordingDotWhileAnotherTabIsActive(t *testing.T) { +func TestMonitorMainTabShowsPulsingRecordingDotWhileQuotaIsActive(t *testing.T) { model := Model{meterStyle: styleBars, monitorState: monitorRunning} colors := paletteFor(themeHacker) model.phase = 0 - bright := model.renderStyleTabs(100, colors) + bright := model.renderMainTabs(100, colors) model.phase = 1 - dark := model.renderStyleTabs(100, colors) + 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") } @@ -105,12 +246,3 @@ func TestMonitorTabShowsPulsingRecordingDotWhileAnotherTabIsActive(t *testing.T) t.Fatalf("tab rail did not fill its responsive width: bright=%d dark=%d", lipgloss.Width(bright), lipgloss.Width(dark)) } } - -func TestSOnlyStartsMonitor(t *testing.T) { - model := Model{meterStyle: styleBars} - updated, command := model.Update(key('s')) - model = updated.(Model) - if command != nil || model.meterStyle != styleBars || model.monitorState != monitorIdle { - t.Fatal("S changed state outside the Monitor tab") - } -} diff --git a/internal/ui/theme.go b/internal/ui/theme.go index 83d08247..07cf66e4 100644 --- a/internal/ui/theme.go +++ b/internal/ui/theme.go @@ -29,12 +29,29 @@ const ( styleCount ) -func (s meterStyleID) next() meterStyleID { - return (s + 1) % styleCount +var quotaStyleOrder = [...]meterStyleID{ + styleBars, + stylePie, + styleConsumptionPace, + styleFuel, } -func (s meterStyleID) previous() meterStyleID { - return (s - 1 + styleCount) % styleCount +func (s meterStyleID) isQuota() bool { + for _, style := range quotaStyleOrder { + if s == style { + return true + } + } + return false +} + +func (s meterStyleID) nextQuota() meterStyleID { + for index, style := range quotaStyleOrder { + if s == style { + return quotaStyleOrder[(index+1)%len(quotaStyleOrder)] + } + } + return styleBars } func (s meterStyleID) name() string { diff --git a/internal/ui/view.go b/internal/ui/view.go index 6fd28d5b..2b4d2728 100644 --- a/internal/ui/view.go +++ b/internal/ui/view.go @@ -21,12 +21,15 @@ func (m Model) View() string { if !m.loading || len(m.snapshot.Meters()) > 0 { account = m.renderAccount(colors) } - header := renderHeader(contentWidth, m.phase, m.renderSignalStatus(colors), account, colors) + header := renderHeader(contentWidth, m.phase, m.renderSignalStatus(contentWidth, colors), account, colors) parts := []string{header} if m.loading && len(m.snapshot.Meters()) == 0 { parts = append(parts, renderBoot(contentWidth, m.phase, colors)) } else { - parts = append(parts, strings.Repeat(" ", contentWidth), m.renderStyleTabs(contentWidth, colors)) + parts = append(parts, strings.Repeat(" ", contentWidth), m.renderMainTabs(contentWidth, colors)) + if m.meterStyle.isQuota() { + parts = append(parts, m.renderQuotaStyleTabs(contentWidth, colors)) + } if m.err != nil { errorView := renderError(contentWidth, m.err, colors) parts = append(parts, errorView) @@ -85,18 +88,27 @@ func (m Model) renderAccount(colors palette) string { return colors.dimmed().Render("ACCOUNT // " + plan) } -func (m Model) renderSignalStatus(colors palette) string { - status := "ONLINE" - color := colors.primary +func (m Model) renderSignalStatus(width int, colors palette) string { + if m.loading { + return renderColoredSignal("SCANNING", colors.accent) + } if m.err != nil { - status = "STALE SIGNAL" - color = colors.warning + return renderColoredSignal("STALE SIGNAL", colors.warning) } - if m.loading { - status = "SCANNING" - color = colors.accent + health := snapshotQuotaHealth(m.snapshot, time.Now()) + semantic := lipgloss.NewStyle().Bold(true).Foreground(health.color(colors)) + online := lipgloss.NewStyle().Bold(true).Foreground(colors.primary) + if width < 24 { + return semantic.Render("● " + health.compactLabel()) } - return lipgloss.NewStyle().Bold(true).Foreground(color).Render("● " + status) + if width < 48 { + return semantic.Render("●") + online.Render(" ON // ") + semantic.Render(health.compactLabel()) + } + return semantic.Render("●") + online.Render(" ONLINE // ") + semantic.Render(health.label()) +} + +func renderColoredSignal(label string, color lipgloss.Color) string { + return lipgloss.NewStyle().Bold(true).Foreground(color).Render("● " + label) } func joinRight(left, right string, width int) string { @@ -124,7 +136,7 @@ func (m Model) renderFooter(width int, colors palette) string { left += fmt.Sprintf(" // RESET TOKENS %d", m.snapshot.RateLimitResetCredits.AvailableCount) } status := left - buttons, separator := footerButtonLayoutWithTheme(width, colors.name) + buttons, separator := footerButtonLayoutWithTheme(width, colors.name, m.meterStyle.isQuota()) controls := make([]string, 0, len(buttons)) for _, button := range buttons { controls = append(controls, footerButtonAppearance( diff --git a/internal/ui/view_test.go b/internal/ui/view_test.go index 0d70a8c3..b5eed381 100644 --- a/internal/ui/view_test.go +++ b/internal/ui/view_test.go @@ -70,6 +70,51 @@ func TestViewReflowsAcrossTerminalDimensions(t *testing.T) { } } +func TestQuotaViewsAccommodateReintroducedFiveHourAndAdditionalWindows(t *testing.T) { + now := time.Now() + window := func(used int, durationMinutes int64) *codex.Window { + reset := now.Add(time.Duration(durationMinutes/2) * time.Minute).Unix() + return &codex.Window{UsedPercent: used, WindowDurationMins: &durationMinutes, ResetsAt: &reset} + } + snapshot := codex.Snapshot{RateLimitsByLimitID: map[string]codex.RateLimitSnapshot{ + "codex": { + Primary: window(35, 300), + Secondary: window(48, 10_080), + }, + "spark": { + LimitName: ptr("spark"), + Primary: window(20, 60), + Secondary: window(70, 1_440), + }, + }} + if meters := snapshot.Meters(); len(meters) != 4 || meters[0].Name != "5 HOURS" { + t.Fatalf("restored snapshot produced meters %#v", meters) + } + + for _, size := range []struct{ width, height int }{{40, 24}, {80, 24}, {120, 40}} { + for _, style := range quotaMeterStyles { + model := Model{ + snapshot: snapshot, width: size.width, height: size.height, + nextRefresh: now.Add(time.Minute), meterStyle: style, + } + output := ansi.Strip(model.View()) + if got := lipgloss.Width(output); got > size.width { + t.Errorf("%s with four windows at %dx%d rendered width %d", style.name(), size.width, size.height, got) + } + if got := lipgloss.Height(output); got > size.height { + t.Errorf("%s with four windows at %dx%d rendered height %d:\n%s", style.name(), size.width, size.height, got, output) + } + if size.width >= 80 { + for _, title := range []string{"5 HOURS LOOP", "1 WEEK LOOP", "SPARK // 1 HOUR LOOP", "SPARK // 1 DAY LOOP"} { + if !strings.Contains(output, title) { + t.Errorf("%s at %dx%d omitted %q:\n%s", style.name(), size.width, size.height, title, output) + } + } + } + } + } +} + func TestStatusAndFooterKeepOnlyEssentialMetadata(t *testing.T) { model := Model{ snapshot: codex.DemoSnapshot(), @@ -81,10 +126,11 @@ func TestStatusAndFooterKeepOnlyEssentialMetadata(t *testing.T) { if account != "ACCOUNT // PLUS" { t.Fatalf("account metadata = %q", account) } - header := ansi.Strip(renderHeader(100, 0, model.renderSignalStatus(colors), model.renderAccount(colors), colors)) + header := ansi.Strip(renderHeader(100, 0, model.renderSignalStatus(100, colors), model.renderAccount(colors), colors)) headerLines := strings.Split(header, "\n") firstLine := headerLines[0] - if !strings.HasSuffix(firstLine, "● ONLINE") { + status := ansi.Strip(model.renderSignalStatus(100, colors)) + if !strings.HasSuffix(firstLine, status) || !strings.Contains(status, "● ONLINE // QUOTA ") { t.Fatalf("online status is not at the top right of the header: %q", firstLine) } if !strings.HasSuffix(headerLines[len(headerLines)-1], "ACCOUNT // PLUS") {