From f8b4f417b92f4381cf8e8f7ac759ac2d67dcb082 Mon Sep 17 00:00:00 2001 From: merefield Date: Tue, 11 Aug 2026 20:49:16 +0100 Subject: [PATCH 1/9] Refine responsive interface and click surfaces --- README.md | 76 +++++++++++++++++++++++++++----- internal/ui/benchmark.go | 71 +++++++++++++++++++++++------ internal/ui/benchmark_test.go | 75 +++++++++++++++++++++++++++---- internal/ui/meters.go | 48 +++++++++++++++----- internal/ui/model.go | 2 +- internal/ui/model_test.go | 7 +++ internal/ui/monitor.go | 32 +++++++++----- internal/ui/monitor_test.go | 46 ++++++++++++++++++- internal/ui/tabs_test.go | 15 +++++++ internal/ui/view.go | 26 ++++++++++- internal/ui/view_test.go | 29 +++++++++++- internal/version/version.go | 2 +- internal/version/version_test.go | 4 +- main_test.go | 2 +- 14 files changed, 371 insertions(+), 64 deletions(-) diff --git a/README.md b/README.md index 42da14ca..c4fe91f2 100644 --- a/README.md +++ b/README.md @@ -306,15 +306,71 @@ exposes no filesystem, process, network, clock, or environment capabilities to submitted code. Restricted return types and bounded result sizes add further containment. +#### Interpreting token and API-equivalent figures + 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 +events. This event is cumulative for a thread; because Codexometer creates a +fresh ephemeral thread containing one benchmark turn, its final total is used +as that trial's token count. The event is matched to both the expected thread +and turn IDs so activity from another trial or Codex session is not included. +The displayed total includes all reported input tokens—including cached input +and cache-write input—and all reported output tokens. Reasoning tokens are +already included in the output-token total and are not added a second time. + +`API EQ` is an estimated **standard, short-context, text-token API equivalent**, +not a bill, a ChatGPT subscription charge, or a prediction of how much account +quota the turn consumed. Codexometer separates ordinary input, cached input, +cache-write input, and output, then applies the per-million-token prices known +to this Codexometer release. An unknown model, or usage in a token class for +which no price was published when the release was built, displays `N/A` rather +than inheriting or guessing a price. Pricing can change after a binary is +released; consult the [official OpenAI API pricing page](https://developers.openai.com/api/docs/pricing) -for the current source values. +for current values. + +The figures are useful for comparing these particular observed trials, but +they have important limitations: + +- They do not reveal the private quota-weighting rules used by ChatGPT plans, + and should not be converted into quota percentages or treated as dollars + actually charged. +- Prompt-cache state can depend on earlier activity and benchmark order. A + later trial may receive cheaper cached input or incur a cache write that an + otherwise identical trial would not, so observed API-equivalent cost is not + a cache-neutral ranking. +- Current costing applies short-context rates to the cumulative trial usage. + It does not implement long-context price thresholds or preserve a separate + price calculation for every upstream response within a turn. +- If Codex reroutes a turn, the accumulated usage is priced using the final + reported model. A turn that actually spans differently priced models cannot + be reconstructed exactly from the cumulative event alone. +- Benchmark instructions prohibit tool use, but that restriction is not yet + verified from the event stream. Any separately billed tool fee would not be + represented by the text-token calculation. +- The current implementation does not distinguish a missing usage event from + a genuine all-zero usage report. A zero-token or zero-cost row should therefore + be treated as unavailable telemetry, not as evidence that a completed turn + was free. +- Model-specific Codex instructions and tool descriptions are part of reported + input usage. That is appropriate when comparing the real Codex experience, + but it is not a measurement of the challenge prompt in isolation. + +PASS/FAIL evaluation is independent of these measurements: incomplete or +ambiguous token telemetry does not make an incorrect program pass, and a valid +program can still have an unavailable or approximate cost. + +#### Future measurement hardening + +Future work should make the accounting fail closed: record whether a matching +usage event was observed, validate that every token field is non-negative and +internally consistent, and display `N/A` whenever those checks fail. Capturing +per-response usage would allow long-context thresholds and model reroutes to be +priced correctly. Tool-call detection should invalidate the cost estimate when +a separately priced tool is used. Finally, reporting both observed cost and a +cache-neutral equivalent—or running balanced warm-up and repeated trials—would +make model/effort comparisons less sensitive to cache order. These changes +would improve measurement confidence without changing the deterministic +PASS/FAIL verifier. ## Options @@ -361,9 +417,9 @@ need Go or Codexometer's source dependencies. ## Versioning -Codexometer follows semantic versioning; the current source version is `v0.2.0`. The Git tag is +Codexometer follows semantic versioning; the current source version is `v0.2.1`. 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.2.0`; direct source builds +with `go install github.com/merefield/codexometer@v0.2.1`; 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: @@ -376,7 +432,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.2.0" . +go build -ldflags="-s -w -X github.com/merefield/codexometer/internal/version.Fallback=0.2.1" . ``` ## How refresh works diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index 8e63f1d5..32cecb8a 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -14,12 +14,15 @@ import ( ) type benchmarkGeometry struct { - width int - height int - topHeight int - tableHeight int - controlsWidth int - statusWidth int + width int + height int + topHeight int + tableHeight int + controlsHeight int + statusHeight int + controlsWidth int + statusWidth int + stacked bool } type benchmarkSortColumn int @@ -57,18 +60,43 @@ func layoutBenchmarkArea(width, height int) benchmarkGeometry { topHeight = max(height/2, 2) } controlsWidth := min(max(width*3/5, 38), max(width-1, 1)) + statusWidth := max(width-controlsWidth-1, 1) + // A framed status panel needs enough room for useful content. Once that is no + // longer true, stack it below the controls instead of letting Lip Gloss grow + // the row beyond the terminal width. + if statusWidth < 12 { + controlsHeight := min(5, height) + statusHeight := 0 + if height-controlsHeight >= 6 { + statusHeight = min(4, height-controlsHeight-3) + } + return benchmarkGeometry{ + width: width, height: height, topHeight: controlsHeight + statusHeight, + tableHeight: max(height-controlsHeight-statusHeight, 1), + controlsHeight: controlsHeight, statusHeight: statusHeight, + controlsWidth: width, statusWidth: width, stacked: true, + } + } return benchmarkGeometry{ width: width, height: height, topHeight: topHeight, - tableHeight: max(height-topHeight-1, 1), - controlsWidth: controlsWidth, statusWidth: max(width-controlsWidth-1, 1), + tableHeight: max(height-topHeight, 1), + controlsHeight: topHeight, statusHeight: topHeight, + controlsWidth: controlsWidth, statusWidth: statusWidth, } } 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) + controls := m.renderBenchmarkControls(layout.controlsWidth, layout.controlsHeight, colors) + top := controls + if layout.statusHeight > 0 { + status := m.renderBenchmarkStatus(layout.statusWidth, layout.statusHeight, colors) + if layout.stacked { + top = lipgloss.JoinVertical(lipgloss.Left, controls, status) + } else { + 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 { @@ -153,6 +181,21 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { {text: "[ PASS ]", button: footerButtonBenchmarkFilterPass, enabled: true, active: m.benchmarkFilter == benchmarkFilterPass}, {text: "[ FAIL ]", button: footerButtonBenchmarkFilterFail, enabled: true, active: m.benchmarkFilter == benchmarkFilterFail}, } + filterWidth := 0 + for index, segment := range filter { + filterWidth += lipgloss.Width(segment.text) + if index > 0 { + filterWidth++ + } + } + if filterWidth > width { + 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} } @@ -214,7 +257,7 @@ func latestBenchmarkFailure(results []codex.BenchmarkResult) string { func (m Model) renderBenchmarkTable(width, height int, colors palette) string { innerWidth := max(width-4, 1) - bodyHeight := max(height-3, 1) + bodyHeight := max(height-2, 1) visibleResults := filterBenchmarkResults(m.benchmarkResults, m.benchmarkFilter) columns := benchmarkTableColumns(innerWidth, m.benchmarkResults) rows := benchmarkTableRows(columns, sortedBenchmarkResults(visibleResults, m.benchmarkSort, m.benchmarkSortDescending)) @@ -534,7 +577,7 @@ func (m Model) benchmarkButtonAt(x, y int) footerButtonID { return footerButtonNone } for line, segments := range m.benchmarkControlLines(max(layout.controlsWidth-4, 1)) { - if localY != line+2 { + if localY != line+1 { continue } segmentX := 2 @@ -556,7 +599,7 @@ func (m Model) benchmarkHeaderAt(x, y int) (benchmarkSortColumn, bool) { dashboard := m.dashboardLayout() geometry := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) tableY := dashboard.meterY + geometry.topHeight - if y != tableY+2 { + if y != tableY+1 { return benchmarkSortNone, false } localX := x - 4 diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index 70d24509..ccda4b1e 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -2,6 +2,7 @@ package ui import ( "context" + "fmt" "strings" "testing" "time" @@ -140,12 +141,12 @@ func TestBenchmarkTableClipsOlderRows(t *testing.T) { }) } output := ansi.Strip(model.renderBenchmarkTable(70, 8, paletteFor(themeBlueSteel))) - if !strings.Contains(output, "ROWS 19-20/20") || lipgloss.Height(output) != 8 { + if !strings.Contains(output, "ROWS 18-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") { + if !strings.Contains(output, "ROWS 14-16/20") { t.Fatalf("scrolled table did not expose older rows:\n%s", output) } } @@ -182,10 +183,10 @@ func TestBenchmarkHeadingButtonsSortAndReverse(t *testing.T) { } dashboard := model.dashboardLayout() geometry := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) - columns := benchmarkTableColumns(max(dashboard.contentWidth-4, 1), model.benchmarkResults) + headerX, headerY := renderedTextCoordinates(t, model, "[MODEL]") mouse := tea.MouseMsg{ - X: 4 + columns[0].x + 1, - Y: dashboard.meterY + geometry.topHeight + 2, + X: headerX, + Y: headerY, Action: tea.MouseActionMotion, } updated, command := model.Update(mouse) @@ -215,6 +216,47 @@ func TestBenchmarkHeadingButtonsSortAndReverse(t *testing.T) { } } +func TestBenchmarkRenderedClickSurfacesMatchHitTestingAcrossSizes(t *testing.T) { + for _, size := range []struct{ width, height int }{ + {40, 16}, {40, 24}, {45, 24}, {60, 24}, {80, 24}, {100, 30}, {160, 45}, + } { + t.Run(fmt.Sprintf("%dx%d", size.width, size.height), func(t *testing.T) { + model := Model{ + snapshot: codex.DemoSnapshot(), width: size.width, height: size.height, + meterStyle: styleBenchmark, benchmarkCombinations: 3, + } + dashboard := model.dashboardLayout() + geometry := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) + for _, segments := range model.benchmarkControlLines(max(geometry.controlsWidth-4, 1)) { + for _, segment := range segments { + if segment.button == footerButtonNone || !segment.enabled { + continue + } + x, y := renderedTextStart(t, model, segment.text) + for offset := 0; offset < lipgloss.Width(segment.text); offset++ { + if got := model.benchmarkButtonAt(x+offset, y); got != segment.button { + t.Errorf("rendered %q cell %d hit button %d, want %d", segment.text, offset, got, segment.button) + } + } + } + } + + tableTitleX, tableTitleY := renderedTextStart(t, model, "RESULT MATRIX") + _ = tableTitleX + headerY := tableTitleY + 1 + columns := benchmarkTableColumns(max(dashboard.contentWidth-4, 1), model.benchmarkResults) + for _, column := range columns { + for offset := 0; offset < column.width; offset++ { + x := 4 + column.x + offset + if got, ok := model.benchmarkHeaderAt(x, headerY); !ok || got != column.sort { + t.Errorf("rendered heading %q cell %d at %d,%d hit (%d,%v)", column.title, offset, x, headerY, got, ok) + } + } + } + }) + } +} + 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}, @@ -375,15 +417,30 @@ func benchmarkControlCoordinates(t *testing.T, model Model, target footerButtonI 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 _, segments := range model.benchmarkControlLines(max(geometry.controlsWidth-4, 1)) { for _, segment := range segments { if segment.button == target { - return x + max(lipgloss.Width(segment.text)/2, 0), dashboard.meterY + line + 2 + return renderedTextCoordinates(t, model, segment.text) } - x += lipgloss.Width(segment.text) + 1 } } t.Fatalf("benchmark control %d not found", target) return 0, 0 } + +func renderedTextCoordinates(t *testing.T, model Model, text string) (int, int) { + t.Helper() + x, y := renderedTextStart(t, model, text) + return x + max(lipgloss.Width(text)/2, 0), y +} + +func renderedTextStart(t *testing.T, model Model, text string) (int, int) { + t.Helper() + for y, line := range strings.Split(ansi.Strip(model.View()), "\n") { + if byteX := strings.Index(line, text); byteX >= 0 { + return lipgloss.Width(line[:byteX]), y + } + } + t.Fatalf("rendered text %q not found", text) + return 0, 0 +} diff --git a/internal/ui/meters.go b/internal/ui/meters.go index 527df5c8..fb18d730 100644 --- a/internal/ui/meters.go +++ b/internal/ui/meters.go @@ -144,9 +144,11 @@ func renderMeterArea(width, height int, meter codex.Meter, style meterStyleID, c } reset = ansi.Truncate(reset, innerWidth, "") + bodyHeight := 0 visualHeight := 0 if height > 0 { - visualHeight = max(height-6, 1) + bodyHeight = max(height-2, 1) + visualHeight = max(bodyHeight-3, 1) } now := time.Now() visual := renderVisualizationSized(innerWidth, visualHeight, used, style, color, colors) @@ -161,6 +163,17 @@ func renderMeterArea(width, height int, meter codex.Meter, style meterStyleID, c resetGauge = renderReverseResetGauge(innerWidth, gaugeWidth, meter.Window, now, reset, color, colors) } bodyParts := []string{stats, visual, resetGauge} + if height > 0 && bodyHeight < 4 { + switch bodyHeight { + case 1: + bodyParts = []string{visual} + case 2: + bodyParts = []string{stats, visual} + case 3: + resetLine := strings.Split(resetGauge, "\n")[0] + bodyParts = []string{stats, visual, resetLine} + } + } body := strings.Join(bodyParts, "\n") title := meter.Name if meter.Bucket != "codex" { @@ -282,7 +295,13 @@ func renderPie(width, used int, color lipgloss.Color, colors palette) string { } func renderPieSized(width, height, used int, color lipgloss.Color, colors palette) string { - cellWidth, cellHeight := radialCanvasSize(width, height, 11) + const legendWidth = 11 + showLegend := width >= legendWidth+8 + reservedLegendWidth := 0 + if showLegend { + reservedLegendWidth = legendWidth + } + cellWidth, cellHeight := radialCanvasSize(width, height, reservedLegendWidth) pixelWidth := cellWidth * 2 pixelHeight := cellHeight * 4 centerX := float64(pixelWidth-1) / 2 @@ -327,15 +346,18 @@ func renderPieSized(width, height, used int, color lipgloss.Color, colors palett } rows = append(rows, row.String()) } - label := []string{ - colors.dimmed().Render("BRAILLE PIE"), - lipgloss.NewStyle().Bold(true).Foreground(color).Render(fmt.Sprintf(" %3d%%", used)), - colors.dimmed().Render("CLOCKWISE"), - } - label = verticallyCenterLines(label, cellHeight) pie := strings.Join(rows, "\n") - legend := strings.Join(label, "\n") - visual := lipgloss.JoinHorizontal(lipgloss.Center, pie, " ", legend) + visual := pie + if showLegend { + label := []string{ + colors.dimmed().Render("BRAILLE PIE"), + lipgloss.NewStyle().Bold(true).Foreground(color).Render(fmt.Sprintf(" %3d%%", used)), + colors.dimmed().Render("CLOCKWISE"), + } + label = verticallyCenterLines(label, cellHeight) + legend := strings.Join(label, "\n") + visual = lipgloss.JoinHorizontal(lipgloss.Center, pie, " ", legend) + } if height > 0 { return lipgloss.Place(width, height, lipgloss.Center, lipgloss.Center, visual) } @@ -350,7 +372,11 @@ func brailleDot(x, y int) int { } func radialCanvasSize(width, height, legendWidth int) (int, int) { - availableWidth := max(width-legendWidth-5, 2) + overhead := 0 + if legendWidth > 0 { + overhead = legendWidth + 5 + } + availableWidth := max(width-overhead, 2) if height <= 0 { height = max((availableWidth+1)/2, 1) } diff --git a/internal/ui/model.go b/internal/ui/model.go index aa53e300..0ddd1cae 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -580,7 +580,7 @@ func (m Model) dashboardLayout() dashboardGeometry { } const statusHeight = 1 const tabsHeight = 1 - const framedErrorHeight = 4 + const framedErrorHeight = 3 const footerHeight = 2 extraHeight := 0 if m.err != nil { diff --git a/internal/ui/model_test.go b/internal/ui/model_test.go index 3241b905..776f8106 100644 --- a/internal/ui/model_test.go +++ b/internal/ui/model_test.go @@ -226,6 +226,13 @@ func TestFooterHitGeometryMatchesRenderedButtonsAcrossSizes(t *testing.T) { if got := model.footerButtonAt(mouse.X, mouse.Y); got != id { t.Errorf("hit button %d, want %d", got, id) } + button, _ := footerButtonByID(model, id) + startX := mouse.X - len(button.label)/2 + for offset := range len(button.label) { + if got := model.footerButtonAt(startX+offset, mouse.Y); got != id { + t.Errorf("button %d cell %d hit %d", id, offset, got) + } + } } }) } diff --git a/internal/ui/monitor.go b/internal/ui/monitor.go index e9797d8a..89908171 100644 --- a/internal/ui/monitor.go +++ b/internal/ui/monitor.go @@ -77,8 +77,15 @@ func (m Model) renderMonitorArea(width, height int, colors palette) monitorView layout := layoutMonitorArea(width, height) 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) + goLabel, stopLabel := "(S)TART", "STO(P)" + if layout.buttonWidths[0] < lipgloss.Width(goLabel)+2 { + goLabel = "(S)" + } + if layout.buttonWidths[1] < lipgloss.Width(stopLabel)+2 { + stopLabel = "(P)" + } + goButton := m.renderMonitorButton(layout.buttonWidths[0], layout.topHeight, goLabel, footerButtonMonitorGo, m.monitorGoEnabled(), colors) + stopButton := m.renderMonitorButton(layout.buttonWidths[1], layout.topHeight, stopLabel, footerButtonMonitorStop, m.monitorStopEnabled(), colors) controls := lipgloss.JoinHorizontal(lipgloss.Top, goButton, strings.Repeat(" ", layout.gap), stopButton) top := lipgloss.JoinHorizontal(lipgloss.Top, readout, strings.Repeat(" ", layout.gap), controls) graph := m.renderMonitorGraph(layout.width, layout.graphHeight, colors) @@ -126,25 +133,26 @@ func (m Model) renderMonitorReadout(width, height int, colors palette) string { stateColor = colors.danger } } + innerWidth := max(width-4, 1) lines := []string{ - lipgloss.NewStyle().Bold(true).Foreground(stateColor).Render(state) + - lipgloss.NewStyle().Bold(true).Foreground(colors.primary).Render(" // "+formatTokens(total)+" TOKENS"), - colors.dimmed().Render(ansi.Truncate(hint, max(width-4, 1), "")), + ansi.Truncate(lipgloss.NewStyle().Bold(true).Foreground(stateColor).Render(state)+ + lipgloss.NewStyle().Bold(true).Foreground(colors.primary).Render(" // "+formatTokens(total)+" TOKENS"), innerWidth, ""), + colors.dimmed().Render(ansi.Truncate(hint, innerWidth, "")), } if height >= 6 { - lines = append(lines, colors.label().Render(fmt.Sprintf("ELAPSED %s // RATE %s/MIN", formatElapsed(elapsed), formatTokens(rate)))) + lines = append(lines, colors.label().Render(ansi.Truncate(fmt.Sprintf("ELAPSED %s // RATE %s/MIN", formatElapsed(elapsed), formatTokens(rate)), innerWidth, ""))) } if height >= 8 && !m.monitorStartedAt.IsZero() { - lines = append(lines, colors.dimmed().Render(fmt.Sprintf("START %s // NOW %s", formatTokens(m.monitorBaseline), formatTokens(m.monitorLatest)))) + lines = append(lines, colors.dimmed().Render(ansi.Truncate(fmt.Sprintf("START %s // NOW %s", formatTokens(m.monitorBaseline), formatTokens(m.monitorLatest)), innerWidth, ""))) } if height >= 10 { - lines = append(lines, colors.dimmed().Render(fmt.Sprintf("SAMPLES %d // NEXT %s", len(m.monitorSamples), m.monitorNextLabel()))) + lines = append(lines, colors.dimmed().Render(ansi.Truncate(fmt.Sprintf("SAMPLES %d // NEXT %s", len(m.monitorSamples), m.monitorNextLabel()), innerWidth, ""))) last := "--:--" if !m.monitorLastActivity.IsZero() { last = compactDuration(time.Since(m.monitorLastActivity)) } 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), ""))) + lines = append(lines, colors.dimmed().Render(ansi.Truncate(telemetry, innerWidth, ""))) } return frameSized(width, max(height-2, 1), "SESSION READOUT", strings.Join(lines, "\n"), colors.primary, colors) } @@ -176,7 +184,7 @@ func (m Model) renderMonitorButton(width, height int, label string, id footerBut func (m Model) renderMonitorGraph(width, height int, colors palette) string { innerWidth := max(width-4, 1) - plotHeight := max(height-3, 1) + plotHeight := max(height-2, 1) const sampleWidth = 2 // one block-wide bar plus one cell of breathing room samples := m.monitorSamples visibleSamples := max((innerWidth+1)/sampleWidth, 1) @@ -263,10 +271,10 @@ func (m Model) monitorButtonAt(x, y int) footerButtonID { dashboard := m.dashboardLayout() area := layoutMonitorArea(dashboard.contentWidth, dashboard.meterHeight) localX, localY := x-2, y-dashboard.meterY - if area.goRect.contains(localX, localY) { + if m.monitorGoEnabled() && area.goRect.contains(localX, localY) { return footerButtonMonitorGo } - if area.stopRect.contains(localX, localY) { + if m.monitorStopEnabled() && area.stopRect.contains(localX, localY) { return footerButtonMonitorStop } return footerButtonNone diff --git a/internal/ui/monitor_test.go b/internal/ui/monitor_test.go index dbcfc270..125eaeea 100644 --- a/internal/ui/monitor_test.go +++ b/internal/ui/monitor_test.go @@ -207,7 +207,7 @@ func TestMonitorLargeButtonsAreClickableAcrossTheirBoxes(t *testing.T) { for _, test := range []struct { rect monitorRect want footerButtonID - }{{geometry.goRect, footerButtonMonitorGo}, {geometry.stopRect, footerButtonMonitorStop}} { + }{{geometry.goRect, footerButtonMonitorGo}, {geometry.stopRect, footerButtonNone}} { // 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 @@ -215,8 +215,18 @@ func TestMonitorLargeButtonsAreClickableAcrossTheirBoxes(t *testing.T) { t.Errorf("button hit = %d, want %d at %d,%d", got, test.want, x, y) } } + model.monitorState = monitorRunning + stopX := originX + geometry.stopRect.x + 1 + stopY := originY + geometry.stopRect.y + 1 hoverX := originX + geometry.goRect.x + 1 hoverY := originY + geometry.goRect.y + 1 + if got := model.monitorButtonAt(stopX, stopY); got != footerButtonMonitorStop { + t.Errorf("enabled Stop button hit = %d, want %d", got, footerButtonMonitorStop) + } + if got := model.monitorButtonAt(hoverX, hoverY); got != footerButtonNone { + t.Errorf("disabled Start button hit = %d, want none", got) + } + model.monitorState = monitorIdle updated, command := model.Update(tea.MouseMsg{X: hoverX, Y: hoverY, Action: tea.MouseActionMotion}) model = updated.(Model) if command != nil || model.hoveredButton != footerButtonMonitorGo { @@ -238,6 +248,40 @@ func TestMonitorLargeButtonsAreClickableAcrossTheirBoxes(t *testing.T) { } } +func TestMonitorButtonBoxesMatchEnabledHitSurfacesAcrossSizes(t *testing.T) { + for _, size := range []struct{ width, height int }{{40, 16}, {40, 24}, {60, 24}, {100, 36}, {160, 45}} { + for _, state := range []monitorState{monitorIdle, monitorRunning} { + model := Model{ + snapshot: codex.DemoSnapshot(), width: size.width, height: size.height, + meterStyle: styleMonitor, monitorState: state, + } + dashboard := model.dashboardLayout() + geometry := layoutMonitorArea(dashboard.contentWidth, dashboard.meterHeight) + for _, button := range []struct { + rect monitorRect + id footerButtonID + enabled bool + }{ + {geometry.goRect, footerButtonMonitorGo, model.monitorGoEnabled()}, + {geometry.stopRect, footerButtonMonitorStop, model.monitorStopEnabled()}, + } { + want := footerButtonNone + if button.enabled { + want = button.id + } + for localY := button.rect.y; localY < button.rect.y+button.rect.height; localY++ { + for localX := button.rect.x; localX < button.rect.x+button.rect.width; localX++ { + got := model.monitorButtonAt(2+localX, dashboard.meterY+localY) + if got != want { + t.Errorf("%dx%d state %d button %d cell %d,%d hit %d, want %d", size.width, size.height, state, button.id, localX, localY, got, want) + } + } + } + } + } + } +} + func TestMonitorGraphIntroducesBarsOnRightAndScrollsThemLeft(t *testing.T) { model := Model{monitorState: monitorRunning, monitorSamples: []monitorSample{{intervalTokens: 10}}} first := ansi.Strip(model.renderMonitorGraph(40, 10, paletteFor(themeHacker))) diff --git a/internal/ui/tabs_test.go b/internal/ui/tabs_test.go index 33eccee1..8a8400a6 100644 --- a/internal/ui/tabs_test.go +++ b/internal/ui/tabs_test.go @@ -73,6 +73,21 @@ func TestStyleTabsSupportHoverClickAndPulse(t *testing.T) { } } +func TestEveryRenderedTabCellIsClickableAcrossWidths(t *testing.T) { + for _, width := range []int{40, 45, 60, 80, 100, 160} { + model := Model{snapshot: codex.DemoSnapshot(), width: width, height: 24} + layout := model.dashboardLayout() + tabs, _ := styleTabLayout(layout.contentWidth, false) + for _, tab := range tabs { + for offset := 0; offset < tab.width; offset++ { + if got, ok := model.styleTabAt(2+tab.x+offset, layout.tabsY); !ok || got != tab.style { + t.Errorf("width %d tab %q cell %d hit (%d,%v)", width, tab.label, offset, got, ok) + } + } + } + } +} + func TestMonitorTabShowsPulsingRecordingDotWhileAnotherTabIsActive(t *testing.T) { model := Model{meterStyle: styleBars, monitorState: monitorRunning} colors := paletteFor(themeHacker) diff --git a/internal/ui/view.go b/internal/ui/view.go index b2cb65d7..6fd28d5b 100644 --- a/internal/ui/view.go +++ b/internal/ui/view.go @@ -162,17 +162,41 @@ func frame(width int, title, body string, color lipgloss.Color, colors palette) } func frameSized(width, height int, title, body string, color lipgloss.Color, colors palette) string { + width = max(width, 1) style := lipgloss.NewStyle(). Width(max(width-2, 1)). Padding(0, 1). Border(lipgloss.RoundedBorder()). + BorderTop(false). BorderForeground(color). Foreground(colors.primary). Background(colors.background) if height > 0 { style = style.Height(height) } - return style.Render("[ " + title + " ]\n" + body) + return renderFrameTitle(width, title, color, colors) + "\n" + style.Render(body) +} + +func renderFrameTitle(width int, title string, color lipgloss.Color, colors palette) string { + width = max(width, 1) + border := lipgloss.RoundedBorder() + borderStyle := lipgloss.NewStyle().Foreground(color).Background(colors.background) + if width == 1 { + return borderStyle.Render(border.Top) + } + if width == 2 { + return borderStyle.Render(border.TopLeft + border.TopRight) + } + + title = strings.TrimSpace(ansi.Truncate(title, max(width-6, 0), "")) + if title == "" { + return borderStyle.Render(border.TopLeft + strings.Repeat(border.Top, width-2) + border.TopRight) + } + prefix := border.TopLeft + border.Top + " " + suffixWidth := max(width-lipgloss.Width(prefix)-lipgloss.Width(title)-1, 1) + suffix := " " + strings.Repeat(border.Top, suffixWidth-1) + border.TopRight + titleStyle := lipgloss.NewStyle().Bold(true).Foreground(color).Background(colors.background) + return borderStyle.Render(prefix) + titleStyle.Render(title) + borderStyle.Render(suffix) } func countdown(at time.Time) string { diff --git a/internal/ui/view_test.go b/internal/ui/view_test.go index 5233345a..f19e978b 100644 --- a/internal/ui/view_test.go +++ b/internal/ui/view_test.go @@ -49,7 +49,7 @@ func TestViewRendersEveryThemeAndStyleWithinStandardTerminal(t *testing.T) { } func TestViewReflowsAcrossTerminalDimensions(t *testing.T) { - sizes := []struct{ width, height int }{{80, 24}, {120, 40}, {200, 60}} + sizes := []struct{ width, height int }{{40, 16}, {40, 24}, {45, 24}, {60, 24}, {80, 24}, {120, 40}, {200, 60}} for _, size := range sizes { for style := styleBars; style < styleCount; style++ { model := Model{ @@ -100,6 +100,33 @@ func TestStatusAndFooterKeepOnlyEssentialMetadata(t *testing.T) { } } +func TestFrameTitlesAreIntegratedIntoBorderInsteadOfButtonBrackets(t *testing.T) { + colors := paletteFor(themeHacker) + output := ansi.Strip(frameSized(36, 3, "SESSION READOUT", "BODY", colors.primary, colors)) + lines := strings.Split(output, "\n") + if len(lines) != 5 { + t.Fatalf("frame height = %d, want 5:\n%s", len(lines), output) + } + if !strings.HasPrefix(lines[0], "╭─ SESSION READOUT ") || !strings.HasSuffix(lines[0], "╮") { + t.Fatalf("title was not integrated into the top border: %q", lines[0]) + } + if strings.Contains(output, "[ SESSION READOUT ]") { + t.Fatalf("frame title still looks like a button:\n%s", output) + } + for index, line := range lines { + if width := lipgloss.Width(line); width != 36 { + t.Errorf("line %d width = %d, want 36: %q", index, width, line) + } + } + + narrow := ansi.Strip(frameSized(5, 1, "TITLE TOO LONG", "X", colors.primary, colors)) + for index, line := range strings.Split(narrow, "\n") { + if width := lipgloss.Width(line); width != 5 { + t.Errorf("narrow line %d width = %d, want 5: %q", index, width, line) + } + } +} + func TestPieViewPlacesQuotaWindowsSideBySide(t *testing.T) { model := Model{ snapshot: codex.DemoSnapshot(), diff --git a/internal/version/version.go b/internal/version/version.go index c6ccd8ee..19a4aa90 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -11,7 +11,7 @@ import ( // checkout. Release automation may override it with: // // -X github.com/merefield/codexometer/internal/version.Fallback=1.2.3 -var Fallback = "0.2.0" +var Fallback = "0.2.1" // Current returns the module version embedded by Go for tagged installs, or // Fallback for ordinary source builds. The leading tag prefix is omitted so diff --git a/internal/version/version_test.go b/internal/version/version_test.go index e2c53bb2..6f62b0af 100644 --- a/internal/version/version_test.go +++ b/internal/version/version_test.go @@ -4,8 +4,8 @@ import "testing" func TestCurrentReportsMaintainedFallbackForSourceBuild(t *testing.T) { got := Current() - if got != "0.2.0" { - t.Fatalf("Current() = %q, want 0.2.0", got) + if got != "0.2.1" { + t.Fatalf("Current() = %q, want 0.2.1", got) } } diff --git a/main_test.go b/main_test.go index 7dab7780..7b77f17c 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.2.0\n" || stderr.Len() != 0 { + if code != 0 || stdout.String() != "codexometer v0.2.1\n" || stderr.Len() != 0 { t.Errorf("flag=%s code=%d stdout=%q stderr=%q", flag, code, stdout.String(), stderr.String()) } } From b060efc57b1c675684b464a4b16aa7c309590e99 Mon Sep 17 00:00:00 2001 From: merefield Date: Tue, 11 Aug 2026 20:59:45 +0100 Subject: [PATCH 2/9] Compact benchmark controls --- internal/ui/benchmark.go | 107 ++++++++++++++++++++-------------- internal/ui/benchmark_test.go | 22 ++++++- 2 files changed, 82 insertions(+), 47 deletions(-) diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index 32cecb8a..c7d777cb 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -55,20 +55,19 @@ type benchmarkControlSegment struct { 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) - } + // Controls and status each contain two useful rows. Keep their shared strip + // tight and give the result matrix the remaining vertical space. + topHeight := min(4, height) controlsWidth := min(max(width*3/5, 38), max(width-1, 1)) statusWidth := max(width-controlsWidth-1, 1) // A framed status panel needs enough room for useful content. Once that is no // longer true, stack it below the controls instead of letting Lip Gloss grow // the row beyond the terminal width. if statusWidth < 12 { - controlsHeight := min(5, height) + controlsHeight := min(4, height) statusHeight := 0 - if height-controlsHeight >= 6 { - statusHeight = min(4, height-controlsHeight-3) + if height-controlsHeight >= 8 { + statusHeight = 4 } return benchmarkGeometry{ width: width, height: height, topHeight: controlsHeight + statusHeight, @@ -107,35 +106,39 @@ func (m Model) renderBenchmarkArea(width, height int, colors palette) string { func (m Model) renderBenchmarkControls(width, height int, colors palette) string { innerWidth := max(width-4, 1) - lines := make([]string, 0, 3) + lines := make([]string, 0, 2) 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) - } + lines = append(lines, m.renderBenchmarkSegments(segments, innerWidth, colors)) + } + return frameSized(width, max(height-2, 1), "BENCHMARK CONTROLS", strings.Join(lines, "\n"), colors.primary, colors) +} + +func (m Model) renderBenchmarkSegments(segments []benchmarkControlSegment, width int, colors palette) string { + 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 segment.active { - style = lipgloss.NewStyle().Bold(true).Foreground(colors.background).Background(colors.primary) + if m.flashedButton == segment.button { + style = style.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 + if segment.active { + style = lipgloss.NewStyle().Bold(true).Foreground(colors.background).Background(colors.primary) } - lines = append(lines, strings.Join(parts, " ")+strings.Repeat(" ", max(innerWidth-used, 0))) + parts = append(parts, style.Render(segment.text)) + used += lipgloss.Width(segment.text) } - return frameSized(width, max(height-2, 1), "BENCHMARK CONTROLS", strings.Join(lines, "\n"), colors.primary, colors) + if len(parts) > 1 { + used += len(parts) - 1 + } + return strings.Join(parts, " ") + strings.Repeat(" ", max(width-used, 0)) } func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { @@ -175,6 +178,10 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { {text: selectedLabel, button: footerButtonBenchmarkSelected, enabled: !running && len(tasks) > 0}, {text: allLabel, button: footerButtonBenchmarkAll, enabled: benchmarkRunAllAvailable(running, m.benchmarkCombinations, len(tasks))}, } + return [][]benchmarkControlSegment{selector, run} +} + +func (m Model) benchmarkFilterLine(width int) []benchmarkControlSegment { filter := []benchmarkControlSegment{ {text: "SHOW //", enabled: true}, {text: "[ ALL ]", button: footerButtonBenchmarkFilterAll, enabled: true, active: m.benchmarkFilter == benchmarkFilterAll}, @@ -196,7 +203,7 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { {text: "[FAIL]", button: footerButtonBenchmarkFilterFail, enabled: true, active: m.benchmarkFilter == benchmarkFilterFail}, } } - return [][]benchmarkControlSegment{selector, run, filter} + return filter } func benchmarkRunAllAvailable(running bool, combinations, taskCount int) bool { @@ -261,8 +268,11 @@ func (m Model) renderBenchmarkTable(width, height int, colors palette) string { 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)} + lines := []string{m.renderBenchmarkSegments(m.benchmarkFilterLine(innerWidth), innerWidth, colors)} if bodyHeight > 1 { + lines = append(lines, m.renderBenchmarkHeader(columns, colors)) + } + if bodyHeight > 2 { lines = append(lines, colors.dimmed().Render(strings.Repeat("─", innerWidth))) } available := max(bodyHeight-len(lines), 0) @@ -573,22 +583,31 @@ func (m Model) benchmarkButtonAt(x, y int) footerButtonID { dashboard := m.dashboardLayout() layout := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) localX, localY := x-2, y-dashboard.meterY - if localX < 0 || localX >= layout.controlsWidth { + if localX < 0 { return footerButtonNone } - for line, segments := range m.benchmarkControlLines(max(layout.controlsWidth-4, 1)) { - if localY != line+1 { - 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 + if localX < layout.controlsWidth { + for line, segments := range m.benchmarkControlLines(max(layout.controlsWidth-4, 1)) { + if localY == line+1 { + return benchmarkSegmentButtonAt(localX, segments) } - segmentX += segmentWidth + 1 } } + if localX < layout.width && localY == layout.topHeight+1 { + return benchmarkSegmentButtonAt(localX, m.benchmarkFilterLine(max(layout.width-4, 1))) + } + return footerButtonNone +} + +func benchmarkSegmentButtonAt(localX int, segments []benchmarkControlSegment) footerButtonID { + 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 } @@ -599,7 +618,7 @@ func (m Model) benchmarkHeaderAt(x, y int) (benchmarkSortColumn, bool) { dashboard := m.dashboardLayout() geometry := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) tableY := dashboard.meterY + geometry.topHeight - if y != tableY+1 { + if y != tableY+2 { return benchmarkSortNone, false } localX := x - 4 diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index ccda4b1e..ad88070f 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -141,12 +141,12 @@ func TestBenchmarkTableClipsOlderRows(t *testing.T) { }) } output := ansi.Strip(model.renderBenchmarkTable(70, 8, paletteFor(themeBlueSteel))) - if !strings.Contains(output, "ROWS 18-20/20") || lipgloss.Height(output) != 8 { + 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 14-16/20") { + if !strings.Contains(output, "ROWS 15-16/20") { t.Fatalf("scrolled table did not expose older rows:\n%s", output) } } @@ -240,10 +240,21 @@ func TestBenchmarkRenderedClickSurfacesMatchHitTestingAcrossSizes(t *testing.T) } } } + for _, segment := range model.benchmarkFilterLine(max(dashboard.contentWidth-4, 1)) { + if segment.button == footerButtonNone || !segment.enabled { + continue + } + x, y := renderedTextStart(t, model, segment.text) + for offset := 0; offset < lipgloss.Width(segment.text); offset++ { + if got := model.benchmarkButtonAt(x+offset, y); got != segment.button { + t.Errorf("rendered matrix filter %q cell %d hit button %d, want %d", segment.text, offset, got, segment.button) + } + } + } tableTitleX, tableTitleY := renderedTextStart(t, model, "RESULT MATRIX") _ = tableTitleX - headerY := tableTitleY + 1 + headerY := tableTitleY + 2 columns := benchmarkTableColumns(max(dashboard.contentWidth-4, 1), model.benchmarkResults) for _, column := range columns { for offset := 0; offset < column.width; offset++ { @@ -424,6 +435,11 @@ func benchmarkControlCoordinates(t *testing.T, model Model, target footerButtonI } } } + for _, segment := range model.benchmarkFilterLine(max(dashboard.contentWidth-4, 1)) { + if segment.button == target { + return renderedTextCoordinates(t, model, segment.text) + } + } t.Fatalf("benchmark control %d not found", target) return 0, 0 } From 4b5a987f27f32a066638d9a40ba95ac77f7479ed Mon Sep 17 00:00:00 2001 From: merefield Date: Tue, 11 Aug 2026 21:03:29 +0100 Subject: [PATCH 3/9] Restore benchmark trial detail row --- internal/ui/benchmark.go | 12 ++++++------ internal/ui/benchmark_test.go | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index c7d777cb..a9b03d1a 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -55,9 +55,9 @@ type benchmarkControlSegment struct { func layoutBenchmarkArea(width, height int) benchmarkGeometry { width = max(width, 1) height = max(height, 1) - // Controls and status each contain two useful rows. Keep their shared strip - // tight and give the result matrix the remaining vertical space. - topHeight := min(4, height) + // Keep three status rows available for runtime state, current trial detail, + // and evaluator limits while still giving the matrix most vertical space. + topHeight := min(5, height) controlsWidth := min(max(width*3/5, 38), max(width-1, 1)) statusWidth := max(width-controlsWidth-1, 1) // A framed status panel needs enough room for useful content. Once that is no @@ -66,8 +66,8 @@ func layoutBenchmarkArea(width, height int) benchmarkGeometry { if statusWidth < 12 { controlsHeight := min(4, height) statusHeight := 0 - if height-controlsHeight >= 8 { - statusHeight = 4 + if height-controlsHeight >= 9 { + statusHeight = 5 } return benchmarkGeometry{ width: width, height: height, topHeight: controlsHeight + statusHeight, @@ -247,7 +247,7 @@ func (m Model) renderBenchmarkStatus(width, height int, colors palette) 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 { + if height >= 5 { 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) diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index ad88070f..ce688fd2 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -53,7 +53,7 @@ func TestBenchmarkViewRendersResponsiveResultsTable(t *testing.T) { }, } 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"} { + for _, want := range []string{"(B) RUN SELECTED", "MERGE RANGES", "SHOW //", "HERMETIC STARLARK", "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) } From 7a3abfe863b62e60a2ed839859cbdcbf9d3c93b0 Mon Sep 17 00:00:00 2001 From: merefield Date: Tue, 11 Aug 2026 21:05:14 +0100 Subject: [PATCH 4/9] Space benchmark control rows --- internal/ui/benchmark.go | 9 ++++++--- internal/ui/benchmark_test.go | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index a9b03d1a..49c1833e 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -64,9 +64,9 @@ func layoutBenchmarkArea(width, height int) benchmarkGeometry { // longer true, stack it below the controls instead of letting Lip Gloss grow // the row beyond the terminal width. if statusWidth < 12 { - controlsHeight := min(4, height) + controlsHeight := min(5, height) statusHeight := 0 - if height-controlsHeight >= 9 { + if height-controlsHeight >= 10 { statusHeight = 5 } return benchmarkGeometry{ @@ -178,7 +178,7 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { {text: selectedLabel, button: footerButtonBenchmarkSelected, enabled: !running && len(tasks) > 0}, {text: allLabel, button: footerButtonBenchmarkAll, enabled: benchmarkRunAllAvailable(running, m.benchmarkCombinations, len(tasks))}, } - return [][]benchmarkControlSegment{selector, run} + return [][]benchmarkControlSegment{selector, nil, run} } func (m Model) benchmarkFilterLine(width int) []benchmarkControlSegment { @@ -617,6 +617,9 @@ func (m Model) benchmarkHeaderAt(x, y int) (benchmarkSortColumn, bool) { } dashboard := m.dashboardLayout() geometry := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) + if geometry.tableHeight <= 3 { + return benchmarkSortNone, false + } tableY := dashboard.meterY + geometry.topHeight if y != tableY+2 { return benchmarkSortNone, false diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index ce688fd2..d48c2fdb 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -64,6 +64,20 @@ func TestBenchmarkViewRendersResponsiveResultsTable(t *testing.T) { if got := lipgloss.Height(output); got != 19 { t.Fatalf("benchmark height = %d, want 19", got) } + controls := ansi.Strip(model.renderBenchmarkControls(58, 5, paletteFor(themeHacker))) + lines := strings.Split(controls, "\n") + selectorLine, runLine := -1, -1 + for index, line := range lines { + if strings.Contains(line, "TASK //") { + selectorLine = index + } + if strings.Contains(line, "(B) RUN SELECTED") { + runLine = index + } + } + if selectorLine < 0 || runLine != selectorLine+2 || strings.Trim(lines[selectorLine+1], " │") != "" { + t.Fatalf("controls do not contain a blank row between Task and Run:\n%s", controls) + } } func TestBenchmarkHotkeyRunsSuiteAndCollectsEvents(t *testing.T) { @@ -255,6 +269,12 @@ func TestBenchmarkRenderedClickSurfacesMatchHitTestingAcrossSizes(t *testing.T) tableTitleX, tableTitleY := renderedTextStart(t, model, "RESULT MATRIX") _ = tableTitleX headerY := tableTitleY + 2 + if geometry.tableHeight <= 3 { + if got, ok := model.benchmarkHeaderAt(4, headerY); ok || got != benchmarkSortNone { + t.Errorf("non-rendered compact heading exposed a click surface: (%d,%v)", got, ok) + } + return + } columns := benchmarkTableColumns(max(dashboard.contentWidth-4, 1), model.benchmarkResults) for _, column := range columns { for offset := 0; offset < column.width; offset++ { From ef7d8757bf3b84fd5c8815adb4abad2029b2cd95 Mon Sep 17 00:00:00 2001 From: merefield Date: Tue, 11 Aug 2026 21:26:49 +0100 Subject: [PATCH 5/9] Harden benchmark telemetry accounting --- README.md | 76 ++++--- internal/codex/benchmark.go | 337 +++++++++++++++++++++++++++---- internal/codex/benchmark_test.go | 240 +++++++++++++++++++++- internal/ui/benchmark.go | 23 ++- internal/ui/benchmark_test.go | 38 +++- 5 files changed, 635 insertions(+), 79 deletions(-) diff --git a/README.md b/README.md index c4fe91f2..9088fadc 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,7 @@ A row is `PASS` only when all of the following are true: 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 +- the turn does not emit a tool-use item; and - none of the supplied inputs are mutated. Any syntax/runtime error, timeout, malformed response, wrong type or value, @@ -308,11 +309,24 @@ containment. #### Interpreting token and API-equivalent figures -Token totals come from the trial thread's live `thread/tokenUsage/updated` -events. This event is cumulative for a thread; because Codexometer creates a -fresh ephemeral thread containing one benchmark turn, its final total is used -as that trial's token count. The event is matched to both the expected thread -and turn IDs so activity from another trial or Codex session is not included. +Codexometer asks the local app-server for its opt-in `rawResponse/completed` +telemetry and, when a complete valid ledger is available, sums the exact usage +reported for each upstream response in the turn. Because that event is an +internal experimental Codex interface, older app-servers may reject or omit it; +Codexometer then falls back automatically to the final cumulative +`thread/tokenUsage/updated` value for the fresh one-turn thread. Both event types +are matched to the expected thread and turn IDs so activity from another trial +or Codex session is not included. + +Before displaying either source, Codexometer checks that all token fields are +non-negative, cached plus cache-write input does not exceed total input, +reasoning output does not exceed output, total equals input plus output, and +cumulative updates never regress. When both complete raw-response and cumulative +telemetry are present, their totals must agree. A valid cumulative total can +stand in for an omitted raw usage payload; otherwise missing, duplicate, or +inconsistent telemetry displays `N/A`. It is never silently converted to zero +or clamped into a plausible value, and the status panel retains the reason. + The displayed total includes all reported input tokens—including cached input and cache-write input—and all reported output tokens. Reasoning tokens are already included in the output-token total and are not added a second time. @@ -321,10 +335,11 @@ already included in the output-token total and are not added a second time. not a bill, a ChatGPT subscription charge, or a prediction of how much account quota the turn consumed. Codexometer separates ordinary input, cached input, cache-write input, and output, then applies the per-million-token prices known -to this Codexometer release. An unknown model, or usage in a token class for -which no price was published when the release was built, displays `N/A` rather -than inheriting or guessing a price. Pricing can change after a binary is -released; consult the +to this Codexometer release. Usage availability and price availability are +tracked separately: a valid token total can still have `API EQ` shown as `N/A` +for an unknown model or a token class whose price was not published when the +release was built. Codexometer does not inherit or guess such a price. Pricing +can change after a binary is released; consult the [official OpenAI API pricing page](https://developers.openai.com/api/docs/pricing) for current values. @@ -338,19 +353,20 @@ they have important limitations: later trial may receive cheaper cached input or incur a cache write that an otherwise identical trial would not, so observed API-equivalent cost is not a cache-neutral ranking. -- Current costing applies short-context rates to the cumulative trial usage. - It does not implement long-context price thresholds or preserve a separate - price calculation for every upstream response within a turn. -- If Codex reroutes a turn, the accumulated usage is priced using the final - reported model. A turn that actually spans differently priced models cannot - be reconstructed exactly from the cumulative event alone. -- Benchmark instructions prohibit tool use, but that restriction is not yet - verified from the event stream. Any separately billed tool fee would not be - represented by the text-token calculation. -- The current implementation does not distinguish a missing usage event from - a genuine all-zero usage report. A zero-token or zero-cost row should therefore - be treated as unavailable telemetry, not as evidence that a completed turn - was free. +- Current costing applies short-context rates to the trial's aggregate usage. + It does not implement long-context price thresholds. Although supported Codex + versions provide per-response usage, the event does not associate a distinct + model price with each response. +- If Codex reroutes a turn, usage is priced using the final reported model. A + turn that actually spans differently priced models cannot be reconstructed + exactly without a response-to-model association. +- Tool use is prohibited for these hermetic trials. If a tool-use item is + observed, the row is forced to `FAIL` and `API EQ` is `N/A`, even when valid + text-token telemetry was also reported. +- Exact raw-response telemetry is an internal experimental app-server facility + and may change independently of Codexometer. The validated cumulative path is + retained for compatibility, but it does not preserve a response-by-response + ledger. - Model-specific Codex instructions and tool descriptions are part of reported input usage. That is appropriate when comparing the real Codex experience, but it is not a measurement of the challenge prompt in isolation. @@ -361,16 +377,12 @@ program can still have an unavailable or approximate cost. #### Future measurement hardening -Future work should make the accounting fail closed: record whether a matching -usage event was observed, validate that every token field is non-negative and -internally consistent, and display `N/A` whenever those checks fail. Capturing -per-response usage would allow long-context thresholds and model reroutes to be -priced correctly. Tool-call detection should invalidate the cost estimate when -a separately priced tool is used. Finally, reporting both observed cost and a -cache-neutral equivalent—or running balanced warm-up and repeated trials—would -make model/effort comparisons less sensitive to cache order. These changes -would improve measurement confidence without changing the deterministic -PASS/FAIL verifier. +Correct long-context and reroute costing still needs each upstream response to +be associated with the model and pricing tier that actually served it, including +the exact threshold semantics. Reporting both observed cost and a cache-neutral +equivalent—or running balanced warm-up and repeated trials—would also make +model/effort comparisons less sensitive to cache order. These improvements +would not change the deterministic PASS/FAIL verifier. ## Options diff --git a/internal/codex/benchmark.go b/internal/codex/benchmark.go index a3b93ac5..358d21ba 100644 --- a/internal/codex/benchmark.go +++ b/internal/codex/benchmark.go @@ -36,20 +36,44 @@ type BenchmarkUsage struct { ReasoningOutputTokens int64 `json:"reasoningOutputTokens"` } +// BenchmarkUsageSource identifies the telemetry used for a benchmark result. +type BenchmarkUsageSource string + +const ( + BenchmarkUsageUnavailable BenchmarkUsageSource = "unavailable" + BenchmarkUsageCumulative BenchmarkUsageSource = "cumulative" + BenchmarkUsageRawResponses BenchmarkUsageSource = "raw-responses" +) + +// BenchmarkResponseUsage is the exact upstream usage for one Responses API +// completion when the current Codex app-server exposes experimental raw events. +type BenchmarkResponseUsage struct { + ResponseID string + Usage BenchmarkUsage +} + // 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 + TaskID BenchmarkTaskID + TaskName string + Model string + DisplayName string + Effort string + ActualModel string + Correct bool + Duration time.Duration + Usage BenchmarkUsage + UsageObserved bool + UsageKnown bool + UsageIssue string + UsageSource BenchmarkUsageSource + ResponseUsage []BenchmarkResponseUsage + CostUSD float64 + CostKnown bool + CostIssue string + ToolUsed bool + ToolType string + Failure string } // BenchmarkEvent incrementally reports discovery, execution, and results. @@ -108,17 +132,18 @@ type benchmarkEnvelope struct { } 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 + 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 + experimentalRawEvents bool } type lockedBuffer struct { @@ -213,6 +238,10 @@ func (c Client) RunBenchmarkSuite(ctx context.Context, taskIDs []BenchmarkTaskID } func startAppServer(ctx context.Context, binary string) (*appServerSession, error) { + return startAppServerWithExperimentalUsage(ctx, binary, true) +} + +func startAppServerWithExperimentalUsage(ctx context.Context, binary string, experimental bool) (*appServerSession, error) { if strings.TrimSpace(binary) == "" { binary = "codex" } @@ -236,14 +265,22 @@ func startAppServer(ctx context.Context, binary string) (*appServerSession, erro 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{}), + experimentalRawEvents: experimental, } go server.readLoop(json.NewDecoder(bufio.NewReader(stdout))) - if _, err := server.call(ctx, "initialize", map[string]any{ + initialize := map[string]any{ "clientInfo": map[string]string{ "name": "codexometer", "title": "Codexometer", "version": version.Current(), }, - }, nil); err != nil { + } + if experimental { + initialize["capabilities"] = map[string]bool{"experimentalApi": true} + } + if _, err := server.call(ctx, "initialize", initialize, nil); err != nil { server.close() + if experimental && experimentalAPIUnsupported(err) { + return startAppServerWithExperimentalUsage(ctx, binary, false) + } return nil, fmt.Errorf("initialize Codex app-server: %w", err) } if err := server.encoder.Encode(map[string]any{"method": "initialized"}); err != nil { @@ -253,6 +290,16 @@ func startAppServer(ctx context.Context, binary string) (*appServerSession, erro return server, nil } +func experimentalAPIUnsupported(err error) bool { + var methodError *benchmarkMethodError + if !errors.As(err, &methodError) { + return false + } + return methodError.code == -32601 || methodError.code == -32602 || + strings.Contains(strings.ToLower(methodError.message), "experimentalapi") || + strings.Contains(strings.ToLower(methodError.message), "experimentalrawevents") +} + func (s *appServerSession) readLoop(decoder *json.Decoder) { for { var envelope benchmarkEnvelope @@ -432,7 +479,7 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma } defer os.RemoveAll(temporary) - threadResult, err := s.call(turnCtx, "thread/start", map[string]any{ + threadParams := map[string]any{ "model": combination.model.Model, "cwd": temporary, "approvalPolicy": "never", @@ -440,7 +487,19 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma "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 s.experimentalRawEvents { + threadParams["experimentalRawEvents"] = true + } + threadResult, err := s.call(turnCtx, "thread/start", threadParams, nil) + if err != nil && s.experimentalRawEvents && experimentalAPIUnsupported(err) { + // Older Codex versions may support the stable benchmark API but not raw + // response telemetry. Retry this thread without the experimental field and + // keep cumulative usage as the compatibility path for the rest of the suite. + s.experimentalRawEvents = false + delete(threadParams, "experimentalRawEvents") + threadResult, err = s.call(turnCtx, "thread/start", threadParams, nil) + } if err != nil { result.Failure = fmt.Sprintf("start thread: %v", err) return result, fatalBenchmarkError(turnCtx, err) @@ -485,6 +544,7 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma } var finalMessage, turnFailure string + telemetry := newBenchmarkTelemetry() completed := false for !completed { _, err = s.readUntilNotification(turnCtx, func(method string, params json.RawMessage) bool { @@ -498,7 +558,17 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma } `json:"tokenUsage"` } if json.Unmarshal(params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID { - result.Usage = event.TokenUsage.Total + telemetry.recordCumulative(event.TokenUsage.Total) + } + case "rawResponse/completed": + var event struct { + ThreadID string `json:"threadId"` + TurnID string `json:"turnId"` + ResponseID string `json:"responseId"` + Usage *BenchmarkUsage `json:"usage"` + } + if json.Unmarshal(params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID { + telemetry.recordRawResponse(event.ResponseID, event.Usage) } case "model/rerouted": var event struct { @@ -509,7 +579,7 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma 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": + case "item/started", "item/completed": var event struct { ThreadID string `json:"threadId"` TurnID string `json:"turnId"` @@ -518,8 +588,13 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma 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 + if json.Unmarshal(params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID { + if benchmarkToolItem(event.Item.Type) && !result.ToolUsed { + result.ToolUsed, result.ToolType = true, event.Item.Type + } + if method == "item/completed" && event.Item.Type == "agentMessage" { + finalMessage = event.Item.Text + } } case "turn/completed": var event struct { @@ -563,11 +638,22 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma } } result.Duration = time.Since(startedAt) - result.CostUSD, result.CostKnown = estimateAPICost(result.ActualModel, result.Usage) + telemetry.apply(&result) + if result.ToolUsed { + result.CostIssue = "tool use prohibited: " + result.ToolType + } else if result.UsageKnown { + result.CostUSD, result.CostKnown, result.CostIssue = estimateAPICostWithIssue(result.ActualModel, result.Usage) + } else { + result.CostIssue = result.UsageIssue + } if turnFailure != "" { result.Failure = turnFailure return result, nil } + if result.ToolUsed { + result.Failure = "tool use prohibited: " + result.ToolType + return result, nil + } code, err := benchmarkCode(finalMessage) if err != nil { result.Failure = err.Error() @@ -581,6 +667,176 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma return result, nil } +type benchmarkTelemetry struct { + cumulative BenchmarkUsage + cumulativeObserved bool + lastCumulative BenchmarkUsage + hasLastCumulative bool + rawResponses []BenchmarkResponseUsage + rawIDs map[string]struct{} + rawObserved bool + rawMissingUsage bool + issue string +} + +func newBenchmarkTelemetry() *benchmarkTelemetry { + return &benchmarkTelemetry{rawIDs: make(map[string]struct{})} +} + +func (t *benchmarkTelemetry) recordCumulative(usage BenchmarkUsage) { + t.cumulativeObserved = true + if issue := validateBenchmarkUsage(usage); issue != "" { + t.setIssue("invalid cumulative usage: " + issue) + } + if t.hasLastCumulative && !benchmarkUsageAtLeast(usage, t.lastCumulative) { + t.setIssue("cumulative usage regressed") + } + t.cumulative = usage + t.lastCumulative = usage + t.hasLastCumulative = true +} + +func (t *benchmarkTelemetry) recordRawResponse(responseID string, usage *BenchmarkUsage) { + t.rawObserved = true + if strings.TrimSpace(responseID) == "" { + t.setIssue("raw response usage omitted response id") + return + } + if _, duplicate := t.rawIDs[responseID]; duplicate { + t.setIssue("duplicate raw response usage: " + responseID) + return + } + t.rawIDs[responseID] = struct{}{} + if usage == nil { + t.rawMissingUsage = true + return + } + if issue := validateBenchmarkUsage(*usage); issue != "" { + t.setIssue("invalid raw response usage: " + issue) + } + t.rawResponses = append(t.rawResponses, BenchmarkResponseUsage{ResponseID: responseID, Usage: *usage}) +} + +func (t *benchmarkTelemetry) apply(result *BenchmarkResult) { + result.UsageObserved = t.cumulativeObserved || t.rawObserved + result.UsageSource = BenchmarkUsageUnavailable + result.ResponseUsage = append([]BenchmarkResponseUsage(nil), t.rawResponses...) + if t.issue != "" { + result.UsageIssue = t.issue + return + } + + rawComplete := len(t.rawResponses) > 0 && !t.rawMissingUsage + if rawComplete { + rawTotal := BenchmarkUsage{} + for _, response := range t.rawResponses { + if issue := rawTotal.add(response.Usage); issue != "" { + result.UsageIssue = "invalid raw response total: " + issue + return + } + } + if issue := validateBenchmarkUsage(rawTotal); issue != "" { + result.UsageIssue = "invalid raw response total: " + issue + return + } + if t.cumulativeObserved && rawTotal != t.cumulative { + result.UsageIssue = "raw and cumulative usage disagree" + return + } + result.Usage, result.UsageKnown, result.UsageSource = rawTotal, true, BenchmarkUsageRawResponses + return + } + if t.cumulativeObserved { + result.Usage, result.UsageKnown, result.UsageSource = t.cumulative, true, BenchmarkUsageCumulative + return + } + if t.rawObserved { + result.UsageIssue = "raw response omitted usage and no cumulative usage was observed" + } else { + result.UsageIssue = "matching usage event was not observed" + } +} + +func (t *benchmarkTelemetry) setIssue(issue string) { + if t.issue == "" { + t.issue = issue + } +} + +func (u *BenchmarkUsage) add(other BenchmarkUsage) string { + fields := []struct { + name string + target *int64 + value int64 + }{ + {"totalTokens", &u.TotalTokens, other.TotalTokens}, + {"inputTokens", &u.InputTokens, other.InputTokens}, + {"cachedInputTokens", &u.CachedInputTokens, other.CachedInputTokens}, + {"cacheWriteInputTokens", &u.CacheWriteInputTokens, other.CacheWriteInputTokens}, + {"outputTokens", &u.OutputTokens, other.OutputTokens}, + {"reasoningOutputTokens", &u.ReasoningOutputTokens, other.ReasoningOutputTokens}, + } + for _, field := range fields { + if field.value < 0 || *field.target > math.MaxInt64-field.value { + return field.name + " overflowed" + } + *field.target += field.value + } + return "" +} + +func validateBenchmarkUsage(usage BenchmarkUsage) string { + fields := []struct { + name string + value int64 + }{ + {"totalTokens", usage.TotalTokens}, + {"inputTokens", usage.InputTokens}, + {"cachedInputTokens", usage.CachedInputTokens}, + {"cacheWriteInputTokens", usage.CacheWriteInputTokens}, + {"outputTokens", usage.OutputTokens}, + {"reasoningOutputTokens", usage.ReasoningOutputTokens}, + } + for _, field := range fields { + if field.value < 0 { + return field.name + " is negative" + } + } + if usage.CachedInputTokens > usage.InputTokens || + usage.CacheWriteInputTokens > usage.InputTokens-usage.CachedInputTokens { + return "cached and cache-write input exceed inputTokens" + } + if usage.ReasoningOutputTokens > usage.OutputTokens { + return "reasoningOutputTokens exceeds outputTokens" + } + if usage.InputTokens > math.MaxInt64-usage.OutputTokens { + return "inputTokens + outputTokens overflow" + } + if usage.TotalTokens != usage.InputTokens+usage.OutputTokens { + return "totalTokens does not equal inputTokens + outputTokens" + } + return "" +} + +func benchmarkUsageAtLeast(current, previous BenchmarkUsage) bool { + return current.TotalTokens >= previous.TotalTokens && + current.InputTokens >= previous.InputTokens && + current.CachedInputTokens >= previous.CachedInputTokens && + current.CacheWriteInputTokens >= previous.CacheWriteInputTokens && + current.OutputTokens >= previous.OutputTokens && + current.ReasoningOutputTokens >= previous.ReasoningOutputTokens +} + +func benchmarkToolItem(itemType string) bool { + switch itemType { + case "plan", "commandExecution", "fileChange", "mcpToolCall", "dynamicToolCall", + "collabAgentToolCall", "subAgentActivity", "webSearch", "imageView", "sleep", "imageGeneration": + return true + default: + return false + } +} + func fatalBenchmarkError(ctx context.Context, err error) error { if ctx.Err() != nil { return ctx.Err() @@ -822,22 +1078,27 @@ var standardAPIPrices = map[string]apiPrice{ } func estimateAPICost(model string, usage BenchmarkUsage) (float64, bool) { + cost, known, _ := estimateAPICostWithIssue(model, usage) + return cost, known +} + +func estimateAPICostWithIssue(model string, usage BenchmarkUsage) (float64, bool, string) { + if issue := validateBenchmarkUsage(usage); issue != "" { + return 0, false, "invalid usage: " + issue + } price, ok := priceForModel(model) if !ok { - return 0, false + return 0, false, "no published price for model " + strings.TrimSpace(model) } if usage.CacheWriteInputTokens > 0 && !price.cacheWriteKnown { - return 0, false + return 0, false, "no published cache-write price for model " + strings.TrimSpace(model) } 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 + return cost / 1_000_000, true, "" } func priceForModel(model string) (apiPrice, bool) { diff --git a/internal/codex/benchmark_test.go b/internal/codex/benchmark_test.go index db2a104f..a8264432 100644 --- a/internal/codex/benchmark_test.go +++ b/internal/codex/benchmark_test.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "io" + "math" "os" "strings" "testing" @@ -240,7 +241,7 @@ func TestRunBenchmarkConsumesStreamedResultAndUsage(t *testing.T) { 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 { + if result.Usage.TotalTokens != 1200 || !result.UsageObserved || !result.UsageKnown || result.UsageSource != BenchmarkUsageCumulative || !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"`) { @@ -251,6 +252,239 @@ func TestRunBenchmarkConsumesStreamedResultAndUsage(t *testing.T) { } } +func TestRunBenchmarkFailsClosedWhenUsageIsMissing(t *testing.T) { + message := string(rawJSON(map[string]string{"code": correctStarlarkSubmission})) + server, _ := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{ + "thread": map[string]string{"id": "thread-1"}, "model": "gpt-5.3-codex", + })}, + benchmarkEnvelope{ID: rawJSON(2), Result: rawJSON(map[string]any{"turn": map[string]string{"id": "turn-1"}})}, + benchmarkEnvelope{Method: "item/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", "item": map[string]string{"type": "agentMessage", "text": message}, + })}, + benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turn": map[string]any{"id": "turn-1", "status": "completed"}, + })}, + ) + result, fatalErr := server.runBenchmark(context.Background(), benchmarkCombination{ + model: benchmarkModel{Model: "gpt-5.3-codex", DisplayName: "GPT-5.3 Codex"}, effort: "low", + }, benchmarkTaskDefinitions[0]) + if fatalErr != nil || !result.Correct { + t.Fatalf("correct result was affected by missing telemetry: %#v, %v", result, fatalErr) + } + if result.UsageObserved || result.UsageKnown || result.CostKnown || result.UsageIssue != "matching usage event was not observed" || result.CostIssue != result.UsageIssue { + t.Fatalf("missing usage did not fail closed: %#v", result) + } +} + +func TestRunBenchmarkRejectsToolUseAndInvalidatesCost(t *testing.T) { + message := string(rawJSON(map[string]string{"code": correctStarlarkSubmission})) + usage := BenchmarkUsage{TotalTokens: 120, InputTokens: 100, OutputTokens: 20} + server, _ := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{ + "thread": map[string]string{"id": "thread-1"}, "model": "gpt-5.3-codex", + })}, + benchmarkEnvelope{ID: rawJSON(2), Result: rawJSON(map[string]any{"turn": map[string]string{"id": "turn-1"}})}, + benchmarkEnvelope{Method: "item/started", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", "item": map[string]string{"type": "commandExecution"}, + })}, + benchmarkEnvelope{Method: "item/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", "item": map[string]string{"type": "agentMessage", "text": message}, + })}, + benchmarkEnvelope{Method: "thread/tokenUsage/updated", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", "tokenUsage": map[string]any{"total": usage}, + })}, + benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turn": map[string]any{"id": "turn-1", "status": "completed"}, + })}, + ) + result, fatalErr := server.runBenchmark(context.Background(), benchmarkCombination{ + model: benchmarkModel{Model: "gpt-5.3-codex", DisplayName: "GPT-5.3 Codex"}, effort: "low", + }, benchmarkTaskDefinitions[0]) + if fatalErr != nil || result.Correct || !result.ToolUsed || result.ToolType != "commandExecution" { + t.Fatalf("tool protocol violation was not rejected: %#v, %v", result, fatalErr) + } + if result.Failure != "tool use prohibited: commandExecution" || result.CostKnown || result.CostIssue != result.Failure || !result.UsageKnown { + t.Fatalf("tool result accounting is invalid: %#v", result) + } +} + +func TestRunBenchmarkPrefersCompleteRawResponseUsage(t *testing.T) { + message := string(rawJSON(map[string]string{"code": correctStarlarkSubmission})) + first := BenchmarkUsage{TotalTokens: 110, InputTokens: 100, CachedInputTokens: 20, OutputTokens: 10} + second := BenchmarkUsage{TotalTokens: 55, InputTokens: 50, OutputTokens: 5} + total := BenchmarkUsage{TotalTokens: 165, InputTokens: 150, CachedInputTokens: 20, OutputTokens: 15} + server, requests := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{ + "thread": map[string]string{"id": "thread-1"}, "model": "gpt-5.3-codex", + })}, + benchmarkEnvelope{ID: rawJSON(2), Result: rawJSON(map[string]any{"turn": map[string]string{"id": "turn-1"}})}, + benchmarkEnvelope{Method: "rawResponse/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", "responseId": "response-1", "usage": first, + })}, + benchmarkEnvelope{Method: "rawResponse/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", "responseId": "response-2", "usage": second, + })}, + benchmarkEnvelope{Method: "thread/tokenUsage/updated", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", "tokenUsage": map[string]any{"total": total}, + })}, + benchmarkEnvelope{Method: "item/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", "item": map[string]string{"type": "agentMessage", "text": message}, + })}, + benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turn": map[string]any{"id": "turn-1", "status": "completed"}, + })}, + ) + server.experimentalRawEvents = true + result, fatalErr := server.runBenchmark(context.Background(), benchmarkCombination{ + model: benchmarkModel{Model: "gpt-5.3-codex", DisplayName: "GPT-5.3 Codex"}, effort: "low", + }, benchmarkTaskDefinitions[0]) + if fatalErr != nil || !result.Correct || !result.UsageKnown || result.UsageSource != BenchmarkUsageRawResponses || result.Usage != total || len(result.ResponseUsage) != 2 { + t.Fatalf("raw response usage was not selected: %#v, %v", result, fatalErr) + } + if !strings.Contains(requests.String(), `"experimentalRawEvents":true`) { + t.Fatalf("thread did not request raw events: %s", requests.String()) + } +} + +func TestRunBenchmarkFallsBackWhenRawEventsAreUnsupported(t *testing.T) { + message := string(rawJSON(map[string]string{"code": correctStarlarkSubmission})) + usage := BenchmarkUsage{TotalTokens: 120, InputTokens: 100, OutputTokens: 20} + server, requests := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Error: &benchmarkRPCError{Code: -32602, Message: "unknown field experimentalRawEvents"}}, + benchmarkEnvelope{ID: rawJSON(2), Result: rawJSON(map[string]any{ + "thread": map[string]string{"id": "thread-1"}, "model": "gpt-5.3-codex", + })}, + benchmarkEnvelope{ID: rawJSON(3), 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": usage}, + })}, + benchmarkEnvelope{Method: "item/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turnId": "turn-1", "item": map[string]string{"type": "agentMessage", "text": message}, + })}, + benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-1", "turn": map[string]any{"id": "turn-1", "status": "completed"}, + })}, + ) + server.experimentalRawEvents = true + result, fatalErr := server.runBenchmark(context.Background(), benchmarkCombination{ + model: benchmarkModel{Model: "gpt-5.3-codex", DisplayName: "GPT-5.3 Codex"}, effort: "low", + }, benchmarkTaskDefinitions[0]) + if fatalErr != nil || !result.Correct || !result.UsageKnown || result.UsageSource != BenchmarkUsageCumulative { + t.Fatalf("stable cumulative fallback failed: %#v, %v", result, fatalErr) + } + if server.experimentalRawEvents || strings.Count(requests.String(), `"experimentalRawEvents":true`) != 1 { + t.Fatalf("raw-event compatibility fallback did not disable the field: %s", requests.String()) + } +} + +func TestBenchmarkTelemetryRejectsInconsistentStreams(t *testing.T) { + valid := BenchmarkUsage{TotalTokens: 110, InputTokens: 100, OutputTokens: 10} + for _, test := range []struct { + name string + record func(*benchmarkTelemetry) + want string + }{ + {name: "negative", record: func(state *benchmarkTelemetry) { + state.recordCumulative(BenchmarkUsage{TotalTokens: -1}) + }, want: "negative"}, + {name: "invalid breakdown", record: func(state *benchmarkTelemetry) { + state.recordCumulative(BenchmarkUsage{TotalTokens: 10, InputTokens: 5, CachedInputTokens: 6, OutputTokens: 5}) + }, want: "exceed"}, + {name: "regression", record: func(state *benchmarkTelemetry) { + state.recordCumulative(valid) + state.recordCumulative(BenchmarkUsage{TotalTokens: 55, InputTokens: 50, OutputTokens: 5}) + }, want: "regressed"}, + {name: "raw mismatch", record: func(state *benchmarkTelemetry) { + state.recordRawResponse("response-1", &valid) + state.recordCumulative(BenchmarkUsage{TotalTokens: 120, InputTokens: 100, OutputTokens: 20}) + }, want: "disagree"}, + {name: "duplicate response", record: func(state *benchmarkTelemetry) { + state.recordRawResponse("response-1", nil) + state.recordRawResponse("response-1", nil) + }, want: "duplicate"}, + {name: "raw aggregate overflow", record: func(state *benchmarkTelemetry) { + maximum := BenchmarkUsage{TotalTokens: math.MaxInt64, InputTokens: math.MaxInt64} + state.recordRawResponse("response-1", &maximum) + state.recordRawResponse("response-2", &maximum) + }, want: "overflowed"}, + } { + t.Run(test.name, func(t *testing.T) { + state := newBenchmarkTelemetry() + test.record(state) + var result BenchmarkResult + state.apply(&result) + if result.UsageKnown || !strings.Contains(result.UsageIssue, test.want) { + t.Fatalf("inconsistent telemetry did not fail closed: %#v", result) + } + }) + } +} + +func TestBenchmarkTelemetryFallsBackWhenRawUsageIsOmitted(t *testing.T) { + valid := BenchmarkUsage{TotalTokens: 110, InputTokens: 100, OutputTokens: 10} + state := newBenchmarkTelemetry() + state.recordRawResponse("response-1", nil) + state.recordCumulative(valid) + var result BenchmarkResult + state.apply(&result) + if !result.UsageObserved || !result.UsageKnown || result.UsageSource != BenchmarkUsageCumulative || result.Usage != valid || result.UsageIssue != "" { + t.Fatalf("valid cumulative fallback was not used: %#v", result) + } +} + +func TestValidateBenchmarkUsageInvariants(t *testing.T) { + valid := BenchmarkUsage{ + TotalTokens: 130, InputTokens: 100, CachedInputTokens: 20, + CacheWriteInputTokens: 10, OutputTokens: 30, ReasoningOutputTokens: 15, + } + if issue := validateBenchmarkUsage(valid); issue != "" { + t.Fatalf("valid usage rejected: %s", issue) + } + for _, mutation := range []func(*BenchmarkUsage){ + func(usage *BenchmarkUsage) { usage.OutputTokens = -1 }, + func(usage *BenchmarkUsage) { usage.CachedInputTokens = 95 }, + func(usage *BenchmarkUsage) { usage.ReasoningOutputTokens = 31 }, + func(usage *BenchmarkUsage) { usage.TotalTokens++ }, + func(usage *BenchmarkUsage) { + *usage = BenchmarkUsage{ + TotalTokens: math.MaxInt64, InputTokens: math.MaxInt64, + CachedInputTokens: math.MaxInt64, CacheWriteInputTokens: math.MaxInt64, + } + }, + func(usage *BenchmarkUsage) { + *usage = BenchmarkUsage{TotalTokens: math.MaxInt64, InputTokens: math.MaxInt64, OutputTokens: 1} + }, + } { + usage := valid + mutation(&usage) + if issue := validateBenchmarkUsage(usage); issue == "" { + t.Fatalf("invalid usage accepted: %#v", usage) + } + } + invalid := valid + invalid.TotalTokens++ + if _, known, issue := estimateAPICostWithIssue("gpt-5.3-codex", invalid); known || !strings.Contains(issue, "invalid usage") { + t.Fatalf("invalid usage received a cost: known=%v issue=%q", known, issue) + } +} + +func TestExperimentalAPIUnsupported(t *testing.T) { + for _, test := range []struct { + err error + want bool + }{ + {err: &benchmarkMethodError{code: -32602, message: "invalid params"}, want: true}, + {err: &benchmarkMethodError{code: -32000, message: "unknown experimentalRawEvents"}, want: true}, + {err: &benchmarkMethodError{code: -32000, message: "account unavailable"}, want: false}, + {err: errors.New("transport failed"), want: false}, + } { + if got := experimentalAPIUnsupported(test.err); got != test.want { + t.Errorf("experimentalAPIUnsupported(%v) = %v, want %v", test.err, got, test.want) + } + } +} + func TestRunBenchmarkSuiteDiscoversAndRunsEveryCombination(t *testing.T) { message := string(rawJSON(map[string]string{"code": correctStarlarkSubmission})) server, _ := newFakeBenchmarkServer( @@ -598,7 +832,7 @@ func TestBenchmarkCombinationsPreserveCatalogOrder(t *testing.T) { func TestEstimateAPICostUsesCachedAndOutputRates(t *testing.T) { usage := BenchmarkUsage{ InputTokens: 2_000, CachedInputTokens: 500, CacheWriteInputTokens: 100, - OutputTokens: 300, ReasoningOutputTokens: 200, + OutputTokens: 300, ReasoningOutputTokens: 200, TotalTokens: 2_300, } cost, ok := estimateAPICost("gpt-5.6-sol-2026-08-01", usage) if !ok { @@ -617,7 +851,7 @@ func TestEstimateAPICostUsesCachedAndOutputRates(t *testing.T) { } func TestEstimateAPICostRequiresPublishedCacheWriteRate(t *testing.T) { - usage := BenchmarkUsage{InputTokens: 1_000, CacheWriteInputTokens: 100, OutputTokens: 50} + usage := BenchmarkUsage{InputTokens: 1_000, CacheWriteInputTokens: 100, OutputTokens: 50, TotalTokens: 1_050} if _, ok := estimateAPICost("gpt-5.5", usage); ok { t.Fatal("model with no published cache-write rate received a guessed price") } diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index 49c1833e..90aa0c09 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -231,6 +231,8 @@ func (m Model) renderBenchmarkStatus(width, height int, colors palette) string { detail = "PRESS B OR CLICK TO RUN AGAIN" if failure := latestBenchmarkFailure(m.benchmarkResults); failure != "" { detail = "LAST FAIL // " + failure + } else if issue := latestBenchmarkMeasurementIssue(m.benchmarkResults); issue != "" { + detail = "LAST N/A // " + issue } if m.benchmarkError != "" { state = "BENCHMARK FAULT" @@ -262,6 +264,18 @@ func latestBenchmarkFailure(results []codex.BenchmarkResult) string { return "" } +func latestBenchmarkMeasurementIssue(results []codex.BenchmarkResult) string { + for index := len(results) - 1; index >= 0; index-- { + if results[index].UsageIssue != "" { + return results[index].UsageIssue + } + if results[index].CostIssue != "" { + return results[index].CostIssue + } + } + return "" +} + func (m Model) renderBenchmarkTable(width, height int, colors palette) string { innerWidth := max(width-4, 1) bodyHeight := max(height-2, 1) @@ -444,6 +458,10 @@ func benchmarkResultValues(result codex.BenchmarkResult) []string { if result.CostKnown { cost = fmt.Sprintf("~$%.4f", result.CostUSD) } + tokens := "N/A" + if result.UsageKnown { + tokens = formatCompactTokens(result.Usage.TotalTokens) + } model := result.DisplayName if result.ActualModel != "" && result.ActualModel != result.Model { model += "→" + result.ActualModel @@ -454,7 +472,7 @@ func benchmarkResultValues(result codex.BenchmarkResult) []string { result.TaskName, outcome, formatBenchmarkDuration(result.Duration), - formatCompactTokens(result.Usage.TotalTokens), + tokens, cost, } } @@ -468,6 +486,9 @@ func sortedBenchmarkResults(results []codex.BenchmarkResult, column benchmarkSor if column == benchmarkSortCost && ordered[left].CostKnown != ordered[right].CostKnown { return ordered[left].CostKnown } + if column == benchmarkSortTokens && ordered[left].UsageKnown != ordered[right].UsageKnown { + return ordered[left].UsageKnown + } comparison := compareBenchmarkResults(ordered[left], ordered[right], column) if descending { return comparison > 0 diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index d48c2fdb..fd0fde9f 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -48,8 +48,8 @@ func TestBenchmarkViewRendersResponsiveResultsTable(t *testing.T) { 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"}, + {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}, UsageKnown: true, 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}, UsageKnown: true, Failure: "wrong result"}, }, } output := ansi.Strip(model.renderBenchmarkArea(96, 19, paletteFor(themeHacker))) @@ -80,6 +80,19 @@ func TestBenchmarkViewRendersResponsiveResultsTable(t *testing.T) { } } +func TestBenchmarkStatusExplainsUnavailableMeasurements(t *testing.T) { + model := Model{ + benchmarkState: benchmarkFinished, + benchmarkResults: []codex.BenchmarkResult{{ + Correct: true, UsageIssue: "matching usage event was not observed", + }}, + } + output := ansi.Strip(model.renderBenchmarkStatus(60, 5, paletteFor(themeHacker))) + if !strings.Contains(output, "LAST N/A // matching usage event was not observed") { + t.Fatalf("benchmark status did not explain unavailable telemetry:\n%s", output) + } +} + func TestBenchmarkHotkeyRunsSuiteAndCollectsEvents(t *testing.T) { result := codex.BenchmarkResult{Model: "model", DisplayName: "Model", Effort: "medium", Correct: true} fetcher := benchmarkStubFetcher{ @@ -290,8 +303,8 @@ func TestBenchmarkRenderedClickSurfacesMatchHitTestingAcrossSizes(t *testing.T) 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: "B", Effort: "xhigh", TaskName: "SHORTEST PATH", Duration: 3 * time.Second, Usage: codex.BenchmarkUsage{TotalTokens: 300}, UsageKnown: true, CostKnown: true, CostUSD: 0.3}, + {DisplayName: "A", Effort: "low", TaskName: "LRU CACHE", Correct: true, Duration: time.Second, Usage: codex.BenchmarkUsage{TotalTokens: 100}, UsageKnown: true, CostKnown: true, CostUSD: 0.1}, {DisplayName: "C", Effort: "medium", TaskName: "MERGE RANGES", Duration: 2 * time.Second, Usage: codex.BenchmarkUsage{TotalTokens: 200}}, } checks := []struct { @@ -315,13 +328,28 @@ func TestBenchmarkSortUsesReasoningOrderAndMetrics(t *testing.T) { if !ordered[0].CostKnown || ordered[len(ordered)-1].CostKnown { t.Fatal("descending cost sort did not leave N/A values last") } + ordered = sortedBenchmarkResults(results, benchmarkSortTokens, true) + if !ordered[0].UsageKnown || ordered[len(ordered)-1].UsageKnown { + t.Fatal("descending token sort did not leave N/A values last") + } +} + +func TestBenchmarkResultValuesDistinguishUnknownFromObservedZero(t *testing.T) { + unknown := benchmarkResultValues(codex.BenchmarkResult{}) + if unknown[5] != "N/A" || unknown[6] != "N/A" { + t.Fatalf("unknown measurements = tokens %q, cost %q; want N/A", unknown[5], unknown[6]) + } + observedZero := benchmarkResultValues(codex.BenchmarkResult{UsageKnown: true, CostKnown: true}) + if observedZero[5] != "0" || observedZero[6] != "~$0.0000" { + t.Fatalf("observed zero measurements = tokens %q, cost %q", observedZero[5], observedZero[6]) + } } 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, + Usage: codex.BenchmarkUsage{TotalTokens: 12_345_678}, UsageKnown: true, CostKnown: true, CostUSD: 12345.6789, }} columns := benchmarkTableColumns(96, results) if len(columns) != 7 { From b8f7b21a592a40dfac37492026a6c950ac57237e Mon Sep 17 00:00:00 2001 From: merefield Date: Tue, 11 Aug 2026 21:31:25 +0100 Subject: [PATCH 6/9] Document benchmark hardening guidance --- README.md | 49 +++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 43 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 9088fadc..8ebfe978 100644 --- a/README.md +++ b/README.md @@ -375,14 +375,51 @@ PASS/FAIL evaluation is independent of these measurements: incomplete or ambiguous token telemetry does not make an incorrect program pass, and a valid program can still have an unavailable or approximate cost. -#### Future measurement hardening +#### Measurement hardening status and guidance -Correct long-context and reroute costing still needs each upstream response to +The measurement path is deliberately fail-closed. Its current hardening status +is: + +| Priority | Safeguard | Status | +| --- | --- | --- | +| **P0** | Distinguish missing telemetry from a genuine observed zero | Complete | +| **P0** | Reject negative, inconsistent, regressing, or overflowing token data | Complete | +| **P0** | Track token availability independently from price availability and retain the reason for `N/A` | Complete | +| **P1** | Prefer a validated per-response ledger, with a validated cumulative compatibility fallback | Complete | +| **P1** | Detect prohibited tool-use items, force the trial to `FAIL`, and invalidate `API EQ` | Complete | +| **P1** | Apply the correct pricing tier to long-context responses | Deferred | +| **P2** | Reduce cache-order bias with balanced warm-ups, randomized ordering, or repeated trials | Open | +| **P2** | Report a cache-neutral comparison alongside the observed cached cost | Open | +| **P2** | Price mixed-model reroutes from a response-to-model association | Open; the current raw event does not expose that association | +| **P2** | Record pricing-table provenance and make stale compiled pricing conspicuous | Open | +| **P2** | Add explicit compatibility diagnostics for future experimental-event schema changes | Partial; automatic cumulative fallback is already implemented | + +Future accounting changes should preserve these rules: + +- Never treat absent or invalid telemetry as zero, and never clamp malformed + fields into a plausible value. +- Validate individual responses, overflow-safe aggregates, cumulative + monotonicity, and raw-versus-cumulative agreement before setting usage as + available. +- Keep correctness, usage availability, and cost availability as independent + states. An unavailable price must not erase a valid token count, and a + measurement problem must not change the deterministic Starlark verdict. +- Prefer exact response telemetry only when response IDs are present and unique; + retain the cumulative path for compatible older app-servers. +- Do not infer prices for unknown models or unpublished token classes. Update + the compiled table only from published OpenAI pricing and record its source + and effective date when provenance support is added. +- Treat any tool-use item as a benchmark protocol violation. Text-token pricing + alone cannot represent separately priced or externally executed work. +- Cover missing fields, invalid invariants, integer overflow, duplicate events, + event regression, source disagreement, tool use, and experimental-protocol + fallback in tests. Keep race-enabled CI green on Linux, macOS, and Windows. + +Correct long-context and reroute costing will require each upstream response to be associated with the model and pricing tier that actually served it, including -the exact threshold semantics. Reporting both observed cost and a cache-neutral -equivalent—or running balanced warm-up and repeated trials—would also make -model/effort comparisons less sensitive to cache order. These improvements -would not change the deterministic PASS/FAIL verifier. +the exact threshold semantics. Cache-neutral or repeated-trial reporting would +improve comparison quality without changing the deterministic PASS/FAIL +verifier. ## Options From 58c548bde19be1ce83620d615f1fa89df030e5af Mon Sep 17 00:00:00 2001 From: merefield Date: Tue, 11 Aug 2026 22:13:04 +0100 Subject: [PATCH 7/9] Collapse benchmark on short terminals --- internal/ui/benchmark.go | 44 ++++++++++++++++----- internal/ui/benchmark_test.go | 74 ++++++++++++++++++++++++++++++----- 2 files changed, 98 insertions(+), 20 deletions(-) diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index 90aa0c09..55ffa79f 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -71,20 +71,28 @@ func layoutBenchmarkArea(width, height int) benchmarkGeometry { } return benchmarkGeometry{ width: width, height: height, topHeight: controlsHeight + statusHeight, - tableHeight: max(height-controlsHeight-statusHeight, 1), + tableHeight: max(height-controlsHeight-statusHeight, 0), controlsHeight: controlsHeight, statusHeight: statusHeight, controlsWidth: width, statusWidth: width, stacked: true, } } return benchmarkGeometry{ width: width, height: height, topHeight: topHeight, - tableHeight: max(height-topHeight, 1), + tableHeight: max(height-topHeight, 0), controlsHeight: topHeight, statusHeight: topHeight, controlsWidth: controlsWidth, statusWidth: statusWidth, } } func (m Model) renderBenchmarkArea(width, height int, colors palette) string { + width, height = max(width, 1), max(height, 1) + if height < 3 { + lines := []string{fitTableCell("BENCHMARK // TERMINAL TOO SHORT", width)} + for len(lines) < height { + lines = append(lines, strings.Repeat(" ", width)) + } + return colors.dimmed().Render(strings.Join(lines, "\n")) + } layout := layoutBenchmarkArea(width, height) controls := m.renderBenchmarkControls(layout.controlsWidth, layout.controlsHeight, colors) top := controls @@ -96,8 +104,10 @@ func (m Model) renderBenchmarkArea(width, height int, colors palette) string { top = lipgloss.JoinHorizontal(lipgloss.Top, controls, " ", status) } } - table := m.renderBenchmarkTable(width, layout.tableHeight, colors) - view := lipgloss.JoinVertical(lipgloss.Left, top, table) + view := top + if layout.tableHeight >= 3 { + view = lipgloss.JoinVertical(lipgloss.Left, top, m.renderBenchmarkTable(width, layout.tableHeight, colors)) + } if padding := height - lipgloss.Height(view); padding > 0 { view += strings.Repeat("\n", padding) } @@ -106,13 +116,26 @@ func (m Model) renderBenchmarkArea(width, height int, colors palette) string { func (m Model) renderBenchmarkControls(width, height int, colors palette) string { innerWidth := max(width-4, 1) - lines := make([]string, 0, 2) - for _, segments := range m.benchmarkControlLines(innerWidth) { + lines := make([]string, 0, max(height-2, 0)) + for _, segments := range m.benchmarkVisibleControlLines(innerWidth, height) { lines = append(lines, m.renderBenchmarkSegments(segments, innerWidth, colors)) } return frameSized(width, max(height-2, 1), "BENCHMARK CONTROLS", strings.Join(lines, "\n"), colors.primary, colors) } +func (m Model) benchmarkVisibleControlLines(width, height int) [][]benchmarkControlSegment { + lines := m.benchmarkControlLines(width) + capacity := max(height-2, 0) + if capacity >= len(lines) { + return lines + } + if capacity == 2 && len(lines) >= 3 { + // Drop the decorative spacer before dropping an actionable row. + return [][]benchmarkControlSegment{lines[0], lines[2]} + } + return lines[:min(len(lines), capacity)] +} + func (m Model) renderBenchmarkSegments(segments []benchmarkControlSegment, width int, colors palette) string { parts := make([]string, 0, len(segments)) used := 0 @@ -252,6 +275,7 @@ func (m Model) renderBenchmarkStatus(width, height int, colors palette) string { if height >= 5 { lines = append(lines, colors.dimmed().Render(ansi.Truncate("HERMETIC STARLARK // 250K STEP LIMIT", max(width-4, 1), ""))) } + lines = lines[:min(len(lines), max(height-2, 0))] return frameSized(width, max(height-2, 1), "ALGORITHM TRIAL", strings.Join(lines, "\n"), color, colors) } @@ -604,17 +628,17 @@ func (m Model) benchmarkButtonAt(x, y int) footerButtonID { dashboard := m.dashboardLayout() layout := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) localX, localY := x-2, y-dashboard.meterY - if localX < 0 { + if localX < 0 || localY < 0 || localY >= layout.height || layout.height < 3 { return footerButtonNone } - if localX < layout.controlsWidth { - for line, segments := range m.benchmarkControlLines(max(layout.controlsWidth-4, 1)) { + if localX < layout.controlsWidth && localY < layout.controlsHeight { + for line, segments := range m.benchmarkVisibleControlLines(max(layout.controlsWidth-4, 1), layout.controlsHeight) { if localY == line+1 { return benchmarkSegmentButtonAt(localX, segments) } } } - if localX < layout.width && localY == layout.topHeight+1 { + if layout.tableHeight >= 3 && localX < layout.width && localY == layout.topHeight+1 { return benchmarkSegmentButtonAt(localX, m.benchmarkFilterLine(max(layout.width-4, 1))) } return footerButtonNone diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index fd0fde9f..0209524f 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -80,6 +80,52 @@ func TestBenchmarkViewRendersResponsiveResultsTable(t *testing.T) { } } +func TestBenchmarkAreaHonorsEveryAllocatedHeight(t *testing.T) { + model := Model{benchmarkState: benchmarkFinished} + for height := 1; height <= 12; height++ { + t.Run(fmt.Sprintf("height-%d", height), func(t *testing.T) { + const width = 76 + output := ansi.Strip(model.renderBenchmarkArea(width, height, paletteFor(themeHacker))) + if got := lipgloss.Height(output); got != height { + t.Fatalf("benchmark height = %d, want %d:\n%s", got, height, output) + } + if got := lipgloss.Width(output); got != width { + t.Fatalf("benchmark width = %d, want %d:\n%s", got, width, output) + } + geometry := layoutBenchmarkArea(width, height) + if geometry.tableHeight < 3 && strings.Contains(output, "RESULT MATRIX") { + t.Fatalf("table rendered in an allocation too short for its frame:\n%s", output) + } + if height == 4 && !strings.Contains(output, "RUN SELECTED") { + t.Fatalf("compact controls dropped an action before their spacer:\n%s", output) + } + }) + } +} + +func TestVeryShortBenchmarkAreaExposesNoHiddenMouseTargets(t *testing.T) { + for _, height := range []int{8, 9, 10} { + model := Model{ + snapshot: codex.DemoSnapshot(), width: 40, height: height, + meterStyle: styleBenchmark, + } + dashboard := model.dashboardLayout() + if dashboard.meterHeight >= 3 { + t.Fatalf("test height %d produced meter height %d", height, dashboard.meterHeight) + } + for y := dashboard.meterY; y < dashboard.footerY; y++ { + for x := 0; x < model.width; x++ { + if button := model.benchmarkButtonAt(x, y); button != footerButtonNone { + t.Fatalf("height %d exposed hidden button %d at %d,%d", height, button, x, y) + } + if column, ok := model.benchmarkHeaderAt(x, y); ok || column != benchmarkSortNone { + t.Fatalf("height %d exposed hidden heading %d at %d,%d", height, column, x, y) + } + } + } + } +} + func TestBenchmarkStatusExplainsUnavailableMeasurements(t *testing.T) { model := Model{ benchmarkState: benchmarkFinished, @@ -254,7 +300,7 @@ func TestBenchmarkRenderedClickSurfacesMatchHitTestingAcrossSizes(t *testing.T) } dashboard := model.dashboardLayout() geometry := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) - for _, segments := range model.benchmarkControlLines(max(geometry.controlsWidth-4, 1)) { + for _, segments := range model.benchmarkVisibleControlLines(max(geometry.controlsWidth-4, 1), geometry.controlsHeight) { for _, segment := range segments { if segment.button == footerButtonNone || !segment.enabled { continue @@ -267,22 +313,30 @@ func TestBenchmarkRenderedClickSurfacesMatchHitTestingAcrossSizes(t *testing.T) } } } - for _, segment := range model.benchmarkFilterLine(max(dashboard.contentWidth-4, 1)) { - if segment.button == footerButtonNone || !segment.enabled { - continue - } - x, y := renderedTextStart(t, model, segment.text) - for offset := 0; offset < lipgloss.Width(segment.text); offset++ { - if got := model.benchmarkButtonAt(x+offset, y); got != segment.button { - t.Errorf("rendered matrix filter %q cell %d hit button %d, want %d", segment.text, offset, got, segment.button) + if geometry.tableHeight >= 3 { + for _, segment := range model.benchmarkFilterLine(max(dashboard.contentWidth-4, 1)) { + if segment.button == footerButtonNone || !segment.enabled { + continue + } + x, y := renderedTextStart(t, model, segment.text) + for offset := 0; offset < lipgloss.Width(segment.text); offset++ { + if got := model.benchmarkButtonAt(x+offset, y); got != segment.button { + t.Errorf("rendered matrix filter %q cell %d hit button %d, want %d", segment.text, offset, got, segment.button) + } } } } + if geometry.tableHeight < 3 { + if got, ok := model.benchmarkHeaderAt(4, dashboard.meterY+geometry.topHeight+2); ok || got != benchmarkSortNone { + t.Errorf("hidden compact table exposed a heading click surface: (%d,%v)", got, ok) + } + return + } tableTitleX, tableTitleY := renderedTextStart(t, model, "RESULT MATRIX") _ = tableTitleX headerY := tableTitleY + 2 - if geometry.tableHeight <= 3 { + if geometry.tableHeight == 3 { if got, ok := model.benchmarkHeaderAt(4, headerY); ok || got != benchmarkSortNone { t.Errorf("non-rendered compact heading exposed a click surface: (%d,%v)", got, ok) } From 18815687d3ddaf7c95adb72a614b0196e3b7aae8 Mon Sep 17 00:00:00 2001 From: merefield Date: Tue, 11 Aug 2026 22:20:00 +0100 Subject: [PATCH 8/9] Continue benchmarks after turn timeout --- README.md | 7 + internal/codex/benchmark.go | 246 ++++++++++++++++++++----------- internal/codex/benchmark_test.go | 96 +++++++++++- 3 files changed, 261 insertions(+), 88 deletions(-) diff --git a/README.md b/README.md index 8ebfe978..d8ba8726 100644 --- a/README.md +++ b/README.md @@ -259,6 +259,13 @@ 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. +Each model/effort trial has a five-minute deadline. If an in-flight turn reaches +that deadline, Codexometer requests `turn/interrupt`, waits for the matching +`turn/completed` event, records that combination as `FAIL`, and continues with +the remaining combinations. Explicit user cancellation, app-server transport +failure, or failure to confirm interruption still stops the suite because the +server's state is then unsafe or unknown. + #### Challenges Every trial asks the model to return one named Starlark function: diff --git a/internal/codex/benchmark.go b/internal/codex/benchmark.go index 358d21ba..b4393653 100644 --- a/internal/codex/benchmark.go +++ b/internal/codex/benchmark.go @@ -21,9 +21,10 @@ import ( ) const ( - benchmarkTurnTimeout = 5 * time.Minute - benchmarkCodeLimit = 64 * 1024 - benchmarkStepLimit = 250_000 + benchmarkTurnTimeout = 5 * time.Minute + benchmarkInterruptTimeout = 15 * time.Second + benchmarkCodeLimit = 64 * 1024 + benchmarkStepLimit = 250_000 ) // BenchmarkUsage is the app-server token breakdown for one isolated turn. @@ -144,6 +145,8 @@ type appServerSession struct { done chan struct{} stop sync.Once experimentalRawEvents bool + turnTimeout time.Duration + interruptTimeout time.Duration } type lockedBuffer struct { @@ -469,7 +472,8 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma Model: combination.model.Model, DisplayName: combination.model.DisplayName, Effort: combination.effort, ActualModel: combination.model.Model, } - turnCtx, cancel := context.WithTimeout(ctx, benchmarkTurnTimeout) + turnTimeout := s.benchmarkTurnTimeout() + turnCtx, cancel := context.WithTimeout(ctx, turnTimeout) defer cancel() temporary, err := os.MkdirTemp("", "codexometer-benchmark-") @@ -546,106 +550,109 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma var finalMessage, turnFailure string telemetry := newBenchmarkTelemetry() 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 { - telemetry.recordCumulative(event.TokenUsage.Total) - } - case "rawResponse/completed": - var event struct { - ThreadID string `json:"threadId"` - TurnID string `json:"turnId"` - ResponseID string `json:"responseId"` - Usage *BenchmarkUsage `json:"usage"` - } - if json.Unmarshal(params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID { - telemetry.recordRawResponse(event.ResponseID, event.Usage) - } - case "model/rerouted": - var event struct { - ThreadID string `json:"threadId"` - TurnID string `json:"turnId"` - ToModel string `json:"toModel"` + handleNotification := 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 { + telemetry.recordCumulative(event.TokenUsage.Total) + } + case "rawResponse/completed": + var event struct { + ThreadID string `json:"threadId"` + TurnID string `json:"turnId"` + ResponseID string `json:"responseId"` + Usage *BenchmarkUsage `json:"usage"` + } + if json.Unmarshal(params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID { + telemetry.recordRawResponse(event.ResponseID, event.Usage) + } + 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/started", "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 { + if benchmarkToolItem(event.Item.Type) && !result.ToolUsed { + result.ToolUsed, result.ToolType = true, event.Item.Type } - if json.Unmarshal(params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID && event.ToModel != "" { - result.ActualModel = event.ToModel + if method == "item/completed" && event.Item.Type == "agentMessage" { + finalMessage = event.Item.Text } - case "item/started", "item/completed": - var event struct { - ThreadID string `json:"threadId"` - TurnID string `json:"turnId"` - Item struct { + } + 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:"item"` - } - if json.Unmarshal(params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID { - if benchmarkToolItem(event.Item.Type) && !result.ToolUsed { - result.ToolUsed, result.ToolType = true, event.Item.Type - } - if method == "item/completed" && event.Item.Type == "agentMessage" { - finalMessage = event.Item.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 } } - 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 - } + if finalMessage == "" { + for _, item := range event.Turn.Items { + if item.Type == "agentMessage" { + finalMessage = item.Text } } - return true } + return true } - return false - }) + } + return false + } + for !completed { + _, err = s.readUntilNotification(turnCtx, handleNotification) if err != nil { result.Duration = time.Since(startedAt) + if recoverableBenchmarkTimeout(ctx, turnCtx, err) { + result.Failure = fmt.Sprintf("turn timed out after %s", turnTimeout) + if interruptErr := s.interruptBenchmarkTurn(ctx, startedThread.Thread.ID, startedTurn.Turn.ID, &completed, handleNotification); interruptErr != nil { + result.Failure += "; cleanup failed: " + interruptErr.Error() + return result, fmt.Errorf("recover timed-out benchmark turn: %w", interruptErr) + } + applyBenchmarkMeasurements(&result, telemetry) + return result, nil + } result.Failure = fmt.Sprintf("wait for turn: %v", err) return result, err } } result.Duration = time.Since(startedAt) - telemetry.apply(&result) - if result.ToolUsed { - result.CostIssue = "tool use prohibited: " + result.ToolType - } else if result.UsageKnown { - result.CostUSD, result.CostKnown, result.CostIssue = estimateAPICostWithIssue(result.ActualModel, result.Usage) - } else { - result.CostIssue = result.UsageIssue - } + applyBenchmarkMeasurements(&result, telemetry) if turnFailure != "" { result.Failure = turnFailure return result, nil @@ -667,6 +674,71 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma return result, nil } +func (s *appServerSession) benchmarkTurnTimeout() time.Duration { + if s.turnTimeout > 0 { + return s.turnTimeout + } + return benchmarkTurnTimeout +} + +func (s *appServerSession) benchmarkInterruptTimeout() time.Duration { + if s.interruptTimeout > 0 { + return s.interruptTimeout + } + return benchmarkInterruptTimeout +} + +func recoverableBenchmarkTimeout(parent, turn context.Context, err error) bool { + return parent.Err() == nil && errors.Is(turn.Err(), context.DeadlineExceeded) && errors.Is(err, context.DeadlineExceeded) +} + +func (s *appServerSession) interruptBenchmarkTurn( + ctx context.Context, + threadID, turnID string, + completed *bool, + handleNotification func(string, json.RawMessage) bool, +) error { + cleanupCtx, cancel := context.WithTimeout(ctx, s.benchmarkInterruptTimeout()) + defer cancel() + + _, err := s.call(cleanupCtx, "turn/interrupt", map[string]string{ + "threadId": threadID, + "turnId": turnID, + }, func(method string, params json.RawMessage) { + handleNotification(method, params) + }) + if err != nil { + var methodError *benchmarkMethodError + // The turn can finish naturally between the deadline and the interrupt + // request. A method rejection is safe only when its matching completion + // notification was also observed. + if !*completed || !errors.As(err, &methodError) { + return fmt.Errorf("interrupt turn: %w", err) + } + } + if *completed { + return nil + } + if _, err := s.readUntilNotification(cleanupCtx, handleNotification); err != nil { + return fmt.Errorf("confirm interrupted turn: %w", err) + } + if !*completed { + return errors.New("confirm interrupted turn: completion was not observed") + } + return nil +} + +func applyBenchmarkMeasurements(result *BenchmarkResult, telemetry *benchmarkTelemetry) { + telemetry.apply(result) + if result.ToolUsed { + result.CostIssue = "tool use prohibited: " + result.ToolType + } else if result.UsageKnown { + result.CostUSD, result.CostKnown, result.CostIssue = estimateAPICostWithIssue(result.ActualModel, result.Usage) + } else { + result.CostIssue = result.UsageIssue + } +} + type benchmarkTelemetry struct { cumulative BenchmarkUsage cumulativeObserved bool diff --git a/internal/codex/benchmark_test.go b/internal/codex/benchmark_test.go index a8264432..4cea8f25 100644 --- a/internal/codex/benchmark_test.go +++ b/internal/codex/benchmark_test.go @@ -195,7 +195,7 @@ func newFakeBenchmarkServer(envelopes ...benchmarkEnvelope) (*appServerSession, requests := &bytes.Buffer{} server := &appServerSession{ stdin: nopWriteCloser{requests}, encoder: json.NewEncoder(requests), - envelopes: make(chan benchmarkEnvelope, len(envelopes)+1), + envelopes: make(chan benchmarkEnvelope, len(envelopes)+16), readErrors: make(chan error, 1), done: make(chan struct{}), stderr: &lockedBuffer{}, } for _, envelope := range envelopes { @@ -277,6 +277,100 @@ func TestRunBenchmarkFailsClosedWhenUsageIsMissing(t *testing.T) { } } +func TestRunBenchmarkSuiteInterruptsTimedOutTurnAndContinues(t *testing.T) { + message := string(rawJSON(map[string]string{"code": correctStarlarkSubmission})) + server, requests := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{ + "data": []any{map[string]any{ + "model": "gpt-5.3-codex", "displayName": "GPT-5.3 Codex", + "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"}, "model": "gpt-5.3-codex", + })}, + benchmarkEnvelope{ID: rawJSON(3), Result: rawJSON(map[string]any{"turn": map[string]string{"id": "turn-low"}})}, + ) + server.turnTimeout = 20 * time.Millisecond + server.interruptTimeout = 2 * time.Second + go func() { + time.Sleep(60 * time.Millisecond) + server.envelopes <- benchmarkEnvelope{ID: rawJSON(4), Result: rawJSON(map[string]any{})} + server.envelopes <- benchmarkEnvelope{Method: "thread/tokenUsage/updated", Params: rawJSON(map[string]any{ + "threadId": "thread-low", "turnId": "turn-low", + "tokenUsage": map[string]any{"total": BenchmarkUsage{TotalTokens: 55, InputTokens: 50, OutputTokens: 5}}, + })} + server.envelopes <- benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-low", "turn": map[string]any{"id": "turn-low", "status": "interrupted"}, + })} + server.envelopes <- benchmarkEnvelope{ID: rawJSON(5), Result: rawJSON(map[string]any{ + "thread": map[string]string{"id": "thread-high"}, "model": "gpt-5.3-codex", + })} + server.envelopes <- benchmarkEnvelope{ID: rawJSON(6), Result: rawJSON(map[string]any{"turn": map[string]string{"id": "turn-high"}})} + server.envelopes <- benchmarkEnvelope{Method: "item/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-high", "turnId": "turn-high", + "item": map[string]string{"type": "agentMessage", "text": message}, + })} + server.envelopes <- 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 results []BenchmarkResult + var final BenchmarkEvent + Client{}.RunBenchmarkSuite(context.Background(), []BenchmarkTaskID{BenchmarkMergeRanges}, func(event BenchmarkEvent) { + if event.Result != nil { + results = append(results, *event.Result) + } + final = event + }) + if len(results) != 2 { + t.Fatalf("suite produced %d results, want 2: %#v", len(results), results) + } + if results[0].Correct || results[0].Failure != "turn timed out after 20ms" || !results[0].UsageKnown || results[0].Usage.TotalTokens != 55 { + t.Fatalf("timed-out result was not retained as a measured failure: %#v", results[0]) + } + if !results[1].Correct || results[1].Effort != "high" { + t.Fatalf("suite did not continue to the next combination: %#v", results[1]) + } + if !final.Done || final.Err != nil || final.Completed != 2 || final.Total != 2 { + t.Fatalf("suite ended as a global fault: %#v", final) + } + requestLog := requests.String() + if !strings.Contains(requestLog, `"method":"turn/interrupt"`) || + !strings.Contains(requestLog, `"threadId":"thread-low"`) || + !strings.Contains(requestLog, `"turnId":"turn-low"`) { + t.Fatalf("timed-out turn was not interrupted: %s", requestLog) + } +} + +func TestRunBenchmarkStopsWhenTimedOutTurnCannotBeCleanedUp(t *testing.T) { + server, _ := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{ + "thread": map[string]string{"id": "thread-1"}, "model": "gpt-5.3-codex", + })}, + benchmarkEnvelope{ID: rawJSON(2), Result: rawJSON(map[string]any{"turn": map[string]string{"id": "turn-1"}})}, + ) + server.turnTimeout = 10 * time.Millisecond + server.interruptTimeout = 20 * time.Millisecond + result, fatalErr := server.runBenchmark(context.Background(), benchmarkCombination{ + model: benchmarkModel{Model: "gpt-5.3-codex", DisplayName: "GPT-5.3 Codex"}, effort: "low", + }, benchmarkTaskDefinitions[0]) + if fatalErr == nil || !errors.Is(fatalErr, context.DeadlineExceeded) { + t.Fatalf("failed cleanup error = %v, want deadline exceeded", fatalErr) + } + if result.Correct || !strings.Contains(result.Failure, "turn timed out after 10ms; cleanup failed") { + t.Fatalf("failed cleanup result = %#v", result) + } +} + func TestRunBenchmarkRejectsToolUseAndInvalidatesCost(t *testing.T) { message := string(rawJSON(map[string]string{"code": correctStarlarkSubmission})) usage := BenchmarkUsage{TotalTokens: 120, InputTokens: 100, OutputTokens: 20} From 5f1b98db6f61056ff81a09d0f46f9f400bfa0c4d Mon Sep 17 00:00:00 2001 From: merefield Date: Tue, 11 Aug 2026 22:25:30 +0100 Subject: [PATCH 9/9] Add forum introduction --- intro-post.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 intro-post.md diff --git a/intro-post.md b/intro-post.md new file mode 100644 index 00000000..23e1a82b --- /dev/null +++ b/intro-post.md @@ -0,0 +1,24 @@ +# Codexometer: a retro quota dashboard for Codex + +[Codexometer](https://github.com/merefield/codexometer) is a small, retro terminal dashboard for your current Codex quota. Leave it open in a second terminal window or pane to see every active usage window, its remaining capacity, and its reset time—without repeatedly opening `/status` in the Codex session where you are working. + +![codexometer|690x454](upload://xcWugpZYodk0zuFVYsDzluTemtf.png) + +## Why use it? + +`/status` is useful, but it lives inside your active session. Codexometer turns the same quota information into an always-visible companion display that refreshes automatically and uses your prevailing Codex login. + +You can choose from five colour themes and several responsive displays, including a consumption-pace meter that shows whether you are using quota faster or slower than the current window is elapsing. There is also a local token-activity monitor and an opt-in deterministic model benchmark. + +It works particularly well in: + +- another Windows Terminal tab or split pane; +- a second Terminal or iTerm window on macOS; +- a tmux, Zellij, or other terminal-multiplexer pane; +- an Ubuntu terminal beside the Codex CLI. + +Codexometer is written in Go and builds as a standalone binary for macOS, Windows, and Linux. + +**GitHub:** https://github.com/merefield/codexometer + +If you enjoy it, please give the project a ⭐ on GitHub!