From 33777a9c173ccf80e0150a1dbf467d91c1c8e91c Mon Sep 17 00:00:00 2001 From: merefield Date: Tue, 11 Aug 2026 18:41:24 +0100 Subject: [PATCH 1/2] Add deterministic benchmark suite --- .github/workflows/ci.yml | 2 +- README.md | 122 ++- go.mod | 7 +- go.sum | 10 +- internal/codex/benchmark.go | 857 ++++++++++++++++++ internal/codex/benchmark_tasks.go | 606 +++++++++++++ internal/codex/benchmark_test.go | 644 +++++++++++++ internal/codex/client.go | 2 +- internal/codex/live_usage.go | 2 +- internal/ui/benchmark.go | 565 ++++++++++++ internal/ui/benchmark_test.go | 368 ++++++++ internal/ui/model.go | 565 +++++++++--- internal/ui/model_test.go | 8 +- internal/ui/{stopwatch.go => monitor.go} | 126 +-- .../ui/{stopwatch_test.go => monitor_test.go} | 174 ++-- internal/ui/tabs.go | 38 +- internal/ui/tabs_test.go | 18 +- internal/ui/theme.go | 6 +- internal/ui/view.go | 6 +- internal/ui/view_test.go | 15 +- internal/version/version.go | 39 +- internal/version/version_test.go | 25 +- main.go | 38 + main_test.go | 2 +- 24 files changed, 3899 insertions(+), 346 deletions(-) create mode 100644 internal/codex/benchmark.go create mode 100644 internal/codex/benchmark_tasks.go create mode 100644 internal/codex/benchmark_test.go create mode 100644 internal/ui/benchmark.go create mode 100644 internal/ui/benchmark_test.go rename internal/ui/{stopwatch.go => monitor.go} (70%) rename internal/ui/{stopwatch_test.go => monitor_test.go} (57%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9ac20a24..8e4b73d0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,7 @@ jobs: - uses: actions/setup-go@v5 with: - go-version: "1.22.x" + go-version: "1.25.x" cache: true - name: Check formatting diff --git a/README.md b/README.md index 3be7a15c..42da14ca 100644 --- a/README.md +++ b/README.md @@ -16,8 +16,9 @@ opening `/status` in your working Codex session. _Hacker theme showing Codex and GPT-5.3-Codex-Spark quota windows._ -Codexometer refreshes once a minute by default. It is read-only: it displays -quota information and never starts a model turn or consumes a reset credit. +Codexometer refreshes once a minute by default. Its quota dashboard is +read-only. The optional Benchmark tab starts model turns only when you +explicitly click its run button; those trials consume Codex quota. ## Why use it? @@ -54,8 +55,11 @@ It works particularly well in: - Available earned reset credits when present. - Online, refreshing, stale-data, and error states. - A countdown to the next automatic refresh. -- An optional Stopwatch view that measures token activity observed across local +- An optional Monitor view that measures token activity observed across local Codex sessions between Go and Stop, with a live 30-second bar chart. +- An opt-in deterministic coding benchmark comparing every visible Codex model + and supported reasoning effort by correctness, elapsed time, token use, and + estimated standard API-equivalent cost. Codexometer does not assume that every account has the same windows. Some accounts expose a shorter rolling window and a weekly window; plans and backend @@ -126,7 +130,7 @@ Codexometer deliberately does not: - send credentials to another service; - invoke a model merely to discover quota information. -The Stopwatch additionally reads locally persisted Codex rollout files under +The Monitor additionally reads locally persisted Codex rollout files under `$CODEX_HOME/sessions` (normally `~/.codex/sessions`). It scans only for `token_count` telemetry records and decodes only their token totals and timestamps; message text, reasoning, commands, tool results, and credentials are @@ -146,8 +150,13 @@ codexometer --codex /path/to/codex | `Tab` | Select the next meter-style tab | | `Shift+Tab` | Select the previous meter-style tab | | `r` | Refresh quota data immediately | -| `s` | Start the Stopwatch recorder (Stopwatch view only) | -| `p` | Stop and take a final up-to-date reading (Stopwatch view only) | +| `s` | Start recording (Monitor view only) | +| `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) | +| `[` / `]`, `Left` / `Right` | Select the previous or next benchmark challenge | +| `f` | Show all, passed, or failed benchmark results | +| `Page Up` / `Page Down` | Scroll through Benchmark result pages | | `q` | Quit | | `Esc` | Quit | | `Ctrl+C` | Quit | @@ -177,7 +186,7 @@ The default remains the original green hacker-terminal presentation. Select a tab with the mouse, `Tab`, or `Shift+Tab`: 1. **Bars** — chunky quota bars, with one full-width rate-limit window per row. -2. **Stopwatch** — establishes a zero baseline across locally active Codex +2. **Monitor** — establishes a zero baseline across locally active Codex sessions when you press Start. A large readout follows newly appended token telemetry once per second and shows total observed tokens, elapsed time, and average rate; clickable Start and Stop controls sit beside it. The full-width @@ -194,6 +203,13 @@ Select a tab with the mouse, `Tab`, or `Shift+Tab`: 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 + four-challenge suite, against every visible model and each reasoning effort + that model advertises. Results arrive sequentially in a 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 @@ -214,7 +230,7 @@ receives its card's remaining width and height, and resizing the terminal immediately reflows and rescales it. The underlying values and reset information never change with presentation. -The Stopwatch is deliberately separate from the percentage gauges: no token +The Monitor is deliberately separate from the percentage gauges: no token ceiling is exposed for those quota windows, so a percentage-based bar would be misleading. It follows the local token telemetry underlying Codex's live [`thread/tokenUsage/updated`](https://developers.openai.com/codex/app-server) @@ -231,6 +247,75 @@ for a model response, not token-by-token while a response is streaming. Raw toke counts also do not reveal or reproduce the backend's quota-weighting rules, so they should not be converted directly into the percentage gauges. +### Deterministic benchmark + +The Benchmark tab discovers the current account's visible models and their +supported reasoning efforts through `model/list`. Select a challenge with the +arrow buttons, then press `b` or click **Run Selected** to run it against every +model/effort combination. **Run All** runs all four challenges against every +combination. Because that means `challenge count × model/effort count` model +turns, Codexometer displays the exact total and requires a second confirmation +within five seconds. A fresh, ephemeral, read-only app-server thread is used for +each trial, so benchmark history does not clutter normal Codex sessions. The +turns still consume the same account quota shown by Codexometer. + +#### Challenges + +Every trial asks the model to return one named Starlark function: + +| Challenge | Required behavior | Verification set | +| --- | --- | --- | +| **Merge Ranges** | Sort inclusive integer ranges and merge every overlapping or adjacent pair into a canonical union. It must handle empty input, duplicates, nesting, negatives, and arbitrary order. | 8 hand-written edge cases + 48 reproducibly generated cases | +| **LRU Cache** | Process integer `put` and `get` operations, update recency, evict the least-recently-used entry, and return both get results and final entries in most-recently-used order. Capacity zero is valid. | 5 hand-written edge cases + 40 reproducibly generated cases | +| **Expression** | Evaluate tokenized non-negative integers with `+`, `-`, `*`, parentheses, normal precedence, and left associativity—without `eval`. | 8 hand-written edge cases + 40 reproducibly generated expressions | +| **Shortest Path** | Return the minimum four-direction move count through a rectangular blocked/open grid, or `-1` when no route exists. | 5 hand-written edge cases + 40 reproducibly generated mazes | + +#### How PASS and FAIL are decided + +There is no LLM judge and no subjective scoring. Codexometer loads the returned +function into its embedded Starlark interpreter, runs every case for that +challenge, computes the expected result with a separate Go reference +implementation, and compares the values exactly. It also snapshots the input +and rejects a solution that mutates it. + +A row is `PASS` only when all of the following are true: + +- the turn completes and returns the required strict JSON object containing + Starlark source; +- the source loads, defines the correctly named callable, and stays within the + 64 KiB source and 250,000 execution-step limits; +- every hand-written and generated case returns the exact reference answer with + the required type and bounded shape; and +- none of the supplied inputs are mutated. + +Any syntax/runtime error, timeout, malformed response, wrong type or value, +mutation, safety/size-limit violation, or failed case produces `FAIL`. The first +failure is retained as the row's diagnostic. The test data is deterministic, so +the same Codexometer version judges every model/effort combination identically. + +Starlark is a deliberately small, Python-like embedded language. Every prompt +includes the same compact language contract—available statements and built-ins, +plus the absence of `while`, recursion, imports, `load`, and `eval`—to reduce +advantage from prior syntax familiarity. It cannot remove that advantage +entirely: these results measure algorithmic coding through Starlark and may +favor models stronger at Python-like languages. They are not a language-neutral +measure of general model quality. + +Codexometer links the Starlark interpreter into the standalone binary and +exposes no filesystem, process, network, clock, or environment capabilities to +submitted code. Restricted return types and bounded result sizes add further +containment. + +Token totals come from the trial thread's live `thread/tokenUsage/updated` +events. API-equivalent cost is an estimate, not a ChatGPT charge: it applies the +published standard API input, cached-input, and output token prices known to +this Codexometer release, plus cache-write prices where OpenAI publishes one. +Reasoning tokens are already included in the output-token total. An unknown +model—or usage in a token class without a published price—displays `N/A` rather +than being guessed. Pricing can change; consult the +[official OpenAI API pricing page](https://developers.openai.com/api/docs/pricing) +for the current source values. + ## Options ```text @@ -276,9 +361,9 @@ need Go or Codexometer's source dependencies. ## Versioning -Codexometer follows semantic versioning; the current source version is `v0.1.2`. The Git tag is +Codexometer follows semantic versioning; the current source version is `v0.2.0`. The Git tag is the release source of truth. Go automatically embeds that tag in binaries built -with `go install github.com/merefield/codexometer@v0.1.2`; direct source builds +with `go install github.com/merefield/codexometer@v0.2.0`; direct source builds fall back to the maintained value in `internal/version/version.go`. Both forms report the embedded version and exit without starting the interface: @@ -291,7 +376,7 @@ codexometer --version Release automation can override the source-build fallback without editing code: ```sh -go build -ldflags="-s -w -X github.com/merefield/codexometer/internal/version.Fallback=0.1.2" . +go build -ldflags="-s -w -X github.com/merefield/codexometer/internal/version.Fallback=0.2.0" . ``` ## How refresh works @@ -309,7 +394,7 @@ 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 Stopwatch is running it checks appended local token telemetry once per +While the Monitor is recording it checks appended local token telemetry once per second and rolls the observed deltas into 30-second graph buckets. These reads do not contact OpenAI or invoke a model. Pressing Stop performs one immediate final local read and forces complete session discovery, including Codex sessions @@ -343,12 +428,12 @@ 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 return to the -compact default bar style with `s`. +rows to display every quota window. Increase the pane height or use `Tab` to +return to the compact default bar style. -### Stopwatch remains at zero +### Monitor remains at zero -The Stopwatch observes rollout telemetry under the same `CODEX_HOME` visible to +The Monitor observes rollout telemetry under the same `CODEX_HOME` visible to the Codexometer process. Confirm that the Codex session doing work is local and uses that home. A native Windows Codex session and a native Windows Codexometer normally share the same user profile; WSL and native Windows have different @@ -375,11 +460,12 @@ go test -cover ./... Codexometer uses: -- Go 1.22+ +- Go 1.25+ - Bubble Tea for the terminal event loop - Lip Gloss for adaptive ANSI styling +- Starlark for deterministic, hermetic benchmark-code evaluation - Codex app-server JSON-RPC for authenticated quota data -- Local Codex rollout `token_count` records for live Stopwatch telemetry +- Local Codex rollout `token_count` records for live Monitor telemetry ## License diff --git a/go.mod b/go.mod index 2554560b..697cdd23 100644 --- a/go.mod +++ b/go.mod @@ -1,15 +1,16 @@ module github.com/merefield/codexometer -go 1.22 +go 1.25.0 require ( github.com/charmbracelet/bubbletea v1.2.4 github.com/charmbracelet/lipgloss v1.0.0 + github.com/charmbracelet/x/ansi v0.4.5 + go.starlark.net v0.0.0-20260708150628-5395d018f003 ) require ( github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect - github.com/charmbracelet/x/ansi v0.4.5 // indirect github.com/charmbracelet/x/term v0.2.1 // indirect github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect @@ -21,6 +22,6 @@ require ( github.com/muesli/termenv v0.15.2 // indirect github.com/rivo/uniseg v0.4.7 // indirect golang.org/x/sync v0.9.0 // indirect - golang.org/x/sys v0.27.0 // indirect + golang.org/x/sys v0.42.0 // indirect golang.org/x/text v0.3.8 // indirect ) diff --git a/go.sum b/go.sum index 6ef777c4..a9de0a96 100644 --- a/go.sum +++ b/go.sum @@ -10,6 +10,8 @@ github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQ github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= @@ -27,11 +29,15 @@ github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1n github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +go.starlark.net v0.0.0-20260708150628-5395d018f003 h1:cAxcqHgW8fnmT0cEBU3TzvVYHIFt8IIGDMWUF6rImk4= +go.starlark.net v0.0.0-20260708150628-5395d018f003/go.mod h1:Iue6g6iirlfLoVi/DYCi5/x0h/bAOuWF3dULTKpt2Vo= golang.org/x/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ= golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s= -golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= diff --git a/internal/codex/benchmark.go b/internal/codex/benchmark.go new file mode 100644 index 00000000..a3b93ac5 --- /dev/null +++ b/internal/codex/benchmark.go @@ -0,0 +1,857 @@ +package codex + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "os" + "os/exec" + "strings" + "sync" + "time" + + "go.starlark.net/starlark" + + "github.com/merefield/codexometer/internal/version" +) + +const ( + benchmarkTurnTimeout = 5 * time.Minute + benchmarkCodeLimit = 64 * 1024 + benchmarkStepLimit = 250_000 +) + +// BenchmarkUsage is the app-server token breakdown for one isolated turn. +type BenchmarkUsage struct { + TotalTokens int64 `json:"totalTokens"` + InputTokens int64 `json:"inputTokens"` + CachedInputTokens int64 `json:"cachedInputTokens"` + CacheWriteInputTokens int64 `json:"cacheWriteInputTokens"` + OutputTokens int64 `json:"outputTokens"` + ReasoningOutputTokens int64 `json:"reasoningOutputTokens"` +} + +// BenchmarkResult contains one model/reasoning-effort run. +type BenchmarkResult struct { + TaskID BenchmarkTaskID + TaskName string + Model string + DisplayName string + Effort string + ActualModel string + Correct bool + Duration time.Duration + Usage BenchmarkUsage + CostUSD float64 + CostKnown bool + Failure string +} + +// BenchmarkEvent incrementally reports discovery, execution, and results. +type BenchmarkEvent struct { + Total int + Completed int + Combinations int + CurrentTaskID BenchmarkTaskID + CurrentTask string + CurrentModel string + CurrentEffort string + Result *BenchmarkResult + Done bool + Err error +} + +type benchmarkModel struct { + ID string `json:"id"` + Model string `json:"model"` + DisplayName string `json:"displayName"` + Hidden bool `json:"hidden"` + SupportedReasoningEfforts []benchmarkEffortOption `json:"supportedReasoningEfforts"` + DefaultReasoningEffort string `json:"defaultReasoningEffort"` +} + +type benchmarkEffortOption struct { + ReasoningEffort string `json:"reasoningEffort"` +} + +type benchmarkCombination struct { + model benchmarkModel + effort string +} + +type benchmarkRPCError struct { + Code int `json:"code"` + Message string `json:"message"` +} + +type benchmarkMethodError struct { + method string + code int + message string +} + +func (e *benchmarkMethodError) Error() string { + return fmt.Sprintf("%s (RPC %d)", e.message, e.code) +} + +type benchmarkEnvelope struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Params json.RawMessage `json:"params"` + Result json.RawMessage `json:"result"` + Error *benchmarkRPCError `json:"error"` +} + +type appServerSession struct { + cmd *exec.Cmd + stdin io.WriteCloser + encoder *json.Encoder + stderr *lockedBuffer + nextID int + wait sync.Once + pending []benchmarkEnvelope + envelopes chan benchmarkEnvelope + readErrors chan error + done chan struct{} + stop sync.Once +} + +type lockedBuffer struct { + mu sync.Mutex + b strings.Builder +} + +func (b *lockedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.b.Write(p) +} + +func (b *lockedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.b.String() +} + +// BenchmarkCombinationCount returns the number of visible model/effort pairs +// without starting a model turn. +func (c Client) BenchmarkCombinationCount(ctx context.Context) (int, error) { + server, err := openBenchmarkAppServer(ctx, c.Binary) + if err != nil { + return 0, err + } + defer server.close() + models, err := server.models(ctx) + if err != nil { + return 0, err + } + return len(benchmarkCombinations(models)), nil +} + +// RunBenchmarkSuite runs each selected deterministic task once for every +// visible model/reasoning-effort combination advertised by the current login. +var openBenchmarkAppServer = startAppServer + +func (c Client) RunBenchmarkSuite(ctx context.Context, taskIDs []BenchmarkTaskID, emit func(BenchmarkEvent)) { + if emit == nil { + emit = func(BenchmarkEvent) {} + } + definitions, err := resolveBenchmarkTasks(taskIDs) + if err != nil { + emit(BenchmarkEvent{Done: true, Err: err}) + return + } + server, err := openBenchmarkAppServer(ctx, c.Binary) + if err != nil { + emit(BenchmarkEvent{Done: true, Err: err}) + return + } + defer server.close() + + models, err := server.models(ctx) + if err != nil { + emit(BenchmarkEvent{Done: true, Err: err}) + return + } + combinations := benchmarkCombinations(models) + if len(combinations) == 0 { + emit(BenchmarkEvent{Done: true, Err: errors.New("Codex returned no benchmarkable models")}) + return + } + total := len(combinations) * len(definitions) + emit(BenchmarkEvent{Total: total, Combinations: len(combinations)}) + + completed := 0 + for _, definition := range definitions { + for _, combination := range combinations { + if err := ctx.Err(); err != nil { + emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: len(combinations), Done: true, Err: err}) + return + } + event := BenchmarkEvent{ + Total: total, Completed: completed, Combinations: len(combinations), + CurrentTaskID: definition.task.ID, CurrentTask: definition.task.Name, + CurrentModel: combination.model.DisplayName, CurrentEffort: combination.effort, + } + emit(event) + result, fatalErr := server.runBenchmark(ctx, combination, definition) + completed++ + event.Completed, event.Result = completed, &result + emit(event) + if fatalErr != nil { + emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: len(combinations), Done: true, Err: fatalErr}) + return + } + } + } + emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: len(combinations), Done: true}) +} + +func startAppServer(ctx context.Context, binary string) (*appServerSession, error) { + if strings.TrimSpace(binary) == "" { + binary = "codex" + } + cmd := exec.CommandContext(ctx, binary, "app-server", "--stdio") + stdin, err := cmd.StdinPipe() + if err != nil { + return nil, fmt.Errorf("open Codex input: %w", err) + } + stdout, err := cmd.StdoutPipe() + if err != nil { + return nil, fmt.Errorf("open Codex output: %w", err) + } + stderr := &lockedBuffer{} + cmd.Stderr = stderr + if err := cmd.Start(); err != nil { + if errors.Is(err, exec.ErrNotFound) || errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("Codex CLI not found; install it or pass --codex PATH") + } + return nil, fmt.Errorf("start Codex app-server: %w", err) + } + server := &appServerSession{ + cmd: cmd, stdin: stdin, encoder: json.NewEncoder(stdin), + stderr: stderr, envelopes: make(chan benchmarkEnvelope, 64), readErrors: make(chan error, 1), done: make(chan struct{}), + } + go server.readLoop(json.NewDecoder(bufio.NewReader(stdout))) + if _, err := server.call(ctx, "initialize", map[string]any{ + "clientInfo": map[string]string{ + "name": "codexometer", "title": "Codexometer", "version": version.Current(), + }, + }, nil); err != nil { + server.close() + return nil, fmt.Errorf("initialize Codex app-server: %w", err) + } + if err := server.encoder.Encode(map[string]any{"method": "initialized"}); err != nil { + server.close() + return nil, fmt.Errorf("acknowledge Codex app-server: %w", err) + } + return server, nil +} + +func (s *appServerSession) readLoop(decoder *json.Decoder) { + for { + var envelope benchmarkEnvelope + if err := decoder.Decode(&envelope); err != nil { + select { + case s.readErrors <- err: + default: + } + return + } + select { + case s.envelopes <- envelope: + case <-s.done: + return + } + } +} + +func (s *appServerSession) nextEnvelope(ctx context.Context) (benchmarkEnvelope, error) { + // Drain decoded protocol messages before observing a terminal decoder error. + // A short-lived server may write its final response and close stdout so close + // together that both channels are ready at once. + select { + case envelope := <-s.envelopes: + return envelope, nil + default: + } + select { + case <-ctx.Done(): + return benchmarkEnvelope{}, ctx.Err() + case <-s.done: + return benchmarkEnvelope{}, errors.New("Codex app-server session closed") + case err := <-s.readErrors: + select { + case envelope := <-s.envelopes: + return envelope, nil + default: + } + if errors.Is(err, io.EOF) { + return benchmarkEnvelope{}, fmt.Errorf("Codex app-server closed unexpectedly: %s", strings.TrimSpace(s.stderr.String())) + } + return benchmarkEnvelope{}, err + case envelope := <-s.envelopes: + return envelope, nil + } +} + +func (s *appServerSession) close() { + if s == nil { + return + } + s.stop.Do(func() { close(s.done) }) + _ = s.stdin.Close() + if s.cmd != nil && s.cmd.Process != nil { + _ = s.cmd.Process.Kill() + } + s.wait.Do(func() { + if s.cmd != nil { + _ = s.cmd.Wait() + } + }) +} + +func (s *appServerSession) call( + ctx context.Context, + method string, + params any, + onNotification func(string, json.RawMessage), +) (json.RawMessage, error) { + s.nextID++ + id := s.nextID + request := map[string]any{"method": method, "id": id} + if params != nil { + request["params"] = params + } + if err := s.encoder.Encode(request); err != nil { + return nil, err + } + for { + if err := ctx.Err(); err != nil { + return nil, err + } + envelope, err := s.nextEnvelope(ctx) + if err != nil { + return nil, err + } + if envelope.Method != "" { + if onNotification != nil { + onNotification(envelope.Method, envelope.Params) + } else { + s.pending = append(s.pending, envelope) + } + continue + } + var responseID int + if len(envelope.ID) == 0 || json.Unmarshal(envelope.ID, &responseID) != nil || responseID != id { + continue + } + if envelope.Error != nil { + return nil, &benchmarkMethodError{method: method, code: envelope.Error.Code, message: envelope.Error.Message} + } + return envelope.Result, nil + } +} + +func (s *appServerSession) models(ctx context.Context) ([]benchmarkModel, error) { + var models []benchmarkModel + var cursor string + for { + params := map[string]any{"limit": 100, "includeHidden": false} + if cursor != "" { + params["cursor"] = cursor + } + result, err := s.call(ctx, "model/list", params, nil) + if err != nil { + return nil, fmt.Errorf("list Codex models: %w", err) + } + var page struct { + Data []benchmarkModel `json:"data"` + NextCursor *string `json:"nextCursor"` + } + if err := json.Unmarshal(result, &page); err != nil { + return nil, fmt.Errorf("decode Codex models: %w", err) + } + for _, model := range page.Data { + if !model.Hidden { + models = append(models, model) + } + } + if page.NextCursor == nil || *page.NextCursor == "" { + break + } + cursor = *page.NextCursor + } + return models, nil +} + +func benchmarkCombinations(models []benchmarkModel) []benchmarkCombination { + var combinations []benchmarkCombination + for _, model := range models { + if strings.TrimSpace(model.Model) == "" { + continue + } + if strings.TrimSpace(model.DisplayName) == "" { + model.DisplayName = model.Model + } + if len(model.SupportedReasoningEfforts) == 0 { + effort := strings.TrimSpace(model.DefaultReasoningEffort) + if effort == "" { + effort = "default" + } + combinations = append(combinations, benchmarkCombination{model: model, effort: effort}) + continue + } + for _, option := range model.SupportedReasoningEfforts { + if effort := strings.TrimSpace(option.ReasoningEffort); effort != "" { + combinations = append(combinations, benchmarkCombination{model: model, effort: effort}) + } + } + } + return combinations +} + +func (s *appServerSession) runBenchmark(ctx context.Context, combination benchmarkCombination, definition benchmarkDefinition) (BenchmarkResult, error) { + result := BenchmarkResult{ + TaskID: definition.task.ID, TaskName: definition.task.Name, + Model: combination.model.Model, DisplayName: combination.model.DisplayName, + Effort: combination.effort, ActualModel: combination.model.Model, + } + turnCtx, cancel := context.WithTimeout(ctx, benchmarkTurnTimeout) + defer cancel() + + temporary, err := os.MkdirTemp("", "codexometer-benchmark-") + if err != nil { + result.Failure = fmt.Sprintf("create isolated workspace: %v", err) + return result, nil + } + defer os.RemoveAll(temporary) + + threadResult, err := s.call(turnCtx, "thread/start", map[string]any{ + "model": combination.model.Model, + "cwd": temporary, + "approvalPolicy": "never", + "sandbox": "read-only", + "ephemeral": true, + "serviceName": "codexometer-benchmark", + "developerInstructions": "Complete only the supplied deterministic benchmark. Do not use tools or inspect the environment. Return exactly the requested structured output.", + }, nil) + if err != nil { + result.Failure = fmt.Sprintf("start thread: %v", err) + return result, fatalBenchmarkError(turnCtx, err) + } + var startedThread struct { + Thread struct { + ID string `json:"id"` + } `json:"thread"` + Model string `json:"model"` + } + if err := json.Unmarshal(threadResult, &startedThread); err != nil || startedThread.Thread.ID == "" { + result.Failure = "Codex returned an invalid thread" + return result, nil + } + if startedThread.Model != "" { + result.ActualModel = startedThread.Model + } + startedAt := time.Now() + turnParams := map[string]any{ + "threadId": startedThread.Thread.ID, + "input": []map[string]any{{"type": "text", "text": benchmarkPrompt(definition)}}, + "outputSchema": benchmarkOutputSchema, + } + if combination.effort != "default" && combination.effort != "" { + turnParams["effort"] = combination.effort + } + turnResponse, err := s.call(turnCtx, "turn/start", turnParams, nil) + if err != nil { + result.Duration = time.Since(startedAt) + result.Failure = fmt.Sprintf("start turn: %v", err) + return result, fatalBenchmarkError(turnCtx, err) + } + var startedTurn struct { + Turn struct { + ID string `json:"id"` + } `json:"turn"` + } + if err := json.Unmarshal(turnResponse, &startedTurn); err != nil || startedTurn.Turn.ID == "" { + result.Duration = time.Since(startedAt) + result.Failure = "Codex returned an invalid turn" + return result, nil + } + + var finalMessage, turnFailure string + completed := false + for !completed { + _, err = s.readUntilNotification(turnCtx, func(method string, params json.RawMessage) bool { + switch method { + case "thread/tokenUsage/updated": + var event struct { + ThreadID string `json:"threadId"` + TurnID string `json:"turnId"` + TokenUsage struct { + Total BenchmarkUsage `json:"total"` + } `json:"tokenUsage"` + } + if json.Unmarshal(params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID { + result.Usage = event.TokenUsage.Total + } + case "model/rerouted": + var event struct { + ThreadID string `json:"threadId"` + TurnID string `json:"turnId"` + ToModel string `json:"toModel"` + } + if json.Unmarshal(params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID && event.ToModel != "" { + result.ActualModel = event.ToModel + } + case "item/completed": + var event struct { + ThreadID string `json:"threadId"` + TurnID string `json:"turnId"` + Item struct { + Type string `json:"type"` + Text string `json:"text"` + } `json:"item"` + } + if json.Unmarshal(params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID && event.Item.Type == "agentMessage" { + finalMessage = event.Item.Text + } + case "turn/completed": + var event struct { + ThreadID string `json:"threadId"` + Turn struct { + ID string `json:"id"` + Status string `json:"status"` + Error *struct { + Message string `json:"message"` + } `json:"error"` + Items []struct { + Type string `json:"type"` + Text string `json:"text"` + } `json:"items"` + } `json:"turn"` + } + if json.Unmarshal(params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.Turn.ID == startedTurn.Turn.ID { + completed = true + if event.Turn.Status != "completed" { + turnFailure = "turn " + event.Turn.Status + if event.Turn.Error != nil && event.Turn.Error.Message != "" { + turnFailure += ": " + event.Turn.Error.Message + } + } + if finalMessage == "" { + for _, item := range event.Turn.Items { + if item.Type == "agentMessage" { + finalMessage = item.Text + } + } + } + return true + } + } + return false + }) + if err != nil { + result.Duration = time.Since(startedAt) + result.Failure = fmt.Sprintf("wait for turn: %v", err) + return result, err + } + } + result.Duration = time.Since(startedAt) + result.CostUSD, result.CostKnown = estimateAPICost(result.ActualModel, result.Usage) + if turnFailure != "" { + result.Failure = turnFailure + return result, nil + } + code, err := benchmarkCode(finalMessage) + if err != nil { + result.Failure = err.Error() + return result, nil + } + if err := definition.verify(code); err != nil { + result.Failure = err.Error() + return result, nil + } + result.Correct = true + return result, nil +} + +func fatalBenchmarkError(ctx context.Context, err error) error { + if ctx.Err() != nil { + return ctx.Err() + } + var methodError *benchmarkMethodError + if errors.As(err, &methodError) { + return nil + } + return err +} + +func (s *appServerSession) readUntilNotification(ctx context.Context, accept func(string, json.RawMessage) bool) (json.RawMessage, error) { + for { + if err := ctx.Err(); err != nil { + return nil, err + } + var envelope benchmarkEnvelope + if len(s.pending) > 0 { + envelope = s.pending[0] + s.pending = s.pending[1:] + } else { + var err error + envelope, err = s.nextEnvelope(ctx) + if err != nil { + return nil, err + } + } + if envelope.Method != "" && accept(envelope.Method, envelope.Params) { + return envelope.Params, nil + } + } +} + +var benchmarkOutputSchema = map[string]any{ + "type": "object", + "properties": map[string]any{ + "code": map[string]any{"type": "string"}, + }, + "required": []string{"code"}, + "additionalProperties": false, +} + +func benchmarkCode(message string) (string, error) { + if len(message) == 0 { + return "", errors.New("Codex returned no final code") + } + if len(message) > benchmarkCodeLimit { + return "", errors.New("returned code exceeds the 64 KiB safety limit") + } + var output struct { + Code string `json:"code"` + } + decoder := json.NewDecoder(bytes.NewReader([]byte(message))) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&output); err != nil { + return "", fmt.Errorf("decode structured result: %w", err) + } + var trailing any + if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) { + return "", errors.New("structured result contains trailing data") + } + if strings.TrimSpace(output.Code) == "" { + return "", errors.New("structured result contains no code") + } + if len(output.Code) > benchmarkCodeLimit { + return "", errors.New("returned code exceeds the 64 KiB safety limit") + } + return output.Code, nil +} + +type interval struct { + start int64 + end int64 +} + +func verifyMergeRanges(code string) error { + thread, function, err := loadBenchmarkFunction(code, "merge_ranges") + if err != nil { + return err + } + + for index, input := range intervalTestCases() { + argument := intervalsToStarlark(input) + before := argument.String() + value, err := starlark.Call(thread, function, starlark.Tuple{argument}, nil) + if err != nil { + return fmt.Errorf("case %d raised an error: %w", index+1, err) + } + if argument.String() != before { + return fmt.Errorf("case %d mutated its input", index+1) + } + got, err := intervalsFromStarlark(value) + if err != nil { + return fmt.Errorf("case %d returned an invalid value: %w", index+1, err) + } + want := mergeIntervals(input) + if !equalIntervals(got, want) { + return fmt.Errorf("case %d returned %s, want %s", index+1, formatIntervals(got), formatIntervals(want)) + } + } + return nil +} + +func intervalTestCases() [][]interval { + cases := [][]interval{ + {}, + {{start: 4, end: 9}}, + {{start: 5, end: 7}, {start: 1, end: 3}, {start: 2, end: 4}, {start: 10, end: 10}, {start: 8, end: 9}}, + {{start: -8, end: -6}, {start: -5, end: -2}, {start: 0, end: 0}, {start: -3, end: 4}}, + {{start: 1, end: 100}, {start: 4, end: 8}, {start: 1, end: 100}, {start: 20, end: 30}}, + {{start: -1000, end: -999}, {start: 999, end: 1000}}, + {{start: math.MaxInt64 - 1, end: math.MaxInt64 - 1}, {start: math.MaxInt64, end: math.MaxInt64}}, + {{start: math.MinInt64, end: math.MinInt64}, {start: math.MinInt64 + 1, end: math.MinInt64 + 4}}, + } + seed := uint64(0xC0DE10E7) + for n := 0; n < 48; n++ { + count := int(seed%9) + 1 + input := make([]interval, 0, count) + for i := 0; i < count; i++ { + seed = seed*6364136223846793005 + 1442695040888963407 + start := int64(seed%61) - 30 + seed = seed*6364136223846793005 + 1442695040888963407 + length := int64(seed % 12) + input = append(input, interval{start: start, end: start + length}) + } + cases = append(cases, input) + } + return cases +} + +func intervalsToStarlark(input []interval) *starlark.List { + values := make([]starlark.Value, 0, len(input)) + for _, item := range input { + values = append(values, starlark.NewList([]starlark.Value{ + starlark.MakeInt64(item.start), starlark.MakeInt64(item.end), + })) + } + return starlark.NewList(values) +} + +func intervalsFromStarlark(value starlark.Value) ([]interval, error) { + list, ok := value.(*starlark.List) + if !ok { + return nil, fmt.Errorf("expected list, got %s", value.Type()) + } + if list.Len() > 256 { + return nil, errors.New("result contains too many ranges") + } + output := make([]interval, 0, list.Len()) + iterator := list.Iterate() + defer iterator.Done() + var item starlark.Value + for iterator.Next(&item) { + pair, ok := item.(*starlark.List) + if !ok || pair.Len() != 2 { + return nil, errors.New("every range must be a two-item list") + } + start, ok := starlarkInt64(pair.Index(0)) + if !ok { + return nil, errors.New("range start is not a 64-bit integer") + } + end, ok := starlarkInt64(pair.Index(1)) + if !ok { + return nil, errors.New("range end is not a 64-bit integer") + } + output = append(output, interval{start: start, end: end}) + } + return output, nil +} + +func starlarkInt64(value starlark.Value) (int64, bool) { + integer, ok := value.(starlark.Int) + if !ok { + return 0, false + } + return integer.Int64() +} + +func mergeIntervals(input []interval) []interval { + if len(input) == 0 { + return nil + } + items := append([]interval(nil), input...) + for i := 1; i < len(items); i++ { + for j := i; j > 0 && (items[j].start < items[j-1].start || (items[j].start == items[j-1].start && items[j].end < items[j-1].end)); j-- { + items[j], items[j-1] = items[j-1], items[j] + } + } + merged := []interval{items[0]} + for _, item := range items[1:] { + last := &merged[len(merged)-1] + if item.start <= last.end || (last.end < math.MaxInt64 && item.start == last.end+1) { + if item.end > last.end { + last.end = item.end + } + continue + } + merged = append(merged, item) + } + return merged +} + +func equalIntervals(left, right []interval) bool { + if len(left) != len(right) { + return false + } + for index := range left { + if left[index] != right[index] { + return false + } + } + return true +} + +func formatIntervals(items []interval) string { + parts := make([]string, 0, len(items)) + for _, item := range items { + parts = append(parts, fmt.Sprintf("[%d,%d]", item.start, item.end)) + } + return "[" + strings.Join(parts, ",") + "]" +} + +type apiPrice struct { + input float64 + cached float64 + cacheWrite float64 + cacheWriteKnown bool + output float64 +} + +var standardAPIPrices = map[string]apiPrice{ + "gpt-5.6-sol": {input: 5.00, cached: 0.50, cacheWrite: 6.25, cacheWriteKnown: true, output: 30.00}, + "gpt-5.6-terra": {input: 2.00, cached: 0.20, cacheWrite: 2.50, cacheWriteKnown: true, output: 12.00}, + "gpt-5.6-luna": {input: 0.20, cached: 0.02, cacheWrite: 0.25, cacheWriteKnown: true, output: 1.20}, + "gpt-5.5": {input: 5.00, cached: 0.50, output: 30.00}, + "gpt-5.4": {input: 2.50, cached: 0.25, output: 15.00}, + "gpt-5.4-mini": {input: 0.75, cached: 0.075, output: 4.50}, + "gpt-5.3-codex": {input: 1.75, cached: 0.175, output: 14.00}, +} + +func estimateAPICost(model string, usage BenchmarkUsage) (float64, bool) { + price, ok := priceForModel(model) + if !ok { + return 0, false + } + if usage.CacheWriteInputTokens > 0 && !price.cacheWriteKnown { + return 0, false + } + regularInput := usage.InputTokens - usage.CachedInputTokens - usage.CacheWriteInputTokens + if regularInput < 0 { + regularInput = 0 + } + cost := float64(regularInput)*price.input + + float64(usage.CachedInputTokens)*price.cached + + float64(usage.CacheWriteInputTokens)*price.cacheWrite + + float64(usage.OutputTokens)*price.output + return cost / 1_000_000, true +} + +func priceForModel(model string) (apiPrice, bool) { + model = strings.ToLower(strings.TrimSpace(model)) + if price, ok := standardAPIPrices[model]; ok { + return price, true + } + for name, price := range standardAPIPrices { + if suffix := strings.TrimPrefix(model, name+"-"); suffix != model { + if _, err := time.Parse("2006-01-02", suffix); err != nil { + continue + } + return price, true + } + } + return apiPrice{}, false +} diff --git a/internal/codex/benchmark_tasks.go b/internal/codex/benchmark_tasks.go new file mode 100644 index 00000000..60b233ad --- /dev/null +++ b/internal/codex/benchmark_tasks.go @@ -0,0 +1,606 @@ +package codex + +import ( + "errors" + "fmt" + "strconv" + + "go.starlark.net/starlark" +) + +// BenchmarkTaskID is the stable identifier for a deterministic benchmark. +type BenchmarkTaskID string + +const ( + BenchmarkMergeRanges BenchmarkTaskID = "merge-ranges" + BenchmarkLRUCache BenchmarkTaskID = "lru-cache" + BenchmarkExpressionParser BenchmarkTaskID = "expression-parser" + BenchmarkShortestPath BenchmarkTaskID = "shortest-path" +) + +// BenchmarkTask is the public description used by the terminal selector. +type BenchmarkTask struct { + ID BenchmarkTaskID + Name string +} + +type benchmarkDefinition struct { + task BenchmarkTask + function string + prompt string + verify func(string) error +} + +var benchmarkTaskDefinitions = []benchmarkDefinition{ + { + task: BenchmarkTask{ID: BenchmarkMergeRanges, Name: "MERGE RANGES"}, + function: "merge_ranges", + prompt: `Write Starlark code defining this function: + + merge_ranges(ranges) + +The input is a list of inclusive integer ranges, each represented by a two-item list [start, end]. Every input range is valid (start <= end). Return a new list containing the same integer union in canonical form: sorted by start, with overlapping and adjacent ranges merged. Do not mutate the input. The function must work for empty input, duplicates, nested ranges, negative values, and arbitrary ordering. Do not use load().`, + verify: verifyMergeRanges, + }, + { + task: BenchmarkTask{ID: BenchmarkLRUCache, Name: "LRU CACHE"}, + function: "lru_cache", + prompt: `Write Starlark code defining this function: + + lru_cache(capacity, operations) + +Simulate a least-recently-used cache. Each operation is ["put", key, value] or ["get", key], where keys and values are integers. A put inserts or updates a key and makes it most recently used. A get returns its value and makes it most recently used; a missing get returns -1. Evict the least recently used key when capacity is exceeded. Capacity may be zero. Return [get_results, final_entries], where final_entries is a list of [key, value] ordered most-recently-used first. Do not mutate the input and do not use load().`, + verify: verifyLRUCache, + }, + { + task: BenchmarkTask{ID: BenchmarkExpressionParser, Name: "EXPRESSION"}, + function: "evaluate_expression", + prompt: `Write Starlark code defining this function: + + evaluate_expression(tokens) + +The input is a valid token list containing non-negative base-10 integer literals, "+", "-", "*", "(" and ")". Evaluate it using normal arithmetic precedence: multiplication before addition and subtraction, parentheses first, and left associativity. Return the integer result. Do not mutate the input, do not call eval, and do not use load().`, + verify: verifyExpressionParser, + }, + { + task: BenchmarkTask{ID: BenchmarkShortestPath, Name: "SHORTEST PATH"}, + function: "shortest_path", + prompt: `Write Starlark code defining this function: + + shortest_path(grid, start, end) + +The grid is a non-empty rectangular list of lists containing 0 for open cells and 1 for blocked cells. Start and end are open [row, column] coordinates. Moving one cell up, down, left, or right costs one. Return the minimum move count from start to end, or -1 if no route exists. Do not mutate any input and do not use load().`, + verify: verifyShortestPath, + }, +} + +// BenchmarkTasks returns the task catalog in selector and Run All order. +func BenchmarkTasks() []BenchmarkTask { + tasks := make([]BenchmarkTask, 0, len(benchmarkTaskDefinitions)) + for _, definition := range benchmarkTaskDefinitions { + tasks = append(tasks, definition.task) + } + return tasks +} + +func resolveBenchmarkTasks(ids []BenchmarkTaskID) ([]benchmarkDefinition, error) { + if len(ids) == 0 { + return nil, errors.New("select at least one benchmark task") + } + requested := make(map[BenchmarkTaskID]bool, len(ids)) + for _, id := range ids { + requested[id] = true + } + definitions := make([]benchmarkDefinition, 0, len(requested)) + for _, definition := range benchmarkTaskDefinitions { + if requested[definition.task.ID] { + definitions = append(definitions, definition) + delete(requested, definition.task.ID) + } + } + if len(requested) > 0 { + for id := range requested { + return nil, fmt.Errorf("unknown benchmark task %q", id) + } + } + return definitions, nil +} + +func benchmarkPrompt(definition benchmarkDefinition) string { + return definition.prompt + ` + +Starlark language contract for this task: +- Starlark is Python-like but deliberately smaller. +- You may use top-level def functions, if/elif/else, for loops, break/continue, range, len, int, lists, dictionaries, indexing, slicing, append, and pop. +- while loops, recursive calls, eval, imports, and load are unavailable. +- Keep all work deterministic and return only the specified value from the named function. + +Return a JSON object containing one field named "code" whose value is the complete Starlark source. Do not include Markdown fences or commentary.` +} + +func loadBenchmarkFunction(code, functionName string) (*starlark.Thread, starlark.Callable, error) { + thread := &starlark.Thread{Name: "codexometer-verifier"} + thread.SetMaxExecutionSteps(benchmarkStepLimit) + globals, err := starlark.ExecFile(thread, "submission.star", code, nil) + if err != nil { + return nil, nil, fmt.Errorf("code does not load: %w", err) + } + value, ok := globals[functionName] + if !ok { + return nil, nil, fmt.Errorf("code does not define %s", functionName) + } + function, ok := value.(starlark.Callable) + if !ok { + return nil, nil, fmt.Errorf("%s is not callable", functionName) + } + return thread, function, nil +} + +type lruOperation struct { + kind string + key int64 + value int64 +} + +type lruCase struct { + capacity int + items []lruOperation +} + +type lruEntry struct { + key int64 + value int64 +} + +func verifyLRUCache(code string) error { + thread, function, err := loadBenchmarkFunction(code, "lru_cache") + if err != nil { + return err + } + for index, test := range lruTestCases() { + operations := lruOperationsToStarlark(test.items) + before := operations.String() + value, err := starlark.Call(thread, function, starlark.Tuple{starlark.MakeInt(test.capacity), operations}, nil) + if err != nil { + return fmt.Errorf("case %d raised an error: %w", index+1, err) + } + if operations.String() != before { + return fmt.Errorf("case %d mutated its input", index+1) + } + gets, entries, err := lruResultFromStarlark(value) + if err != nil { + return fmt.Errorf("case %d returned an invalid value: %w", index+1, err) + } + wantGets, wantEntries := simulateLRU(test.capacity, test.items) + if !equalInt64s(gets, wantGets) || entries != formatLRUEntries(wantEntries) { + return fmt.Errorf("case %d returned gets=%v entries=%s, want gets=%v entries=%s", index+1, gets, entries, wantGets, formatLRUEntries(wantEntries)) + } + } + return nil +} + +func lruTestCases() []lruCase { + cases := []lruCase{ + {capacity: 0, items: []lruOperation{{kind: "put", key: 1, value: 10}, {kind: "get", key: 1}}}, + {capacity: 1, items: []lruOperation{{kind: "get", key: 4}}}, + {capacity: 1, items: []lruOperation{{kind: "put", key: 1, value: 10}, {kind: "put", key: 2, value: 20}, {kind: "get", key: 1}, {kind: "get", key: 2}}}, + {capacity: 2, items: []lruOperation{{kind: "put", key: 1, value: 10}, {kind: "put", key: 2, value: 20}, {kind: "get", key: 1}, {kind: "put", key: 3, value: 30}, {kind: "get", key: 2}}}, + {capacity: 2, items: []lruOperation{{kind: "put", key: -1, value: -10}, {kind: "put", key: -1, value: 99}, {kind: "get", key: -1}}}, + } + seed := uint64(0x1A2B3C4D) + for n := 0; n < 40; n++ { + seed = nextBenchmarkSeed(seed) + capacity := int(seed % 6) + seed = nextBenchmarkSeed(seed) + count := int(seed%24) + 6 + operations := make([]lruOperation, 0, count) + for i := 0; i < count; i++ { + seed = nextBenchmarkSeed(seed) + key := int64(seed%9) - 4 + if seed%3 == 0 { + operations = append(operations, lruOperation{kind: "get", key: key}) + continue + } + seed = nextBenchmarkSeed(seed) + operations = append(operations, lruOperation{kind: "put", key: key, value: int64(seed%201) - 100}) + } + cases = append(cases, lruCase{capacity: capacity, items: operations}) + } + return cases +} + +func lruOperationsToStarlark(operations []lruOperation) *starlark.List { + values := make([]starlark.Value, 0, len(operations)) + for _, operation := range operations { + parts := []starlark.Value{starlark.String(operation.kind), starlark.MakeInt64(operation.key)} + if operation.kind == "put" { + parts = append(parts, starlark.MakeInt64(operation.value)) + } + values = append(values, starlark.NewList(parts)) + } + return starlark.NewList(values) +} + +func lruResultFromStarlark(value starlark.Value) ([]int64, string, error) { + outer, ok := value.(*starlark.List) + if !ok || outer.Len() != 2 { + return nil, "", errors.New("expected [get_results, final_entries]") + } + gets, err := intListFromStarlark(outer.Index(0), 256) + if err != nil { + return nil, "", fmt.Errorf("get results: %w", err) + } + entries, err := intPairsFromStarlark(outer.Index(1), 256) + if err != nil { + return nil, "", fmt.Errorf("final entries: %w", err) + } + return gets, formatIntervals(entries), nil +} + +func simulateLRU(capacity int, operations []lruOperation) ([]int64, []lruEntry) { + var gets []int64 + var entries []lruEntry + for _, operation := range operations { + found := -1 + for index, entry := range entries { + if entry.key == operation.key { + found = index + break + } + } + if operation.kind == "get" { + if found < 0 { + gets = append(gets, -1) + continue + } + entry := entries[found] + gets = append(gets, entry.value) + entries = append([]lruEntry{entry}, append(entries[:found], entries[found+1:]...)...) + continue + } + entry := lruEntry{key: operation.key, value: operation.value} + if found >= 0 { + entries = append(entries[:found], entries[found+1:]...) + } + entries = append([]lruEntry{entry}, entries...) + if len(entries) > capacity { + entries = entries[:capacity] + } + } + return gets, entries +} + +func formatLRUEntries(entries []lruEntry) string { + items := make([]interval, 0, len(entries)) + for _, entry := range entries { + items = append(items, interval{start: entry.key, end: entry.value}) + } + return formatIntervals(items) +} + +type expressionCase struct { + tokens []string + want int64 +} + +func verifyExpressionParser(code string) error { + thread, function, err := loadBenchmarkFunction(code, "evaluate_expression") + if err != nil { + return err + } + for index, test := range expressionTestCases() { + values := make([]starlark.Value, 0, len(test.tokens)) + for _, token := range test.tokens { + values = append(values, starlark.String(token)) + } + argument := starlark.NewList(values) + before := argument.String() + value, err := starlark.Call(thread, function, starlark.Tuple{argument}, nil) + if err != nil { + return fmt.Errorf("case %d raised an error: %w", index+1, err) + } + if argument.String() != before { + return fmt.Errorf("case %d mutated its input", index+1) + } + got, ok := starlarkInt64(value) + if !ok { + return fmt.Errorf("case %d returned a non-64-bit integer", index+1) + } + if got != test.want { + return fmt.Errorf("case %d returned %d, want %d", index+1, got, test.want) + } + } + return nil +} + +func expressionTestCases() []expressionCase { + raw := [][]string{ + {"0"}, {"42"}, {"2", "+", "3", "*", "4"}, {"(", "2", "+", "3", ")", "*", "4"}, + {"9", "-", "3", "-", "2"}, {"1", "-", "8", "*", "2"}, {"(", "7", ")"}, + {"2", "*", "(", "3", "+", "4", "*", "5", ")", "-", "6"}, + } + cases := make([]expressionCase, 0, len(raw)+40) + for _, tokens := range raw { + want, _ := evaluateTokens(tokens) + cases = append(cases, expressionCase{tokens: tokens, want: want}) + } + seed := uint64(0xE7E55) + for n := 0; n < 40; n++ { + tokens := generateExpressionTokens(&seed, 0) + want, err := evaluateTokens(tokens) + if err != nil { + panic(err) + } + cases = append(cases, expressionCase{tokens: tokens, want: want}) + } + return cases +} + +func generateExpressionTokens(seed *uint64, depth int) []string { + parts := generateTermTokens(seed, depth) + *seed = nextBenchmarkSeed(*seed) + count := int(*seed % 2) + for i := 0; i < count; i++ { + *seed = nextBenchmarkSeed(*seed) + op := "+" + if *seed%2 == 0 { + op = "-" + } + parts = append(parts, op) + parts = append(parts, generateTermTokens(seed, depth)...) + } + return parts +} + +func generateTermTokens(seed *uint64, depth int) []string { + parts := generateFactorTokens(seed, depth) + *seed = nextBenchmarkSeed(*seed) + count := int(*seed % 2) + for i := 0; i < count; i++ { + parts = append(parts, "*") + parts = append(parts, generateFactorTokens(seed, depth)...) + } + return parts +} + +func generateFactorTokens(seed *uint64, depth int) []string { + *seed = nextBenchmarkSeed(*seed) + if depth < 2 && *seed%4 == 0 { + return append(append([]string{"("}, generateExpressionTokens(seed, depth+1)...), ")") + } + return []string{strconv.FormatUint(*seed%10, 10)} +} + +type tokenParser struct { + tokens []string + index int +} + +func evaluateTokens(tokens []string) (int64, error) { + parser := tokenParser{tokens: tokens} + value, err := parser.expression() + if err != nil { + return 0, err + } + if parser.index != len(tokens) { + return 0, errors.New("trailing expression tokens") + } + return value, nil +} + +func (p *tokenParser) expression() (int64, error) { + value, err := p.term() + for err == nil && p.index < len(p.tokens) && (p.tokens[p.index] == "+" || p.tokens[p.index] == "-") { + op := p.tokens[p.index] + p.index++ + var right int64 + right, err = p.term() + if op == "+" { + value += right + } else { + value -= right + } + } + return value, err +} + +func (p *tokenParser) term() (int64, error) { + value, err := p.factor() + for err == nil && p.index < len(p.tokens) && p.tokens[p.index] == "*" { + p.index++ + var right int64 + right, err = p.factor() + value *= right + } + return value, err +} + +func (p *tokenParser) factor() (int64, error) { + if p.index >= len(p.tokens) { + return 0, errors.New("missing expression factor") + } + token := p.tokens[p.index] + p.index++ + if token == "(" { + value, err := p.expression() + if err != nil || p.index >= len(p.tokens) || p.tokens[p.index] != ")" { + return 0, errors.New("unclosed expression group") + } + p.index++ + return value, nil + } + return strconv.ParseInt(token, 10, 64) +} + +type pathCase struct { + grid [][]int64 + start, end [2]int64 +} + +func verifyShortestPath(code string) error { + thread, function, err := loadBenchmarkFunction(code, "shortest_path") + if err != nil { + return err + } + for index, test := range pathTestCases() { + grid := intGridToStarlark(test.grid) + start := coordinateToStarlark(test.start) + end := coordinateToStarlark(test.end) + before := grid.String() + start.String() + end.String() + value, err := starlark.Call(thread, function, starlark.Tuple{grid, start, end}, nil) + if err != nil { + return fmt.Errorf("case %d raised an error: %w", index+1, err) + } + if grid.String()+start.String()+end.String() != before { + return fmt.Errorf("case %d mutated its input", index+1) + } + got, ok := starlarkInt64(value) + if !ok { + return fmt.Errorf("case %d returned a non-64-bit integer", index+1) + } + want := shortestPath(test) + if got != want { + return fmt.Errorf("case %d returned %d, want %d", index+1, got, want) + } + } + return nil +} + +func pathTestCases() []pathCase { + cases := []pathCase{ + {grid: [][]int64{{0}}, start: [2]int64{0, 0}, end: [2]int64{0, 0}}, + {grid: [][]int64{{0, 0, 0}}, start: [2]int64{0, 0}, end: [2]int64{0, 2}}, + {grid: [][]int64{{0, 1}, {1, 0}}, start: [2]int64{0, 0}, end: [2]int64{1, 1}}, + {grid: [][]int64{{0, 0, 1}, {1, 0, 1}, {1, 0, 0}}, start: [2]int64{0, 0}, end: [2]int64{2, 2}}, + {grid: [][]int64{{0}, {0}, {0}, {0}}, start: [2]int64{3, 0}, end: [2]int64{0, 0}}, + } + seed := uint64(0x5A07E57) + for n := 0; n < 40; n++ { + seed = nextBenchmarkSeed(seed) + rows := int(seed%7) + 2 + seed = nextBenchmarkSeed(seed) + columns := int(seed%7) + 2 + grid := make([][]int64, rows) + for row := range grid { + grid[row] = make([]int64, columns) + for column := range grid[row] { + seed = nextBenchmarkSeed(seed) + if seed%4 == 0 { + grid[row][column] = 1 + } + } + } + seed = nextBenchmarkSeed(seed) + start := [2]int64{int64(seed % uint64(rows)), int64((seed / 7) % uint64(columns))} + seed = nextBenchmarkSeed(seed) + end := [2]int64{int64(seed % uint64(rows)), int64((seed / 7) % uint64(columns))} + grid[start[0]][start[1]], grid[end[0]][end[1]] = 0, 0 + cases = append(cases, pathCase{grid: grid, start: start, end: end}) + } + return cases +} + +func intGridToStarlark(grid [][]int64) *starlark.List { + rows := make([]starlark.Value, 0, len(grid)) + for _, row := range grid { + values := make([]starlark.Value, 0, len(row)) + for _, cell := range row { + values = append(values, starlark.MakeInt64(cell)) + } + rows = append(rows, starlark.NewList(values)) + } + return starlark.NewList(rows) +} + +func coordinateToStarlark(coordinate [2]int64) *starlark.List { + return starlark.NewList([]starlark.Value{starlark.MakeInt64(coordinate[0]), starlark.MakeInt64(coordinate[1])}) +} + +func shortestPath(test pathCase) int64 { + rows, columns := len(test.grid), len(test.grid[0]) + distance := make([][]int64, rows) + for row := range distance { + distance[row] = make([]int64, columns) + for column := range distance[row] { + distance[row][column] = -1 + } + } + queue := [][2]int64{test.start} + distance[test.start[0]][test.start[1]] = 0 + for len(queue) > 0 { + current := queue[0] + queue = queue[1:] + if current == test.end { + return distance[current[0]][current[1]] + } + for _, delta := range [][2]int64{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} { + next := [2]int64{current[0] + delta[0], current[1] + delta[1]} + if next[0] < 0 || next[0] >= int64(rows) || next[1] < 0 || next[1] >= int64(columns) || + test.grid[next[0]][next[1]] != 0 || distance[next[0]][next[1]] >= 0 { + continue + } + distance[next[0]][next[1]] = distance[current[0]][current[1]] + 1 + queue = append(queue, next) + } + } + return -1 +} + +func intListFromStarlark(value starlark.Value, limit int) ([]int64, error) { + list, ok := value.(*starlark.List) + if !ok { + return nil, fmt.Errorf("expected list, got %s", value.Type()) + } + if list.Len() > limit { + return nil, errors.New("result contains too many items") + } + output := make([]int64, 0, list.Len()) + for index := 0; index < list.Len(); index++ { + item, ok := starlarkInt64(list.Index(index)) + if !ok { + return nil, errors.New("result item is not a 64-bit integer") + } + output = append(output, item) + } + return output, nil +} + +func intPairsFromStarlark(value starlark.Value, limit int) ([]interval, error) { + list, ok := value.(*starlark.List) + if !ok { + return nil, fmt.Errorf("expected list, got %s", value.Type()) + } + if list.Len() > limit { + return nil, errors.New("result contains too many pairs") + } + output := make([]interval, 0, list.Len()) + for index := 0; index < list.Len(); index++ { + pair, ok := list.Index(index).(*starlark.List) + if !ok || pair.Len() != 2 { + return nil, errors.New("every entry must be a two-item list") + } + first, firstOK := starlarkInt64(pair.Index(0)) + second, secondOK := starlarkInt64(pair.Index(1)) + if !firstOK || !secondOK { + return nil, errors.New("entry values must be 64-bit integers") + } + output = append(output, interval{start: first, end: second}) + } + return output, nil +} + +func equalInt64s(left, right []int64) bool { + if len(left) != len(right) { + return false + } + for index := range left { + if left[index] != right[index] { + return false + } + } + return true +} + +func nextBenchmarkSeed(seed uint64) uint64 { + return seed*6364136223846793005 + 1442695040888963407 +} diff --git a/internal/codex/benchmark_test.go b/internal/codex/benchmark_test.go new file mode 100644 index 00000000..db2a104f --- /dev/null +++ b/internal/codex/benchmark_test.go @@ -0,0 +1,644 @@ +package codex + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "os" + "strings" + "testing" + "time" +) + +const correctStarlarkSubmission = ` +def merge_ranges(ranges): + items = [] + for pair in ranges: + items.append([pair[0], pair[1]]) + items = sorted(items) + result = [] + for pair in items: + if not result or pair[0] > result[-1][1] + 1: + result.append([pair[0], pair[1]]) + elif pair[1] > result[-1][1]: + result[-1][1] = pair[1] + return result +` + +const correctLRUSubmission = ` +def lru_cache(capacity, operations): + entries = [] + gets = [] + for operation in operations: + found = -1 + for i in range(len(entries)): + if entries[i][0] == operation[1]: + found = i + if operation[0] == "get": + if found < 0: + gets.append(-1) + else: + entry = entries[found] + gets.append(entry[1]) + entries = [entry] + entries[:found] + entries[found + 1:] + else: + if found >= 0: + entries = entries[:found] + entries[found + 1:] + entries = [[operation[1], operation[2]]] + entries + if len(entries) > capacity: + entries = entries[:capacity] + return [gets, entries] +` + +const correctExpressionSubmission = ` +def _apply_operator(values, operators): + right = values.pop() + left = values.pop() + operator = operators.pop() + if operator == "+": + values.append(left + right) + elif operator == "-": + values.append(left - right) + else: + values.append(left * right) + +def evaluate_expression(tokens): + values = [] + operators = [] + precedence = {"+": 1, "-": 1, "*": 2} + for token in tokens: + if token == "(": + operators.append(token) + elif token == ")": + for _ in range(len(operators)): + if operators[-1] == "(": + break + _apply_operator(values, operators) + operators.pop() + elif token == "+" or token == "-" or token == "*": + for _ in range(len(operators)): + if operators[-1] == "(" or precedence[operators[-1]] < precedence[token]: + break + _apply_operator(values, operators) + operators.append(token) + else: + values.append(int(token)) + for _ in range(len(operators)): + _apply_operator(values, operators) + return values[0] +` + +const correctShortestPathSubmission = ` +def shortest_path(grid, start, end): + distances = [] + for row in grid: + distances.append([-1 for _ in row]) + queue = [[start[0], start[1]]] + distances[start[0]][start[1]] = 0 + head = 0 + for _ in range(len(grid) * len(grid[0])): + if head >= len(queue): + break + current = queue[head] + head += 1 + if current == end: + return distances[current[0]][current[1]] + for delta in [[-1, 0], [1, 0], [0, -1], [0, 1]]: + row = current[0] + delta[0] + column = current[1] + delta[1] + if row >= 0 and row < len(grid) and column >= 0 and column < len(grid[0]): + if grid[row][column] == 0 and distances[row][column] < 0: + distances[row][column] = distances[current[0]][current[1]] + 1 + queue.append([row, column]) + return -1 +` + +func TestVerifyMergeRangesAcceptsCorrectHermeticSubmission(t *testing.T) { + if err := verifyMergeRanges(correctStarlarkSubmission); err != nil { + t.Fatalf("correct submission failed: %v", err) + } +} + +func TestAdditionalBenchmarkVerifiersAcceptCorrectSubmissions(t *testing.T) { + tests := []struct { + name string + verify func(string) error + code string + }{ + {name: "LRU cache", verify: verifyLRUCache, code: correctLRUSubmission}, + {name: "expression parser", verify: verifyExpressionParser, code: correctExpressionSubmission}, + {name: "shortest path", verify: verifyShortestPath, code: correctShortestPathSubmission}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if err := test.verify(test.code); err != nil { + t.Fatalf("correct submission failed: %v", err) + } + }) + } +} + +func TestAdditionalBenchmarkVerifiersRejectIncorrectSubmissions(t *testing.T) { + tests := []struct { + name string + verify func(string) error + code string + }{ + {name: "LRU cache", verify: verifyLRUCache, code: "def lru_cache(capacity, operations):\n return [[], []]\n"}, + {name: "expression parser", verify: verifyExpressionParser, code: "def evaluate_expression(tokens):\n return 0\n"}, + {name: "shortest path", verify: verifyShortestPath, code: "def shortest_path(grid, start, end):\n return -1\n"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if err := test.verify(test.code); err == nil { + t.Fatal("incorrect submission unexpectedly passed") + } + }) + } +} + +func TestBenchmarkTaskCatalogAndSelection(t *testing.T) { + tasks := BenchmarkTasks() + if len(tasks) != 4 || tasks[0].ID != BenchmarkMergeRanges || tasks[3].ID != BenchmarkShortestPath { + t.Fatalf("task catalog = %#v", tasks) + } + definitions, err := resolveBenchmarkTasks([]BenchmarkTaskID{BenchmarkShortestPath, BenchmarkLRUCache, BenchmarkLRUCache}) + if err != nil || len(definitions) != 2 || definitions[0].task.ID != BenchmarkLRUCache || definitions[1].task.ID != BenchmarkShortestPath { + t.Fatalf("resolved tasks = %#v, %v", definitions, err) + } + if _, err := resolveBenchmarkTasks(nil); err == nil { + t.Fatal("empty benchmark selection was accepted") + } + if _, err := resolveBenchmarkTasks([]BenchmarkTaskID{"unknown"}); err == nil { + t.Fatal("unknown benchmark selection was accepted") + } + for _, definition := range benchmarkTaskDefinitions { + prompt := benchmarkPrompt(definition) + for _, required := range []string{definition.function, "Starlark language contract", "while loops", `field named "code"`} { + if !strings.Contains(prompt, required) { + t.Fatalf("%s prompt is missing %q", definition.task.ID, required) + } + } + } +} + +type nopWriteCloser struct { + io.Writer +} + +func (nopWriteCloser) Close() error { return nil } + +func newFakeBenchmarkServer(envelopes ...benchmarkEnvelope) (*appServerSession, *bytes.Buffer) { + requests := &bytes.Buffer{} + server := &appServerSession{ + stdin: nopWriteCloser{requests}, encoder: json.NewEncoder(requests), + envelopes: make(chan benchmarkEnvelope, len(envelopes)+1), + readErrors: make(chan error, 1), done: make(chan struct{}), stderr: &lockedBuffer{}, + } + for _, envelope := range envelopes { + server.envelopes <- envelope + } + return server, requests +} + +func rawJSON(value any) json.RawMessage { + data, err := json.Marshal(value) + if err != nil { + panic(err) + } + return data +} + +func TestRunBenchmarkConsumesStreamedResultAndUsage(t *testing.T) { + message := string(rawJSON(map[string]string{"code": correctStarlarkSubmission})) + server, requests := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{ + "thread": map[string]string{"id": "thread-1"}, "model": "gpt-5.3-codex", + })}, + // A fast notification arriving before the turn/start response must be retained. + benchmarkEnvelope{Method: "item/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", + "item": map[string]string{"type": "agentMessage", "text": message}, + })}, + benchmarkEnvelope{ID: rawJSON(2), Result: rawJSON(map[string]any{ + "turn": map[string]string{"id": "turn-1"}, + })}, + benchmarkEnvelope{Method: "thread/tokenUsage/updated", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", + "tokenUsage": map[string]any{"total": BenchmarkUsage{TotalTokens: 1200, InputTokens: 1000, CachedInputTokens: 200, OutputTokens: 200}}, + })}, + benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", + "turn": map[string]any{"id": "turn-1", "status": "completed", "items": []any{}}, + })}, + ) + result, fatalErr := server.runBenchmark(context.Background(), benchmarkCombination{ + model: benchmarkModel{Model: "gpt-5.3-codex", DisplayName: "GPT-5.3 Codex"}, effort: "high", + }, benchmarkTaskDefinitions[0]) + if fatalErr != nil || !result.Correct { + t.Fatalf("benchmark result = %#v, fatal error = %v", result, fatalErr) + } + if result.Usage.TotalTokens != 1200 || !result.CostKnown || result.CostUSD <= 0 { + t.Fatalf("usage/cost not captured: %#v", result) + } + if !strings.Contains(requests.String(), `"method":"thread/start"`) || !strings.Contains(requests.String(), `"effort":"high"`) { + t.Fatalf("requests missing thread or effort: %s", requests.String()) + } + if !strings.Contains(requests.String(), `"sandbox":"read-only"`) { + t.Fatalf("thread request did not use the app-server sandbox spelling: %s", requests.String()) + } +} + +func TestRunBenchmarkSuiteDiscoversAndRunsEveryCombination(t *testing.T) { + message := string(rawJSON(map[string]string{"code": correctStarlarkSubmission})) + server, _ := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{ + "data": []any{map[string]any{ + "model": "gpt-5.6-luna", "displayName": "GPT-5.6 Luna", + "supportedReasoningEfforts": []any{ + map[string]string{"reasoningEffort": "low"}, + map[string]string{"reasoningEffort": "high"}, + }, + }}, + })}, + benchmarkEnvelope{ID: rawJSON(2), Result: rawJSON(map[string]any{"thread": map[string]string{"id": "thread-low"}})}, + benchmarkEnvelope{ID: rawJSON(3), Result: rawJSON(map[string]any{"turn": map[string]string{"id": "turn-low"}})}, + benchmarkEnvelope{Method: "item/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-low", "turnId": "turn-low", "item": map[string]string{"type": "agentMessage", "text": message}, + })}, + benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-low", "turn": map[string]any{"id": "turn-low", "status": "completed"}, + })}, + benchmarkEnvelope{ID: rawJSON(4), Result: rawJSON(map[string]any{"thread": map[string]string{"id": "thread-high"}})}, + benchmarkEnvelope{ID: rawJSON(5), Result: rawJSON(map[string]any{"turn": map[string]string{"id": "turn-high"}})}, + benchmarkEnvelope{Method: "item/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-high", "turnId": "turn-high", "item": map[string]string{"type": "agentMessage", "text": message}, + })}, + benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-high", "turn": map[string]any{"id": "turn-high", "status": "completed"}, + })}, + ) + original := openBenchmarkAppServer + openBenchmarkAppServer = func(context.Context, string) (*appServerSession, error) { return server, nil } + t.Cleanup(func() { openBenchmarkAppServer = original }) + + var events []BenchmarkEvent + Client{Binary: "ignored"}.RunBenchmarkSuite(context.Background(), []BenchmarkTaskID{BenchmarkMergeRanges}, func(event BenchmarkEvent) { + events = append(events, event) + }) + var efforts []string + for _, event := range events { + if event.Result != nil { + if !event.Result.Correct { + t.Fatalf("suite result failed: %#v", event.Result) + } + efforts = append(efforts, event.Result.Effort) + } + } + if len(efforts) != 2 || efforts[0] != "low" || efforts[1] != "high" { + t.Fatalf("suite efforts = %v, want [low high]", efforts) + } + last := events[len(events)-1] + if !last.Done || last.Err != nil || last.Total != 2 || last.Completed != 2 { + t.Fatalf("final suite event = %#v", last) + } +} + +func TestRunBenchmarkSuiteMultipliesSelectedTasksByCombinations(t *testing.T) { + mergeMessage := string(rawJSON(map[string]string{"code": correctStarlarkSubmission})) + lruMessage := string(rawJSON(map[string]string{"code": correctLRUSubmission})) + server, _ := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{ + "data": []any{map[string]any{ + "model": "gpt-5.6-luna", "displayName": "GPT-5.6 Luna", + "supportedReasoningEfforts": []any{map[string]string{"reasoningEffort": "low"}}, + }}, + })}, + benchmarkEnvelope{ID: rawJSON(2), Result: rawJSON(map[string]any{"thread": map[string]string{"id": "thread-merge"}})}, + benchmarkEnvelope{ID: rawJSON(3), Result: rawJSON(map[string]any{"turn": map[string]string{"id": "turn-merge"}})}, + benchmarkEnvelope{Method: "item/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-merge", "turnId": "turn-merge", "item": map[string]string{"type": "agentMessage", "text": mergeMessage}, + })}, + benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-merge", "turn": map[string]any{"id": "turn-merge", "status": "completed"}, + })}, + benchmarkEnvelope{ID: rawJSON(4), Result: rawJSON(map[string]any{"thread": map[string]string{"id": "thread-lru"}})}, + benchmarkEnvelope{ID: rawJSON(5), Result: rawJSON(map[string]any{"turn": map[string]string{"id": "turn-lru"}})}, + benchmarkEnvelope{Method: "item/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-lru", "turnId": "turn-lru", "item": map[string]string{"type": "agentMessage", "text": lruMessage}, + })}, + benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-lru", "turn": map[string]any{"id": "turn-lru", "status": "completed"}, + })}, + ) + original := openBenchmarkAppServer + openBenchmarkAppServer = func(context.Context, string) (*appServerSession, error) { return server, nil } + t.Cleanup(func() { openBenchmarkAppServer = original }) + + var results []BenchmarkResult + var final BenchmarkEvent + Client{}.RunBenchmarkSuite(context.Background(), []BenchmarkTaskID{BenchmarkLRUCache, BenchmarkMergeRanges}, func(event BenchmarkEvent) { + if event.Result != nil { + results = append(results, *event.Result) + } + final = event + }) + if len(results) != 2 || results[0].TaskID != BenchmarkMergeRanges || results[1].TaskID != BenchmarkLRUCache { + t.Fatalf("task results = %#v", results) + } + if !results[0].Correct || !results[1].Correct || !final.Done || final.Total != 2 || final.Completed != 2 || final.Combinations != 1 { + t.Fatalf("suite result = %#v, final = %#v", results, final) + } +} + +func TestRunBenchmarkSuiteReportsStartupFailure(t *testing.T) { + original := openBenchmarkAppServer + openBenchmarkAppServer = func(context.Context, string) (*appServerSession, error) { + return nil, errors.New("offline") + } + t.Cleanup(func() { openBenchmarkAppServer = original }) + var final BenchmarkEvent + Client{}.RunBenchmarkSuite(context.Background(), []BenchmarkTaskID{BenchmarkMergeRanges}, func(event BenchmarkEvent) { final = event }) + if !final.Done || final.Err == nil || final.Err.Error() != "offline" { + t.Fatalf("startup failure event = %#v", final) + } +} + +func TestBenchmarkCombinationCountUsesVisibleCatalogWithoutTurns(t *testing.T) { + server, requests := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{ + "data": []any{ + map[string]any{"model": "a", "supportedReasoningEfforts": []any{map[string]string{"reasoningEffort": "low"}, map[string]string{"reasoningEffort": "high"}}}, + map[string]any{"model": "b", "defaultReasoningEffort": "medium"}, + }, + })}, + ) + original := openBenchmarkAppServer + openBenchmarkAppServer = func(context.Context, string) (*appServerSession, error) { return server, nil } + t.Cleanup(func() { openBenchmarkAppServer = original }) + count, err := (Client{}).BenchmarkCombinationCount(context.Background()) + if err != nil || count != 3 { + t.Fatalf("combination count = %d, %v; want 3", count, err) + } + if strings.Contains(requests.String(), `"method":"turn/start"`) { + t.Fatalf("catalog planning unexpectedly started a model turn: %s", requests.String()) + } +} + +func TestAppServerReadLoopAndClose(t *testing.T) { + server, _ := newFakeBenchmarkServer() + input := strings.NewReader("{\"method\":\"first\"}\n{\"method\":\"second\"}\n") + go server.readLoop(json.NewDecoder(input)) + for _, want := range []string{"first", "second"} { + envelope, err := server.nextEnvelope(context.Background()) + if err != nil || envelope.Method != want { + t.Fatalf("decoded envelope = %#v, %v; want %s", envelope, err, want) + } + } + if _, err := server.nextEnvelope(context.Background()); err == nil || !strings.Contains(err.Error(), "closed unexpectedly") { + t.Fatalf("decoder terminal error = %v, want unexpected-close diagnostic", err) + } + server.close() +} + +func TestLockedBufferAndFatalErrorClassification(t *testing.T) { + buffer := &lockedBuffer{} + if _, err := buffer.Write([]byte("diagnostic")); err != nil || buffer.String() != "diagnostic" { + t.Fatalf("locked buffer = %q, %v", buffer.String(), err) + } + if err := fatalBenchmarkError(context.Background(), &benchmarkMethodError{method: "turn/start", code: -1, message: "rejected"}); err != nil { + t.Fatalf("RPC method failure was classified fatal: %v", err) + } + transport := errors.New("transport") + if err := fatalBenchmarkError(context.Background(), transport); !errors.Is(err, transport) { + t.Fatalf("transport error = %v, want original", err) + } +} + +func TestModelsPaginatesAndOmitsHiddenRows(t *testing.T) { + next := "page-2" + server, _ := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{ + "data": []any{ + map[string]any{"model": "visible-a", "displayName": "A"}, + map[string]any{"model": "hidden", "displayName": "Hidden", "hidden": true}, + }, + "nextCursor": next, + })}, + benchmarkEnvelope{ID: rawJSON(2), Result: rawJSON(map[string]any{ + "data": []any{map[string]any{"model": "visible-b", "displayName": "B"}}, + "nextCursor": nil, + })}, + ) + models, err := server.models(context.Background()) + if err != nil || len(models) != 2 || models[0].Model != "visible-a" || models[1].Model != "visible-b" { + t.Fatalf("models = %#v, error = %v", models, err) + } +} + +func TestNextEnvelopeHonorsCancellation(t *testing.T) { + server, _ := newFakeBenchmarkServer() + ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) + defer cancel() + if _, err := server.nextEnvelope(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("nextEnvelope error = %v, want deadline exceeded", err) + } +} + +func TestLiveBenchmarkModelCatalog(t *testing.T) { + if os.Getenv("CODEXOMETER_LIVE_TEST") != "1" { + t.Skip("set CODEXOMETER_LIVE_TEST=1 to exercise the installed Codex app-server") + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + server, err := startAppServer(ctx, "codex") + if err != nil { + t.Fatal(err) + } + defer server.close() + models, err := server.models(ctx) + if err != nil { + t.Fatal(err) + } + if combinations := benchmarkCombinations(models); len(combinations) == 0 { + t.Fatalf("model catalog contained no benchmark combinations: %#v", models) + } else { + t.Logf("discovered %d visible model(s) and %d model/effort combination(s)", len(models), len(combinations)) + for _, model := range models { + t.Logf("model %s efforts=%v", model.Model, model.SupportedReasoningEfforts) + } + } +} + +func TestLiveBenchmarkThreadStart(t *testing.T) { + if os.Getenv("CODEXOMETER_LIVE_TEST") != "1" { + t.Skip("set CODEXOMETER_LIVE_TEST=1 to exercise the installed Codex app-server") + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + server, err := startAppServer(ctx, "codex") + if err != nil { + t.Fatal(err) + } + defer server.close() + workspace := t.TempDir() + result, err := server.call(ctx, "thread/start", map[string]any{ + "cwd": workspace, "approvalPolicy": "never", "sandbox": "read-only", "ephemeral": true, + }, nil) + if err != nil { + t.Fatalf("start ephemeral read-only benchmark thread: %v", err) + } + if !strings.Contains(string(result), `"thread"`) { + t.Fatalf("thread/start returned %s", result) + } +} + +func TestLiveBenchmarkSingleLunaTrial(t *testing.T) { + if os.Getenv("CODEXOMETER_LIVE_BENCHMARK") != "1" { + t.Skip("set CODEXOMETER_LIVE_BENCHMARK=1 to consume quota for one live Luna/low trial") + } + ctx, cancel := context.WithTimeout(context.Background(), benchmarkTurnTimeout) + defer cancel() + server, err := startAppServer(ctx, "codex") + if err != nil { + t.Fatal(err) + } + defer server.close() + models, err := server.models(ctx) + if err != nil { + t.Fatal(err) + } + var selected *benchmarkCombination + for _, combination := range benchmarkCombinations(models) { + if combination.model.Model == "gpt-5.6-luna" && combination.effort == "low" { + candidate := combination + selected = &candidate + break + } + } + if selected == nil { + t.Skip("gpt-5.6-luna/low is not visible to this account") + } + result, fatalErr := server.runBenchmark(ctx, *selected, benchmarkTaskDefinitions[0]) + if fatalErr != nil { + t.Fatalf("live trial transport failure: %v", fatalErr) + } + if !result.Correct { + t.Fatalf("live trial failed: %s (usage=%+v)", result.Failure, result.Usage) + } + if result.Usage.TotalTokens <= 0 { + t.Fatalf("live trial passed without token telemetry: %+v", result) + } + t.Logf("live Luna/low passed in %s using %d tokens", result.Duration.Round(time.Millisecond), result.Usage.TotalTokens) +} + +func TestVerifyMergeRangesRejectsWrongUnsafeAndMalformedSubmissions(t *testing.T) { + tests := []struct { + name string + code string + want string + }{ + {name: "wrong answer", code: "def merge_ranges(ranges):\n return ranges\n", want: "returned"}, + {name: "missing function", code: "answer = 42\n", want: "does not define"}, + {name: "not callable", code: "merge_ranges = 42\n", want: "not callable"}, + {name: "bad type", code: "def merge_ranges(ranges):\n return 42\n", want: "expected list"}, + {name: "mutates input", code: "def merge_ranges(ranges):\n ranges.append([99, 100])\n return ranges\n", want: "mutated"}, + {name: "load denied", code: "load(\"outside.star\", \"x\")\ndef merge_ranges(ranges):\n return []\n", want: "load not implemented"}, + {name: "step limit", code: "def merge_ranges(ranges):\n x = 0\n for i in range(10000000):\n x += i\n return []\n", want: "too many steps"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := verifyMergeRanges(test.code) + if err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("verify error = %v, want containing %q", err, test.want) + } + }) + } +} + +func TestBenchmarkCodeRequiresStrictStructuredOutput(t *testing.T) { + code, err := benchmarkCode(`{"code":"def merge_ranges(ranges):\n return []"}`) + if err != nil || !strings.Contains(code, "merge_ranges") { + t.Fatalf("valid code result = %q, %v", code, err) + } + for _, message := range []string{"", "```python\npass\n```", `{"code":""}`, `{"code":"pass","extra":true}`, `{"code":"pass"} {"code":"pass"}`} { + if _, err := benchmarkCode(message); err == nil { + t.Fatalf("benchmarkCode(%q) unexpectedly succeeded", message) + } + } + oversized := `{"code":"` + strings.Repeat("x", benchmarkCodeLimit) + `"}` + if _, err := benchmarkCode(oversized); err == nil { + t.Fatal("oversized result unexpectedly succeeded") + } +} + +func TestBenchmarkCombinationsPreserveCatalogOrder(t *testing.T) { + models := []benchmarkModel{ + { + Model: "model-a", DisplayName: "Model A", DefaultReasoningEffort: "medium", + SupportedReasoningEfforts: []benchmarkEffortOption{{ReasoningEffort: "low"}, {ReasoningEffort: "high"}}, + }, + {Model: "model-b", DefaultReasoningEffort: "medium"}, + {Model: ""}, + } + got := benchmarkCombinations(models) + if len(got) != 3 { + t.Fatalf("got %d combinations, want 3", len(got)) + } + if got[0].effort != "low" || got[1].effort != "high" || got[2].effort != "medium" { + t.Fatalf("effort order = %q, %q, %q", got[0].effort, got[1].effort, got[2].effort) + } + if got[2].model.DisplayName != "model-b" { + t.Fatalf("fallback display name = %q", got[2].model.DisplayName) + } +} + +func TestEstimateAPICostUsesCachedAndOutputRates(t *testing.T) { + usage := BenchmarkUsage{ + InputTokens: 2_000, CachedInputTokens: 500, CacheWriteInputTokens: 100, + OutputTokens: 300, ReasoningOutputTokens: 200, + } + cost, ok := estimateAPICost("gpt-5.6-sol-2026-08-01", usage) + if !ok { + t.Fatal("known model was not priced") + } + want := (1_400*5.00 + 500*0.50 + 100*6.25 + 300*30.00) / 1_000_000 + if cost != want { + t.Fatalf("cost = %.8f, want %.8f", cost, want) + } + if _, ok := estimateAPICost("future-unpriced-model", usage); ok { + t.Fatal("unknown model received a guessed price") + } + if _, ok := estimateAPICost("gpt-5.3-codex-spark", usage); ok { + t.Fatal("unlisted Spark pricing was guessed from a different model") + } +} + +func TestEstimateAPICostRequiresPublishedCacheWriteRate(t *testing.T) { + usage := BenchmarkUsage{InputTokens: 1_000, CacheWriteInputTokens: 100, OutputTokens: 50} + if _, ok := estimateAPICost("gpt-5.5", usage); ok { + t.Fatal("model with no published cache-write rate received a guessed price") + } + usage.CacheWriteInputTokens = 0 + cost, ok := estimateAPICost("gpt-5.5", usage) + if !ok { + t.Fatal("published GPT-5.5 rates were not used") + } + want := (1_000*5.00 + 50*30.00) / 1_000_000 + if cost != want { + t.Fatalf("cost = %.8f, want %.8f", cost, want) + } +} + +func TestFormatIntervalsAndReferenceMerge(t *testing.T) { + input := []interval{{5, 7}, {1, 3}, {2, 4}, {10, 10}, {8, 9}} + got := mergeIntervals(input) + if formatted := formatIntervals(got); formatted != "[[1,10]]" { + t.Fatalf("merge result = %s", formatted) + } + if input[0] != (interval{5, 7}) { + t.Fatal("reference merge mutated input") + } +} diff --git a/internal/codex/client.go b/internal/codex/client.go index 472a2136..6127effc 100644 --- a/internal/codex/client.go +++ b/internal/codex/client.go @@ -33,7 +33,7 @@ func (c Client) FetchTokenUsage(ctx context.Context) (LiveUsageSnapshot, error) } // FetchTokenUsageFresh forces complete local rollout discovery for a final -// Stopwatch reading. +// Monitor reading. func (c Client) FetchTokenUsageFresh(ctx context.Context) (LiveUsageSnapshot, error) { if c.LiveUsage == nil { return LiveUsageSnapshot{}, errors.New("local Codex session telemetry is not configured") diff --git a/internal/codex/live_usage.go b/internal/codex/live_usage.go index 8136c324..370ac671 100644 --- a/internal/codex/live_usage.go +++ b/internal/codex/live_usage.go @@ -96,7 +96,7 @@ func (r *LiveUsageReader) FetchTokenUsage(ctx context.Context) (LiveUsageSnapsho } // FetchTokenUsageFresh forces a complete session discovery before consuming -// telemetry. The Stopwatch uses this for its final Stop reading so a recently +// telemetry. The Monitor uses this for its final Stop 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) diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go new file mode 100644 index 00000000..332a7f44 --- /dev/null +++ b/internal/ui/benchmark.go @@ -0,0 +1,565 @@ +package ui + +import ( + "fmt" + "slices" + "sort" + "strings" + "time" + + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + + "github.com/merefield/codexometer/internal/codex" +) + +type benchmarkGeometry struct { + width int + height int + topHeight int + tableHeight int + controlsWidth int + statusWidth int +} + +type benchmarkSortColumn int + +const ( + benchmarkSortNone benchmarkSortColumn = iota + benchmarkSortModel + benchmarkSortEffort + benchmarkSortTask + benchmarkSortResult + benchmarkSortTime + benchmarkSortTokens + benchmarkSortCost +) + +type benchmarkColumn struct { + sort benchmarkSortColumn + title string + x int + width int +} + +type benchmarkControlSegment struct { + text string + button footerButtonID + enabled bool + active bool +} + +func layoutBenchmarkArea(width, height int) benchmarkGeometry { + width = max(width, 1) + height = max(height, 1) + topHeight := min(max(height/3, 7), 9) + if height < 8 { + topHeight = max(height/2, 2) + } + controlsWidth := min(max(width*3/5, 38), max(width-1, 1)) + return benchmarkGeometry{ + width: width, height: height, topHeight: topHeight, + tableHeight: max(height-topHeight-1, 1), + controlsWidth: controlsWidth, statusWidth: max(width-controlsWidth-1, 1), + } +} + +func (m Model) renderBenchmarkArea(width, height int, colors palette) string { + layout := layoutBenchmarkArea(width, height) + controls := m.renderBenchmarkControls(layout.controlsWidth, layout.topHeight, colors) + status := m.renderBenchmarkStatus(layout.statusWidth, layout.topHeight, colors) + top := lipgloss.JoinHorizontal(lipgloss.Top, controls, " ", status) + table := m.renderBenchmarkTable(width, layout.tableHeight, colors) + view := lipgloss.JoinVertical(lipgloss.Left, top, table) + if padding := height - lipgloss.Height(view); padding > 0 { + view += strings.Repeat("\n", padding) + } + return view +} + +func (m Model) renderBenchmarkControls(width, height int, colors palette) string { + innerWidth := max(width-4, 1) + lines := make([]string, 0, 3) + for _, segments := range m.benchmarkControlLines(innerWidth) { + parts := make([]string, 0, len(segments)) + used := 0 + for _, segment := range segments { + style := colors.dimmed() + if segment.button == footerButtonNone { + style = lipgloss.NewStyle().Foreground(colors.primary) + } else if segment.enabled { + style = lipgloss.NewStyle().Foreground(colors.primary) + if m.hoveredButton == segment.button { + style = style.Bold(true).Foreground(colors.accent) + } + if m.flashedButton == segment.button { + style = style.Bold(true).Foreground(colors.background).Background(colors.primary) + } + } + if segment.active { + style = lipgloss.NewStyle().Bold(true).Foreground(colors.background).Background(colors.primary) + } + parts = append(parts, style.Render(segment.text)) + used += lipgloss.Width(segment.text) + } + if len(parts) > 1 { + used += len(parts) - 1 + } + lines = append(lines, strings.Join(parts, " ")+strings.Repeat(" ", max(innerWidth-used, 0))) + } + return frameSized(width, max(height-2, 1), "BENCHMARK CONTROLS", strings.Join(lines, "\n"), colors.primary, colors) +} + +func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { + tasks := codex.BenchmarkTasks() + selected := codex.BenchmarkTask{Name: "NO TASKS"} + if len(tasks) > 0 { + selected = tasks[m.benchmarkSelectedTask%len(tasks)] + } + running := m.benchmarkState == benchmarkRunning + selectorMiddleWidth := max(width-10, 1) + selector := []benchmarkControlSegment{ + {text: "[◀]", button: footerButtonBenchmarkPrevious, enabled: !running}, + {text: ansi.Truncate("TASK // "+selected.Name, selectorMiddleWidth, ""), enabled: true}, + {text: "[▶]", button: footerButtonBenchmarkNext, enabled: !running}, + } + + selectedLabel := "[ (B) RUN SELECTED ]" + allTurns := m.benchmarkCombinations * len(tasks) + allLabel := fmt.Sprintf("[ (A) RUN ALL // %d ]", allTurns) + if m.benchmarkPlanning { + allLabel = "[ DISCOVERING TURNS… ]" + } + if m.benchmarkAllArmed { + allLabel = fmt.Sprintf("[ CONFIRM // %d TURNS ]", allTurns) + } + if lipgloss.Width(selectedLabel)+lipgloss.Width(allLabel)+1 > width { + selectedLabel = "[B:RUN]" + allLabel = fmt.Sprintf("[A:ALL %d]", allTurns) + if m.benchmarkPlanning { + allLabel = "[A:WAIT]" + } + if m.benchmarkAllArmed { + allLabel = fmt.Sprintf("[A:CONFIRM %d]", allTurns) + } + } + run := []benchmarkControlSegment{ + {text: selectedLabel, button: footerButtonBenchmarkSelected, enabled: !running && len(tasks) > 0}, + {text: allLabel, button: footerButtonBenchmarkAll, enabled: !running && m.benchmarkCombinations > 0}, + } + filter := []benchmarkControlSegment{ + {text: "SHOW //", enabled: true}, + {text: "[ ALL ]", button: footerButtonBenchmarkFilterAll, enabled: true, active: m.benchmarkFilter == benchmarkFilterAll}, + {text: "[ PASS ]", button: footerButtonBenchmarkFilterPass, enabled: true, active: m.benchmarkFilter == benchmarkFilterPass}, + {text: "[ FAIL ]", button: footerButtonBenchmarkFilterFail, enabled: true, active: m.benchmarkFilter == benchmarkFilterFail}, + } + return [][]benchmarkControlSegment{selector, run, filter} +} + +func (m Model) renderBenchmarkStatus(width, height int, colors palette) string { + state := "READY" + detail := "USES QUOTA // EVERY VISIBLE MODEL + EFFORT" + color := colors.primary + switch m.benchmarkState { + case benchmarkRunning: + state = fmt.Sprintf("RUNNING %d/%d", m.benchmarkCompleted, m.benchmarkTotal) + if m.benchmarkTotal == 0 { + state = "DISCOVERING MODELS" + } + detail = strings.TrimSpace(m.benchmarkCurrentTask + " // " + m.benchmarkCurrentModel + " // " + strings.ToUpper(m.benchmarkCurrentEffort)) + if detail == "//" || detail == "" { + detail = "QUERYING LOCAL CODEX APP-SERVER" + } + color = colors.accent + case benchmarkFinished: + passed := benchmarkPassCount(m.benchmarkResults) + state = fmt.Sprintf("COMPLETE // %d/%d PASS", passed, len(m.benchmarkResults)) + detail = "PRESS B OR CLICK TO RUN AGAIN" + if failure := latestBenchmarkFailure(m.benchmarkResults); failure != "" { + detail = "LAST FAIL // " + failure + } + if m.benchmarkError != "" { + state = "BENCHMARK FAULT" + detail = m.benchmarkError + color = colors.danger + } + } + if m.benchmarkError != "" && m.benchmarkState != benchmarkRunning { + state = "BENCHMARK FAULT" + detail = m.benchmarkError + color = colors.danger + } + lines := []string{ + lipgloss.NewStyle().Bold(true).Foreground(color).Render(ansi.Truncate(state, max(width-4, 1), "")), + colors.dimmed().Render(ansi.Truncate(detail, max(width-4, 1), "")), + } + if height >= 6 { + lines = append(lines, colors.dimmed().Render(ansi.Truncate("HERMETIC STARLARK // 250K STEP LIMIT", max(width-4, 1), ""))) + } + return frameSized(width, max(height-2, 1), "ALGORITHM TRIAL", strings.Join(lines, "\n"), color, colors) +} + +func latestBenchmarkFailure(results []codex.BenchmarkResult) string { + for index := len(results) - 1; index >= 0; index-- { + if !results[index].Correct && results[index].Failure != "" { + return results[index].Failure + } + } + return "" +} + +func (m Model) renderBenchmarkTable(width, height int, colors palette) string { + innerWidth := max(width-4, 1) + bodyHeight := max(height-3, 1) + visibleResults := filterBenchmarkResults(m.benchmarkResults, m.benchmarkFilter) + columns := benchmarkTableColumns(innerWidth, m.benchmarkResults) + rows := benchmarkTableRows(columns, sortedBenchmarkResults(visibleResults, m.benchmarkSort, m.benchmarkSortDescending)) + lines := []string{m.renderBenchmarkHeader(columns, colors)} + if bodyHeight > 1 { + lines = append(lines, colors.dimmed().Render(strings.Repeat("─", innerWidth))) + } + available := max(bodyHeight-len(lines), 0) + if len(rows) > available && available >= 2 { + pageSize := available - 1 + maximumScroll := max(len(rows)-pageSize, 0) + scroll := min(max(m.benchmarkScroll, 0), maximumScroll) + end := len(rows) - scroll + start := max(end-pageSize, 0) + lines = append(lines, colors.dimmed().Render(fitTableCell( + fmt.Sprintf("ROWS %d-%d/%d // PGUP PGDN // MOUSE WHEEL", start+1, end, len(rows)), innerWidth, + ))) + rows = rows[start:end] + } else if len(rows) > available { + rows = rows[len(rows)-available:] + } + for _, row := range rows { + style := colors.dimmed() + if row.pass { + style = lipgloss.NewStyle().Foreground(colors.primary) + } else { + style = lipgloss.NewStyle().Foreground(colors.danger) + } + lines = append(lines, style.Render(row.text)) + } + if len(visibleResults) == 0 && len(lines) < bodyHeight { + message := "RUN SELECTED OR RUN ALL TO BEGIN // THIS CONSUMES CODEX QUOTA" + if m.benchmarkState == benchmarkRunning { + message = "WAITING FOR FIRST RESULT" + } else if len(m.benchmarkResults) > 0 { + message = "NO RESULTS MATCH THE ACTIVE FILTER" + } + lines = append(lines, colors.dimmed().Render(fitTableCell(message, innerWidth))) + } + for len(lines) < bodyHeight { + lines = append(lines, strings.Repeat(" ", innerWidth)) + } + if len(lines) > bodyHeight { + lines = lines[:bodyHeight] + } + title := "RESULT MATRIX // STANDARD API-EQUIVALENT USD" + return frameSized(width, max(height-2, 1), ansi.Truncate(title, max(innerWidth-4, 1), ""), strings.Join(lines, "\n"), colors.primary, colors) +} + +type benchmarkTableRow struct { + text string + pass bool +} + +func benchmarkTableColumns(width int, results []codex.BenchmarkResult) []benchmarkColumn { + titles := []string{"MODEL", "EFFORT", "TASK", "RESULT", "TIME", "TOKENS", "API EQ"} + sorts := []benchmarkSortColumn{benchmarkSortModel, benchmarkSortEffort, benchmarkSortTask, benchmarkSortResult, benchmarkSortTime, benchmarkSortTokens, benchmarkSortCost} + widths := make([]int, len(titles)) + idealWidths := make([]int, len(titles)) + for index, title := range titles { + // Reserve brackets and a sort arrow even before this column is active. + widths[index] = lipgloss.Width(title) + 3 + idealWidths[index] = widths[index] + } + for _, result := range results { + for index, value := range benchmarkResultValues(result) { + idealWidths[index] = max(idealWidths[index], lipgloss.Width(value)) + } + } + + separatorWidth := len(widths) - 1 + cellBudget := max(width-separatorWidth, len(widths)) + for sumInts(widths) > cellBudget { + widest := -1 + for index, columnWidth := range widths { + if columnWidth > 1 && (widest < 0 || columnWidth > widths[widest]) { + widest = index + } + } + if widest < 0 { + break + } + widths[widest]-- + } + for sumInts(widths) < cellBudget { + grewTowardContent := false + for index := range widths { + if sumInts(widths) >= cellBudget { + break + } + if widths[index] < idealWidths[index] { + widths[index]++ + grewTowardContent = true + } + } + if !grewTowardContent { + break + } + } + for index := 0; sumInts(widths) < cellBudget; index++ { + widths[index%len(widths)]++ + } + + columns := make([]benchmarkColumn, 0, len(widths)) + x := 0 + for index := range widths { + columns = append(columns, benchmarkColumn{sort: sorts[index], title: titles[index], x: x, width: widths[index]}) + x += widths[index] + 1 + } + return columns +} + +func sumInts(values []int) int { + total := 0 + for _, value := range values { + total += value + } + return total +} + +func formatBenchmarkColumns(columns []benchmarkColumn, values ...string) string { + parts := make([]string, 0, len(columns)) + for index, column := range columns { + value := "" + if index < len(values) { + value = values[index] + } + parts = append(parts, fitTableCell(value, column.width)) + } + return strings.Join(parts, " ") +} + +func (m Model) renderBenchmarkHeader(columns []benchmarkColumn, colors palette) string { + parts := make([]string, 0, len(columns)) + for _, column := range columns { + label := column.title + if m.benchmarkSort == column.sort { + if m.benchmarkSortDescending { + label += "▼" + } else { + label += "▲" + } + } + label = "[" + label + "]" + style := lipgloss.NewStyle().Foreground(colors.primary).Background(colors.background) + if m.benchmarkSortHovered && m.benchmarkHoveredSort == column.sort { + style = style.Bold(true).Foreground(colors.accent) + } + if m.benchmarkSort == column.sort { + style = style.Bold(true).Foreground(colors.background).Background(colors.primary) + } + parts = append(parts, style.Render(fitTableCell(label, column.width))) + } + return strings.Join(parts, colors.dimmed().Render(" ")) +} + +func benchmarkTableRows(columns []benchmarkColumn, results []codex.BenchmarkResult) []benchmarkTableRow { + rows := make([]benchmarkTableRow, 0, len(results)) + for _, result := range results { + rows = append(rows, benchmarkTableRow{ + text: formatBenchmarkColumns(columns, benchmarkResultValues(result)...), + pass: result.Correct, + }) + } + return rows +} + +func benchmarkResultValues(result codex.BenchmarkResult) []string { + outcome := "FAIL" + if result.Correct { + outcome = "PASS" + } + cost := "N/A" + if result.CostKnown { + cost = fmt.Sprintf("~$%.4f", result.CostUSD) + } + model := result.DisplayName + if result.ActualModel != "" && result.ActualModel != result.Model { + model += "→" + result.ActualModel + } + return []string{ + model, + strings.ToUpper(result.Effort), + result.TaskName, + outcome, + formatBenchmarkDuration(result.Duration), + formatCompactTokens(result.Usage.TotalTokens), + cost, + } +} + +func sortedBenchmarkResults(results []codex.BenchmarkResult, column benchmarkSortColumn, descending bool) []codex.BenchmarkResult { + ordered := slices.Clone(results) + if column == benchmarkSortNone { + return ordered + } + sort.SliceStable(ordered, func(left, right int) bool { + if column == benchmarkSortCost && ordered[left].CostKnown != ordered[right].CostKnown { + return ordered[left].CostKnown + } + comparison := compareBenchmarkResults(ordered[left], ordered[right], column) + if descending { + return comparison > 0 + } + return comparison < 0 + }) + return ordered +} + +func compareBenchmarkResults(left, right codex.BenchmarkResult, column benchmarkSortColumn) int { + switch column { + case benchmarkSortModel: + return strings.Compare(strings.ToLower(left.DisplayName), strings.ToLower(right.DisplayName)) + case benchmarkSortEffort: + return compareInt(benchmarkEffortRank(left.Effort), benchmarkEffortRank(right.Effort)) + case benchmarkSortTask: + return strings.Compare(strings.ToLower(left.TaskName), strings.ToLower(right.TaskName)) + case benchmarkSortResult: + return compareInt(boolInt(left.Correct), boolInt(right.Correct)) + case benchmarkSortTime: + return compareInt64(int64(left.Duration), int64(right.Duration)) + case benchmarkSortTokens: + return compareInt64(left.Usage.TotalTokens, right.Usage.TotalTokens) + case benchmarkSortCost: + if left.CostUSD < right.CostUSD { + return -1 + } + if left.CostUSD > right.CostUSD { + return 1 + } + } + return 0 +} + +func benchmarkEffortRank(effort string) int { + for index, name := range []string{"none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"} { + if strings.EqualFold(effort, name) { + return index + } + } + return 100 +} + +func compareInt(left, right int) int { + if left < right { + return -1 + } + if left > right { + return 1 + } + return 0 +} + +func compareInt64(left, right int64) int { + if left < right { + return -1 + } + if left > right { + return 1 + } + return 0 +} + +func boolInt(value bool) int { + if value { + return 1 + } + return 0 +} + +func filterBenchmarkResults(results []codex.BenchmarkResult, filter benchmarkResultFilter) []codex.BenchmarkResult { + if filter == benchmarkFilterAll { + return slices.Clone(results) + } + filtered := make([]codex.BenchmarkResult, 0, len(results)) + for _, result := range results { + if (filter == benchmarkFilterPass && result.Correct) || (filter == benchmarkFilterFail && !result.Correct) { + filtered = append(filtered, result) + } + } + return filtered +} + +func fitTableCell(value string, width int) string { + value = ansi.Truncate(value, max(width, 0), "") + return value + strings.Repeat(" ", max(width-lipgloss.Width(value), 0)) +} + +func formatBenchmarkDuration(duration time.Duration) string { + if duration < 0 { + duration = 0 + } + if duration < time.Minute { + return fmt.Sprintf("%.1fs", duration.Seconds()) + } + return fmt.Sprintf("%dm%02ds", int(duration/time.Minute), int(duration/time.Second)%60) +} + +func benchmarkPassCount(results []codex.BenchmarkResult) int { + passed := 0 + for _, result := range results { + if result.Correct { + passed++ + } + } + return passed +} + +func (m Model) benchmarkButtonAt(x, y int) footerButtonID { + if m.loading && len(m.snapshot.Meters()) == 0 { + return footerButtonNone + } + dashboard := m.dashboardLayout() + layout := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) + localX, localY := x-2, y-dashboard.meterY + if localX < 0 || localX >= layout.controlsWidth { + return footerButtonNone + } + for line, segments := range m.benchmarkControlLines(max(layout.controlsWidth-4, 1)) { + if localY != line+2 { + continue + } + segmentX := 2 + for _, segment := range segments { + segmentWidth := lipgloss.Width(segment.text) + if segment.button != footerButtonNone && segment.enabled && localX >= segmentX && localX < segmentX+segmentWidth { + return segment.button + } + segmentX += segmentWidth + 1 + } + } + return footerButtonNone +} + +func (m Model) benchmarkHeaderAt(x, y int) (benchmarkSortColumn, bool) { + if m.meterStyle != styleBenchmark || x < 0 || y < 0 { + return benchmarkSortNone, false + } + dashboard := m.dashboardLayout() + geometry := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) + tableY := dashboard.meterY + geometry.topHeight + if y != tableY+2 { + return benchmarkSortNone, false + } + localX := x - 4 + for _, column := range benchmarkTableColumns(max(dashboard.contentWidth-4, 1), m.benchmarkResults) { + if localX >= column.x && localX < column.x+column.width { + return column.sort, true + } + } + return benchmarkSortNone, false +} diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go new file mode 100644 index 00000000..b658c35b --- /dev/null +++ b/internal/ui/benchmark_test.go @@ -0,0 +1,368 @@ +package ui + +import ( + "context" + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + + "github.com/merefield/codexometer/internal/codex" +) + +type benchmarkStubFetcher struct { + stubFetcher + results []codex.BenchmarkResult +} + +func (f benchmarkStubFetcher) BenchmarkCombinationCount(context.Context) (int, error) { return 2, nil } + +func (f benchmarkStubFetcher) RunBenchmarkSuite(ctx context.Context, tasks []codex.BenchmarkTaskID, emit func(codex.BenchmarkEvent)) { + emit(codex.BenchmarkEvent{Total: len(f.results), Combinations: 2}) + for index := range f.results { + select { + case <-ctx.Done(): + emit(codex.BenchmarkEvent{Done: true, Err: ctx.Err()}) + return + default: + } + result := f.results[index] + if len(tasks) > 0 && result.TaskID == "" { + result.TaskID, result.TaskName = tasks[0], "MERGE RANGES" + } + emit(codex.BenchmarkEvent{ + Total: len(f.results), Completed: index + 1, Combinations: 2, + CurrentTaskID: result.TaskID, CurrentTask: result.TaskName, + CurrentModel: result.DisplayName, CurrentEffort: result.Effort, Result: &result, + }) + } + emit(codex.BenchmarkEvent{Total: len(f.results), Completed: len(f.results), Done: true}) +} + +func TestBenchmarkViewRendersResponsiveResultsTable(t *testing.T) { + model := Model{ + width: 100, height: 30, meterStyle: styleBenchmark, + benchmarkState: benchmarkFinished, + benchmarkResults: []codex.BenchmarkResult{ + {TaskName: "MERGE RANGES", Model: "gpt-5.6-sol", DisplayName: "GPT-5.6 Sol", Effort: "high", Correct: true, Duration: 12500 * time.Millisecond, Usage: codex.BenchmarkUsage{TotalTokens: 4321}, CostKnown: true, CostUSD: 0.0412}, + {TaskName: "LRU CACHE", Model: "future", DisplayName: "Future Model", Effort: "low", Correct: false, Duration: 2 * time.Minute, Usage: codex.BenchmarkUsage{TotalTokens: 999}, Failure: "wrong result"}, + }, + } + output := ansi.Strip(model.renderBenchmarkArea(96, 19, paletteFor(themeHacker))) + for _, want := range []string{"(B) RUN SELECTED", "MERGE RANGES", "SHOW //", "1/2 PASS", "PASS", "FAIL", "4.3K", "~$0.0412", "N/A"} { + if !strings.Contains(output, want) { + t.Fatalf("benchmark view missing %q:\n%s", want, output) + } + } + if got := lipgloss.Width(output); got != 96 { + t.Fatalf("benchmark width = %d, want 96", got) + } + if got := lipgloss.Height(output); got != 19 { + t.Fatalf("benchmark height = %d, want 19", got) + } +} + +func TestBenchmarkHotkeyRunsSuiteAndCollectsEvents(t *testing.T) { + result := codex.BenchmarkResult{Model: "model", DisplayName: "Model", Effort: "medium", Correct: true} + fetcher := benchmarkStubFetcher{ + stubFetcher: stubFetcher{snapshot: codex.DemoSnapshot()}, + results: []codex.BenchmarkResult{result}, + } + model := New(fetcher, time.Minute) + model.snapshot = codex.DemoSnapshot() + model.loading = false + model.meterStyle = styleBenchmark + + updated, command := model.Update(key('b')) + model = updated.(Model) + if model.benchmarkState != benchmarkRunning || command == nil || model.flashedButton != footerButtonBenchmarkSelected { + t.Fatalf("benchmark did not start: state=%d command=%v", model.benchmarkState, command != nil) + } + + rawCommandMessage := command() + batch, ok := rawCommandMessage.(tea.BatchMsg) + if !ok { + t.Fatalf("hotkey command returned %T, want tea.BatchMsg", rawCommandMessage) + } + var message benchmarkEventMsg + found := false + for _, child := range batch { + if candidate, ok := child().(benchmarkEventMsg); ok { + message, found = candidate, true + break + } + } + if !found { + t.Fatal("hotkey batch did not contain benchmark launch command") + } + for model.benchmarkState == benchmarkRunning { + updated, command = model.Update(message) + model = updated.(Model) + if model.benchmarkState == benchmarkRunning { + message = command().(benchmarkEventMsg) + } + } + if len(model.benchmarkResults) != 1 || !model.benchmarkResults[0].Correct || model.benchmarkCompleted != 1 { + t.Fatalf("benchmark results not collected: %#v", model.benchmarkResults) + } +} + +func TestBenchmarkButtonSupportsHoverAndClick(t *testing.T) { + model := New(benchmarkStubFetcher{stubFetcher: stubFetcher{snapshot: codex.DemoSnapshot()}}, time.Minute) + model.snapshot = codex.DemoSnapshot() + model.loading = false + model.width, model.height = 100, 30 + model.meterStyle = styleBenchmark + x, y := benchmarkControlCoordinates(t, model, footerButtonBenchmarkSelected) + mouse := tea.MouseMsg{X: x, Y: y, Action: tea.MouseActionMotion} + updated, command := model.Update(mouse) + model = updated.(Model) + if command != nil || model.hoveredButton != footerButtonBenchmarkSelected { + t.Fatal("benchmark button hover was not recorded") + } + mouse.Action = tea.MouseActionPress + mouse.Button = tea.MouseButtonLeft + updated, command = model.Update(mouse) + model = updated.(Model) + if command == nil || model.benchmarkState != benchmarkRunning { + t.Fatal("benchmark button click did not start suite") + } +} + +func TestBenchmarkTableClipsOlderRows(t *testing.T) { + model := Model{benchmarkState: benchmarkFinished} + for index := 0; index < 20; index++ { + model.benchmarkResults = append(model.benchmarkResults, codex.BenchmarkResult{ + Model: "model", DisplayName: "Model", Effort: "low", Correct: index%2 == 0, + }) + } + output := ansi.Strip(model.renderBenchmarkTable(70, 8, paletteFor(themeBlueSteel))) + if !strings.Contains(output, "ROWS 19-20/20") || lipgloss.Height(output) != 8 { + t.Fatalf("clipped table is invalid:\n%s", output) + } + model.benchmarkScroll = 4 + output = ansi.Strip(model.renderBenchmarkTable(70, 8, paletteFor(themeBlueSteel))) + if !strings.Contains(output, "ROWS 15-16/20") { + t.Fatalf("scrolled table did not expose older rows:\n%s", output) + } +} + +func TestBenchmarkPageKeysAndMouseWheelScrollResults(t *testing.T) { + model := Model{width: 90, height: 28, meterStyle: styleBenchmark, benchmarkState: benchmarkFinished} + for index := 0; index < 30; index++ { + model.benchmarkResults = append(model.benchmarkResults, codex.BenchmarkResult{DisplayName: "Model", Effort: "low"}) + } + updated, command := model.Update(tea.KeyMsg{Type: tea.KeyPgUp}) + model = updated.(Model) + if command != nil || model.benchmarkScroll == 0 { + t.Fatalf("Page Up did not scroll: offset=%d command=%v", model.benchmarkScroll, command != nil) + } + updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyPgDown}) + model = updated.(Model) + if model.benchmarkScroll != 0 { + t.Fatalf("Page Down offset = %d, want 0", model.benchmarkScroll) + } + updated, _ = model.Update(tea.MouseMsg{Button: tea.MouseButtonWheelUp}) + model = updated.(Model) + if model.benchmarkScroll != 3 { + t.Fatalf("mouse-wheel offset = %d, want 3", model.benchmarkScroll) + } +} + +func TestBenchmarkHeadingButtonsSortAndReverse(t *testing.T) { + model := Model{ + width: 100, height: 30, meterStyle: styleBenchmark, benchmarkState: benchmarkFinished, + benchmarkResults: []codex.BenchmarkResult{ + {DisplayName: "Zulu", Effort: "low", Duration: 2 * time.Second, Usage: codex.BenchmarkUsage{TotalTokens: 200}}, + {DisplayName: "Alpha", Effort: "high", Correct: true, Duration: time.Second, Usage: codex.BenchmarkUsage{TotalTokens: 100}}, + }, + } + dashboard := model.dashboardLayout() + geometry := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) + columns := benchmarkTableColumns(max(dashboard.contentWidth-4, 1), model.benchmarkResults) + mouse := tea.MouseMsg{ + X: 4 + columns[0].x + 1, + Y: dashboard.meterY + geometry.topHeight + 2, + Action: tea.MouseActionMotion, + } + updated, command := model.Update(mouse) + model = updated.(Model) + if command != nil || !model.benchmarkSortHovered || model.benchmarkHoveredSort != benchmarkSortModel { + t.Fatal("model heading did not highlight on hover") + } + mouse.Button, mouse.Action = tea.MouseButtonLeft, tea.MouseActionPress + updated, command = model.Update(mouse) + model = updated.(Model) + if command != nil || model.benchmarkSort != benchmarkSortModel || model.benchmarkSortDescending { + t.Fatalf("first heading click did not select ascending model sort: %#v", model) + } + ordered := sortedBenchmarkResults(model.benchmarkResults, model.benchmarkSort, model.benchmarkSortDescending) + if ordered[0].DisplayName != "Alpha" { + t.Fatalf("ascending model order = %q first, want Alpha", ordered[0].DisplayName) + } + updated, _ = model.Update(mouse) + model = updated.(Model) + ordered = sortedBenchmarkResults(model.benchmarkResults, model.benchmarkSort, model.benchmarkSortDescending) + if !model.benchmarkSortDescending || ordered[0].DisplayName != "Zulu" { + t.Fatalf("second heading click did not reverse model sort: descending=%v first=%q", model.benchmarkSortDescending, ordered[0].DisplayName) + } + view := ansi.Strip(model.renderBenchmarkTable(dashboard.contentWidth, geometry.tableHeight, paletteFor(themeHacker))) + if !strings.Contains(view, "[MODEL▼]") || !strings.Contains(view, "[EFFORT]") { + t.Fatalf("heading buttons or sort direction missing:\n%s", view) + } +} + +func TestBenchmarkSortUsesReasoningOrderAndMetrics(t *testing.T) { + results := []codex.BenchmarkResult{ + {DisplayName: "B", Effort: "xhigh", TaskName: "SHORTEST PATH", Duration: 3 * time.Second, Usage: codex.BenchmarkUsage{TotalTokens: 300}, CostKnown: true, CostUSD: 0.3}, + {DisplayName: "A", Effort: "low", TaskName: "LRU CACHE", Correct: true, Duration: time.Second, Usage: codex.BenchmarkUsage{TotalTokens: 100}, CostKnown: true, CostUSD: 0.1}, + {DisplayName: "C", Effort: "medium", TaskName: "MERGE RANGES", Duration: 2 * time.Second, Usage: codex.BenchmarkUsage{TotalTokens: 200}}, + } + checks := []struct { + column benchmarkSortColumn + want string + }{ + {benchmarkSortEffort, "A"}, + {benchmarkSortTask, "A"}, + {benchmarkSortResult, "B"}, + {benchmarkSortTime, "A"}, + {benchmarkSortTokens, "A"}, + {benchmarkSortCost, "A"}, + } + for _, check := range checks { + ordered := sortedBenchmarkResults(results, check.column, false) + if ordered[0].DisplayName != check.want { + t.Errorf("column %d sorted %q first, want %q", check.column, ordered[0].DisplayName, check.want) + } + } + ordered := sortedBenchmarkResults(results, benchmarkSortCost, true) + if !ordered[0].CostKnown || ordered[len(ordered)-1].CostKnown { + t.Fatal("descending cost sort did not leave N/A values last") + } +} + +func TestBenchmarkColumnsRespondToHeadingsValuesAndAvailableWidth(t *testing.T) { + results := []codex.BenchmarkResult{{ + Model: "gpt-5.6-luna", DisplayName: "GPT-5.6 Luna", Effort: "ultra", TaskName: "SHORTEST PATH", + Correct: true, Duration: 12*time.Minute + 34*time.Second, + Usage: codex.BenchmarkUsage{TotalTokens: 12_345_678}, CostKnown: true, CostUSD: 12345.6789, + }} + columns := benchmarkTableColumns(96, results) + if len(columns) != 7 { + t.Fatalf("column count = %d, want 7", len(columns)) + } + used := len(columns) - 1 + for _, column := range columns { + used += column.width + minimumHeadingWidth := lipgloss.Width(column.title) + 3 + if column.width < minimumHeadingWidth { + t.Errorf("%s width = %d, want at least %d for brackets and sort arrow", column.title, column.width, minimumHeadingWidth) + } + } + if used != 96 { + t.Fatalf("responsive columns use %d cells, want 96", used) + } + if columns[0].width > 24 { + t.Fatalf("model column consumed %d cells despite short model values", columns[0].width) + } + values := benchmarkResultValues(results[0]) + for index, value := range values { + if lipgloss.Width(value) > columns[index].width { + t.Errorf("column %s width %d truncates value %q despite ample space", columns[index].title, columns[index].width, value) + } + } + + model := Model{benchmarkResults: results, benchmarkSort: benchmarkSortResult} + header := ansi.Strip(model.renderBenchmarkHeader(columns, paletteFor(themeHacker))) + if !strings.Contains(header, "[RESULT▲]") || !strings.Contains(header, "[MODEL]") { + t.Fatalf("full headings were truncated despite ample space: %q", header) + } + + narrow := benchmarkTableColumns(42, results) + used = len(narrow) - 1 + for _, column := range narrow { + used += column.width + } + if used != 42 { + t.Fatalf("narrow columns use %d cells, want 42", used) + } +} + +func TestBenchmarkTaskSelectorRunAllGuardAndExactTurnCount(t *testing.T) { + model := New(benchmarkStubFetcher{stubFetcher: stubFetcher{snapshot: codex.DemoSnapshot()}}, time.Minute) + model.snapshot = codex.DemoSnapshot() + model.loading = false + model.width, model.height = 100, 30 + model.meterStyle = styleBenchmark + model.benchmarkCombinations = 33 + + updated, _ := model.Update(tea.KeyMsg{Type: tea.KeyRight}) + model = updated.(Model) + if model.benchmarkSelectedTask != 1 { + t.Fatalf("right arrow selected task %d, want 1", model.benchmarkSelectedTask) + } + controls := ansi.Strip(model.renderBenchmarkControls(60, 8, paletteFor(themeHacker))) + if !strings.Contains(controls, "LRU CACHE") || !strings.Contains(controls, "132") { + t.Fatalf("selector or exact all-turn count missing:\n%s", controls) + } + + updated, command := model.Update(key('a')) + model = updated.(Model) + if !model.benchmarkAllArmed || model.benchmarkState == benchmarkRunning || command == nil { + t.Fatal("first Run All press did not arm confirmation without running") + } + controls = ansi.Strip(model.renderBenchmarkControls(60, 8, paletteFor(themeHacker))) + if !strings.Contains(controls, "CONFIRM") || !strings.Contains(controls, "132") { + t.Fatalf("confirmation label missing exact turn count:\n%s", controls) + } + updated, command = model.Update(key('a')) + model = updated.(Model) + if model.benchmarkAllArmed || model.benchmarkState != benchmarkRunning || command == nil { + t.Fatal("second Run All press did not launch the suite") + } +} + +func TestBenchmarkPassFailFilterButtonsAndHotkey(t *testing.T) { + model := Model{ + width: 100, height: 30, meterStyle: styleBenchmark, benchmarkState: benchmarkFinished, + benchmarkResults: []codex.BenchmarkResult{ + {DisplayName: "Passing", TaskName: "LRU CACHE", Correct: true}, + {DisplayName: "Failing", TaskName: "SHORTEST PATH", Correct: false}, + }, + } + x, y := benchmarkControlCoordinates(t, model, footerButtonBenchmarkFilterFail) + updated, command := model.Update(tea.MouseMsg{X: x, Y: y, Button: tea.MouseButtonLeft, Action: tea.MouseActionPress}) + model = updated.(Model) + if command == nil || model.benchmarkFilter != benchmarkFilterFail { + t.Fatal("FAIL filter button did not activate") + } + visible := filterBenchmarkResults(model.benchmarkResults, model.benchmarkFilter) + if len(visible) != 1 || visible[0].DisplayName != "Failing" { + t.Fatalf("FAIL filter results = %#v", visible) + } + updated, _ = model.Update(key('f')) + model = updated.(Model) + if model.benchmarkFilter != benchmarkFilterAll { + t.Fatalf("filter hotkey cycled to %d, want ALL", model.benchmarkFilter) + } +} + +func benchmarkControlCoordinates(t *testing.T, model Model, target footerButtonID) (int, int) { + t.Helper() + dashboard := model.dashboardLayout() + geometry := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) + for line, segments := range model.benchmarkControlLines(max(geometry.controlsWidth-4, 1)) { + x := 4 + for _, segment := range segments { + if segment.button == target { + return x + max(lipgloss.Width(segment.text)/2, 0), dashboard.meterY + line + 2 + } + x += lipgloss.Width(segment.text) + 1 + } + } + t.Fatalf("benchmark control %d not found", target) + return 0, 0 +} diff --git a/internal/ui/model.go b/internal/ui/model.go index 24d961d4..d9b371f8 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -23,42 +23,70 @@ type FreshTokenUsageFetcher interface { FetchTokenUsageFresh(context.Context) (codex.LiveUsageSnapshot, error) } +type BenchmarkRunner interface { + BenchmarkCombinationCount(context.Context) (int, error) + RunBenchmarkSuite(context.Context, []codex.BenchmarkTaskID, func(codex.BenchmarkEvent)) +} + type Model struct { - fetcher Fetcher - usageFetcher TokenUsageFetcher - refreshEvery time.Duration - snapshot codex.Snapshot - err error - width int - height int - loading bool - lastRefresh time.Time - nextRefresh time.Time - phase int - theme themeID - meterStyle meterStyleID - hoveredStyle meterStyleID - styleHovered bool - flashedStyle meterStyleID - styleFlashing bool - styleSequence uint64 - hoveredButton footerButtonID - flashedButton footerButtonID - flashSequence uint64 - - stopwatchState stopwatchState - stopwatchStartedAt time.Time - stopwatchStoppedAt time.Time - stopwatchBaseline int64 - stopwatchLatest int64 - stopwatchSamples []stopwatchSample - stopwatchRequest uint64 - stopwatchFetchActive bool - stopwatchNextSample time.Time - stopwatchGraphStart int64 - stopwatchLastActivity time.Time - stopwatchSessions int - stopwatchError string + fetcher Fetcher + usageFetcher TokenUsageFetcher + refreshEvery time.Duration + snapshot codex.Snapshot + err error + width int + height int + loading bool + lastRefresh time.Time + nextRefresh time.Time + phase int + theme themeID + meterStyle meterStyleID + hoveredStyle meterStyleID + styleHovered bool + flashedStyle meterStyleID + styleFlashing bool + styleSequence uint64 + hoveredButton footerButtonID + flashedButton footerButtonID + flashSequence uint64 + benchmarkRunner BenchmarkRunner + + benchmarkState benchmarkState + benchmarkResults []codex.BenchmarkResult + benchmarkTotal int + benchmarkCompleted int + benchmarkCurrentModel string + benchmarkCurrentEffort string + benchmarkCurrentTask string + benchmarkError string + benchmarkPlanning bool + benchmarkCombinations int + benchmarkSelectedTask int + benchmarkFilter benchmarkResultFilter + benchmarkAllArmed bool + benchmarkConfirmSequence uint64 + benchmarkScroll int + benchmarkSort benchmarkSortColumn + benchmarkSortDescending bool + benchmarkSortHovered bool + benchmarkHoveredSort benchmarkSortColumn + benchmarkEvents <-chan codex.BenchmarkEvent + benchmarkCancel context.CancelFunc + + monitorState monitorState + monitorStartedAt time.Time + monitorStoppedAt time.Time + monitorBaseline int64 + monitorLatest int64 + monitorSamples []monitorSample + monitorRequest uint64 + monitorFetchActive bool + monitorNextSample time.Time + monitorGraphStart int64 + monitorLastActivity time.Time + monitorSessions int + monitorError string } type fetchedMsg struct { @@ -69,31 +97,31 @@ type fetchedMsg struct { type secondMsg time.Time type refreshMsg time.Time -type stopwatchState int +type monitorState int const ( - stopwatchIdle stopwatchState = iota - stopwatchStarting - stopwatchRunning - stopwatchStopping - stopwatchStopped + monitorIdle monitorState = iota + monitorStarting + monitorRunning + monitorStopping + monitorStopped ) -type stopwatchFetchKind int +type monitorFetchKind int const ( - stopwatchFetchStart stopwatchFetchKind = iota - stopwatchFetchSample - stopwatchFetchStop + monitorFetchStart monitorFetchKind = iota + monitorFetchSample + monitorFetchStop ) -type stopwatchSample struct { +type monitorSample struct { at time.Time intervalTokens int64 } -type stopwatchFetchedMsg struct { - kind stopwatchFetchKind +type monitorFetchedMsg struct { + kind monitorFetchKind sequence uint64 usage codex.LiveUsageSnapshot err error @@ -110,6 +138,37 @@ type styleTabFlashExpiredMsg struct { sequence uint64 } +type benchmarkState int + +const ( + benchmarkIdle benchmarkState = iota + benchmarkRunning + benchmarkFinished +) + +type benchmarkEventMsg struct { + event codex.BenchmarkEvent + events <-chan codex.BenchmarkEvent + ok bool +} + +type benchmarkPlanMsg struct { + combinations int + err error +} + +type benchmarkConfirmExpiredMsg struct { + sequence uint64 +} + +type benchmarkResultFilter int + +const ( + benchmarkFilterAll benchmarkResultFilter = iota + benchmarkFilterPass + benchmarkFilterFail +) + const footerButtonFlashDuration = 150 * time.Millisecond type footerButtonID int @@ -119,8 +178,15 @@ const ( footerButtonTheme footerButtonRefresh footerButtonQuit - footerButtonStopwatchGo - footerButtonStopwatchStop + footerButtonMonitorGo + footerButtonMonitorStop + footerButtonBenchmarkPrevious + footerButtonBenchmarkNext + footerButtonBenchmarkSelected + footerButtonBenchmarkAll + footerButtonBenchmarkFilterAll + footerButtonBenchmarkFilterPass + footerButtonBenchmarkFilterFail ) type footerButton struct { @@ -148,6 +214,9 @@ func New(fetcher Fetcher, refreshEvery time.Duration) Model { if usageFetcher, ok := fetcher.(TokenUsageFetcher); ok { model.usageFetcher = usageFetcher } + if runner, ok := fetcher.(BenchmarkRunner); ok { + model.benchmarkRunner = runner + } return model } @@ -160,12 +229,13 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { case tea.KeyMsg: switch strings.ToLower(message.String()) { case "ctrl+c", "esc": + m.cancelBenchmark() return m, tea.Quit case "t": return m.pressFooterButton(footerButtonTheme) case "s": - if m.meterStyle == styleStopwatch { - return m.pressFooterButton(footerButtonStopwatchGo) + if m.meterStyle == styleMonitor { + return m.pressFooterButton(footerButtonMonitorGo) } case "tab": return m.pressStyleTab(m.meterStyle.next()) @@ -175,9 +245,40 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { return m.pressFooterButton(footerButtonRefresh) case "q": return m.pressFooterButton(footerButtonQuit) + case "b": + if m.meterStyle == styleBenchmark { + return m.pressFooterButton(footerButtonBenchmarkSelected) + } + case "a": + if m.meterStyle == styleBenchmark { + return m.pressFooterButton(footerButtonBenchmarkAll) + } + case "left", "[": + if m.meterStyle == styleBenchmark { + return m.pressFooterButton(footerButtonBenchmarkPrevious) + } + case "right", "]": + if m.meterStyle == styleBenchmark { + return m.pressFooterButton(footerButtonBenchmarkNext) + } + case "f": + if m.meterStyle == styleBenchmark { + m.setBenchmarkFilter((m.benchmarkFilter + 1) % 3) + return m, nil + } + case "pgup": + if m.meterStyle == styleBenchmark { + m.scrollBenchmarkPage(1) + return m, nil + } + case "pgdown": + if m.meterStyle == styleBenchmark { + m.scrollBenchmarkPage(-1) + return m, nil + } case "p": - if m.meterStyle == styleStopwatch { - return m.pressFooterButton(footerButtonStopwatchStop) + if m.meterStyle == styleMonitor { + return m.pressFooterButton(footerButtonMonitorStop) } } case tea.MouseMsg: @@ -191,6 +292,26 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { return m, nil } m.styleHovered = false + if column, ok := m.benchmarkHeaderAt(message.X, message.Y); ok { + m.benchmarkSortHovered = true + m.benchmarkHoveredSort = column + m.hoveredButton = footerButtonNone + if message.Button == tea.MouseButtonLeft && message.Action == tea.MouseActionPress { + m.sortBenchmarkBy(column) + } + return m, nil + } + m.benchmarkSortHovered = false + if m.meterStyle == styleBenchmark { + switch message.Button { + case tea.MouseButtonWheelUp: + m.scrollBenchmarkRows(3) + return m, nil + case tea.MouseButtonWheelDown: + m.scrollBenchmarkRows(-3) + return m, nil + } + } button := m.footerButtonAt(message.X, message.Y) m.hoveredButton = button if message.Button == tea.MouseButtonLeft && message.Action == tea.MouseActionPress && button != footerButtonNone { @@ -209,20 +330,20 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { case secondMsg: m.phase++ commands := []tea.Cmd{secondTick()} - if m.stopwatchState == stopwatchRunning { + if m.monitorState == monitorRunning { now := time.Time(message) - if !m.stopwatchNextSample.IsZero() && !now.Before(m.stopwatchNextSample) { - delta := max(m.stopwatchLatest-m.stopwatchGraphStart, int64(0)) - m.stopwatchSamples = append(m.stopwatchSamples, stopwatchSample{at: now, intervalTokens: delta}) - m.stopwatchGraphStart = m.stopwatchLatest - for !m.stopwatchNextSample.After(now) { - m.stopwatchNextSample = m.stopwatchNextSample.Add(stopwatchSampleInterval) + if !m.monitorNextSample.IsZero() && !now.Before(m.monitorNextSample) { + delta := max(m.monitorLatest-m.monitorGraphStart, int64(0)) + m.monitorSamples = append(m.monitorSamples, monitorSample{at: now, intervalTokens: delta}) + m.monitorGraphStart = m.monitorLatest + for !m.monitorNextSample.After(now) { + m.monitorNextSample = m.monitorNextSample.Add(monitorSampleInterval) } } - if !m.stopwatchFetchActive { - m.stopwatchRequest++ - m.stopwatchFetchActive = true - commands = append(commands, m.stopwatchFetch(stopwatchFetchSample, m.stopwatchRequest)) + if !m.monitorFetchActive { + m.monitorRequest++ + m.monitorFetchActive = true + commands = append(commands, m.monitorFetch(monitorFetchSample, m.monitorRequest)) } } return m, tea.Batch(commands...) @@ -230,12 +351,12 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { m.loading = true m.nextRefresh = time.Now().Add(m.refreshEvery) return m, tea.Batch(m.fetch(), refreshTick(m.refreshEvery)) - case stopwatchFetchedMsg: - if message.sequence != m.stopwatchRequest { + case monitorFetchedMsg: + if message.sequence != m.monitorRequest { return m, nil } - m.stopwatchFetchActive = false - return m.applyStopwatchFetch(message) + m.monitorFetchActive = false + return m.applyMonitorFetch(message) case footerButtonFlashExpiredMsg: if message.sequence == m.flashSequence && message.button == m.flashedButton { m.flashedButton = footerButtonNone @@ -244,6 +365,50 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { if message.sequence == m.styleSequence && message.style == m.flashedStyle { m.styleFlashing = false } + case benchmarkEventMsg: + if !message.ok { + m.benchmarkState = benchmarkFinished + m.benchmarkEvents = nil + m.benchmarkCancel = nil + return m, nil + } + event := message.event + m.benchmarkTotal = event.Total + m.benchmarkCompleted = event.Completed + m.benchmarkCurrentModel = event.CurrentModel + m.benchmarkCurrentEffort = event.CurrentEffort + m.benchmarkCurrentTask = event.CurrentTask + if event.Combinations > 0 { + m.benchmarkCombinations = event.Combinations + } + if event.Result != nil { + if m.benchmarkScroll > 0 { + m.benchmarkScroll++ + } + m.benchmarkResults = append(m.benchmarkResults, *event.Result) + } + if event.Err != nil { + m.benchmarkError = event.Err.Error() + } + if event.Done { + m.benchmarkState = benchmarkFinished + m.benchmarkEvents = nil + m.benchmarkCancel = nil + return m, nil + } + return m, waitBenchmarkEvent(message.events) + case benchmarkPlanMsg: + m.benchmarkPlanning = false + if message.err != nil { + m.benchmarkError = message.err.Error() + } else { + m.benchmarkError = "" + m.benchmarkCombinations = message.combinations + } + case benchmarkConfirmExpiredMsg: + if message.sequence == m.benchmarkConfirmSequence { + m.benchmarkAllArmed = false + } } return m, nil } @@ -257,9 +422,14 @@ func (m Model) pressStyleTab(style meterStyleID) (tea.Model, tea.Cmd) { m.flashedStyle = style m.styleFlashing = true sequence := m.styleSequence - return m, tea.Tick(footerButtonFlashDuration, func(time.Time) tea.Msg { + commands := []tea.Cmd{tea.Tick(footerButtonFlashDuration, func(time.Time) tea.Msg { return styleTabFlashExpiredMsg{style: style, sequence: sequence} - }) + })} + if style == styleBenchmark && m.benchmarkRunner != nil && m.benchmarkCombinations == 0 && !m.benchmarkPlanning { + m.benchmarkPlanning = true + commands = append(commands, planBenchmark(m.benchmarkRunner)) + } + return m, tea.Batch(commands...) } func (m Model) pressFooterButton(button footerButtonID) (tea.Model, tea.Cmd) { @@ -267,6 +437,7 @@ func (m Model) pressFooterButton(button footerButtonID) (tea.Model, tea.Cmd) { m.flashedButton = button sequence := m.flashSequence if button == footerButtonQuit { + m.cancelBenchmark() return m, tea.Tick(footerButtonFlashDuration, func(time.Time) tea.Msg { return tea.Quit() }) } @@ -289,26 +460,64 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { m.loading = true return m, m.fetch() } - case footerButtonStopwatchGo: - if m.meterStyle == styleStopwatch && (m.stopwatchState == stopwatchIdle || m.stopwatchState == stopwatchStopped) { - m.stopwatchState = stopwatchStarting - m.stopwatchStartedAt = time.Time{} - m.stopwatchStoppedAt = time.Time{} - m.stopwatchSamples = nil - m.stopwatchLastActivity = time.Time{} - m.stopwatchSessions = 0 - m.stopwatchError = "" - m.stopwatchRequest++ - m.stopwatchFetchActive = true - return m, m.stopwatchFetch(stopwatchFetchStart, m.stopwatchRequest) - } - case footerButtonStopwatchStop: - if m.meterStyle == styleStopwatch && m.stopwatchState == stopwatchRunning { - m.stopwatchState = stopwatchStopping - m.stopwatchRequest++ - m.stopwatchFetchActive = true - return m, m.stopwatchFetch(stopwatchFetchStop, m.stopwatchRequest) + case footerButtonMonitorGo: + if m.meterStyle == styleMonitor && (m.monitorState == monitorIdle || m.monitorState == monitorStopped) { + m.monitorState = monitorStarting + m.monitorStartedAt = time.Time{} + m.monitorStoppedAt = time.Time{} + m.monitorSamples = nil + m.monitorLastActivity = time.Time{} + m.monitorSessions = 0 + m.monitorError = "" + m.monitorRequest++ + m.monitorFetchActive = true + return m, m.monitorFetch(monitorFetchStart, m.monitorRequest) + } + case footerButtonMonitorStop: + if m.meterStyle == styleMonitor && m.monitorState == monitorRunning { + m.monitorState = monitorStopping + m.monitorRequest++ + m.monitorFetchActive = true + return m, m.monitorFetch(monitorFetchStop, m.monitorRequest) } + case footerButtonBenchmarkPrevious: + if m.benchmarkState != benchmarkRunning { + m.selectBenchmarkTask(-1) + } + case footerButtonBenchmarkNext: + if m.benchmarkState != benchmarkRunning { + m.selectBenchmarkTask(1) + } + case footerButtonBenchmarkSelected: + if m.meterStyle == styleBenchmark && m.benchmarkState != benchmarkRunning { + m.benchmarkAllArmed = false + tasks := codex.BenchmarkTasks() + if len(tasks) > 0 { + return m.startBenchmark([]codex.BenchmarkTaskID{tasks[m.benchmarkSelectedTask%len(tasks)].ID}) + } + } + case footerButtonBenchmarkAll: + if m.meterStyle == styleBenchmark && m.benchmarkState != benchmarkRunning && m.benchmarkCombinations > 0 { + if !m.benchmarkAllArmed { + m.benchmarkAllArmed = true + m.benchmarkConfirmSequence++ + sequence := m.benchmarkConfirmSequence + return m, tea.Tick(5*time.Second, func(time.Time) tea.Msg { return benchmarkConfirmExpiredMsg{sequence: sequence} }) + } + m.benchmarkAllArmed = false + tasks := codex.BenchmarkTasks() + ids := make([]codex.BenchmarkTaskID, 0, len(tasks)) + for _, task := range tasks { + ids = append(ids, task.ID) + } + return m.startBenchmark(ids) + } + case footerButtonBenchmarkFilterAll: + m.setBenchmarkFilter(benchmarkFilterAll) + case footerButtonBenchmarkFilterPass: + m.setBenchmarkFilter(benchmarkFilterPass) + case footerButtonBenchmarkFilterFail: + m.setBenchmarkFilter(benchmarkFilterFail) } return m, nil } @@ -320,8 +529,13 @@ func (m Model) footerButtonAt(x, y int) footerButtonID { if m.loading && len(m.snapshot.Meters()) == 0 { return footerButtonNone } - if m.meterStyle == styleStopwatch { - if button := m.stopwatchButtonAt(x, y); button != footerButtonNone { + if m.meterStyle == styleMonitor { + if button := m.monitorButtonAt(x, y); button != footerButtonNone { + return button + } + } + if m.meterStyle == styleBenchmark { + if button := m.benchmarkButtonAt(x, y); button != footerButtonNone { return button } } @@ -379,7 +593,7 @@ func (m Model) dashboardLayout() dashboardGeometry { meterY := tabsY + tabsHeight + extraHeight meterHeight := max(contentHeight-headerHeight-statusHeight-tabsHeight-extraHeight-footerHeight, 1) footerY := meterY - if m.meterStyle == styleStopwatch || len(m.snapshot.Meters()) > 0 { + if m.meterStyle == styleMonitor || m.meterStyle == styleBenchmark || len(m.snapshot.Meters()) > 0 { footerY += meterHeight } return dashboardGeometry{ @@ -391,6 +605,107 @@ func (m Model) dashboardLayout() dashboardGeometry { } } +func launchBenchmark(ctx context.Context, runner BenchmarkRunner, tasks []codex.BenchmarkTaskID, events chan codex.BenchmarkEvent) tea.Cmd { + return func() tea.Msg { + go func() { + defer close(events) + runner.RunBenchmarkSuite(ctx, tasks, func(event codex.BenchmarkEvent) { + select { + case events <- event: + case <-ctx.Done(): + } + }) + }() + event, ok := <-events + return benchmarkEventMsg{event: event, events: events, ok: ok} + } +} + +func planBenchmark(runner BenchmarkRunner) tea.Cmd { + return func() tea.Msg { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + combinations, err := runner.BenchmarkCombinationCount(ctx) + return benchmarkPlanMsg{combinations: combinations, err: err} + } +} + +func waitBenchmarkEvent(events <-chan codex.BenchmarkEvent) tea.Cmd { + return func() tea.Msg { + event, ok := <-events + return benchmarkEventMsg{event: event, events: events, ok: ok} + } +} + +func (m *Model) cancelBenchmark() { + if m.benchmarkCancel != nil { + m.benchmarkCancel() + m.benchmarkCancel = nil + } +} + +func (m Model) startBenchmark(tasks []codex.BenchmarkTaskID) (Model, tea.Cmd) { + if m.benchmarkRunner == nil { + m.benchmarkState = benchmarkFinished + m.benchmarkError = "benchmark runner unavailable" + return m, nil + } + m.benchmarkResults = nil + m.benchmarkTotal = 0 + m.benchmarkCompleted = 0 + m.benchmarkCurrentModel = "" + m.benchmarkCurrentEffort = "" + m.benchmarkCurrentTask = "" + m.benchmarkError = "" + m.benchmarkScroll = 0 + m.benchmarkState = benchmarkRunning + ctx, cancel := context.WithCancel(context.Background()) + m.benchmarkCancel = cancel + events := make(chan codex.BenchmarkEvent, 2) + m.benchmarkEvents = events + return m, launchBenchmark(ctx, m.benchmarkRunner, tasks, events) +} + +func (m *Model) selectBenchmarkTask(direction int) { + tasks := codex.BenchmarkTasks() + if len(tasks) == 0 { + return + } + m.benchmarkSelectedTask = (m.benchmarkSelectedTask + direction + len(tasks)) % len(tasks) + m.benchmarkAllArmed = false +} + +func (m *Model) setBenchmarkFilter(filter benchmarkResultFilter) { + m.benchmarkFilter = filter + m.benchmarkScroll = 0 +} + +func (m Model) benchmarkPageSize() int { + layout := m.dashboardLayout() + geometry := layoutBenchmarkArea(layout.contentWidth, layout.meterHeight) + bodyHeight := max(geometry.tableHeight-3, 1) + return max(bodyHeight-3, 1) +} + +func (m *Model) scrollBenchmarkPage(direction int) { + m.scrollBenchmarkRows(direction * m.benchmarkPageSize()) +} + +func (m *Model) scrollBenchmarkRows(rows int) { + maximum := max(len(filterBenchmarkResults(m.benchmarkResults, m.benchmarkFilter))-m.benchmarkPageSize(), 0) + m.benchmarkScroll = min(max(m.benchmarkScroll+rows, 0), maximum) +} + +func (m *Model) sortBenchmarkBy(column benchmarkSortColumn) { + if m.benchmarkSort == column { + m.benchmarkSortDescending = !m.benchmarkSortDescending + } else { + m.benchmarkSort = column + m.benchmarkSortDescending = false + } + m.benchmarkScroll = 0 +} + func (m Model) contentWidth() int { width := m.width if width == 0 { @@ -447,18 +762,18 @@ func (m Model) fetch() tea.Cmd { } } -const stopwatchSampleInterval = 30 * time.Second +const monitorSampleInterval = 30 * time.Second -func (m Model) stopwatchFetch(kind stopwatchFetchKind, sequence uint64) tea.Cmd { +func (m Model) monitorFetch(kind monitorFetchKind, sequence uint64) tea.Cmd { return func() tea.Msg { if m.usageFetcher == nil { - return stopwatchFetchedMsg{ + return monitorFetchedMsg{ kind: kind, sequence: sequence, err: errors.New("local Codex session telemetry unavailable"), at: time.Now(), } } var usage codex.LiveUsageSnapshot var err error - if kind == stopwatchFetchStop { + if kind == monitorFetchStop { if freshFetcher, ok := m.usageFetcher.(FreshTokenUsageFetcher); ok { usage, err = freshFetcher.FetchTokenUsageFresh(context.Background()) } else { @@ -467,47 +782,47 @@ func (m Model) stopwatchFetch(kind stopwatchFetchKind, sequence uint64) tea.Cmd } else { usage, err = m.usageFetcher.FetchTokenUsage(context.Background()) } - return stopwatchFetchedMsg{ + return monitorFetchedMsg{ kind: kind, sequence: sequence, usage: usage, err: err, at: time.Now(), } } } -func (m Model) applyStopwatchFetch(message stopwatchFetchedMsg) (tea.Model, tea.Cmd) { +func (m Model) applyMonitorFetch(message monitorFetchedMsg) (tea.Model, tea.Cmd) { if message.err != nil { - m.stopwatchError = message.err.Error() - if message.kind == stopwatchFetchStop { - m.stopwatchState = stopwatchStopped - m.stopwatchStoppedAt = message.at - } else if message.kind == stopwatchFetchStart { - m.stopwatchState = stopwatchStopped + m.monitorError = message.err.Error() + if message.kind == monitorFetchStop { + m.monitorState = monitorStopped + m.monitorStoppedAt = message.at + } else if message.kind == monitorFetchStart { + m.monitorState = monitorStopped } return m, nil } switch message.kind { - case stopwatchFetchStart: - m.stopwatchBaseline = message.usage.TotalTokens - m.stopwatchLatest = message.usage.TotalTokens - m.stopwatchGraphStart = message.usage.TotalTokens - m.stopwatchStartedAt = message.at - m.stopwatchState = stopwatchRunning - m.stopwatchSessions = message.usage.SessionCount - m.stopwatchError = "" - m.stopwatchNextSample = message.at.Add(stopwatchSampleInterval) - case stopwatchFetchSample, stopwatchFetchStop: - if message.usage.TotalTokens < m.stopwatchLatest { - m.stopwatchError = "local Codex token counter moved backwards" + 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.monitorSessions = message.usage.SessionCount + m.monitorError = "" + m.monitorNextSample = message.at.Add(monitorSampleInterval) + case monitorFetchSample, monitorFetchStop: + if message.usage.TotalTokens < m.monitorLatest { + m.monitorError = "local Codex token counter moved backwards" } else { - if message.usage.TotalTokens > m.stopwatchLatest { - m.stopwatchLastActivity = message.usage.LastActivity + if message.usage.TotalTokens > m.monitorLatest { + m.monitorLastActivity = message.usage.LastActivity } - m.stopwatchLatest = message.usage.TotalTokens - m.stopwatchSessions = message.usage.SessionCount - m.stopwatchError = "" + m.monitorLatest = message.usage.TotalTokens + m.monitorSessions = message.usage.SessionCount + m.monitorError = "" } - if message.kind == stopwatchFetchStop { - m.stopwatchState = stopwatchStopped - m.stopwatchStoppedAt = message.at + if message.kind == monitorFetchStop { + m.monitorState = monitorStopped + m.monitorStoppedAt = message.at } } return m, nil diff --git a/internal/ui/model_test.go b/internal/ui/model_test.go index 0be88a80..3241b905 100644 --- a/internal/ui/model_test.go +++ b/internal/ui/model_test.go @@ -41,7 +41,7 @@ func TestThemeHotkeyCyclesAndWraps(t *testing.T) { func TestTabCyclesStylesAndShiftTabMovesBack(t *testing.T) { model := New(nil, time.Minute) - for want := styleStopwatch; want < styleCount; want++ { + for want := styleMonitor; want < styleCount; want++ { updated, _ := model.Update(tea.KeyMsg{Type: tea.KeyTab}) model = updated.(Model) if model.meterStyle != want { @@ -55,8 +55,8 @@ func TestTabCyclesStylesAndShiftTabMovesBack(t *testing.T) { } updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyShiftTab}) model = updated.(Model) - if model.meterStyle != styleFuel { - t.Fatalf("reverse style navigation got %d, want %d", model.meterStyle, styleFuel) + if model.meterStyle != styleBenchmark { + t.Fatalf("reverse style navigation got %d, want %d", model.meterStyle, styleBenchmark) } } @@ -203,7 +203,7 @@ func TestFooterHitGeometryMatchesRenderedButtonsAcrossSizes(t *testing.T) { {name: "standard", width: 80, height: 24}, {name: "large error", width: 120, height: 40, withError: true}, {name: "empty quota", width: 80, height: 24, empty: true}, - {name: "empty stopwatch", width: 80, height: 24, empty: true, style: styleStopwatch}, + {name: "empty monitor", width: 80, height: 24, empty: true, style: styleMonitor}, } { t.Run(test.name, func(t *testing.T) { model := New(stubFetcher{snapshot: codex.DemoSnapshot()}, time.Minute) diff --git a/internal/ui/stopwatch.go b/internal/ui/monitor.go similarity index 70% rename from internal/ui/stopwatch.go rename to internal/ui/monitor.go index bb413624..e9797d8a 100644 --- a/internal/ui/stopwatch.go +++ b/internal/ui/monitor.go @@ -11,24 +11,24 @@ import ( "github.com/charmbracelet/x/ansi" ) -type stopwatchRect struct { +type monitorRect struct { x int y int width int height int } -func (r stopwatchRect) contains(x, y int) bool { +func (r monitorRect) contains(x, y int) bool { return x >= r.x && x < r.x+r.width && y >= r.y && y < r.y+r.height } -type stopwatchView struct { +type monitorView struct { view string - goRect stopwatchRect - stopRect stopwatchRect + goRect monitorRect + stopRect monitorRect } -type stopwatchGeometry struct { +type monitorGeometry struct { width int height int gap int @@ -36,11 +36,11 @@ type stopwatchGeometry struct { graphHeight int readoutWidth int buttonWidths [2]int - goRect stopwatchRect - stopRect stopwatchRect + goRect monitorRect + stopRect monitorRect } -func layoutStopwatchArea(width, height int) stopwatchGeometry { +func layoutMonitorArea(width, height int) monitorGeometry { width = max(width, 1) height = max(height, 1) gap := 1 @@ -58,7 +58,7 @@ func layoutStopwatchArea(width, height int) stopwatchGeometry { } buttonWidths := distributeSpace(max(controlsWidth-gap, 2), 2) goX := readoutWidth + gap - return stopwatchGeometry{ + return monitorGeometry{ width: width, height: height, gap: gap, @@ -66,61 +66,61 @@ func layoutStopwatchArea(width, height int) stopwatchGeometry { graphHeight: graphHeight, readoutWidth: readoutWidth, buttonWidths: [2]int{buttonWidths[0], buttonWidths[1]}, - goRect: stopwatchRect{x: goX, width: buttonWidths[0], height: topHeight}, - stopRect: stopwatchRect{ + goRect: monitorRect{x: goX, width: buttonWidths[0], height: topHeight}, + stopRect: monitorRect{ x: goX + buttonWidths[0] + gap, width: buttonWidths[1], height: topHeight, }, } } -func (m Model) renderStopwatchArea(width, height int, colors palette) stopwatchView { - layout := layoutStopwatchArea(width, height) +func (m Model) renderMonitorArea(width, height int, colors palette) monitorView { + layout := layoutMonitorArea(width, height) - readout := m.renderStopwatchReadout(layout.readoutWidth, layout.topHeight, colors) - goButton := m.renderStopwatchButton(layout.buttonWidths[0], layout.topHeight, "(S)TART", footerButtonStopwatchGo, m.stopwatchGoEnabled(), colors) - stopButton := m.renderStopwatchButton(layout.buttonWidths[1], layout.topHeight, "STO(P)", footerButtonStopwatchStop, m.stopwatchStopEnabled(), colors) + readout := m.renderMonitorReadout(layout.readoutWidth, layout.topHeight, colors) + goButton := m.renderMonitorButton(layout.buttonWidths[0], layout.topHeight, "(S)TART", footerButtonMonitorGo, m.monitorGoEnabled(), colors) + stopButton := m.renderMonitorButton(layout.buttonWidths[1], layout.topHeight, "STO(P)", footerButtonMonitorStop, m.monitorStopEnabled(), colors) controls := lipgloss.JoinHorizontal(lipgloss.Top, goButton, strings.Repeat(" ", layout.gap), stopButton) top := lipgloss.JoinHorizontal(lipgloss.Top, readout, strings.Repeat(" ", layout.gap), controls) - graph := m.renderStopwatchGraph(layout.width, layout.graphHeight, colors) + graph := m.renderMonitorGraph(layout.width, layout.graphHeight, colors) view := lipgloss.JoinVertical(lipgloss.Left, top, strings.Repeat("\n", layout.gap-1)+graph) if padding := layout.height - lipgloss.Height(view); padding > 0 { view += strings.Repeat("\n", padding) } - return stopwatchView{ + return monitorView{ view: view, goRect: layout.goRect, stopRect: layout.stopRect, } } -func (m Model) renderStopwatchReadout(width, height int, colors palette) string { +func (m Model) renderMonitorReadout(width, height int, colors palette) string { state := "READY" hint := "PRESS S OR CLICK START // LOCAL SESSIONS" - switch m.stopwatchState { - case stopwatchStarting: + switch m.monitorState { + case monitorStarting: state, hint = "ZEROING COUNTER", "SCANNING LOCAL CODEX TELEMETRY" - case stopwatchRunning: - state, hint = "RECORDING ●", fmt.Sprintf("LIVE LOCAL SESSIONS %d // P OR CLICK STOP", m.stopwatchSessions) - case stopwatchStopping: + 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 stopwatchStopped: - state, hint = "STOPPED", fmt.Sprintf("FINAL CONSUMPTION // LOCAL SESSIONS %d", m.stopwatchSessions) + case monitorStopped: + state, hint = "STOPPED", fmt.Sprintf("FINAL CONSUMPTION // LOCAL SESSIONS %d", m.monitorSessions) } - if m.stopwatchError != "" { - state, hint = "NO TOKEN SIGNAL", m.stopwatchError + if m.monitorError != "" { + state, hint = "NO TOKEN SIGNAL", m.monitorError } total := int64(0) - if !m.stopwatchStartedAt.IsZero() && m.stopwatchLatest >= m.stopwatchBaseline { - total = m.stopwatchLatest - m.stopwatchBaseline + if !m.monitorStartedAt.IsZero() && m.monitorLatest >= m.monitorBaseline { + total = m.monitorLatest - m.monitorBaseline } - elapsed := m.stopwatchElapsed(time.Now()) + elapsed := m.monitorElapsed(time.Now()) rate := int64(0) if elapsed > 0 { rate = int64(math.Round(float64(total) / elapsed.Minutes())) } stateColor := colors.primary - if m.stopwatchState == stopwatchRunning && m.stopwatchError == "" { + if m.monitorState == monitorRunning && m.monitorError == "" { stateColor = lipgloss.Color("#7A2633") if m.phase%2 == 0 { stateColor = colors.danger @@ -134,22 +134,22 @@ func (m Model) renderStopwatchReadout(width, height int, colors palette) string if height >= 6 { lines = append(lines, colors.label().Render(fmt.Sprintf("ELAPSED %s // RATE %s/MIN", formatElapsed(elapsed), formatTokens(rate)))) } - if height >= 8 && !m.stopwatchStartedAt.IsZero() { - lines = append(lines, colors.dimmed().Render(fmt.Sprintf("START %s // NOW %s", formatTokens(m.stopwatchBaseline), formatTokens(m.stopwatchLatest)))) + if height >= 8 && !m.monitorStartedAt.IsZero() { + lines = append(lines, colors.dimmed().Render(fmt.Sprintf("START %s // NOW %s", formatTokens(m.monitorBaseline), formatTokens(m.monitorLatest)))) } if height >= 10 { - lines = append(lines, colors.dimmed().Render(fmt.Sprintf("SAMPLES %d // NEXT %s", len(m.stopwatchSamples), m.stopwatchNextLabel()))) + lines = append(lines, colors.dimmed().Render(fmt.Sprintf("SAMPLES %d // NEXT %s", len(m.monitorSamples), m.monitorNextLabel()))) last := "--:--" - if !m.stopwatchLastActivity.IsZero() { - last = compactDuration(time.Since(m.stopwatchLastActivity)) + if !m.monitorLastActivity.IsZero() { + last = compactDuration(time.Since(m.monitorLastActivity)) } - telemetry := fmt.Sprintf("LOCAL SESSIONS %d // LAST %s AGO", m.stopwatchSessions, last) + telemetry := fmt.Sprintf("LOCAL SESSIONS %d // LAST %s AGO", m.monitorSessions, last) lines = append(lines, colors.dimmed().Render(ansi.Truncate(telemetry, max(width-4, 1), ""))) } return frameSized(width, max(height-2, 1), "SESSION READOUT", strings.Join(lines, "\n"), colors.primary, colors) } -func (m Model) renderStopwatchButton(width, height int, label string, id footerButtonID, enabled bool, colors palette) string { +func (m Model) renderMonitorButton(width, height int, label string, id footerButtonID, enabled bool, colors palette) string { border := colors.dim foreground := colors.dim if enabled { @@ -174,11 +174,11 @@ func (m Model) renderStopwatchButton(width, height int, label string, id footerB return style.Render(label) } -func (m Model) renderStopwatchGraph(width, height int, colors palette) string { +func (m Model) renderMonitorGraph(width, height int, colors palette) string { innerWidth := max(width-4, 1) plotHeight := max(height-3, 1) const sampleWidth = 2 // one block-wide bar plus one cell of breathing room - samples := m.stopwatchSamples + samples := m.monitorSamples visibleSamples := max((innerWidth+1)/sampleWidth, 1) if len(samples) > visibleSamples { samples = samples[len(samples)-visibleSamples:] @@ -196,9 +196,9 @@ func (m Model) renderStopwatchGraph(width, height int, colors palette) string { } if len(samples) == 0 { message := "WAITING FOR FIRST SAMPLE" - if m.stopwatchState == stopwatchIdle { + if m.monitorState == monitorIdle { message = "PRESS START TO ARM RECORDER" - } else if m.stopwatchState == stopwatchStopped { + } else if m.monitorState == monitorStopped { message = "NO COMPLETE 30 SEC SAMPLE" } message = ansi.Truncate(message, innerWidth, "") @@ -234,12 +234,12 @@ func (m Model) renderStopwatchGraph(width, height int, colors palette) string { return r }, string(runes))) } - lines[row] = renderStopwatchBarRow(runes, colors) + lines[row] = renderMonitorBarRow(runes, colors) } return frameSized(width, max(height-2, 1), ansi.Truncate(title, max(innerWidth-4, 1), ""), strings.Join(lines, "\n"), colors.primary, colors) } -func renderStopwatchBarRow(cells []rune, colors palette) string { +func renderMonitorBarRow(cells []rune, colors palette) string { active := lipgloss.NewStyle().Foreground(colors.primary) dimmed := lipgloss.NewStyle().Foreground(colors.dim) var row strings.Builder @@ -256,49 +256,49 @@ func renderStopwatchBarRow(cells []rune, colors palette) string { return row.String() } -func (m Model) stopwatchButtonAt(x, y int) footerButtonID { +func (m Model) monitorButtonAt(x, y int) footerButtonID { if m.loading && len(m.snapshot.Meters()) == 0 { return footerButtonNone } dashboard := m.dashboardLayout() - area := layoutStopwatchArea(dashboard.contentWidth, dashboard.meterHeight) + area := layoutMonitorArea(dashboard.contentWidth, dashboard.meterHeight) localX, localY := x-2, y-dashboard.meterY if area.goRect.contains(localX, localY) { - return footerButtonStopwatchGo + return footerButtonMonitorGo } if area.stopRect.contains(localX, localY) { - return footerButtonStopwatchStop + return footerButtonMonitorStop } return footerButtonNone } -func (m Model) stopwatchGoEnabled() bool { - return m.stopwatchState == stopwatchIdle || m.stopwatchState == stopwatchStopped +func (m Model) monitorGoEnabled() bool { + return m.monitorState == monitorIdle || m.monitorState == monitorStopped } -func (m Model) stopwatchStopEnabled() bool { - return m.stopwatchState == stopwatchRunning +func (m Model) monitorStopEnabled() bool { + return m.monitorState == monitorRunning } -func (m Model) stopwatchElapsed(now time.Time) time.Duration { - if m.stopwatchStartedAt.IsZero() { +func (m Model) monitorElapsed(now time.Time) time.Duration { + if m.monitorStartedAt.IsZero() { return 0 } end := now - if m.stopwatchState == stopwatchStopped && !m.stopwatchStoppedAt.IsZero() { - end = m.stopwatchStoppedAt + if m.monitorState == monitorStopped && !m.monitorStoppedAt.IsZero() { + end = m.monitorStoppedAt } - if end.Before(m.stopwatchStartedAt) { + if end.Before(m.monitorStartedAt) { return 0 } - return end.Sub(m.stopwatchStartedAt) + return end.Sub(m.monitorStartedAt) } -func (m Model) stopwatchNextLabel() string { - if m.stopwatchState != stopwatchRunning || m.stopwatchNextSample.IsZero() { +func (m Model) monitorNextLabel() string { + if m.monitorState != monitorRunning || m.monitorNextSample.IsZero() { return "--:--" } - return compactDuration(time.Until(m.stopwatchNextSample)) + return compactDuration(time.Until(m.monitorNextSample)) } func niceTokenCeiling(value int64) int64 { diff --git a/internal/ui/stopwatch_test.go b/internal/ui/monitor_test.go similarity index 57% rename from internal/ui/stopwatch_test.go rename to internal/ui/monitor_test.go index ec5f39c1..dbcfc270 100644 --- a/internal/ui/stopwatch_test.go +++ b/internal/ui/monitor_test.go @@ -15,173 +15,173 @@ import ( "github.com/merefield/codexometer/internal/codex" ) -func TestStopwatchGoSampleAndStopLifecycle(t *testing.T) { +func TestMonitorGoSampleAndStopLifecycle(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.meterStyle = styleStopwatch + model.meterStyle = styleMonitor updated, command := model.Update(key('s')) model = updated.(Model) - if command == nil || model.stopwatchState != stopwatchStarting || model.flashedButton != footerButtonStopwatchGo { - t.Fatalf("Go did not arm stopwatch: state=%d flash=%d command=%v", model.stopwatchState, model.flashedButton, command) + 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.renderStopwatchButton(14, 6, "(S)TART", footerButtonStopwatchGo, model.stopwatchGoEnabled(), paletteFor(themeHacker)) + 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.stopwatchRequest + sequence := model.monitorRequest startedAt := time.Unix(100, 0) - updated, command = model.Update(stopwatchFetchedMsg{ - kind: stopwatchFetchStart, sequence: sequence, usage: usageWithTokens(baseline), at: startedAt, + updated, command = model.Update(monitorFetchedMsg{ + kind: monitorFetchStart, sequence: sequence, usage: usageWithTokens(baseline), at: startedAt, }) model = updated.(Model) - if model.stopwatchState != stopwatchRunning || model.stopwatchBaseline != baseline || command != nil { + if model.monitorState != monitorRunning || model.monitorBaseline != baseline || command != nil { t.Fatalf("baseline was not established: %#v", model) } - model.stopwatchRequest++ - updated, _ = model.Update(stopwatchFetchedMsg{ - kind: stopwatchFetchSample, sequence: model.stopwatchRequest, + model.monitorRequest++ + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchSample, sequence: model.monitorRequest, usage: usageWithTokens(1_250), at: startedAt.Add(29 * time.Second), }) model = updated.(Model) - if model.stopwatchLatest != 1_250 || len(model.stopwatchSamples) != 0 { - t.Fatalf("live read should update the readout without prematurely adding a graph bucket: %#v", model.stopwatchSamples) + if model.monitorLatest != 1_250 || len(model.monitorSamples) != 0 { + t.Fatalf("live read should update the readout without prematurely adding a graph bucket: %#v", model.monitorSamples) } - model.stopwatchFetchActive = true + model.monitorFetchActive = true updated, _ = model.Update(secondMsg(startedAt.Add(30 * time.Second))) model = updated.(Model) - model.stopwatchFetchActive = false - if len(model.stopwatchSamples) != 1 || model.stopwatchSamples[0].intervalTokens != 250 { - t.Fatalf("30-second graph bucket was not recorded: %#v", model.stopwatchSamples) + model.monitorFetchActive = false + if len(model.monitorSamples) != 1 || model.monitorSamples[0].intervalTokens != 250 { + t.Fatalf("30-second graph bucket was not recorded: %#v", model.monitorSamples) } updated, command = model.Update(key('p')) model = updated.(Model) - if command == nil || model.stopwatchState != stopwatchStopping || model.flashedButton != footerButtonStopwatchStop { - t.Fatalf("Stop did not request final sync: state=%d flash=%d command=%v", model.stopwatchState, model.flashedButton, command) + 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) } - stopSequence := model.stopwatchRequest - updated, _ = model.Update(stopwatchFetchedMsg{ - kind: stopwatchFetchStop, sequence: stopSequence, + stopSequence := model.monitorRequest + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchStop, sequence: stopSequence, usage: usageWithTokens(1_400), at: startedAt.Add(45 * time.Second), }) model = updated.(Model) - if model.stopwatchState != stopwatchStopped || model.stopwatchLatest-model.stopwatchBaseline != 400 { - t.Fatalf("final usage was not recorded: state=%d total=%d", model.stopwatchState, model.stopwatchLatest-model.stopwatchBaseline) + if model.monitorState != monitorStopped || model.monitorLatest-model.monitorBaseline != 400 { + t.Fatalf("final usage was not recorded: state=%d total=%d", model.monitorState, model.monitorLatest-model.monitorBaseline) } - if len(model.stopwatchSamples) != 1 { - t.Fatalf("partial final interval was incorrectly plotted as a 30-second bucket: %#v", model.stopwatchSamples) + if len(model.monitorSamples) != 1 { + t.Fatalf("partial final interval was incorrectly plotted as a 30-second bucket: %#v", model.monitorSamples) } } -func TestStopwatchTickSamplesOnlyWhileRunningAndIgnoresStaleResults(t *testing.T) { +func TestMonitorTickSamplesOnlyWhileRunningAndIgnoresStaleResults(t *testing.T) { model := New(stubLiveFetcher{stubFetcher: stubFetcher{snapshot: codex.DemoSnapshot()}}, time.Minute) - model.meterStyle = styleStopwatch + model.meterStyle = styleMonitor updated, command := model.Update(secondMsg(time.Now())) model = updated.(Model) - if command == nil || model.stopwatchFetchActive { - t.Fatal("idle stopwatch did not retain only the global clock tick") + if command == nil || model.monitorFetchActive { + t.Fatal("idle monitor did not retain only the global clock tick") } - model.stopwatchState = stopwatchRunning - model.stopwatchRequest = 4 - model.stopwatchNextSample = time.Now().Add(time.Minute) + model.monitorState = monitorRunning + model.monitorRequest = 4 + model.monitorNextSample = time.Now().Add(time.Minute) updated, command = model.Update(secondMsg(time.Now())) model = updated.(Model) - if command == nil || !model.stopwatchFetchActive || model.stopwatchRequest != 5 { + if command == nil || !model.monitorFetchActive || model.monitorRequest != 5 { t.Fatalf("running clock tick did not request live telemetry: %#v", model) } - updated, _ = model.Update(stopwatchFetchedMsg{ - kind: stopwatchFetchSample, sequence: 4, usage: usageWithTokens(999), at: time.Now(), + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchSample, sequence: 4, usage: usageWithTokens(999), at: time.Now(), }) model = updated.(Model) - if model.stopwatchLatest != 0 || !model.stopwatchFetchActive { - t.Fatal("stale response changed stopwatch state") + if model.monitorLatest != 0 || !model.monitorFetchActive { + t.Fatal("stale response changed monitor state") } } -func TestStopwatchSurfacesUnavailableAndFailedFinalUsage(t *testing.T) { - model := Model{meterStyle: styleStopwatch, stopwatchState: stopwatchStarting, stopwatchRequest: 1} - updated, _ := model.Update(stopwatchFetchedMsg{ - kind: stopwatchFetchStart, sequence: 1, err: errors.New("local telemetry unavailable"), at: time.Now(), +func TestMonitorSurfacesUnavailableAndFailedFinalUsage(t *testing.T) { + model := Model{meterStyle: styleMonitor, monitorState: monitorStarting, monitorRequest: 1} + updated, _ := model.Update(monitorFetchedMsg{ + kind: monitorFetchStart, sequence: 1, err: errors.New("local telemetry unavailable"), at: time.Now(), }) model = updated.(Model) - if model.stopwatchState != stopwatchStopped || !strings.Contains(model.stopwatchError, "local telemetry unavailable") { + if model.monitorState != monitorStopped || !strings.Contains(model.monitorError, "local telemetry unavailable") { t.Fatalf("missing usage was not surfaced: %#v", model) } - model.stopwatchState = stopwatchStopping - model.stopwatchRequest = 2 - updated, _ = model.Update(stopwatchFetchedMsg{ - kind: stopwatchFetchStop, sequence: 2, err: errors.New("offline"), at: time.Now(), + model.monitorState = monitorStopping + model.monitorRequest = 2 + updated, _ = model.Update(monitorFetchedMsg{ + kind: monitorFetchStop, sequence: 2, err: errors.New("offline"), at: time.Now(), }) model = updated.(Model) - if model.stopwatchState != stopwatchStopped || model.stopwatchError != "offline" { + if model.monitorState != monitorStopped || model.monitorError != "offline" { t.Fatalf("failed final sync was not surfaced: %#v", model) } } -func TestStopwatchFetchUsesConfiguredLocalSource(t *testing.T) { +func TestMonitorFetchUsesConfiguredLocalSource(t *testing.T) { want := codex.LiveUsageSnapshot{TotalTokens: 321, SessionCount: 2} model := New(stubLiveFetcher{usage: want}, time.Minute) - message := model.stopwatchFetch(stopwatchFetchStart, 7)().(stopwatchFetchedMsg) + message := model.monitorFetch(monitorFetchStart, 7)().(monitorFetchedMsg) if message.err != nil || message.sequence != 7 || message.usage != want { t.Fatalf("live source result = %#v", message) } missing := New(stubFetcher{}, time.Minute) - message = missing.stopwatchFetch(stopwatchFetchStart, 8)().(stopwatchFetchedMsg) + message = missing.monitorFetch(monitorFetchStart, 8)().(monitorFetchedMsg) if message.err == nil || !strings.Contains(message.err.Error(), "local Codex session telemetry") { t.Fatalf("missing live source error = %v", message.err) } } -func TestStopwatchStopUsesFreshLocalSourceWhenAvailable(t *testing.T) { +func TestMonitorStopUsesFreshLocalSourceWhenAvailable(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.stopwatchFetch(stopwatchFetchStop, 9)().(stopwatchFetchedMsg) + message := model.monitorFetch(monitorFetchStop, 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) } } -func TestStopwatchViewIsResponsiveAndGraphAutoScales(t *testing.T) { +func TestMonitorViewIsResponsiveAndGraphAutoScales(t *testing.T) { for _, size := range []struct{ width, height int }{{80, 24}, {120, 40}, {200, 60}} { model := Model{ snapshot: codex.DemoSnapshot(), width: size.width, height: size.height, - meterStyle: styleStopwatch, stopwatchState: stopwatchRunning, - stopwatchBaseline: 1_000, stopwatchLatest: 7_250, - stopwatchStartedAt: time.Now().Add(-time.Minute), - stopwatchSamples: []stopwatchSample{{intervalTokens: 250}, {intervalTokens: 6_000}}, + meterStyle: styleMonitor, monitorState: monitorRunning, + monitorBaseline: 1_000, monitorLatest: 7_250, + monitorStartedAt: time.Now().Add(-time.Minute), + monitorSamples: []monitorSample{{intervalTokens: 250}, {intervalTokens: 6_000}}, } output := model.View() plain := ansi.Strip(output) for _, want := range []string{"SESSION READOUT", "6,250 TOKENS", "ELAPSED", "(S)TART", "STO(P)", "LOCAL TOKEN BARS", "AUTO 0-10K", "█", "░"} { if !strings.Contains(plain, want) { - t.Errorf("%dx%d stopwatch missing %q:\n%s", size.width, size.height, want, plain) + t.Errorf("%dx%d monitor missing %q:\n%s", size.width, size.height, want, plain) } } if lipgloss.Width(output) > size.width || lipgloss.Height(output) > size.height { - t.Errorf("stopwatch overflowed %dx%d: got %dx%d", size.width, size.height, lipgloss.Width(output), lipgloss.Height(output)) + t.Errorf("monitor overflowed %dx%d: got %dx%d", size.width, size.height, lipgloss.Width(output), lipgloss.Height(output)) } } } -func TestStopwatchRecordingLampPulsesBetweenDarkAndBrightRed(t *testing.T) { +func TestMonitorRecordingLampPulsesBetweenDarkAndBrightRed(t *testing.T) { colors := paletteFor(themeHacker) - model := Model{stopwatchState: stopwatchRunning, stopwatchStartedAt: time.Now()} + model := Model{monitorState: monitorRunning, monitorStartedAt: time.Now()} model.phase = 0 - bright := model.renderStopwatchReadout(60, 8, colors) + bright := model.renderMonitorReadout(60, 8, colors) model.phase = 1 - dark := model.renderStopwatchReadout(60, 8, colors) + 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 ●") if !strings.Contains(bright, wantBright) || !strings.Contains(dark, wantDark) || ansi.Strip(bright) != ansi.Strip(dark) { @@ -189,15 +189,15 @@ func TestStopwatchRecordingLampPulsesBetweenDarkAndBrightRed(t *testing.T) { } } -func TestStopwatchLargeButtonsAreClickableAcrossTheirBoxes(t *testing.T) { +func TestMonitorLargeButtonsAreClickableAcrossTheirBoxes(t *testing.T) { model := Model{ snapshot: codex.DemoSnapshot(), width: 100, height: 36, - meterStyle: styleStopwatch, stopwatchState: stopwatchIdle, + meterStyle: styleMonitor, monitorState: monitorIdle, } colors := paletteFor(model.theme) dashboard := model.dashboardLayout() - geometry := layoutStopwatchArea(dashboard.contentWidth, dashboard.meterHeight) - area := model.renderStopwatchArea(dashboard.contentWidth, dashboard.meterHeight, colors) + geometry := layoutMonitorArea(dashboard.contentWidth, dashboard.meterHeight) + area := model.renderMonitorArea(dashboard.contentWidth, dashboard.meterHeight, colors) if area.goRect != geometry.goRect || area.stopRect != geometry.stopRect { t.Fatalf("rendered controls diverged from pure layout: rendered=%#v layout=%#v", area, geometry) } @@ -205,13 +205,13 @@ func TestStopwatchLargeButtonsAreClickableAcrossTheirBoxes(t *testing.T) { originY := dashboard.meterY for _, test := range []struct { - rect stopwatchRect + rect monitorRect want footerButtonID - }{{geometry.goRect, footerButtonStopwatchGo}, {geometry.stopRect, footerButtonStopwatchStop}} { + }{{geometry.goRect, footerButtonMonitorGo}, {geometry.stopRect, footerButtonMonitorStop}} { // 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 - if got := model.stopwatchButtonAt(x, y); got != test.want { + if got := model.monitorButtonAt(x, y); got != test.want { t.Errorf("button hit = %d, want %d at %d,%d", got, test.want, x, y) } } @@ -219,10 +219,10 @@ func TestStopwatchLargeButtonsAreClickableAcrossTheirBoxes(t *testing.T) { hoverY := originY + geometry.goRect.y + 1 updated, command := model.Update(tea.MouseMsg{X: hoverX, Y: hoverY, Action: tea.MouseActionMotion}) model = updated.(Model) - if command != nil || model.hoveredButton != footerButtonStopwatchGo { + if command != nil || model.hoveredButton != footerButtonMonitorGo { t.Fatal("hovering the Go box did not select it") } - hovered := model.renderStopwatchButton(14, 6, "(S)TART", footerButtonStopwatchGo, true, colors) + hovered := model.renderMonitorButton(14, 6, "(S)TART", footerButtonMonitorGo, true, colors) wantHover := lipgloss.NewStyle().Bold(true).Foreground(colors.accent).Background(colors.background).Render("(S)TART") if !strings.Contains(hovered, wantHover) { t.Fatal("hovering the Go box did not highlight its label") @@ -233,34 +233,34 @@ func TestStopwatchLargeButtonsAreClickableAcrossTheirBoxes(t *testing.T) { Button: tea.MouseButtonLeft, Action: tea.MouseActionPress, }) model = updated.(Model) - if command == nil || model.stopwatchState != stopwatchStarting { - t.Fatal("clicking the Go box did not start the stopwatch") + if command == nil || model.monitorState != monitorStarting { + t.Fatal("clicking the Go box did not start the monitor") } } -func TestStopwatchGraphIntroducesBarsOnRightAndScrollsThemLeft(t *testing.T) { - model := Model{stopwatchState: stopwatchRunning, stopwatchSamples: []stopwatchSample{{intervalTokens: 10}}} - first := ansi.Strip(model.renderStopwatchGraph(40, 10, paletteFor(themeHacker))) +func TestMonitorGraphIntroducesBarsOnRightAndScrollsThemLeft(t *testing.T) { + model := Model{monitorState: monitorRunning, monitorSamples: []monitorSample{{intervalTokens: 10}}} + first := ansi.Strip(model.renderMonitorGraph(40, 10, paletteFor(themeHacker))) firstX := graphRightmostBar(first) if firstX < 0 { t.Fatalf("first graph has no bar:\n%s", first) } - model.stopwatchSamples = append(model.stopwatchSamples, stopwatchSample{intervalTokens: 10}) - second := ansi.Strip(model.renderStopwatchGraph(40, 10, paletteFor(themeHacker))) + model.monitorSamples = append(model.monitorSamples, monitorSample{intervalTokens: 10}) + second := ansi.Strip(model.renderMonitorGraph(40, 10, paletteFor(themeHacker))) line := graphBarLine(second) if !strings.Contains(line, "█ █") || graphRightmostBar(second) != firstX { t.Fatalf("new bar did not enter on the right while the old bar shifted left:\nfirst:\n%s\nsecond:\n%s", first, second) } } -func TestStopwatchGraphUsesVerticalGranularBars(t *testing.T) { +func TestMonitorGraphUsesVerticalGranularBars(t *testing.T) { model := Model{ - stopwatchState: stopwatchRunning, - stopwatchSamples: []stopwatchSample{{intervalTokens: 25}, {intervalTokens: 100}}, + monitorState: monitorRunning, + monitorSamples: []monitorSample{{intervalTokens: 25}, {intervalTokens: 100}}, } - graph := ansi.Strip(model.renderStopwatchGraph(40, 12, paletteFor(themeHacker))) - if strings.Count(graph, "█") <= len(model.stopwatchSamples) { + graph := ansi.Strip(model.renderMonitorGraph(40, 12, paletteFor(themeHacker))) + if strings.Count(graph, "█") <= len(model.monitorSamples) { t.Fatalf("bars did not extend vertically across multiple rows:\n%s", graph) } if !strings.Contains(graph, "░") { @@ -268,7 +268,7 @@ func TestStopwatchGraphUsesVerticalGranularBars(t *testing.T) { } } -func TestStopwatchFormattingAndScaleHelpers(t *testing.T) { +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 { t.Errorf("formatTokens(%d) = %q, want %q", input, got, want) diff --git a/internal/ui/tabs.go b/internal/ui/tabs.go index e52c362f..ae34c301 100644 --- a/internal/ui/tabs.go +++ b/internal/ui/tabs.go @@ -14,31 +14,37 @@ type styleTab struct { } func styleTabLayout(width int, recording bool) ([]styleTab, string) { - stopwatchFull := "╭ STOPWATCH ╮" - stopwatchCompact := "╭TIMER╮" - stopwatchMinimal := "[S]" - microStopwatch := "S" + monitorFull := "╭ MONITOR ╮" + monitorCompact := "╭MON╮" + monitorMinimal := "[M]" + microMonitor := "M" if recording { - stopwatchFull = "╭ STOPWATCH ●╮" - stopwatchCompact = "╭TIMER●╮" - stopwatchMinimal = "[S●]" - microStopwatch = "●" + monitorFull = "╭ MONITOR ●╮" + monitorCompact = "╭MON●╮" + monitorMinimal = "[M●]" + microMonitor = "●" } tiers := [][]string{ - {"╭ BARS ╮", stopwatchFull, "╭ PIE ╮", "╭ CONSUMPTION PACE ╮", "╭ FUEL TANK ╮"}, - {"╭BAR╮", stopwatchCompact, "╭PIE╮", "╭PACE╮", "╭FUEL╮"}, - {"[B]", stopwatchMinimal, "[P]", "[C]", "[F]"}, - {"B", microStopwatch, "P", "C", "F"}, + {"╭ 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"}, } - separator := " " + separator := "" labels := tiers[len(tiers)-1] for _, candidate := range tiers { + candidateSeparator := " " total := len(candidate) - 1 for _, label := range candidate { total += lipgloss.Width(label) } + if total > width { + total -= len(candidate) - 1 + candidateSeparator = "" + } if total <= width { labels = candidate + separator = candidateSeparator break } } @@ -57,7 +63,7 @@ func styleTabLayout(width int, recording bool) ([]styleTab, string) { } func (m Model) renderStyleTabs(width int, colors palette) string { - recording := m.stopwatchState == stopwatchRunning + recording := m.monitorState == monitorRunning tabs, separator := styleTabLayout(width, recording) parts := make([]string, 0, len(tabs)) used := 0 @@ -80,7 +86,7 @@ func (m Model) renderStyleTabs(width int, colors palette) string { 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 == styleStopwatch, m.phase, colors)) + parts = append(parts, renderStyleTabLabel(tab.label, base, background, recording && tab.style == styleMonitor, m.phase, colors)) used += tab.width } if len(parts) > 1 { @@ -115,7 +121,7 @@ func (m Model) styleTabAt(x, y int) (meterStyleID, bool) { return styleBars, false } localX := x - 2 - tabs, _ := styleTabLayout(layout.contentWidth, m.stopwatchState == stopwatchRunning) + tabs, _ := styleTabLayout(layout.contentWidth, m.monitorState == monitorRunning) 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 0e9910cb..33eccee1 100644 --- a/internal/ui/tabs_test.go +++ b/internal/ui/tabs_test.go @@ -18,9 +18,9 @@ func TestStyleTabsChooseResponsiveLabels(t *testing.T) { want string }{ {width: 100, want: "CONSUMPTION PACE"}, - {width: 44, want: "TIMER"}, - {width: 19, want: "[S]"}, - {width: 9, want: "S"}, + {width: 44, want: "MON"}, + {width: 19, want: "[M]"}, + {width: 9, want: "M"}, } { t.Run(test.want, func(t *testing.T) { tabs, _ := styleTabLayout(test.width, false) @@ -73,15 +73,15 @@ func TestStyleTabsSupportHoverClickAndPulse(t *testing.T) { } } -func TestStopwatchTabShowsPulsingRecordingDotWhileAnotherTabIsActive(t *testing.T) { - model := Model{meterStyle: styleBars, stopwatchState: stopwatchRunning} +func TestMonitorTabShowsPulsingRecordingDotWhileAnotherTabIsActive(t *testing.T) { + model := Model{meterStyle: styleBars, monitorState: monitorRunning} colors := paletteFor(themeHacker) model.phase = 0 bright := model.renderStyleTabs(100, colors) model.phase = 1 dark := model.renderStyleTabs(100, colors) if !strings.Contains(ansi.Strip(bright), "●") { - t.Fatal("recording tab did not retain a pulsing dot away from the Stopwatch view") + t.Fatal("recording tab did not retain a pulsing dot away from the Monitor view") } if recordingDotColor(0, colors) == recordingDotColor(1, colors) { t.Fatal("recording tab dot does not alternate between bright and dark red") @@ -91,11 +91,11 @@ func TestStopwatchTabShowsPulsingRecordingDotWhileAnotherTabIsActive(t *testing. } } -func TestSOnlyStartsStopwatch(t *testing.T) { +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.stopwatchState != stopwatchIdle { - t.Fatal("S changed state outside the Stopwatch tab") + 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 1b8f1645..83d08247 100644 --- a/internal/ui/theme.go +++ b/internal/ui/theme.go @@ -21,10 +21,11 @@ type meterStyleID int const ( styleBars meterStyleID = iota - styleStopwatch + styleMonitor stylePie styleConsumptionPace styleFuel + styleBenchmark styleCount ) @@ -39,10 +40,11 @@ func (s meterStyleID) previous() meterStyleID { func (s meterStyleID) name() string { return [...]string{ "BARS", - "STOPWATCH", + "MONITOR", "PIE", "CONSUMPTION PACE", "FUEL TANK", + "BENCHMARK", }[s] } diff --git a/internal/ui/view.go b/internal/ui/view.go index 0fb277b8..b2cb65d7 100644 --- a/internal/ui/view.go +++ b/internal/ui/view.go @@ -37,8 +37,10 @@ func (m Model) View() string { parts = append(parts, emptyView) } footer := m.renderFooter(contentWidth, colors) - if m.meterStyle == styleStopwatch { - parts = append(parts, m.renderStopwatchArea(contentWidth, layout.meterHeight, colors).view) + if m.meterStyle == styleMonitor { + parts = append(parts, m.renderMonitorArea(contentWidth, layout.meterHeight, colors).view) + } else if m.meterStyle == styleBenchmark { + parts = append(parts, m.renderBenchmarkArea(contentWidth, layout.meterHeight, colors)) } else if len(meters) > 1 { parts = append(parts, renderMeterGrid(contentWidth, layout.meterHeight, meters, m.meterStyle, colors)) } else if len(meters) == 1 { diff --git a/internal/ui/view_test.go b/internal/ui/view_test.go index 02c5481d..5233345a 100644 --- a/internal/ui/view_test.go +++ b/internal/ui/view_test.go @@ -30,9 +30,13 @@ func TestViewRendersEveryThemeAndStyleWithinStandardTerminal(t *testing.T) { if !strings.Contains(output, style.name()) { t.Errorf("style %d name missing from view", style) } - if style == styleStopwatch { + if style == styleMonitor { if !strings.Contains(output, "SESSION READOUT") || !strings.Contains(output, "30 SEC LOCAL TOKEN BARS") { - t.Errorf("stopwatch components missing for theme %d", theme) + t.Errorf("monitor components missing for theme %d", theme) + } + } else if style == styleBenchmark { + if !strings.Contains(output, "ALGORITHM TRIAL") || !strings.Contains(output, "RESULT MATRIX") { + t.Errorf("benchmark components missing for theme %d", theme) } } else if !strings.Contains(output, "5 HOURS LOOP") || !strings.Contains(output, "1 WEEK LOOP") { t.Errorf("quota windows missing for theme %d style %d", theme, style) @@ -123,8 +127,11 @@ func TestGaugeGridStyleClassification(t *testing.T) { t.Errorf("usesMeterGrid(%s) = false, want true", style.name()) } } - if usesMeterGrid(styleStopwatch) { - t.Fatal("stopwatch should use its own full-width layout") + if usesMeterGrid(styleMonitor) { + t.Fatal("monitor should use its own full-width layout") + } + if usesMeterGrid(styleBenchmark) { + t.Fatal("benchmark should use its own full-width layout") } } diff --git a/internal/version/version.go b/internal/version/version.go index f9cbedb4..c6ccd8ee 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -4,23 +4,52 @@ package version import ( "runtime/debug" "strings" + "time" ) // Fallback is the version reported by binaries built directly from a source // checkout. Release automation may override it with: // // -X github.com/merefield/codexometer/internal/version.Fallback=1.2.3 -var Fallback = "0.1.2" +var Fallback = "0.2.0" // Current returns the module version embedded by Go for tagged installs, or // Fallback for ordinary source builds. The leading tag prefix is omitted so // callers can choose how to present it. func Current() string { if info, ok := debug.ReadBuildInfo(); ok { - moduleVersion := strings.TrimSpace(info.Main.Version) - if moduleVersion != "" && moduleVersion != "(devel)" { - return strings.TrimPrefix(moduleVersion, "v") + return selectVersion(info.Main.Version, Fallback) + } + return selectVersion("", Fallback) +} + +func selectVersion(moduleVersion, fallback string) string { + moduleVersion = strings.TrimSpace(moduleVersion) + if moduleVersion != "" && moduleVersion != "(devel)" && !isPseudoVersion(moduleVersion) { + return strings.TrimPrefix(moduleVersion, "v") + } + return strings.TrimPrefix(strings.TrimSpace(fallback), "v") +} + +func isPseudoVersion(value string) bool { + parts := strings.Split(strings.TrimPrefix(strings.TrimSpace(value), "v"), "-") + if len(parts) < 3 { + return false + } + timestamp, revision := parts[len(parts)-2], parts[len(parts)-1] + if clean, _, found := strings.Cut(revision, "+"); found { + revision = clean + } + if len(timestamp) != 14 || len(revision) < 7 { + return false + } + if _, err := time.Parse("20060102150405", timestamp); err != nil { + return false + } + for _, character := range revision { + if !strings.ContainsRune("0123456789abcdef", character) { + return false } } - return strings.TrimPrefix(strings.TrimSpace(Fallback), "v") + return true } diff --git a/internal/version/version_test.go b/internal/version/version_test.go index 116a1262..e2c53bb2 100644 --- a/internal/version/version_test.go +++ b/internal/version/version_test.go @@ -4,7 +4,28 @@ import "testing" func TestCurrentReportsMaintainedFallbackForSourceBuild(t *testing.T) { got := Current() - if got != "0.1.2" { - t.Fatalf("Current() = %q, want 0.1.2", got) + if got != "0.2.0" { + t.Fatalf("Current() = %q, want 0.2.0", got) + } +} + +func TestSelectVersion(t *testing.T) { + tests := []struct { + name string + module string + fallback string + want string + }{ + {name: "tagged install", module: "v1.2.3", fallback: "0.2.0", want: "1.2.3"}, + {name: "development build", module: "(devel)", fallback: "v0.2.0", want: "0.2.0"}, + {name: "Go 1.25 source pseudo-version", module: "v0.0.0-20260811151632-815179a0b2e7+dirty", fallback: "0.2.0", want: "0.2.0"}, + {name: "pre-release tag", module: "v1.2.3-rc.1", fallback: "0.2.0", want: "1.2.3-rc.1"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := selectVersion(test.module, test.fallback); got != test.want { + t.Fatalf("selectVersion(%q, %q) = %q, want %q", test.module, test.fallback, got, test.want) + } + }) } } diff --git a/main.go b/main.go index e1f66dc7..5bf7e7a6 100644 --- a/main.go +++ b/main.go @@ -38,6 +38,44 @@ func (d *demoFetcher) FetchTokenUsage(context.Context) (codex.LiveUsageSnapshot, }, nil } +func (d *demoFetcher) BenchmarkCombinationCount(context.Context) (int, error) { return 2, nil } + +func (d *demoFetcher) RunBenchmarkSuite(ctx context.Context, tasks []codex.BenchmarkTaskID, emit func(codex.BenchmarkEvent)) { + baseResults := []codex.BenchmarkResult{ + {Model: "gpt-5.6-sol", DisplayName: "GPT-5.6 Sol", Effort: "medium", ActualModel: "gpt-5.6-sol", Correct: true, Duration: 12_400 * time.Millisecond, Usage: codex.BenchmarkUsage{TotalTokens: 4_820}, CostUSD: 0.0412, CostKnown: true}, + {Model: "gpt-5.6-terra", DisplayName: "GPT-5.6 Terra", Effort: "low", ActualModel: "gpt-5.6-terra", Correct: false, Duration: 7_900 * time.Millisecond, Usage: codex.BenchmarkUsage{TotalTokens: 2_210}, CostUSD: 0.0091, CostKnown: true, Failure: "case 17 returned the wrong answer"}, + } + if len(tasks) == 0 { + tasks = []codex.BenchmarkTaskID{codex.BenchmarkMergeRanges} + } + var results []codex.BenchmarkResult + for _, taskID := range tasks { + for _, task := range codex.BenchmarkTasks() { + if task.ID != taskID { + continue + } + for _, base := range baseResults { + result := base + result.TaskID, result.TaskName = task.ID, task.Name + results = append(results, result) + } + } + } + emit(codex.BenchmarkEvent{Total: len(results), Combinations: 2}) + for index := range results { + select { + case <-ctx.Done(): + emit(codex.BenchmarkEvent{Total: len(results), Completed: index, Done: true, Err: ctx.Err()}) + return + default: + } + emit(codex.BenchmarkEvent{Total: len(results), Completed: index, CurrentModel: results[index].DisplayName, CurrentEffort: results[index].Effort}) + result := results[index] + emit(codex.BenchmarkEvent{Total: len(results), Completed: index + 1, Combinations: 2, CurrentTaskID: result.TaskID, CurrentTask: result.TaskName, CurrentModel: result.DisplayName, CurrentEffort: result.Effort, Result: &result}) + } + emit(codex.BenchmarkEvent{Total: len(results), Completed: len(results), Done: true}) +} + func main() { os.Exit(run(os.Args[1:], os.Stdout, os.Stderr, defaultDependencies())) } diff --git a/main_test.go b/main_test.go index 5127aa99..7dab7780 100644 --- a/main_test.go +++ b/main_test.go @@ -16,7 +16,7 @@ func TestRunVersion(t *testing.T) { for _, flag := range []string{"-v", "--version"} { var stdout, stderr bytes.Buffer code := run([]string{flag}, &stdout, &stderr, dependencies{}) - if code != 0 || stdout.String() != "codexometer v0.1.2\n" || stderr.Len() != 0 { + if code != 0 || stdout.String() != "codexometer v0.2.0\n" || stderr.Len() != 0 { t.Errorf("flag=%s code=%d stdout=%q stderr=%q", flag, code, stdout.String(), stderr.String()) } } From 0c05b999b7b897941af736cb064822f697dd73fc Mon Sep 17 00:00:00 2001 From: merefield Date: Tue, 11 Aug 2026 18:56:32 +0100 Subject: [PATCH 2/2] Guard empty benchmark catalogs --- internal/ui/benchmark.go | 6 +++++- internal/ui/benchmark_test.go | 21 +++++++++++++++++++++ internal/ui/model.go | 4 ++-- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index 332a7f44..8e63f1d5 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -145,7 +145,7 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { } run := []benchmarkControlSegment{ {text: selectedLabel, button: footerButtonBenchmarkSelected, enabled: !running && len(tasks) > 0}, - {text: allLabel, button: footerButtonBenchmarkAll, enabled: !running && m.benchmarkCombinations > 0}, + {text: allLabel, button: footerButtonBenchmarkAll, enabled: benchmarkRunAllAvailable(running, m.benchmarkCombinations, len(tasks))}, } filter := []benchmarkControlSegment{ {text: "SHOW //", enabled: true}, @@ -156,6 +156,10 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { return [][]benchmarkControlSegment{selector, run, filter} } +func benchmarkRunAllAvailable(running bool, combinations, taskCount int) bool { + return !running && combinations > 0 && taskCount > 0 +} + func (m Model) renderBenchmarkStatus(width, height int, colors palette) string { state := "READY" detail := "USES QUOTA // EVERY VISIBLE MODEL + EFFORT" diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index b658c35b..70d24509 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -325,6 +325,27 @@ func TestBenchmarkTaskSelectorRunAllGuardAndExactTurnCount(t *testing.T) { } } +func TestBenchmarkRunAllAvailabilityRequiresTasksAndCombinations(t *testing.T) { + for _, test := range []struct { + name string + running bool + combinations int + tasks int + want bool + }{ + {name: "available", combinations: 2, tasks: 4, want: true}, + {name: "no tasks", combinations: 2}, + {name: "no combinations", tasks: 4}, + {name: "already running", running: true, combinations: 2, tasks: 4}, + } { + t.Run(test.name, func(t *testing.T) { + if got := benchmarkRunAllAvailable(test.running, test.combinations, test.tasks); got != test.want { + t.Fatalf("benchmarkRunAllAvailable(%v, %d, %d) = %v, want %v", test.running, test.combinations, test.tasks, got, test.want) + } + }) + } +} + func TestBenchmarkPassFailFilterButtonsAndHotkey(t *testing.T) { model := Model{ width: 100, height: 30, meterStyle: styleBenchmark, benchmarkState: benchmarkFinished, diff --git a/internal/ui/model.go b/internal/ui/model.go index d9b371f8..aa53e300 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -497,7 +497,8 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { } } case footerButtonBenchmarkAll: - if m.meterStyle == styleBenchmark && m.benchmarkState != benchmarkRunning && m.benchmarkCombinations > 0 { + tasks := codex.BenchmarkTasks() + if m.meterStyle == styleBenchmark && benchmarkRunAllAvailable(m.benchmarkState == benchmarkRunning, m.benchmarkCombinations, len(tasks)) { if !m.benchmarkAllArmed { m.benchmarkAllArmed = true m.benchmarkConfirmSequence++ @@ -505,7 +506,6 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { return m, tea.Tick(5*time.Second, func(time.Time) tea.Msg { return benchmarkConfirmExpiredMsg{sequence: sequence} }) } m.benchmarkAllArmed = false - tasks := codex.BenchmarkTasks() ids := make([]codex.BenchmarkTaskID, 0, len(tasks)) for _, task := range tasks { ids = append(ids, task.ID)