Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(evals): add an interactive terminal dashboard (#117583)

Daniel Parker36fb5847dda4
diff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.md
index 739ec100f3f4..6d08e5e9c4be 100644
--- a/products/posthog_ai/eval_harness/README.md
+++ b/products/posthog_ai/eval_harness/README.md
@@ -77,6 +77,8 @@ python -m products.posthog_ai.eval_harness.harness --list
| `--create-db` | Rebuild the eval test database instead of reusing it. |
| `--case-timeout <seconds>` | Agent-run budget (minimum 1 second), started after the case's team setup. |
| `--verbose` | Show detailed logs and tracebacks in the console. The transcript always keeps the detailed logs. |
+| `--tui` | Force the interactive view using the session's terminal, including when standard streams are redirected. |
+| `--no-tui` | Use plain text output, including in an interactive terminal. |
| `--trials N` | Run every case N times (Braintrust trials), for variance on stochastic agents. |
| `--infra-retries N` | Retry temporary case setup failures and service readiness timeouts N times. Default 2; use 0 to disable. |
| `--fail-under <fraction>` | Exit nonzero when the mean score across all experiments falls below this (0-1). |
@@ -109,11 +111,49 @@ A timeout summary contains the failure reason. Its raw log file can be empty; th
`EXPORT_EVAL_RESULTS=1` additionally appends one structured JSON summary per experiment to `eval_results.jsonl`.
The full plain-text run transcript is always written without this setting.
-Normal console output shows runner progress, summaries, and short error messages.
+Interactive terminals show a live view by default. CI and redirected standard input or output use plain text.
+Plain text output shows runner progress, summaries, and short error messages.
Dependency warnings, SDK progress bars, and direct setup prints stay in the transcript.
`--verbose` also shows Python warnings, SDK output, and detailed logs in the console.
Native subprocess output always goes to the transcript.
+### Interactive view
+
+The view is `phrocs evals`, the same Bubble Tea program that renders `hogli start`.
+It runs in its own process, so a busy eval run does not delay key presses or redraws.
+The harness builds the in-repo phrocs (`tools/phrocs/dist/phrocs`) when Go is available, otherwise it uses `phrocs` on `PATH`.
+If phrocs is missing or too old to have the `evals` command, the run continues with plain text output.
+
+The sidebar shows the run and one row per trial, grouped by experiment, with status and elapsed time.
+A failed trial shows its full error and traceback. Select **Run** for setup status, trial counts, and warnings. Press `l` to switch to the full run transcript.
+During agent execution, use this transcript for live logs. Per-trial log files become available after execution.
+Click a row or use the mouse wheel over the sidebar to change the selection. The wheel over the output pane scrolls it.
+Drag over the output pane to select text. The view copies the selection when you release the button, through OSC 52 and `pbcopy` on macOS.
+
+| Key | Action |
+| ------------------------ | ------------------------------------------------------------------------------------ |
+| Up/Down, `j`/`k` | Select a trial or the run, or scroll when the output pane has focus |
+| Tab, Enter | Move focus between the sidebar and the output pane |
+| `l` | Switch between the summary and logs |
+| `/`, Up/Down, Escape | Search the output, move between matches, or clear the search |
+| PgUp/PgDn, Home | Scroll the output |
+| End | Jump to the end and follow new output |
+| `q`, then `y` | Cancel a running eval and wait for cleanup; `n` continues the run |
+| Ctrl-C | Cancel once and wait for cleanup |
+| `q` after completion | Close the view |
+| Mouse drag in the output | Select text; releasing the button copies it to the clipboard |
+| `c`, then `c` twice | Select lines with Up/Down and copy them; the mouse can also drag-select in this mode |
+| `?` | Show all keys |
+
+The final results stay visible until you close the view. The terminal then prints the final summary and transcript path.
+Use `--no-tui` for the existing text output. `--verbose` adds detailed messages to the view or text output.
+`--tui` overrides automatic detection, including `TERM=dumb` and CI. It uses `/dev/tty` when a launcher redirects standard input or output.
+Redirecting stderr alone does not disable the view. A session without an attached terminal still requires `--no-tui`.
+`hogli evals` opens the view by default in a terminal, even though its secrets wrapper pipes stdout. Redirect the output of `hogli evals` to get text output.
+With `--tui`, setup starts only after the first screen is drawn. A startup failure stops the command and reports its cause.
+If the view exits during a run, the runner stops through its cleanup path and saves the view error in the transcript.
+The view does not change scores, retries, timeouts, or sandbox cleanup. Its screen controls are not written to the transcript.
+
### Comparing skill delivery
MCP instructions are configured once for the whole harness process, so bundled and exec skill delivery must run separately.
@@ -179,6 +219,7 @@ An unchanged image passes the check in under a second, and even a rebuild is mos
**modal** runs sandboxes remotely.
Modal's network cannot reach `localhost`, so the harness exposes the host services via Tailscale Funnel itself and points the sandbox at the public URLs.
+A new Funnel takes up to a few minutes before all of its public relays serve it, so Modal setup waits for them before the first case starts.
Eval sandboxes run in the dedicated `posthog-sandbox-evals` Modal app, separate from production and local development sandboxes.
The manual tunnel setup in [`docs/internal/sandboxes-setup-guide.md`](../../../../docs/internal/sandboxes-setup-guide.md) is therefore not needed for evals.
The first modal run pays a one-time remote image build; later runs reuse the cached image until the skills or build context change.
@@ -313,7 +354,7 @@ python -m products.posthog_ai.eval_harness.harness --list | grep my_thing
## Output
-Progress lines use stable labels as cases and suites start or finish: `SUITE START`, `EXPERIMENT START`, `CASE START`, `CASE PHASE`, `CASE READY`, `CASE DONE`, `EXPERIMENT DONE`, and `SUITE DONE`.
+In plain text output and the transcript, progress lines use stable labels as cases and suites start or finish: `SUITE START`, `EXPERIMENT START`, `CASE START`, `CASE PHASE`, `CASE READY`, `CASE DONE`, `EXPERIMENT DONE`, and `SUITE DONE`.
Only the overall run uses `PASS` or `FAIL`, so a suite with a low behavioral score still reads as completed rather than passed.
The console shows case starts and phase changes for each trial.
A status line every 30 seconds shows execution totals, phase counts, elapsed time, and the oldest active trial.
@@ -321,7 +362,8 @@ A status line every 30 seconds shows execution totals, phase counts, elapsed tim
`CASE DONE` and `EXPERIMENT DONE` mean the scores are ready.
The `scoring` phase includes time waiting for all results in that experiment, so it is not an isolated scorer duration.
Use `--verbose` to show detailed service and agent logs in the console. The transcript retains these logs in both modes.
-Warnings and errors use short console messages. Open the transcript for full tracebacks.
+Warnings and errors use short console messages, including the exception type and message when available.
+Open the transcript for full tracebacks.
The final summary gives labeled suite and case totals, the score gate, total duration, and one block per experiment with scorer averages, PostHog and Braintrust URLs, and the agent-log directory.
Each scorer line shows its score with a 95% confidence interval clustered by case. With `--trials N` a second line adds pass^N (every trial passed), pass@N (any trial passed) and the number of flaky cases, counting only cases scored on all N trials, so a noisy suite is distinguishable from a real score change.
diff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.py
index 4be9e0c995d2..5d847e703f26 100644
--- a/products/posthog_ai/eval_harness/base.py
+++ b/products/posthog_ai/eval_harness/base.py
@@ -5,6 +5,7 @@ import time
import uuid
import asyncio
import logging
+import traceback
from collections.abc import Callable, Sequence
from contextlib import suppress
from dataclasses import replace
@@ -258,6 +259,7 @@ class _BaseEvalRun:
)
status: Literal["ok", "timeout", "error"] = "ok"
error_type: str | None = None
+ error_detail: str | None = None
cancelled = False
try:
return await self._execute_case(input, hooks)
@@ -271,7 +273,8 @@ class _BaseEvalRun:
output["stderr"] = str(error)
if poll_timeout := hooks.metadata.get("poll_timeout"):
output["poll_timeout"] = poll_timeout
- logger.warning("Eval case '%s' timed out: %s", case_name, output.get("stderr") or output.get("error"))
+ error_detail = str(output.get("stderr") or output.get("error") or "")
+ logger.warning("Eval case '%s' timed out: %s", case_name, error_detail)
try:
write_case_logs(
case_dir=self.run_log_dir,
@@ -291,6 +294,7 @@ class _BaseEvalRun:
raise
except Exception as error:
error_type = type(error).__name__
+ error_detail = "".join(traceback.format_exception(error)).rstrip()
# Infra failure (provisioning, demo copy, setup hook, poll). Re-raise so
# Braintrust records the case as errored and excludes it from score
# averages, instead of scoring the task 0 for the harness's fault.
@@ -309,6 +313,7 @@ class _BaseEvalRun:
status=status,
trial_id=hooks.metadata["trial_id"],
error_type=error_type,
+ error_detail=error_detail,
)
async def _set_case_phase(self, hooks: CaseHooks | None, phase: CasePhase) -> None:
@@ -642,6 +647,7 @@ class _SandboxedEvalRun(_BaseEvalRun):
total_attempts=self.ctx.infrastructure_retries + 1,
delay_seconds=delay,
error_type=error_type,
+ trial_id=hooks.metadata.get("trial_id") if hooks is not None else None,
)
await asyncio.sleep(delay)
raise AssertionError("unreachable")
diff --git a/products/posthog_ai/eval_harness/harness/README.md b/products/posthog_ai/eval_harness/harness/README.md
index a7f7b9b8973f..340822493973 100644
--- a/products/posthog_ai/eval_harness/harness/README.md
+++ b/products/posthog_ai/eval_harness/harness/README.md
@@ -27,7 +27,7 @@ A run of one-shot suites never pays for — or fails preflight on — the sandbo
| `env_preflight.py` | Loads the repo-root `.env` (stdlib parser, shell wins) and validates per-kind env vars via pydantic models. |
| `ports.py` | The seven port constants. Deliberately free of Django imports. |
| `providers.py` | `SandboxProviderStrategy` and its docker/modal implementations: preflight, settings overrides, sandbox TTL, cleanup. |
-| `tunnels.py` | `TailscaleFunnel`. Modal only: enables Tailscale Funnel on the host services and resolves their public URLs. |
+| `tunnels.py` | `TailscaleFunnel`. Modal only: enables Tailscale Funnel on the host services, waits for the public relays, and resolves the URLs. |
| `requirements.py` | `SuiteKind`, `Infra`, and the kind → infrastructure mapping (with implication closure). |
| `django_env.py` | `setup_django()`, the `NullDbBlocker` shim, and `EvalDatabase` (test database lifecycle). |
| `live_server.py` | `EvalLiveServer`, a session-lifetime Uvicorn server for PostHog's full ASGI application. |
@@ -38,6 +38,9 @@ A run of one-shot suites never pays for — or fails preflight on — the sandbo
| `context.py` | `EvalContext`, the single object every suite receives. |
| `reporting.py` | `ProgressReporter` and the final summary table. The quiet Braintrust reporter lives with the engine (`../engines/braintrust.py`). |
| `transcript.py` | Mirrors stdout and stderr to one run log, then publishes its absolute path as the final line. |
+| `dashboard.py` | Starts the `phrocs evals` view process and streams run progress to it over a socket pair. |
+| `progress.py` | Immutable trial progress shared by the reporter and interactive view. |
+| `terminal.py` | Opens terminal streams without sharing the descriptors used by transcript capture. |
| `lifecycle.py` | `SandboxedEvalHarness`: orchestrates bootstrap, the run, and teardown. |
## Boot sequence
@@ -54,7 +57,7 @@ The bootstrap is deliberately synchronous and runs before any event loop exists,
3. `personhog-replica` (`:15051`) and `personhog-router` (`:15052`) start against the test persons database — before anything can query, so a dead router never poisons the negative group-types cache.
4. `EvalLiveServer` serves PostHog's ASGI application on `0.0.0.0:18000`, including the sandbox event-ingest route.
5. The LLM gateway (`:13308`) starts and local skills are built. In bundled mode, the MCP server (`:18787`) starts with exec skill distribution forced off. In exec mode, the skills are packaged, the local archive server (`:18788`) starts, and MCP receives its content-addressed URL with distribution forced on.
-6. Docker only: the `posthog-sandbox-base` image freshness check runs (rebuilding when the Dockerfile or its agent pin changed). Modal only: Tailscale Funnel comes up, exposing the callback services publicly.
+6. Docker only: the `posthog-sandbox-base` image freshness check runs (rebuilding when the Dockerfile or its agent pin changed). Modal only: Tailscale Funnel comes up, exposing the callback services publicly. Setup then waits until every public Funnel relay serves every service, because the relays start serving at different times and can take minutes.
7. Bundled mode bind-mounts the built skills on Docker and bakes them into the Modal image. Exec mode suppresses those skills and clears native skill directories before every case; `disable_bundled_skills=True` remains available as a per-case override in other modes.
8. The master Hedgebox team is seeded.
@@ -79,9 +82,26 @@ Terminal writes do not hold the transcript file lock, so progress output cannot
The runner starts workflow cleanup before progress reporting.
Cancellation during progress reporting does not stop workflow cleanup.
The sandbox window always reclaims notebook kernels after the agent run, without another progress report.
-The console defaults to concise output. `--verbose` shows detailed logging and tracebacks.
+Interactive terminals use the dashboard by default. CI, pipes, and `--no-tui` use concise text output.
+`--tui` overrides CI and `TERM=dumb` detection and opens `/dev/tty` when standard input or output is redirected.
+Redirected stderr does not disable automatic detection. Sessions without a controlling terminal use text output.
+`hogli evals` runs through the secrets wrapper (`op run`), which pipes stdout. hogli records whether its own stdout was a terminal in `HOGLI_STDOUT_TTY`, and detection uses that record when stdout is a pipe.
+`--verbose` shows detailed logging and tracebacks.
Both modes retain detailed logs in the transcript, including routine service stderr without a warning label.
+The reporter publishes immutable trial updates to the dashboard; the view does not parse log lines to infer case state.
+The view is a separate `phrocs evals` process (`tools/phrocs/internal/tui/evals.go`). It owns the terminal, so the harness's GIL never delays input or rendering.
+The harness passes one end of a socket pair with `--fd`. It writes one JSON event per line; the view replies `ready` after its first layout and `cancel` when the user confirms.
+The view reads the selected summary, agent log, or transcript itself. The harness sends file paths, never file contents.
+The view process gets a duplicate terminal descriptor, outside stdout/stderr capture.
+While the view runs, the harness points its own stdin at `/dev/null`. Services inherit stdin, and a service that reads the terminal (for example `tsx watch`) takes key presses from the view.
+The transcript routes console messages to the view while still saving their original text.
+Cancel replies send one SIGINT through the existing cleanup path. The view ignores SIGINT, so it stays open during teardown.
+The completed view stays open until `q`, then the final summary and transcript path print to the restored terminal.
+Dashboard readiness requires the `ready` reply. Forced UI startup failures stop before eval setup; automatic mode reports the failure before selecting text output.
+If the view process exits during a run, the runner stops through its cleanup path and saves the view's stderr in the transcript.
+UI loop exceptions propagate through the worker, interrupt an active run once for cleanup, and are logged with their original traceback.
+
Every invocation that attempts an eval writes the combined stdout/stderr stream to `logs/harness/<timestamp>_<id>.log`.
An explanatory line identifies the full run transcript, followed by the log's unlabeled absolute path as the final line in both the transcript and terminal.
`logs/harness/latest.log` points to it.
diff --git a/products/posthog_ai/eval_harness/harness/__main__.py b/products/posthog_ai/eval_harness/harness/__main__.py
index ebb93775aede..de613775f5ce 100644
--- a/products/posthog_ai/eval_harness/harness/__main__.py
+++ b/products/posthog_ai/eval_harness/harness/__main__.py
@@ -3,20 +3,28 @@ from __future__ import annotations
import os
import sys
import logging
+from contextlib import ExitStack
+from typing import TYPE_CHECKING
from .cli import HarnessOptions, parse_args
from .django_env import setup_django
from .env_preflight import load_env_file
from .ports import PERSONHOG_ROUTER_PORT
from .providers import SANDBOX_PROVIDER_SETTING, PreflightError
+from .terminal import open_terminal
from .transcript import RunTranscript, write_console
+if TYPE_CHECKING:
+ from .dashboard import EvalDashboard
+
logger = logging.getLogger("products.posthog_ai.eval_harness")
USAGE_ERROR_EXIT_CODE = 2
-def _run(options: HarnessOptions, *, transcript: RunTranscript | None = None) -> int:
+def _run(
+ options: HarnessOptions, *, transcript: RunTranscript | None = None, dashboard: EvalDashboard | None = None
+) -> int:
# Load the repo-root .env before Django reads the environment, so the harness
# works without a manual `set -a; source .env`. Shell values win, and the
# explicit overrides below still trump anything an env file provided.
@@ -49,7 +57,7 @@ def _run(options: HarnessOptions, *, transcript: RunTranscript | None = None) ->
from .lifecycle import SandboxedEvalHarness # noqa: PLC0415 — must import after django.setup()
try:
- return SandboxedEvalHarness(options).run()
+ return SandboxedEvalHarness(options, dashboard=dashboard).run()
except (PreflightError, SuiteDiscoveryError) as e:
# A missing prerequisite or a typo'd selector is user error, not a harness
# bug: say what's wrong without a traceback.
@@ -66,27 +74,91 @@ def _configure_logging(transcript: RunTranscript | None = None, *, verbose: bool
)
+def use_dashboard(options: HarnessOptions) -> bool:
+ if options.interactive is False:
+ return False
+ # hogli runs evals through a secrets wrapper that pipes stdout, so trust hogli's record of
+ # its own stdout. The view draws on /dev/tty, which the pipe does not affect.
+ stdout_tty = sys.stdout.isatty() or os.getenv("HOGLI_STDOUT_TTY") == "1"
+ terminal = sys.stdin.isatty() and stdout_tty
+ if options.interactive is True:
+ if not terminal:
+ try:
+ with open_terminal():
+ pass
+ except OSError as error:
+ raise PreflightError(
+ f"--tui could not open this session's terminal: {error}. Use --no-tui for a session without a terminal."
+ ) from error
+ return True
+ return terminal and os.getenv("TERM") != "dumb" and not os.getenv("CI")
+
+
+def _run_captured(options: HarnessOptions, transcript: RunTranscript, dashboard: EvalDashboard | None) -> int:
+ _configure_logging(transcript, verbose=options.verbose)
+ exit_code = 1
+ try:
+ try:
+ if dashboard is None or dashboard.begin_run():
+ if dashboard:
+ logger.info("Interactive eval view ready")
+ exit_code = _run(options, transcript=transcript, dashboard=dashboard)
+ except KeyboardInterrupt:
+ if dashboard is None or dashboard.failure is None:
+ logger.warning("Interrupted")
+ exit_code = 130
+ except Exception:
+ logger.exception("Sandboxed eval harness failed")
+ finally:
+ if dashboard:
+ dashboard.end_run()
+ if dashboard:
+ dashboard.finish(exit_code)
+ finally:
+ if dashboard and (ui_error := dashboard.failure) is not None:
+ logger.error("Interactive eval view failed", exc_info=(type(ui_error), ui_error, ui_error.__traceback__))
+ exit_code = 1
+ logging.shutdown()
+ return exit_code
+
+
def main(argv: list[str] | None = None) -> int:
options = parse_args(argv)
if options.list_only:
_configure_logging()
return _run(options)
+ try:
+ interactive = use_dashboard(options)
+ except PreflightError as error:
+ write_console(f"error: {error}\n", stream=sys.stderr)
+ return USAGE_ERROR_EXIT_CODE
+
transcript = RunTranscript.create()
exit_code = 1
try:
- with transcript.capture(verbose=options.verbose):
- _configure_logging(transcript, verbose=options.verbose)
- try:
- exit_code = _run(options, transcript=transcript)
- except KeyboardInterrupt:
- logger.warning("Interrupted")
- exit_code = 130
- except Exception:
- logger.exception("Sandboxed eval harness failed")
- exit_code = 1
- finally:
- logging.shutdown()
+ with ExitStack() as stack:
+ dashboard = None
+ if interactive:
+ from .dashboard import (
+ open_dashboard, # noqa: PLC0415 — keep the terminal UI off the noninteractive import path
+ )
+
+ try:
+ dashboard = stack.enter_context(open_dashboard(transcript.path))
+ except (OSError, RuntimeError):
+ with transcript.capture(verbose=options.verbose):
+ _configure_logging(transcript, verbose=options.verbose)
+ logger.exception("Interactive eval view could not start")
+ if options.interactive is not True:
+ write_console("Continuing with plain text output. Use --no-tui to select text output.\n")
+ logging.shutdown()
+ if options.interactive is True:
+ return 1
+ with transcript.capture(verbose=options.verbose, console_output=dashboard.write if dashboard else None):
+ exit_code = _run_captured(options, transcript, dashboard)
+ if dashboard:
+ write_console(dashboard.result_text)
finally:
transcript.finish()
return exit_code
diff --git a/products/posthog_ai/eval_harness/harness/cli.py b/products/posthog_ai/eval_harness/harness/cli.py
index 391a18d51324..a7f9b68a1d51 100644
--- a/products/posthog_ai/eval_harness/harness/cli.py
+++ b/products/posthog_ai/eval_harness/harness/cli.py
@@ -63,6 +63,7 @@ class HarnessOptions:
verbose: bool = False
infrastructure_retries: int = DEFAULT_INFRA_RETRIES
+ interactive: bool | None = None
def _default_case_timeout() -> int:
@@ -179,6 +180,10 @@ def build_parser() -> argparse.ArgumentParser:
parser.add_argument(
"--verbose", action="store_true", help="Show detailed logs in the console as well as the transcript."
)
+ display = parser.add_mutually_exclusive_group()
+ display.add_argument("--tui", dest="interactive", action="store_true", help="Show the interactive terminal view.")
+ display.add_argument("--no-tui", dest="interactive", action="store_false", help="Use plain text output.")
+ parser.set_defaults(interactive=None)
parser.add_argument(
"--fail-under",
type=float,
@@ -262,4 +267,5 @@ def parse_args(argv: list[str] | None = None) -> HarnessOptions:
sandbox_flags_set=sandbox_flags_set,
infrastructure_retries=args.infra_retries,
verbose=args.verbose,
+ interactive=args.interactive,
)
diff --git a/products/posthog_ai/eval_harness/harness/dashboard.py b/products/posthog_ai/eval_harness/harness/dashboard.py
new file mode 100644
index 000000000000..f5e1534ea77a
--- /dev/null
+++ b/products/posthog_ai/eval_harness/harness/dashboard.py
@@ -0,0 +1,336 @@
+from __future__ import annotations
+
+import os
+import json
+import time
+import queue
+import select
+import shutil
+import signal
+import socket
+import termios
+import threading
+import subprocess
+from collections.abc import Callable, Iterator, Sequence
+from contextlib import contextmanager
+from pathlib import Path
+from typing import TextIO
+
+from ..log_sink import _case_log_slug
+from .progress import TrialProgress
+from .terminal import TerminalStreams, open_terminal
+from .transcript import write_console
+
+PHROCS_DIR = Path(__file__).resolve().parents[4] / "tools" / "phrocs"
+READY_TIMEOUT_SECONDS = 5
+VIEW_WRITE_TIMEOUT_SECONDS = 30
+"""How long the view may stop reading progress events before the harness treats it as failed."""
+VIEW_QUEUE_LIMIT = 10_000
+
+
+def resolve_view_command() -> list[str]:
+ """Find the phrocs binary that renders the view, building the in-repo copy when Go is available.
+
+ `bin/start` uses the same order, so the eval view and `hogli start` run the same build.
+ """
+ if shutil.which("go") and shutil.which("make") and (PHROCS_DIR / "Makefile").exists():
+ make = ["make", "-s", "-C", str(PHROCS_DIR), "build"]
+ if subprocess.run([*make, "-q"], capture_output=True).returncode != 0:
+ write_console("Building phrocs for the eval view...\n")
+ subprocess.run(make, capture_output=True)
+ built = PHROCS_DIR / "dist" / "phrocs"
+ if built.exists():
+ return [str(built)]
+ if installed := shutil.which("phrocs"):
+ return [installed]
+ raise RuntimeError("phrocs is not installed. Run `hogli phrocs:build` or use --no-tui")
+
+
+TerminalModes = list[int | list[bytes | int]]
+
+
+def _terminal_modes(stream: TextIO) -> TerminalModes | None:
+ try:
+ return termios.tcgetattr(stream.fileno())
+ except (OSError, ValueError, termios.error):
+ return None
+
+
+def _restore_terminal_modes(stream: TextIO, modes: TerminalModes) -> None:
+ try:
+ termios.tcsetattr(stream.fileno(), termios.TCSADRAIN, modes)
+ except (OSError, ValueError, termios.error):
+ pass
+
+
+@contextmanager
+def _detach_stdin() -> Iterator[None]:
+ """Point stdin at /dev/null so that services the run starts cannot read the terminal.
+
+ Child processes inherit stdin. A child that reads the terminal, such as `tsx watch`, takes key
+ presses from the view, so the view seems to drop arrow keys.
+ """
+ saved = os.dup(0)
+ devnull = os.open(os.devnull, os.O_RDONLY)
+ try:
+ os.dup2(devnull, 0)
+ yield
+ finally:
+ os.dup2(saved, 0)
+ os.close(saved)
+ os.close(devnull)
+
+
+class EvalDashboard:
+ """Streams run progress to a `phrocs evals` child process that owns the terminal.
+
+ The view runs in its own process, so the eval run cannot delay key presses or redraws.
+ """
+
+ def __init__(
+ self,
+ transcript: Path,
+ *,
+ command: Sequence[str],
+ terminal: TerminalStreams,
+ cancel: Callable[[], None],
+ ) -> None:
+ self.transcript = transcript
+ self.result_text = ""
+ self._command = list(command)
+ self._terminal = terminal
+ self._cancel = cancel
+ self._socket: socket.socket | None = None
+ self._outbox: queue.Queue[bytes | None] = queue.Queue(maxsize=VIEW_QUEUE_LIMIT)
+ self._process: subprocess.Popen[bytes] | None = None
+ self._reader: threading.Thread | None = None
+ self._writer: threading.Thread | None = None
+ self._ready = threading.Event()
+ self._run_active = threading.Event()
+ self._stopping = threading.Event()
+ self._exit_code: int | None = None
+ self._cancel_requested = False
+ self._error: BaseException | None = None
+
+ def _send(self, event: dict[str, object]) -> None:
+ # The reporter calls this from the eval event loop, so it must never wait on the view.
+ # A full queue means the view already stopped reading, and the writer reports that.
+ try:
+ self._outbox.put_nowait(json.dumps(event).encode() + b"\n")
+ except queue.Full:
+ pass
+
+ def _write_events(self) -> None:
+ assert self._socket is not None
+ sock = self._socket
+ while (data := self._outbox.get()) is not None:
+ view = memoryview(data)
+ deadline = time.monotonic() + VIEW_WRITE_TIMEOUT_SECONDS
+ while view:
+ remaining = deadline - time.monotonic()
+ if self._stopping.is_set() or remaining <= 0:
+ if not self._stopping.is_set():
+ self._view_failed(
+ RuntimeError(
+ f"The terminal view stopped reading progress for {VIEW_WRITE_TIMEOUT_SECONDS} seconds"
+ )
+ )
+ return
+ try:
+ _, writable, _ = select.select([], [sock], [], min(remaining, 1.0))
+ if writable:
+ view = view[sock.send(view) :]
+ except BlockingIOError:
+ continue
+ except (OSError, ValueError):
+ # The reader thread sees the closed view and reports the failure.
+ return
+
+ def _view_failed(self, error: BaseException) -> None:
+ if self._error is None:
+ self._error = error
+ if self._run_active.is_set():
+ self.request_cancel()
+
+ def configure(self, description: str) -> None:
+ self._send({"type": "run", "description": description, "transcript": str(self.transcript)})
+
+ def setup_started(self, phase: str) -> None:
+ self._send({"type": "setup", "phase": phase})
+
+ def setup_finished(self) -> None:
+ self._send({"type": "setup_done"})
+
+ def set_stage(self, stage: str) -> None:
+ self._send({"type": "stage", "stage": stage})
+
+ def experiment_started(self, name: str, total: int) -> None:
+ self._send({"type": "experiment", "name": name, "total": total})
+
+ def update_trial(self, trial: TrialProgress) -> None:
+ wall_offset = time.time() - time.monotonic()
+ event: dict[str, object] = {
+ "type": "trial",
+ "id": trial.trial_id,
+ "experiment": trial.experiment,
+ "name": trial.name,
+ "index": trial.trial_index,
+ "phase": trial.phase,
+ "started": trial.started + wall_offset,
+ "ended": trial.ended + wall_offset if trial.ended is not None else 0,
+ "detail": trial.detail,
+ }
+ if trial.log_dir is not None:
+ slug = _case_log_slug(trial.name, trial.trial_id)
+ event["summary_path"] = str(trial.log_dir / f"{slug}.summary.txt")
+ event["log_path"] = str(trial.log_dir / f"{slug}.jsonl")
+ self._send(event)
+
+ def trial_retry(self, trial_id: str, detail: str) -> None:
+ self._send({"type": "retry", "id": trial_id, "detail": detail})
+
+ def write(self, text: str) -> None:
+ if text.lstrip().startswith(("Sandboxed eval summary", "ERROR:", "error:")):
+ self.result_text = text
+ self._send({"type": "message", "text": text})
+
+ @property
+ def failure(self) -> BaseException | None:
+ return self._error
+
+ def begin_run(self) -> bool:
+ self._run_active.set()
+ if self.failure is not None:
+ self._run_active.clear()
+ return False
+ return True
+
+ def end_run(self) -> None:
+ self._run_active.clear()
+
+ def request_cancel(self) -> None:
+ if not self._cancel_requested:
+ self._cancel_requested = True
+ self._cancel()
+
+ def _read_replies(self) -> None:
+ assert self._socket is not None and self._process is not None
+ sock = self._socket
+ pending = b""
+ while True:
+ try:
+ readable, _, _ = select.select([sock], [], [], 1.0)
+ if not readable:
+ continue
+ chunk = sock.recv(4096)
+ except BlockingIOError:
+ continue
+ except (OSError, ValueError):
+ break
+ if not chunk:
+ break
+ pending += chunk
+ while b"\n" in pending:
+ line, pending = pending.split(b"\n", 1)
+ reply = line.strip()
+ if reply == b"ready":
+ self._ready.set()
+ elif reply == b"cancel":
+ self.request_cancel()
+ returncode = self._process.wait()
+ if self._exit_code is None and not self._stopping.is_set():
+ stderr = self._process.stderr.read().decode(errors="replace").strip() if self._process.stderr else ""
+ self._view_failed(
+ RuntimeError(
+ f"The terminal view exited with code {returncode} before the eval run completed"
+ + (f": {stderr}" if stderr else "")
+ )
+ )
+ self._ready.set()
+
+ @contextmanager
+ def display(self) -> Iterator[None]:
+ saved_modes = _terminal_modes(self._terminal.input)
+ parent, child = socket.socketpair()
+ environment = dict(os.environ)
+ if environment.get("TERM", "dumb") == "dumb":
+ environment["TERM"] = "xterm-256color"
+ try:
+ try:
+ self._process = subprocess.Popen(
+ [*self._command, "evals", "--fd", str(child.fileno())],
+ stdin=self._terminal.input,
+ stdout=self._terminal.output,
+ stderr=subprocess.PIPE,
+ pass_fds=(child.fileno(),),
+ env=environment,
+ )
+ finally:
+ child.close()
+ # Non-blocking, so a view that stops reading can never block the writer thread.
+ parent.setblocking(False)
+ self._socket = parent
+ self._reader = threading.Thread(target=self._read_replies, name="eval-view-replies", daemon=True)
+ self._reader.start()
+ self._writer = threading.Thread(target=self._write_events, name="eval-view-events", daemon=True)
+ self._writer.start()
+ if not self._ready.wait(timeout=READY_TIMEOUT_SECONDS):
+ raise RuntimeError(f"The terminal view did not start within {READY_TIMEOUT_SECONDS} seconds")
+ if self._error is not None:
+ raise RuntimeError(f"Could not start the terminal view: {self._error}") from self._error
+ with _detach_stdin():
+ yield
+ finally:
+ self._stopping.set()
+ if self._process is not None and self._process.poll() is None:
+ self._process.terminate()
+ try:
+ self._process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ self._process.kill()
+ self._process.wait()
+ # A view that died from a signal cannot restore the terminal, so the shell would
+ # inherit raw mode. Restore the modes from before the view started.
+ if saved_modes is not None:
+ _restore_terminal_modes(self._terminal.input, saved_modes)
+ if self._writer is not None:
+ try:
+ self._outbox.put_nowait(None)
+ except queue.Full:
+ pass
+ self._writer.join(timeout=5)
+ self._socket = None
+ parent.close()
+ if self._reader is not None:
+ self._reader.join(timeout=5)
+
+ def finish(self, exit_code: int) -> None:
+ self._exit_code = exit_code
+ summary = self.result_text if self.result_text.lstrip().startswith("Sandboxed eval summary") else ""
+ event = json.dumps({"type": "finish", "exit_code": exit_code, "text": summary}).encode() + b"\n"
+ try:
+ # The view stays open until it receives this event, so wait for queue room here.
+ self._outbox.put(event, timeout=VIEW_WRITE_TIMEOUT_SECONDS)
+ except queue.Full:
+ return
+ # A failed view never reads the finish event, so stop waiting and let display() terminate it.
+ while self._process is not None and self._error is None:
+ try:
+ self._process.wait(timeout=0.5)
+ return
+ except subprocess.TimeoutExpired:
+ continue
+
+
+@contextmanager
+def open_dashboard(transcript: Path) -> Iterator[EvalDashboard]:
+ command = resolve_view_command()
+ with open_terminal() as terminal:
+ dashboard = EvalDashboard(
+ transcript,
+ command=command,
+ terminal=terminal,
+ cancel=lambda: os.kill(os.getpid(), signal.SIGINT),
+ )
+ with dashboard.display():
+ yield dashboard
diff --git a/products/posthog_ai/eval_harness/harness/lifecycle.py b/products/posthog_ai/eval_harness/harness/lifecycle.py
index ed7b03e643c4..1f6105cc8b9d 100644
--- a/products/posthog_ai/eval_harness/harness/lifecycle.py
+++ b/products/posthog_ai/eval_harness/harness/lifecycle.py
@@ -10,6 +10,7 @@ from collections.abc import Sequence
from contextlib import AsyncExitStack, ExitStack
from dataclasses import replace
from functools import partial
+from typing import TYPE_CHECKING
from unittest.mock import patch
@@ -48,6 +49,9 @@ from .ports import DJANGO_LIVE_PORT
from .providers import PreflightError, SandboxProviderStrategy, build_provider
from .reporting import ProgressReporter, SuiteRunResult
from .requirements import Infra, infra_union
+
+if TYPE_CHECKING:
+ from .dashboard import EvalDashboard
from .services import (
LONG_LIVED_SUBPROCESSES,
build_local_skills,
@@ -118,8 +122,9 @@ class SandboxedEvalHarness:
and the shared semaphores that bound sandbox load and serialize team setup.
"""
- def __init__(self, options: HarnessOptions) -> None:
+ def __init__(self, options: HarnessOptions, *, dashboard: EvalDashboard | None = None) -> None:
self.options = options
+ self._dashboard = dashboard
self.provider: SandboxProviderStrategy | None = None
# The execution/reporting backend for this run. No --engine flag yet, so
# this is the registry default; it feeds preflight and every suite's run.
@@ -169,7 +174,7 @@ class SandboxedEvalHarness:
flags = ", ".join(self.options.sandbox_flags_set)
raise PreflightError(f"{flags}: no selected suite is sandboxed, so sandbox flags have no effect")
- reporter = ProgressReporter(total_suites=len(suites), verbose=self.options.verbose)
+ reporter = ProgressReporter(total_suites=len(suites), verbose=self.options.verbose, dashboard=self._dashboard)
reporter.print_run_header(
provider=self.options.provider,
agent_runtime=self.options.agent_runtime,
@@ -197,13 +202,17 @@ class SandboxedEvalHarness:
reporter.setup_started("build personhog")
ensure_personhog_binaries()
reporter.setup_started("start shared services and prepare demo data")
- self._bootstrap(required)
+ self._bootstrap(required, reporter)
+ if self._dashboard:
+ self._dashboard.setup_finished()
results = asyncio.run(self._run_suites(suites, required, reporter))
except KeyboardInterrupt:
logger.warning("Interrupted, tearing down")
interrupted = True
finally:
try:
+ if self._dashboard:
+ self._dashboard.set_stage("Cleaning up shared services")
self._stack.close()
finally:
atexit.unregister(stop_all_subprocesses)
@@ -248,7 +257,7 @@ class SandboxedEvalHarness:
if error:
raise PreflightError(error)
- def _bootstrap(self, required: frozenset[Infra]) -> None:
+ def _bootstrap(self, required: frozenset[Infra], reporter: ProgressReporter) -> None:
"""Stand up everything the selected suites share. Teardown is registered in
reverse on the stack, so what wasn't started is never torn down."""
LONG_LIVED_SUBPROCESSES.startup_retries = self.options.infrastructure_retries
@@ -259,26 +268,31 @@ class SandboxedEvalHarness:
self._stack.callback(self.provider.cleanup)
if Infra.DATABASE in required:
+ reporter.setup_started("prepare eval databases")
database = EvalDatabase(keepdb=not self.options.create_db)
database.setup()
self._stack.callback(database.teardown)
self._database = database
if Infra.PERSONHOG in required:
+ reporter.setup_started("start personhog")
# Bring personhog up before the live server and demo seeding: those bootstrap
# reads go through the router, and a dead router would poison personhog's 30s
# negative group-types cache for the rest of the run.
self._stack.callback(start_personhog())
if Infra.LIVE_SERVER in required:
+ reporter.setup_started("start Django server")
live_server = EvalLiveServer(DJANGO_LIVE_PORT)
self._stack.callback(live_server.stop)
self._live_server = live_server
if Infra.LLM_GATEWAY in required:
+ reporter.setup_started("start LLM gateway")
assert self._live_server is not None
self._stack.callback(start_llm_gateway(self._live_server.url))
if Infra.MCP_SERVER in required:
+ reporter.setup_started("build skills and start MCP server")
assert self._live_server is not None
# Both delivery modes use rendered skills from this checkout, never a
@@ -300,6 +314,7 @@ class SandboxedEvalHarness:
)
if Infra.SANDBOX in required:
+ reporter.setup_started("prepare sandbox provider")
assert self.provider is not None
# Modal sandboxes live off-host, so the three services above have to be
# publicly reachable before any settings pointing at them are computed.
@@ -315,6 +330,7 @@ class SandboxedEvalHarness:
self._stack.callback(self._posthog_evaluation_client.shutdown)
if Infra.DEMO_DATA in required:
+ reporter.setup_started("prepare demo data")
assert self._database is not None
self._demo_data = ensure_demo_ready(
blocker=self._database.blocker,
diff --git a/products/posthog_ai/eval_harness/harness/progress.py b/products/posthog_ai/eval_harness/harness/progress.py
new file mode 100644
index 000000000000..c56d480f6d8a
--- /dev/null
+++ b/products/posthog_ai/eval_harness/harness/progress.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Literal
+
+from posthog.dataclasses import frozen
+
+TrialPhase = Literal["queued", "setup", "agent", "cleanup", "logs", "scoring", "done", "error", "timeout", "canceled"]
+TERMINAL_PHASES = {"done", "error", "timeout", "canceled"}
+
+
+@frozen
+class TrialProgress:
+ trial_id: str
+ experiment: str
+ name: str
+ trial_index: int
+ phase: TrialPhase
+ started: float
+ log_dir: Path | None
+ ended: float | None = None
+ detail: str = ""
+ retries: int = 0
diff --git a/products/posthog_ai/eval_harness/harness/reporting.py b/products/posthog_ai/eval_harness/harness/reporting.py
index cc384d53447c..9588ef1ccc31 100644
--- a/products/posthog_ai/eval_harness/harness/reporting.py
+++ b/products/posthog_ai/eval_harness/harness/reporting.py
@@ -9,14 +9,18 @@ from collections.abc import AsyncIterator, Sequence
from contextlib import asynccontextmanager, suppress
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
from posthog.dataclasses import frozen
from ..engines.types import EvalSummary
+from .progress import TrialPhase, TrialProgress
from .transcript import write_console
from .trial_stats import ScorerTrialStats
+if TYPE_CHECKING:
+ from .dashboard import EvalDashboard
+
EVAL_RESULTS_JSONL = "eval_results.jsonl"
"""Machine-readable per-experiment summary export, opt-in via ``EXPORT_EVAL_RESULTS``."""
@@ -68,7 +72,7 @@ class _CaseProgress:
class ProgressReporter:
"""Serializes harness output and renders the stable final summary."""
- def __init__(self, total_suites: int, *, verbose: bool = False) -> None:
+ def __init__(self, total_suites: int, *, verbose: bool = False, dashboard: EvalDashboard | None = None) -> None:
self._total_suites = total_suites
self._verbose = verbose
self._lock = asyncio.Lock()
@@ -85,6 +89,25 @@ class ProgressReporter:
self._log_dirs: dict[str, Path] = {}
self._active_cases: dict[str, _CaseProgress] = {}
self._started = time.monotonic()
+ self._dashboard = dashboard
+
+ def _publish_trial(
+ self, trial_id: str, case: _CaseProgress, *, phase: TrialPhase | None = None, detail: str = ""
+ ) -> None:
+ if self._dashboard is not None:
+ self._dashboard.update_trial(
+ TrialProgress(
+ trial_id=trial_id,
+ experiment=case.experiment,
+ name=case.name,
+ trial_index=case.trial_index,
+ phase=phase or case.phase,
+ started=case.started,
+ ended=time.monotonic() if phase in {"done", "error", "timeout", "canceled"} else None,
+ log_dir=self._log_dirs.get(case.experiment),
+ detail=detail,
+ )
+ )
@asynccontextmanager
async def live_updates(self) -> AsyncIterator[None]:
@@ -127,6 +150,7 @@ class ProgressReporter:
experiment=experiment, name=name, trial_index=trial_index, started=now, phase_started=now
)
self._active_cases[trial_id] = case
+ self._publish_trial(trial_id, case)
await asyncio.to_thread(_emit, f"CASE START {case.label()} queued; id={trial_id}")
return case.durations
@@ -136,6 +160,7 @@ class ProgressReporter:
if case is None or case.phase == phase:
return
case.transition(phase)
+ self._publish_trial(trial_id, case)
await asyncio.to_thread(_emit, f"CASE PHASE {case.label()} {phase}")
async def case_scored(self, trial_id: str, *, error: str | None = None) -> None:
@@ -150,6 +175,12 @@ class ProgressReporter:
marker = (
"ERROR" if error is not None else {"ok": "DONE", "timeout": "TIMEOUT", "error": "ERROR"}[case.status]
)
+ phase: TrialPhase = "done"
+ if error is not None or case.status == "error":
+ phase = "error"
+ elif case.status == "timeout":
+ phase = "timeout"
+ self._publish_trial(trial_id, case, phase=phase, detail=error or "")
await asyncio.to_thread(_emit, f"CASE {marker:<7} {case.label()} results ready")
async def finish_cases(self, trial_ids: Sequence[str]) -> None:
@@ -158,6 +189,7 @@ class ProgressReporter:
case = self._active_cases.pop(trial_id, None)
if case is not None:
case.transition(case.phase)
+ self._publish_trial(trial_id, case, phase="canceled")
async def finish_experiment(self, experiment: str) -> None:
await self.finish_cases(
@@ -165,6 +197,8 @@ class ProgressReporter:
)
def setup_started(self, phase: str) -> None:
+ if self._dashboard:
+ self._dashboard.setup_started(phase)
_emit(f"SETUP START {phase}")
def print_run_header(
@@ -177,6 +211,10 @@ class ProgressReporter:
trials: int,
case_timeout_seconds: int,
) -> None:
+ if self._dashboard:
+ self._dashboard.configure(
+ f"{provider} | {agent_runtime} / {agent_model} | {max_sandboxes} sandboxes | {trials} trials per case"
+ )
lines = [
"Sandboxed eval run",
f"Suites: {self._total_suites}",
@@ -199,6 +237,8 @@ class ProgressReporter:
async with self._lock:
self._experiment_totals[experiment_name] = planned_cases
self._log_dirs[experiment_name] = log_dir
+ if self._dashboard:
+ self._dashboard.experiment_started(experiment_name, planned_cases)
await asyncio.to_thread(_emit, f"EXPERIMENT START {experiment_name} [{planned_cases} cases]")
async def case_done(
@@ -210,6 +250,7 @@ class ProgressReporter:
status: CaseStatus = "ok",
trial_id: str | None = None,
error_type: str | None = None,
+ error_detail: str | None = None,
) -> None:
async with self._lock:
self._case_counts[experiment_name] += 1
@@ -229,6 +270,12 @@ class ProgressReporter:
marker = "READY" if status == "ok" else "TIMEOUT"
detail = "; execution complete; scoring pending"
case.transition("scoring")
+ self._publish_trial(
+ trial_id,
+ case,
+ phase="error" if status == "error" else None,
+ detail=error_detail or detail.removeprefix("; "),
+ )
total = self._experiment_totals.get(experiment_name)
progress = f"[{self._case_counts[experiment_name]}/{total}]" if total is not None else ""
await asyncio.to_thread(
@@ -245,9 +292,15 @@ class ProgressReporter:
total_attempts: int,
delay_seconds: float,
error_type: str,
+ trial_id: str | None = None,
) -> None:
async with self._lock:
self._setup_retry_count += 1
+ if self._dashboard and trial_id:
+ self._dashboard.trial_retry(
+ trial_id,
+ f"Setup attempt {next_attempt}/{total_attempts} in {delay_seconds:.1f}s ({error_type}). No action required.",
+ )
await asyncio.to_thread(
_emit,
f"CASE RETRY {experiment_name} :: {case_name} setup attempt {next_attempt}/{total_attempts} "
diff --git a/products/posthog_ai/eval_harness/harness/services.py b/products/posthog_ai/eval_harness/harness/services.py
index db893d48a517..93cde2a0f4be 100644
--- a/products/posthog_ai/eval_harness/harness/services.py
+++ b/products/posthog_ai/eval_harness/harness/services.py
@@ -4,9 +4,11 @@ import os
import sys
import json
import shutil
+import signal
import hashlib
import logging
import zipfile
+import contextlib
import subprocess
from collections.abc import Callable
from pathlib import Path
@@ -198,19 +200,29 @@ def ensure_personhog_binaries() -> None:
logger.info(
"Building personhog binaries (first build can take several minutes; later builds are incremental no-ops)"
)
- result = subprocess.run(
+ # Cargo runs in its own process group so a cancel can stop the rustc processes it
+ # starts. A SIGINT to the harness alone stops Cargo and leaves the compilers running.
+ build = subprocess.Popen(
["cargo", "build", "-p", "personhog-replica", "-p", "personhog-router"],
cwd=rust_dir,
- capture_output=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
text=True,
+ start_new_session=True,
+ )
+ try:
# The first build compiles the whole dependency tree; only later builds are
# incremental no-ops. Keep the ceiling well clear of a cold compile.
- timeout=20 * 60,
- )
- if result.returncode != 0:
- output = (result.stdout or "") + (result.stderr or "")
+ stdout, stderr = build.communicate(timeout=20 * 60)
+ except BaseException:
+ with contextlib.suppress(ProcessLookupError):
+ os.killpg(build.pid, signal.SIGKILL)
+ build.wait()
+ raise
+ if build.returncode != 0:
+ output = (stdout or "") + (stderr or "")
tail = "\n".join(output.splitlines()[-30:])
- raise PreflightError(f"Failed to build personhog binaries (cargo exit {result.returncode}):\n{tail}")
+ raise PreflightError(f"Failed to build personhog binaries (cargo exit {build.returncode}):\n{tail}")
def start_personhog() -> Callable[[], None]:
diff --git a/products/posthog_ai/eval_harness/harness/terminal.py b/products/posthog_ai/eval_harness/harness/terminal.py
new file mode 100644
index 000000000000..cbba75f89c9b
--- /dev/null
+++ b/products/posthog_ai/eval_harness/harness/terminal.py
@@ -0,0 +1,27 @@
+from __future__ import annotations
+
+import os
+import sys
+from collections.abc import Iterator
+from contextlib import ExitStack, contextmanager
+from typing import TextIO
+
+from posthog.dataclasses import frozen
+
+
+@frozen
+class TerminalStreams:
+ input: TextIO
+ output: TextIO
+
+
+@contextmanager
+def open_terminal() -> Iterator[TerminalStreams]:
+ with ExitStack() as stack:
+ if sys.stdin.isatty() and sys.stdout.isatty():
+ input = stack.enter_context(os.fdopen(os.dup(sys.stdin.fileno()), "r", encoding="utf-8"))
+ output = stack.enter_context(os.fdopen(os.dup(sys.stdout.fileno()), "w", encoding="utf-8"))
+ else:
+ input = stack.enter_context(open("/dev/tty", encoding="utf-8"))
+ output = stack.enter_context(open("/dev/tty", "w", encoding="utf-8"))
+ yield TerminalStreams(input=input, output=output)
diff --git a/products/posthog_ai/eval_harness/harness/transcript.py b/products/posthog_ai/eval_harness/harness/transcript.py
index a60f7f0b756c..2a53b1813fd4 100644
--- a/products/posthog_ai/eval_harness/harness/transcript.py
+++ b/products/posthog_ai/eval_harness/harness/transcript.py
@@ -5,7 +5,7 @@ import sys
import uuid
import logging
import threading
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from contextlib import ExitStack, contextmanager, redirect_stderr, redirect_stdout
from datetime import UTC, datetime
from pathlib import Path
@@ -24,6 +24,7 @@ class _TranscriptSink:
self.lock = threading.Lock()
self.finished = False
self.ends_with_newline = True
+ self.console_output: Callable[[str], None] | None = None
def write(self, terminal: TextIO, text: str, *, terminal_text: str | None = None) -> int:
with self.lock:
@@ -35,8 +36,11 @@ class _TranscriptSink:
self.ends_with_newline = text.endswith("\n")
console_text = text if terminal_text is None else terminal_text
if console_text:
- terminal.write(console_text)
- terminal.flush()
+ if self.console_output is not None:
+ self.console_output(console_text)
+ else:
+ terminal.write(console_text)
+ terminal.flush()
return len(text)
def flush(self, terminal: TextIO) -> None:
@@ -81,8 +85,11 @@ class _TranscriptLogHandler(logging.Handler):
elif record.levelno >= logging.WARNING and record.name.startswith("products.posthog_ai.eval_harness"):
message = str(
record.msg.get("event", record.msg) if isinstance(record.msg, dict) else record.getMessage()
- ).splitlines()
- terminal_text = f"{record.levelname}: {record.name}: {message[0][:240] if message else ''}\n"
+ )
+ if record.exc_info and (error := record.exc_info[1]) is not None:
+ message = f"{message}: {type(error).__name__}: {error}"
+ lines = message.splitlines()
+ terminal_text = f"{record.levelname}: {record.name}: {lines[0][:240] if lines else ''}\n"
self._sink.write(self._terminal, detail, terminal_text=terminal_text)
except Exception:
self.handleError(record)
@@ -181,15 +188,19 @@ class RunTranscript:
self._sink.stdout = terminal
@contextmanager
- def capture(self, *, verbose: bool = True) -> Iterator[None]:
+ def capture(self, *, verbose: bool = True, console_output: Callable[[str], None] | None = None) -> Iterator[None]:
self._stdout._verbose = verbose
self._stderr._verbose = verbose
- with ExitStack() as stack:
- stack.enter_context(self._capture_file_descriptor(self._stdout, 1))
- stack.enter_context(self._capture_file_descriptor(self._stderr, 2))
- stack.enter_context(redirect_stdout(self._stdout))
- stack.enter_context(redirect_stderr(self._stderr))
- yield
+ self._sink.console_output = console_output
+ try:
+ with ExitStack() as stack:
+ stack.enter_context(self._capture_file_descriptor(self._stdout, 1))
+ stack.enter_context(self._capture_file_descriptor(self._stderr, 2))
+ stack.enter_context(redirect_stdout(self._stdout))
+ stack.enter_context(redirect_stderr(self._stderr))
+ yield
+ finally:
+ self._sink.console_output = None
def finish(self) -> None:
self._sink.finish()
diff --git a/products/posthog_ai/eval_harness/harness/tunnels.py b/products/posthog_ai/eval_harness/harness/tunnels.py
index c7af0dc315c9..54d31190808f 100644
--- a/products/posthog_ai/eval_harness/harness/tunnels.py
+++ b/products/posthog_ai/eval_harness/harness/tunnels.py
@@ -1,12 +1,18 @@
from __future__ import annotations
+import ssl
import json
+import time
import shutil
+import socket
import logging
import subprocess
+from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
+import requests
+
logger = logging.getLogger(__name__)
SETUP_GUIDE = "docs/internal/sandboxes-setup-guide.md"
@@ -18,6 +24,15 @@ callbacks; each requested service is assigned one in the order the caller lists
them."""
+PUBLIC_DNS_URL = "https://cloudflare-dns.com/dns-query"
+FUNNEL_READY_TIMEOUT_SECONDS = 300
+FUNNEL_READY_ROUNDS = 3
+"""Consecutive rounds in which every relay must answer every service. A relay switches cleanly
+from failing to working, so a few clean rounds in a row mean the relay is up, not lucky."""
+FUNNEL_PROBE_INTERVAL_SECONDS = 2
+FUNNEL_PROBE_TIMEOUT_SECONDS = 5
+
+
class TailscaleFunnelError(RuntimeError):
"""Tailscale Funnel could not expose the host services for the eval run."""
@@ -116,6 +131,40 @@ def _configured_public_ports() -> set[int]:
return ports
+def _public_ips(host: str) -> list[str]:
+ """IPv4 addresses that public DNS gives for ``host``.
+
+ The local resolver returns this node's tailnet address, which skips the Funnel relays that
+ a Modal sandbox connects to, so the readiness probe has to ask a public resolver.
+ """
+ response = requests.get(
+ PUBLIC_DNS_URL,
+ params={"name": host, "type": "A"},
+ headers={"accept": "application/dns-json"},
+ timeout=FUNNEL_PROBE_TIMEOUT_SECONDS,
+ )
+ response.raise_for_status()
+ payload = response.json()
+ return sorted({answer["data"] for answer in payload.get("Answer", []) if answer.get("type") == 1})
+
+
+def _relay_answers(ip: str, host: str, public_port: int) -> bool:
+ """Whether one Funnel relay completes TLS for ``host`` and returns an HTTP response.
+
+ Any HTTP status counts, because the probe tests the public path, not the service behind it.
+ """
+ context = ssl.create_default_context()
+ try:
+ with (
+ socket.create_connection((ip, public_port), timeout=FUNNEL_PROBE_TIMEOUT_SECONDS) as raw,
+ context.wrap_socket(raw, server_hostname=host) as connection,
+ ):
+ connection.sendall(f"HEAD / HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n".encode())
+ return connection.recv(16).startswith(b"HTTP/")
+ except (OSError, ssl.SSLError):
+ return False
+
+
class TailscaleFunnel:
"""Modal-only Tailscale Funnel lifecycle: publicly exposes the host services a
remote Modal sandbox must reach (Django API, LLM gateway, MCP server).
@@ -128,7 +177,15 @@ class TailscaleFunnel:
registers ``stop`` on its cleanup stack.
"""
- def __init__(self, ports: dict[str, int]) -> None:
+ def __init__(
+ self,
+ ports: dict[str, int],
+ *,
+ resolve_public_ips: Callable[[str], list[str]] = _public_ips,
+ relay_answers: Callable[[str, str, int], bool] = _relay_answers,
+ clock: Callable[[], float] = time.monotonic,
+ sleep: Callable[[float], None] = time.sleep,
+ ) -> None:
if len(ports) > len(FUNNEL_PUBLIC_PORTS):
raise TailscaleFunnelError(
f"Tailscale Funnel exposes at most {len(FUNNEL_PUBLIC_PORTS)} public ports "
@@ -140,6 +197,10 @@ class TailscaleFunnel:
}
self._public_urls: dict[str, str] = {}
self._enabled_ports: list[int] = []
+ self._resolve_public_ips = resolve_public_ips
+ self._relay_answers = relay_answers
+ self._clock = clock
+ self._sleep = sleep
def start(self) -> None:
host = self._resolve_public_host()
@@ -159,6 +220,13 @@ class TailscaleFunnel:
self._enable_funnel(assignment.public_port, assignment.local_port)
self._enabled_ports.append(assignment.public_port)
self._public_urls[name] = _public_url(host, assignment.public_port)
+ try:
+ self._wait_until_public(host)
+ except BaseException:
+ # The caller registers stop() only after start() returns, so a failed or interrupted
+ # wait must turn the ports off here or they stay public.
+ self.stop()
+ raise
logger.info("Tailscale Funnel ready: %s", self._public_urls)
def url_for(self, name: str) -> str:
@@ -192,6 +260,44 @@ class TailscaleFunnel:
if not still_public:
self._public_urls = {}
+ def _wait_until_public(self, host: str) -> None:
+ """Block until every public Funnel relay serves every service.
+
+ `tailscale funnel --bg` returns before the public relays accept the new config, and each
+ relay starts serving at its own time, which can take minutes. Public DNS rotates between
+ the relays, so a sandbox that starts too early fails TLS on some connections, and a failed
+ startup request ends the whole case.
+ """
+ try:
+ ips = self._resolve_public_ips(host)
+ except Exception:
+ logger.warning(
+ "Could not resolve the Funnel relays through public DNS; not waiting for them", exc_info=True
+ )
+ return
+ if not ips:
+ logger.warning("Public DNS returned no Funnel relays for %s; not waiting for them", host)
+ return
+
+ ports = [assignment.public_port for assignment in self._assignments.values()]
+ logger.info("Waiting for Tailscale Funnel relays %s to serve ports %s", ips, ports)
+ deadline = self._clock() + FUNNEL_READY_TIMEOUT_SECONDS
+ clean_rounds = 0
+ failing: list[str] = []
+ while True:
+ failing = [f"{ip}:{port}" for ip in ips for port in ports if not self._relay_answers(ip, host, port)]
+ clean_rounds = 0 if failing else clean_rounds + 1
+ if clean_rounds >= FUNNEL_READY_ROUNDS:
+ return
+ if self._clock() >= deadline:
+ raise TailscaleFunnelError(
+ self._failure_message(
+ f"Tailscale Funnel relays did not serve within {FUNNEL_READY_TIMEOUT_SECONDS}s: "
+ f"{', '.join(failing) or 'unstable responses'}. Remote sandboxes cannot reach this host reliably."
+ )
+ )
+ self._sleep(FUNNEL_PROBE_INTERVAL_SECONDS)
+
def _resolve_public_host(self) -> str:
status = tailscale_status()
if status is None:
diff --git a/products/posthog_ai/eval_harness/test/test_dashboard.py b/products/posthog_ai/eval_harness/test/test_dashboard.py
new file mode 100644
index 000000000000..7bccfbaead9e
--- /dev/null
+++ b/products/posthog_ai/eval_harness/test/test_dashboard.py
@@ -0,0 +1,113 @@
+from __future__ import annotations
+
+import os
+import sys
+import json
+import time
+import threading
+from pathlib import Path
+from textwrap import dedent
+
+import pytest
+
+from products.posthog_ai.eval_harness.harness import dashboard as dashboard_module
+from products.posthog_ai.eval_harness.harness.dashboard import EvalDashboard
+from products.posthog_ai.eval_harness.harness.progress import TrialProgress
+from products.posthog_ai.eval_harness.harness.terminal import TerminalStreams
+from products.posthog_ai.eval_harness.log_sink import _case_log_slug
+
+FAKE_VIEW = dedent("""
+ import json, socket, sys, time
+ mode, events = sys.argv[1], sys.argv[2]
+ if mode == "startup":
+ sys.stderr.write("phrocs: unknown flag: evals")
+ raise SystemExit(2)
+ stream = socket.socket(fileno=int(sys.argv[5]))
+ stream.sendall(b"ready\\n")
+ if mode == "stall":
+ time.sleep(30)
+ with open(events, "w") as record:
+ for line in stream.makefile("rb"):
+ event = json.loads(line)
+ record.write(line.decode())
+ record.flush()
+ if event["type"] == "experiment":
+ if mode == "runtime":
+ raise SystemExit(3)
+ stream.sendall(b"cancel\\n")
+ if event["type"] == "finish":
+ break
+""")
+
+
[email protected]("mode", ["cancel", "startup", "runtime", "stall"])
+def test_dashboard_streams_progress_and_relays_view_cancel_and_failures(
+ tmp_path: Path, mode: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(dashboard_module, "VIEW_WRITE_TIMEOUT_SECONDS", 0.5)
+ events = tmp_path / "events.jsonl"
+ canceled = threading.Event()
+ with open(os.devnull) as terminal_input, open(os.devnull, "w") as terminal_output:
+ dashboard = EvalDashboard(
+ tmp_path / "run.log",
+ command=[sys.executable, "-c", FAKE_VIEW, mode, str(events)],
+ terminal=TerminalStreams(input=terminal_input, output=terminal_output),
+ cancel=canceled.set,
+ )
+ if mode == "startup":
+ with pytest.raises(RuntimeError, match="unknown flag: evals"):
+ with dashboard.display():
+ pass
+ return
+ saved_stdin = os.dup(0)
+ pipe_read, pipe_write = os.pipe()
+ os.dup2(pipe_read, 0)
+ try:
+ with dashboard.display():
+ assert os.path.samestat(os.fstat(0), os.stat(os.devnull))
+ assert dashboard.begin_run()
+ if mode == "stall":
+ started = time.monotonic()
+ for _ in range(2_000):
+ dashboard.write("x" * 10_000)
+ assert time.monotonic() - started < 1
+ assert canceled.wait(timeout=5)
+ assert "stopped reading" in str(dashboard.failure)
+ finishing = threading.Thread(target=dashboard.finish, args=(130,), daemon=True)
+ finishing.start()
+ finishing.join(timeout=5)
+ assert not finishing.is_alive()
+ return
+ dashboard.update_trial(
+ TrialProgress(
+ trial_id="t1",
+ experiment="sql-basics",
+ name="count events",
+ trial_index=0,
+ phase="agent",
+ started=time.monotonic(),
+ log_dir=tmp_path,
+ )
+ )
+ dashboard.experiment_started("sql-basics", 1)
+ assert canceled.wait(timeout=5)
+ dashboard.end_run()
+ dashboard.finish(130)
+ assert os.path.samestat(os.fstat(0), os.fstat(pipe_read))
+ finally:
+ os.dup2(saved_stdin, 0)
+ for fd in (saved_stdin, pipe_read, pipe_write):
+ os.close(fd)
+
+ if mode == "runtime":
+ assert isinstance(dashboard.failure, RuntimeError)
+ assert "exited with code 3" in str(dashboard.failure)
+ return
+ assert dashboard.failure is None
+ received = [json.loads(line) for line in events.read_text().splitlines()]
+ trial = next(event for event in received if event["type"] == "trial")
+ slug = _case_log_slug("count events", "t1")
+ assert trial["summary_path"] == str(tmp_path / f"{slug}.summary.txt")
+ assert trial["log_path"] == str(tmp_path / f"{slug}.jsonl")
+ assert abs(trial["started"] - time.time()) < 60
+ assert received[-1] == {"type": "finish", "exit_code": 130, "text": ""}
diff --git a/products/posthog_ai/eval_harness/test/test_one_shot_runner.py b/products/posthog_ai/eval_harness/test/test_one_shot_runner.py
index cee656be28b3..f204b9c2ba28 100644
--- a/products/posthog_ai/eval_harness/test/test_one_shot_runner.py
+++ b/products/posthog_ai/eval_harness/test/test_one_shot_runner.py
@@ -28,6 +28,7 @@ from products.posthog_ai.eval_harness.engines.types import (
from products.posthog_ai.eval_harness.harness.cli import parse_args
from products.posthog_ai.eval_harness.harness.context import EvalContext
from products.posthog_ai.eval_harness.harness.lifecycle import SandboxedEvalHarness
+from products.posthog_ai.eval_harness.harness.reporting import ProgressReporter
from products.posthog_ai.eval_harness.harness.trial_stats import ScorerTrialStats
from products.posthog_ai.eval_harness.one_shot import _OneShotEvalRun
from products.tasks.backend.facade.agents import TurnPollTimeout
@@ -63,6 +64,7 @@ class _StubReporter:
status: str,
trial_id: str | None = None,
error_type: str | None = None,
+ error_detail: str | None = None,
) -> None:
self.done.append((case_name, status))
@@ -282,7 +284,7 @@ def test_run_routes_through_the_engine(
):
harness = SandboxedEvalHarness(parse_args(["--agent-model", "claude-test"]))
with harness._stack:
- harness._bootstrap(frozenset())
+ harness._bootstrap(frozenset(), ProgressReporter(total_suites=0))
ctx = harness._build_context(frozenset(), reporter) # type: ignore[arg-type]
runs = [_build_run(tmp_path, monkeypatch, ctx, task) for _ in range(2)]
for run in runs:
diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_cli.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_cli.py
index a670c5267606..9eb6ddffabf8 100644
--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_cli.py
+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_cli.py
@@ -1,7 +1,9 @@
from __future__ import annotations
import pytest
+from unittest.mock import MagicMock
+from products.posthog_ai.eval_harness.harness.__main__ import use_dashboard
from products.posthog_ai.eval_harness.harness.cli import SkillDelivery, parse_args
@@ -32,3 +34,30 @@ def test_infrastructure_retry_budget(argv: list[str], expected: int | None) -> N
@pytest.mark.parametrize("argv,verbose", [([], False), (["--verbose"], True)])
def test_console_output_detail(argv: list[str], verbose: bool) -> None:
assert parse_args(argv).verbose is verbose
+
+
+ "stdout_tty,hogli_stdout_tty,ci,expected",
+ [
+ (True, None, False, True),
+ (True, None, True, False),
+ (False, "1", False, True),
+ (False, "0", False, False),
+ ],
+ ids=["terminal", "ci", "secrets-wrapper-pipe", "redirected-hogli-output"],
+)
+def test_interactive_output_selection(
+ monkeypatch: pytest.MonkeyPatch, stdout_tty: bool, hogli_stdout_tty: str | None, ci: bool, expected: bool
+) -> None:
+ monkeypatch.setattr("sys.stdin.isatty", MagicMock(return_value=True))
+ monkeypatch.setattr("sys.stdout.isatty", MagicMock(return_value=stdout_tty))
+ if hogli_stdout_tty is None:
+ monkeypatch.delenv("HOGLI_STDOUT_TTY", raising=False)
+ else:
+ monkeypatch.setenv("HOGLI_STDOUT_TTY", hogli_stdout_tty)
+ monkeypatch.setenv("TERM", "xterm-256color")
+ if ci:
+ monkeypatch.setenv("CI", "true")
+ else:
+ monkeypatch.delenv("CI", raising=False)
+ assert use_dashboard(parse_args([])) is expected
diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py
index 2871ab102be9..0129fd34db0b 100644
--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py
+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py
@@ -746,7 +746,7 @@ def test_console_detail_does_not_remove_transcript_logs(
None,
)
try:
- raise ValueError("service unavailable")
+ raise ValueError("service unavailable\nconnection details")
except ValueError:
error = logging.LogRecord(
"products.posthog_ai.eval_harness.example",
@@ -788,6 +788,8 @@ def test_console_detail_does_not_remove_transcript_logs(
assert ("optional dependency detail" in output.err) is verbose
assert "agent detail" in saved
assert "ValueError: service unavailable" in saved
+ assert "ValueError: service unavailable" in output.err
+ assert ("connection details" in output.err) is verbose
assert "case error" in output.err
assert ("agent detail" in output.err) is verbose
assert ("Traceback" in output.err) is verbose
@@ -795,11 +797,13 @@ def test_console_detail_does_not_remove_transcript_logs(
@pytest.mark.parametrize("verbose", [False, True])
[email protected]("interactive", [False, True])
def test_native_child_output_stays_in_transcript_and_file_descriptors_restore(
- tmp_path: Path, capfd: pytest.CaptureFixture[str], verbose: bool
+ tmp_path: Path, capfd: pytest.CaptureFixture[str], verbose: bool, interactive: bool
) -> None:
transcript = RunTranscript.create(tmp_path)
- with transcript.capture(verbose=verbose):
+ console: list[str] = []
+ with transcript.capture(verbose=verbose, console_output=console.append if interactive else None):
subprocess.run(
[sys.executable, "-c", "import os; os.write(1, b'native stdout\\n'); os.write(2, b'native stderr')"],
check=True,
@@ -811,7 +815,8 @@ def test_native_child_output_stays_in_transcript_and_file_descriptors_restore(
saved = transcript.path.read_text()
assert "native stdout" not in output.out
assert "native stderr" not in output.err
- assert "SETUP START example service" in output.out
+ assert ("SETUP START example service" in output.out) is (not interactive)
+ assert ("SETUP START example service\n" in console) is interactive
assert "descriptors restored" in output.out
assert "native stdout\nnative stderr" in saved
assert saved.count("SETUP START example service") == 1
diff --git a/products/posthog_ai/eval_harness/test/test_tunnels.py b/products/posthog_ai/eval_harness/test/test_tunnels.py
new file mode 100644
index 000000000000..35321985fa1e
--- /dev/null
+++ b/products/posthog_ai/eval_harness/test/test_tunnels.py
@@ -0,0 +1,58 @@
+from __future__ import annotations
+
+import json
+import subprocess
+
+import pytest
+from unittest.mock import patch
+
+from products.posthog_ai.eval_harness.harness import tunnels
+from products.posthog_ai.eval_harness.harness.tunnels import TailscaleFunnel, TailscaleFunnelError
+
+HOST = "eval-host.example.ts.net"
+RELAYS = ["192.0.2.1", "192.0.2.2"]
+
+
+class _FakeTailscale:
+ def __init__(self) -> None:
+ self.public_ports: set[int] = set()
+
+ def __call__(self, args: list[str], *, timeout: int) -> subprocess.CompletedProcess[str]:
+ if args[:2] == ["status", "--json"]:
+ stdout = json.dumps({"BackendState": "Running", "Self": {"DNSName": f"{HOST}."}})
+ elif args[:2] == ["serve", "status"]:
+ stdout = "{}"
+ elif args[0] == "funnel" and args[-1] == "off":
+ self.public_ports.discard(int(args[2]))
+ stdout = ""
+ else:
+ self.public_ports.add(int(args[2].removeprefix("--https=")))
+ stdout = ""
+ return subprocess.CompletedProcess(args, 0, stdout=stdout, stderr="")
+
+
+class _FakeClock:
+ def __init__(self) -> None:
+ self.now = 0.0
+
+ def time(self) -> float:
+ return self.now
+
+ def sleep(self, seconds: float) -> None:
+ self.now += seconds
+
+
+def test_start_unpublishes_ports_when_a_relay_never_serves() -> None:
+ tailscale = _FakeTailscale()
+ clock = _FakeClock()
+ funnel = TailscaleFunnel(
+ {"django": 18000, "gateway": 13308},
+ resolve_public_ips=lambda host: RELAYS,
+ relay_answers=lambda ip, host, port: ip == RELAYS[0],
+ clock=clock.time,
+ sleep=clock.sleep,
+ )
+
+ with patch.object(tunnels, "_run_tailscale", tailscale), pytest.raises(TailscaleFunnelError, match="192.0.2.2:443"):
+ funnel.start()
+ assert tailscale.public_ports == set()
diff --git a/pyproject.toml b/pyproject.toml
index cad9d47188ba..7401cdf89b27 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -255,6 +255,7 @@ dev = [
"orjson==3.11.9",
"packaging==25.0",
"parameterized==0.9.0",
+ "prompt-toolkit~=3.0.51",
"prance==23.6.21.0",
"pyarrow==23.0.1",
"pyarrow-stubs==20.0.0.20260625",
diff --git a/tools/hogli/AGENTS.md b/tools/hogli/AGENTS.md
index e13f53c264f7..af645fd3e6cc 100644
--- a/tools/hogli/AGENTS.md
+++ b/tools/hogli/AGENTS.md
@@ -50,6 +50,7 @@ Even 1Password's own docs don't recommend a "task runner integration" — they j
- `config.env.files: [...]` — list of dotenv files, loaded in order, first wins, shell env always wins.
- `config.env.secrets.{file, marker, wrap}` — optional generic wrapper hook. Re-execs the invocation under `wrap` when (1) the invoked subcommand opts in via `needs_secrets: true`, (2) the file contains `marker`, and (3) `wrap[0]` is on PATH. Otherwise loads the file directly with marker-matching lines skipped, so literals don't leak as garbage strings.
- `HOGLI_SECRETS_WRAPPED=1` sentinel — set before the wrap re-exec, inherited by subprocesses so composite/steps chains don't re-prompt for auth on every step.
+- `HOGLI_STDOUT_TTY=1|0` — set next to the sentinel. It records whether hogli's stdout was a terminal, because a wrap tool can pipe the child's stdout (for example to mask secrets).
- Per-command `needs_secrets: true` — opt-in gate for the wrap. Without it the wrap never fires; the built-in `hogli run` is the one framework command that always opts in.
**Not in core:**
@@ -90,7 +91,7 @@ If you're about to add code to `tools/hogli/` and you're not sure whether it's g
Core and consumers share the `HOGLI_` env prefix; check both lists before minting a new name.
-Core-reserved (defined in `tools/hogli/src/hogli/`): `HOGLI_DEBUG`, `HOGLI_MANIFEST`, `HOGLI_SECRETS_WRAPPED`, `HOGLI_NESTED_INVOCATION`.
+Core-reserved (defined in `tools/hogli/src/hogli/`): `HOGLI_DEBUG`, `HOGLI_MANIFEST`, `HOGLI_SECRETS_WRAPPED`, `HOGLI_STDOUT_TTY`, `HOGLI_NESTED_INVOCATION`.
Consumer-owned (defined in `tools/hogli-commands/`): `HOGLI_ENVIRONMENT`, `HOGLI_AGENT`, `HOGLI_ACTOR`, `HOGLI_GIT_HOOK`, `HOGLI_PROCESS_MANAGER` (telemetry self-declaration), `HOGLI_NO_HINTS`, `HOGLI_MPROCS_PATH`, `HOGLI_DEVBOX_CODER_URL`, `HOGLI_DEVBOX_CODER_VERSION`.
diff --git a/tools/hogli/src/hogli/cli.py b/tools/hogli/src/hogli/cli.py
index 22962f996d31..3a2bf8ee1487 100644
--- a/tools/hogli/src/hogli/cli.py
+++ b/tools/hogli/src/hogli/cli.py
@@ -341,6 +341,11 @@ def concepts() -> None:
# binary; checked at the top of `_apply_env_config` on subsequent invocations.
_SECRETS_WRAPPED_ENV = "HOGLI_SECRETS_WRAPPED"
+# Whether hogli's own stdout was a terminal before the wrap re-exec. Wrap tools can pipe the
+# child's stdout (`op run` does, to mask secrets), so the child cannot see that the user is
+# at a terminal. Set to "1" or "0" next to the sentinel.
+_STDOUT_TTY_ENV = "HOGLI_STDOUT_TTY"
+
# Substituted to the absolute path of the secrets file when building the wrap
# argv. Kept as a constant so the README, AGENTS.md, and runtime stay in sync.
_WRAP_FILE_PLACEHOLDER = "{file}"
@@ -497,6 +502,7 @@ def _maybe_reexec_via_wrap(secrets: dict[str, Any], env_files: list[Path]) -> No
resolved_wrap = [arg.replace(_WRAP_FILE_PLACEHOLDER, str(secrets_file)) for arg in wrap]
os.environ[_SECRETS_WRAPPED_ENV] = "1"
+ os.environ[_STDOUT_TTY_ENV] = "1" if sys.stdout.isatty() else "0"
os.execvp(resolved_wrap[0], [*resolved_wrap, sys.executable, "-m", "hogli", *sys.argv[1:]])
diff --git a/tools/hogli/tests/test_cli.py b/tools/hogli/tests/test_cli.py
index 9dc828de6012..92b8695bd16f 100644
--- a/tools/hogli/tests/test_cli.py
+++ b/tools/hogli/tests/test_cli.py
@@ -431,7 +431,7 @@ class TestApplyEnvConfig:
needs_secrets_commands={"start"},
),
)
- for k in ("PRELOADED", "HOGLI_SECRETS_WRAPPED"):
+ for k in ("PRELOADED", "HOGLI_SECRETS_WRAPPED", "HOGLI_STDOUT_TTY"):
monkeypatch.delenv(k, raising=False)
# Re-exec only fires when hogli owns the process (real CLI entrypoint).
monkeypatch.setattr("hogli.cli._is_process_entrypoint", True)
@@ -439,10 +439,12 @@ class TestApplyEnvConfig:
with (
patch("shutil.which", return_value="/usr/local/bin/op"),
patch("os.execvp") as mock_exec,
+ patch("sys.stdout.isatty", return_value=True),
):
_apply_env_config("start")
mock_exec.assert_called_once()
+ assert os.environ["HOGLI_STDOUT_TTY"] == "1"
args, _kwargs = mock_exec.call_args
binary, argv = args
assert binary == "op"
diff --git a/tools/phrocs/README.md b/tools/phrocs/README.md
index feacd289b3a3..ab471d70e8df 100644
--- a/tools/phrocs/README.md
+++ b/tools/phrocs/README.md
@@ -54,6 +54,7 @@ hogli phrocs:build
phrocs --config <config.yaml>
phrocs --config <config.yaml> --debug # write debug log to /tmp/phrocs-debug.log
phrocs --version # print version and exit
+phrocs evals --fd N # live eval run view (started by `hogli evals`)
```
The config is generated by `hogli dev:generate` and lives at `.posthog/.generated/mprocs.yaml` in the repo root.
diff --git a/tools/phrocs/evals.go b/tools/phrocs/evals.go
new file mode 100644
index 000000000000..be39d52098b1
--- /dev/null
+++ b/tools/phrocs/evals.go
@@ -0,0 +1,86 @@
+package main
+
+import (
+ "bufio"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "os/signal"
+ "strconv"
+ "syscall"
+
+ tea "charm.land/bubbletea/v2"
+ "github.com/charmbracelet/x/term"
+ "github.com/posthog/posthog/phrocs/internal/tui"
+)
+
+// runEvals renders an eval harness run. The harness passes one end of a socket
+// pair as streamFD: it writes JSON events, and this view writes back "ready"
+// and "cancel" lines.
+func runEvals(streamFD int) int {
+ stream := os.NewFile(uintptr(streamFD), "eval-events")
+ if stream == nil {
+ fmt.Fprintf(os.Stderr, "phrocs: evals: file descriptor %d is not open\n", streamFD)
+ return 2
+ }
+ defer func() { _ = stream.Close() }()
+
+ // The harness owns cancellation. A stray SIGINT must not close the view
+ // while the harness still cleans up sandboxes.
+ signal.Ignore(syscall.SIGINT)
+ // Go's default action for these signals exits without restoring the
+ // terminal, which leaves the shell in raw mode after the run.
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGHUP)
+
+ m := tui.NewEvalModel(func(command string) {
+ _, _ = fmt.Fprintln(stream, command)
+ })
+ opts := []tea.ProgramOption{tea.WithoutSignalHandler()}
+ if !term.IsTerminal(os.Stdout.Fd()) {
+ ttyIn, ttyOut, err := tea.OpenTTY()
+ if err == nil {
+ opts = append(opts, tea.WithInput(ttyIn), tea.WithOutput(ttyOut))
+ defer func() {
+ _ = ttyIn.Close()
+ _ = ttyOut.Close()
+ }()
+ }
+ }
+ p := tea.NewProgram(m, opts...)
+ go func() {
+ <-sigCh
+ p.Kill()
+ }()
+
+ go func() {
+ scanner := bufio.NewScanner(stream)
+ scanner.Buffer(make([]byte, 64*1024), 16*1024*1024)
+ for scanner.Scan() {
+ var event tui.EvalEvent
+ if err := json.Unmarshal(scanner.Bytes(), &event); err == nil {
+ p.Send(tui.EvalEventMsg(event))
+ }
+ }
+ p.Send(tui.EvalStreamClosedMsg{})
+ }()
+
+ final, err := p.Run()
+ if err != nil && !errors.Is(err, tea.ErrProgramKilled) {
+ fmt.Fprintf(os.Stderr, "phrocs: %v\n", err)
+ return 1
+ }
+ if view, ok := final.(tui.EvalModel); ok && view.HarnessLost() {
+ fmt.Fprintln(os.Stderr, "phrocs: the eval run stopped before it reported a result. Read its transcript for details.")
+ }
+ return 0
+}
+
+func parseFD(value string) (int, error) {
+ fd, err := strconv.Atoi(value)
+ if err != nil || fd < 3 {
+ return 0, fmt.Errorf("--fd must be a file descriptor number of 3 or more, got %q", value)
+ }
+ return fd, nil
+}
diff --git a/tools/phrocs/internal/tui/evals.go b/tools/phrocs/internal/tui/evals.go
new file mode 100644
index 000000000000..a52b72dab65c
--- /dev/null
+++ b/tools/phrocs/internal/tui/evals.go
@@ -0,0 +1,1438 @@
+package tui
+
+import (
+ "fmt"
+ "image/color"
+ "io"
+ "os"
+ "os/exec"
+ "strings"
+ "time"
+
+ "charm.land/bubbles/v2/help"
+ "charm.land/bubbles/v2/key"
+ "charm.land/bubbles/v2/spinner"
+ "charm.land/bubbles/v2/viewport"
+ tea "charm.land/bubbletea/v2"
+ "charm.land/lipgloss/v2"
+ "github.com/charmbracelet/x/ansi"
+)
+
+// EvalEvent is one progress update that the eval harness streams to `phrocs evals`.
+type EvalEvent struct {
+ Type string `json:"type"`
+ Description string `json:"description,omitempty"`
+ Transcript string `json:"transcript,omitempty"`
+ Phase string `json:"phase,omitempty"`
+ Stage string `json:"stage,omitempty"`
+ Name string `json:"name,omitempty"`
+ Total int `json:"total,omitempty"`
+ ID string `json:"id,omitempty"`
+ Experiment string `json:"experiment,omitempty"`
+ Index int `json:"index,omitempty"`
+ Started float64 `json:"started,omitempty"`
+ Ended float64 `json:"ended,omitempty"`
+ Detail string `json:"detail,omitempty"`
+ SummaryPath string `json:"summary_path,omitempty"`
+ LogPath string `json:"log_path,omitempty"`
+ Text string `json:"text,omitempty"`
+ ExitCode *int `json:"exit_code,omitempty"`
+}
+
+type EvalEventMsg EvalEvent
+
+// EvalStreamClosedMsg reports that the harness closed its end of the event stream.
+type EvalStreamClosedMsg struct{}
+
+type evalTickMsg struct{}
+
+type evalFileMsg struct {
+ path string
+ text string
+ size int64
+ modTime time.Time
+ changed bool
+}
+
+const (
+ evalTailBytes = 256 * 1024
+ evalMaxDiagnostics = 500
+ evalPollInterval = 250 * time.Millisecond
+)
+
+var evalDiagnosticPrefixes = []string{"WARNING:", "ERROR:", "error:", "CASE RETRY", "CASE ERROR", "CASE TIMEOUT", "SUITE CRASH"}
+
+type evalTrial struct {
+ id string
+ experiment string
+ name string
+ index int
+ phase string
+ started time.Time
+ ended time.Time
+ detail string
+ retries int
+ summaryPath string
+ logPath string
+}
+
+func (t *evalTrial) finished() bool {
+ switch t.phase {
+ case "done", "error", "timeout", "canceled":
+ return true
+ }
+ return false
+}
+
+// evalPoint is a cell in the soft-wrapped output: row counts wrapped rows from
+// the top of the content, and col counts cells from the left edge of the pane.
+type evalPoint struct{ row, col int }
+
+func (p evalPoint) before(o evalPoint) bool {
+ return p.row < o.row || (p.row == o.row && p.col < o.col)
+}
+
+type wrappedRow struct {
+ text string
+ // continued is true when the row is a soft-wrapped part of the row above.
+ continued bool
+}
+
+type evalRow struct {
+ header string
+ trial *evalTrial
+}
+
+func (r evalRow) selectable() bool { return r.header == "" }
+
+type evalKeyMap struct {
+ Up key.Binding
+ Down key.Binding
+ NextPane key.Binding
+ ScrollUp key.Binding
+ ScrollDown key.Binding
+ GotoTop key.Binding
+ GotoBottom key.Binding
+ Logs key.Binding
+ Search key.Binding
+ CopyMode key.Binding
+ Quit key.Binding
+ Interrupt key.Binding
+ Help key.Binding
+}
+
+func newEvalKeyMap() evalKeyMap {
+ return evalKeyMap{
+ Up: key.NewBinding(key.WithKeys("up", "k"), key.WithHelp("↑/k:", "prev")),
+ Down: key.NewBinding(key.WithKeys("down", "j"), key.WithHelp("↓/j:", "next")),
+ NextPane: key.NewBinding(key.WithKeys("tab", "shift+tab"), key.WithHelp("↹:", "focus")),
+ ScrollUp: key.NewBinding(key.WithKeys("pgup"), key.WithHelp("pgup:", "↥")),
+ ScrollDown: key.NewBinding(key.WithKeys("pgdown"), key.WithHelp("pgdn:", "↧")),
+ GotoTop: key.NewBinding(key.WithKeys("home", "g"), key.WithHelp("home:", "⤒")),
+ GotoBottom: key.NewBinding(key.WithKeys("end", "G"), key.WithHelp("end:", "⤓ follow")),
+ Logs: key.NewBinding(key.WithKeys("l"), key.WithHelp("l:", "logs")),
+ Search: key.NewBinding(key.WithKeys("/"), key.WithHelp("/:", "search")),
+ CopyMode: key.NewBinding(key.WithKeys("c"), key.WithHelp("c:", "select lines")),
+ Quit: key.NewBinding(key.WithKeys("q"), key.WithHelp("q:", "cancel run")),
+ Interrupt: key.NewBinding(key.WithKeys("ctrl+c")),
+ Help: key.NewBinding(key.WithKeys("?"), key.WithHelp("?:", "help")),
+ }
+}
+
+func (k evalKeyMap) ShortHelp() []key.Binding {
+ return []key.Binding{k.Up, k.Down, k.NextPane, k.Logs, k.Search, k.CopyMode, k.Quit, k.Help}
+}
+
+func (k evalKeyMap) FullHelp() [][]key.Binding {
+ return [][]key.Binding{
+ {k.Up, k.Down, k.NextPane},
+ {k.ScrollUp, k.ScrollDown, k.GotoTop, k.GotoBottom},
+ {k.Logs, k.Search, k.CopyMode},
+ {k.Quit, k.Help},
+ }
+}
+
+// EvalModel renders a live eval run in the same layout as the phrocs process view:
+// the sidebar lists the run overview and every trial, and the output pane shows the
+// selected item's summary or logs.
+type EvalModel struct {
+ notify func(string)
+ clipboard func(string)
+
+ description string
+ transcript string
+ stage string
+ setup []string
+ setupDone bool
+ experiments []string
+ totals map[string]int
+ trials map[string]*evalTrial
+ order map[string][]*evalTrial
+ diagnostics []string
+ summary string
+ started time.Time
+ stopped time.Time
+ exitCode *int
+
+ streamClosed bool
+ confirmCancel bool
+ cancelRequested bool
+ showLogs bool
+
+ rows []evalRow
+ cursor int
+ offset int
+ focus focusPane
+
+ viewport viewport.Model
+ atBottom bool
+ shownKey string
+ // content is the pane text before wrapping. continued marks the rows that
+ // wrapping split off the row above, so copies can rejoin them.
+ content string
+ continued []bool
+ wrapWidth int
+
+ filePath string
+ fileText string
+ fileSize int64
+ fileModTime time.Time
+ fileLoading bool
+
+ dragging bool
+ selected bool
+ selAnchor evalPoint
+ selCursor evalPoint
+
+ copyMode bool
+ copyAnchor int
+ copyCursor int
+ flash string
+
+ searchMode bool
+ query string
+ matches []int
+ matchCursor int
+
+ keys evalKeyMap
+ help help.Model
+ spinner spinner.Model
+ showHelp bool
+
+ width int
+ height int
+ ready bool
+ isDark bool
+ now func() time.Time
+}
+
+// NewEvalModel builds the eval view. notify receives "ready" after the first
+// layout and "cancel" when the user confirms that the run should stop.
+func NewEvalModel(notify func(string)) EvalModel {
+ h := help.New()
+ h.Styles = helpStyles()
+ m := EvalModel{
+ notify: notify,
+ clipboard: pbcopy,
+ stage: "Starting",
+ totals: map[string]int{},
+ trials: map[string]*evalTrial{},
+ order: map[string][]*evalTrial{},
+ started: time.Now(),
+ focus: focusServices,
+ atBottom: true,
+ isDark: true,
+ keys: newEvalKeyMap(),
+ help: h,
+ spinner: spinner.New(spinner.WithSpinner(spinner.MiniDot)),
+ now: time.Now,
+ }
+ m.rebuildRows()
+ return m
+}
+
+func (m EvalModel) Init() tea.Cmd {
+ return tea.Batch(tea.RequestBackgroundColor, m.spinner.Tick, evalTick())
+}
+
+func evalTick() tea.Cmd {
+ return tea.Tick(evalPollInterval, func(time.Time) tea.Msg { return evalTickMsg{} })
+}
+
+func (m EvalModel) send(command string) tea.Cmd {
+ notify := m.notify
+ return func() tea.Msg {
+ if notify != nil {
+ notify(command)
+ }
+ return nil
+ }
+}
+
+func (m EvalModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
+ var cmds []tea.Cmd
+ switch msg := msg.(type) {
+ case tea.WindowSizeMsg:
+ m.width, m.height = msg.Width, msg.Height
+ if !m.ready {
+ m.viewport = viewport.New()
+ m.viewport.FillHeight = true
+ m.viewport.HighlightStyle = searchMatchStyle
+ m.viewport.SelectedHighlightStyle = searchCurrentMatchStyle
+ m.ready = true
+ cmds = append(cmds, m.send("ready"))
+ }
+ m.applySize()
+ m.refreshContent()
+
+ case tea.BackgroundColorMsg:
+ m.isDark = msg.IsDark()
+
+ case spinner.TickMsg:
+ var cmd tea.Cmd
+ m.spinner, cmd = m.spinner.Update(msg)
+ cmds = append(cmds, cmd)
+
+ case evalTickMsg:
+ cmds = append(cmds, evalTick())
+ if cmd := m.pollFile(); cmd != nil {
+ cmds = append(cmds, cmd)
+ }
+
+ case evalFileMsg:
+ if msg.path == m.filePath {
+ m.fileLoading = false
+ if msg.changed {
+ m.fileText, m.fileSize, m.fileModTime = msg.text, msg.size, msg.modTime
+ m.refreshContent()
+ }
+ }
+
+ case EvalEventMsg:
+ m.applyEvent(EvalEvent(msg))
+
+ case EvalStreamClosedMsg:
+ m.streamClosed = true
+ m.confirmCancel = false
+ if m.stopped.IsZero() {
+ m.stopped = m.now()
+ }
+ // Without a finish event the harness process is gone and the shell has
+ // the terminal again, so the view must give it back now.
+ if m.exitCode == nil {
+ return m, tea.Quit
+ }
+ m.refreshContent()
+
+ case tea.KeyPressMsg:
+ return m.handleKey(msg, cmds)
+
+ case tea.MouseClickMsg:
+ m.handleClick(msg)
+
+ case tea.MouseMotionMsg:
+ if m.dragging {
+ top := headerHeight + 1
+ if msg.Y < top {
+ m.viewport.ScrollUp(1)
+ } else if msg.Y >= top+m.viewport.Height() {
+ m.viewport.ScrollDown(1)
+ }
+ m.selCursor = m.outputPoint(msg.X, msg.Y)
+ }
+
+ case tea.MouseReleaseMsg:
+ if m.dragging {
+ m.dragging = false
+ m.selCursor = m.outputPoint(msg.X, msg.Y)
+ m.selected = m.selCursor != m.selAnchor
+ if m.selected {
+ cmds = append(cmds, m.copySelection())
+ }
+ }
+
+ case tea.MouseWheelMsg:
+ if msg.X < m.sidebarWidth() {
+ switch msg.Button {
+ case tea.MouseWheelDown:
+ m.moveCursor(1)
+ case tea.MouseWheelUp:
+ m.moveCursor(-1)
+ }
+ } else {
+ var cmd tea.Cmd
+ m.viewport, cmd = m.viewport.Update(msg)
+ m.atBottom = m.viewport.AtBottom()
+ cmds = append(cmds, cmd)
+ }
+ }
+ return m, tea.Batch(cmds...)
+}
+
+func (m *EvalModel) applyEvent(ev EvalEvent) {
+ switch ev.Type {
+ case "run":
+ m.description = ev.Description
+ if ev.Transcript != "" {
+ m.transcript = ev.Transcript
+ }
+ case "setup":
+ m.setup = append(m.setup, ev.Phase)
+ m.stage = ev.Phase
+ case "setup_done":
+ m.setupDone = true
+ m.stage = "Running trials"
+ case "stage":
+ m.stage = ev.Stage
+ case "experiment":
+ if _, ok := m.totals[ev.Name]; !ok {
+ m.experiments = append(m.experiments, ev.Name)
+ }
+ m.totals[ev.Name] = ev.Total
+ m.rebuildRows()
+ case "trial":
+ t, ok := m.trials[ev.ID]
+ if !ok {
+ t = &evalTrial{id: ev.ID}
+ m.trials[ev.ID] = t
+ if _, known := m.totals[ev.Experiment]; !known {
+ m.experiments = append(m.experiments, ev.Experiment)
+ m.totals[ev.Experiment] = 0
+ }
+ m.order[ev.Experiment] = append(m.order[ev.Experiment], t)
+ defer m.rebuildRows()
+ }
+ t.experiment, t.name, t.index, t.phase, t.detail = ev.Experiment, ev.Name, ev.Index, ev.Phase, ev.Detail
+ t.summaryPath, t.logPath = ev.SummaryPath, ev.LogPath
+ t.started = unixTime(ev.Started)
+ t.ended = unixTime(ev.Ended)
+ case "retry":
+ if t, ok := m.trials[ev.ID]; ok {
+ t.retries++
+ t.detail = ev.Detail
+ }
+ case "message":
+ added := false
+ for _, line := range strings.Split(ev.Text, "\n") {
+ if hasAnyPrefix(line, evalDiagnosticPrefixes) {
+ m.diagnostics = append(m.diagnostics, line)
+ added = true
+ }
+ }
+ if over := len(m.diagnostics) - evalMaxDiagnostics; over > 0 {
+ m.diagnostics = m.diagnostics[over:]
+ }
+ // Other messages change nothing on screen, so skip the rebuild.
+ if !added || m.selectedTrial() != nil || m.showLogs {
+ return
+ }
+ case "finish":
+ code := 1
+ if ev.ExitCode != nil {
+ code = *ev.ExitCode
+ }
+ m.exitCode = &code
+ m.stopped = m.now()
+ m.summary = ev.Text
+ m.confirmCancel = false
+ if code == 0 {
+ m.stage = "Results ready. Press q to close."
+ } else {
+ m.stage = "Run stopped. Select Run for details. Press q to close."
+ }
+ }
+ m.refreshContent()
+}
+
+func unixTime(seconds float64) time.Time {
+ if seconds <= 0 {
+ return time.Time{}
+ }
+ return time.UnixMilli(int64(seconds * 1000))
+}
+
+func hasAnyPrefix(s string, prefixes []string) bool {
+ for _, p := range prefixes {
+ if strings.HasPrefix(s, p) {
+ return true
+ }
+ }
+ return false
+}
+
+func (m *EvalModel) rebuildRows() {
+ var selected *evalTrial
+ if m.cursor < len(m.rows) {
+ selected = m.rows[m.cursor].trial
+ }
+ rows := []evalRow{{}}
+ for _, name := range m.experiments {
+ trials := m.order[name]
+ if len(trials) == 0 {
+ continue
+ }
+ rows = append(rows, evalRow{header: name})
+ for _, t := range trials {
+ rows = append(rows, evalRow{trial: t})
+ }
+ }
+ m.rows = rows
+ m.cursor = 0
+ for i, r := range rows {
+ if r.trial != nil && r.trial == selected {
+ m.cursor = i
+ }
+ }
+ m.ensureCursorVisible()
+}
+
+func (m EvalModel) selectedTrial() *evalTrial {
+ if m.cursor < len(m.rows) {
+ return m.rows[m.cursor].trial
+ }
+ return nil
+}
+
+func (m EvalModel) finished() bool { return m.exitCode != nil || m.streamClosed }
+
+// HarnessLost reports that the harness closed the stream without a final result.
+func (m EvalModel) HarnessLost() bool { return m.streamClosed && m.exitCode == nil }
+
+func (m EvalModel) handleKey(msg tea.KeyPressMsg, cmds []tea.Cmd) (tea.Model, tea.Cmd) {
+ m.flash = ""
+ m.selected = false
+ // Ctrl-C must cancel from every mode, because the view ignores SIGINT and
+ // leaves cancellation to this key.
+ if key.Matches(msg, m.keys.Interrupt) {
+ if m.finished() {
+ return m, tea.Quit
+ }
+ m.confirmCancel = false
+ if !m.cancelRequested {
+ m.cancelRequested = true
+ cmds = append(cmds, m.send("cancel"))
+ }
+ return m, tea.Batch(cmds...)
+ }
+ if m.copyMode {
+ cmds = append(cmds, m.handleCopyKey(msg))
+ return m, tea.Batch(cmds...)
+ }
+ if m.searchMode {
+ m.handleSearchKey(msg)
+ return m, tea.Batch(cmds...)
+ }
+ if m.confirmCancel {
+ switch msg.String() {
+ case "y", "Y":
+ m.confirmCancel = false
+ m.cancelRequested = true
+ cmds = append(cmds, m.send("cancel"))
+ case "n", "N", "esc", "q":
+ m.confirmCancel = false
+ }
+ return m, tea.Batch(cmds...)
+ }
+
+ switch {
+ case key.Matches(msg, m.keys.Quit):
+ if m.finished() {
+ return m, tea.Quit
+ }
+ if !m.cancelRequested {
+ m.confirmCancel = true
+ }
+ case msg.String() == "esc":
+ if m.query != "" {
+ m.clearSearch()
+ }
+ case key.Matches(msg, m.keys.Up):
+ if m.focus == focusOutput {
+ m.viewport.ScrollUp(1)
+ m.atBottom = m.viewport.AtBottom()
+ } else {
+ m.moveCursor(-1)
+ }
+ case key.Matches(msg, m.keys.Down):
+ if m.focus == focusOutput {
+ m.viewport.ScrollDown(1)
+ m.atBottom = m.viewport.AtBottom()
+ } else {
+ m.moveCursor(1)
+ }
+ case msg.String() == "enter":
+ if m.focus == focusServices {
+ m.focus = focusOutput
+ } else if len(m.matches) > 0 {
+ m.matchCursor = (m.matchCursor + 1) % len(m.matches)
+ m.applySearch(true)
+ }
+ case key.Matches(msg, m.keys.NextPane):
+ if m.focus == focusServices {
+ m.focus = focusOutput
+ } else {
+ m.focus = focusServices
+ }
+ case key.Matches(msg, m.keys.ScrollUp):
+ m.viewport.PageUp()
+ m.atBottom = m.viewport.AtBottom()
+ case key.Matches(msg, m.keys.ScrollDown):
+ m.viewport.PageDown()
+ m.atBottom = m.viewport.AtBottom()
+ case key.Matches(msg, m.keys.GotoTop):
+ m.viewport.GotoTop()
+ m.atBottom = false
+ case key.Matches(msg, m.keys.GotoBottom):
+ m.viewport.GotoBottom()
+ m.atBottom = true
+ case key.Matches(msg, m.keys.Logs):
+ m.showLogs = !m.showLogs
+ m.refreshContent()
+ case key.Matches(msg, m.keys.CopyMode):
+ m.copyMode = true
+ m.copyAnchor = -1
+ m.copyCursor = m.firstVisibleLine()
+ m.applySize()
+ m.applyCopyStyle()
+ case key.Matches(msg, m.keys.Search):
+ m.searchMode = true
+ m.query = ""
+ m.applySearch(false)
+ case key.Matches(msg, m.keys.Help):
+ m.showHelp = !m.showHelp
+ m.applySize()
+ }
+ return m, tea.Batch(cmds...)
+}
+
+func (m *EvalModel) handleSearchKey(msg tea.KeyPressMsg) {
+ switch s := msg.String(); s {
+ case "esc":
+ m.searchMode = false
+ m.clearSearch()
+ case "enter":
+ m.searchMode = false
+ case "down":
+ if len(m.matches) > 0 {
+ m.matchCursor = (m.matchCursor + 1) % len(m.matches)
+ m.applySearch(true)
+ }
+ case "up":
+ if len(m.matches) > 0 {
+ m.matchCursor = (m.matchCursor - 1 + len(m.matches)) % len(m.matches)
+ m.applySearch(true)
+ }
+ case "backspace":
+ if runes := []rune(m.query); len(runes) > 0 {
+ m.query = string(runes[:len(runes)-1])
+ m.matchCursor = 0
+ m.applySearch(true)
+ }
+ default:
+ ch := msg.Text
+ if s == "space" {
+ ch = " "
+ }
+ if ch != "" {
+ m.query += ch
+ m.matchCursor = 0
+ m.applySearch(true)
+ }
+ }
+ m.applySize()
+}
+
+func (m *EvalModel) handleCopyKey(msg tea.KeyPressMsg) tea.Cmd {
+ last := len(m.contentLines()) - 1
+ switch {
+ case msg.String() == "esc", key.Matches(msg, m.keys.Quit):
+ m.exitCopyMode()
+ case key.Matches(msg, m.keys.CopyMode), msg.String() == "enter":
+ if m.copyAnchor < 0 {
+ m.copyAnchor = m.copyCursor
+ } else {
+ lo, hi := min(m.copyAnchor, m.copyCursor), max(m.copyAnchor, m.copyCursor)
+ m.exitCopyMode()
+ return m.copyLines(lo, hi)
+ }
+ case key.Matches(msg, m.keys.Down):
+ m.copyCursor = min(m.copyCursor+1, last)
+ case key.Matches(msg, m.keys.Up):
+ m.copyCursor = max(m.copyCursor-1, 0)
+ case key.Matches(msg, m.keys.ScrollDown):
+ m.copyCursor = min(m.copyCursor+m.viewport.Height(), last)
+ case key.Matches(msg, m.keys.ScrollUp):
+ m.copyCursor = max(m.copyCursor-m.viewport.Height(), 0)
+ case key.Matches(msg, m.keys.GotoTop):
+ m.copyCursor = 0
+ case key.Matches(msg, m.keys.GotoBottom):
+ m.copyCursor = last
+ default:
+ return nil
+ }
+ if m.copyMode {
+ m.applyCopyStyle()
+ m.ensureLineVisible(m.copyCursor)
+ }
+ return nil
+}
+
+func (m *EvalModel) exitCopyMode() {
+ m.copyMode = false
+ m.viewport.StyleLineFunc = nil
+ m.applySize()
+ m.refreshContent()
+}
+
+func (m *EvalModel) applyCopyStyle() {
+ cursor, anchor := m.copyCursor, m.copyAnchor
+ lo, hi := min(anchor, cursor), max(anchor, cursor)
+ selected := lipgloss.NewStyle().Background(selectionBg(m.isDark))
+ m.viewport.StyleLineFunc = func(i int) lipgloss.Style {
+ switch {
+ case i == cursor:
+ return copyModeStyle
+ case anchor >= 0 && i >= lo && i <= hi:
+ return selected
+ }
+ return lipgloss.NewStyle()
+ }
+}
+
+func (m EvalModel) contentLines() []string {
+ return strings.Split(m.viewport.GetContent(), "\n")
+}
+
+// copyLines puts plain text on the clipboard through OSC 52 and, on macOS,
+// through pbcopy, because Terminal.app ignores OSC 52.
+func (m *EvalModel) copyLines(lo, hi int) tea.Cmd {
+ lines := m.contentLines()
+ hi = min(hi, len(lines)-1)
+ if lo > hi {
+ return nil
+ }
+ var plain []string
+ for i, line := range lines[lo : hi+1] {
+ text := ansi.Strip(line)
+ if i > 0 && lo+i < len(m.continued) && m.continued[lo+i] {
+ plain[len(plain)-1] += text
+ continue
+ }
+ plain = append(plain, text)
+ }
+ return m.copyText(strings.Join(plain, "\n"), len(plain))
+}
+
+func (m *EvalModel) copyText(text string, lines int) tea.Cmd {
+ if strings.TrimSpace(text) == "" {
+ return nil
+ }
+ if lines == 1 {
+ m.flash = "Copied the selection to the clipboard"
+ } else {
+ m.flash = fmt.Sprintf("Copied %d lines to the clipboard", lines)
+ }
+ clipboard := m.clipboard
+ return tea.Batch(tea.SetClipboard(text), func() tea.Msg {
+ if clipboard != nil {
+ clipboard(text)
+ }
+ return nil
+ })
+}
+
+func pbcopy(text string) {
+ if path, err := exec.LookPath("pbcopy"); err == nil {
+ cmd := exec.Command(path)
+ cmd.Stdin = strings.NewReader(text)
+ _ = cmd.Run()
+ }
+}
+
+// setContent wraps the pane text once per change. The viewport's own soft wrap
+// rescans a line for every row it cuts, so one large log line made every frame
+// slow enough to block keys.
+func (m *EvalModel) setContent(content string) {
+ m.content = content
+ m.wrapWidth = max(m.viewport.Width(), 1)
+ var rows []string
+ m.continued = m.continued[:0]
+ for _, line := range strings.Split(content, "\n") {
+ for i, row := range strings.Split(ansi.Hardwrap(line, m.wrapWidth, true), "\n") {
+ rows = append(rows, row)
+ m.continued = append(m.continued, i > 0)
+ }
+ }
+ m.viewport.SetContentLines(rows)
+}
+
+func (m EvalModel) firstVisibleLine() int {
+ return m.viewport.YOffset()
+}
+
+func (m *EvalModel) ensureLineVisible(row int) {
+ if offset := m.viewport.YOffset(); row < offset {
+ m.viewport.SetYOffset(row)
+ } else if row >= offset+m.viewport.Height() {
+ m.viewport.SetYOffset(row - m.viewport.Height() + 1)
+ }
+ m.atBottom = m.viewport.AtBottom()
+}
+
+func (m EvalModel) outputPoint(x, y int) evalPoint {
+ row := min(max(y-headerHeight-1, 0), max(m.viewport.Height()-1, 0))
+ col := min(max(x-m.sidebarWidth()-1, 0), max(m.viewport.Width()-1, 0))
+ return evalPoint{row: m.viewport.YOffset() + row, col: col}
+}
+
+func (m EvalModel) wrappedRows() []wrappedRow {
+ lines := m.contentLines()
+ rows := make([]wrappedRow, len(lines))
+ for i, line := range lines {
+ rows[i] = wrappedRow{text: ansi.Strip(line), continued: i < len(m.continued) && m.continued[i]}
+ }
+ return rows
+}
+
+func (m EvalModel) selectionBounds() (evalPoint, evalPoint) {
+ if m.selCursor.before(m.selAnchor) {
+ return m.selCursor, m.selAnchor
+ }
+ return m.selAnchor, m.selCursor
+}
+
+func (m *EvalModel) copySelection() tea.Cmd {
+ lo, hi := m.selectionBounds()
+ rows := m.wrappedRows()
+ var b strings.Builder
+ for r := lo.row; r <= hi.row && r < len(rows); r++ {
+ start, end := 0, ansi.StringWidth(rows[r].text)
+ if r == lo.row {
+ start = lo.col
+ }
+ if r == hi.row {
+ end = min(end, hi.col+1)
+ }
+ if r > lo.row && !rows[r].continued {
+ b.WriteByte('\n')
+ }
+ if start < end {
+ b.WriteString(ansi.Cut(rows[r].text, start, end))
+ }
+ }
+ lines := strings.Split(b.String(), "\n")
+ for i := range lines {
+ lines[i] = strings.TrimRight(lines[i], " ")
+ }
+ return m.copyText(strings.Join(lines, "\n"), len(lines))
+}
+
+func (m *EvalModel) clearSearch() {
+ m.query = ""
+ m.matches = nil
+ m.matchCursor = 0
+ m.viewport.StyleLineFunc = nil
+}
+
+func (m *EvalModel) moveCursor(dir int) {
+ for i := m.cursor + dir; i >= 0 && i < len(m.rows); i += dir {
+ if m.rows[i].selectable() {
+ m.cursor = i
+ m.ensureCursorVisible()
+ m.refreshContent()
+ return
+ }
+ }
+}
+
+func (m *EvalModel) handleClick(msg tea.MouseClickMsg) {
+ if msg.Button != tea.MouseLeft {
+ return
+ }
+ m.selected = false
+ if msg.X >= m.sidebarWidth() {
+ m.focus = focusOutput
+ // Stop following so new output cannot scroll the text under the pointer.
+ m.atBottom = false
+ m.dragging = true
+ m.selAnchor = m.outputPoint(msg.X, msg.Y)
+ m.selCursor = m.selAnchor
+ return
+ }
+ m.focus = focusServices
+ row := m.offset + msg.Y - headerHeight - 1
+ if m.offset > 0 {
+ row--
+ }
+ if row >= 0 && row < len(m.rows) && m.rows[row].selectable() {
+ m.cursor = row
+ m.refreshContent()
+ }
+}
+
+func (m EvalModel) sidebarWidth() int {
+ return min(max(m.width*35/100, 28), 56)
+}
+
+func (m EvalModel) bodyHeight() int {
+ borders := 2
+ if m.copyMode {
+ borders = 0
+ }
+ return max(m.height-headerHeight-lipgloss.Height(m.renderFooter())-borders, 1)
+}
+
+func (m *EvalModel) applySize() {
+ if !m.ready {
+ return
+ }
+ if m.copyMode {
+ m.viewport.SetWidth(max(m.width, 1))
+ } else {
+ m.viewport.SetWidth(max(m.width-m.sidebarWidth()-2, 1))
+ }
+ m.viewport.SetHeight(m.bodyHeight())
+ if m.viewport.Width() != m.wrapWidth && m.content != "" {
+ m.setContent(m.content)
+ }
+ m.ensureCursorVisible()
+}
+
+func (m *EvalModel) ensureCursorVisible() {
+ h := m.bodyHeight()
+ if len(m.rows) <= h {
+ m.offset = 0
+ return
+ }
+ visible := max(h-2, 1)
+ if m.cursor < m.offset {
+ m.offset = m.cursor
+ }
+ if m.cursor >= m.offset+visible {
+ m.offset = m.cursor - visible + 1
+ }
+ m.offset = min(max(m.offset, 0), len(m.rows)-visible)
+}
+
+func (m EvalModel) currentFile() string {
+ if t := m.selectedTrial(); t != nil {
+ if m.showLogs {
+ return t.logPath
+ }
+ return t.summaryPath
+ }
+ if m.showLogs {
+ return m.transcript
+ }
+ return ""
+}
+
+func (m *EvalModel) pollFile() tea.Cmd {
+ path := m.currentFile()
+ if path == "" || m.fileLoading {
+ return nil
+ }
+ if path != m.filePath {
+ m.filePath, m.fileText, m.fileSize, m.fileModTime = path, "", -1, time.Time{}
+ }
+ m.fileLoading = true
+ size, modTime := m.fileSize, m.fileModTime
+ return func() tea.Msg { return readEvalFile(path, size, modTime) }
+}
+
+func readEvalFile(path string, lastSize int64, lastMod time.Time) evalFileMsg {
+ missing := evalFileMsg{path: path, size: -1, changed: lastSize != -1}
+ info, err := os.Stat(path)
+ if err != nil {
+ return missing
+ }
+ if info.Size() == lastSize && info.ModTime().Equal(lastMod) {
+ return evalFileMsg{path: path}
+ }
+ f, err := os.Open(path)
+ if err != nil {
+ return missing
+ }
+ defer func() { _ = f.Close() }()
+ start := max(info.Size()-evalTailBytes, 0)
+ if _, err := f.Seek(start, io.SeekStart); err != nil {
+ return missing
+ }
+ data, err := io.ReadAll(f)
+ if err != nil {
+ return missing
+ }
+ text := strings.ToValidUTF8(string(data), "�")
+ if start > 0 {
+ if i := strings.IndexByte(text, '\n'); i >= 0 {
+ text = text[i+1:]
+ }
+ text = "Showing recent output. Open the file for earlier lines.\n\n" + text
+ }
+ return evalFileMsg{path: path, text: strings.TrimRight(text, "\n"), size: info.Size(), modTime: info.ModTime(), changed: true}
+}
+
+// refreshContent rebuilds the output pane from the current state. It runs only
+// when an event, a file read, or a key changes what the pane shows.
+func (m *EvalModel) refreshContent() {
+ // Copy mode keeps the pane still, so new output cannot move the selection.
+ if !m.ready || m.copyMode {
+ return
+ }
+ selectedID := ""
+ if t := m.selectedTrial(); t != nil {
+ selectedID = t.id
+ }
+ shownKey := fmt.Sprintf("%s|%v", selectedID, m.showLogs)
+ switched := shownKey != m.shownKey
+ m.shownKey = shownKey
+ path := m.currentFile()
+ if path != m.filePath {
+ m.filePath, m.fileText, m.fileSize, m.fileModTime, m.fileLoading = path, "", -1, time.Time{}, false
+ }
+
+ var content string
+ if t := m.selectedTrial(); t != nil {
+ content = m.renderTrial(t)
+ } else if m.showLogs {
+ content = m.renderFile(m.transcript, "The run transcript is not available yet.")
+ } else {
+ content = m.renderOverview()
+ }
+ m.setContent(content)
+ if m.query != "" {
+ m.applySearch(false)
+ }
+ if switched {
+ m.selected = false
+ m.atBottom = m.showLogs
+ if m.atBottom {
+ m.viewport.GotoBottom()
+ } else {
+ m.viewport.GotoTop()
+ }
+ } else if m.atBottom {
+ m.viewport.GotoBottom()
+ }
+}
+
+func (m EvalModel) renderFile(path, missing string) string {
+ if path == "" {
+ return missing
+ }
+ text := m.fileText
+ if path != m.filePath || m.fileSize < 0 {
+ text = missing
+ }
+ return lipgloss.NewStyle().Foreground(colorBrightBlack).Render(path) + "\n\n" + text
+}
+
+var evalTitleStyle = lipgloss.NewStyle().Bold(true).Foreground(colorYellow)
+
+func (m EvalModel) renderOverview() string {
+ var b strings.Builder
+ if m.description != "" {
+ b.WriteString(m.description + "\n")
+ }
+ b.WriteString(m.stage + "\n\n")
+
+ b.WriteString(evalTitleStyle.Render("Setup") + "\n")
+ for i, phase := range m.setup {
+ done := m.setupDone || i < len(m.setup)-1
+ icon, c := iconCharRunning, colorGreen
+ if done {
+ icon, c = iconCharDone, nil
+ } else if m.finished() {
+ icon, c = iconCharCrashed, colorRed
+ }
+ b.WriteString(" " + lipgloss.NewStyle().Foreground(c).Render(icon) + " " + phase + "\n")
+ }
+
+ b.WriteString("\n" + evalTitleStyle.Render("Trials") + "\n")
+ counts := map[string]int{}
+ for _, t := range m.trials {
+ counts[t.phase]++
+ }
+ var parts []string
+ for _, phase := range []string{"queued", "setup", "agent", "cleanup", "logs", "scoring", "done", "error", "timeout", "canceled"} {
+ if counts[phase] > 0 {
+ parts = append(parts, fmt.Sprintf("%s %d", phase, counts[phase]))
+ }
+ }
+ if len(parts) == 0 {
+ parts = append(parts, "No trials have started yet.")
+ }
+ b.WriteString(" " + strings.Join(parts, " · ") + "\n")
+ for _, name := range m.experiments {
+ finished := 0
+ for _, t := range m.order[name] {
+ if t.finished() {
+ finished++
+ }
+ }
+ fmt.Fprintf(&b, " %s %d/%d\n", name, finished, m.totals[name])
+ }
+
+ if len(m.diagnostics) > 0 {
+ b.WriteString("\n" + evalTitleStyle.Render("Warnings and errors") + "\n")
+ b.WriteString(strings.Join(m.diagnostics, "\n") + "\n")
+ }
+ if m.summary != "" {
+ b.WriteString("\n" + strings.TrimRight(m.summary, "\n") + "\n")
+ }
+ if m.transcript != "" {
+ b.WriteString("\n" + lipgloss.NewStyle().Foreground(colorBrightBlack).Render("Transcript: "+m.transcript) + "\n")
+ }
+ return strings.TrimRight(b.String(), "\n")
+}
+
+func (m EvalModel) renderTrial(t *evalTrial) string {
+ var b strings.Builder
+ b.WriteString(evalTitleStyle.Render(fmt.Sprintf("%s :: %s [trial %d]", t.experiment, t.name, t.index+1)) + "\n")
+ fmt.Fprintf(&b, "Phase: %s | Setup retries: %d\n", t.phase, t.retries)
+ failed := t.phase == "error" || t.phase == "timeout"
+ if t.detail != "" && failed {
+ b.WriteString("\n" + lipgloss.NewStyle().Bold(true).Foreground(colorRed).Render("Error") + "\n")
+ b.WriteString(t.detail + "\n")
+ } else if t.detail != "" {
+ b.WriteString(t.detail + "\n")
+ }
+ b.WriteString("\n")
+ missing := "The summary appears when the trial finishes. Press l for the agent log."
+ if failed {
+ missing = "No summary for this trial. Select Run and press l for the full transcript."
+ }
+ if m.showLogs {
+ missing = "The agent log appears when the trial finishes. Select Run and press l for live logs."
+ }
+ path := t.summaryPath
+ if m.showLogs {
+ path = t.logPath
+ }
+ b.WriteString(m.renderFile(path, missing))
+ return b.String()
+}
+
+func (m *EvalModel) applySearch(jump bool) {
+ if m.query == "" {
+ m.matches = nil
+ m.viewport.StyleLineFunc = nil
+ return
+ }
+ tokens := parseMatchTokens(m.query)
+ lines := strings.Split(m.viewport.GetContent(), "\n")
+ m.matches = m.matches[:0]
+ for i, line := range lines {
+ if lineMatchesTokens(line, tokens) {
+ m.matches = append(m.matches, i)
+ }
+ }
+ if len(m.matches) == 0 {
+ m.matchCursor = 0
+ m.viewport.StyleLineFunc = nil
+ return
+ }
+ m.matchCursor = min(m.matchCursor, len(m.matches)-1)
+ matchSet := make(map[int]bool, len(m.matches))
+ for _, i := range m.matches {
+ matchSet[i] = true
+ }
+ current := m.matches[m.matchCursor]
+ m.viewport.StyleLineFunc = func(i int) lipgloss.Style {
+ if i == current {
+ return searchCurrentMatchStyle
+ }
+ if matchSet[i] {
+ return searchMatchStyle
+ }
+ return lipgloss.NewStyle()
+ }
+ if jump {
+ m.viewport.SetYOffset(max(current-m.viewport.Height()/2, 0))
+ m.atBottom = m.viewport.AtBottom()
+ }
+}
+
+func (m EvalModel) View() tea.View {
+ if !m.ready {
+ v := tea.NewView("\n Initialising...\n")
+ v.AltScreen = true
+ return v
+ }
+ v := tea.NewView("")
+ v.AltScreen = true
+ if m.copyMode {
+ // Without mouse capture, the terminal's own drag selection works too.
+ v.SetContent(lipgloss.JoinVertical(lipgloss.Left, m.renderHeader(), m.viewport.View(), m.renderFooter()))
+ v.MouseMode = tea.MouseModeNone
+ return v
+ }
+ body := lipgloss.JoinHorizontal(lipgloss.Top, m.renderSidebar(), m.renderOutput())
+ v.SetContent(lipgloss.JoinVertical(lipgloss.Left, m.renderHeader(), body, m.renderFooter()))
+ v.MouseMode = tea.MouseModeCellMotion
+ return v
+}
+
+func (m EvalModel) counts() (finished, running, failed, total int) {
+ for _, t := range m.trials {
+ switch {
+ case t.phase == "error" || t.phase == "timeout":
+ failed++
+ finished++
+ case t.finished():
+ finished++
+ case t.phase != "queued":
+ running++
+ }
+ }
+ for _, n := range m.totals {
+ total += n
+ }
+ return
+}
+
+func (m EvalModel) runStatus() string {
+ switch {
+ case m.exitCode == nil && m.streamClosed:
+ return "stopped"
+ case m.exitCode == nil && m.cancelRequested:
+ return "canceling"
+ case m.exitCode == nil:
+ return "running"
+ case *m.exitCode == 0:
+ return "PASS"
+ case *m.exitCode == 130:
+ return "interrupted"
+ default:
+ return "FAIL"
+ }
+}
+
+// clock stops at the end of the run, so unfinished trials stop counting too.
+func (m EvalModel) clock() time.Time {
+ if !m.stopped.IsZero() {
+ return m.stopped
+ }
+ return m.now()
+}
+
+func (m EvalModel) runElapsed() time.Duration {
+ return m.clock().Sub(m.started)
+}
+
+func (m EvalModel) renderHeader() string {
+ brand := headerBrandStyle.Render("evals")
+ finished, running, failed, total := m.counts()
+ meta := []string{m.runStatus(), fmt.Sprintf("%d/%d finished", finished, total)}
+ if running > 0 {
+ meta = append(meta, fmt.Sprintf("%d running", running))
+ }
+ if failed > 0 {
+ meta = append(meta, fmt.Sprintf("%d failed", failed))
+ }
+ meta = append(meta, formatDuration(m.runElapsed()))
+ right := headerMetaStyle.Render(strings.Join(meta, " • "))
+ spacerW := max(m.width-lipgloss.Width(stripesStyle)-lipgloss.Width(brand)-lipgloss.Width(right), 0)
+ return lipgloss.JoinHorizontal(lipgloss.Top, stripesStyle, brand, strings.Repeat(" ", spacerW), right)
+}
+
+func (m EvalModel) trialIcon(t *evalTrial) (string, color.Color) {
+ switch t.phase {
+ case "queued":
+ return ansi.Strip(m.spinner.View()), colorYellow
+ case "done":
+ return iconCharDone, nil
+ case "error", "timeout":
+ return iconCharCrashed, colorRed
+ case "canceled":
+ return iconCharStopped, nil
+ default:
+ return iconCharRunning, colorGreen
+ }
+}
+
+func (m EvalModel) renderSidebar() string {
+ h := m.bodyHeight()
+ innerW := m.sidebarWidth() - 2
+ now := m.clock()
+
+ canUp := m.offset > 0
+ visible := h
+ if len(m.rows) > h {
+ visible = max(h-2, 1)
+ }
+ end := min(len(m.rows), m.offset+visible)
+ canDown := end < len(m.rows)
+
+ var rows []string
+ if len(m.rows) > h {
+ arrow := ""
+ if canUp {
+ arrow = "▲"
+ }
+ rows = append(rows, scrollArrowStyle.Width(innerW).Render(arrow))
+ }
+ for i := m.offset; i < end; i++ {
+ r := m.rows[i]
+ if r.header != "" {
+ rows = append(rows, groupHeaderStyle.Width(innerW).Render(truncate(r.header, innerW-1)))
+ continue
+ }
+ var icon, label, suffix string
+ var iconColor color.Color
+ if r.trial == nil {
+ icon, iconColor, label = m.runIcon(), m.runIconColor(), "Run"
+ suffix = formatDuration(m.runElapsed())
+ } else {
+ t := r.trial
+ icon, iconColor = m.trialIcon(t)
+ label = t.name
+ if m.multiTrial(t.experiment) {
+ label = fmt.Sprintf("%s #%d", t.name, t.index+1)
+ }
+ end := t.ended
+ if end.IsZero() {
+ end = now
+ }
+ if !t.started.IsZero() {
+ suffix = formatDuration(end.Sub(t.started))
+ }
+ }
+ nameW := max(innerW-3, 0)
+ label = truncate(label, max(nameW-len(suffix)-1, 1))
+ gap := max(nameW-lipgloss.Width(label)-len(suffix), 1)
+ row := sidebarRow{
+ icon: icon,
+ name: label + strings.Repeat(" ", gap) + suffix,
+ iconColor: iconColor,
+ selected: i == m.cursor,
+ innerW: innerW,
+ isDark: m.isDark,
+ }
+ rows = append(rows, renderSidebarRow(row))
+ }
+ if len(m.rows) > h {
+ arrow := ""
+ if canDown {
+ arrow = "▼"
+ }
+ rows = append(rows, scrollArrowStyle.Width(innerW).Render(arrow))
+ }
+ for len(rows) < h {
+ rows = append(rows, procInactiveStyle.Width(innerW).Render(""))
+ }
+ return borderFor(m.isDark, m.focus == focusServices).Render(strings.Join(rows, "\n"))
+}
+
+func (m EvalModel) multiTrial(experiment string) bool {
+ for _, t := range m.order[experiment] {
+ if t.index > 0 {
+ return true
+ }
+ }
+ return false
+}
+
+func (m EvalModel) runIcon() string {
+ switch m.runStatus() {
+ case "running", "canceling":
+ return iconCharRunning
+ case "PASS":
+ return iconCharDone
+ case "interrupted":
+ return iconCharStopped
+ default:
+ return iconCharCrashed
+ }
+}
+
+func (m EvalModel) runIconColor() color.Color {
+ switch m.runStatus() {
+ case "running":
+ return colorGreen
+ case "canceling":
+ return colorYellow
+ case "PASS", "interrupted":
+ return nil
+ default:
+ return colorRed
+ }
+}
+
+func (m EvalModel) renderOutput() string {
+ lines := strings.Split(m.viewport.View(), "\n")
+ if m.dragging || m.selected {
+ lo, hi := m.selectionBounds()
+ for i, line := range lines {
+ row := m.viewport.YOffset() + i
+ if row < lo.row || row > hi.row {
+ continue
+ }
+ start, end := 0, m.viewport.Width()
+ if row == lo.row {
+ start = lo.col
+ }
+ if row == hi.row {
+ end = hi.col + 1
+ }
+ w := ansi.StringWidth(line)
+ lines[i] = ansi.Cut(line, 0, start) + copyModeStyle.Render(ansi.Strip(ansi.Cut(line, start, end))) + ansi.Cut(line, end, w)
+ }
+ }
+ if !m.viewport.AtBottom() && len(lines) > 0 {
+ indicator := scrollIndicatorStyle.Render("end: follow")
+ if w, iw := lipgloss.Width(lines[0]), lipgloss.Width(indicator); w >= iw {
+ lines[0] = ansi.Truncate(lines[0], w-iw, "") + indicator
+ }
+ }
+ return borderFor(m.isDark, m.focus == focusOutput).Render(strings.Join(lines, "\n"))
+}
+
+func (m EvalModel) renderFooter() string {
+ w := max(m.width-2, 1)
+ prompt := func(c color.Color, text string) string {
+ return footerStyle.Width(w).Render(lipgloss.NewStyle().Foreground(c).Render(text))
+ }
+ switch {
+ case m.copyMode && m.copyAnchor < 0:
+ return prompt(colorBlue, fmt.Sprintf("-- COPY MODE -- line %d ↑/↓: move c: mark start esc: cancel (mouse drag also selects)", m.copyCursor+1))
+ case m.copyMode:
+ lo, hi := min(m.copyAnchor, m.copyCursor)+1, max(m.copyAnchor, m.copyCursor)+1
+ return prompt(colorBlue, fmt.Sprintf("-- COPY MODE -- lines %d–%d ↑/↓: extend c: copy esc: cancel", lo, hi))
+ case m.flash != "":
+ return prompt(colorGreen, m.flash)
+ case m.searchMode:
+ info := ""
+ if m.query != "" {
+ if len(m.matches) == 0 {
+ info = " [no matches]"
+ } else {
+ info = fmt.Sprintf(" [%d/%d]", m.matchCursor+1, len(m.matches))
+ }
+ }
+ return prompt(colorYellow, fmt.Sprintf("/ %s▌%s ↑/↓: prev/next ↵: done esc: clear", m.query, info))
+ case m.confirmCancel:
+ return prompt(colorYellow, "Cancel this run and clean up? y: yes n: continue")
+ case m.cancelRequested && !m.finished():
+ return prompt(colorYellow, "Cancel requested. Waiting for cleanup.")
+ }
+ keys := m.keys
+ if m.finished() {
+ keys.Quit.SetHelp("q:", "close")
+ }
+ if m.showLogs {
+ keys.Logs.SetHelp("l:", "summary")
+ }
+ var content string
+ if m.showHelp {
+ content = m.help.FullHelpView(keys.FullHelp())
+ } else {
+ content = m.help.ShortHelpView(keys.ShortHelp())
+ }
+ if m.query != "" {
+ content = lipgloss.NewStyle().Foreground(colorYellow).Render(
+ fmt.Sprintf("search: %q [%d matches] ↵: next esc: clear", m.query, len(m.matches)),
+ ) + "\n" + content
+ }
+ return footerStyle.Width(w).Render(content)
+}
diff --git a/tools/phrocs/internal/tui/evals_test.go b/tools/phrocs/internal/tui/evals_test.go
new file mode 100644
index 000000000000..aaa789319572
--- /dev/null
+++ b/tools/phrocs/internal/tui/evals_test.go
@@ -0,0 +1,100 @@
+package tui
+
+import (
+ "strings"
+ "testing"
+
+ tea "charm.land/bubbletea/v2"
+)
+
+type evalHarness struct {
+ t *testing.T
+ m EvalModel
+ replies []string
+ quit bool
+}
+
+func newEvalHarness(t *testing.T) *evalHarness {
+ t.Helper()
+ h := &evalHarness{t: t}
+ h.m = NewEvalModel(func(reply string) { h.replies = append(h.replies, reply) })
+ h.update(tea.WindowSizeMsg{Width: 120, Height: 30})
+ h.replies = nil
+ return h
+}
+
+// run executes the commands a key or event produced. Key and event handlers
+// only return reply and quit commands, so no timer command blocks here.
+func (h *evalHarness) run(cmd tea.Cmd) {
+ if cmd == nil {
+ return
+ }
+ switch msg := cmd().(type) {
+ case tea.BatchMsg:
+ for _, c := range msg {
+ h.run(c)
+ }
+ case tea.QuitMsg:
+ h.quit = true
+ }
+}
+
+func (h *evalHarness) update(msg tea.Msg) {
+ next, cmd := h.m.Update(msg)
+ h.m = next.(EvalModel)
+ h.run(cmd)
+}
+
+func (h *evalHarness) keys(keys ...tea.KeyPressMsg) {
+ for _, k := range keys {
+ h.update(k)
+ }
+}
+
+func (h *evalHarness) event(ev EvalEvent) { h.update(EvalEventMsg(ev)) }
+
+var ctrlC = tea.KeyPressMsg{Code: 'c', Mod: tea.ModCtrl}
+
+func TestEvalCancelAndClose(t *testing.T) {
+ exitCode := 0
+ tests := []struct {
+ name string
+ finished bool
+ keys []tea.KeyPressMsg
+ wantReplies []string
+ wantQuit bool
+ }{
+ {name: "q asks before it cancels", keys: []tea.KeyPressMsg{keypress('q')}},
+ {name: "q then n keeps the run", keys: []tea.KeyPressMsg{keypress('q'), keypress('n'), keypress('y')}},
+ {name: "q then y cancels", keys: []tea.KeyPressMsg{keypress('q'), keypress('y')}, wantReplies: []string{"cancel"}},
+ {name: "ctrl+c cancels once", keys: []tea.KeyPressMsg{ctrlC, ctrlC, keypress('q'), keypress('y')}, wantReplies: []string{"cancel"}},
+ {name: "ctrl+c cancels while searching", keys: []tea.KeyPressMsg{keypress('/'), ctrlC}, wantReplies: []string{"cancel"}},
+ {name: "ctrl+c cancels at the confirmation", keys: []tea.KeyPressMsg{keypress('q'), ctrlC}, wantReplies: []string{"cancel"}},
+ {name: "q closes a finished run", finished: true, keys: []tea.KeyPressMsg{keypress('q')}, wantQuit: true},
+ {name: "ctrl+c closes a finished run", finished: true, keys: []tea.KeyPressMsg{ctrlC}, wantQuit: true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ h := newEvalHarness(t)
+ if tt.finished {
+ h.event(EvalEvent{Type: "finish", ExitCode: &exitCode})
+ }
+ h.keys(tt.keys...)
+ if strings.Join(h.replies, ",") != strings.Join(tt.wantReplies, ",") {
+ t.Fatalf("replies = %v, want %v", h.replies, tt.wantReplies)
+ }
+ if h.quit != tt.wantQuit {
+ t.Fatalf("quit = %v, want %v", h.quit, tt.wantQuit)
+ }
+ })
+ }
+}
+
+func TestEvalStreamCloseWithoutResultReleasesTheTerminal(t *testing.T) {
+ h := newEvalHarness(t)
+ h.keys(keypress('q'))
+ h.update(EvalStreamClosedMsg{})
+ if !h.quit || len(h.replies) != 0 || !h.m.HarnessLost() {
+ t.Fatalf("quit = %v, replies = %v, lost = %v; want an immediate quit without cancel", h.quit, h.replies, h.m.HarnessLost())
+ }
+}
diff --git a/tools/phrocs/main.go b/tools/phrocs/main.go
index dfca5589381b..1ce55558a266 100644
--- a/tools/phrocs/main.go
+++ b/tools/phrocs/main.go
@@ -11,6 +11,7 @@
// phrocs wait [--timeout N] [--json] # block on readiness
// phrocs stop [--timeout N] # stop detached process via IPC
// phrocs attach # polling TUI against a detached process
+// phrocs evals --fd N # live view of an eval harness run
// phrocs --version
//
// Flags:
@@ -56,6 +57,7 @@ type parsedArgs struct {
detach bool
timeout int
asJSON bool
+ fd int
}
func printUsage() {
@@ -67,6 +69,7 @@ Usage:
phrocs wait [--timeout N] [--json] block until ready, crashed, or timeout
phrocs stop [--timeout N] stop the detached process gracefully
phrocs attach polling status client against a detached process
+ phrocs evals --fd N live view of an eval harness run (started by hogli evals)
phrocs --version`)
}
@@ -76,7 +79,7 @@ func parseArgs(args []string) (parsedArgs, error) {
// First pass: if the first arg is a known subcommand, consume it.
if len(args) > 0 {
switch args[0] {
- case "wait", "stop", "attach", "detach":
+ case "wait", "stop", "attach", "detach", "evals":
pa.subcommand = args[0]
i = 1
}
@@ -111,6 +114,16 @@ func parseArgs(args []string) (parsedArgs, error) {
i++
case "--json":
pa.asJSON = true
+ case "--fd":
+ if i+1 >= len(args) {
+ return pa, fmt.Errorf("--fd requires a value")
+ }
+ fd, err := parseFD(args[i+1])
+ if err != nil {
+ return pa, err
+ }
+ pa.fd = fd
+ i++
default:
return pa, fmt.Errorf("unknown flag: %s", args[i])
}
@@ -132,6 +145,12 @@ func main() {
os.Exit(runStop(pa.timeout))
case "attach":
os.Exit(runAttach())
+ case "evals":
+ if pa.fd == 0 {
+ fmt.Fprintln(os.Stderr, "phrocs: evals requires --fd")
+ os.Exit(2)
+ }
+ os.Exit(runEvals(pa.fd))
case "detach":
// `phrocs detach` is an alias for `phrocs -d`
pa.detach = true
diff --git a/uv.lock b/uv.lock
index de51bed642c9..20ca40785e93 100644
--- a/uv.lock
+++ b/uv.lock
@@ -6040,6 +6040,7 @@ dev = [
{ name = "packaging" },
{ name = "parameterized" },
{ name = "prance" },
+ { name = "prompt-toolkit" },
{ name = "pyarrow" },
{ name = "pyarrow-stubs" },
{ name = "pyinstrument" },
@@ -6337,6 +6338,7 @@ dev = [
{ name = "packaging", specifier = "==25.0" },
{ name = "parameterized", specifier = "==0.9.0" },
{ name = "prance", specifier = "==23.6.21.0" },
+ { name = "prompt-toolkit", specifier = "~=3.0.51" },
{ name = "pyarrow", specifier = "==23.0.1" },
{ name = "pyarrow-stubs", specifier = "==20.0.0.20260625" },
{ name = "pyinstrument", specifier = "~=5.1" },