diff --git a/README.md b/README.md index c9f5bd9e..bef66b39 100644 --- a/README.md +++ b/README.md @@ -76,9 +76,11 @@ It works particularly well in: For a root with linked agents, fresh activity from any member suppresses that uncertain fallback; definite input or approval signals still propagate from the member that raised them. -- An opt-in deterministic coding benchmark comparing every visible Codex model - and supported reasoning effort by correctness, elapsed time, token use, and - estimated standard API-equivalent cost. +- An opt-in deterministic coding benchmark comparing a selectable scope of + visible Codex models and supported reasoning efforts by correctness, elapsed + time, token use, and estimated standard API-equivalent cost. The current trial appears immediately + as an `IN PROGRESS` row; select or click any row to inspect its benchmark-only + prompt, structured response, verifier outcome, and telemetry. Codexometer does not assume that every account has the same windows. Some accounts expose a shorter rolling window and a weekly window; plans and backend @@ -315,9 +317,13 @@ boundary. It also reads lifecycle event names and blocking flags to identify an explicit unresolved input or approval request. To distinguish an open CLI waiting at its prompt from a closed historical session, it inspects the lock state—not the contents—of Codex's per-thread writer lock. Message text—including -the final response carried beside timing -metadata—reasoning, commands, tool results, and credentials are ignored and -never retained by Codexometer. +the final response carried beside timing metadata—reasoning, commands, tool +results, and credentials are ignored and never retained from ordinary Codex +sessions. The sole content-reading exception is a benchmark turn explicitly +started by Codexometer: its known prompt and visible structured response are +kept in bounded process memory for the Benchmark run detail view. Reasoning +events, credentials, request headers, and internal thread, turn, or response +IDs are not captured. When the managed shared daemon is available, Codexometer also keeps a local app-server subscription for already-loaded thread IDs. From that stream it @@ -341,16 +347,21 @@ codexometer --codex /path/to/codex | `Shift+Tab` | Select the previous top-level tab | | `r` | Refresh quota data immediately | | `v` | Cycle the active Quota view | -| `s` | Start recording (Monitor only) | +| `s` | Start recording (Monitor) or open Benchmark Scope | | `p` | Stop and take a final up-to-date reading (Monitor view only) | | `b` | Run the selected challenge (Benchmark view only) | | `a` | Arm, then confirm, Run All (Benchmark view only) | +| `x` | Stop the active benchmark suite and retain its incomplete trial | +| `d` | Close the Benchmark Scope screen | | `[` / `]`, `Left` / `Right` | Select the previous or next challenge | | `f` | Show all, passed, or failed benchmark results | | `w` | Cycle Cost, Balanced, and Speed benchmark ranking weights | +| `Up` / `Down` | Select a Benchmark row, or scroll its open detail | +| `Enter` / `Space` | Open a selected result, or toggle a Benchmark Scope checkbox | +| `c` | Copy the complete open Benchmark detail to the terminal clipboard | | `Page Up` / `Page Down` | Scroll Monitor session rows or Benchmark result pages | | `q` | Quit | -| `Esc` | Quit | +| `Esc` | Return from Benchmark detail or Scope; otherwise quit | | `Ctrl+C` | Quit | The responsive top rail below the account status selects Quota, Monitor, or @@ -737,23 +748,66 @@ Codexometer falls back to its safe defaults. ### Deterministic benchmark The Benchmark tab discovers the current account's visible models and their -supported reasoning efforts through `model/list`. Select any challenge with the -arrow buttons; the selector reserves a stable responsive track for the longest -name, so its controls do not move as the selection changes. Press `b` or click -**Run Selected** to run that challenge against every model/effort combination. -**Run All** runs the complete catalog against every combination. Because that -means `challenge count × model/effort count` model turns, Codexometer displays -the exact total and requires a second confirmation within five seconds. A fresh, -ephemeral, read-only app-server thread is used for each trial, so benchmark -history does not clutter normal Codex sessions. The turns still consume the -same account quota shown by Codexometer. +supported reasoning efforts through `model/list`. Initially every compatible +model/effort pair is selected. Press `s` or click **Scope** to open a separate +selection screen: every model and reasoning level has its own checkbox, and +each group has a **Check All** control that changes to **Clear All** when the +whole group is selected. The supported reasoning levels shown beside each +model dim immediately when they fall outside the selected scope. Click a row, +or use `Up`/`Down` and `Space`/`Enter`, then click **Done** or press `d`/`Esc` +to return. Unsupported model/effort intersections are never counted or run. + +Select any challenge with the arrow buttons; the selector reserves a stable +responsive track for the longest name, so its controls do not move as the +selection changes. Press `b` or click **Run Selected** to run that challenge +against the selected scope. **Run All** runs the complete challenge catalog +against that same scope. Because that means `challenge count × selected +model/effort pair count` model turns, Codexometer displays the exact total and +requires a second confirmation within five seconds. A fresh, ephemeral, +read-only app-server thread is used for each trial, so benchmark history does +not clutter normal Codex sessions. The turns still consume the same account +quota shown by Codexometer. 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. +the remaining combinations. App-server transport failure or failure to confirm +timeout interruption still stops the suite because the server's state is then +unsafe or unknown. + +The **Stop** control remains visible but disabled until a suite starts. Press +`x` or click **Stop** to request `turn/interrupt` for the current trial and wait +for its matching completion before the temporary app-server is closed. +Completed results are retained, the current row becomes `STOPPED`, remaining +trials are not started, and the status reports how many planned trials were +complete. A stopped row is incomplete rather than failed, so it appears under +**All** but not the **Fail** filter or rankings. If remote interruption cannot +be confirmed before cleanup, the stopped result reports that uncertainty as a +**Stop Issue**. + +The current trial appears in the existing Result Matrix immediately as an +`IN PROGRESS` row, before any result has completed. Click that or any completed +row, or use `Up`/`Down` followed by `Enter`, to replace the matrix with the +run's scrollable detail. An open live detail updates as safe benchmark events +arrive, then changes in place to the final `PASS`, `FAIL`, or `STOPPED` result. It shows the +requested and actual model, effort, task, outcome, live duration, token classes, +API-equivalent cost, exact benchmark prompt, visible structured response +(including the submitted Starlark), policy events, and deterministic-verifier +result. `Esc` returns to the same selected matrix row. Page keys, arrow keys, +and the mouse wheel scroll a long detail. Press `c` or click **Copy** in the +detail title to copy the complete unstyled detail, including interactions below +the visible scroll window. Copy uses the terminal's OSC 52 clipboard support, +which is not available in every terminal. + +This transcript is deliberately benchmark-only. It is populated directly by +the ephemeral thread that Codexometer created for that trial, bounded to 16 +entries of at most 64 KiB each and 128 KiB total, retained only in process +memory, and discarded when a new suite starts or Codexometer exits. It does not +subscribe to or read ordinary Codex conversations, and it excludes reasoning +events, credentials, request headers, and internal app-server IDs. +Codexometer sends that bounded transcript to the system clipboard only when you +explicitly press `c` or click **Copy**; the clipboard then falls under your +operating system and terminal's normal retention behavior. #### Challenges and difficulty diff --git a/internal/codex/benchmark.go b/internal/codex/benchmark.go index bd141b9e..5d0279f6 100644 --- a/internal/codex/benchmark.go +++ b/internal/codex/benchmark.go @@ -23,6 +23,9 @@ const ( benchmarkTurnTimeout = 5 * time.Minute benchmarkInterruptTimeout = 15 * time.Second benchmarkCodeLimit = 64 * 1024 + benchmarkInteractionLimit = 64 * 1024 + benchmarkTranscriptLimit = 128 * 1024 + benchmarkInteractionCount = 16 benchmarkStepLimit = 250_000 benchmarkHardStepLimit = 2_000_000 @@ -93,6 +96,24 @@ type BenchmarkResponseUsage struct { Usage BenchmarkUsage } +type BenchmarkInteractionKind string + +const ( + BenchmarkInteractionPrompt BenchmarkInteractionKind = "prompt" + BenchmarkInteractionResponse BenchmarkInteractionKind = "response" + BenchmarkInteractionPolicy BenchmarkInteractionKind = "policy" + BenchmarkInteractionVerifier BenchmarkInteractionKind = "verifier" +) + +// BenchmarkInteraction is content emitted only by a benchmark turn that +// Codexometer created. Codexometer never adds app-server IDs, credentials, +// request headers, or reasoning events to this transcript. +type BenchmarkInteraction struct { + Elapsed time.Duration + Kind BenchmarkInteractionKind + Content string +} + // BenchmarkResult contains one model/reasoning-effort run. type BenchmarkResult struct { TaskID BenchmarkTaskID @@ -102,6 +123,7 @@ type BenchmarkResult struct { Effort string ActualModel string Correct bool + Stopped bool Duration time.Duration Usage BenchmarkUsage UsageObserved bool @@ -115,6 +137,7 @@ type BenchmarkResult struct { ToolUsed bool ToolType string Failure string + Interactions []BenchmarkInteraction } // BenchmarkEvent incrementally reports discovery, execution, and results. @@ -126,11 +149,61 @@ type BenchmarkEvent struct { CurrentTask string CurrentModel string CurrentEffort string + Active *BenchmarkResult Result *BenchmarkResult + Stopped bool Done bool Err error } +// BenchmarkPlan describes the model and reasoning-effort choices currently +// advertised by the user's Codex account. +type BenchmarkPlan struct { + Models []BenchmarkModelOption + Efforts []string +} + +// BenchmarkModelOption is one selectable model and its supported efforts. +type BenchmarkModelOption struct { + Model string + DisplayName string + Efforts []string +} + +// BenchmarkScope selects the model/effort intersections included in a suite. +// Empty selections intentionally produce no combinations. +type BenchmarkScope struct { + Models []string + Efforts []string +} + +// AllScope selects every model and effort in the plan. +func (p BenchmarkPlan) AllScope() BenchmarkScope { + scope := BenchmarkScope{Efforts: append([]string(nil), p.Efforts...)} + for _, model := range p.Models { + scope.Models = append(scope.Models, model.Model) + } + return scope +} + +// CombinationCount returns the compatible model/effort pairs in scope. +func (p BenchmarkPlan) CombinationCount(scope BenchmarkScope) int { + models := stringSet(scope.Models) + efforts := stringSet(scope.Efforts) + count := 0 + for _, model := range p.Models { + if !models[model.Model] { + continue + } + for _, effort := range model.Efforts { + if efforts[effort] { + count++ + } + } + } + return count +} + type benchmarkModel struct { ID string `json:"id"` Model string `json:"model"` @@ -209,16 +282,26 @@ func (b *lockedBuffer) String() string { // BenchmarkCombinationCount returns the number of visible model/effort pairs // without starting a model turn. func (c Client) BenchmarkCombinationCount(ctx context.Context) (int, error) { - server, err := openBenchmarkAppServer(ctx, c.Binary) + plan, err := c.BenchmarkPlan(ctx) if err != nil { return 0, err } + return plan.CombinationCount(plan.AllScope()), nil +} + +// BenchmarkPlan returns the visible model/effort catalog without starting a +// model turn. +func (c Client) BenchmarkPlan(ctx context.Context) (BenchmarkPlan, error) { + server, err := openBenchmarkAppServer(ctx, c.Binary) + if err != nil { + return BenchmarkPlan{}, err + } defer server.close() models, err := server.models(ctx) if err != nil { - return 0, err + return BenchmarkPlan{}, err } - return len(benchmarkCombinations(models)), nil + return benchmarkPlan(models), nil } // RunBenchmarkSuite runs each selected deterministic task once for every @@ -226,29 +309,40 @@ func (c Client) BenchmarkCombinationCount(ctx context.Context) (int, error) { var openBenchmarkAppServer = startAppServer func (c Client) RunBenchmarkSuite(ctx context.Context, taskIDs []BenchmarkTaskID, emit func(BenchmarkEvent)) { + c.runBenchmarkSuite(ctx, taskIDs, emit) +} + +// RunBenchmarkSuiteScoped runs the selected tasks only for compatible pairs in +// scope. It is separate from RunBenchmarkSuite to preserve the all-model +// behavior for callers that do not expose scope controls. +func (c Client) RunBenchmarkSuiteScoped(ctx context.Context, taskIDs []BenchmarkTaskID, scope BenchmarkScope, emit func(BenchmarkEvent)) { + c.runBenchmarkSuite(ctx, taskIDs, emit, scope) +} + +func (c Client) runBenchmarkSuite(ctx context.Context, taskIDs []BenchmarkTaskID, emit func(BenchmarkEvent), scopes ...BenchmarkScope) { if emit == nil { emit = func(BenchmarkEvent) {} } definitions, err := resolveBenchmarkTasks(taskIDs) if err != nil { - emit(BenchmarkEvent{Done: true, Err: err}) + emit(benchmarkTerminalEvent(ctx, 0, 0, 0, err)) return } server, err := openBenchmarkAppServer(ctx, c.Binary) if err != nil { - emit(BenchmarkEvent{Done: true, Err: err}) + emit(benchmarkTerminalEvent(ctx, 0, 0, 0, err)) return } defer server.close() models, err := server.models(ctx) if err != nil { - emit(BenchmarkEvent{Done: true, Err: err}) + emit(benchmarkTerminalEvent(ctx, 0, 0, 0, err)) return } - combinations := benchmarkCombinations(models) + combinations := benchmarkCombinations(models, scopes...) if len(combinations) == 0 { - emit(BenchmarkEvent{Done: true, Err: errors.New("Codex returned no benchmarkable models")}) + emit(BenchmarkEvent{Done: true, Err: errors.New("selected benchmark scope has no compatible model/effort pairs")}) return } total := len(combinations) * len(definitions) @@ -258,7 +352,7 @@ func (c Client) RunBenchmarkSuite(ctx context.Context, taskIDs []BenchmarkTaskID for _, definition := range definitions { for _, combination := range combinations { if err := ctx.Err(); err != nil { - emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: len(combinations), Done: true, Err: err}) + emit(benchmarkTerminalEvent(ctx, total, completed, len(combinations), err)) return } event := BenchmarkEvent{ @@ -266,10 +360,20 @@ func (c Client) RunBenchmarkSuite(ctx context.Context, taskIDs []BenchmarkTaskID CurrentTaskID: definition.task.ID, CurrentTask: definition.task.Name, CurrentModel: combination.model.DisplayName, CurrentEffort: combination.effort, } - emit(event) - result, fatalErr := server.runBenchmark(ctx, combination, definition) + result, fatalErr := server.runBenchmark(ctx, combination, definition, func(active BenchmarkResult) { + active = benchmarkResultSnapshot(active) + event.Active, event.Result = &active, nil + emit(event) + }) + if fatalErr != nil && errors.Is(ctx.Err(), context.Canceled) { + markBenchmarkStopped(&result) + event.Active, event.Result, event.Stopped = nil, &result, true + emit(event) + emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: len(combinations), Stopped: true, Done: true}) + return + } completed++ - event.Completed, event.Result = completed, &result + event.Completed, event.Active, event.Result = completed, nil, &result emit(event) if fatalErr != nil { emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: len(combinations), Done: true, Err: fatalErr}) @@ -280,6 +384,30 @@ func (c Client) RunBenchmarkSuite(ctx context.Context, taskIDs []BenchmarkTaskID emit(BenchmarkEvent{Total: total, Completed: completed, Combinations: len(combinations), Done: true}) } +func benchmarkTerminalEvent(ctx context.Context, total, completed, combinations int, err error) BenchmarkEvent { + stopped := errors.Is(ctx.Err(), context.Canceled) + if stopped { + err = nil + } + return BenchmarkEvent{ + Total: total, Completed: completed, Combinations: combinations, + Stopped: stopped, Done: true, Err: err, + } +} + +func markBenchmarkStopped(result *BenchmarkResult) { + if result == nil { + return + } + result.Correct = false + result.Stopped = true + if !strings.HasPrefix(result.Failure, "remote interruption could not be confirmed") { + result.Failure = "" + } + startedAt := time.Now().Add(-result.Duration) + appendBenchmarkInteraction(result, startedAt, BenchmarkInteractionVerifier, "Benchmark stopped before completion.") +} + func startAppServer(ctx context.Context, binary string) (*appServerSession, error) { return startAppServerWithExperimentalUsage(ctx, binary, true) } @@ -288,7 +416,10 @@ func startAppServerWithExperimentalUsage(ctx context.Context, binary string, exp if strings.TrimSpace(binary) == "" { binary = "codex" } - cmd := exec.CommandContext(ctx, binary, "app-server", "--stdio") + // Calls remain context-bound, but the short-lived process is closed + // explicitly so a cancelled benchmark still has a chance to send and confirm + // turn/interrupt before teardown. + cmd := exec.Command(binary, "app-server", "--stdio") stdin, err := cmd.StdinPipe() if err != nil { return nil, fmt.Errorf("open Codex input: %w", err) @@ -478,12 +609,20 @@ func (s *appServerSession) models(ctx context.Context) ([]benchmarkModel, error) return models, nil } -func benchmarkCombinations(models []benchmarkModel) []benchmarkCombination { +func benchmarkCombinations(models []benchmarkModel, scopes ...BenchmarkScope) []benchmarkCombination { + var selectedModels, selectedEfforts map[string]bool + if len(scopes) > 0 { + selectedModels = stringSet(scopes[0].Models) + selectedEfforts = stringSet(scopes[0].Efforts) + } var combinations []benchmarkCombination for _, model := range models { if strings.TrimSpace(model.Model) == "" { continue } + if selectedModels != nil && !selectedModels[model.Model] { + continue + } if strings.TrimSpace(model.DisplayName) == "" { model.DisplayName = model.Model } @@ -492,11 +631,13 @@ func benchmarkCombinations(models []benchmarkModel) []benchmarkCombination { if effort == "" { effort = "default" } - combinations = append(combinations, benchmarkCombination{model: model, effort: effort}) + if selectedEfforts == nil || selectedEfforts[effort] { + combinations = append(combinations, benchmarkCombination{model: model, effort: effort}) + } continue } for _, option := range model.SupportedReasoningEfforts { - if effort := strings.TrimSpace(option.ReasoningEffort); effort != "" { + if effort := strings.TrimSpace(option.ReasoningEffort); effort != "" && (selectedEfforts == nil || selectedEfforts[effort]) { combinations = append(combinations, benchmarkCombination{model: model, effort: effort}) } } @@ -504,12 +645,55 @@ func benchmarkCombinations(models []benchmarkModel) []benchmarkCombination { return combinations } -func (s *appServerSession) runBenchmark(ctx context.Context, combination benchmarkCombination, definition benchmarkDefinition) (BenchmarkResult, error) { - result := BenchmarkResult{ - TaskID: definition.task.ID, TaskName: definition.task.Name, - Model: combination.model.Model, DisplayName: combination.model.DisplayName, - Effort: combination.effort, ActualModel: combination.model.Model, +func benchmarkPlan(models []benchmarkModel) BenchmarkPlan { + combinations := benchmarkCombinations(models) + plan := BenchmarkPlan{} + modelIndexes := make(map[string]int) + efforts := make(map[string]bool) + for _, combination := range combinations { + index, ok := modelIndexes[combination.model.Model] + if !ok { + index = len(plan.Models) + modelIndexes[combination.model.Model] = index + plan.Models = append(plan.Models, BenchmarkModelOption{ + Model: combination.model.Model, DisplayName: combination.model.DisplayName, + }) + } + plan.Models[index].Efforts = append(plan.Models[index].Efforts, combination.effort) + if !efforts[combination.effort] { + efforts[combination.effort] = true + plan.Efforts = append(plan.Efforts, combination.effort) + } + } + return plan +} + +func stringSet(values []string) map[string]bool { + set := make(map[string]bool, len(values)) + for _, value := range values { + set[value] = true } + return set +} + +func (s *appServerSession) runBenchmark( + ctx context.Context, + combination benchmarkCombination, + definition benchmarkDefinition, + progressCallbacks ...func(BenchmarkResult), +) (BenchmarkResult, error) { + result := benchmarkPendingResult(combination, definition) + var startedAt time.Time + publish := func() { + if len(progressCallbacks) > 0 && progressCallbacks[0] != nil { + snapshot := benchmarkResultSnapshot(result) + if !startedAt.IsZero() { + snapshot.Duration = time.Since(startedAt) + } + progressCallbacks[0](snapshot) + } + } + publish() turnTimeout := s.benchmarkTurnTimeout() turnCtx, cancel := context.WithTimeout(ctx, turnTimeout) defer cancel() @@ -558,11 +742,13 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma } if startedThread.Model != "" { result.ActualModel = startedThread.Model + publish() } - startedAt := time.Now() + startedAt = time.Now() + prompt := benchmarkPrompt(definition) turnParams := map[string]any{ "threadId": startedThread.Thread.ID, - "input": []map[string]any{{"type": "text", "text": benchmarkPrompt(definition)}}, + "input": []map[string]any{{"type": "text", "text": prompt}}, "outputSchema": benchmarkOutputSchema, } if combination.effort != "default" && combination.effort != "" { @@ -572,6 +758,8 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma if err != nil { result.Duration = time.Since(startedAt) result.Failure = fmt.Sprintf("start turn: %v", err) + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionVerifier, "Run failed before the model turn started.") + publish() return result, fatalBenchmarkError(turnCtx, err) } var startedTurn struct { @@ -582,6 +770,8 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma if err := json.Unmarshal(turnResponse, &startedTurn); err != nil || startedTurn.Turn.ID == "" { result.Duration = time.Since(startedAt) result.Failure = "Codex returned an invalid turn" + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionVerifier, result.Failure) + publish() return result, nil } @@ -600,6 +790,12 @@ 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 { telemetry.recordCumulative(event.TokenUsage.Total) + preview := benchmarkResultSnapshot(result) + preview.Duration = time.Since(startedAt) + applyBenchmarkMeasurements(&preview, telemetry) + if len(progressCallbacks) > 0 && progressCallbacks[0] != nil { + progressCallbacks[0](preview) + } } case "rawResponse/completed": var event struct { @@ -619,6 +815,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 + publish() } case "item/started", "item/completed": var event struct { @@ -630,11 +827,19 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma } `json:"item"` } if json.Unmarshal(params, &event) == nil && event.ThreadID == startedThread.Thread.ID && event.TurnID == startedTurn.Turn.ID { + changed := false if benchmarkToolItem(event.Item.Type) && !result.ToolUsed { result.ToolUsed, result.ToolType = true, event.Item.Type + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionPolicy, "Prohibited tool event observed: "+event.Item.Type) + changed = true } if method == "item/completed" && event.Item.Type == "agentMessage" { finalMessage = event.Item.Text + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionResponse, finalMessage) + changed = true + } + if changed { + publish() } } case "turn/completed": @@ -664,6 +869,8 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma for _, item := range event.Turn.Items { if item.Type == "agentMessage" { finalMessage = item.Text + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionResponse, finalMessage) + publish() } } } @@ -676,16 +883,30 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma _, err = s.readUntilNotification(turnCtx, handleNotification) if err != nil { result.Duration = time.Since(startedAt) + if errors.Is(ctx.Err(), context.Canceled) { + cleanupCtx, cancel := context.WithTimeout(context.Background(), s.benchmarkInterruptTimeout()) + interruptErr := s.interruptBenchmarkTurn(cleanupCtx, startedThread.Thread.ID, startedTurn.Turn.ID, &completed, handleNotification) + cancel() + applyBenchmarkMeasurements(&result, telemetry) + if interruptErr != nil { + result.Failure = "remote interruption could not be confirmed: " + interruptErr.Error() + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionVerifier, "Stop requested; "+result.Failure) + } + return result, ctx.Err() + } 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() + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionVerifier, "Turn timed out and interruption could not be confirmed.") return result, fmt.Errorf("recover timed-out benchmark turn: %w", interruptErr) } applyBenchmarkMeasurements(&result, telemetry) + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionVerifier, result.Failure) return result, nil } result.Failure = fmt.Sprintf("wait for turn: %v", err) + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionVerifier, "App-server transport failed before benchmark completion.") return result, err } } @@ -693,25 +914,75 @@ func (s *appServerSession) runBenchmark(ctx context.Context, combination benchma applyBenchmarkMeasurements(&result, telemetry) if turnFailure != "" { result.Failure = turnFailure + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionVerifier, "Codex turn did not complete successfully.") return result, nil } if result.ToolUsed { result.Failure = "tool use prohibited: " + result.ToolType + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionVerifier, result.Failure) return result, nil } code, err := benchmarkCode(finalMessage) if err != nil { result.Failure = err.Error() + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionVerifier, result.Failure) return result, nil } if err := definition.verify(code); err != nil { result.Failure = err.Error() + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionVerifier, result.Failure) return result, nil } result.Correct = true + appendBenchmarkInteraction(&result, startedAt, BenchmarkInteractionVerifier, "Submission passed the deterministic verifier.") return result, nil } +func benchmarkPendingResult(combination benchmarkCombination, definition benchmarkDefinition) BenchmarkResult { + result := BenchmarkResult{ + TaskID: definition.task.ID, TaskName: definition.task.Name, + Model: combination.model.Model, DisplayName: combination.model.DisplayName, + Effort: combination.effort, ActualModel: combination.model.Model, + } + appendBenchmarkInteraction(&result, time.Time{}, BenchmarkInteractionPrompt, benchmarkPrompt(definition)) + return result +} + +func benchmarkResultSnapshot(result BenchmarkResult) BenchmarkResult { + result.Interactions = append([]BenchmarkInteraction(nil), result.Interactions...) + result.ResponseUsage = append([]BenchmarkResponseUsage(nil), result.ResponseUsage...) + return result +} + +func appendBenchmarkInteraction(result *BenchmarkResult, startedAt time.Time, kind BenchmarkInteractionKind, content string) { + if result == nil || len(result.Interactions) >= benchmarkInteractionCount { + return + } + used := 0 + for _, interaction := range result.Interactions { + used += len(interaction.Content) + } + remaining := benchmarkTranscriptLimit - used + if remaining <= 0 { + return + } + content = strings.ToValidUTF8(content, "�") + limit := min(benchmarkInteractionLimit, remaining) + if len(content) > limit { + const marker = "\n… [truncated by Codexometer]" + contentLimit := max(limit-len(marker), 0) + content = strings.ToValidUTF8(content[:contentLimit], "") + if len(marker) <= limit { + content += marker + } + } + elapsed := time.Duration(0) + if !startedAt.IsZero() { + elapsed = time.Since(startedAt) + } + result.Interactions = append(result.Interactions, BenchmarkInteraction{Elapsed: elapsed, Kind: kind, Content: content}) +} + func (s *appServerSession) benchmarkTurnTimeout() time.Duration { if s.turnTimeout > 0 { return s.turnTimeout diff --git a/internal/codex/benchmark_test.go b/internal/codex/benchmark_test.go index 296394c5..4163aa50 100644 --- a/internal/codex/benchmark_test.go +++ b/internal/codex/benchmark_test.go @@ -11,6 +11,7 @@ import ( "strings" "testing" "time" + "unicode/utf8" ) const correctStarlarkSubmission = ` @@ -250,6 +251,43 @@ func TestRunBenchmarkConsumesStreamedResultAndUsage(t *testing.T) { if !strings.Contains(requests.String(), `"sandbox":"read-only"`) { t.Fatalf("thread request did not use the app-server sandbox spelling: %s", requests.String()) } + if len(result.Interactions) != 3 || result.Interactions[0].Kind != BenchmarkInteractionPrompt || result.Interactions[1].Kind != BenchmarkInteractionResponse || result.Interactions[2].Kind != BenchmarkInteractionVerifier { + t.Fatalf("benchmark interaction transcript = %#v", result.Interactions) + } + if !strings.Contains(result.Interactions[0].Content, "Starlark language contract") || result.Interactions[1].Content != message || !strings.Contains(result.Interactions[2].Content, "passed") { + t.Fatalf("benchmark interaction content = %#v", result.Interactions) + } + for _, interaction := range result.Interactions { + if strings.Contains(interaction.Content, "thread-1") || strings.Contains(interaction.Content, "turn-1") { + t.Fatalf("internal app-server ID leaked into benchmark transcript: %#v", result.Interactions) + } + } +} + +func TestBenchmarkInteractionCaptureIsBoundedAndValidUTF8(t *testing.T) { + countBounded := BenchmarkResult{} + for index := 0; index < benchmarkInteractionCount+4; index++ { + appendBenchmarkInteraction(&countBounded, time.Time{}, BenchmarkInteractionPolicy, "event") + } + if len(countBounded.Interactions) != benchmarkInteractionCount { + t.Fatalf("captured %d interactions, want %d", len(countBounded.Interactions), benchmarkInteractionCount) + } + + result := BenchmarkResult{} + content := strings.Repeat("x", benchmarkInteractionLimit-1) + "£" + strings.Repeat("y", 10) + for index := 0; index < benchmarkInteractionCount+4; index++ { + appendBenchmarkInteraction(&result, time.Time{}, BenchmarkInteractionResponse, content) + } + total := 0 + for _, interaction := range result.Interactions { + total += len(interaction.Content) + if !strings.Contains(interaction.Content, "[truncated by Codexometer]") || !utf8.ValidString(interaction.Content) { + t.Fatalf("bounded interaction was not valid, visibly truncated UTF-8: %q", interaction.Content[len(interaction.Content)-64:]) + } + } + if total > benchmarkTranscriptLimit { + t.Fatalf("transcript captured %d bytes, limit is %d", total, benchmarkTranscriptLimit) + } } func TestRunBenchmarkFailsClosedWhenUsageIsMissing(t *testing.T) { @@ -351,6 +389,62 @@ func TestRunBenchmarkSuiteInterruptsTimedOutTurnAndContinues(t *testing.T) { } } +func TestRunBenchmarkSuiteMarksCancelledCurrentTrialStopped(t *testing.T) { + server, requests := newFakeBenchmarkServer( + benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{ + "data": []any{map[string]any{ + "model": "gpt-5.6-luna", "displayName": "GPT-5.6 Luna", + "supportedReasoningEfforts": []any{map[string]string{"reasoningEffort": "low"}}, + }}, + })}, + benchmarkEnvelope{ID: rawJSON(2), Result: rawJSON(map[string]any{ + "thread": map[string]string{"id": "thread-low"}, "model": "gpt-5.6-luna", + })}, + benchmarkEnvelope{ID: rawJSON(3), Result: rawJSON(map[string]any{"turn": map[string]string{"id": "turn-low"}})}, + 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}}, + })}, + benchmarkEnvelope{ID: rawJSON(4), Result: rawJSON(map[string]any{})}, + benchmarkEnvelope{Method: "turn/completed", Params: rawJSON(map[string]any{ + "threadId": "thread-low", "turn": map[string]any{"id": "turn-low", "status": "interrupted"}, + })}, + ) + original := openBenchmarkAppServer + openBenchmarkAppServer = func(context.Context, string) (*appServerSession, error) { return server, nil } + t.Cleanup(func() { openBenchmarkAppServer = original }) + + ctx, cancel := context.WithCancel(context.Background()) + var events []BenchmarkEvent + Client{}.RunBenchmarkSuite(ctx, []BenchmarkTaskID{BenchmarkMergeRanges}, func(event BenchmarkEvent) { + events = append(events, event) + if event.Active != nil && event.Active.UsageKnown { + cancel() + } + }) + + var stopped *BenchmarkResult + for _, event := range events { + if event.Result != nil && event.Result.Stopped { + result := *event.Result + stopped = &result + } + } + if stopped == nil || stopped.Correct || stopped.Failure != "" { + t.Fatalf("cancelled current trial was not retained as stopped: %#v", stopped) + } + if len(stopped.Interactions) < 2 || stopped.Interactions[len(stopped.Interactions)-1].Content != "Benchmark stopped before completion." { + t.Fatalf("stopped transcript is incomplete: %#v", stopped.Interactions) + } + final := events[len(events)-1] + if !final.Done || !final.Stopped || final.Err != nil || final.Completed != 0 || final.Total != 1 { + t.Fatalf("stopped suite final event = %#v", final) + } + if requestLog := requests.String(); !strings.Contains(requestLog, `"method":"turn/interrupt"`) || !strings.Contains(requestLog, `"turnId":"turn-low"`) { + t.Fatalf("Stop did not interrupt the remote turn: %s", requestLog) + } +} + func TestRunBenchmarkStopsWhenTimedOutTurnCannotBeCleanedUp(t *testing.T) { server, _ := newFakeBenchmarkServer( benchmarkEnvelope{ID: rawJSON(1), Result: rawJSON(map[string]any{ @@ -660,8 +754,22 @@ func TestRunBenchmarkSuiteDiscoversAndRunsEveryCombination(t *testing.T) { events = append(events, event) }) var efforts []string - for _, event := range events { + activeEfforts := make(map[string]bool) + firstActive, firstResult := -1, -1 + for index, event := range events { + if event.Active != nil { + activeEfforts[event.Active.Effort] = true + if firstActive < 0 { + firstActive = index + } + if len(event.Active.Interactions) == 0 || event.Active.Interactions[0].Kind != BenchmarkInteractionPrompt { + t.Fatalf("active event omitted the benchmark prompt: %#v", event.Active) + } + } if event.Result != nil { + if firstResult < 0 { + firstResult = index + } if !event.Result.Correct { t.Fatalf("suite result failed: %#v", event.Result) } @@ -671,6 +779,9 @@ func TestRunBenchmarkSuiteDiscoversAndRunsEveryCombination(t *testing.T) { if len(efforts) != 2 || efforts[0] != "low" || efforts[1] != "high" { t.Fatalf("suite efforts = %v, want [low high]", efforts) } + if !activeEfforts["low"] || !activeEfforts["high"] || firstActive < 0 || firstActive >= firstResult { + t.Fatalf("suite active events = %v, first active/result = %d/%d", activeEfforts, firstActive, firstResult) + } last := events[len(events)-1] if !last.Done || last.Err != nil || last.Total != 2 || last.Completed != 2 { t.Fatalf("final suite event = %#v", last) @@ -966,6 +1077,22 @@ func TestBenchmarkCombinationsPreserveCatalogOrder(t *testing.T) { } } +func TestBenchmarkPlanFiltersCompatibleModelEffortPairs(t *testing.T) { + models := []benchmarkModel{ + {Model: "model-a", DisplayName: "Model A", SupportedReasoningEfforts: []benchmarkEffortOption{{ReasoningEffort: "low"}, {ReasoningEffort: "high"}}}, + {Model: "model-b", DisplayName: "Model B", SupportedReasoningEfforts: []benchmarkEffortOption{{ReasoningEffort: "low"}}}, + } + plan := benchmarkPlan(models) + if len(plan.Models) != 2 || len(plan.Efforts) != 2 || plan.CombinationCount(plan.AllScope()) != 3 { + t.Fatalf("benchmark plan = %#v", plan) + } + scope := BenchmarkScope{Models: []string{"model-a"}, Efforts: []string{"high"}} + combinations := benchmarkCombinations(models, scope) + if plan.CombinationCount(scope) != 1 || len(combinations) != 1 || combinations[0].model.Model != "model-a" || combinations[0].effort != "high" { + t.Fatalf("scoped combinations = %#v", combinations) + } +} + func TestEstimateAPICostUsesCachedAndOutputRates(t *testing.T) { usage := BenchmarkUsage{ InputTokens: 2_000, CachedInputTokens: 500, CacheWriteInputTokens: 100, diff --git a/internal/ui/benchmark.go b/internal/ui/benchmark.go index 158aa171..1ea2f31a 100644 --- a/internal/ui/benchmark.go +++ b/internal/ui/benchmark.go @@ -54,6 +54,8 @@ type benchmarkControlSegment struct { active bool } +const benchmarkDetailCopyLabel = "[ (C) COPY ]" + func layoutBenchmarkArea(width, height int) benchmarkGeometry { width = max(width, 1) height = max(height, 1) @@ -95,6 +97,12 @@ func (m Model) renderBenchmarkArea(width, height int, colors palette) string { } return colors.dimmed().Render(strings.Join(lines, "\n")) } + if m.benchmarkScopeOpen { + return m.renderBenchmarkScope(width, height, colors) + } + if m.benchmarkDetail != nil { + return m.renderBenchmarkDetail(width, height, colors) + } layout := layoutBenchmarkArea(width, height) controls := m.renderBenchmarkControls(layout.controlsWidth, layout.controlsHeight, colors) top := controls @@ -116,6 +124,461 @@ func (m Model) renderBenchmarkArea(width, height int, colors palette) string { return view } +func (m Model) renderBenchmarkDetail(width, height int, colors palette) string { + width, height = max(width, 1), max(height, 1) + if m.benchmarkDetail == nil { + return "" + } + innerWidth := max(width-4, 1) + bodyHeight := max(height-2, 1) + lines := m.benchmarkDetailLines(innerWidth, colors) + maximum := max(len(lines)-bodyHeight, 0) + scroll := min(max(m.benchmarkDetailScroll, 0), maximum) + end := min(scroll+bodyHeight, len(lines)) + visible := lines[scroll:end] + for len(visible) < bodyHeight { + visible = append(visible, strings.Repeat(" ", innerWidth)) + } + detailState := "RUN DETAIL" + if m.benchmarkDetailActive { + detailState = "LIVE RUN DETAIL // IN PROGRESS" + } + title := fmt.Sprintf("%s // BENCHMARK-ONLY // LINES %d-%d/%d // ESC BACK", detailState, min(scroll+1, len(lines)), end, len(lines)) + return frameSizedWithTitleAction(width, bodyHeight, ansi.Truncate(title, max(innerWidth-4, 1), ""), m.renderBenchmarkDetailCopy(colors), strings.Join(visible, "\n"), colors.primary, colors) +} + +func (m Model) benchmarkDetailLines(width int, colors palette) []string { + result, ok := m.benchmarkDetailResult() + if !ok { + return nil + } + model := result.DisplayName + if model == "" { + model = result.Model + } + if result.ActualModel != "" && result.ActualModel != result.Model { + model += " → " + result.ActualModel + } + outcome := "FAIL" + outcomeStyle := lipgloss.NewStyle().Bold(true).Foreground(colors.danger) + if result.Stopped { + outcome = "STOPPED" + outcomeStyle = lipgloss.NewStyle().Bold(true).Foreground(colors.warning) + } else if m.benchmarkDetailActive { + outcome = "IN PROGRESS" + outcomeStyle = lipgloss.NewStyle().Bold(true).Foreground(colors.accent) + } else if result.Correct { + outcome = "PASS" + outcomeStyle = lipgloss.NewStyle().Bold(true).Foreground(colors.primary) + } + lines := []string{ + outcomeStyle.Render(fitTableCell("RESULT // "+outcome, width)), + colors.label().Render(fitTableCell("MODEL // "+model+" // EFFORT // "+strings.ToUpper(result.Effort), width)), + colors.label().Render(fitTableCell("TASK // "+result.TaskName+" // TIME // "+formatBenchmarkDuration(result.Duration), width)), + } + usage := "TOKENS // N/A" + if result.UsageKnown { + usage = "TOKENS // " + benchmarkUsageDetail(result) + } + lines = append(lines, colors.dimmed().Render(fitTableCell(usage, width))) + cost := "API EQ // N/A" + if result.CostKnown { + cost = fmt.Sprintf("API EQ // ~$%.4f", result.CostUSD) + } else if result.CostIssue != "" { + cost += " // " + result.CostIssue + } + lines = append(lines, colors.dimmed().Render(fitTableCell(cost, width))) + if result.Failure != "" { + label := "FAILURE // " + if result.Stopped { + label = "STOP ISSUE // " + } + lines = append(lines, lipgloss.NewStyle().Foreground(colors.danger).Render(fitTableCell(label+result.Failure, width))) + } + lines = append(lines, colors.dimmed().Render(strings.Repeat("─", width))) + if len(result.Interactions) == 0 { + lines = append(lines, + colors.label().Render(fitTableCell("BENCHMARK TRANSCRIPT // UNAVAILABLE", width)), + colors.dimmed().Render(fitTableCell("This result predates detail capture or was supplied by demo data.", width)), + ) + return lines + } + for index, interaction := range result.Interactions { + if index > 0 { + lines = append(lines, colors.dimmed().Render(strings.Repeat("─", width))) + } + heading := fmt.Sprintf("%s // +%s", strings.ToUpper(string(interaction.Kind)), formatBenchmarkDuration(interaction.Elapsed)) + headingStyle := colors.label() + if interaction.Kind == codex.BenchmarkInteractionVerifier && !result.Correct { + headingStyle = lipgloss.NewStyle().Bold(true).Foreground(colors.danger) + } + lines = append(lines, headingStyle.Render(fitTableCell(heading, width))) + contentStyle := lipgloss.NewStyle().Foreground(colors.primary) + if interaction.Kind == codex.BenchmarkInteractionPolicy { + contentStyle = lipgloss.NewStyle().Foreground(colors.warning) + } + for _, line := range benchmarkDetailWrap(interaction.Content, width) { + lines = append(lines, contentStyle.Render(fitTableCell(line, width))) + } + } + return lines +} + +func (m Model) benchmarkDetailResult() (codex.BenchmarkResult, bool) { + if m.benchmarkDetail == nil { + return codex.BenchmarkResult{}, false + } + result := *m.benchmarkDetail + if m.benchmarkDetailActive { + if active := m.currentBenchmarkActive(); active != nil && benchmarkRunKey(*active) == benchmarkRunKey(result) { + result = *active + } + } + return result, true +} + +func (m Model) renderBenchmarkDetailCopy(colors palette) string { + style := lipgloss.NewStyle().Foreground(colors.dim).Background(colors.background) + if m.hoveredButton == footerButtonBenchmarkCopy { + style = style.Bold(true).Foreground(colors.accent) + } + if m.flashedButton == footerButtonBenchmarkCopy { + style = style.Bold(true).Foreground(colors.background).Background(colors.primary) + } + return style.Render(benchmarkDetailCopyLabel) +} + +func (m Model) benchmarkDetailClipboardText() string { + result, ok := m.benchmarkDetailResult() + if !ok { + return "" + } + status := "FAIL" + if result.Stopped { + status = "STOPPED" + } else if m.benchmarkDetailActive { + status = "IN PROGRESS" + } else if result.Correct { + status = "PASS" + } + model := result.DisplayName + if model == "" { + model = result.Model + } + + var output strings.Builder + output.WriteString("CODEXOMETER BENCHMARK RUN DETAIL\n") + output.WriteString("TRANSCRIPT: BENCHMARK-ONLY\n") + fmt.Fprintf(&output, "RESULT: %s\n", status) + fmt.Fprintf(&output, "MODEL: %s\n", model) + if result.ActualModel != "" && result.ActualModel != result.Model { + fmt.Fprintf(&output, "ACTUAL MODEL: %s\n", result.ActualModel) + } + fmt.Fprintf(&output, "EFFORT: %s\n", strings.ToUpper(result.Effort)) + fmt.Fprintf(&output, "TASK: %s\n", result.TaskName) + fmt.Fprintf(&output, "TIME: %s\n", formatBenchmarkDuration(result.Duration)) + if result.UsageKnown { + fmt.Fprintf(&output, "TOKENS: %s\n", benchmarkUsageDetail(result)) + } else { + output.WriteString("TOKENS: N/A\n") + } + if result.CostKnown { + fmt.Fprintf(&output, "API EQ: ~$%.4f\n", result.CostUSD) + } else if result.CostIssue != "" { + fmt.Fprintf(&output, "API EQ: N/A // %s\n", result.CostIssue) + } else { + output.WriteString("API EQ: N/A\n") + } + if result.Failure != "" { + label := "FAILURE" + if result.Stopped { + label = "STOP ISSUE" + } + fmt.Fprintf(&output, "%s: %s\n", label, result.Failure) + } + if len(result.Interactions) == 0 { + output.WriteString("\nBENCHMARK TRANSCRIPT: UNAVAILABLE\n") + return output.String() + } + for _, interaction := range result.Interactions { + fmt.Fprintf(&output, "\n[%s +%s]\n", strings.ToUpper(string(interaction.Kind)), formatBenchmarkDuration(interaction.Elapsed)) + if interaction.Content == "" { + output.WriteString("(empty)\n") + continue + } + output.WriteString(interaction.Content) + if !strings.HasSuffix(interaction.Content, "\n") { + output.WriteByte('\n') + } + } + return output.String() +} + +func benchmarkUsageDetail(result codex.BenchmarkResult) string { + detail := fmt.Sprintf("TOTAL %d // INPUT %d // CACHED %d // OUTPUT %d // REASONING %d", + result.Usage.TotalTokens, result.Usage.InputTokens, result.Usage.CachedInputTokens, + result.Usage.OutputTokens, result.Usage.ReasoningOutputTokens) + if result.UsageSource != "" { + detail += " // SOURCE " + string(result.UsageSource) + } + return detail +} + +func benchmarkDetailWrap(content string, width int) []string { + width = max(width, 1) + content = strings.ReplaceAll(content, "\t", " ") + if content == "" { + return []string{"(empty)"} + } + wrapped := ansi.Wrap(content, width, " \t") + lines := strings.Split(wrapped, "\n") + for index := range lines { + lines[index] = ansi.Truncate(lines[index], width, "") + } + return lines +} + +func (m Model) benchmarkDetailPageSize() int { + layout := m.dashboardLayout() + return max(layout.meterHeight-2, 1) +} + +func (m Model) benchmarkDetailMaximumScroll() int { + if m.benchmarkDetail == nil { + return 0 + } + layout := m.dashboardLayout() + lines := m.benchmarkDetailLines(max(layout.contentWidth-4, 1), paletteFor(m.theme)) + return max(len(lines)-max(layout.meterHeight-2, 1), 0) +} + +type benchmarkScopeItemKind int + +const ( + benchmarkScopeDone benchmarkScopeItemKind = iota + benchmarkScopeAllModels + benchmarkScopeModel + benchmarkScopeAllEfforts + benchmarkScopeEffort +) + +type benchmarkScopeItem struct { + kind benchmarkScopeItemKind + value string + label string + efforts []string + selected bool +} + +func (m Model) renderBenchmarkScope(width, height int, colors palette) string { + width, height = max(width, 1), max(height, 1) + innerWidth := max(width-4, 1) + bodyHeight := max(height-2, 1) + items := m.benchmarkScopeItems() + selectedEfforts := stringSetUI(m.benchmarkScope.Efforts) + start := min(max(m.benchmarkScopeScroll, 0), max(len(items)-bodyHeight, 0)) + end := min(start+bodyHeight, len(items)) + lines := make([]string, 0, bodyHeight) + for index := start; index < end; index++ { + lines = append(lines, m.renderBenchmarkScopeItem(items[index], index, innerWidth, colors, selectedEfforts)) + } + for len(lines) < bodyHeight { + lines = append(lines, strings.Repeat(" ", innerWidth)) + } + title := fmt.Sprintf("BENCHMARK SCOPE // %d MODELS // %d EFFORTS // %d PAIRS // SPACE TOGGLE // ESC DONE", + len(m.benchmarkScope.Models), len(m.benchmarkScope.Efforts), m.benchmarkCombinations) + return frameSized(width, bodyHeight, ansi.Truncate(title, max(innerWidth-4, 1), ""), strings.Join(lines, "\n"), colors.primary, colors) +} + +func (m Model) renderBenchmarkScopeItem(item benchmarkScopeItem, index, width int, colors palette, selectedEfforts map[string]bool) string { + label := item.label + if len(item.efforts) > 0 { + label += " // " + strings.ToUpper(strings.Join(item.efforts, ", ")) + } + if index == m.benchmarkScopeCursor || index == m.benchmarkScopeHover { + style := lipgloss.NewStyle().Bold(true).Foreground(colors.background).Background(colors.accent) + return style.Render(fitTableCell(label, width)) + } + + if item.kind == benchmarkScopeModel && len(item.efforts) > 0 { + modelStyle := colors.dimmed() + if item.selected { + modelStyle = lipgloss.NewStyle().Foreground(colors.primary) + } + line := modelStyle.Render(item.label) + colors.dimmed().Render(" // ") + for effortIndex, effort := range item.efforts { + if effortIndex > 0 { + line += colors.dimmed().Render(", ") + } + effortStyle := colors.dimmed() + if item.selected && selectedEfforts[effort] { + effortStyle = lipgloss.NewStyle().Foreground(colors.primary) + } + line += effortStyle.Render(strings.ToUpper(effort)) + } + return fitTableCell(line, width) + } + + style := colors.dimmed() + if item.selected { + style = lipgloss.NewStyle().Foreground(colors.primary) + } + if item.kind == benchmarkScopeDone || item.kind == benchmarkScopeAllModels || item.kind == benchmarkScopeAllEfforts { + style = style.Bold(true).Foreground(colors.accent) + } + return style.Render(fitTableCell(label, width)) +} + +func (m Model) benchmarkScopeItems() []benchmarkScopeItem { + allModels := len(m.benchmarkPlan.Models) > 0 && len(m.benchmarkScope.Models) == len(m.benchmarkPlan.Models) + allEfforts := len(m.benchmarkPlan.Efforts) > 0 && len(m.benchmarkScope.Efforts) == len(m.benchmarkPlan.Efforts) + items := []benchmarkScopeItem{{ + kind: benchmarkScopeDone, label: "[ (D) DONE ] // RETURN TO BENCHMARK", selected: true, + }, { + kind: benchmarkScopeAllModels, selected: allModels, + label: scopeCheckLabel(allModels) + " MODELS // " + scopeAllAction(allModels), + }} + selectedModels := stringSetUI(m.benchmarkScope.Models) + for _, model := range m.benchmarkPlan.Models { + selected := selectedModels[model.Model] + label := " " + scopeCheckLabel(selected) + " " + model.DisplayName + items = append(items, benchmarkScopeItem{ + kind: benchmarkScopeModel, value: model.Model, label: label, + efforts: append([]string(nil), model.Efforts...), selected: selected, + }) + } + items = append(items, benchmarkScopeItem{ + kind: benchmarkScopeAllEfforts, selected: allEfforts, + label: scopeCheckLabel(allEfforts) + " REASONING LEVELS // " + scopeAllAction(allEfforts), + }) + selectedEfforts := stringSetUI(m.benchmarkScope.Efforts) + for _, effort := range m.benchmarkPlan.Efforts { + selected := selectedEfforts[effort] + items = append(items, benchmarkScopeItem{ + kind: benchmarkScopeEffort, value: effort, selected: selected, + label: " " + scopeCheckLabel(selected) + " " + strings.ToUpper(effort), + }) + } + return items +} + +func scopeCheckLabel(selected bool) string { + if selected { + return "[x]" + } + return "[ ]" +} + +func scopeAllAction(selected bool) string { + if selected { + return "CLEAR ALL" + } + return "CHECK ALL" +} + +func stringSetUI(values []string) map[string]bool { + set := make(map[string]bool, len(values)) + for _, value := range values { + set[value] = true + } + return set +} + +func (m *Model) openBenchmarkScope() { + if m.benchmarkRunActive() || len(m.benchmarkPlan.Models) == 0 { + return + } + m.benchmarkScopeOpen = true + m.benchmarkScopeHover = -1 + m.benchmarkScopeCursor = min(max(m.benchmarkScopeCursor, 0), max(len(m.benchmarkScopeItems())-1, 0)) + m.revealBenchmarkScopeCursor() +} + +func (m *Model) closeBenchmarkScope() { + m.benchmarkScopeOpen = false + m.benchmarkScopeHover = -1 +} + +func (m *Model) moveBenchmarkScopeCursor(direction int) { + items := m.benchmarkScopeItems() + if len(items) == 0 { + return + } + m.benchmarkScopeCursor = min(max(m.benchmarkScopeCursor+direction, 0), len(items)-1) + m.benchmarkScopeHover = -1 + m.revealBenchmarkScopeCursor() +} + +func (m *Model) revealBenchmarkScopeCursor() { + pageSize := m.benchmarkScopePageSize() + if m.benchmarkScopeCursor < m.benchmarkScopeScroll { + m.benchmarkScopeScroll = m.benchmarkScopeCursor + } else if m.benchmarkScopeCursor >= m.benchmarkScopeScroll+pageSize { + m.benchmarkScopeScroll = m.benchmarkScopeCursor - pageSize + 1 + } + m.benchmarkScopeScroll = min(max(m.benchmarkScopeScroll, 0), max(len(m.benchmarkScopeItems())-pageSize, 0)) +} + +func (m Model) benchmarkScopePageSize() int { + return max(m.dashboardLayout().meterHeight-2, 1) +} + +func (m *Model) toggleBenchmarkScopeCursor() { + items := m.benchmarkScopeItems() + if m.benchmarkScopeCursor < 0 || m.benchmarkScopeCursor >= len(items) { + return + } + item := items[m.benchmarkScopeCursor] + switch item.kind { + case benchmarkScopeDone: + m.closeBenchmarkScope() + return + case benchmarkScopeAllModels: + if item.selected { + m.benchmarkScope.Models = nil + } else { + m.benchmarkScope.Models = m.benchmarkPlan.AllScope().Models + } + case benchmarkScopeModel: + m.benchmarkScope.Models = toggleScopeValue(m.benchmarkScope.Models, item.value) + case benchmarkScopeAllEfforts: + if item.selected { + m.benchmarkScope.Efforts = nil + } else { + m.benchmarkScope.Efforts = m.benchmarkPlan.AllScope().Efforts + } + case benchmarkScopeEffort: + m.benchmarkScope.Efforts = toggleScopeValue(m.benchmarkScope.Efforts, item.value) + } + m.benchmarkCombinations = m.benchmarkPlan.CombinationCount(m.benchmarkScope) + m.benchmarkAllArmed = false +} + +func toggleScopeValue(values []string, value string) []string { + for index, existing := range values { + if existing == value { + return append(append([]string(nil), values[:index]...), values[index+1:]...) + } + } + return append(append([]string(nil), values...), value) +} + +func (m Model) benchmarkScopeItemAt(x, y int) (int, bool) { + if m.meterView != viewBenchmark || !m.benchmarkScopeOpen || x < 0 || y < 0 { + return 0, false + } + dashboard := m.dashboardLayout() + localY := y - dashboard.meterY - 1 + if x < 4 || x >= dashboard.contentWidth || localY < 0 || localY >= m.benchmarkScopePageSize() { + return 0, false + } + index := m.benchmarkScopeScroll + localY + if index < 0 || index >= len(m.benchmarkScopeItems()) { + return 0, false + } + return index, true +} + func (m Model) renderBenchmarkControls(width, height int, colors palette) string { innerWidth := max(width-4, 1) lines := make([]string, 0, max(height-2, 0)) @@ -132,8 +595,10 @@ func (m Model) benchmarkVisibleControlLines(width, height int) [][]benchmarkCont return lines } if capacity == 2 && len(lines) >= 3 { - // Drop the decorative spacer before dropping an actionable row. - return [][]benchmarkControlSegment{lines[0], lines[2]} + if m.benchmarkRunActive() { + return [][]benchmarkControlSegment{lines[0], lines[2]} + } + return lines[:2] } return lines[:min(len(lines), capacity)] } @@ -172,7 +637,7 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { if len(tasks) > 0 { selected = tasks[m.benchmarkSelectedTask%len(tasks)] } - running := m.benchmarkState == benchmarkRunning + running := m.benchmarkRunActive() selectorMiddleWidth := 0 for _, task := range tasks { selectorMiddleWidth = max(selectorMiddleWidth, lipgloss.Width("TASK // "+task.Name)) @@ -190,6 +655,8 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { selectedLabel := "[ (B) RUN SELECTED ]" allTurns := m.benchmarkCombinations * len(tasks) allLabel := fmt.Sprintf("[ (A) RUN ALL // %d ]", allTurns) + scopeLabel := fmt.Sprintf("[ (S) SCOPE // %d ]", m.benchmarkCombinations) + stopLabel := "[ (X) STOP ]" if m.benchmarkPlanning { allLabel = "[ DISCOVERING TURNS… ]" } @@ -207,8 +674,8 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { } } if lipgloss.Width(selectedLabel)+lipgloss.Width(allLabel)+1 > width { - selectedLabel = "[B]" - allLabel = fmt.Sprintf("[A:%d]", allTurns) + selectedLabel = "[RUN]" + allLabel = fmt.Sprintf("[ALL:%d]", allTurns) if m.benchmarkPlanning { allLabel = "[A:…]" } @@ -216,14 +683,32 @@ func (m Model) benchmarkControlLines(width int) [][]benchmarkControlSegment { allLabel = fmt.Sprintf("[A:%d?]", allTurns) } } - run := []benchmarkControlSegment{ - {text: selectedLabel, button: footerButtonBenchmarkSelected, enabled: !running && len(tasks) > 0}, + if lipgloss.Width(scopeLabel)+lipgloss.Width(stopLabel)+1 > width { + scopeLabel = fmt.Sprintf("[S:SCOPE %d]", m.benchmarkCombinations) + stopLabel = "[X:STOP]" + } + if lipgloss.Width(scopeLabel)+lipgloss.Width(stopLabel)+1 > width { + scopeLabel = fmt.Sprintf("[SCOPE:%d]", m.benchmarkCombinations) + stopLabel = "[STOP]" + } + primary := []benchmarkControlSegment{ + {text: selectedLabel, button: footerButtonBenchmarkSelected, enabled: m.benchmarkCanRunSelected() && len(tasks) > 0}, {text: allLabel, button: footerButtonBenchmarkAll, enabled: benchmarkRunAllAvailable(running, m.benchmarkCombinations, len(tasks))}, } - if benchmarkSegmentsWidth(run) > width { - run = run[:1] + secondary := []benchmarkControlSegment{ + {text: scopeLabel, button: footerButtonBenchmarkScope, enabled: !running && len(m.benchmarkPlan.Models) > 0}, + {text: stopLabel, button: footerButtonBenchmarkStop, enabled: m.benchmarkState == benchmarkRunning}, + } + if running { + secondary[0], secondary[1] = secondary[1], secondary[0] + } + for benchmarkSegmentsWidth(primary) > width && len(primary) > 1 { + primary = primary[:len(primary)-1] + } + for benchmarkSegmentsWidth(secondary) > width && len(secondary) > 1 { + secondary = secondary[:len(secondary)-1] } - return [][]benchmarkControlSegment{selector, nil, run} + return [][]benchmarkControlSegment{selector, primary, secondary} } func benchmarkSegmentsWidth(segments []benchmarkControlSegment) int { @@ -279,7 +764,10 @@ func benchmarkRunAllAvailable(running bool, combinations, taskCount int) bool { func (m Model) renderBenchmarkStatus(width, height int, colors palette) string { state := "READY" - detail := "USES QUOTA // EVERY VISIBLE MODEL + EFFORT" + detail := fmt.Sprintf("USES QUOTA // %d SELECTED MODEL + EFFORT PAIRS", m.benchmarkCombinations) + if m.benchmarkPlanning { + detail = "DISCOVERING VISIBLE MODELS + EFFORTS" + } color := colors.primary switch m.benchmarkState { case benchmarkRunning: @@ -292,6 +780,17 @@ func (m Model) renderBenchmarkStatus(width, height int, colors palette) string { detail = "QUERYING LOCAL CODEX APP-SERVER" } color = colors.accent + case benchmarkStopping: + state = fmt.Sprintf("STOPPING // %d/%d COMPLETE", m.benchmarkCompleted, m.benchmarkTotal) + detail = "INTERRUPTING CURRENT BENCHMARK TRIAL" + color = colors.warning + case benchmarkStopped: + state = fmt.Sprintf("STOPPED // %d/%d COMPLETE", m.benchmarkCompleted, m.benchmarkTotal) + detail = "COMPLETED RESULTS RETAINED // PRESS B TO RUN AGAIN" + if issue := latestBenchmarkStopIssue(m.benchmarkResults); issue != "" { + detail = "STOP ISSUE // " + issue + } + color = colors.warning case benchmarkFinished: passed := benchmarkPassCount(m.benchmarkResults) state = fmt.Sprintf("COMPLETE // %d/%d PASS", passed, len(m.benchmarkResults)) @@ -307,7 +806,7 @@ func (m Model) renderBenchmarkStatus(width, height int, colors palette) string { color = colors.danger } } - if m.benchmarkError != "" && m.benchmarkState != benchmarkRunning { + if m.benchmarkError != "" && !m.benchmarkRunActive() { state = "BENCHMARK FAULT" detail = m.benchmarkError color = colors.danger @@ -332,6 +831,15 @@ func latestBenchmarkFailure(results []codex.BenchmarkResult) string { return "" } +func latestBenchmarkStopIssue(results []codex.BenchmarkResult) string { + for index := len(results) - 1; index >= 0; index-- { + if results[index].Stopped && results[index].Failure != "" { + return results[index].Failure + } + } + return "" +} + func latestBenchmarkMeasurementIssue(results []codex.BenchmarkResult) string { for index := len(results) - 1; index >= 0; index-- { if results[index].UsageIssue != "" { @@ -348,9 +856,9 @@ func (m Model) renderBenchmarkTable(width, height int, colors palette) string { innerWidth := max(width-4, 1) bodyHeight := max(height-2, 1) visibleResults := filterBenchmarkResults(m.benchmarkResults, m.benchmarkFilter) - rankings := benchmarkRankings(m.benchmarkResults, m.benchmarkRankMode) - columns := benchmarkTableColumns(innerWidth, m.benchmarkResults) - rows := benchmarkTableRows(columns, sortedBenchmarkResults(visibleResults, m.benchmarkSort, m.benchmarkSortDescending, rankings), rankings) + allTableResults := m.benchmarkTableResults() + columns := benchmarkTableColumns(innerWidth, allTableResults, m.activeBenchmarkKey()) + rows, _, clipped := m.benchmarkVisibleRows(width, height) lines := []string{m.renderBenchmarkSegments(m.benchmarkFilterLine(innerWidth), innerWidth, colors)} if bodyHeight > 1 { lines = append(lines, m.renderBenchmarkHeader(columns, colors)) @@ -358,32 +866,33 @@ func (m Model) renderBenchmarkTable(width, height int, colors palette) string { if bodyHeight > 2 { lines = append(lines, colors.dimmed().Render(strings.Repeat("─", innerWidth))) } - available := max(bodyHeight-len(lines), 0) - if len(rows) > available && available >= 2 { - pageSize := available - 1 - maximumScroll := max(len(rows)-pageSize, 0) - scroll := min(max(m.benchmarkScroll, 0), maximumScroll) - end := len(rows) - scroll - start := max(end-pageSize, 0) + if clipped { + ordered := m.orderedBenchmarkResults() + start, end, _ := benchmarkVisibleResultRange(len(ordered), max(bodyHeight-len(lines), 0), m.benchmarkScroll) lines = append(lines, colors.dimmed().Render(fitTableCell( - fmt.Sprintf("ROWS %d-%d/%d // PGUP PGDN // MOUSE WHEEL", start+1, end, len(rows)), innerWidth, + fmt.Sprintf("ROWS %d-%d/%d // ↑ ↓ SELECT // ENTER OR CLICK DETAILS", start+1, end, len(ordered)), innerWidth, ))) - rows = rows[start:end] - } else if len(rows) > available { - rows = rows[len(rows)-available:] } for _, row := range rows { style := colors.dimmed() - if row.pass { + if row.active { + style = lipgloss.NewStyle().Bold(true).Foreground(colors.accent) + } else if row.stopped { + style = lipgloss.NewStyle().Bold(true).Foreground(colors.warning) + } else if row.pass { style = lipgloss.NewStyle().Foreground(colors.primary) } else { style = lipgloss.NewStyle().Foreground(colors.danger) } + key := benchmarkRunKey(row.result) + if m.benchmarkSelectedRun == key || (m.benchmarkRunHovered && m.benchmarkHoveredRun == key) { + style = style.Bold(true).Foreground(colors.background).Background(colors.accent) + } lines = append(lines, style.Render(row.text)) } - if len(visibleResults) == 0 && len(lines) < bodyHeight { + if len(visibleResults) == 0 && m.benchmarkActive == nil && len(lines) < bodyHeight { message := "RUN SELECTED OR RUN ALL TO BEGIN // THIS CONSUMES CODEX QUOTA" - if m.benchmarkState == benchmarkRunning { + if m.benchmarkRunActive() { message = "WAITING FOR FIRST RESULT" } else if len(m.benchmarkResults) > 0 { message = "NO RESULTS MATCH THE ACTIVE FILTER" @@ -401,11 +910,100 @@ func (m Model) renderBenchmarkTable(width, height int, colors palette) string { } type benchmarkTableRow struct { - text string - pass bool + text string + pass bool + active bool + stopped bool + result codex.BenchmarkResult } -func benchmarkTableColumns(width int, results []codex.BenchmarkResult) []benchmarkColumn { +func (m Model) orderedBenchmarkResults() []codex.BenchmarkResult { + visible := filterBenchmarkResults(m.benchmarkResults, m.benchmarkFilter) + rankings := benchmarkRankings(m.benchmarkResults, m.benchmarkRankMode) + ordered := sortedBenchmarkResults(visible, m.benchmarkSort, m.benchmarkSortDescending, rankings) + if active := m.currentBenchmarkActive(); active != nil { + ordered = append(ordered, *active) + } + return ordered +} + +func (m Model) benchmarkTableResults() []codex.BenchmarkResult { + results := slices.Clone(m.benchmarkResults) + if active := m.currentBenchmarkActive(); active != nil { + results = append(results, *active) + } + return results +} + +func (m Model) currentBenchmarkActive() *codex.BenchmarkResult { + if m.benchmarkActive == nil { + return nil + } + active := *m.benchmarkActive + if !m.benchmarkActiveSince.IsZero() { + active.Duration = max(time.Since(m.benchmarkActiveSince), 0) + } + return &active +} + +func (m Model) activeBenchmarkKey() string { + if m.benchmarkActive == nil { + return "" + } + return benchmarkRunKey(*m.benchmarkActive) +} + +func benchmarkVisibleResultRange(total, available, scroll int) (start, end int, banner bool) { + available = max(available, 0) + if total > available && available >= 2 { + pageSize := available - 1 + maximumScroll := max(total-pageSize, 0) + scroll = min(max(scroll, 0), maximumScroll) + end = total - scroll + start = max(end-pageSize, 0) + return start, end, true + } + end = total + start = max(end-available, 0) + return start, end, false +} + +// benchmarkVisibleRows is shared by rendering and hit testing so only rows +// actually drawn on screen can open a detail view. +func (m Model) benchmarkVisibleRows(width, height int) (rows []benchmarkTableRow, firstBodyLine int, banner bool) { + innerWidth := max(width-4, 1) + bodyHeight := max(height-2, 1) + firstBodyLine = 1 + if bodyHeight > 1 { + firstBodyLine++ + } + if bodyHeight > 2 { + firstBodyLine++ + } + ordered := m.orderedBenchmarkResults() + start, end, banner := benchmarkVisibleResultRange(len(ordered), max(bodyHeight-firstBodyLine, 0), m.benchmarkScroll) + if banner { + firstBodyLine++ + } + rankings := benchmarkRankings(m.benchmarkResults, m.benchmarkRankMode) + activeKey := m.activeBenchmarkKey() + columns := benchmarkTableColumns(innerWidth, m.benchmarkTableResults(), activeKey) + return benchmarkTableRows(columns, ordered[start:end], rankings, activeKey), firstBodyLine, banner +} + +func benchmarkRunKey(result codex.BenchmarkResult) string { + model := result.Model + if model == "" { + model = result.DisplayName + } + task := string(result.TaskID) + if task == "" { + task = result.TaskName + } + return strings.ToLower(model) + "\x00" + strings.ToLower(result.Effort) + "\x00" + strings.ToLower(task) +} + +func benchmarkTableColumns(width int, results []codex.BenchmarkResult, activeKeys ...string) []benchmarkColumn { titles := []string{"RANK", "MODEL", "EFFORT", "TASK", "RESULT", "TIME", "TOKENS", "API EQ"} sorts := []benchmarkSortColumn{benchmarkSortRank, benchmarkSortModel, benchmarkSortEffort, benchmarkSortTask, benchmarkSortResult, benchmarkSortTime, benchmarkSortTokens, benchmarkSortCost} widths := make([]int, len(titles)) @@ -418,7 +1016,8 @@ func benchmarkTableColumns(width int, results []codex.BenchmarkResult) []benchma combinations := make(map[string]struct{}) for _, result := range results { combinations[benchmarkCombinationKey(result)] = struct{}{} - for index, value := range benchmarkResultValues(result, nil) { + active := len(activeKeys) > 0 && activeKeys[0] != "" && activeKeys[0] == benchmarkRunKey(result) + for index, value := range benchmarkResultValues(result, nil, active) { idealWidths[index] = max(idealWidths[index], lipgloss.Width(value)) } } @@ -512,20 +1111,29 @@ func (m Model) renderBenchmarkHeader(columns []benchmarkColumn, colors palette) return strings.Join(parts, colors.dimmed().Render(" ")) } -func benchmarkTableRows(columns []benchmarkColumn, results []codex.BenchmarkResult, rankings map[string]int) []benchmarkTableRow { +func benchmarkTableRows(columns []benchmarkColumn, results []codex.BenchmarkResult, rankings map[string]int, activeKeys ...string) []benchmarkTableRow { rows := make([]benchmarkTableRow, 0, len(results)) for _, result := range results { + active := len(activeKeys) > 0 && activeKeys[0] != "" && activeKeys[0] == benchmarkRunKey(result) rows = append(rows, benchmarkTableRow{ - text: formatBenchmarkColumns(columns, benchmarkResultValues(result, rankings)...), - pass: result.Correct, + text: formatBenchmarkColumns(columns, benchmarkResultValues(result, rankings, active)...), + pass: result.Correct, + active: active, + stopped: result.Stopped, + result: result, }) } return rows } -func benchmarkResultValues(result codex.BenchmarkResult, rankings map[string]int) []string { +func benchmarkResultValues(result codex.BenchmarkResult, rankings map[string]int, active ...bool) []string { + inProgress := len(active) > 0 && active[0] outcome := "FAIL" - if result.Correct { + if inProgress { + outcome = "IN PROGRESS" + } else if result.Stopped { + outcome = "STOPPED" + } else if result.Correct { outcome = "PASS" } cost := "N/A" @@ -541,7 +1149,7 @@ func benchmarkResultValues(result codex.BenchmarkResult, rankings map[string]int model += "→" + result.ActualModel } rank := "—" - if value := rankings[benchmarkCombinationKey(result)]; value > 0 { + if value := rankings[benchmarkCombinationKey(result)]; !inProgress && !result.Stopped && value > 0 { rank = fmt.Sprintf("#%d", value) } return []string{ @@ -622,6 +1230,9 @@ func benchmarkRankings(results []codex.BenchmarkResult, modes ...benchmarkRankMo } byKey := make(map[string]*benchmarkRankSummary) for _, result := range results { + if result.Stopped { + continue + } key := benchmarkCombinationKey(result) summary := byKey[key] if summary == nil { @@ -834,7 +1445,7 @@ func filterBenchmarkResults(results []codex.BenchmarkResult, filter benchmarkRes } filtered := make([]codex.BenchmarkResult, 0, len(results)) for _, result := range results { - if (filter == benchmarkFilterPass && result.Correct) || (filter == benchmarkFilterFail && !result.Correct) { + if (filter == benchmarkFilterPass && result.Correct) || (filter == benchmarkFilterFail && !result.Correct && !result.Stopped) { filtered = append(filtered, result) } } @@ -870,6 +1481,12 @@ func (m Model) benchmarkButtonAt(x, y int) footerButtonID { if m.loading && len(m.snapshot.Meters()) == 0 { return footerButtonNone } + if m.benchmarkScopeOpen { + return footerButtonNone + } + if m.benchmarkDetail != nil { + return m.benchmarkDetailCopyAt(x, y) + } dashboard := m.dashboardLayout() layout := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) localX, localY := x-2, y-dashboard.meterY @@ -889,6 +1506,23 @@ func (m Model) benchmarkButtonAt(x, y int) footerButtonID { return footerButtonNone } +func (m Model) benchmarkDetailCopyAt(x, y int) footerButtonID { + if m.meterView != viewBenchmark || m.benchmarkDetail == nil || x < 0 || y < 0 { + return footerButtonNone + } + dashboard := m.dashboardLayout() + labelWidth := lipgloss.Width(benchmarkDetailCopyLabel) + if dashboard.contentWidth < labelWidth+8 || y != dashboard.meterY { + return footerButtonNone + } + localX := x - 2 + start := dashboard.contentWidth - labelWidth - 2 + if localX >= start && localX < start+labelWidth { + return footerButtonBenchmarkCopy + } + return footerButtonNone +} + func benchmarkSegmentButtonAt(localX int, segments []benchmarkControlSegment) footerButtonID { segmentX := 2 for _, segment := range segments { @@ -902,7 +1536,7 @@ func benchmarkSegmentButtonAt(localX int, segments []benchmarkControlSegment) fo } func (m Model) benchmarkHeaderAt(x, y int) (benchmarkSortColumn, bool) { - if m.meterView != viewBenchmark || x < 0 || y < 0 { + if m.meterView != viewBenchmark || m.benchmarkDetail != nil || x < 0 || y < 0 { return benchmarkSortNone, false } dashboard := m.dashboardLayout() @@ -915,10 +1549,31 @@ func (m Model) benchmarkHeaderAt(x, y int) (benchmarkSortColumn, bool) { return benchmarkSortNone, false } localX := x - 4 - for _, column := range benchmarkTableColumns(max(dashboard.contentWidth-4, 1), m.benchmarkResults) { + for _, column := range benchmarkTableColumns(max(dashboard.contentWidth-4, 1), m.benchmarkTableResults(), m.activeBenchmarkKey()) { if localX >= column.x && localX < column.x+column.width { return column.sort, true } } return benchmarkSortNone, false } + +func (m Model) benchmarkRunAt(x, y int) (benchmarkTableRow, bool) { + if m.meterView != viewBenchmark || m.benchmarkDetail != nil || x < 0 || y < 0 { + return benchmarkTableRow{}, false + } + dashboard := m.dashboardLayout() + geometry := layoutBenchmarkArea(dashboard.contentWidth, dashboard.meterHeight) + if geometry.tableHeight < 4 { + return benchmarkTableRow{}, false + } + tableY := dashboard.meterY + geometry.topHeight + if x < 4 || x >= 2+dashboard.contentWidth-2 { + return benchmarkTableRow{}, false + } + rows, firstBodyLine, _ := m.benchmarkVisibleRows(dashboard.contentWidth, geometry.tableHeight) + index := y - (tableY + 1 + firstBodyLine) + if index < 0 || index >= len(rows) { + return benchmarkTableRow{}, false + } + return rows[index], true +} diff --git a/internal/ui/benchmark_test.go b/internal/ui/benchmark_test.go index bd615568..5b35e1c1 100644 --- a/internal/ui/benchmark_test.go +++ b/internal/ui/benchmark_test.go @@ -25,6 +25,29 @@ type benchmarkCaptureFetcher struct { tasks chan []codex.BenchmarkTaskID } +type benchmarkScopedCaptureFetcher struct { + stubFetcher + plan codex.BenchmarkPlan + scopes chan codex.BenchmarkScope +} + +func (f benchmarkScopedCaptureFetcher) BenchmarkCombinationCount(context.Context) (int, error) { + return f.plan.CombinationCount(f.plan.AllScope()), nil +} + +func (f benchmarkScopedCaptureFetcher) BenchmarkPlan(context.Context) (codex.BenchmarkPlan, error) { + return f.plan, nil +} + +func (f benchmarkScopedCaptureFetcher) RunBenchmarkSuite(ctx context.Context, tasks []codex.BenchmarkTaskID, emit func(codex.BenchmarkEvent)) { + f.RunBenchmarkSuiteScoped(ctx, tasks, f.plan.AllScope(), emit) +} + +func (f benchmarkScopedCaptureFetcher) RunBenchmarkSuiteScoped(_ context.Context, _ []codex.BenchmarkTaskID, scope codex.BenchmarkScope, emit func(codex.BenchmarkEvent)) { + f.scopes <- scope + emit(codex.BenchmarkEvent{Done: true, Combinations: f.plan.CombinationCount(scope)}) +} + func (f benchmarkCaptureFetcher) BenchmarkCombinationCount(context.Context) (int, error) { return 1, nil } @@ -90,8 +113,189 @@ func TestBenchmarkViewRendersResponsiveResultsTable(t *testing.T) { 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) + if selectorLine < 0 || runLine != selectorLine+1 || !strings.Contains(lines[selectorLine+2], "(S) SCOPE") || !strings.Contains(lines[selectorLine+2], "(X) STOP") { + t.Fatalf("controls do not contain stable Run, Scope, and Stop rows:\n%s", controls) + } +} + +func TestBenchmarkRowClickOpensScrollableBenchmarkOnlyDetail(t *testing.T) { + result := codex.BenchmarkResult{ + TaskID: "merge-ranges", TaskName: "MERGE RANGES", Model: "detail-model", DisplayName: "Detail Model", Effort: "high", + Correct: true, Duration: 12500 * time.Millisecond, + Usage: codex.BenchmarkUsage{TotalTokens: 4321, InputTokens: 3000, CachedInputTokens: 1000, OutputTokens: 1321, ReasoningOutputTokens: 500}, + UsageKnown: true, UsageSource: codex.BenchmarkUsageRawResponses, CostKnown: true, CostUSD: 0.0412, + Interactions: []codex.BenchmarkInteraction{ + {Kind: codex.BenchmarkInteractionPrompt, Content: "Solve the benchmark-only prompt."}, + {Elapsed: time.Second, Kind: codex.BenchmarkInteractionResponse, Content: strings.Repeat("{\"code\":\"safe benchmark response\"}\n", 40)}, + {Elapsed: 2 * time.Second, Kind: codex.BenchmarkInteractionVerifier, Content: "Submission passed the deterministic verifier."}, + }, + } + model := Model{ + snapshot: codex.DemoSnapshot(), width: 100, height: 30, meterView: viewBenchmark, + benchmarkState: benchmarkFinished, benchmarkResults: []codex.BenchmarkResult{result}, + } + x, y := benchmarkRunCoordinates(t, model, benchmarkRunKey(result)) + updated, command := model.Update(tea.MouseMotionMsg{X: x, Y: y}) + model = updated.(Model) + if command != nil || !model.benchmarkRunHovered || model.benchmarkHoveredRun != benchmarkRunKey(result) { + t.Fatal("benchmark row hover was not recorded") + } + updated, command = model.Update(tea.MouseClickMsg{X: x, Y: y, Button: tea.MouseLeft}) + model = updated.(Model) + if command != nil || model.benchmarkDetail == nil { + t.Fatal("benchmark row click did not open its detail") + } + output := ansi.Strip(model.render()) + for _, want := range []string{"RUN DETAIL", benchmarkDetailCopyLabel, "RESULT // PASS", "Detail Model", "TOTAL 4321", "PROMPT //", "Solve the benchmark-only prompt", "RESPONSE //", "safe benchmark response"} { + if !strings.Contains(output, want) { + t.Fatalf("benchmark detail missing %q:\n%s", want, output) + } + } + if got := lipgloss.Width(output); got != model.width { + t.Fatalf("benchmark detail width = %d, want %d", got, model.width) + } + if got := lipgloss.Height(output); got != model.height { + t.Fatalf("benchmark detail height = %d, want %d", got, model.height) + } + copyX, copyY := renderedTextStart(t, model, benchmarkDetailCopyLabel) + updated, command = model.Update(tea.MouseMotionMsg{X: copyX, Y: copyY}) + model = updated.(Model) + if command != nil || model.hoveredButton != footerButtonBenchmarkCopy { + t.Fatal("benchmark detail Copy hover was not recorded") + } + updated, command = model.Update(tea.MouseClickMsg{X: copyX, Y: copyY, Button: tea.MouseLeft}) + model = updated.(Model) + if command == nil || model.flashedButton != footerButtonBenchmarkCopy { + t.Fatal("benchmark detail Copy click did not issue a clipboard command") + } + clipboard := model.benchmarkDetailClipboardText() + for _, want := range []string{"CODEXOMETER BENCHMARK RUN DETAIL", "RESULT: PASS", "MODEL: Detail Model", "[PROMPT +0.0s]", "Solve the benchmark-only prompt.", "[VERIFIER +2.0s]", "Submission passed the deterministic verifier."} { + if !strings.Contains(clipboard, want) { + t.Fatalf("full clipboard export missing %q:\n%s", want, clipboard) + } + } + if ansi.Strip(clipboard) != clipboard || strings.Contains(clipboard, "╭") { + t.Fatalf("clipboard export contains terminal styling or frame decoration:\n%q", clipboard) + } + updated, _ = model.Update(specialKey(tea.KeyPgDown)) + model = updated.(Model) + if model.benchmarkDetailScroll == 0 { + t.Fatal("Page Down did not scroll a long benchmark detail") + } + updated, command = model.Update(specialKey(tea.KeyEscape)) + model = updated.(Model) + if command != nil || model.benchmarkDetail != nil || model.benchmarkSelectedRun != benchmarkRunKey(result) { + t.Fatal("Escape did not return to the selected matrix row") + } +} + +func TestBenchmarkDetailCopyShortcutExportsContentOutsideViewport(t *testing.T) { + result := codex.BenchmarkResult{ + TaskName: "LONG DETAIL", Model: "model", DisplayName: "Model", Effort: "medium", Correct: true, + Interactions: []codex.BenchmarkInteraction{ + {Kind: codex.BenchmarkInteractionPrompt, Content: strings.Repeat("prompt line\n", 50)}, + {Elapsed: time.Second, Kind: codex.BenchmarkInteractionVerifier, Content: "final offscreen verifier"}, + }, + } + model := Model{snapshot: codex.DemoSnapshot(), width: 80, height: 20, meterView: viewBenchmark, benchmarkDetail: &result} + if strings.Contains(ansi.Strip(model.render()), "final offscreen verifier") { + t.Fatal("test fixture verifier unexpectedly fits in the visible viewport") + } + updated, command := model.Update(tea.KeyPressMsg{Code: 'c', Text: "c"}) + model = updated.(Model) + if command == nil || model.flashedButton != footerButtonBenchmarkCopy { + t.Fatal("c did not activate benchmark detail Copy") + } + if clipboard := model.benchmarkDetailClipboardText(); !strings.Contains(clipboard, "final offscreen verifier") { + t.Fatalf("clipboard omitted content outside viewport:\n%s", clipboard) + } +} + +func TestBenchmarkDetailOmitsEmptyUsageSource(t *testing.T) { + result := codex.BenchmarkResult{ + TaskName: "DEMO", Model: "model", DisplayName: "Model", Effort: "low", Correct: true, + UsageKnown: true, Usage: codex.BenchmarkUsage{TotalTokens: 100, InputTokens: 70, OutputTokens: 30}, + } + model := Model{benchmarkDetail: &result} + screen := ansi.Strip(strings.Join(model.benchmarkDetailLines(200, paletteFor(themeHacker)), "\n")) + clipboard := model.benchmarkDetailClipboardText() + if strings.Contains(screen, "SOURCE") || strings.Contains(clipboard, "SOURCE") { + t.Fatalf("empty usage source left a dangling label:\nscreen: %s\nclipboard: %s", screen, clipboard) + } + + result.UsageSource = codex.BenchmarkUsageCumulative + screen = ansi.Strip(strings.Join(model.benchmarkDetailLines(200, paletteFor(themeHacker)), "\n")) + clipboard = model.benchmarkDetailClipboardText() + if !strings.Contains(screen, "SOURCE cumulative") || !strings.Contains(clipboard, "SOURCE cumulative") { + t.Fatalf("known usage source was omitted:\nscreen: %s\nclipboard: %s", screen, clipboard) + } +} + +func TestInProgressBenchmarkRowOpensAndUpdatesLiveDetail(t *testing.T) { + active := codex.BenchmarkResult{ + TaskID: "merge-ranges", TaskName: "MERGE RANGES", Model: "live-model", DisplayName: "Live Model", Effort: "medium", + Interactions: []codex.BenchmarkInteraction{{Kind: codex.BenchmarkInteractionPrompt, Content: "Live benchmark prompt"}}, + } + model := Model{ + snapshot: codex.DemoSnapshot(), width: 100, height: 30, meterView: viewBenchmark, + benchmarkState: benchmarkRunning, benchmarkActive: &active, benchmarkActiveSince: time.Now().Add(-2 * time.Second), + } + table := ansi.Strip(model.renderBenchmarkArea(96, 19, paletteFor(themeHacker))) + if !strings.Contains(table, "IN PROGRESS") || !strings.Contains(table, "Live Model") { + t.Fatalf("active benchmark row is missing:\n%s", table) + } + x, y := benchmarkRunCoordinates(t, model, benchmarkRunKey(active)) + updated, command := model.Update(tea.MouseClickMsg{X: x, Y: y, Button: tea.MouseLeft}) + model = updated.(Model) + if command != nil || model.benchmarkDetail == nil || !model.benchmarkDetailActive { + t.Fatal("active benchmark row did not open a live detail") + } + detail := ansi.Strip(model.render()) + if !strings.Contains(detail, "LIVE RUN DETAIL") || !strings.Contains(detail, "RESULT // IN PROGRESS") || !strings.Contains(detail, "Live benchmark prompt") { + t.Fatalf("live detail is incomplete:\n%s", detail) + } + + progress := active + progress.Duration = 3 * time.Second + progress.Interactions = append(progress.Interactions, codex.BenchmarkInteraction{ + Elapsed: 3 * time.Second, Kind: codex.BenchmarkInteractionResponse, Content: "{\"code\":\"live response\"}", + }) + updated, _ = model.Update(benchmarkEventMsg{ok: true, event: codex.BenchmarkEvent{Active: &progress, Total: 1}}) + model = updated.(Model) + if model.benchmarkDetail == nil || !strings.Contains(model.benchmarkDetail.Interactions[1].Content, "live response") { + t.Fatal("active event did not update the open detail") + } + + result := progress + result.Correct = true + result.Interactions = append(result.Interactions, codex.BenchmarkInteraction{ + Elapsed: 4 * time.Second, Kind: codex.BenchmarkInteractionVerifier, Content: "Submission passed the deterministic verifier.", + }) + updated, _ = model.Update(benchmarkEventMsg{ok: true, event: codex.BenchmarkEvent{Result: &result, Total: 1, Completed: 1}}) + model = updated.(Model) + if model.benchmarkActive != nil || model.benchmarkDetailActive || model.benchmarkDetail == nil || !model.benchmarkDetail.Correct { + t.Fatal("completed result did not replace the live row and finalize its open detail") + } + if output := ansi.Strip(model.render()); !strings.Contains(output, "RESULT // PASS") || !strings.Contains(output, "VERIFIER //") { + t.Fatalf("finalized live detail is incomplete:\n%s", output) + } +} + +func TestBenchmarkKeyboardSelectsAndOpensResultRow(t *testing.T) { + results := []codex.BenchmarkResult{ + {TaskName: "FIRST", Model: "first", DisplayName: "First", Effort: "low"}, + {TaskName: "SECOND", Model: "second", DisplayName: "Second", Effort: "high", Correct: true}, + } + model := Model{width: 100, height: 30, meterView: viewBenchmark, benchmarkState: benchmarkFinished, benchmarkResults: results} + updated, _ := model.Update(specialKey(tea.KeyUp)) + model = updated.(Model) + if model.benchmarkSelectedRun != benchmarkRunKey(results[1]) { + t.Fatalf("Up selected %q, want newest visible row", model.benchmarkSelectedRun) + } + updated, command := model.Update(specialKey(tea.KeyEnter)) + model = updated.(Model) + if command != nil || model.benchmarkDetail == nil || model.benchmarkDetail.DisplayName != "Second" { + t.Fatal("Enter did not open the keyboard-selected benchmark detail") } } @@ -230,6 +434,160 @@ func TestBenchmarkButtonSupportsHoverAndClick(t *testing.T) { } } +func TestBenchmarkStopCancelsAndRetainsStoppedCurrentRow(t *testing.T) { + cancelled := false + active := codex.BenchmarkResult{ + TaskID: codex.BenchmarkMergeRanges, TaskName: "MERGE RANGES", Model: "model", DisplayName: "Model", Effort: "high", + Interactions: []codex.BenchmarkInteraction{{Kind: codex.BenchmarkInteractionPrompt, Content: "prompt"}}, + } + model := Model{ + snapshot: codex.DemoSnapshot(), width: 100, height: 30, meterView: viewBenchmark, + benchmarkState: benchmarkRunning, benchmarkTotal: 3, benchmarkCompleted: 1, + benchmarkCombinations: 1, benchmarkActive: &active, benchmarkCancel: func() { cancelled = true }, + } + controls := ansi.Strip(model.renderBenchmarkControls(58, 5, paletteFor(themeHacker))) + if !strings.Contains(controls, "(X) STOP") { + t.Fatalf("running controls omitted Stop:\n%s", controls) + } + x, y := benchmarkControlCoordinates(t, model, footerButtonBenchmarkStop) + updated, command := model.Update(tea.MouseClickMsg{X: x, Y: y, Button: tea.MouseLeft}) + model = updated.(Model) + if command == nil || !cancelled || model.benchmarkState != benchmarkStopping { + t.Fatalf("Stop did not request cancellation: state=%d cancelled=%v", model.benchmarkState, cancelled) + } + + stopped := active + stopped.Stopped = true + stopped.Interactions = append(stopped.Interactions, codex.BenchmarkInteraction{Kind: codex.BenchmarkInteractionVerifier, Content: "Benchmark stopped before completion."}) + updated, _ = model.Update(benchmarkEventMsg{ok: true, event: codex.BenchmarkEvent{Total: 3, Completed: 1, Result: &stopped, Stopped: true}}) + model = updated.(Model) + updated, _ = model.Update(benchmarkEventMsg{ok: true, event: codex.BenchmarkEvent{Total: 3, Completed: 1, Stopped: true, Done: true}}) + model = updated.(Model) + if model.benchmarkState != benchmarkStopped || len(model.benchmarkResults) != 1 || !model.benchmarkResults[0].Stopped { + t.Fatalf("stopped result was not retained: state=%d results=%#v", model.benchmarkState, model.benchmarkResults) + } + output := ansi.Strip(model.renderBenchmarkArea(96, 19, paletteFor(themeHacker))) + if !strings.Contains(output, "STOPPED // 1/3 COMPLETE") || !strings.Contains(output, "STOPPED") { + t.Fatalf("stopped state is not visible:\n%s", output) + } + model.openBenchmarkDetail(stopped) + detail := ansi.Strip(model.renderBenchmarkArea(96, 19, paletteFor(themeHacker))) + if !strings.Contains(detail, "RESULT // STOPPED") || !strings.Contains(model.benchmarkDetailClipboardText(), "RESULT: STOPPED") { + t.Fatalf("stopped detail/export is not explicit:\n%s", detail) + } +} + +func TestBenchmarkScopeScreenSelectsModelsAndEffortsForRun(t *testing.T) { + plan := codex.BenchmarkPlan{ + Models: []codex.BenchmarkModelOption{ + {Model: "model-a", DisplayName: "Model A", Efforts: []string{"low", "high"}}, + {Model: "model-b", DisplayName: "Model B", Efforts: []string{"low"}}, + }, + Efforts: []string{"low", "high"}, + } + scopes := make(chan codex.BenchmarkScope, 1) + fetcher := benchmarkScopedCaptureFetcher{stubFetcher: stubFetcher{snapshot: codex.DemoSnapshot()}, plan: plan, scopes: scopes} + model := New(fetcher, time.Minute) + model.snapshot = codex.DemoSnapshot() + model.loading = false + model.width, model.height = 100, 30 + model.meterView = viewBenchmark + updated, _ := model.Update(benchmarkPlanMsg{plan: plan, combinations: 3}) + model = updated.(Model) + + updated, command := model.Update(key('s')) + model = updated.(Model) + if command == nil || !model.benchmarkScopeOpen || model.benchmarkCombinations != 3 { + t.Fatal("Scope hotkey did not open the all-selected scope screen") + } + screen := ansi.Strip(model.renderBenchmarkArea(96, 19, paletteFor(themeHacker))) + for _, want := range []string{"BENCHMARK SCOPE", "(D) DONE", "[x] MODELS // CLEAR ALL", "Model A", "Model B", "[x] REASONING LEVELS // CLEAR ALL", "LOW", "HIGH"} { + if !strings.Contains(screen, want) { + t.Fatalf("scope screen missing %q:\n%s", want, screen) + } + } + + clickScopeItem := func(index int) { + t.Helper() + x, y := benchmarkScopeCoordinates(t, model, index) + updated, _ = model.Update(tea.MouseClickMsg{X: x, Y: y, Button: tea.MouseLeft}) + model = updated.(Model) + } + clickScopeItem(1) // Clear All models. + if model.benchmarkCombinations != 0 || len(model.benchmarkScope.Models) != 0 || model.benchmarkPlanNeeded() { + t.Fatalf("model Clear All did not clear scope: %#v", model.benchmarkScope) + } + clickScopeItem(1) // Check All models. + if model.benchmarkCombinations != 3 || len(model.benchmarkScope.Models) != 2 { + t.Fatalf("model Check All did not restore scope: %#v", model.benchmarkScope) + } + clickScopeItem(3) // Model B off: Model A low/high remain. + if model.benchmarkCombinations != 2 || len(model.benchmarkScope.Models) != 1 || model.benchmarkScope.Models[0] != "model-a" { + t.Fatalf("model checkbox did not narrow scope: %#v", model.benchmarkScope) + } + colors := paletteFor(themeHacker) + modelARow := model.renderBenchmarkScopeItem(model.benchmarkScopeItems()[2], 2, 90, colors, stringSetUI(model.benchmarkScope.Efforts)) + if !strings.Contains(modelARow, lipgloss.NewStyle().Foreground(colors.primary).Render("HIGH")) { + t.Fatalf("selected reasoning level was not active in model row: %q", modelARow) + } + clickScopeItem(6) // High off: Model A/low remains. + if model.benchmarkCombinations != 1 || slices.Contains(model.benchmarkScope.Efforts, "high") { + t.Fatalf("effort checkbox did not narrow scope: %#v", model.benchmarkScope) + } + modelARow = model.renderBenchmarkScopeItem(model.benchmarkScopeItems()[2], 2, 90, colors, stringSetUI(model.benchmarkScope.Efforts)) + if !strings.Contains(modelARow, colors.dimmed().Render("HIGH")) || strings.Contains(modelARow, lipgloss.NewStyle().Foreground(colors.primary).Render("HIGH")) { + t.Fatalf("out-of-scope reasoning level was not dimmed in model row: %q", modelARow) + } + model.benchmarkScopeCursor = 4 + updated, _ = model.Update(specialKey(tea.KeySpace)) // Check All reasoning levels. + model = updated.(Model) + if model.benchmarkCombinations != 2 || len(model.benchmarkScope.Efforts) != 2 { + t.Fatalf("reasoning Check All did not restore efforts: %#v", model.benchmarkScope) + } + clickScopeItem(6) // Keep the final launched scope to low only. + + clickScopeItem(0) + if model.benchmarkScopeOpen { + t.Fatal("Done did not close Scope") + } + updated, command = model.Update(key('b')) + model = updated.(Model) + if command == nil || model.benchmarkState != benchmarkRunning { + t.Fatal("scoped benchmark did not start") + } + rawCommand := command() + batch, ok := rawCommand.(tea.BatchMsg) + if !ok { + t.Fatalf("scoped run command returned %T, want tea.BatchMsg", rawCommand) + } + for _, child := range batch { + if _, ok := child().(benchmarkEventMsg); ok { + break + } + } + got := <-scopes + if len(got.Models) != 1 || got.Models[0] != "model-a" || len(got.Efforts) != 1 || got.Efforts[0] != "low" { + t.Fatalf("runner received scope %#v", got) + } +} + +func TestBenchmarkScopeAreaHonorsAllocatedSize(t *testing.T) { + plan := codex.BenchmarkPlan{ + Models: []codex.BenchmarkModelOption{{Model: "model", DisplayName: "Model", Efforts: []string{"low", "high"}}}, + Efforts: []string{"low", "high"}, + } + for _, size := range []struct{ width, height int }{{20, 3}, {40, 8}, {76, 12}, {120, 24}} { + model := Model{benchmarkPlan: plan, benchmarkScope: plan.AllScope(), benchmarkScopeOpen: true} + output := ansi.Strip(model.renderBenchmarkArea(size.width, size.height, paletteFor(themeHacker))) + if got := lipgloss.Width(output); got != size.width { + t.Errorf("scope width at %dx%d = %d", size.width, size.height, got) + } + if got := lipgloss.Height(output); got != size.height { + t.Errorf("scope height at %dx%d = %d", size.width, size.height, got) + } + } +} + func TestBenchmarkTableClipsOlderRows(t *testing.T) { model := Model{benchmarkState: benchmarkFinished} for index := 0; index < 20; index++ { @@ -764,6 +1122,32 @@ func benchmarkControlCoordinates(t *testing.T, model Model, target footerButtonI return 0, 0 } +func benchmarkRunCoordinates(t *testing.T, model Model, key string) (int, int) { + t.Helper() + for y := 0; y < model.height; y++ { + for x := 0; x < model.width; x++ { + if row, ok := model.benchmarkRunAt(x, y); ok && benchmarkRunKey(row.result) == key { + return x, y + } + } + } + t.Fatalf("benchmark run %q was not clickable", key) + return 0, 0 +} + +func benchmarkScopeCoordinates(t *testing.T, model Model, index int) (int, int) { + t.Helper() + for y := 0; y < model.height; y++ { + for x := 0; x < model.width; x++ { + if got, ok := model.benchmarkScopeItemAt(x, y); ok && got == index { + return x, y + } + } + } + t.Fatalf("benchmark scope item %d has no click coordinates", index) + return 0, 0 +} + func renderedTextCoordinates(t *testing.T, model Model, text string) (int, int) { t.Helper() x, y := renderedTextStart(t, model, text) diff --git a/internal/ui/model.go b/internal/ui/model.go index 70b11b63..da21f080 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -30,35 +30,42 @@ type BenchmarkRunner interface { RunBenchmarkSuite(context.Context, []codex.BenchmarkTaskID, func(codex.BenchmarkEvent)) } +type ScopedBenchmarkRunner interface { + BenchmarkRunner + BenchmarkPlan(context.Context) (codex.BenchmarkPlan, error) + RunBenchmarkSuiteScoped(context.Context, []codex.BenchmarkTaskID, codex.BenchmarkScope, func(codex.BenchmarkEvent)) +} + type Model struct { - fetcher Fetcher - usageFetcher TokenUsageFetcher - refreshEvery time.Duration - snapshot codex.Snapshot - err error - width int - height int - inline bool - loading bool - lastRefresh time.Time - nextRefresh time.Time - phase int - theme themeID - meterView meterViewID - quotaMeterView meterViewID - hoveredMainTab mainTabID - mainTabHovered bool - hoveredView meterViewID - viewHovered bool - flashedView meterViewID - viewFlashing bool - viewSequence uint64 - hoveredButton footerButtonID - flashedButton footerButtonID - flashSequence uint64 - benchmarkRunner BenchmarkRunner - preferenceStore PreferenceStore - appVersion string + fetcher Fetcher + usageFetcher TokenUsageFetcher + refreshEvery time.Duration + snapshot codex.Snapshot + err error + width int + height int + inline bool + loading bool + lastRefresh time.Time + nextRefresh time.Time + phase int + theme themeID + meterView meterViewID + quotaMeterView meterViewID + hoveredMainTab mainTabID + mainTabHovered bool + hoveredView meterViewID + viewHovered bool + flashedView meterViewID + viewFlashing bool + viewSequence uint64 + hoveredButton footerButtonID + flashedButton footerButtonID + flashSequence uint64 + benchmarkRunner BenchmarkRunner + benchmarkScopedRunner ScopedBenchmarkRunner + preferenceStore PreferenceStore + appVersion string benchmarkState benchmarkState benchmarkResults []codex.BenchmarkResult @@ -70,6 +77,12 @@ type Model struct { benchmarkError string benchmarkPlanning bool benchmarkCombinations int + benchmarkPlan codex.BenchmarkPlan + benchmarkScope codex.BenchmarkScope + benchmarkScopeOpen bool + benchmarkScopeCursor int + benchmarkScopeScroll int + benchmarkScopeHover int benchmarkSelectedTask int benchmarkFilter benchmarkResultFilter benchmarkAllArmed bool @@ -82,6 +95,14 @@ type Model struct { benchmarkRankMode benchmarkRankMode benchmarkEvents <-chan codex.BenchmarkEvent benchmarkCancel context.CancelFunc + benchmarkActive *codex.BenchmarkResult + benchmarkActiveSince time.Time + benchmarkSelectedRun string + benchmarkHoveredRun string + benchmarkRunHovered bool + benchmarkDetail *codex.BenchmarkResult + benchmarkDetailActive bool + benchmarkDetailScroll int monitorState monitorState monitorStartedAt time.Time @@ -228,6 +249,8 @@ type benchmarkState int const ( benchmarkIdle benchmarkState = iota benchmarkRunning + benchmarkStopping + benchmarkStopped benchmarkFinished ) @@ -238,6 +261,7 @@ type benchmarkEventMsg struct { } type benchmarkPlanMsg struct { + plan codex.BenchmarkPlan combinations int err error } @@ -284,6 +308,9 @@ const ( footerButtonBenchmarkRankCost footerButtonBenchmarkRankBalanced footerButtonBenchmarkRankSpeed + footerButtonBenchmarkCopy + footerButtonBenchmarkScope + footerButtonBenchmarkStop ) type footerButton struct { @@ -310,14 +337,15 @@ func New(fetcher Fetcher, refreshEvery time.Duration) Model { refreshEvery = time.Minute } model := Model{ - fetcher: fetcher, - refreshEvery: refreshEvery, - loading: true, - nextRefresh: time.Now().Add(refreshEvery), - benchmarkRankMode: benchmarkRankBalanced, - quotaAPIAnchors: make(map[string]quotaAPIAnchor), - quotaAPIIssues: make(map[string]string), - appVersion: version.Current(), + fetcher: fetcher, + refreshEvery: refreshEvery, + loading: true, + nextRefresh: time.Now().Add(refreshEvery), + benchmarkRankMode: benchmarkRankBalanced, + benchmarkScopeHover: -1, + quotaAPIAnchors: make(map[string]quotaAPIAnchor), + quotaAPIIssues: make(map[string]string), + appVersion: version.Current(), } if usageFetcher, ok := fetcher.(TokenUsageFetcher); ok { model.usageFetcher = usageFetcher @@ -325,6 +353,9 @@ func New(fetcher Fetcher, refreshEvery time.Duration) Model { if runner, ok := fetcher.(BenchmarkRunner); ok { model.benchmarkRunner = runner } + if runner, ok := fetcher.(ScopedBenchmarkRunner); ok { + model.benchmarkScopedRunner = runner + } return model } @@ -342,7 +373,18 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { switch message := message.(type) { case tea.KeyPressMsg: switch strings.ToLower(message.String()) { - case "ctrl+c", "esc": + case "ctrl+c": + m.cancelBenchmark() + return m, tea.Quit + case "esc": + if m.meterView == viewBenchmark && m.benchmarkScopeOpen { + m.closeBenchmarkScope() + return m, nil + } + if m.meterView == viewBenchmark && m.benchmarkDetail != nil { + m.closeBenchmarkDetail() + return m, nil + } m.cancelBenchmark() return m, tea.Quit case "t": @@ -351,6 +393,18 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { if m.meterView == viewMonitor { return m.pressFooterButton(footerButtonMonitorGo) } + if m.meterView == viewBenchmark && !m.benchmarkScopeOpen && m.benchmarkDetail == nil && len(m.benchmarkPlan.Models) > 0 { + return m.pressFooterButton(footerButtonBenchmarkScope) + } + case "x": + if m.meterView == viewBenchmark { + return m.pressFooterButton(footerButtonBenchmarkStop) + } + case "d": + if m.meterView == viewBenchmark && m.benchmarkScopeOpen { + m.closeBenchmarkScope() + return m, nil + } case "v": if m.meterView.isQuota() { return m.pressFooterButton(footerButtonView) @@ -364,33 +418,79 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { case "q": return m.pressFooterButton(footerButtonQuit) case "b": - if m.meterView == viewBenchmark { + if m.meterView == viewBenchmark && !m.benchmarkScopeOpen && m.benchmarkDetail == nil { return m.pressFooterButton(footerButtonBenchmarkSelected) } + case "c": + if m.meterView == viewBenchmark && m.benchmarkDetail != nil { + return m.pressFooterButton(footerButtonBenchmarkCopy) + } case "a": - if m.meterView == viewBenchmark { + if m.meterView == viewBenchmark && !m.benchmarkScopeOpen && m.benchmarkDetail == nil { return m.pressFooterButton(footerButtonBenchmarkAll) } - case "left", "[": + case "enter": + if m.meterView == viewBenchmark && m.benchmarkScopeOpen { + m.toggleBenchmarkScopeCursor() + return m, nil + } + if m.meterView == viewBenchmark && m.benchmarkDetail == nil { + m.openSelectedBenchmarkDetail() + return m, nil + } + case "space", " ": + if m.meterView == viewBenchmark && m.benchmarkScopeOpen { + m.toggleBenchmarkScopeCursor() + return m, nil + } + case "up": if m.meterView == viewBenchmark { + if m.benchmarkScopeOpen { + m.moveBenchmarkScopeCursor(-1) + } else if m.benchmarkDetail != nil { + m.scrollBenchmarkDetail(-1) + } else { + m.selectBenchmarkRun(-1) + } + return m, nil + } + case "down": + if m.meterView == viewBenchmark { + if m.benchmarkScopeOpen { + m.moveBenchmarkScopeCursor(1) + } else if m.benchmarkDetail != nil { + m.scrollBenchmarkDetail(1) + } else { + m.selectBenchmarkRun(1) + } + return m, nil + } + case "left", "[": + if m.meterView == viewBenchmark && !m.benchmarkScopeOpen && m.benchmarkDetail == nil { return m.pressFooterButton(footerButtonBenchmarkPrevious) } case "right", "]": - if m.meterView == viewBenchmark { + if m.meterView == viewBenchmark && !m.benchmarkScopeOpen && m.benchmarkDetail == nil { return m.pressFooterButton(footerButtonBenchmarkNext) } case "f": - if m.meterView == viewBenchmark { + if m.meterView == viewBenchmark && !m.benchmarkScopeOpen && m.benchmarkDetail == nil { m.setBenchmarkFilter((m.benchmarkFilter + 1) % 3) return m, nil } case "w": - if m.meterView == viewBenchmark { + if m.meterView == viewBenchmark && !m.benchmarkScopeOpen && m.benchmarkDetail == nil { return m.pressFooterButton(benchmarkRankButton(m.benchmarkRankMode.next())) } case "pgup": if m.meterView == viewBenchmark { - m.scrollBenchmarkPage(1) + if m.benchmarkScopeOpen { + m.moveBenchmarkScopeCursor(-m.benchmarkScopePageSize()) + } else if m.benchmarkDetail != nil { + m.scrollBenchmarkDetailPage(-1) + } else { + m.scrollBenchmarkPage(1) + } return m, nil } if m.meterView == viewMonitor { @@ -399,7 +499,13 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { } case "pgdown": if m.meterView == viewBenchmark { - m.scrollBenchmarkPage(-1) + if m.benchmarkScopeOpen { + m.moveBenchmarkScopeCursor(m.benchmarkScopePageSize()) + } else if m.benchmarkDetail != nil { + m.scrollBenchmarkDetailPage(1) + } else { + m.scrollBenchmarkPage(-1) + } return m, nil } if m.meterView == viewMonitor { @@ -435,6 +541,38 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { return m, nil } m.viewHovered = false + if m.meterView == viewBenchmark && m.benchmarkScopeOpen { + if item, ok := m.benchmarkScopeItemAt(mouse.X, mouse.Y); ok { + m.benchmarkScopeHover = item + m.hoveredButton = footerButtonNone + if mouse.Button == tea.MouseLeft && clicked { + m.benchmarkScopeCursor = item + m.toggleBenchmarkScopeCursor() + } + return m, nil + } + m.benchmarkScopeHover = -1 + switch mouse.Button { + case tea.MouseWheelUp: + m.moveBenchmarkScopeCursor(-1) + return m, nil + case tea.MouseWheelDown: + m.moveBenchmarkScopeCursor(1) + return m, nil + } + } + if m.meterView == viewBenchmark && m.benchmarkDetail != nil { + m.benchmarkRunHovered = false + m.benchmarkHoveredRun = "" + switch mouse.Button { + case tea.MouseWheelUp: + m.scrollBenchmarkDetail(-3) + return m, nil + case tea.MouseWheelDown: + m.scrollBenchmarkDetail(3) + return m, nil + } + } if column, ok := m.benchmarkHeaderAt(mouse.X, mouse.Y); ok { m.benchmarkSortHovered = true m.benchmarkHoveredSort = column @@ -445,6 +583,17 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { return m, nil } m.benchmarkSortHovered = false + if row, ok := m.benchmarkRunAt(mouse.X, mouse.Y); ok { + m.benchmarkRunHovered = true + m.benchmarkHoveredRun = benchmarkRunKey(row.result) + m.hoveredButton = footerButtonNone + if mouse.Button == tea.MouseLeft && clicked { + m.openBenchmarkDetail(row.result, row.active) + } + return m, nil + } + m.benchmarkRunHovered = false + m.benchmarkHoveredRun = "" if id, ok := m.monitorSessionDismissAt(mouse.X, mouse.Y); ok { m.monitorDismissHover = id m.hoveredButton = footerButtonNone @@ -570,13 +719,21 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { } case benchmarkEventMsg: if !message.ok { - m.benchmarkState = benchmarkFinished + if m.benchmarkState == benchmarkStopping { + m.benchmarkState = benchmarkStopped + } else { + m.benchmarkState = benchmarkFinished + } + m.benchmarkActive = nil + m.benchmarkActiveSince = time.Time{} m.benchmarkEvents = nil m.benchmarkCancel = nil return m, nil } event := message.event - m.benchmarkTotal = event.Total + if event.Total > 0 || !event.Stopped { + m.benchmarkTotal = event.Total + } m.benchmarkCompleted = event.Completed m.benchmarkCurrentModel = event.CurrentModel m.benchmarkCurrentEffort = event.CurrentEffort @@ -584,17 +741,45 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { if event.Combinations > 0 { m.benchmarkCombinations = event.Combinations } + if event.Active != nil { + newRun := m.benchmarkActive == nil || benchmarkRunKey(*m.benchmarkActive) != benchmarkRunKey(*event.Active) + if m.benchmarkActive == nil && m.benchmarkScroll > 0 { + m.benchmarkScroll++ + } + active := *event.Active + m.benchmarkActive = &active + if newRun { + m.benchmarkActiveSince = time.Now().Add(-active.Duration) + } + if m.benchmarkDetailActive && m.benchmarkDetail != nil && benchmarkRunKey(*m.benchmarkDetail) == benchmarkRunKey(active) { + m.benchmarkDetail = &active + } + } if event.Result != nil { - if m.benchmarkScroll > 0 { + hadActive := m.benchmarkActive != nil && benchmarkRunKey(*m.benchmarkActive) == benchmarkRunKey(*event.Result) + if !hadActive && m.benchmarkScroll > 0 { m.benchmarkScroll++ } - m.benchmarkResults = append(m.benchmarkResults, *event.Result) + result := *event.Result + m.benchmarkResults = append(m.benchmarkResults, result) + if m.benchmarkDetailActive && m.benchmarkDetail != nil && benchmarkRunKey(*m.benchmarkDetail) == benchmarkRunKey(result) { + m.benchmarkDetail = &result + m.benchmarkDetailActive = false + } + m.benchmarkActive = nil + m.benchmarkActiveSince = time.Time{} } if event.Err != nil { m.benchmarkError = event.Err.Error() } if event.Done { - m.benchmarkState = benchmarkFinished + if event.Stopped { + m.benchmarkState = benchmarkStopped + } else { + m.benchmarkState = benchmarkFinished + } + m.benchmarkActive = nil + m.benchmarkActiveSince = time.Time{} m.benchmarkEvents = nil m.benchmarkCancel = nil return m, nil @@ -606,6 +791,10 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) { m.benchmarkError = message.err.Error() } else { m.benchmarkError = "" + if len(message.plan.Models) > 0 { + m.benchmarkPlan = message.plan + m.benchmarkScope = message.plan.AllScope() + } m.benchmarkCombinations = message.combinations } case benchmarkConfirmExpiredMsg: @@ -632,7 +821,7 @@ func (m Model) pressViewTab(view meterViewID) (tea.Model, tea.Cmd) { commands := []tea.Cmd{tea.Tick(footerButtonFlashDuration, func(time.Time) tea.Msg { return viewTabFlashExpiredMsg{view: view, sequence: sequence} })} - if view == viewBenchmark && m.benchmarkRunner != nil && m.benchmarkCombinations == 0 && !m.benchmarkPlanning { + if view == viewBenchmark && m.benchmarkRunner != nil && m.benchmarkPlanNeeded() && !m.benchmarkPlanning { m.benchmarkPlanning = true commands = append(commands, planBenchmark(m.benchmarkRunner)) } @@ -716,15 +905,15 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { return m, m.monitorFetch(monitorFetchStop, m.monitorRequest) } case footerButtonBenchmarkPrevious: - if m.benchmarkState != benchmarkRunning { + if !m.benchmarkRunActive() { m.selectBenchmarkTask(-1) } case footerButtonBenchmarkNext: - if m.benchmarkState != benchmarkRunning { + if !m.benchmarkRunActive() { m.selectBenchmarkTask(1) } case footerButtonBenchmarkSelected: - if m.meterView == viewBenchmark && m.benchmarkState != benchmarkRunning { + if m.meterView == viewBenchmark && m.benchmarkCanRunSelected() { m.benchmarkAllArmed = false tasks := m.benchmarkTasks() if len(tasks) > 0 { @@ -733,7 +922,7 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { } case footerButtonBenchmarkAll: tasks := m.benchmarkTasks() - if m.meterView == viewBenchmark && benchmarkRunAllAvailable(m.benchmarkState == benchmarkRunning, m.benchmarkCombinations, len(tasks)) { + if m.meterView == viewBenchmark && benchmarkRunAllAvailable(m.benchmarkRunActive(), m.benchmarkCombinations, len(tasks)) { if !m.benchmarkAllArmed { m.benchmarkAllArmed = true m.benchmarkConfirmSequence++ @@ -759,6 +948,20 @@ func (m Model) activateFooterButton(button footerButtonID) (Model, tea.Cmd) { m.setBenchmarkRankMode(benchmarkRankBalanced) case footerButtonBenchmarkRankSpeed: m.setBenchmarkRankMode(benchmarkRankSpeed) + case footerButtonBenchmarkCopy: + if m.meterView == viewBenchmark && m.benchmarkDetail != nil { + return m, tea.SetClipboard(m.benchmarkDetailClipboardText()) + } + case footerButtonBenchmarkScope: + if m.meterView == viewBenchmark && !m.benchmarkRunActive() && len(m.benchmarkPlan.Models) > 0 { + m.openBenchmarkScope() + } + case footerButtonBenchmarkStop: + if m.meterView == viewBenchmark && m.benchmarkState == benchmarkRunning { + m.benchmarkState = benchmarkStopping + m.benchmarkAllArmed = false + m.cancelBenchmark() + } } return m, nil } @@ -866,16 +1069,25 @@ func (m Model) dashboardLayout() dashboardGeometry { } } -func launchBenchmark(ctx context.Context, runner BenchmarkRunner, tasks []codex.BenchmarkTaskID, events chan codex.BenchmarkEvent) tea.Cmd { +func launchBenchmark(ctx context.Context, runner BenchmarkRunner, tasks []codex.BenchmarkTaskID, scope codex.BenchmarkScope, events chan codex.BenchmarkEvent) tea.Cmd { return func() tea.Msg { go func() { defer close(events) - runner.RunBenchmarkSuite(ctx, tasks, func(event codex.BenchmarkEvent) { + emit := func(event codex.BenchmarkEvent) { + if event.Stopped { + events <- event + return + } select { case events <- event: case <-ctx.Done(): } - }) + } + if scoped, ok := runner.(ScopedBenchmarkRunner); ok { + scoped.RunBenchmarkSuiteScoped(ctx, tasks, scope, emit) + } else { + runner.RunBenchmarkSuite(ctx, tasks, emit) + } }() event, ok := <-events return benchmarkEventMsg{event: event, events: events, ok: ok} @@ -886,6 +1098,10 @@ func planBenchmark(runner BenchmarkRunner) tea.Cmd { return func() tea.Msg { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() + if scoped, ok := runner.(ScopedBenchmarkRunner); ok { + plan, err := scoped.BenchmarkPlan(ctx) + return benchmarkPlanMsg{plan: plan, combinations: plan.CombinationCount(plan.AllScope()), err: err} + } combinations, err := runner.BenchmarkCombinationCount(ctx) return benchmarkPlanMsg{combinations: combinations, err: err} } @@ -905,6 +1121,21 @@ func (m *Model) cancelBenchmark() { } } +func (m Model) benchmarkRunActive() bool { + return m.benchmarkState == benchmarkRunning || m.benchmarkState == benchmarkStopping +} + +func (m Model) benchmarkCanRunSelected() bool { + return !m.benchmarkRunActive() && (m.benchmarkScopedRunner == nil || m.benchmarkCombinations > 0) +} + +func (m Model) benchmarkPlanNeeded() bool { + if m.benchmarkScopedRunner != nil { + return len(m.benchmarkPlan.Models) == 0 + } + return m.benchmarkCombinations == 0 +} + func (m Model) startBenchmark(tasks []codex.BenchmarkTaskID) (Model, tea.Cmd) { if m.benchmarkRunner == nil { m.benchmarkState = benchmarkFinished @@ -912,19 +1143,29 @@ func (m Model) startBenchmark(tasks []codex.BenchmarkTaskID) (Model, tea.Cmd) { return m, nil } m.benchmarkResults = nil - m.benchmarkTotal = 0 + m.benchmarkTotal = m.benchmarkCombinations * len(tasks) m.benchmarkCompleted = 0 m.benchmarkCurrentModel = "" m.benchmarkCurrentEffort = "" m.benchmarkCurrentTask = "" m.benchmarkError = "" m.benchmarkScroll = 0 + m.benchmarkActive = nil + m.benchmarkActiveSince = time.Time{} + m.benchmarkSelectedRun = "" + m.benchmarkHoveredRun = "" + m.benchmarkRunHovered = false + m.benchmarkDetail = nil + m.benchmarkDetailActive = false + m.benchmarkDetailScroll = 0 + m.benchmarkScopeOpen = false + m.benchmarkScopeHover = -1 m.benchmarkState = benchmarkRunning ctx, cancel := context.WithCancel(context.Background()) m.benchmarkCancel = cancel events := make(chan codex.BenchmarkEvent, 2) m.benchmarkEvents = events - return m, launchBenchmark(ctx, m.benchmarkRunner, tasks, events) + return m, launchBenchmark(ctx, m.benchmarkRunner, tasks, m.benchmarkScope, events) } func (m *Model) selectBenchmarkTask(direction int) { @@ -943,6 +1184,7 @@ func (m Model) benchmarkTasks() []codex.BenchmarkTask { func (m *Model) setBenchmarkFilter(filter benchmarkResultFilter) { m.benchmarkFilter = filter m.benchmarkScroll = 0 + m.benchmarkSelectedRun = "" m.persistPreferences() } @@ -989,10 +1231,104 @@ func (m *Model) scrollBenchmarkPage(direction int) { } func (m *Model) scrollBenchmarkRows(rows int) { - maximum := max(len(filterBenchmarkResults(m.benchmarkResults, m.benchmarkFilter))-m.benchmarkPageSize(), 0) + maximum := max(len(m.orderedBenchmarkResults())-m.benchmarkPageSize(), 0) m.benchmarkScroll = min(max(m.benchmarkScroll+rows, 0), maximum) } +func (m *Model) selectBenchmarkRun(direction int) { + results := m.orderedBenchmarkResults() + if len(results) == 0 { + m.benchmarkSelectedRun = "" + return + } + selected := -1 + for index, result := range results { + if benchmarkRunKey(result) == m.benchmarkSelectedRun { + selected = index + break + } + } + if selected < 0 { + selected = len(results) - 1 + if direction > 0 { + selected = 0 + } + } else { + selected = min(max(selected+direction, 0), len(results)-1) + } + m.benchmarkSelectedRun = benchmarkRunKey(results[selected]) + m.revealBenchmarkRun(selected, len(results)) +} + +func (m *Model) revealBenchmarkRun(index, total int) { + layout := m.dashboardLayout() + geometry := layoutBenchmarkArea(layout.contentWidth, layout.meterHeight) + bodyHeight := max(geometry.tableHeight-2, 1) + baseLines := 1 + if bodyHeight > 1 { + baseLines++ + } + if bodyHeight > 2 { + baseLines++ + } + available := max(bodyHeight-baseLines, 0) + start, end, banner := benchmarkVisibleResultRange(total, available, m.benchmarkScroll) + pageSize := available + if banner { + pageSize-- + } + pageSize = max(pageSize, 1) + if index < start { + m.benchmarkScroll = min(max(total-(index+pageSize), 0), max(total-pageSize, 0)) + } else if index >= end { + m.benchmarkScroll = max(total-index-1, 0) + } +} + +func (m *Model) openSelectedBenchmarkDetail() { + results := m.orderedBenchmarkResults() + if len(results) == 0 { + return + } + if m.benchmarkSelectedRun == "" { + m.selectBenchmarkRun(-1) + } + for _, result := range results { + if benchmarkRunKey(result) == m.benchmarkSelectedRun { + active := m.benchmarkActive != nil && benchmarkRunKey(*m.benchmarkActive) == benchmarkRunKey(result) + m.openBenchmarkDetail(result, active) + return + } + } +} + +func (m *Model) openBenchmarkDetail(result codex.BenchmarkResult, active ...bool) { + m.benchmarkSelectedRun = benchmarkRunKey(result) + m.benchmarkDetail = &result + m.benchmarkDetailActive = len(active) > 0 && active[0] + m.benchmarkDetailScroll = 0 + m.benchmarkRunHovered = false + m.benchmarkHoveredRun = "" +} + +func (m *Model) closeBenchmarkDetail() { + m.benchmarkDetail = nil + m.benchmarkDetailActive = false + m.benchmarkDetailScroll = 0 +} + +func (m *Model) scrollBenchmarkDetail(rows int) { + if m.benchmarkDetail == nil { + return + } + maximum := m.benchmarkDetailMaximumScroll() + m.benchmarkDetailScroll = min(max(m.benchmarkDetailScroll+rows, 0), maximum) +} + +func (m *Model) scrollBenchmarkDetailPage(direction int) { + m.scrollBenchmarkDetail(direction * m.benchmarkDetailPageSize()) +} + func (m *Model) sortBenchmarkBy(column benchmarkSortColumn) { if m.benchmarkSort == column { m.benchmarkSortDescending = !m.benchmarkSortDescending @@ -1001,6 +1337,7 @@ func (m *Model) sortBenchmarkBy(column benchmarkSortColumn) { m.benchmarkSortDescending = false } m.benchmarkScroll = 0 + m.benchmarkSelectedRun = "" } func (m Model) contentWidth() int { diff --git a/main.go b/main.go index 0a7288cc..4be6e6ae 100644 --- a/main.go +++ b/main.go @@ -111,9 +111,34 @@ func (d *demoFetcher) FetchTokenUsage(context.Context) (codex.LiveUsageSnapshot, func (d *demoFetcher) BenchmarkCombinationCount(context.Context) (int, error) { return 2, nil } func (d *demoFetcher) RunBenchmarkSuite(ctx context.Context, tasks []codex.BenchmarkTaskID, emit func(codex.BenchmarkEvent)) { + d.RunBenchmarkSuiteScoped(ctx, tasks, d.demoBenchmarkPlan().AllScope(), emit) +} + +func (d *demoFetcher) BenchmarkPlan(context.Context) (codex.BenchmarkPlan, error) { + return d.demoBenchmarkPlan(), nil +} + +func (d *demoFetcher) demoBenchmarkPlan() codex.BenchmarkPlan { + return codex.BenchmarkPlan{ + Models: []codex.BenchmarkModelOption{ + {Model: "gpt-5.6-sol", DisplayName: "GPT-5.6 Sol", Efforts: []string{"medium"}}, + {Model: "gpt-5.6-terra", DisplayName: "GPT-5.6 Terra", Efforts: []string{"low"}}, + }, + Efforts: []string{"low", "medium"}, + } +} + +func (d *demoFetcher) RunBenchmarkSuiteScoped(ctx context.Context, tasks []codex.BenchmarkTaskID, scope codex.BenchmarkScope, emit func(codex.BenchmarkEvent)) { baseResults := []codex.BenchmarkResult{ - {Model: "gpt-5.6-sol", DisplayName: "GPT-5.6 Sol", Effort: "medium", ActualModel: "gpt-5.6-sol", Correct: true, Duration: 12_400 * time.Millisecond, Usage: codex.BenchmarkUsage{TotalTokens: 4_820}, CostUSD: 0.0412, CostKnown: true}, - {Model: "gpt-5.6-terra", DisplayName: "GPT-5.6 Terra", Effort: "low", ActualModel: "gpt-5.6-terra", Correct: false, Duration: 7_900 * time.Millisecond, Usage: codex.BenchmarkUsage{TotalTokens: 2_210}, CostUSD: 0.0091, CostKnown: true, Failure: "case 17 returned the wrong answer"}, + {Model: "gpt-5.6-sol", DisplayName: "GPT-5.6 Sol", Effort: "medium", ActualModel: "gpt-5.6-sol", Correct: true, Duration: 12_400 * time.Millisecond, Usage: codex.BenchmarkUsage{TotalTokens: 4_820}, UsageKnown: true, CostUSD: 0.0412, CostKnown: true, Interactions: demoBenchmarkInteractions(true)}, + {Model: "gpt-5.6-terra", DisplayName: "GPT-5.6 Terra", Effort: "low", ActualModel: "gpt-5.6-terra", Correct: false, Duration: 7_900 * time.Millisecond, Usage: codex.BenchmarkUsage{TotalTokens: 2_210}, UsageKnown: true, CostUSD: 0.0091, CostKnown: true, Failure: "case 17 returned the wrong answer", Interactions: demoBenchmarkInteractions(false)}, + } + models, efforts := make(map[string]bool), make(map[string]bool) + for _, model := range scope.Models { + models[model] = true + } + for _, effort := range scope.Efforts { + efforts[effort] = true } if len(tasks) == 0 { tasks = []codex.BenchmarkTaskID{codex.BenchmarkMergeRanges} @@ -125,6 +150,9 @@ func (d *demoFetcher) RunBenchmarkSuite(ctx context.Context, tasks []codex.Bench continue } for _, base := range baseResults { + if !models[base.Model] || !efforts[base.Effort] { + continue + } result := base result.TaskID, result.TaskName = task.ID, task.Name results = append(results, result) @@ -146,6 +174,18 @@ func (d *demoFetcher) RunBenchmarkSuite(ctx context.Context, tasks []codex.Bench emit(codex.BenchmarkEvent{Total: len(results), Completed: len(results), Done: true}) } +func demoBenchmarkInteractions(passed bool) []codex.BenchmarkInteraction { + verdict := "case 17 returned the wrong answer" + if passed { + verdict = "Submission passed the deterministic verifier." + } + return []codex.BenchmarkInteraction{ + {Kind: codex.BenchmarkInteractionPrompt, Content: "Implement the selected deterministic benchmark as one Starlark function and return a JSON object containing its complete source."}, + {Elapsed: 7 * time.Second, Kind: codex.BenchmarkInteractionResponse, Content: "{\"code\":\"def solve(items):\\n return items\\n\"}"}, + {Elapsed: 8 * time.Second, Kind: codex.BenchmarkInteractionVerifier, Content: verdict}, + } +} + func main() { os.Exit(run(os.Args[1:], os.Stdout, os.Stderr, defaultDependencies())) }