Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)
Python
Add full agent-run logging with SQLite index and /evals/agent-runs viewer
Abi Rajac4f1a9e37291
diff --git a/backend/agent/engine.py b/backend/agent/engine.pyindex 9ce6e986..dbcd8be9 100644--- a/backend/agent/engine.py+++ b/backend/agent/engine.py@@ -1,4 +1,5 @@import asyncio+import tracebackimport uuidfrom typing import Any, Awaitable, Callable, Dict, List, Optional, cast@@ -17,6 +18,7 @@ from agent.tools import (summarize_text,summarize_tool_input,)+from fs_logging.agent_runs import AgentRunRecorderclass AgentEngine:@@ -37,9 +39,11 @@ class AgentEngine:asset_base_url: str = "",initial_file_state: Optional[Dict[str, str]] = None,option_codes: Optional[List[str]] = None,+ recorder: Optional[AgentRunRecorder] = None,):self.send_message = send_messageself.variant_index = variant_index+ self.recorder = recorderself.openai_api_key = openai_api_keyself.openai_base_url = openai_base_urlself.anthropic_api_key = anthropic_api_key@@ -133,6 +137,8 @@ class AgentEngine:await self._send("setCode", content)self._mark_preview_length(tool_event_id, total_len)+ if self.recorder is not None:+ self.recorder.record_set_code(total_len, "stream_preview")async def _handle_streamed_tool_delta(self,@@ -192,6 +198,15 @@ class AgentEngine:streamed_lengths: Dict[str, int] = {}async def on_event(event: StreamEvent) -> None:+ if self.recorder is not None:+ if event.type == "assistant_delta":+ stream_event_id = assistant_event_id+ elif event.type == "thinking_delta":+ stream_event_id = thinking_event_id+ else:+ stream_event_id = event.tool_call_id+ self.recorder.record_stream_event(event, stream_event_id)+if event.type == "assistant_delta":if event.text:await self._send(@@ -240,9 +255,21 @@ class AgentEngine:if content:await self._stream_code_preview(tool_event_id, content)+ # Timing starts here, after the cosmetic preview stream, so+ # tool durations measure execution only.+ if self.recorder is not None:+ self.recorder.record_tool_start(tool_event_id, tool_call)tool_result = await self.tool_runtime.execute(tool_call)+ if self.recorder is not None:+ self.recorder.record_tool_end(+ tool_event_id, tool_call, tool_result+ )if tool_result.updated_content:await self._send("setCode", tool_result.updated_content)+ if self.recorder is not None:+ self.recorder.record_set_code(+ len(tool_result.updated_content), "tool_result"+ )await self._send("toolResult",@@ -265,6 +292,9 @@ class AgentEngine:self.tool_runtime.input_images = self._extract_input_images(prompt_messages)seed_file_state_from_messages(self.file_state, prompt_messages)+ if self.recorder is not None:+ self.recorder.record_run_start(model, prompt_messages)+session = create_provider_session(model=model,prompt_messages=prompt_messages,@@ -281,9 +311,24 @@ class AgentEngine:should_extract_assets=(self.should_extract_assets and bool(self.tool_runtime.input_images)),+ recorder=self.recorder,)try:- return await self._run_with_session(session)+ result = await self._run_with_session(session)+ if self.recorder is not None:+ await self.recorder.record_run_end("completed", final_html=result)+ return result+ # BaseException so cancellation (client disconnect) still finalizes+ # the run record instead of leaving it stuck at "running".+ except BaseException as exc:+ if self.recorder is not None:+ await self.recorder.record_run_end(+ "failed",+ error="".join(+ traceback.format_exception_only(type(exc), exc)+ ).strip(),+ )+ raisefinally:await session.close()@@ -295,5 +340,7 @@ class AgentEngine:if html:self.file_state.content = htmlawait self._send("setCode", html)+ if self.recorder is not None:+ self.recorder.record_set_code(len(html), "finalize")return self.file_state.contentdiff --git a/backend/agent/providers/anthropic/provider.py b/backend/agent/providers/anthropic/provider.pyindex 968e956d..7b5f0f31 100644--- a/backend/agent/providers/anthropic/provider.py+++ b/backend/agent/providers/anthropic/provider.py@@ -4,7 +4,7 @@ import copyimport jsonimport uuidfrom dataclasses import dataclass, field-from typing import Any, Dict, List, cast+from typing import Any, Dict, List, Optional, castfrom anthropic import AsyncAnthropicfrom openai.types.chat import ChatCompletionMessageParam@@ -25,6 +25,7 @@ from agent.providers.anthropic.image import (from agent.providers.pricing import MODEL_PRICINGfrom agent.providers.token_usage import TokenUsagefrom agent.tools import CanonicalToolDefinition, ToolCall, parse_json_arguments+from fs_logging.agent_runs import AgentRunRecorderfrom fs_logging.prompt_reports import PromptReportLoggerfrom llm import Llm@@ -314,11 +315,13 @@ class AnthropicProviderSession(ProviderSession):model: Llm,prompt_messages: List[ChatCompletionMessageParam],tools: List[Dict[str, Any]],+ recorder: Optional[AgentRunRecorder] = None,):self._client = clientself._model = modelself._tools = toolsself._total_usage = TokenUsage()+ self._recorder = recorderself._prompt_report_logger = PromptReportLogger(provider="anthropic",model=model,@@ -368,6 +371,10 @@ class AnthropicProviderSession(ProviderSession):stream_kwargs["temperature"] = 0.0self._prompt_report_logger.record_request(stream_kwargs)+ if self._recorder is not None:+ self._recorder.record_llm_request(+ "anthropic", _get_anthropic_api_model_name(self._model), stream_kwargs+ )state = AnthropicParseState()async with self._client.messages.stream(**stream_kwargs) as stream:@@ -380,6 +387,10 @@ class AnthropicProviderSession(ProviderSession):self._total_usage.accumulate(turn_usage)tool_calls = _extract_tool_calls(final_message)+ if self._recorder is not None:+ self._recorder.record_llm_response(+ state.assistant_text, tool_calls, turn_usage+ )return ProviderTurn(assistant_text=state.assistant_text,tool_calls=tool_calls,diff --git a/backend/agent/providers/factory.py b/backend/agent/providers/factory.pyindex 64ee882c..eca55690 100644--- a/backend/agent/providers/factory.py+++ b/backend/agent/providers/factory.py@@ -11,6 +11,7 @@ from agent.providers.gemini import GeminiProviderSession, serialize_gemini_toolsfrom agent.providers.openai import OpenAIProviderSession, serialize_openai_toolsfrom agent.tools import canonical_tool_definitionsfrom config import REPLICATE_API_KEY+from fs_logging.agent_runs import AgentRunRecorderfrom llm import ANTHROPIC_MODELS, GEMINI_MODELS, OPENAI_MODELS, Llmfrom preview_screenshot import is_screenshot_preview_available@@ -25,6 +26,7 @@ def create_provider_session(gemini_api_key: Optional[str],replicate_api_key: Optional[str],should_extract_assets: bool = True,+ recorder: Optional[AgentRunRecorder] = None,) -> ProviderSession:canonical_tools = canonical_tool_definitions(image_generation_enabled=should_generate_images,@@ -46,6 +48,7 @@ def create_provider_session(model=model,prompt_messages=prompt_messages,tools=serialize_openai_tools(canonical_tools),+ recorder=recorder,)if model in ANTHROPIC_MODELS:@@ -58,6 +61,7 @@ def create_provider_session(model=model,prompt_messages=prompt_messages,tools=serialize_anthropic_tools(canonical_tools),+ recorder=recorder,)if model in GEMINI_MODELS:@@ -70,6 +74,7 @@ def create_provider_session(model=model,prompt_messages=prompt_messages,tools=serialize_gemini_tools(canonical_tools),+ recorder=recorder,)raise ValueError(f"Unsupported model: {model.value}")diff --git a/backend/agent/providers/gemini.py b/backend/agent/providers/gemini.pyindex 9807d554..60a53593 100644--- a/backend/agent/providers/gemini.py+++ b/backend/agent/providers/gemini.py@@ -5,7 +5,7 @@ import uuidimport httpxfrom dataclasses import dataclass, field-from typing import Any, Dict, List, cast+from typing import Any, Dict, List, Optional, castfrom google import genaifrom google.genai import types@@ -21,6 +21,7 @@ from agent.providers.base import (from agent.providers.pricing import MODEL_PRICINGfrom agent.providers.token_usage import TokenUsagefrom agent.tools import CanonicalToolDefinition, ToolCall+from fs_logging.agent_runs import AgentRunRecorderfrom fs_logging.prompt_reports import PromptReportLoggerfrom llm import Llm@@ -281,11 +282,13 @@ class GeminiProviderSession(ProviderSession):model: Llm,prompt_messages: List[ChatCompletionMessageParam],tools: List[types.Tool],+ recorder: Optional[AgentRunRecorder] = None,):self._client = clientself._model = modelself._tools = toolsself._total_usage = TokenUsage()+ self._recorder = recorderself._prompt_report_logger = PromptReportLogger(provider="gemini",model=model,@@ -311,13 +314,16 @@ class GeminiProviderSession(ProviderSession):tools=self._tools,)- self._prompt_report_logger.record_request(- {- "model": api_model_name,- "contents": self._contents,- "config": config,- }- )+ request_payload = {+ "model": api_model_name,+ "contents": self._contents,+ "config": config,+ }+ self._prompt_report_logger.record_request(request_payload)+ if self._recorder is not None:+ self._recorder.record_llm_request(+ "gemini", api_model_name, request_payload+ )stream = await self._client.aio.models.generate_content_stream(model=api_model_name,@@ -337,6 +343,11 @@ class GeminiProviderSession(ProviderSession):self._prompt_report_logger.record_usage(turn_usage)self._total_usage.accumulate(turn_usage)+ if self._recorder is not None:+ self._recorder.record_llm_response(+ state.assistant_text, state.tool_calls, turn_usage+ )+assistant_turn = (types.Content(role=state.model_role, parts=state.model_parts)if state.model_partsdiff --git a/backend/agent/providers/openai.py b/backend/agent/providers/openai.pyindex 0ae87052..2214c46b 100644--- a/backend/agent/providers/openai.py+++ b/backend/agent/providers/openai.py@@ -4,7 +4,7 @@ import copyimport jsonimport uuidfrom dataclasses import dataclass, field-from typing import Any, Dict, List+from typing import Any, Dict, List, Optionalfrom openai import AsyncOpenAIfrom openai.types.chat import ChatCompletionMessageParam@@ -20,6 +20,7 @@ from agent.providers.pricing import MODEL_PRICINGfrom agent.providers.token_usage import TokenUsagefrom agent.state import ensure_strfrom agent.tools import CanonicalToolDefinition, ToolCall, parse_json_arguments+from fs_logging.agent_runs import AgentRunRecorderfrom fs_logging.prompt_reports import PromptReportLoggerfrom llm import Llm, get_openai_api_name, get_openai_reasoning_effort@@ -422,11 +423,13 @@ class OpenAIProviderSession(ProviderSession):model: Llm,prompt_messages: List[ChatCompletionMessageParam],tools: List[Dict[str, Any]],+ recorder: Optional["AgentRunRecorder"] = None,):self._client = clientself._model = modelself._tools = toolsself._total_usage = TokenUsage()+ self._recorder = recorderself._prompt_report_logger = PromptReportLogger(provider="openai",model=model,@@ -455,6 +458,8 @@ class OpenAIProviderSession(ProviderSession):params["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}self._prompt_report_logger.record_request(params)+ if self._recorder is not None:+ self._recorder.record_llm_request("openai", model_name, params)state = OpenAIResponsesParseState()stream = await self._client.responses.create(**params) # type: ignore@@ -465,7 +470,12 @@ class OpenAIProviderSession(ProviderSession):self._prompt_report_logger.record_usage(state.turn_usage)self._total_usage.accumulate(state.turn_usage)- return _build_provider_turn(state)+ turn = _build_provider_turn(state)+ if self._recorder is not None:+ self._recorder.record_llm_response(+ turn.assistant_text, turn.tool_calls, state.turn_usage+ )+ return turn@staticmethoddef _image_ref(part: Any) -> str | None:diff --git a/backend/agent/providers/pricing.py b/backend/agent/providers/pricing.pyindex 51957385..445af866 100644--- a/backend/agent/providers/pricing.py+++ b/backend/agent/providers/pricing.py@@ -15,22 +15,25 @@ class ModelPricing:# Pricing keyed by the API model name string sent to the provider.MODEL_PRICING: Dict[str, ModelPricing] = {# --- OpenAI ---+ # Verified against developers.openai.com/api/docs/pricing on 2026-07-24."gpt-5.4-mini": ModelPricing(- input=0.40, output=3.20, cache_read=0.10+ input=0.75, output=4.50, cache_read=0.075),"gpt-5.4-2026-03-05": ModelPricing(input=2.50, output=15.00, cache_read=0.25),"gpt-5.5": ModelPricing(- input=2.50, output=15.00, cache_read=0.25+ input=5.00, output=30.00, cache_read=0.50),"gpt-5.6-sol": ModelPricing(- input=2.50, output=15.00, cache_read=0.25+ input=5.00, output=30.00, cache_read=0.50),"gpt-5.6-terra": ModelPricing(input=2.50, output=15.00, cache_read=0.25),# --- Anthropic ---+ # Verified against platform.claude.com/docs/en/about-claude/pricing on+ # 2026-07-24. cache_write is the 5-minute cache-write rate (1.25x input)."claude-sonnet-4-6": ModelPricing(input=3.00, output=15.00, cache_read=0.30, cache_write=3.75),@@ -41,6 +44,10 @@ MODEL_PRICING: Dict[str, ModelPricing] = {input=10.00, output=50.00, cache_read=1.00, cache_write=12.50),# --- Gemini ---+ # Verified against ai.google.dev/gemini-api/docs/pricing on 2026-07-24.+ # Pro models bill higher rates for prompts >200k tokens ($4/$18 for 3.1+ # Pro); this flat table uses the <=200k tier, so long-context costs are+ # underestimated."gemini-3-flash-preview": ModelPricing(input=0.50, output=3.00, cache_read=0.05),@@ -51,6 +58,6 @@ MODEL_PRICING: Dict[str, ModelPricing] = {input=2.00, output=12.00, cache_read=0.20),"gemini-3.5-flash": ModelPricing(- input=0.50, output=3.00, cache_read=0.05+ input=1.50, output=9.00, cache_read=0.15),}diff --git a/backend/evals/core.py b/backend/evals/core.pyindex 089e2b2d..8e59eb9d 100644--- a/backend/evals/core.py+++ b/backend/evals/core.py@@ -1,3 +1,6 @@+import uuid+from datetime import datetime+from config import (ANTHROPIC_API_KEY,GEMINI_API_KEY,@@ -8,6 +11,7 @@ from config import ()from llm import Llm, OPENAI_MODELS, ANTHROPIC_MODELS, GEMINI_MODELSfrom agent.runner import Agent+from fs_logging.agent_runs import AgentRunRecorderfrom prompts.create.image import build_image_prompt_messagesfrom prompts.prompt_types import Stackfrom openai.types.chat import ChatCompletionMessageParam@@ -40,6 +44,16 @@ async def generate_code_for_image(image_url: str, stack: Stack, model: Llm) -> sprint(f"[EVALS] Using agent runner for model: {model.value}")+ recorder = AgentRunRecorder(+ generation_id=(+ f"gen_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}"+ ),+ variant_index=0,+ entry_point="eval",+ stack=str(stack),+ input_mode="image",+ generation_type="create",+ )runner = Agent(send_message=send_message,variant_index=0,@@ -54,5 +68,6 @@ async def generate_code_for_image(image_url: str, stack: Stack, model: Llm) -> sasset_base_url=LOCAL_ASSET_BASE_URL,initial_file_state=None,option_codes=None,+ recorder=recorder,)return await runner.run(model, prompt_messages)diff --git a/backend/fs_logging/agent_runs.py b/backend/fs_logging/agent_runs.pynew file mode 100644index 00000000..5b355de7--- /dev/null+++ b/backend/fs_logging/agent_runs.py@@ -0,0 +1,775 @@+"""Full on-disk capture of agent runs.++When ``PROMPT_REPORTS_ENABLED`` is on, every agent run (one variant of a UI+generation, or one eval task) records everything it does:++- every LLM call: full request payload, assembled response, token usage, cost+- every tool call: full arguments, full result, duration+- every streamed delta (thinking/assistant/tool-args) with timestamps+- the final HTML plus a snapshot of the assets it references++Layout under ``{LOGS_PATH}/run_logs/agent_runs``:++ {run_id}/events.jsonl appended live, one event per line+ {run_id}/run.json summary written at finalize+ {run_id}/final.html final output, verbatim+ {run_id}/final_selfcontained.html asset refs rewritten to assets/...+ {run_id}/assets/ copied local assets + downloaded remote images+ {run_id}/assets_manifest.json original URL -> capture status+ index.db SQLite index (runs + llm_calls)++Recording must never break generation: every public method no-ops when+disabled and swallows its own exceptions.+"""++import hashlib+import json+import os+import re+import shutil+import sqlite3+import time+import uuid+from datetime import datetime+from typing import TYPE_CHECKING, Any, Optional+from urllib.parse import unquote, urlparse++from config import LOCAL_ASSET_DIR, PROMPT_REPORTS_ENABLED+from llm import MODEL_PROVIDER, Llm+from agent.providers.pricing import MODEL_PRICING+from agent.providers.token_usage import TokenUsage+from fs_logging.prompt_reports import get_run_logs_directory, to_serializable++if TYPE_CHECKING:+ from agent.providers.base import StreamEvent+ from agent.tools.types import ToolCall, ToolExecutionResult++AGENT_RUNS_DIRNAME = "agent_runs"+RUN_ID_PATTERN = re.compile(r"^run_\d{8}_\d{6}_[0-9a-f]{8}$")++# Refs to assets the backend serves itself, with or without a host prefix.+_LOCAL_ASSET_URL_RE = re.compile(+ r"(?:https?://[^\s\"'()<>]+)?/local-assets/[^\s\"'()<>?#]+"+)+# Remote URLs in image-bearing positions: src/srcset/href attributes and CSS+# url(...). Generated images (e.g. replicate.delivery) expire, so they must be+# snapshotted; stable script/stylesheet CDNs are filtered out by extension.+_REMOTE_URL_RE = re.compile(+ r"""(?:src|srcset|href)\s*=\s*["'](https?://[^\s"'<>]+)["']|url\(\s*["']?(https?://[^\s"')]+)["']?\s*\)"""+)+_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".svg", ".avif", ".ico"}+_ALWAYS_SNAPSHOT_HOSTS = ("replicate.delivery",)++_ASSET_DOWNLOAD_TIMEOUT_SECONDS = 15.0+++def get_agent_runs_directory() -> str:+ return os.path.join(get_run_logs_directory(), AGENT_RUNS_DIRNAME)+++def get_agent_runs_db_path() -> str:+ return os.path.join(get_agent_runs_directory(), "index.db")+++_SCHEMA = """+CREATE TABLE IF NOT EXISTS runs (+ run_id TEXT PRIMARY KEY,+ generation_id TEXT NOT NULL,+ variant_index INTEGER NOT NULL,+ entry_point TEXT NOT NULL,+ provider TEXT,+ model TEXT,+ api_model_name TEXT,+ stack TEXT,+ input_mode TEXT,+ generation_type TEXT,+ status TEXT NOT NULL DEFAULT 'running',+ error TEXT,+ created_at TEXT NOT NULL,+ completed_at TEXT,+ total_duration_ms INTEGER,+ llm_time_ms INTEGER,+ tool_time_ms INTEGER,+ num_llm_calls INTEGER NOT NULL DEFAULT 0,+ num_tool_calls INTEGER NOT NULL DEFAULT 0,+ input_tokens INTEGER,+ output_tokens INTEGER,+ cache_read_tokens INTEGER,+ cache_write_tokens INTEGER,+ total_tokens INTEGER,+ total_cost_usd REAL,+ has_unpriced_calls INTEGER NOT NULL DEFAULT 0,+ run_dir TEXT NOT NULL,+ size_bytes INTEGER+);+CREATE INDEX IF NOT EXISTS idx_runs_generation ON runs(generation_id);+CREATE INDEX IF NOT EXISTS idx_runs_created ON runs(created_at);+CREATE TABLE IF NOT EXISTS llm_calls (+ run_id TEXT NOT NULL REFERENCES runs(run_id) ON DELETE CASCADE,+ step INTEGER NOT NULL,+ started_at TEXT,+ duration_ms INTEGER,+ thinking_ms INTEGER,+ time_to_first_delta_ms INTEGER,+ input_tokens INTEGER,+ output_tokens INTEGER,+ cache_read_tokens INTEGER,+ cache_write_tokens INTEGER,+ total_tokens INTEGER,+ cost_usd REAL,+ num_tool_calls INTEGER,+ PRIMARY KEY (run_id, step)+);+"""+++def open_index_db() -> sqlite3.Connection:+ os.makedirs(get_agent_runs_directory(), exist_ok=True)+ conn = sqlite3.connect(get_agent_runs_db_path(), timeout=5)+ conn.execute("PRAGMA journal_mode=WAL")+ conn.execute("PRAGMA synchronous=NORMAL")+ conn.execute("PRAGMA busy_timeout=5000")+ conn.execute("PRAGMA foreign_keys=ON")+ conn.executescript(_SCHEMA)+ return conn+++def _now_iso() -> str:+ return datetime.now().isoformat(timespec="seconds")+++def _guess_extension(url: str, content_type: Optional[str]) -> str:+ path_ext = os.path.splitext(urlparse(url).path)[1].lower()+ if path_ext in _IMAGE_EXTENSIONS:+ return path_ext+ if content_type:+ subtype = content_type.split("/")[-1].split(";")[0].strip().lower()+ mapped = {"jpeg": ".jpg", "svg+xml": ".svg"}.get(subtype, f".{subtype}")+ if mapped in _IMAGE_EXTENSIONS:+ return mapped+ return ".bin"+++class AgentRunRecorder:+ """Records one agent run (one variant). One instance per ``Agent.run()``."""++ def __init__(+ self,+ *,+ generation_id: str,+ variant_index: int,+ entry_point: str,+ stack: Optional[str] = None,+ input_mode: Optional[str] = None,+ generation_type: Optional[str] = None,+ enabled: Optional[bool] = None,+ ) -> None:+ self.enabled = PROMPT_REPORTS_ENABLED if enabled is None else enabled+ self.generation_id = generation_id+ self.variant_index = variant_index+ self.entry_point = entry_point+ self.stack = stack+ self.input_mode = input_mode+ self.generation_type = generation_type+ self.run_id = (+ f"run_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}"+ )++ self._seq = 0+ self._ended = False+ self._model: Optional[str] = None+ self._provider: Optional[str] = None+ self._api_model_name: Optional[str] = None++ self._run_started_mono: Optional[float] = None+ self._step = 0+ self._step_started_mono: Optional[float] = None+ self._step_started_at: Optional[str] = None+ self._first_delta_mono: Optional[float] = None+ self._first_thinking_mono: Optional[float] = None+ self._last_thinking_mono: Optional[float] = None+ self._thinking_buffer: list[str] = []+ self._assistant_buffer: list[str] = []+ self._tool_args_progress: dict[str, int] = {}+ self._tool_started_mono: dict[str, float] = {}++ self._total_usage = TokenUsage()+ self._priced_cost_usd = 0.0+ self._num_priced_calls = 0+ self._has_unpriced_calls = False+ self._llm_time_ms = 0+ self._tool_time_ms = 0+ self._num_tool_calls = 0+ self._llm_call_summaries: list[dict[str, Any]] = []+ self._tool_call_summaries: list[dict[str, Any]] = []++ # ------------------------------------------------------------------ paths++ @property+ def run_dir(self) -> str:+ return os.path.join(get_agent_runs_directory(), self.run_id)++ def _events_path(self) -> str:+ return os.path.join(self.run_dir, "events.jsonl")++ # ------------------------------------------------------------- primitives++ def _append_event(self, event_type: str, payload: dict[str, Any]) -> None:+ self._seq += 1+ event: dict[str, Any] = {+ "seq": self._seq,+ "ts_ms": int(time.time() * 1000),+ "type": event_type,+ }+ event.update(payload)+ os.makedirs(self.run_dir, exist_ok=True)+ with open(self._events_path(), "a", encoding="utf-8") as f:+ f.write(json.dumps(to_serializable(event), ensure_ascii=False) + "\n")++ def _db_write(self, sql: str, params: tuple[Any, ...]) -> None:+ conn = open_index_db()+ try:+ conn.execute(sql, params)+ conn.commit()+ finally:+ conn.close()++ @staticmethod+ def _elapsed_ms(since: Optional[float]) -> Optional[int]:+ if since is None:+ return None+ return int((time.perf_counter() - since) * 1000)++ # -------------------------------------------------------------- lifecycle++ def record_run_start(self, model: Llm, prompt_messages: Any) -> None:+ if not self.enabled:+ return+ try:+ self._run_started_mono = time.perf_counter()+ self._model = model.value+ self._provider = MODEL_PROVIDER.get(model)+ self._append_event(+ "run_start",+ {+ "run_id": self.run_id,+ "generation_id": self.generation_id,+ "variant_index": self.variant_index,+ "entry_point": self.entry_point,+ "model": self._model,+ "provider": self._provider,+ "stack": self.stack,+ "input_mode": self.input_mode,+ "generation_type": self.generation_type,+ "prompt_messages": prompt_messages,+ },+ )+ self._db_write(+ """INSERT OR REPLACE INTO runs+ (run_id, generation_id, variant_index, entry_point, provider,+ model, stack, input_mode, generation_type, status,+ created_at, run_dir)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?)""",+ (+ self.run_id,+ self.generation_id,+ self.variant_index,+ self.entry_point,+ self._provider,+ self._model,+ self.stack,+ self.input_mode,+ self.generation_type,+ _now_iso(),+ self.run_dir,+ ),+ )+ except Exception as exc:+ print(f"[AGENT RUN] Failed to record run start: {exc}")++ # -------------------------------------------------------------- LLM hooks++ def record_llm_request(+ self, provider: str, api_model_name: str, payload: Any+ ) -> None:+ if not self.enabled:+ return+ try:+ self._step += 1+ self._step_started_mono = time.perf_counter()+ self._step_started_at = _now_iso()+ self._first_delta_mono = None+ self._first_thinking_mono = None+ self._last_thinking_mono = None+ self._thinking_buffer = []+ self._assistant_buffer = []+ self._api_model_name = api_model_name+ self._append_event(+ "llm_call_start",+ {+ "step": self._step,+ "provider": provider,+ "api_model_name": api_model_name,+ "request": payload,+ },+ )+ except Exception as exc:+ print(f"[AGENT RUN] Failed to record LLM request: {exc}")++ def record_stream_event(+ self, event: "StreamEvent", event_id: Optional[str]+ ) -> None:+ if not self.enabled:+ return+ try:+ now = time.perf_counter()+ if self._first_delta_mono is None:+ self._first_delta_mono = now+ payload: dict[str, Any] = {"step": self._step, "event_id": event_id}+ if event.type == "thinking_delta":+ if self._first_thinking_mono is None:+ self._first_thinking_mono = now+ self._last_thinking_mono = now+ self._thinking_buffer.append(event.text)+ payload.update({"kind": "thinking", "text": event.text})+ elif event.type == "assistant_delta":+ self._assistant_buffer.append(event.text)+ payload.update({"kind": "assistant", "text": event.text})+ else: # tool_call_delta+ args = event.tool_arguments+ args_text = args if isinstance(args, str) else json.dumps(+ to_serializable(args), ensure_ascii=False+ )+ # OpenAI streams *cumulative* argument snapshots; record only+ # the unseen suffix so the JSONL replays without O(n^2) bloat.+ key = event.tool_call_id or "unknown"+ seen = self._tool_args_progress.get(key, 0)+ delta = args_text[seen:] if len(args_text) > seen else ""+ self._tool_args_progress[key] = max(seen, len(args_text))+ payload.update(+ {+ "kind": "tool_call",+ "tool_call_id": event.tool_call_id,+ "tool_name": event.tool_name,+ "args_len": len(args_text),+ "args_delta": delta,+ }+ )+ self._append_event("stream_delta", payload)+ except Exception as exc:+ print(f"[AGENT RUN] Failed to record stream event: {exc}")++ def record_llm_response(+ self,+ assistant_text: str,+ tool_calls: "list[ToolCall]",+ usage: Optional[TokenUsage],+ ) -> None:+ if not self.enabled:+ return+ try:+ duration_ms = self._elapsed_ms(self._step_started_mono)+ time_to_first_delta_ms = (+ int((self._first_delta_mono - self._step_started_mono) * 1000)+ if self._first_delta_mono is not None+ and self._step_started_mono is not None+ else None+ )+ thinking_ms = (+ int((self._last_thinking_mono - self._first_thinking_mono) * 1000)+ if self._first_thinking_mono is not None+ and self._last_thinking_mono is not None+ else 0+ )+ cost_usd: Optional[float] = None+ usage_dict: Optional[dict[str, int]] = None+ if usage is not None:+ usage_dict = {+ "input": usage.input,+ "output": usage.output,+ "cache_read": usage.cache_read,+ "cache_write": usage.cache_write,+ "total": usage.total,+ }+ self._total_usage.accumulate(usage)+ pricing = (+ MODEL_PRICING.get(self._api_model_name)+ if self._api_model_name+ else None+ )+ if pricing is not None:+ cost_usd = usage.cost(pricing)+ self._priced_cost_usd += cost_usd+ self._num_priced_calls += 1+ else:+ self._has_unpriced_calls = True+ else:+ self._has_unpriced_calls = True+ if duration_ms is not None:+ self._llm_time_ms += duration_ms++ call_summary: dict[str, Any] = {+ "step": self._step,+ "started_at": self._step_started_at,+ "duration_ms": duration_ms,+ "thinking_ms": thinking_ms,+ "time_to_first_delta_ms": time_to_first_delta_ms,+ "usage": usage_dict,+ "cost_usd": cost_usd,+ "num_tool_calls": len(tool_calls),+ }+ self._llm_call_summaries.append(call_summary)+ self._append_event(+ "llm_call_end",+ {+ **call_summary,+ "assistant_text": assistant_text,+ "thinking_text": "".join(self._thinking_buffer),+ "tool_calls": [+ {"id": c.id, "name": c.name, "arguments": c.arguments}+ for c in tool_calls+ ],+ },+ )+ self._db_write(+ """INSERT OR REPLACE INTO llm_calls+ (run_id, step, started_at, duration_ms, thinking_ms,+ time_to_first_delta_ms, input_tokens, output_tokens,+ cache_read_tokens, cache_write_tokens, total_tokens,+ cost_usd, num_tool_calls)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",+ (+ self.run_id,+ self._step,+ self._step_started_at,+ duration_ms,+ thinking_ms,+ time_to_first_delta_ms,+ usage.input if usage else None,+ usage.output if usage else None,+ usage.cache_read if usage else None,+ usage.cache_write if usage else None,+ usage.total if usage else None,+ cost_usd,+ len(tool_calls),+ ),+ )+ except Exception as exc:+ print(f"[AGENT RUN] Failed to record LLM response: {exc}")++ # ------------------------------------------------------------- tool hooks++ def record_tool_start(self, tool_event_id: str, tool_call: "ToolCall") -> None:+ if not self.enabled:+ return+ try:+ self._tool_started_mono[tool_event_id] = time.perf_counter()+ self._append_event(+ "tool_call_start",+ {+ "step": self._step,+ "tool_event_id": tool_event_id,+ "tool_call_id": tool_call.id,+ "name": tool_call.name,+ "arguments": tool_call.arguments,+ },+ )+ except Exception as exc:+ print(f"[AGENT RUN] Failed to record tool start: {exc}")++ def record_tool_end(+ self,+ tool_event_id: str,+ tool_call: "ToolCall",+ result: "ToolExecutionResult",+ ) -> None:+ if not self.enabled:+ return+ try:+ duration_ms = self._elapsed_ms(+ self._tool_started_mono.pop(tool_event_id, None)+ )+ if duration_ms is not None:+ self._tool_time_ms += duration_ms+ self._num_tool_calls += 1+ multimodal_meta: list[dict[str, Any]] = [+ {+ "display_name": part.display_name,+ "mime_type": part.mime_type,+ # Bytes reappear base64'd in the next llm_call_start+ # request payload, so store metadata only here.+ "data_len": len(part.data) if part.data is not None else None,+ "image_url": part.image_url,+ }+ for part in (result.multimodal_parts or [])+ ]+ self._tool_call_summaries.append(+ {+ "step": self._step,+ "name": tool_call.name,+ "ok": result.ok,+ "duration_ms": duration_ms,+ "summary": result.summary,+ }+ )+ self._append_event(+ "tool_call_end",+ {+ "step": self._step,+ "tool_event_id": tool_event_id,+ "name": tool_call.name,+ "ok": result.ok,+ "duration_ms": duration_ms,+ "result": result.result,+ "summary": result.summary,+ "updated_content_len": (+ len(result.updated_content)+ if result.updated_content is not None+ else None+ ),+ "multimodal_parts": multimodal_meta,+ },+ )+ except Exception as exc:+ print(f"[AGENT RUN] Failed to record tool end: {exc}")++ def record_set_code(self, content_len: int, source: str) -> None:+ if not self.enabled:+ return+ try:+ self._append_event(+ "set_code", {"step": self._step, "source": source, "content_len": content_len}+ )+ except Exception as exc:+ print(f"[AGENT RUN] Failed to record set_code: {exc}")++ # --------------------------------------------------------------- finalize++ async def record_run_end(+ self,+ status: str,+ error: Optional[str] = None,+ final_html: Optional[str] = None,+ ) -> None:+ if not self.enabled or self._ended:+ return+ self._ended = True+ try:+ total_duration_ms = self._elapsed_ms(self._run_started_mono)+ total_cost_usd = (+ self._priced_cost_usd if self._num_priced_calls > 0 else None+ )+ if final_html:+ await self._snapshot_output(final_html)+ self._append_event(+ "run_end",+ {+ "status": status,+ "error": error,+ "total_duration_ms": total_duration_ms,+ "llm_time_ms": self._llm_time_ms,+ "tool_time_ms": self._tool_time_ms,+ "num_llm_calls": self._step,+ "num_tool_calls": self._num_tool_calls,+ "usage": {+ "input": self._total_usage.input,+ "output": self._total_usage.output,+ "cache_read": self._total_usage.cache_read,+ "cache_write": self._total_usage.cache_write,+ "total": self._total_usage.total,+ },+ "total_cost_usd": total_cost_usd,+ "has_unpriced_calls": self._has_unpriced_calls,+ "final_html_len": len(final_html) if final_html else None,+ },+ )+ run_summary: dict[str, Any] = {+ "run_id": self.run_id,+ "generation_id": self.generation_id,+ "variant_index": self.variant_index,+ "entry_point": self.entry_point,+ "provider": self._provider,+ "model": self._model,+ "api_model_name": self._api_model_name,+ "stack": self.stack,+ "input_mode": self.input_mode,+ "generation_type": self.generation_type,+ "status": status,+ "error": error,+ "completed_at": _now_iso(),+ "total_duration_ms": total_duration_ms,+ "llm_time_ms": self._llm_time_ms,+ "tool_time_ms": self._tool_time_ms,+ "total_cost_usd": total_cost_usd,+ "has_unpriced_calls": self._has_unpriced_calls,+ "llm_calls": self._llm_call_summaries,+ "tool_calls": self._tool_call_summaries,+ "final_html": final_html,+ }+ os.makedirs(self.run_dir, exist_ok=True)+ with open(+ os.path.join(self.run_dir, "run.json"), "w", encoding="utf-8"+ ) as f:+ json.dump(to_serializable(run_summary), f, indent=2, ensure_ascii=False)++ size_bytes = 0+ for root, _, files in os.walk(self.run_dir):+ for name in files:+ size_bytes += os.path.getsize(os.path.join(root, name))++ self._db_write(+ """UPDATE runs SET+ status = ?, error = ?, completed_at = ?, api_model_name = ?,+ total_duration_ms = ?, llm_time_ms = ?, tool_time_ms = ?,+ num_llm_calls = ?, num_tool_calls = ?,+ input_tokens = ?, output_tokens = ?, cache_read_tokens = ?,+ cache_write_tokens = ?, total_tokens = ?,+ total_cost_usd = ?, has_unpriced_calls = ?, size_bytes = ?+ WHERE run_id = ?""",+ (+ status,+ error,+ _now_iso(),+ self._api_model_name,+ total_duration_ms,+ self._llm_time_ms,+ self._tool_time_ms,+ self._step,+ self._num_tool_calls,+ self._total_usage.input,+ self._total_usage.output,+ self._total_usage.cache_read,+ self._total_usage.cache_write,+ self._total_usage.total,+ total_cost_usd,+ 1 if self._has_unpriced_calls else 0,+ size_bytes,+ self.run_id,+ ),+ )+ except Exception as exc:+ print(f"[AGENT RUN] Failed to record run end: {exc}")++ # --------------------------------------------------------- output capture++ async def _snapshot_output(self, final_html: str) -> None:+ """Save final.html plus every asset it references.++ Local ``/local-assets/`` files are copied from ``LOCAL_ASSET_DIR``;+ remote image URLs are downloaded (generated-image hosts expire their+ URLs). ``final_selfcontained.html`` gets all captured refs rewritten+ to relative ``assets/`` paths so the run folder stands alone.+ """+ assets_dir = os.path.join(self.run_dir, "assets")+ os.makedirs(assets_dir, exist_ok=True)+ with open(+ os.path.join(self.run_dir, "final.html"), "w", encoding="utf-8"+ ) as f:+ f.write(final_html)++ manifest: list[dict[str, Any]] = []+ replacements: dict[str, str] = {}+ used_names: set[str] = set()++ def unique_name(candidate: str) -> str:+ base, ext = os.path.splitext(os.path.basename(candidate) or "asset")+ name = f"{base}{ext}"+ counter = 1+ while name in used_names:+ name = f"{base}_{counter}{ext}"+ counter += 1+ used_names.add(name)+ return name++ # The same file can be referenced under several URL forms (with and+ # without a host prefix); copy it once and point every form at it.+ copied_local: dict[str, str] = {}+ for url in dict.fromkeys(_LOCAL_ASSET_URL_RE.findall(final_html)):+ filename = unquote(url.split("/local-assets/", 1)[1])+ source_path = os.path.join(LOCAL_ASSET_DIR, filename)+ entry: dict[str, Any] = {"url": url, "kind": "local"}+ if filename in copied_local:+ saved_name = copied_local[filename]+ entry.update(+ {+ "file": f"assets/{saved_name}",+ "bytes": os.path.getsize(source_path),+ "status": "copied",+ }+ )+ replacements[url] = f"assets/{saved_name}"+ elif os.path.isfile(source_path):+ saved_name = unique_name(filename)+ shutil.copy2(source_path, os.path.join(assets_dir, saved_name))+ copied_local[filename] = saved_name+ entry.update(+ {+ "file": f"assets/{saved_name}",+ "bytes": os.path.getsize(source_path),+ "status": "copied",+ }+ )+ replacements[url] = f"assets/{saved_name}"+ else:+ entry["status"] = "missing"+ manifest.append(entry)++ remote_urls: list[str] = []+ for match in _REMOTE_URL_RE.finditer(final_html):+ url = match.group(1) or match.group(2)+ if not url or "/local-assets/" in url or url in remote_urls:+ continue+ path_ext = os.path.splitext(urlparse(url).path)[1].lower()+ host = urlparse(url).netloc+ if path_ext in _IMAGE_EXTENSIONS or any(+ host.endswith(h) for h in _ALWAYS_SNAPSHOT_HOSTS+ ):+ remote_urls.append(url)++ if remote_urls:+ import httpx++ async with httpx.AsyncClient(+ timeout=_ASSET_DOWNLOAD_TIMEOUT_SECONDS, follow_redirects=True+ ) as client:+ for url in remote_urls:+ entry = {"url": url, "kind": "remote"}+ try:+ response = await client.get(url)+ response.raise_for_status()+ content = response.content+ digest = hashlib.sha256(content).hexdigest()[:12]+ ext = _guess_extension(+ url, response.headers.get("content-type")+ )+ saved_name = unique_name(f"remote_{digest}{ext}")+ with open(os.path.join(assets_dir, saved_name), "wb") as f:+ f.write(content)+ entry.update(+ {+ "file": f"assets/{saved_name}",+ "bytes": len(content),+ "sha256": digest,+ "status": "downloaded",+ }+ )+ replacements[url] = f"assets/{saved_name}"+ except Exception as exc:+ entry.update({"status": "failed", "error": str(exc)})+ manifest.append(entry)++ self_contained = final_html+ # Longest-first so a bare "/local-assets/x" ref never clobbers the+ # middle of a full "http://host/local-assets/x" ref.+ for url in sorted(replacements, key=len, reverse=True):+ self_contained = self_contained.replace(url, replacements[url])+ with open(+ os.path.join(self.run_dir, "final_selfcontained.html"),+ "w",+ encoding="utf-8",+ ) as f:+ f.write(self_contained)+ with open(+ os.path.join(self.run_dir, "assets_manifest.json"), "w", encoding="utf-8"+ ) as f:+ json.dump(manifest, f, indent=2, ensure_ascii=False)diff --git a/backend/main.py b/backend/main.pyindex 347d0f89..3a4b8541 100644--- a/backend/main.py+++ b/backend/main.py@@ -15,6 +15,7 @@ from routes import (export,design_systems,prompt_reports,+ agent_runs,)from uploaded_assets import configure_uploaded_asset_routes@@ -53,3 +54,4 @@ app.include_router(evals.router)app.include_router(export.router)app.include_router(design_systems.router)app.include_router(prompt_reports.router)+app.include_router(agent_runs.router)diff --git a/backend/routes/agent_runs.py b/backend/routes/agent_runs.pynew file mode 100644index 00000000..a1d1dee2--- /dev/null+++ b/backend/routes/agent_runs.py@@ -0,0 +1,264 @@+"""API for browsing recorded agent runs (see ``fs_logging/agent_runs.py``).++The list endpoint reads the SQLite index; the detail endpoint replays the+run's ``events.jsonl`` from disk. Output endpoints serve the snapshotted+final HTML and its captured assets so the viewer can render a run's result+without depending on expiring remote URLs or the live asset store.+"""++import json+import os+import shutil+import sqlite3+from datetime import datetime, timedelta+from typing import Any, Optional++from fastapi import APIRouter, HTTPException+from fastapi.responses import FileResponse, HTMLResponse+from pydantic import BaseModel++from fs_logging.agent_runs import (+ RUN_ID_PATTERN,+ get_agent_runs_db_path,+ get_agent_runs_directory,+ open_index_db,+)++router = APIRouter()++_RUN_COLUMNS = [+ "run_id",+ "generation_id",+ "variant_index",+ "entry_point",+ "provider",+ "model",+ "api_model_name",+ "stack",+ "input_mode",+ "generation_type",+ "status",+ "error",+ "created_at",+ "completed_at",+ "total_duration_ms",+ "llm_time_ms",+ "tool_time_ms",+ "num_llm_calls",+ "num_tool_calls",+ "input_tokens",+ "output_tokens",+ "cache_read_tokens",+ "cache_write_tokens",+ "total_tokens",+ "total_cost_usd",+ "has_unpriced_calls",+ "size_bytes",+]+++class AgentRunSummary(BaseModel):+ run_id: str+ generation_id: str+ variant_index: int+ entry_point: str+ provider: Optional[str]+ model: Optional[str]+ api_model_name: Optional[str]+ stack: Optional[str]+ input_mode: Optional[str]+ generation_type: Optional[str]+ status: str+ error: Optional[str]+ created_at: str+ completed_at: Optional[str]+ total_duration_ms: Optional[int]+ llm_time_ms: Optional[int]+ tool_time_ms: Optional[int]+ num_llm_calls: int+ num_tool_calls: int+ input_tokens: Optional[int]+ output_tokens: Optional[int]+ cache_read_tokens: Optional[int]+ cache_write_tokens: Optional[int]+ total_tokens: Optional[int]+ total_cost_usd: Optional[float]+ has_unpriced_calls: bool+ size_bytes: Optional[int]+++class AgentRunListResponse(BaseModel):+ runs: list[AgentRunSummary]+ total_size_bytes: int+ runs_directory: str+++class AgentRunDetailResponse(BaseModel):+ run: AgentRunSummary+ events: list[dict[str, Any]]+++class PruneAgentRunsRequest(BaseModel):+ max_age_days: int = 7+++class PruneAgentRunsResponse(BaseModel):+ deleted_count: int+ freed_bytes: int+++def _row_to_summary(row: tuple[Any, ...]) -> AgentRunSummary:+ data = dict(zip(_RUN_COLUMNS, row))+ data["has_unpriced_calls"] = bool(data["has_unpriced_calls"])+ return AgentRunSummary(**data)+++def _directory_size_bytes(path: str) -> int:+ total = 0+ for root, _, files in os.walk(path):+ for name in files:+ try:+ total += os.path.getsize(os.path.join(root, name))+ except OSError:+ continue+ return total+++def _fetch_run(run_id: str) -> AgentRunSummary:+ if not RUN_ID_PATTERN.match(run_id):+ raise HTTPException(status_code=400, detail="Invalid run id")+ if not os.path.isfile(get_agent_runs_db_path()):+ raise HTTPException(status_code=404, detail="No runs recorded")+ conn = open_index_db()+ try:+ row = conn.execute(+ f"SELECT {', '.join(_RUN_COLUMNS)} FROM runs WHERE run_id = ?",+ (run_id,),+ ).fetchone()+ finally:+ conn.close()+ if row is None:+ raise HTTPException(status_code=404, detail="Run not found")+ return _row_to_summary(row)++[email protected]("/agent-runs", response_model=AgentRunListResponse)+async def list_agent_runs(limit: int = 200) -> AgentRunListResponse:+ runs_directory = get_agent_runs_directory()+ if not os.path.isfile(get_agent_runs_db_path()):+ return AgentRunListResponse(+ runs=[], total_size_bytes=0, runs_directory=runs_directory+ )++ conn = open_index_db()+ try:+ rows = conn.execute(+ f"SELECT {', '.join(_RUN_COLUMNS)} FROM runs "+ "ORDER BY created_at DESC, run_id DESC LIMIT ?",+ (max(1, min(limit, 1000)),),+ ).fetchall()+ finally:+ conn.close()++ return AgentRunListResponse(+ runs=[_row_to_summary(row) for row in rows],+ total_size_bytes=_directory_size_bytes(runs_directory),+ runs_directory=runs_directory,+ )++[email protected]("/agent-runs/{run_id}", response_model=AgentRunDetailResponse)+async def get_agent_run(+ run_id: str, include_stream_deltas: bool = False+) -> AgentRunDetailResponse:+ run = _fetch_run(run_id)+ events: list[dict[str, Any]] = []+ events_path = os.path.join(get_agent_runs_directory(), run_id, "events.jsonl")+ if os.path.isfile(events_path):+ with open(events_path, "r", encoding="utf-8") as f:+ for line in f:+ line = line.strip()+ if not line:+ continue+ try:+ event = json.loads(line)+ except json.JSONDecodeError:+ # A crashed writer can leave a torn final line.+ continue+ if not include_stream_deltas and event.get("type") == "stream_delta":+ continue+ events.append(event)+ return AgentRunDetailResponse(run=run, events=events)++[email protected]("/agent-runs/{run_id}/output")+async def get_agent_run_output(run_id: str) -> HTMLResponse:+ _fetch_run(run_id)+ run_dir = os.path.join(get_agent_runs_directory(), run_id)+ for candidate in ("final_selfcontained.html", "final.html"):+ path = os.path.join(run_dir, candidate)+ if os.path.isfile(path):+ with open(path, "r", encoding="utf-8") as f:+ return HTMLResponse(content=f.read())+ raise HTTPException(status_code=404, detail="Run has no captured output")++[email protected]("/agent-runs/{run_id}/assets/{filename}")+async def get_agent_run_asset(run_id: str, filename: str) -> FileResponse:+ _fetch_run(run_id)+ assets_dir = os.path.join(get_agent_runs_directory(), run_id, "assets")+ # basename() strips any traversal components before the containment check.+ safe_name = os.path.basename(filename)+ path = os.path.realpath(os.path.join(assets_dir, safe_name))+ if not path.startswith(os.path.realpath(assets_dir) + os.sep):+ raise HTTPException(status_code=400, detail="Invalid asset path")+ if not os.path.isfile(path):+ raise HTTPException(status_code=404, detail="Asset not found")+ return FileResponse(path)++[email protected]("/agent-runs/prune", response_model=PruneAgentRunsResponse)+async def prune_agent_runs(request: PruneAgentRunsRequest) -> PruneAgentRunsResponse:+ if request.max_age_days < 1:+ raise HTTPException(status_code=400, detail="max_age_days must be >= 1")++ runs_directory = get_agent_runs_directory()+ if not os.path.isdir(runs_directory):+ return PruneAgentRunsResponse(deleted_count=0, freed_bytes=0)++ cutoff_timestamp = (+ datetime.now() - timedelta(days=request.max_age_days)+ ).timestamp()++ deleted_count = 0+ freed_bytes = 0+ deleted_run_ids: list[str] = []++ for entry in os.scandir(runs_directory):+ if not entry.is_dir() or not RUN_ID_PATTERN.match(entry.name):+ continue+ if entry.stat().st_mtime >= cutoff_timestamp:+ continue+ freed_bytes += _directory_size_bytes(entry.path)+ shutil.rmtree(entry.path, ignore_errors=True)+ deleted_run_ids.append(entry.name)+ deleted_count += 1++ if os.path.isfile(get_agent_runs_db_path()):+ conn = open_index_db()+ try:+ for run_id in deleted_run_ids:+ conn.execute("DELETE FROM runs WHERE run_id = ?", (run_id,))+ # Rows whose directories vanished out-of-band are orphans too.+ for (run_id, run_dir) in conn.execute(+ "SELECT run_id, run_dir FROM runs"+ ).fetchall():+ if not os.path.isdir(run_dir):+ conn.execute("DELETE FROM runs WHERE run_id = ?", (run_id,))+ conn.commit()+ except sqlite3.Error as e:+ print(f"[AGENT RUN] Prune index cleanup failed: {e}")+ finally:+ conn.close()++ return PruneAgentRunsResponse(deleted_count=deleted_count, freed_bytes=freed_bytes)diff --git a/backend/routes/generate_code.py b/backend/routes/generate_code.pyindex 7ea2feee..091874ba 100644--- a/backend/routes/generate_code.py+++ b/backend/routes/generate_code.py@@ -1,5 +1,7 @@import asyncio+import uuidfrom dataclasses import dataclass, field+from datetime import datetimefrom abc import ABC, abstractmethodimport tracebackfrom typing import Callable, Awaitable@@ -60,6 +62,7 @@ from uploaded_assets import (infer_local_asset_base_url,)from agent.runner import Agent+from fs_logging.agent_runs import AgentRunRecorderfrom routes.model_choice_sets import (ALL_KEYS_MODELS_DEFAULT,ALL_KEYS_MODELS_TEXT_CREATE,@@ -559,6 +562,10 @@ class AgenticGenerationStage:asset_base_url: str,option_codes: List[str] | None,should_extract_assets: bool = True,+ generation_id: str | None = None,+ stack: str | None = None,+ input_mode: str | None = None,+ generation_type: str | None = None,):self.send_message = send_messageself.openai_api_key = openai_api_key@@ -571,6 +578,13 @@ class AgenticGenerationStage:self.file_state = file_stateself.asset_base_url = asset_base_urlself.option_codes = option_codes or []+ self.generation_id = (+ generation_id+ or f"gen_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}"+ )+ self.stack = stack+ self.input_mode = input_mode+ self.generation_type = generation_typeasync def process_variants(self,@@ -618,6 +632,14 @@ class AgenticGenerationStage:event_id,)+ recorder = AgentRunRecorder(+ generation_id=self.generation_id,+ variant_index=index,+ entry_point="websocket",+ stack=self.stack,+ input_mode=self.input_mode,+ generation_type=self.generation_type,+ )runner = Agent(send_message=send_runner_message,variant_index=index,@@ -631,6 +653,7 @@ class AgenticGenerationStage:asset_base_url=self.asset_base_url,initial_file_state=self.file_state,option_codes=self.option_codes,+ recorder=recorder,)completion = await runner.run(model, prompt_messages)if completion:@@ -814,6 +837,9 @@ class CodeGenerationMiddleware(Middleware):file_state=context.extracted_params.file_state,asset_base_url=context.extracted_params.asset_base_url,option_codes=context.extracted_params.option_codes,+ stack=str(context.extracted_params.stack),+ input_mode=str(context.extracted_params.input_mode),+ generation_type=context.extracted_params.generation_type,)context.variant_completions = await generation_stage.process_variants(diff --git a/backend/routes/prompt_reports.py b/backend/routes/prompt_reports.pyindex 4b77d716..ec822a25 100644--- a/backend/routes/prompt_reports.py+++ b/backend/routes/prompt_reports.py@@ -181,6 +181,11 @@ async def prune_prompt_reports(deleted_count = 0freed_bytes = 0for entry in os.scandir(run_logs_directory):+ # agent_runs has its own index + prune endpoint (/agent-runs/prune);+ # rmtree'ing it here would destroy the SQLite index and fresh runs.+ if entry.is_dir() and entry.name == "agent_runs":+ continue+# The prompt_reports subdirectory itself is permanent; prune inside it.if entry.is_dir() and entry.name == "prompt_reports":for report_entry in os.scandir(entry.path):diff --git a/backend/tests/test_agent_runs.py b/backend/tests/test_agent_runs.pynew file mode 100644index 00000000..13284ba2--- /dev/null+++ b/backend/tests/test_agent_runs.py@@ -0,0 +1,679 @@+import json+import sqlite3+from pathlib import Path+from typing import Any, Optional++import pytest++from agent.providers.base import StreamEvent+from agent.providers.pricing import MODEL_PRICING+from agent.providers.token_usage import TokenUsage+from agent.tools.types import ToolCall, ToolExecutionResult+from fs_logging.agent_runs import (+ RUN_ID_PATTERN,+ AgentRunRecorder,+ get_agent_runs_db_path,+ get_agent_runs_directory,+)+from llm import Llm+++def logs_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ monkeypatch.setenv("LOGS_PATH", str(tmp_path))+ return tmp_path+++def _make_recorder(enabled: bool = True, **overrides: Any) -> AgentRunRecorder:+ kwargs: dict[str, Any] = dict(+ generation_id="gen_test_00000000",+ variant_index=0,+ entry_point="websocket",+ stack="html_tailwind",+ input_mode="image",+ generation_type="create",+ enabled=enabled,+ )+ kwargs.update(overrides)+ return AgentRunRecorder(**kwargs)+++def _read_events(recorder: AgentRunRecorder) -> list[dict[str, Any]]:+ events_path = Path(recorder.run_dir) / "events.jsonl"+ with open(events_path) as f:+ return [json.loads(line) for line in f if line.strip()]+++def _db_row(query: str, params: tuple[Any, ...] = ()) -> Optional[tuple[Any, ...]]:+ conn = sqlite3.connect(get_agent_runs_db_path())+ try:+ cursor = conn.execute(query, params)+ return cursor.fetchone()+ finally:+ conn.close()+++async def test_disabled_recorder_writes_nothing(logs_path: Path) -> None:+ recorder = _make_recorder(enabled=False)+ recorder.record_run_start(Llm.GPT_5_5_HIGH, [{"role": "user", "content": "hi"}])+ recorder.record_llm_request("openai", "gpt-5.5", {"input": []})+ recorder.record_llm_response("text", [], TokenUsage(input=10, output=5, total=15))+ await recorder.record_run_end("completed", final_html="<html></html>")++ assert not (logs_path / "run_logs").exists()+++def test_run_start_creates_events_and_db_row(logs_path: Path) -> None:+ recorder = _make_recorder()+ assert RUN_ID_PATTERN.match(recorder.run_id)+ recorder.record_run_start(+ Llm.CLAUDE_OPUS_4_8_HIGH, [{"role": "user", "content": "make a page"}]+ )++ events = _read_events(recorder)+ assert [e["type"] for e in events] == ["run_start"]+ assert events[0]["model"] == Llm.CLAUDE_OPUS_4_8_HIGH.value+ assert events[0]["provider"] == "anthropic"+ assert events[0]["prompt_messages"] == [{"role": "user", "content": "make a page"}]++ row = _db_row(+ "SELECT generation_id, variant_index, entry_point, provider, status "+ "FROM runs WHERE run_id = ?",+ (recorder.run_id,),+ )+ assert row == ("gen_test_00000000", 0, "websocket", "anthropic", "running")+++async def test_full_run_records_events_costs_and_totals(logs_path: Path) -> None:+ recorder = _make_recorder()+ recorder.record_run_start(Llm.GPT_5_5_HIGH, [{"role": "user", "content": "go"}])++ # Step 1: thinking + assistant deltas, one tool call+ recorder.record_llm_request("openai", "gpt-5.5", {"input": ["go"]})+ recorder.record_stream_event(+ StreamEvent(type="thinking_delta", text="hmm "), "thinking-0-abc"+ )+ recorder.record_stream_event(+ StreamEvent(type="thinking_delta", text="ok"), "thinking-0-abc"+ )+ recorder.record_stream_event(+ StreamEvent(+ type="tool_call_delta",+ tool_call_id="call_1",+ tool_name="create_file",+ tool_arguments='{"path": "index.html"',+ ),+ "call_1",+ )+ recorder.record_stream_event(+ StreamEvent(+ type="tool_call_delta",+ tool_call_id="call_1",+ tool_name="create_file",+ tool_arguments='{"path": "index.html", "content": "<html>"}',+ ),+ "call_1",+ )+ usage_1 = TokenUsage(input=1000, output=500, cache_read=200, total=1700)+ tool_call = ToolCall(+ id="call_1",+ name="create_file",+ arguments={"path": "index.html", "content": "<html>"},+ )+ recorder.record_llm_response("", [tool_call], usage_1)++ recorder.record_tool_start("call_1", tool_call)+ recorder.record_tool_end(+ "call_1",+ tool_call,+ ToolExecutionResult(+ ok=True,+ result={"path": "index.html"},+ summary={"path": "index.html"},+ updated_content="<html></html>",+ ),+ )+ recorder.record_set_code(14, "tool_result")++ # Step 2: final assistant turn, no tools+ recorder.record_llm_request("openai", "gpt-5.5", {"input": ["continue"]})+ recorder.record_stream_event(+ StreamEvent(type="assistant_delta", text="done"), "assistant-0-def"+ )+ usage_2 = TokenUsage(input=2000, output=100, total=2100)+ recorder.record_llm_response("done", [], usage_2)++ await recorder.record_run_end("completed", final_html="<html>final</html>")++ events = _read_events(recorder)+ assert [e["type"] for e in events] == [+ "run_start",+ "llm_call_start",+ "stream_delta",+ "stream_delta",+ "stream_delta",+ "stream_delta",+ "llm_call_end",+ "tool_call_start",+ "tool_call_end",+ "set_code",+ "llm_call_start",+ "stream_delta",+ "llm_call_end",+ "run_end",+ ]+ assert [e["seq"] for e in events] == list(range(1, len(events) + 1))++ # Cumulative tool-arg snapshots are recorded as incremental suffixes.+ tool_deltas = [+ e for e in events if e["type"] == "stream_delta" and e["kind"] == "tool_call"+ ]+ assert tool_deltas[0]["args_delta"] == '{"path": "index.html"'+ assert tool_deltas[1]["args_delta"] == ', "content": "<html>"}'++ llm_end_1 = events[6]+ assert llm_end_1["thinking_text"] == "hmm ok"+ assert llm_end_1["thinking_ms"] >= 0+ assert llm_end_1["tool_calls"] == [+ {+ "id": "call_1",+ "name": "create_file",+ "arguments": {"path": "index.html", "content": "<html>"},+ }+ ]+ pricing = MODEL_PRICING["gpt-5.5"]+ assert llm_end_1["cost_usd"] == pytest.approx(usage_1.cost(pricing))++ tool_end = events[8]+ assert tool_end["ok"] is True+ assert tool_end["result"] == {"path": "index.html"}+ assert tool_end["updated_content_len"] == len("<html></html>")+ assert tool_end["duration_ms"] >= 0++ run_end = events[-1]+ expected_total = usage_1.cost(pricing) + usage_2.cost(pricing)+ assert run_end["status"] == "completed"+ assert run_end["num_llm_calls"] == 2+ assert run_end["num_tool_calls"] == 1+ assert run_end["usage"]["input"] == 3000+ assert run_end["usage"]["total"] == 3800+ assert run_end["total_cost_usd"] == pytest.approx(expected_total)+ assert run_end["has_unpriced_calls"] is False+ assert run_end["final_html_len"] == len("<html>final</html>")++ row = _db_row(+ "SELECT status, num_llm_calls, num_tool_calls, input_tokens, total_tokens, "+ "total_cost_usd, has_unpriced_calls, total_duration_ms, llm_time_ms, "+ "tool_time_ms, api_model_name FROM runs WHERE run_id = ?",+ (recorder.run_id,),+ )+ assert row is not None+ assert row[0] == "completed"+ assert row[1] == 2+ assert row[2] == 1+ assert row[3] == 3000+ assert row[4] == 3800+ assert row[5] == pytest.approx(expected_total)+ assert row[6] == 0+ assert row[7] >= 0 and row[8] >= 0 and row[9] >= 0+ assert row[10] == "gpt-5.5"++ call_rows = []+ conn = sqlite3.connect(get_agent_runs_db_path())+ try:+ call_rows = conn.execute(+ "SELECT step, input_tokens, cost_usd FROM llm_calls "+ "WHERE run_id = ? ORDER BY step",+ (recorder.run_id,),+ ).fetchall()+ finally:+ conn.close()+ assert len(call_rows) == 2+ assert call_rows[0][1] == 1000+ assert call_rows[0][2] == pytest.approx(usage_1.cost(pricing))++ run_json = json.loads((Path(recorder.run_dir) / "run.json").read_text())+ assert run_json["final_html"] == "<html>final</html>"+ assert len(run_json["llm_calls"]) == 2+ assert len(run_json["tool_calls"]) == 1+ assert (Path(recorder.run_dir) / "final.html").read_text() == "<html>final</html>"+++async def test_unpriced_model_flags_and_null_cost(logs_path: Path) -> None:+ recorder = _make_recorder()+ recorder.record_run_start(Llm.GPT_5_5_HIGH, [])+ recorder.record_llm_request("openai", "unknown-model-x", {})+ recorder.record_llm_response("hi", [], TokenUsage(input=10, output=5, total=15))+ await recorder.record_run_end("completed")++ events = _read_events(recorder)+ llm_end = next(e for e in events if e["type"] == "llm_call_end")+ assert llm_end["cost_usd"] is None+ run_end = events[-1]+ assert run_end["total_cost_usd"] is None+ assert run_end["has_unpriced_calls"] is True++ row = _db_row(+ "SELECT total_cost_usd, has_unpriced_calls FROM runs WHERE run_id = ?",+ (recorder.run_id,),+ )+ assert row == (None, 1)+++async def test_gemini_none_usage_is_tolerated(logs_path: Path) -> None:+ recorder = _make_recorder()+ recorder.record_run_start(Llm.GEMINI_3_5_FLASH_HIGH, [])+ recorder.record_llm_request("gemini", "gemini-3.5-flash", {})+ recorder.record_llm_response("hi", [], None)+ await recorder.record_run_end("completed")++ events = _read_events(recorder)+ llm_end = next(e for e in events if e["type"] == "llm_call_end")+ assert llm_end["usage"] is None+ assert llm_end["cost_usd"] is None+ assert events[-1]["has_unpriced_calls"] is True+++async def test_failed_run_and_idempotent_run_end(logs_path: Path) -> None:+ recorder = _make_recorder()+ recorder.record_run_start(Llm.GPT_5_5_HIGH, [])+ await recorder.record_run_end("failed", error="boom")+ # A second call (e.g. failure path after cancel) must not double-write.+ await recorder.record_run_end("completed", final_html="<html></html>")++ events = _read_events(recorder)+ assert [e["type"] for e in events] == ["run_start", "run_end"]+ assert events[-1]["status"] == "failed"+ assert events[-1]["error"] == "boom"++ row = _db_row(+ "SELECT status, error FROM runs WHERE run_id = ?", (recorder.run_id,)+ )+ assert row == ("failed", "boom")+++async def test_asset_snapshot_copies_local_and_rewrites(+ logs_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ local_asset_dir = logs_path / "local_assets"+ local_asset_dir.mkdir()+ (local_asset_dir / "crop_abc.png").write_bytes(b"png-bytes")+ monkeypatch.setattr(+ "fs_logging.agent_runs.LOCAL_ASSET_DIR", str(local_asset_dir)+ )++ html = (+ '<html><img src="http://127.0.0.1:7001/local-assets/crop_abc.png">'+ '<img src="/local-assets/missing.png">'+ '<div style="background: url(/local-assets/crop_abc.png)"></div></html>'+ )+ recorder = _make_recorder()+ recorder.record_run_start(Llm.GPT_5_5_HIGH, [])+ await recorder.record_run_end("completed", final_html=html)++ run_dir = Path(recorder.run_dir)+ assert (run_dir / "final.html").read_text() == html+ assert (run_dir / "assets" / "crop_abc.png").read_bytes() == b"png-bytes"++ rewritten = (run_dir / "final_selfcontained.html").read_text()+ assert "assets/crop_abc.png" in rewritten+ assert "http://127.0.0.1:7001/local-assets/" not in rewritten+ assert "url(assets/crop_abc.png)" in rewritten++ manifest = json.loads((run_dir / "assets_manifest.json").read_text())+ statuses = {entry["url"]: entry["status"] for entry in manifest}+ assert statuses["http://127.0.0.1:7001/local-assets/crop_abc.png"] == "copied"+ assert statuses["/local-assets/missing.png"] == "missing"+++async def test_asset_snapshot_downloads_remote_images(+ logs_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ class FakeResponse:+ content = b"remote-image-bytes"+ headers = {"content-type": "image/png"}++ def raise_for_status(self) -> None:+ return None++ class FakeClient:+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ self.requested: list[str] = []++ async def __aenter__(self) -> "FakeClient":+ return self++ async def __aexit__(self, *args: Any) -> None:+ return None++ async def get(self, url: str) -> FakeResponse:+ self.requested.append(url)+ if "broken" in url:+ raise RuntimeError("download failed")+ return FakeResponse()++ import httpx++ monkeypatch.setattr(httpx, "AsyncClient", FakeClient)++ html = (+ '<html><img src="https://replicate.delivery/xyz/generated">'+ '<img src="https://example.com/broken.png"></html>'+ )+ recorder = _make_recorder()+ recorder.record_run_start(Llm.GPT_5_5_HIGH, [])+ await recorder.record_run_end("completed", final_html=html)++ run_dir = Path(recorder.run_dir)+ manifest = json.loads((run_dir / "assets_manifest.json").read_text())+ by_url = {entry["url"]: entry for entry in manifest}+ ok_entry = by_url["https://replicate.delivery/xyz/generated"]+ assert ok_entry["status"] == "downloaded"+ saved = run_dir / ok_entry["file"]+ assert saved.read_bytes() == b"remote-image-bytes"+ assert by_url["https://example.com/broken.png"]["status"] == "failed"++ rewritten = (run_dir / "final_selfcontained.html").read_text()+ assert "https://replicate.delivery/xyz/generated" not in rewritten+ # Failed downloads keep their original URL.+ assert "https://example.com/broken.png" in rewritten+++class _ToolThenDoneSession:+ """One create_file tool turn, then a final assistant turn."""++ def __init__(self) -> None:+ self.turns = 0+ self.closed = False++ async def stream_turn(self, on_event: Any) -> Any:+ from agent.providers.base import ProviderTurn, StreamEvent++ self.turns += 1+ if self.turns == 1:+ await on_event(StreamEvent(type="thinking_delta", text="planning"))+ return ProviderTurn(+ assistant_text="",+ tool_calls=[+ ToolCall(+ id="call_1",+ name="create_file",+ arguments={+ "path": "index.html",+ "content": "<html>from tool</html>",+ },+ )+ ],+ )+ return ProviderTurn(assistant_text="done", tool_calls=[])++ async def append_tool_results(self, turn: Any, executed_tool_calls: Any) -> None:+ return None++ async def close(self) -> None:+ self.closed = True+++class _ExplodingSession:+ async def stream_turn(self, on_event: Any) -> Any:+ raise RuntimeError("provider exploded")++ async def append_tool_results(self, turn: Any, executed_tool_calls: Any) -> None:+ return None++ async def close(self) -> None:+ return None+++def _make_engine(recorder: AgentRunRecorder) -> Any:+ from agent.engine import AgentEngine++ async def send_message(+ message_type: str,+ value: Optional[str],+ variant_index: int,+ data: Optional[dict[str, Any]],+ event_id: Optional[str],+ ) -> None:+ return None++ return AgentEngine(+ send_message=send_message,+ variant_index=0,+ openai_api_key="key",+ openai_base_url=None,+ anthropic_api_key=None,+ gemini_api_key=None,+ replicate_api_key=None,+ should_generate_images=False,+ recorder=recorder,+ )+++async def test_engine_records_full_run(+ logs_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ session = _ToolThenDoneSession()+ monkeypatch.setattr(+ "agent.engine.create_provider_session", lambda **kwargs: session+ )++ recorder = _make_recorder()+ engine = _make_engine(recorder)+ result = await engine.run(+ Llm.GPT_5_5_HIGH, [{"role": "user", "content": "build it"}] # type: ignore[list-item]+ )++ assert result == "<html>from tool</html>"+ events = _read_events(recorder)+ types = [e["type"] for e in events]+ assert types[0] == "run_start"+ assert "stream_delta" in types+ assert "tool_call_start" in types and "tool_call_end" in types+ assert types[-1] == "run_end"+ assert events[-1]["status"] == "completed"+ assert events[-1]["num_tool_calls"] == 1++ tool_end = next(e for e in events if e["type"] == "tool_call_end")+ assert tool_end["name"] == "create_file"+ assert tool_end["ok"] is True++ row = _db_row("SELECT status FROM runs WHERE run_id = ?", (recorder.run_id,))+ assert row == ("completed",)+ assert (Path(recorder.run_dir) / "final.html").read_text() == (+ "<html>from tool</html>"+ )+++async def test_engine_records_failed_run_and_reraises(+ logs_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(+ "agent.engine.create_provider_session",+ lambda **kwargs: _ExplodingSession(),+ )++ recorder = _make_recorder()+ engine = _make_engine(recorder)+ with pytest.raises(RuntimeError, match="provider exploded"):+ await engine.run(Llm.GPT_5_5_HIGH, [])++ events = _read_events(recorder)+ assert events[-1]["type"] == "run_end"+ assert events[-1]["status"] == "failed"+ assert "provider exploded" in events[-1]["error"]++ row = _db_row(+ "SELECT status, error FROM runs WHERE run_id = ?", (recorder.run_id,)+ )+ assert row is not None+ assert row[0] == "failed"+ assert "provider exploded" in row[1]+++async def _record_minimal_run(**overrides: Any) -> AgentRunRecorder:+ recorder = _make_recorder(**overrides)+ recorder.record_run_start(Llm.GPT_5_5_HIGH, [{"role": "user", "content": "go"}])+ recorder.record_llm_request("openai", "gpt-5.5", {"input": ["go"]})+ recorder.record_llm_response(+ "done", [], TokenUsage(input=100, output=50, total=150)+ )+ await recorder.record_run_end("completed", final_html="<html>out</html>")+ return recorder+++async def test_list_and_detail_routes(logs_path: Path) -> None:+ from routes.agent_runs import get_agent_run, list_agent_runs++ recorder_a = await _record_minimal_run(variant_index=0)+ recorder_b = await _record_minimal_run(+ variant_index=1, generation_id="gen_test_11111111"+ )++ listing = await list_agent_runs()+ assert {r.run_id for r in listing.runs} == {recorder_a.run_id, recorder_b.run_id}+ assert listing.total_size_bytes > 0+ by_id = {r.run_id: r for r in listing.runs}+ assert by_id[recorder_a.run_id].generation_id == "gen_test_00000000"+ assert by_id[recorder_a.run_id].status == "completed"+ assert by_id[recorder_a.run_id].num_llm_calls == 1+ assert by_id[recorder_a.run_id].total_cost_usd is not None++ detail = await get_agent_run(recorder_a.run_id)+ types = [e["type"] for e in detail.events]+ assert "run_start" in types and "llm_call_end" in types and "run_end" in types+ assert "stream_delta" not in types++ recorder_c = _make_recorder()+ recorder_c.record_run_start(Llm.GPT_5_5_HIGH, [])+ recorder_c.record_llm_request("openai", "gpt-5.5", {})+ recorder_c.record_stream_event(+ StreamEvent(type="assistant_delta", text="hi"), "a-1"+ )+ recorder_c.record_llm_response("hi", [], None)+ await recorder_c.record_run_end("completed")+ detail_with_deltas = await get_agent_run(+ recorder_c.run_id, include_stream_deltas=True+ )+ assert "stream_delta" in [e["type"] for e in detail_with_deltas.events]+++async def test_detail_route_rejects_bad_ids(logs_path: Path) -> None:+ from fastapi import HTTPException++ from routes.agent_runs import get_agent_run, list_agent_runs++ listing = await list_agent_runs()+ assert listing.runs == []++ with pytest.raises(HTTPException) as excinfo:+ await get_agent_run("../secrets")+ assert excinfo.value.status_code == 400++ await _record_minimal_run()+ with pytest.raises(HTTPException) as excinfo:+ await get_agent_run("run_20260101_000000_deadbeef")+ assert excinfo.value.status_code == 404+++async def test_output_and_asset_routes(logs_path: Path) -> None:+ from fastapi import HTTPException++ from routes.agent_runs import get_agent_run_asset, get_agent_run_output++ recorder = await _record_minimal_run()+ (Path(recorder.run_dir) / "assets").mkdir(exist_ok=True)+ (Path(recorder.run_dir) / "assets" / "pic.png").write_bytes(b"img")++ response = await get_agent_run_output(recorder.run_id)+ assert bytes(response.body).decode() == "<html>out</html>"++ asset_response = await get_agent_run_asset(recorder.run_id, "pic.png")+ assert asset_response.path == str(Path(recorder.run_dir) / "assets" / "pic.png")++ with pytest.raises(HTTPException) as excinfo:+ await get_agent_run_asset(recorder.run_id, "nope.png")+ assert excinfo.value.status_code == 404+++async def test_prune_removes_old_runs_and_keeps_index(logs_path: Path) -> None:+ import os++ from routes.agent_runs import (+ PruneAgentRunsRequest,+ list_agent_runs,+ prune_agent_runs,+ )++ old_recorder = await _record_minimal_run()+ fresh_recorder = await _record_minimal_run(generation_id="gen_test_22222222")++ ninety_days_ago = 90 * 24 * 3600+ old_time = __import__("time").time() - ninety_days_ago+ os.utime(old_recorder.run_dir, (old_time, old_time))++ result = await prune_agent_runs(PruneAgentRunsRequest(max_age_days=7))+ assert result.deleted_count == 1+ assert result.freed_bytes > 0+ assert not Path(old_recorder.run_dir).exists()+ assert Path(fresh_recorder.run_dir).exists()+ assert Path(get_agent_runs_db_path()).exists()++ listing = await list_agent_runs()+ assert [r.run_id for r in listing.runs] == [fresh_recorder.run_id]++ # Orphan rows (directory removed out-of-band) get cleaned up too.+ import shutil as _shutil++ _shutil.rmtree(fresh_recorder.run_dir)+ await prune_agent_runs(PruneAgentRunsRequest(max_age_days=7))+ listing = await list_agent_runs()+ assert listing.runs == []+++async def test_prompt_reports_prune_skips_agent_runs(logs_path: Path) -> None:+ import os++ from routes.prompt_reports import (+ PrunePromptReportsRequest,+ prune_prompt_reports,+ )++ recorder = await _record_minimal_run()++ ninety_days_ago = 90 * 24 * 3600+ old_time = __import__("time").time() - ninety_days_ago+ agent_runs_dir = Path(get_agent_runs_directory())+ os.utime(agent_runs_dir, (old_time, old_time))+ os.utime(recorder.run_dir, (old_time, old_time))++ result = await prune_prompt_reports(PrunePromptReportsRequest(max_age_days=7))+ assert result.deleted_count == 0+ assert Path(recorder.run_dir).exists()+ assert Path(get_agent_runs_db_path()).exists()+++def test_recorder_survives_internal_errors(logs_path: Path) -> None:+ recorder = _make_recorder()+ recorder.record_run_start(Llm.GPT_5_5_HIGH, [])+ # Unserializable-ish payloads and bad state must not raise.+ recorder.record_llm_request("openai", "gpt-5.5", {"obj": object()})+ recorder.record_llm_response("x", [], TokenUsage())+++def test_agent_runs_directory_under_logs_path(logs_path: Path) -> None:+ assert get_agent_runs_directory() == str(logs_path / "run_logs" / "agent_runs")diff --git a/frontend/src/components/evals/AgentRunsPage.tsx b/frontend/src/components/evals/AgentRunsPage.tsxnew file mode 100644index 00000000..d035cfcd--- /dev/null+++ b/frontend/src/components/evals/AgentRunsPage.tsx@@ -0,0 +1,534 @@+import { useCallback, useEffect, useMemo, useState } from "react";+import toast from "react-hot-toast";+import { BsBoxArrowUpRight } from "react-icons/bs";++import { HTTP_BACKEND_URL } from "../../config";+import EvalNavigation from "./EvalNavigation";+import AgentRunTimeline, {+ ExpandMode,+ ExpandSignal,+ RunEvent,+ TimelineViewMode,+} from "./agent-run-timeline";+import { LightboxProvider } from "./image-lightbox";+import {+ formatBytes,+ formatCost,+ formatMs,+ formatTimestamp,+ providerBadgeClass,+} from "./report-format";++interface AgentRunSummary {+ run_id: string;+ generation_id: string;+ variant_index: number;+ entry_point: string;+ provider: string | null;+ model: string | null;+ api_model_name: string | null;+ stack: string | null;+ input_mode: string | null;+ generation_type: string | null;+ status: string;+ error: string | null;+ created_at: string;+ completed_at: string | null;+ total_duration_ms: number | null;+ llm_time_ms: number | null;+ tool_time_ms: number | null;+ num_llm_calls: number;+ num_tool_calls: number;+ input_tokens: number | null;+ output_tokens: number | null;+ cache_read_tokens: number | null;+ cache_write_tokens: number | null;+ total_tokens: number | null;+ total_cost_usd: number | null;+ has_unpriced_calls: boolean;+ size_bytes: number | null;+}++interface AgentRunListResponse {+ runs: AgentRunSummary[];+ total_size_bytes: number;+ runs_directory: string;+}++interface AgentRunDetailResponse {+ run: AgentRunSummary;+ events: RunEvent[];+}++interface GenerationGroup {+ generationId: string;+ entryPoint: string;+ createdAt: string;+ costUsd: number | null;+ runs: AgentRunSummary[];+}++function groupByGeneration(runs: AgentRunSummary[]): GenerationGroup[] {+ const groups = new Map<string, GenerationGroup>();+ for (const run of runs) {+ let group = groups.get(run.generation_id);+ if (!group) {+ group = {+ generationId: run.generation_id,+ entryPoint: run.entry_point,+ createdAt: run.created_at,+ costUsd: null,+ runs: [],+ };+ groups.set(run.generation_id, group);+ }+ if (typeof run.total_cost_usd === "number") {+ group.costUsd = (group.costUsd ?? 0) + run.total_cost_usd;+ }+ if (run.created_at > group.createdAt) group.createdAt = run.created_at;+ group.runs.push(run);+ }+ const result = [...groups.values()];+ for (const group of result) {+ group.runs.sort((a, b) => a.variant_index - b.variant_index);+ }+ result.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));+ return result;+}++function statusDotClass(status: string): string {+ if (status === "completed") return "bg-emerald-400";+ if (status === "failed") return "bg-red-400";+ return "bg-amber-400 animate-pulse";+}++function runOutputUrl(runId: string): string {+ return `${HTTP_BACKEND_URL}/agent-runs/${encodeURIComponent(runId)}/output`;+}++function StatChip({ label, value }: { label: string; value: string }) {+ return (+ <span className="whitespace-nowrap">+ <span className="font-mono text-zinc-100">{value}</span>{" "}+ <span className="text-zinc-500">{label}</span>+ </span>+ );+}++function SummaryStats({ run }: { run: AgentRunSummary }) {+ const costLabel =+ formatCost(run.total_cost_usd) + (run.has_unpriced_calls ? "*" : "");+ return (+ <div+ className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg border border-zinc-800 bg-zinc-950 px-2.5 py-1.5 text-xs"+ title={+ run.has_unpriced_calls+ ? "* some calls had no pricing entry; the true cost is higher"+ : undefined+ }+ >+ <StatChip label="cost" value={costLabel} />+ <StatChip label="total" value={formatMs(run.total_duration_ms)} />+ <StatChip label="llm" value={formatMs(run.llm_time_ms)} />+ <StatChip label="tools" value={formatMs(run.tool_time_ms)} />+ <StatChip label="llm calls" value={String(run.num_llm_calls)} />+ <StatChip label="tool calls" value={String(run.num_tool_calls)} />+ <StatChip label="in" value={(run.input_tokens ?? 0).toLocaleString()} />+ <StatChip label="out" value={(run.output_tokens ?? 0).toLocaleString()} />+ <StatChip+ label="cache read"+ value={(run.cache_read_tokens ?? 0).toLocaleString()}+ />+ <StatChip+ label="total tok"+ value={(run.total_tokens ?? 0).toLocaleString()}+ />+ </div>+ );+}++function AgentRunsPage() {+ const [runs, setRuns] = useState<AgentRunSummary[]>([]);+ const [totalSizeBytes, setTotalSizeBytes] = useState(0);+ const [runsDirectory, setRunsDirectory] = useState("");+ const [selectedRunId, setSelectedRunId] = useState<string | null>(null);+ const [detail, setDetail] = useState<AgentRunDetailResponse | null>(null);+ const [activeTab, setActiveTab] = useState<"timeline" | "output" | "raw">(+ "timeline"+ );+ const [viewMode, setViewMode] = useState<TimelineViewMode>("readable");+ const [expandSignal, setExpandSignal] = useState<ExpandSignal>({+ mode: "best",+ version: 0,+ });+ const [includeDeltas, setIncludeDeltas] = useState(false);+ const [isLoadingList, setIsLoadingList] = useState(true);+ const [isLoadingDetail, setIsLoadingDetail] = useState(false);+ const [isPruning, setIsPruning] = useState(false);++ const generationGroups = useMemo(() => groupByGeneration(runs), [runs]);++ const fetchRuns = useCallback(async (): Promise<AgentRunSummary[]> => {+ setIsLoadingList(true);+ try {+ const response = await fetch(`${HTTP_BACKEND_URL}/agent-runs`);+ const data: AgentRunListResponse = await response.json();+ setRuns(data.runs);+ setTotalSizeBytes(data.total_size_bytes);+ setRunsDirectory(data.runs_directory);+ return data.runs;+ } catch (error) {+ console.error("Error fetching agent runs", error);+ toast.error("Failed to load agent runs.");+ return [];+ } finally {+ setIsLoadingList(false);+ }+ }, []);++ const openRun = useCallback(+ async (runId: string, withDeltas: boolean = false) => {+ setSelectedRunId(runId);+ setActiveTab("timeline");+ setIncludeDeltas(withDeltas);+ setExpandSignal({ mode: "best", version: 0 });+ setIsLoadingDetail(true);+ try {+ const response = await fetch(+ `${HTTP_BACKEND_URL}/agent-runs/${encodeURIComponent(+ runId+ )}?include_stream_deltas=${withDeltas}`+ );+ if (!response.ok) {+ const data = await response.json();+ throw new Error(data.detail || "Request failed");+ }+ setDetail(await response.json());+ } catch (error) {+ console.error("Error fetching run detail", error);+ setDetail(null);+ toast.error("Failed to load run.");+ } finally {+ setIsLoadingDetail(false);+ }+ },+ []+ );++ useEffect(() => {+ fetchRuns().then((loadedRuns) => {+ if (loadedRuns.length > 0) {+ const groups = groupByGeneration(loadedRuns);+ openRun(groups[0].runs[0].run_id);+ }+ });+ }, [fetchRuns, openRun]);++ const handlePrune = async () => {+ if (!window.confirm("Delete all recorded runs older than 7 days?")) {+ return;+ }+ setIsPruning(true);+ try {+ const response = await fetch(`${HTTP_BACKEND_URL}/agent-runs/prune`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ max_age_days: 7 }),+ });+ if (!response.ok) throw new Error("Prune request failed");+ const data = await response.json();+ toast.success(+ `Pruned ${data.deleted_count} run${+ data.deleted_count === 1 ? "" : "s"+ }, freed ${formatBytes(data.freed_bytes)}.`,+ { duration: 8000 }+ );+ const refreshed = await fetchRuns();+ if (+ selectedRunId &&+ !refreshed.some((run) => run.run_id === selectedRunId)+ ) {+ setSelectedRunId(null);+ setDetail(null);+ }+ } catch (error) {+ console.error("Error pruning agent runs", error);+ toast.error("Failed to prune runs.");+ } finally {+ setIsPruning(false);+ }+ };++ const selectedRun = detail?.run ?? null;++ return (+ <div className="flex h-screen flex-col overflow-hidden bg-zinc-950 text-white">+ <div className="shrink-0">+ <EvalNavigation />+ </div>+ <div className="mx-auto flex min-h-0 w-full max-w-[1600px] flex-1 flex-col gap-2 px-4 py-2">+ <div className="flex shrink-0 flex-wrap items-center justify-between gap-2 rounded-xl border border-zinc-800 bg-zinc-900/80 px-4 py-2">+ <div className="flex min-w-0 items-baseline gap-3">+ <h1 className="text-base font-semibold tracking-tight">+ Agent Runs+ </h1>+ {runsDirectory && (+ <span+ className="hidden truncate font-mono text-[11px] text-zinc-500 md:inline"+ title={runsDirectory}+ >+ {runsDirectory}+ </span>+ )}+ </div>+ <div className="flex items-center gap-2 text-xs">+ <span className="font-mono text-zinc-400">+ {formatBytes(totalSizeBytes)}+ </span>+ <button+ onClick={handlePrune}+ disabled={isPruning}+ className="rounded-md border border-red-800 bg-red-950/60 px-2 py-1 text-red-200 transition-colors hover:bg-red-900/60 disabled:opacity-50"+ >+ {isPruning ? "Pruning…" : "Prune >7d"}+ </button>+ </div>+ </div>++ <div className="grid min-h-0 flex-1 gap-3 lg:grid-cols-[340px_minmax(0,1fr)]">+ <section className="min-h-0 overflow-y-auto rounded-xl border border-zinc-800 bg-zinc-900/60 p-2">+ <div className="px-2 py-1 text-xs uppercase tracking-wide text-zinc-500">+ {isLoadingList+ ? "Loading…"+ : `${generationGroups.length} generation${+ generationGroups.length === 1 ? "" : "s"+ } · ${runs.length} run${runs.length === 1 ? "" : "s"}`}+ </div>+ {!isLoadingList && runs.length === 0 && (+ <p className="px-2 py-4 text-sm text-zinc-400">+ No runs yet. Start the backend with{" "}+ <code className="rounded bg-zinc-800 px-1 py-0.5">+ PROMPT_REPORTS_ENABLED=1+ </code>{" "}+ and generate some code.+ </p>+ )}+ {generationGroups.map((group) => (+ <div+ key={group.generationId}+ className="mb-2 rounded-xl border border-zinc-800 bg-zinc-950/50 px-3 py-2"+ >+ <div className="flex items-center justify-between gap-2">+ <span className="rounded-full border border-zinc-600 bg-zinc-800 px-2 py-0.5 text-[11px] text-zinc-200">+ {group.entryPoint}+ </span>+ <span className="text-[11px] text-zinc-500">+ {formatTimestamp(group.createdAt)}+ </span>+ <span+ className="font-mono text-[11px] font-medium text-emerald-400"+ title="Total cost across all variants"+ >+ {formatCost(group.costUsd)}+ </span>+ </div>+ <div className="mt-2 flex flex-col gap-1">+ {group.runs.map((run) => (+ <div+ key={run.run_id}+ onClick={() => openRun(run.run_id)}+ className={`flex cursor-pointer items-center gap-2 rounded-lg border px-2 py-1.5 text-left text-xs transition-colors ${+ run.run_id === selectedRunId+ ? "border-blue-600 bg-blue-950/60 text-blue-100"+ : "border-zinc-700 text-zinc-300 hover:bg-zinc-800"+ }`}+ >+ <span+ className={`h-2 w-2 shrink-0 rounded-full ${statusDotClass(+ run.status+ )}`}+ />+ <span className="shrink-0 font-mono text-zinc-500">+ v{run.variant_index}+ </span>+ <span className="min-w-0 flex-1 truncate font-mono">+ {run.model ?? "unknown"}+ </span>+ <span className="shrink-0 font-mono text-zinc-500">+ {formatMs(run.total_duration_ms)}+ </span>+ <a+ href={runOutputUrl(run.run_id)}+ target="_blank"+ rel="noreferrer"+ onClick={(e) => e.stopPropagation()}+ title="Open captured HTML in a new tab"+ className="shrink-0 rounded p-1 text-zinc-500 hover:bg-zinc-700 hover:text-zinc-200"+ >+ <BsBoxArrowUpRight />+ </a>+ </div>+ ))}+ </div>+ </div>+ ))}+ </section>++ <section className="min-h-0 overflow-y-auto rounded-xl border border-zinc-800 bg-zinc-900/60 p-3">+ {!selectedRunId && (+ <p className="py-8 text-center text-sm text-zinc-400">+ Select a run to inspect it.+ </p>+ )}+ {selectedRunId && isLoadingDetail && (+ <p className="py-8 text-center text-sm text-zinc-400">+ Loading run…+ </p>+ )}+ {selectedRunId && !isLoadingDetail && detail && selectedRun && (+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap items-center gap-2 text-xs">+ {selectedRun.provider && (+ <span+ className={`rounded-full border px-2 py-0.5 ${providerBadgeClass(+ selectedRun.provider+ )}`}+ >+ {selectedRun.provider}+ </span>+ )}+ <span className="font-mono text-sm text-zinc-100">+ {selectedRun.model}+ </span>+ <span className="font-mono text-[11px] text-zinc-500">+ {selectedRun.stack} · {selectedRun.generation_type} · v+ {selectedRun.variant_index} ·{" "}+ {formatTimestamp(selectedRun.created_at)}+ </span>+ <a+ href={runOutputUrl(selectedRun.run_id)}+ target="_blank"+ rel="noreferrer"+ className="ml-auto flex items-center gap-1.5 rounded-md border border-zinc-700 px-2 py-1 text-zinc-300 transition-colors hover:bg-zinc-800"+ >+ <BsBoxArrowUpRight /> Open HTML+ </a>+ </div>++ {selectedRun.status === "failed" && (+ <div className="rounded-lg border border-red-900 bg-red-950/40 px-2.5 py-1.5 font-mono text-xs text-red-200">+ {selectedRun.error ?? "Run failed"}+ </div>+ )}++ <SummaryStats run={selectedRun} />++ <div className="flex flex-wrap items-center gap-2 border-b border-zinc-800 pb-2 text-xs">+ {(["timeline", "output", "raw"] as const).map((tab) => (+ <button+ key={tab}+ onClick={() => setActiveTab(tab)}+ className={`rounded-md px-2.5 py-1 capitalize transition-colors ${+ activeTab === tab+ ? "bg-zinc-800 text-zinc-100"+ : "text-zinc-400 hover:text-zinc-200"+ }`}+ >+ {tab === "raw" ? "Raw events" : tab}+ </button>+ ))}+ {activeTab === "timeline" && (+ <>+ <div className="mx-1 h-4 w-px bg-zinc-800" />+ <div className="flex overflow-hidden rounded-md border border-zinc-700">+ {(["readable", "raw"] as const).map((mode) => (+ <button+ key={mode}+ onClick={() => setViewMode(mode)}+ className={`px-2.5 py-1 capitalize transition-colors ${+ viewMode === mode+ ? "bg-zinc-700 text-zinc-100"+ : "text-zinc-400 hover:text-zinc-200"+ }`}+ >+ {mode}+ </button>+ ))}+ </div>+ <div className="flex overflow-hidden rounded-md border border-zinc-700">+ {(+ [+ ["expand", "Expanded"],+ ["best", "Best"],+ ["collapse", "Collapsed"],+ ] as [ExpandMode, string][]+ ).map(([mode, label]) => (+ <button+ key={mode}+ title={+ mode === "best"+ ? "Everything open except create_file / edit_file"+ : undefined+ }+ onClick={() =>+ setExpandSignal((s) => ({+ mode,+ version: s.version + 1,+ }))+ }+ className={`px-2.5 py-1 transition-colors ${+ expandSignal.mode === mode+ ? "bg-zinc-700 text-zinc-100"+ : "text-zinc-400 hover:text-zinc-200"+ }`}+ >+ {label}+ </button>+ ))}+ </div>+ <label className="ml-auto flex items-center gap-1.5 text-zinc-400">+ <input+ type="checkbox"+ checked={includeDeltas}+ onChange={(e) =>+ openRun(selectedRunId, e.target.checked)+ }+ />+ stream deltas+ </label>+ </>+ )}+ </div>++ {activeTab === "timeline" && (+ <LightboxProvider>+ <AgentRunTimeline+ key={`${selectedRunId}-${viewMode}`}+ events={detail.events}+ viewMode={viewMode}+ expandSignal={expandSignal}+ />+ </LightboxProvider>+ )}+ {activeTab === "output" && (+ <iframe+ title="Captured final output"+ src={runOutputUrl(selectedRunId)}+ className="h-[75vh] w-full rounded-xl border border-zinc-800 bg-white"+ />+ )}+ {activeTab === "raw" && (+ <pre className="overflow-x-auto whitespace-pre-wrap break-all rounded-lg bg-zinc-950 p-3 text-xs text-zinc-300">+ {JSON.stringify(detail.events, null, 2)}+ </pre>+ )}+ </div>+ )}+ </section>+ </div>+ </div>+ </div>+ );+}++export default AgentRunsPage;diff --git a/frontend/src/components/evals/EvalNavigation.tsx b/frontend/src/components/evals/EvalNavigation.tsxindex 079fefcd..635f2b5e 100644--- a/frontend/src/components/evals/EvalNavigation.tsx+++ b/frontend/src/components/evals/EvalNavigation.tsx@@ -40,6 +40,13 @@ function EvalNavigation() {>Prompt Reports</Link>++ <Link+ to="/evals/agent-runs"+ className="hover:text-blue-300 transition-colors"+ >+ Agent Runs+ </Link></div><Linkdiff --git a/frontend/src/components/evals/PromptReportsPage.tsx b/frontend/src/components/evals/PromptReportsPage.tsxindex 97468729..bf2a203b 100644--- a/frontend/src/components/evals/PromptReportsPage.tsx+++ b/frontend/src/components/evals/PromptReportsPage.tsx@@ -1,9 +1,15 @@import { useCallback, useEffect, useMemo, useState } from "react";import toast from "react-hot-toast";-import Markdown from "react-markdown";import { HTTP_BACKEND_URL } from "../../config";import EvalNavigation from "./EvalNavigation";+import {+ formatBytes,+ formatCost,+ formatTimestamp,+ providerBadgeClass,+} from "./report-format";+import { JsonNode } from "./report-json";interface PromptReportSummary {filename: string;@@ -53,44 +59,6 @@ interface SessionGroup {turns: PromptReportSummary[];}-const PROVIDER_BADGE_CLASSES: Record<string, string> = {- openai: "bg-emerald-900/60 text-emerald-200 border-emerald-700",- anthropic: "bg-orange-900/60 text-orange-200 border-orange-700",- gemini: "bg-sky-900/60 text-sky-200 border-sky-700",-};--function providerBadgeClass(provider: string): string {- return (- PROVIDER_BADGE_CLASSES[provider] ||- "bg-zinc-800 text-zinc-200 border-zinc-600"- );-}--function formatBytes(bytes: number): string {- if (bytes < 1024) return `${bytes} B`;- const units = ["KB", "MB", "GB", "TB"];- let value = bytes;- let unitIndex = -1;- do {- value /= 1024;- unitIndex += 1;- } while (value >= 1024 && unitIndex < units.length - 1);- return `${value.toFixed(value >= 100 ? 0 : 1)} ${units[unitIndex]}`;-}--function formatTimestamp(isoTimestamp: string): string {- const date = new Date(isoTimestamp);- if (isNaN(date.getTime())) return isoTimestamp;- return date.toLocaleString();-}--function formatCost(costUsd: number | null): string {- if (costUsd === null) return "—";- // Round to cents; flag sub-cent totals so a real cost never reads as $0.00.- if (costUsd > 0 && costUsd < 0.01) return "<$0.01";- return `$${costUsd.toFixed(2)}`;-}-function groupBySession(reports: PromptReportSummary[]): SessionGroup[] {const groups = new Map<string, SessionGroup>();for (const report of reports) {@@ -124,257 +92,6 @@ function groupBySession(reports: PromptReportSummary[]): SessionGroup[] {return result;}-interface MediaInfo {- src: string;- kind: "image" | "video";-}--// Pydantic's JSON mode emits URL-safe base64; data: URLs need the standard-// alphabet. Normalize so reports written before the writer fix still render.-function normalizeBase64(data: string): string {- return data.replace(/-/g, "+").replace(/_/g, "/");-}--// Detects renderable media in a JSON value: either a data URL string or an-// object shaped like {data: <base64>, mime_type|media_type: image/*|video/*}.-function mediaFromValue(value: unknown): MediaInfo | null {- if (typeof value === "string") {- if (value.startsWith("data:image/")) return { src: value, kind: "image" };- if (value.startsWith("data:video/")) return { src: value, kind: "video" };- return null;- }-- if (typeof value === "object" && value !== null && !Array.isArray(value)) {- const record = value as Record<string, unknown>;- const mime = record["mime_type"] ?? record["media_type"];- const data = record["data"];- if (- typeof mime === "string" &&- typeof data === "string" &&- data.length > 0- ) {- if (mime.startsWith("image/") || mime.startsWith("video/")) {- return {- src: `data:${mime};base64,${normalizeBase64(data)}`,- kind: mime.startsWith("image/") ? "image" : "video",- };- }- }- }-- return null;-}--function MediaPreview({ media }: { media: MediaInfo }) {- if (media.kind === "video") {- return (- <video- src={media.src}- controls- className="my-1 max-h-48 rounded-lg border border-zinc-700"- />- );- }- return (- <a href={media.src} target="_blank" rel="noreferrer">- <img- src={media.src}- alt="embedded media"- className="my-1 max-h-48 rounded-lg border border-zinc-700 bg-white object-contain"- />- </a>- );-}--function nodeSummary(value: unknown): string {- if (Array.isArray(value)) {- return `array · ${value.length} item${value.length === 1 ? "" : "s"}`;- }- if (typeof value === "object" && value !== null) {- const keyCount = Object.keys(value).length;- return `object · ${keyCount} key${keyCount === 1 ? "" : "s"}`;- }- return typeof value;-}--const LONG_STRING_PREVIEW_CHARS = 280;-const MARKDOWN_MAX_CHARS = 20000;-// Object keys whose string values are prompt/message prose — rendered as-// markdown instead of a raw string.-const PROSE_KEYS = new Set([- "text",- "content",- "system",- "system_instruction",- "instructions",-]);--const MARKDOWN_STYLES = [- "[&_h1]:mt-3 [&_h1]:text-base [&_h1]:font-bold",- "[&_h2]:mt-3 [&_h2]:text-sm [&_h2]:font-bold",- "[&_h3]:mt-2 [&_h3]:text-sm [&_h3]:font-semibold",- "[&_p]:my-1.5",- "[&_ul]:my-1.5 [&_ul]:list-disc [&_ul]:pl-5",- "[&_ol]:my-1.5 [&_ol]:list-decimal [&_ol]:pl-5",- "[&_li]:my-0.5",- "[&_code]:rounded [&_code]:bg-zinc-800 [&_code]:px-1 [&_code]:text-[11px] [&_code]:text-amber-100",- "[&_pre]:my-2 [&_pre]:overflow-x-auto [&_pre]:rounded [&_pre]:bg-zinc-900 [&_pre]:p-2",- "[&_a]:text-blue-400 [&_a]:underline",- "[&_blockquote]:border-l-2 [&_blockquote]:border-zinc-700 [&_blockquote]:pl-3 [&_blockquote]:text-zinc-400",-].join(" ");--function MarkdownLeaf({ text }: { text: string }) {- const [showRaw, setShowRaw] = useState(false);- return (- <div className="min-w-0 flex-1">- <div className="mt-1 max-h-96 overflow-y-auto rounded-lg border border-zinc-800 bg-zinc-950 p-3">- {showRaw ? (- <pre className="whitespace-pre-wrap break-all text-xs text-amber-100">- {text}- </pre>- ) : (- <div className={`text-xs leading-5 text-zinc-200 ${MARKDOWN_STYLES}`}>- <Markdown>{text}</Markdown>- </div>- )}- </div>- <button- onClick={() => setShowRaw(!showRaw)}- className="mt-1 text-xs text-blue-400 hover:text-blue-300"- >- {showRaw ? "Show rendered" : "Show raw"}- </button>- </div>- );-}--function StringLeaf({ text }: { text: string }) {- const [expanded, setExpanded] = useState(false);-- if (text.length <= LONG_STRING_PREVIEW_CHARS) {- return (- <code className="whitespace-pre-wrap break-all rounded bg-zinc-800 px-1.5 py-0.5 text-xs text-amber-100">- {text}- </code>- );- }-- return (- <div className="min-w-0">- <pre className="mt-1 max-h-96 overflow-auto whitespace-pre-wrap break-all rounded-lg border border-zinc-800 bg-zinc-950 p-2 text-xs text-amber-100">- {expanded ? text : `${text.slice(0, LONG_STRING_PREVIEW_CHARS)}…`}- </pre>- <button- onClick={() => setExpanded(!expanded)}- className="mt-1 text-xs text-blue-400 hover:text-blue-300"- >- {expanded- ? "Collapse"- : `Show all ${text.length.toLocaleString()} chars`}- </button>- </div>- );-}--function ScalarLeaf({ label, value }: { label: string; value: unknown }) {- if (typeof value === "string") {- if (- PROSE_KEYS.has(label) &&- value.length > 80 &&- value.length <= MARKDOWN_MAX_CHARS- ) {- return <MarkdownLeaf text={value} />;- }- return <StringLeaf text={value} />;- }- return (- <code className="rounded bg-zinc-800 px-1.5 py-0.5 text-xs text-teal-300">- {value === null ? "null" : String(value)}- </code>- );-}--// Arrays under these keys hold tool definitions: collapse them by default and-// label each entry with the tool's name so the list scans as a name index.-const TOOL_ARRAY_KEYS = new Set(["tools", "function_declarations"]);--function toolEntryName(value: unknown): string | null {- if (typeof value !== "object" || value === null || Array.isArray(value)) {- return null;- }- const name = (value as Record<string, unknown>)["name"];- return typeof name === "string" ? name : null;-}--function JsonNode({- label,- value,- depth,- defaultOpen,-}: {- label: string;- value: unknown;- depth: number;- defaultOpen?: boolean;-}) {- const [open, setOpen] = useState(defaultOpen ?? depth < 5);- const media = mediaFromValue(value);- const isContainer =- typeof value === "object" && value !== null && !(media && !open);-- if (!isContainer || typeof value !== "object" || value === null) {- return (- <div className="flex min-w-0 items-start gap-2 py-0.5">- <span className="shrink-0 font-mono text-xs text-violet-300">- {label}:- </span>- {media ? (- <MediaPreview media={media} />- ) : (- <ScalarLeaf label={label} value={value} />- )}- </div>- );- }-- const isToolArray = TOOL_ARRAY_KEYS.has(label) && Array.isArray(value);- const entries: [string, unknown, boolean][] = Array.isArray(value)- ? value.map((child, index) => {- const toolName = isToolArray ? toolEntryName(child) : null;- return [toolName ?? `[${index}]`, child, toolName !== null];- })- : Object.entries(value).map(([key, child]) => [key, child, false]);-- return (- <div className="min-w-0">- <button- onClick={() => setOpen(!open)}- className="flex items-center gap-2 rounded px-1 py-0.5 text-left hover:bg-zinc-800/60"- >- <span className="w-3 text-xs text-zinc-500">{open ? "▾" : "▸"}</span>- <span className="font-mono text-xs text-violet-300">{label}</span>- <span className="font-mono text-xs text-blue-400">- {nodeSummary(value)}- </span>- </button>- {open && (- <div className="ml-2 border-l border-zinc-800 pl-4">- {media && <MediaPreview media={media} />}- {entries.map(([childLabel, childValue, isTool]) => (- <JsonNode- key={childLabel}- label={childLabel}- value={childValue}- depth={depth + 1}- defaultOpen={isTool ? false : undefined}- />- ))}- </div>- )}- </div>- );-}-function UsagePanel({ usage }: { usage: PromptReportUsage }) {const metrics: [string, string][] = [["Input tokens", usage.input_tokens.toLocaleString()],diff --git a/frontend/src/components/evals/agent-run-timeline.tsx b/frontend/src/components/evals/agent-run-timeline.tsxnew file mode 100644index 00000000..816ba50c--- /dev/null+++ b/frontend/src/components/evals/agent-run-timeline.tsx@@ -0,0 +1,418 @@+import { useEffect, useState } from "react";+import Markdown from "react-markdown";+import {+ BsBookmarkCheck,+ BsBoundingBox,+ BsCamera,+ BsChatDots,+ BsChevronDown,+ BsChevronRight,+ BsFileEarmarkPlus,+ BsFiles,+ BsFlagFill,+ BsImage,+ BsLightbulb,+ BsPencilSquare,+ BsScissors,+} from "react-icons/bs";++import { formatCost, formatMs } from "./report-format";+import { JsonNode } from "./report-json";+import ToolPreview from "./agent-run-tool-preview";++export interface RunEvent {+ seq: number;+ ts_ms: number;+ type: string;+ step?: number;+ [key: string]: unknown;+}++export type TimelineViewMode = "readable" | "raw";++// "best" opens everything except bulky code tools (create_file, edit_file).+export type ExpandMode = "expand" | "collapse" | "best";++export interface ExpandSignal {+ mode: ExpandMode;+ version: number;+}++const BULKY_TOOLS = new Set(["create_file", "edit_file"]);++interface UsageDict {+ input: number;+ output: number;+ cache_read: number;+ cache_write: number;+ total: number;+}++interface ToolRow {+ toolEventId: string;+ name: string;+ start?: RunEvent;+ end?: RunEvent;+}++interface StepGroup {+ step: number;+ start?: RunEvent;+ end?: RunEvent;+ tools: ToolRow[];+}++// Mirrors AgentActivity's getEventIcon so the timeline reads like the+// in-app tool-call list.+function toolIcon(toolName: string) {+ switch (toolName) {+ case "create_file":+ return <BsFileEarmarkPlus className="text-indigo-400" />;+ case "edit_file":+ return <BsPencilSquare className="text-purple-400" />;+ case "generate_images":+ return <BsImage className="text-pink-400" />;+ case "remove_background":+ return <BsScissors className="text-teal-400" />;+ case "edit_image":+ return <BsImage className="text-violet-400" />;+ case "retrieve_option":+ return <BsFiles className="text-slate-400" />;+ case "save_assets":+ return <BsBookmarkCheck className="text-emerald-400" />;+ case "extract_assets":+ return <BsBoundingBox className="text-orange-400" />;+ case "screenshot_preview":+ return <BsCamera className="text-cyan-400" />;+ default:+ return <BsFileEarmarkPlus className="text-gray-400" />;+ }+}++function groupEvents(events: RunEvent[]): {+ steps: StepGroup[];+ runEnd: RunEvent | null;+} {+ const stepsByNumber = new Map<number, StepGroup>();+ let runEnd: RunEvent | null = null;++ const stepFor = (stepNumber: number): StepGroup => {+ let group = stepsByNumber.get(stepNumber);+ if (!group) {+ group = { step: stepNumber, tools: [] };+ stepsByNumber.set(stepNumber, group);+ }+ return group;+ };++ for (const event of events) {+ if (event.type === "llm_call_start" && typeof event.step === "number") {+ stepFor(event.step).start = event;+ } else if (event.type === "llm_call_end" && typeof event.step === "number") {+ stepFor(event.step).end = event;+ } else if (+ (event.type === "tool_call_start" || event.type === "tool_call_end") &&+ typeof event.step === "number"+ ) {+ const group = stepFor(event.step);+ const toolEventId = String(event.tool_event_id ?? "");+ let row = group.tools.find((tool) => tool.toolEventId === toolEventId);+ if (!row) {+ row = {+ toolEventId,+ name: String(event.name ?? "unknown_tool"),+ start: undefined,+ end: undefined,+ };+ group.tools.push(row);+ }+ if (event.type === "tool_call_start") row.start = event;+ else row.end = event;+ } else if (event.type === "run_end") {+ runEnd = event;+ }+ }++ const steps = [...stepsByNumber.values()].sort((a, b) => a.step - b.step);+ return { steps, runEnd };+}++function openForSignal(signal: ExpandSignal, collapseInBest: boolean): boolean {+ if (signal.mode === "best") return !collapseInBest;+ return signal.mode === "expand";+}++function CollapsibleCard({+ icon,+ title,+ meta,+ tint,+ collapseInBest = false,+ expandSignal,+ children,+}: {+ icon: React.ReactNode;+ title: string;+ meta?: string;+ tint?: "error";+ collapseInBest?: boolean;+ expandSignal: ExpandSignal;+ children: React.ReactNode;+}) {+ const [open, setOpen] = useState(() =>+ openForSignal(expandSignal, collapseInBest)+ );++ useEffect(() => {+ setOpen(openForSignal(expandSignal, collapseInBest));+ }, [expandSignal, collapseInBest]);++ return (+ <div+ className={`rounded-lg border ${+ tint === "error"+ ? "border-red-900 bg-red-950/30"+ : "border-zinc-800 bg-zinc-950/50"+ }`}+ >+ <button+ onClick={() => setOpen(!open)}+ className="flex w-full items-center gap-2 px-2.5 py-1.5 text-left"+ >+ <span className="shrink-0">{icon}</span>+ <span className="min-w-0 flex-1 truncate text-xs text-zinc-100">+ {title}+ </span>+ {meta && (+ <span className="shrink-0 font-mono text-[11px] text-zinc-500">+ {meta}+ </span>+ )}+ <span className="shrink-0 text-zinc-500">+ {open ? <BsChevronDown /> : <BsChevronRight />}+ </span>+ </button>+ {open && (+ <div className="border-t border-zinc-800/70 p-2.5">{children}</div>+ )}+ </div>+ );+}++function usageBreakdown(usage: UsageDict | null | undefined): string {+ if (!usage) return "no usage";+ const parts = [+ `in ${usage.input.toLocaleString()}`,+ `out ${usage.output.toLocaleString()}`,+ `cr ${usage.cache_read.toLocaleString()}`,+ ];+ if (usage.cache_write > 0) parts.push(`cw ${usage.cache_write.toLocaleString()}`);+ return parts.join(" · ");+}++function StepCard({+ group,+ viewMode,+ expandSignal,+}: {+ group: StepGroup;+ viewMode: TimelineViewMode;+ expandSignal: ExpandSignal;+}) {+ const readable = viewMode === "readable";+ const end = group.end;+ const thinkingText =+ typeof end?.thinking_text === "string" ? end.thinking_text : "";+ const assistantText =+ typeof end?.assistant_text === "string" ? end.assistant_text : "";+ const usage = (end?.usage ?? null) as UsageDict | null;+ const costUsd = typeof end?.cost_usd === "number" ? end.cost_usd : null;+ const durationMs =+ typeof end?.duration_ms === "number" ? end.duration_ms : null;+ const thinkingMs = typeof end?.thinking_ms === "number" ? end.thinking_ms : 0;+ const apiModel =+ typeof group.start?.api_model_name === "string"+ ? group.start.api_model_name+ : "";++ const headerMeta = [+ costUsd === null ? null : formatCost(costUsd),+ formatMs(durationMs),+ usageBreakdown(usage),+ ]+ .filter(Boolean)+ .join(" · ");++ return (+ <div className="rounded-xl border border-zinc-800 bg-zinc-900/50 p-2.5">+ <div className="mb-1.5 flex flex-wrap items-center justify-between gap-x-2 gap-y-0.5">+ <div className="text-xs font-semibold text-zinc-200">+ Step {group.step}+ {apiModel && (+ <span className="ml-2 font-mono text-[11px] font-normal text-zinc-500">+ {apiModel}+ </span>+ )}+ </div>+ <div className="font-mono text-[11px] text-zinc-400">{headerMeta}</div>+ </div>+ <div className="flex flex-col gap-1.5">+ {!readable && group.start && (+ <CollapsibleCard+ icon={<BsChatDots className="text-blue-400" />}+ title="LLM request"+ meta="full payload"+ expandSignal={expandSignal}+ >+ <JsonNode label="request" value={group.start.request} depth={0} />+ </CollapsibleCard>+ )}+ {thinkingText && (+ <CollapsibleCard+ icon={<BsLightbulb className="text-yellow-400" />}+ title={+ thinkingMs > 0 ? `Thought for ${formatMs(thinkingMs)}` : "Thinking"+ }+ meta={`${thinkingText.length.toLocaleString()} chars`}+ expandSignal={expandSignal}+ >+ <div className="max-h-96 overflow-y-auto text-xs leading-5 text-zinc-300">+ <Markdown>{thinkingText}</Markdown>+ </div>+ </CollapsibleCard>+ )}+ {group.tools.map((tool) => {+ const toolEnd = tool.end;+ const ok = toolEnd ? toolEnd.ok !== false : true;+ const toolDuration =+ typeof toolEnd?.duration_ms === "number"+ ? toolEnd.duration_ms+ : null;+ const bulky = BULKY_TOOLS.has(tool.name);+ return (+ <CollapsibleCard+ key={tool.toolEventId}+ icon={toolIcon(tool.name)}+ title={tool.name}+ meta={`${formatMs(toolDuration)}${ok ? "" : " · error"}`}+ tint={ok ? undefined : "error"}+ collapseInBest={bulky}+ expandSignal={expandSignal}+ >+ {readable ? (+ <ToolPreview+ name={tool.name}+ args={tool.start?.arguments}+ summary={toolEnd?.summary ?? null}+ />+ ) : (+ <div className="flex flex-col gap-3">+ {tool.start && (+ <JsonNode+ label="input"+ value={tool.start.arguments}+ depth={0}+ defaultOpen+ />+ )}+ {toolEnd && (+ <JsonNode+ label="output"+ value={toolEnd.result ?? toolEnd.summary}+ depth={0}+ defaultOpen+ />+ )}+ </div>+ )}+ {!toolEnd && (+ <p className="mt-2 text-xs italic text-zinc-500">+ No result recorded (run may have been interrupted).+ </p>+ )}+ </CollapsibleCard>+ );+ })}+ {assistantText && (+ <CollapsibleCard+ icon={<BsChatDots className="text-blue-400" />}+ title="Response"+ meta={`${assistantText.length.toLocaleString()} chars`}+ expandSignal={expandSignal}+ >+ <div className="max-h-96 overflow-y-auto text-xs leading-5 text-zinc-300">+ <Markdown>{assistantText}</Markdown>+ </div>+ </CollapsibleCard>+ )}+ {!end && (+ <p className="text-xs italic text-zinc-500">+ LLM call did not complete (run failed or is still in flight).+ </p>+ )}+ </div>+ </div>+ );+}++function AgentRunTimeline({+ events,+ viewMode,+ expandSignal,+}: {+ events: RunEvent[];+ viewMode: TimelineViewMode;+ expandSignal: ExpandSignal;+}) {+ const { steps, runEnd } = groupEvents(events);++ if (steps.length === 0 && !runEnd) {+ return (+ <p className="py-4 text-center text-sm text-zinc-400">+ No timeline events recorded for this run.+ </p>+ );+ }++ const runEndError =+ runEnd && typeof runEnd.error === "string" ? runEnd.error : null;++ return (+ <div className="flex flex-col gap-2">+ {steps.map((group) => (+ <StepCard+ key={group.step}+ group={group}+ viewMode={viewMode}+ expandSignal={expandSignal}+ />+ ))}+ {runEnd && (+ <div+ className={`flex items-center gap-2 rounded-lg border px-2.5 py-1.5 text-xs ${+ runEnd.status === "completed"+ ? "border-emerald-900 bg-emerald-950/30 text-emerald-200"+ : "border-red-900 bg-red-950/30 text-red-200"+ }`}+ >+ <BsFlagFill />+ <span>+ Run {String(runEnd.status)} · total{" "}+ {formatMs(+ typeof runEnd.total_duration_ms === "number"+ ? runEnd.total_duration_ms+ : null+ )}+ </span>+ {runEndError && (+ <span className="min-w-0 flex-1 truncate font-mono text-[11px]">+ {runEndError}+ </span>+ )}+ </div>+ )}+ </div>+ );+}++export default AgentRunTimeline;diff --git a/frontend/src/components/evals/agent-run-tool-preview.tsx b/frontend/src/components/evals/agent-run-tool-preview.tsxnew file mode 100644index 00000000..73044dd7--- /dev/null+++ b/frontend/src/components/evals/agent-run-tool-preview.tsx@@ -0,0 +1,417 @@+import { Light as SyntaxHighlighterBase } from "react-syntax-highlighter";+import html from "react-syntax-highlighter/dist/esm/languages/hljs/xml";+import { vs2015 } from "react-syntax-highlighter/dist/esm/styles/hljs";++import { LightboxImage } from "./image-lightbox";++SyntaxHighlighterBase.registerLanguage("html", html);+// eslint-disable-next-line @typescript-eslint/no-explicit-any+const SyntaxHighlighter = SyntaxHighlighterBase as any;++function getRecord(value: unknown): Record<string, unknown> | null {+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+}++function getArray(value: unknown, field: string): unknown[] | null {+ const record = getRecord(value);+ const fieldValue = record?.[field];+ return Array.isArray(fieldValue) ? fieldValue : null;+}++function getString(value: unknown, field: string): string | null {+ const record = getRecord(value);+ const fieldValue = record?.[field];+ return typeof fieldValue === "string" ? fieldValue : null;+}++function CompactJson({ data }: { data: unknown }) {+ let json = "";+ try {+ json = JSON.stringify(data, null, 2);+ } catch {+ json = String(data);+ }+ if (json.length > 2000) json = json.slice(0, 2000) + "…";+ return (+ <pre className="overflow-x-auto whitespace-pre-wrap break-all rounded-md bg-zinc-950 p-2 text-xs text-zinc-300">+ {json}+ </pre>+ );+}++function FieldLabel({ children }: { children: React.ReactNode }) {+ return (+ <div className="mb-1 text-xs text-zinc-500">{children}</div>+ );+}++function UrlChip({ url }: { url: string }) {+ return (+ <div className="break-all rounded bg-zinc-950 p-2 font-mono text-xs text-zinc-400">+ {url}+ </div>+ );+}++function MissingBox({ label = "Missing" }: { label?: string }) {+ return (+ <div className="flex h-20 w-20 items-center justify-center rounded bg-zinc-800 text-xs text-zinc-500">+ {label}+ </div>+ );+}++// Small thumbnail; click opens the shared zoom/pan lightbox.+function Img({ src, alt }: { src: string; alt: string }) {+ return <LightboxImage src={src} alt={alt} />;+}++/**+ * Human-readable tool previews mirroring the in-app AgentActivity views+ * (edit_image shows main/edited images, screenshot_preview shows the captured+ * screenshots, etc.), restyled for the dark eval theme. `args` is the full+ * recorded tool input; `summary` is the compact result the app itself renders.+ */+function ToolPreview({+ name,+ args,+ summary,+}: {+ name: string;+ args: unknown;+ summary: unknown;+}) {+ const error = getString(summary, "error");+ if (error) {+ return (+ <div className="rounded-md border border-red-900 bg-red-950/40 p-3">+ <div className="text-xs uppercase tracking-wide text-red-400">+ Error+ </div>+ <div className="mt-1 text-sm text-red-200">{error}</div>+ {args !== undefined && args !== null && (+ <div className="mt-2">+ <FieldLabel>Input</FieldLabel>+ <CompactJson data={args} />+ </div>+ )}+ </div>+ );+ }++ if (name === "create_file") {+ const content = getString(args, "content");+ const path = getString(args, "path");+ if (content) {+ return (+ <div>+ {path && <FieldLabel>{path}</FieldLabel>}+ <div className="max-h-80 overflow-auto rounded-md">+ <SyntaxHighlighter+ language="html"+ style={vs2015}+ customStyle={{+ margin: 0,+ padding: "0.5rem",+ fontSize: "0.75rem",+ borderRadius: "0.375rem",+ }}+ wrapLongLines+ >+ {content}+ </SyntaxHighlighter>+ </div>+ </div>+ );+ }+ }++ if (name === "edit_file") {+ const edits = getArray(summary, "edits");+ if (edits) {+ return (+ <div className="space-y-2">+ {edits.map((edit, index) => {+ const oldText = getString(edit, "old_text") ?? "";+ const newText = getString(edit, "new_text") ?? "";+ const replaced = getRecord(edit)?.replaced;+ return (+ <div+ key={`${oldText.slice(0, 40)}-${index}`}+ className="rounded-md border border-zinc-800 bg-zinc-950/60 p-3"+ >+ <div className="text-xs uppercase tracking-wide text-zinc-500">+ Edit {index + 1}+ </div>+ <div className="mt-2 grid gap-2">+ <div>+ <FieldLabel>Old</FieldLabel>+ <div className="break-all rounded bg-red-950/40 p-2 font-mono text-xs text-red-200">+ {oldText}+ </div>+ </div>+ <div>+ <FieldLabel>New</FieldLabel>+ <div className="break-all rounded bg-emerald-950/40 p-2 font-mono text-xs text-emerald-200">+ {newText}+ </div>+ </div>+ </div>+ {replaced !== undefined && (+ <div className="mt-2 text-xs text-zinc-500">+ Replaced {String(replaced)} time+ {replaced === 1 ? "" : "s"}+ </div>+ )}+ </div>+ );+ })}+ </div>+ );+ }+ }++ if (name === "generate_images") {+ const images = getArray(summary, "images");+ if (images) {+ return (+ <div className="divide-y divide-zinc-800">+ {images.map((item, index) => {+ const url = getString(item, "url");+ const prompt = getString(item, "prompt");+ return (+ <div key={`${prompt}-${index}`} className="flex items-center gap-3 py-1.5">+ <div className="shrink-0">+ {url ? (+ <Img src={url} alt={prompt || `Generated image ${index + 1}`} />+ ) : (+ <MissingBox label="Failed" />+ )}+ </div>+ <div className="min-w-0 flex-1 text-xs text-zinc-400">+ {prompt}+ </div>+ </div>+ );+ })}+ </div>+ );+ }+ }++ if (name === "remove_background") {+ const images = getArray(summary, "images");+ if (images) {+ return (+ <div className="divide-y divide-zinc-800">+ {images.map((item, index) => {+ const before = getString(item, "image_url");+ const after = getString(item, "result_url");+ return (+ <div key={`${before}-${index}`} className="flex gap-4 py-1.5">+ <div>+ <FieldLabel>Before</FieldLabel>+ {before ? (+ <Img src={before} alt={`Original image ${index + 1}`} />+ ) : (+ <MissingBox />+ )}+ </div>+ <div>+ <FieldLabel>After</FieldLabel>+ {after ? (+ <Img src={after} alt="Background removed" />+ ) : (+ <MissingBox label="Failed" />+ )}+ </div>+ </div>+ );+ })}+ </div>+ );+ }+ }++ if (name === "edit_image") {+ const image = getRecord(getRecord(summary)?.image);+ const prompt = getString(args, "prompt") ?? getString(image, "prompt");+ const imageUrls = getArray(image, "image_urls") ?? getArray(args, "image_urls");+ const mainUrl =+ imageUrls && typeof imageUrls[0] === "string" ? imageUrls[0] : null;+ const resultUrl = getString(image, "result_url");+ const referenceUrls = (imageUrls ?? [])+ .slice(1)+ .filter((url): url is string => typeof url === "string");+ return (+ <div className="space-y-3">+ {prompt && (+ <div>+ <FieldLabel>Prompt</FieldLabel>+ <p className="whitespace-pre-wrap break-words text-xs text-zinc-300">+ {prompt}+ </p>+ </div>+ )}+ <div className="flex flex-wrap gap-4">+ <div>+ <FieldLabel>Main image</FieldLabel>+ {mainUrl ? <Img src={mainUrl} alt="Main image" /> : <MissingBox />}+ </div>+ <div>+ <FieldLabel>Edited image</FieldLabel>+ {resultUrl ? (+ <Img src={resultUrl} alt="Edited image" />+ ) : (+ <MissingBox label="Failed" />+ )}+ </div>+ {referenceUrls.length > 0 && (+ <div>+ <FieldLabel>Reference images</FieldLabel>+ <div className="flex flex-wrap gap-2">+ {referenceUrls.map((url, index) => (+ <Img+ key={`${url}-${index}`}+ src={url}+ alt={`Reference ${index + 2}`}+ />+ ))}+ </div>+ </div>+ )}+ </div>+ {resultUrl && (+ <div>+ <FieldLabel>Result URL</FieldLabel>+ <UrlChip url={resultUrl} />+ </div>+ )}+ </div>+ );+ }++ if (name === "save_assets") {+ const images = getArray(summary, "images");+ if (images) {+ return (+ <div className="divide-y divide-zinc-800">+ {images.map((item, index) => {+ const publicUrl = getString(item, "public_url");+ return (+ <div+ key={`${publicUrl}-${index}`}+ className="flex items-center gap-3 py-1.5"+ >+ <div className="shrink-0">+ {publicUrl ? (+ <Img src={publicUrl} alt={`Saved asset ${index + 1}`} />+ ) : (+ <MissingBox label="Failed" />+ )}+ </div>+ <div className="min-w-0 flex-1">+ <FieldLabel>Permanent URL</FieldLabel>+ {publicUrl && <UrlChip url={publicUrl} />}+ </div>+ </div>+ );+ })}+ </div>+ );+ }+ }++ if (name === "extract_assets") {+ const assets = getArray(summary, "assets");+ if (assets) {+ return (+ <div className="divide-y divide-zinc-800">+ {assets.map((asset, index) => {+ const description =+ getString(asset, "description") ?? `Asset ${index + 1}`;+ const previewUrl =+ getString(asset, "public_url") ?? getString(asset, "data_url");+ const box = getArray(asset, "box_2d");+ const status = getString(asset, "status") ?? (previewUrl ? "ok" : "missing");+ return (+ <div+ key={`${description}-${index}`}+ className="flex items-center gap-3 py-1.5"+ >+ <div className="shrink-0">+ {previewUrl ? (+ <Img src={previewUrl} alt={description} />+ ) : (+ <MissingBox />+ )}+ </div>+ <div className="min-w-0 flex-1 text-xs text-zinc-300">+ {description}+ <span className="ml-2 font-mono text-[11px] text-zinc-500">+ {status}+ {box && ` · [${box.join(", ")}]`}+ </span>+ </div>+ </div>+ );+ })}+ </div>+ );+ }+ }++ if (name === "screenshot_preview") {+ const screenshots = getArray(summary, "screenshots") ?? [];+ return (+ <div className="grid gap-3 py-1 sm:grid-cols-2">+ {(["desktop", "mobile"] as const).map((viewport) => {+ const screenshot = screenshots.find(+ (item) => getString(item, "viewport") === viewport+ );+ const imageUrl = getString(screenshot, "image_url");+ return (+ <div key={viewport}>+ <FieldLabel>+ <span className="capitalize">{viewport}</span>+ </FieldLabel>+ {imageUrl ? (+ <div className="max-h-48 overflow-y-auto rounded border border-zinc-800">+ <LightboxImage+ src={imageUrl}+ alt={`${viewport} preview screenshot`}+ className="w-full"+ />+ </div>+ ) : (+ <MissingBox />+ )}+ </div>+ );+ })}+ </div>+ );+ }++ // Unknown tools (retrieve_option, future additions): compact JSON.+ return (+ <div className="space-y-3">+ {args !== undefined && args !== null && (+ <div>+ <FieldLabel>Input</FieldLabel>+ <CompactJson data={args} />+ </div>+ )}+ {summary !== undefined && summary !== null && (+ <div>+ <FieldLabel>Output</FieldLabel>+ <CompactJson data={summary} />+ </div>+ )}+ </div>+ );+}++export default ToolPreview;diff --git a/frontend/src/components/evals/image-lightbox.tsx b/frontend/src/components/evals/image-lightbox.tsxnew file mode 100644index 00000000..d1603a06--- /dev/null+++ b/frontend/src/components/evals/image-lightbox.tsx@@ -0,0 +1,409 @@+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useId,+ useMemo,+ useRef,+ useState,+} from "react";+import {+ BsArrowsFullscreen,+ BsBoxArrowUpRight,+ BsChevronLeft,+ BsChevronRight,+ BsDash,+ BsPlus,+ BsX,+} from "react-icons/bs";++interface LightboxEntry {+ id: string;+ src: string;+ alt: string;+}++interface LightboxContextValue {+ register: (entry: LightboxEntry) => void;+ unregister: (id: string) => void;+ open: (id: string) => void;+}++const LightboxContext = createContext<LightboxContextValue | null>(null);++const MIN_SCALE_FACTOR = 0.2; // relative to fit+const MAX_SCALE = 16;++function clamp(value: number, min: number, max: number): number {+ return Math.min(max, Math.max(min, value));+}++function LightboxViewer({+ entries,+ index,+ onClose,+ onNavigate,+}: {+ entries: LightboxEntry[];+ index: number;+ onClose: () => void;+ onNavigate: (nextIndex: number) => void;+}) {+ const entry = entries[index];+ const containerRef = useRef<HTMLDivElement>(null);+ const [natural, setNatural] = useState<{ w: number; h: number } | null>(null);+ const [scale, setScale] = useState(1);+ const [tx, setTx] = useState(0);+ const [ty, setTy] = useState(0);+ const dragRef = useRef<{ x: number; y: number } | null>(null);+ const [isDragging, setIsDragging] = useState(false);++ const fitScale = useMemo(() => {+ const container = containerRef.current;+ if (!natural || !container) return 1;+ return Math.min(+ (container.clientWidth * 0.92) / natural.w,+ (container.clientHeight * 0.85) / natural.h,+ 1+ );+ }, [natural]);++ const resetToFit = useCallback(() => {+ setScale(fitScale);+ setTx(0);+ setTy(0);+ }, [fitScale]);++ // Refit when the image changes/loads.+ useEffect(() => {+ resetToFit();+ }, [resetToFit, entry?.src]);++ const zoomAt = useCallback(+ (clientX: number, clientY: number, factor: number) => {+ const container = containerRef.current;+ if (!container) return;+ const rect = container.getBoundingClientRect();+ const cx = clientX - rect.left - rect.width / 2;+ const cy = clientY - rect.top - rect.height / 2;+ setScale((previousScale) => {+ const nextScale = clamp(+ previousScale * factor,+ fitScale * MIN_SCALE_FACTOR,+ MAX_SCALE+ );+ const ratio = nextScale / previousScale;+ setTx((previousTx) => cx - (cx - previousTx) * ratio);+ setTy((previousTy) => cy - (cy - previousTy) * ratio);+ return nextScale;+ });+ },+ [fitScale]+ );++ // Native wheel listener: React's synthetic wheel handlers are passive, so+ // preventDefault (needed to stop page scroll) requires a manual listener.+ useEffect(() => {+ const container = containerRef.current;+ if (!container) return;+ const onWheel = (e: WheelEvent) => {+ e.preventDefault();+ zoomAt(e.clientX, e.clientY, Math.exp(-e.deltaY * 0.0018));+ };+ container.addEventListener("wheel", onWheel, { passive: false });+ return () => container.removeEventListener("wheel", onWheel);+ }, [zoomAt]);++ useEffect(() => {+ const onKeyDown = (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose();+ else if (e.key === "+" || e.key === "=") {+ const container = containerRef.current;+ if (!container) return;+ const rect = container.getBoundingClientRect();+ zoomAt(rect.left + rect.width / 2, rect.top + rect.height / 2, 1.3);+ } else if (e.key === "-" || e.key === "_") {+ const container = containerRef.current;+ if (!container) return;+ const rect = container.getBoundingClientRect();+ zoomAt(rect.left + rect.width / 2, rect.top + rect.height / 2, 1 / 1.3);+ } else if (e.key === "0" || e.key.toLowerCase() === "f") {+ resetToFit();+ } else if (e.key === "1") {+ setScale(1);+ } else if (e.key === "ArrowLeft" && entries.length > 1) {+ onNavigate((index - 1 + entries.length) % entries.length);+ } else if (e.key === "ArrowRight" && entries.length > 1) {+ onNavigate((index + 1) % entries.length);+ }+ };+ window.addEventListener("keydown", onKeyDown);+ return () => window.removeEventListener("keydown", onKeyDown);+ }, [onClose, onNavigate, resetToFit, zoomAt, entries.length, index]);++ // Lock page scroll while open.+ useEffect(() => {+ const previous = document.body.style.overflow;+ document.body.style.overflow = "hidden";+ return () => {+ document.body.style.overflow = previous;+ };+ }, []);++ if (!entry) return null;++ const zoomPercent = natural ? Math.round(scale * 100) : 100;++ const toolbarButton =+ "flex h-8 w-8 items-center justify-center rounded-md text-zinc-300 transition-colors hover:bg-zinc-700 hover:text-white";++ return (+ <div+ className="fixed inset-0 z-50 flex flex-col bg-black/90 backdrop-blur-sm"+ onClick={onClose}+ >+ <div+ className="mx-auto mt-3 flex shrink-0 items-center gap-1 rounded-xl border border-zinc-700 bg-zinc-900/90 px-2 py-1 shadow-xl"+ onClick={(e) => e.stopPropagation()}+ >+ <button+ className={toolbarButton}+ title="Zoom out (-)"+ onClick={() => {+ const rect = containerRef.current?.getBoundingClientRect();+ if (rect)+ zoomAt(rect.left + rect.width / 2, rect.top + rect.height / 2, 1 / 1.3);+ }}+ >+ <BsDash />+ </button>+ <span className="w-14 text-center font-mono text-xs text-zinc-300">+ {zoomPercent}%+ </span>+ <button+ className={toolbarButton}+ title="Zoom in (+)"+ onClick={() => {+ const rect = containerRef.current?.getBoundingClientRect();+ if (rect)+ zoomAt(rect.left + rect.width / 2, rect.top + rect.height / 2, 1.3);+ }}+ >+ <BsPlus />+ </button>+ <button+ className={`${toolbarButton} w-auto px-2 text-xs`}+ title="Fit to screen (0 / f)"+ onClick={resetToFit}+ >+ <BsArrowsFullscreen className="mr-1" /> Fit+ </button>+ <button+ className={`${toolbarButton} w-auto px-2 font-mono text-xs`}+ title="Actual size (1)"+ onClick={() => setScale(1)}+ >+ 1:1+ </button>+ <div className="mx-1 h-5 w-px bg-zinc-700" />+ <a+ href={entry.src}+ target="_blank"+ rel="noreferrer"+ className={toolbarButton}+ title="Open in new tab"+ >+ <BsBoxArrowUpRight />+ </a>+ <button className={toolbarButton} title="Close (Esc)" onClick={onClose}>+ <BsX className="text-lg" />+ </button>+ </div>++ <div+ ref={containerRef}+ className={`relative min-h-0 flex-1 overflow-hidden ${+ isDragging ? "cursor-grabbing" : "cursor-grab"+ }`}+ onPointerDown={(e) => {+ e.preventDefault();+ e.stopPropagation();+ dragRef.current = { x: e.clientX, y: e.clientY };+ setIsDragging(true);+ (e.target as HTMLElement).setPointerCapture(e.pointerId);+ }}+ onPointerMove={(e) => {+ if (!dragRef.current) return;+ const dx = e.clientX - dragRef.current.x;+ const dy = e.clientY - dragRef.current.y;+ dragRef.current = { x: e.clientX, y: e.clientY };+ setTx((previous) => previous + dx);+ setTy((previous) => previous + dy);+ }}+ onPointerUp={(e) => {+ dragRef.current = null;+ setIsDragging(false);+ (e.target as HTMLElement).releasePointerCapture(e.pointerId);+ }}+ onDoubleClick={(e) => {+ // Toggle between fit and a closer look at the point under the cursor.+ if (scale > fitScale * 1.4) resetToFit();+ else zoomAt(e.clientX, e.clientY, (fitScale * 3) / scale || 3);+ }}+ onClick={(e) => e.stopPropagation()}+ >+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center">+ <img+ src={entry.src}+ alt={entry.alt}+ draggable={false}+ onLoad={(e) => {+ const img = e.currentTarget;+ setNatural({ w: img.naturalWidth, h: img.naturalHeight });+ }}+ style={{+ transform: `translate(${tx}px, ${ty}px) scale(${scale})`,+ maxWidth: "none",+ maxHeight: "none",+ }}+ className="select-none"+ />+ </div>+ </div>++ <div+ className="pointer-events-none mx-auto mb-3 flex shrink-0 items-center gap-3 text-xs text-zinc-400"+ onClick={(e) => e.stopPropagation()}+ >+ {entries.length > 1 && (+ <div className="pointer-events-auto flex items-center gap-2 rounded-xl border border-zinc-700 bg-zinc-900/90 px-2 py-1">+ <button+ className={toolbarButton}+ title="Previous image (←)"+ onClick={() =>+ onNavigate((index - 1 + entries.length) % entries.length)+ }+ >+ <BsChevronLeft />+ </button>+ <span className="font-mono">+ {index + 1} / {entries.length}+ </span>+ <button+ className={toolbarButton}+ title="Next image (→)"+ onClick={() => onNavigate((index + 1) % entries.length)}+ >+ <BsChevronRight />+ </button>+ </div>+ )}+ <span className="max-w-[50vw] truncate rounded-lg bg-zinc-900/80 px-2 py-1">+ {entry.alt}+ </span>+ </div>+ </div>+ );+}++/**+ * Collects every LightboxImage rendered beneath it so the viewer can page+ * through all images in the run with ←/→.+ */+export function LightboxProvider({ children }: { children: React.ReactNode }) {+ const [entries, setEntries] = useState<LightboxEntry[]>([]);+ const [openId, setOpenId] = useState<string | null>(null);++ const register = useCallback((entry: LightboxEntry) => {+ setEntries((previous) => {+ const without = previous.filter((e) => e.id !== entry.id);+ return [...without, entry];+ });+ }, []);++ const unregister = useCallback((id: string) => {+ setEntries((previous) => previous.filter((e) => e.id !== id));+ }, []);++ const open = useCallback((id: string) => setOpenId(id), []);++ const value = useMemo(+ () => ({ register, unregister, open }),+ [register, unregister, open]+ );++ const openIndex = entries.findIndex((e) => e.id === openId);++ return (+ <LightboxContext.Provider value={value}>+ {children}+ {openId !== null && openIndex >= 0 && (+ <LightboxViewer+ entries={entries}+ index={openIndex}+ onClose={() => setOpenId(null)}+ onNavigate={(nextIndex) => setOpenId(entries[nextIndex]?.id ?? null)}+ />+ )}+ </LightboxContext.Provider>+ );+}++/**+ * Thumbnail that opens the shared lightbox. Falls back to opening the image+ * in a new tab when no LightboxProvider is mounted (e.g. PromptReportsPage).+ */+export function LightboxImage({+ src,+ alt,+ className,+}: {+ src: string;+ alt: string;+ className?: string;+}) {+ const context = useContext(LightboxContext);+ const id = useId();++ useEffect(() => {+ if (!context) return;+ context.register({ id, src, alt });+ return () => context.unregister(id);+ }, [context, id, src, alt]);++ const image = (+ <img+ src={src}+ alt={alt}+ title={alt}+ className={+ className ??+ "max-h-28 w-auto max-w-full rounded bg-zinc-800 object-contain transition-opacity hover:opacity-80"+ }+ loading="lazy"+ />+ );++ if (!context) {+ return (+ <a href={src} target="_blank" rel="noreferrer" className="inline-block">+ {image}+ </a>+ );+ }++ return (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ context.open(id);+ }}+ className="inline-block cursor-zoom-in"+ title={`${alt} — click to zoom`}+ >+ {image}+ </button>+ );+}diff --git a/frontend/src/components/evals/report-format.ts b/frontend/src/components/evals/report-format.tsnew file mode 100644index 00000000..146ccc46--- /dev/null+++ b/frontend/src/components/evals/report-format.ts@@ -0,0 +1,48 @@+const PROVIDER_BADGE_CLASSES: Record<string, string> = {+ openai: "bg-emerald-900/60 text-emerald-200 border-emerald-700",+ anthropic: "bg-orange-900/60 text-orange-200 border-orange-700",+ gemini: "bg-sky-900/60 text-sky-200 border-sky-700",+};++export function providerBadgeClass(provider: string): string {+ return (+ PROVIDER_BADGE_CLASSES[provider] ||+ "bg-zinc-800 text-zinc-200 border-zinc-600"+ );+}++export function formatBytes(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ const units = ["KB", "MB", "GB", "TB"];+ let value = bytes;+ let unitIndex = -1;+ do {+ value /= 1024;+ unitIndex += 1;+ } while (value >= 1024 && unitIndex < units.length - 1);+ return `${value.toFixed(value >= 100 ? 0 : 1)} ${units[unitIndex]}`;+}++export function formatTimestamp(isoTimestamp: string): string {+ const date = new Date(isoTimestamp);+ if (isNaN(date.getTime())) return isoTimestamp;+ return date.toLocaleString();+}++export function formatCost(costUsd: number | null): string {+ if (costUsd === null) return "—";+ // Round to cents; flag sub-cent totals so a real cost never reads as $0.00.+ if (costUsd > 0 && costUsd < 0.01) return "<$0.01";+ return `$${costUsd.toFixed(2)}`;+}++// formatDurationMs (generation-time.ts) floors at 1s; run timelines need+// millisecond precision for fast tool calls.+export function formatMs(milliseconds: number | null | undefined): string {+ if (milliseconds === null || milliseconds === undefined) return "—";+ if (milliseconds < 1000) return `${Math.round(milliseconds)}ms`;+ if (milliseconds < 60_000) return `${(milliseconds / 1000).toFixed(1)}s`;+ const minutes = Math.floor(milliseconds / 60_000);+ const seconds = Math.round((milliseconds % 60_000) / 1000);+ return `${minutes}m ${seconds}s`;+}diff --git a/frontend/src/components/evals/report-json.tsx b/frontend/src/components/evals/report-json.tsxnew file mode 100644index 00000000..667fe82e--- /dev/null+++ b/frontend/src/components/evals/report-json.tsx@@ -0,0 +1,253 @@+import { useState } from "react";+import Markdown from "react-markdown";++import { LightboxImage } from "./image-lightbox";++interface MediaInfo {+ src: string;+ kind: "image" | "video";+}++// Pydantic's JSON mode emits URL-safe base64; data: URLs need the standard+// alphabet. Normalize so reports written before the writer fix still render.+function normalizeBase64(data: string): string {+ return data.replace(/-/g, "+").replace(/_/g, "/");+}++// Detects renderable media in a JSON value: either a data URL string or an+// object shaped like {data: <base64>, mime_type|media_type: image/*|video/*}.+function mediaFromValue(value: unknown): MediaInfo | null {+ if (typeof value === "string") {+ if (value.startsWith("data:image/")) return { src: value, kind: "image" };+ if (value.startsWith("data:video/")) return { src: value, kind: "video" };+ return null;+ }++ if (typeof value === "object" && value !== null && !Array.isArray(value)) {+ const record = value as Record<string, unknown>;+ const mime = record["mime_type"] ?? record["media_type"];+ const data = record["data"];+ if (+ typeof mime === "string" &&+ typeof data === "string" &&+ data.length > 0+ ) {+ if (mime.startsWith("image/") || mime.startsWith("video/")) {+ return {+ src: `data:${mime};base64,${normalizeBase64(data)}`,+ kind: mime.startsWith("image/") ? "image" : "video",+ };+ }+ }+ }++ return null;+}++function MediaPreview({ media }: { media: MediaInfo }) {+ if (media.kind === "video") {+ return (+ <video+ src={media.src}+ controls+ className="my-1 max-h-48 rounded-lg border border-zinc-700"+ />+ );+ }+ return (+ <LightboxImage+ src={media.src}+ alt="embedded media"+ className="my-1 max-h-48 rounded-lg border border-zinc-700 bg-white object-contain"+ />+ );+}++function nodeSummary(value: unknown): string {+ if (Array.isArray(value)) {+ return `array · ${value.length} item${value.length === 1 ? "" : "s"}`;+ }+ if (typeof value === "object" && value !== null) {+ const keyCount = Object.keys(value).length;+ return `object · ${keyCount} key${keyCount === 1 ? "" : "s"}`;+ }+ return typeof value;+}++const LONG_STRING_PREVIEW_CHARS = 280;+const MARKDOWN_MAX_CHARS = 20000;+// Object keys whose string values are prompt/message prose — rendered as+// markdown instead of a raw string.+const PROSE_KEYS = new Set([+ "text",+ "content",+ "system",+ "system_instruction",+ "instructions",+]);++const MARKDOWN_STYLES = [+ "[&_h1]:mt-3 [&_h1]:text-base [&_h1]:font-bold",+ "[&_h2]:mt-3 [&_h2]:text-sm [&_h2]:font-bold",+ "[&_h3]:mt-2 [&_h3]:text-sm [&_h3]:font-semibold",+ "[&_p]:my-1.5",+ "[&_ul]:my-1.5 [&_ul]:list-disc [&_ul]:pl-5",+ "[&_ol]:my-1.5 [&_ol]:list-decimal [&_ol]:pl-5",+ "[&_li]:my-0.5",+ "[&_code]:rounded [&_code]:bg-zinc-800 [&_code]:px-1 [&_code]:text-[11px] [&_code]:text-amber-100",+ "[&_pre]:my-2 [&_pre]:overflow-x-auto [&_pre]:rounded [&_pre]:bg-zinc-900 [&_pre]:p-2",+ "[&_a]:text-blue-400 [&_a]:underline",+ "[&_blockquote]:border-l-2 [&_blockquote]:border-zinc-700 [&_blockquote]:pl-3 [&_blockquote]:text-zinc-400",+].join(" ");++export function MarkdownLeaf({ text }: { text: string }) {+ const [showRaw, setShowRaw] = useState(false);+ return (+ <div className="min-w-0 flex-1">+ <div className="mt-1 max-h-96 overflow-y-auto rounded-lg border border-zinc-800 bg-zinc-950 p-3">+ {showRaw ? (+ <pre className="whitespace-pre-wrap break-all text-xs text-amber-100">+ {text}+ </pre>+ ) : (+ <div className={`text-xs leading-5 text-zinc-200 ${MARKDOWN_STYLES}`}>+ <Markdown>{text}</Markdown>+ </div>+ )}+ </div>+ <button+ onClick={() => setShowRaw(!showRaw)}+ className="mt-1 text-xs text-blue-400 hover:text-blue-300"+ >+ {showRaw ? "Show rendered" : "Show raw"}+ </button>+ </div>+ );+}++function StringLeaf({ text }: { text: string }) {+ const [expanded, setExpanded] = useState(false);++ if (text.length <= LONG_STRING_PREVIEW_CHARS) {+ return (+ <code className="whitespace-pre-wrap break-all rounded bg-zinc-800 px-1.5 py-0.5 text-xs text-amber-100">+ {text}+ </code>+ );+ }++ return (+ <div className="min-w-0">+ <pre className="mt-1 max-h-96 overflow-auto whitespace-pre-wrap break-all rounded-lg border border-zinc-800 bg-zinc-950 p-2 text-xs text-amber-100">+ {expanded ? text : `${text.slice(0, LONG_STRING_PREVIEW_CHARS)}…`}+ </pre>+ <button+ onClick={() => setExpanded(!expanded)}+ className="mt-1 text-xs text-blue-400 hover:text-blue-300"+ >+ {expanded+ ? "Collapse"+ : `Show all ${text.length.toLocaleString()} chars`}+ </button>+ </div>+ );+}++function ScalarLeaf({ label, value }: { label: string; value: unknown }) {+ if (typeof value === "string") {+ if (+ PROSE_KEYS.has(label) &&+ value.length > 80 &&+ value.length <= MARKDOWN_MAX_CHARS+ ) {+ return <MarkdownLeaf text={value} />;+ }+ return <StringLeaf text={value} />;+ }+ return (+ <code className="rounded bg-zinc-800 px-1.5 py-0.5 text-xs text-teal-300">+ {value === null ? "null" : String(value)}+ </code>+ );+}++// Arrays under these keys hold tool definitions: collapse them by default and+// label each entry with the tool's name so the list scans as a name index.+const TOOL_ARRAY_KEYS = new Set(["tools", "function_declarations"]);++function toolEntryName(value: unknown): string | null {+ if (typeof value !== "object" || value === null || Array.isArray(value)) {+ return null;+ }+ const name = (value as Record<string, unknown>)["name"];+ return typeof name === "string" ? name : null;+}++export function JsonNode({+ label,+ value,+ depth,+ defaultOpen,+}: {+ label: string;+ value: unknown;+ depth: number;+ defaultOpen?: boolean;+}) {+ const [open, setOpen] = useState(defaultOpen ?? depth < 5);+ const media = mediaFromValue(value);+ const isContainer =+ typeof value === "object" && value !== null && !(media && !open);++ if (!isContainer || typeof value !== "object" || value === null) {+ return (+ <div className="flex min-w-0 items-start gap-2 py-0.5">+ <span className="shrink-0 font-mono text-xs text-violet-300">+ {label}:+ </span>+ {media ? (+ <MediaPreview media={media} />+ ) : (+ <ScalarLeaf label={label} value={value} />+ )}+ </div>+ );+ }++ const isToolArray = TOOL_ARRAY_KEYS.has(label) && Array.isArray(value);+ const entries: [string, unknown, boolean][] = Array.isArray(value)+ ? value.map((child, index) => {+ const toolName = isToolArray ? toolEntryName(child) : null;+ return [toolName ?? `[${index}]`, child, toolName !== null];+ })+ : Object.entries(value).map(([key, child]) => [key, child, false]);++ return (+ <div className="min-w-0">+ <button+ onClick={() => setOpen(!open)}+ className="flex items-center gap-2 rounded px-1 py-0.5 text-left hover:bg-zinc-800/60"+ >+ <span className="w-3 text-xs text-zinc-500">{open ? "▾" : "▸"}</span>+ <span className="font-mono text-xs text-violet-300">{label}</span>+ <span className="font-mono text-xs text-blue-400">+ {nodeSummary(value)}+ </span>+ </button>+ {open && (+ <div className="ml-2 border-l border-zinc-800 pl-4">+ {media && <MediaPreview media={media} />}+ {entries.map(([childLabel, childValue, isTool]) => (+ <JsonNode+ key={childLabel}+ label={childLabel}+ value={childValue}+ depth={depth + 1}+ defaultOpen={isTool ? false : undefined}+ />+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex 4709025b..d2f2f065 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -9,6 +9,7 @@ import BestOfNEvalsPage from "./components/evals/BestOfNEvalsPage.tsx";import AllEvalsPage from "./components/evals/AllEvalsPage.tsx";import OpenAIInputComparePage from "./components/evals/OpenAIInputComparePage.tsx";import PromptReportsPage from "./components/evals/PromptReportsPage.tsx";+import AgentRunsPage from "./components/evals/AgentRunsPage.tsx";ReactDOM.createRoot(document.getElementById("root")!).render(<React.StrictMode>@@ -23,6 +24,7 @@ ReactDOM.createRoot(document.getElementById("root")!).render(element={<OpenAIInputComparePage />}/><Route path="/evals/prompt-reports" element={<PromptReportsPage />} />+ <Route path="/evals/agent-runs" element={<AgentRunsPage />} /></Routes></Router><Toaster toastOptions={{ className: "dark:bg-zinc-950 dark:text-white" }} />