Compare commits

..
Author SHA1 Message Date
parkerpettitandGitHub 9e3be00b39 feat(dashboard): add trace timeline viewer (#3390)
## Summary

- add a Prime-styled synchronized timeline for agent lifecycle phases
and model-call activity
- render VF-native root-to-leaf `Branch` paths instead of inferring
harness-specific subagent identities or hierarchy
- keep each environment agent as the main lane and show one flat row per
native zero-based branch index, ordered by its first unique activity
- retain shared-prefix calls on every branch path and mute them visually
to distinguish reuse from branch-unique execution
- show the trace reward on every branch training sample
- preserve exact call identity, including repeated calls, node-less
calls, and explicitly unknown timing
- show input, cached input, total input, output, reasoning, maximum
context length, total tokens, and cost in timeline tooltips and Overview
when reported
- keep large multi-agent tab strips horizontally scrollable and
integrate with Messages and Rendered transcript modes
- reject stale timeline responses after episode selection changes and
preserve unknown completed-phase end timing
- retain report navigation, transcript highlighting, rendered-token
mode, and dashboard view-command support

## Screenshot of multiagent episode (with subagent calls)
Codex harness
<img width="2400" height="2490" alt="image"
src="https://github.com/user-attachments/assets/1fe4a274-5cf2-49de-adf8-f328086d9f4a"
/>

RLM harness
<img width="2400" height="3260" alt="image"
src="https://github.com/user-attachments/assets/1ea0d693-a72e-495d-8133-c5b82770f2a0"
/>

## Validation

- `uv run --frozen ruff check .`
- `uv run --frozen ruff format --check .`
- `node --check src/prime_rl/dashboard/static/app.js`
- real interactive Codex multi-agent episode projects 29 native branches
across four environment-agent traces, with every branch containing
exactly its root-to-leaf model calls and all 46 actual calls covered
- real interactive RLM multi-agent episode projects 40 native branches
across four environment-agent traces, with every branch containing
exactly its root-to-leaf model calls and all 125 actual calls covered
- captured full-episode Playwright screenshots of both branch timelines
2026-08-25 17:53:01 -07:00
5 changed files with 685 additions and 33 deletions
+3 -1
View File
@@ -3,7 +3,9 @@
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
directories (metrics, resolved configs, rollout traces, cited reports,
component logs) at
http://localhost:7788. Needs the `dashboard` extra. Every instance also serves
http://localhost:7788. The trace viewer includes transcript and synchronized
agent timeline views; timeline activities open the corresponding transcript
call. Needs the `dashboard` extra. Every instance also serves
the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
(one dashboard per host per user); `--isolated` serves only the given dirs and
skips the registry. See `skills/dashboard/SKILL.md` for discovery,
+305
View File
@@ -781,6 +781,306 @@ def traces_path(run: str, step: int, kind: str, subset: str) -> Path:
raise HTTPException(404, "no traces for this step/kind/subset")
def read_episode_record(path: Path, line: int) -> dict:
offsets = line_offsets(path)
if not 0 <= line < len(offsets):
raise HTTPException(404, "episode line out of range")
with path.open("rb") as f:
f.seek(offsets[line])
return orjson.loads(f.readline())
def message_text(message: dict) -> str:
content = message.get("content")
if isinstance(content, str):
return content
if isinstance(content, list):
return "".join(part.get("text", "") if isinstance(part, dict) else str(part) for part in content)
return "" if content is None else str(content)
def timeline_status(trace: dict) -> str:
if not trace.get("is_completed"):
return "running"
if not trace.get("ok") and (trace.get("errors") or trace.get("stop_condition") == "error"):
return "failed"
return "completed"
def timeline_reward(trace: dict) -> float | None:
rewards = [reward for reward in (trace.get("rewards") or {}).values() if isinstance(reward, dict)]
if not rewards:
return None
return sum(
(reward.get("score") or 0) * (reward.get("weight") if reward.get("weight") is not None else 1)
for reward in rewards
)
def trace_branch_paths(nodes: list[dict]) -> list[list[int]]:
"""Return VF-native root-to-leaf branches in leaf-index order."""
if not nodes:
return []
parents = {parent for node in nodes if isinstance((parent := node.get("parent")), int) and 0 <= parent < len(nodes)}
paths = []
for leaf in (index for index in range(len(nodes)) if index not in parents):
path = []
seen = set()
node_index: int | None = leaf
while isinstance(node_index, int) and 0 <= node_index < len(nodes) and node_index not in seen:
seen.add(node_index)
path.append(node_index)
node_index = nodes[node_index].get("parent")
paths.append(list(reversed(path)))
return paths
def token_usage(usage: dict) -> tuple[int | None, int | None, int | None]:
prompt_tokens = usage.get("prompt_tokens")
output_tokens = usage.get("completion_tokens")
if "cached_input_tokens" in usage:
return prompt_tokens, usage.get("cached_input_tokens"), output_tokens
cached_tokens = (usage.get("prompt_tokens_details") or {}).get("cached_tokens")
input_tokens = (
max(0, prompt_tokens - cached_tokens) if prompt_tokens is not None and cached_tokens else prompt_tokens
)
return input_tokens, cached_tokens, output_tokens
def activity_spans(
trace: dict,
node_indexes: set[int],
*,
include_unlinked: bool = False,
shared_node_indexes: set[int] | None = None,
) -> list[dict]:
nodes = trace.get("nodes") or []
spans = []
for call_index, call in enumerate(trace.get("calls") or []):
node_index = call.get("node")
if node_index is None:
if not include_unlinked:
continue
node = {}
elif node_index not in node_indexes:
continue
else:
node = nodes[node_index]
call_time = call.get("time") or {}
started = call_time.get("start")
ended = call_time.get("end")
usage = call.get("usage") or {}
input_tokens, cached_tokens, output_tokens = token_usage(usage)
reasoning_tokens = usage.get("reasoning_tokens")
if reasoning_tokens is None:
reasoning_tokens = (usage.get("completion_tokens_details") or {}).get("reasoning_tokens")
text = " ".join(message_text(node.get("message") or {}).split())
spans.append(
{
"kind": "model_call",
"label": f"turn {len(spans) + 1}",
"track": "activity",
"call_index": call_index,
"node_index": node_index,
"shared": node_index in shared_node_indexes if shared_node_indexes is not None else False,
"started_at": started,
"ended_at": ended,
"status": "completed" if ended is not None or trace.get("is_completed") else "running",
"snippet": text[:240],
"input_tokens": input_tokens,
"cached_tokens": cached_tokens,
"output_tokens": output_tokens,
"reasoning_tokens": reasoning_tokens,
"cost": usage.get("cost"),
}
)
return sorted(spans, key=lambda span: span["started_at"] if span["started_at"] is not None else float("inf"))
def lifecycle_spans(trace: dict) -> list[dict]:
timing = trace.get("timing") or {}
spans = []
for kind, label in (
("boot", "boot"),
("setup", "setup"),
("agent", "agent"),
("finalize", "finalize"),
("scoring", "scoring"),
):
span = timing.get(kind) or {}
if not span.get("start"):
continue
spans.append(
{
"kind": kind,
"label": label,
"track": "lifecycle",
"started_at": span["start"],
"ended_at": span.get("end") or None,
"status": "completed" if span.get("end") or trace.get("is_completed") else "running",
}
)
return spans
def timeline_lane(
trace: dict,
trace_index: int,
*,
label: str,
depth: int,
branch: bool,
lifecycle: list[dict],
activities: list[dict],
started_at: float | None = None,
) -> dict:
spans = lifecycle + activities
starts = [span["started_at"] for span in spans if span.get("started_at") is not None]
ends = [span["ended_at"] for span in spans if span.get("ended_at") is not None]
started = started_at if started_at is not None else min(starts or ends, default=None)
status = (
("completed" if all(span["status"] == "completed" for span in lifecycle + activities) else "running")
if branch
else timeline_status(trace)
)
ended = max(ends, default=None) if status != "running" else None
agent = trace.get("agent") or {}
config = agent.get("config") or {}
client = config.get("client") or {}
def total(field: str) -> int | float | None:
values = [span[field] for span in activities if isinstance(span.get(field), (int, float))]
return sum(values) if values else None
input_tokens = total("input_tokens")
cached_tokens = total("cached_tokens")
output_tokens = total("output_tokens")
reasoning_tokens = total("reasoning_tokens")
total_input_tokens = input_tokens + (cached_tokens or 0) if input_tokens is not None else None
total_tokens = (
total_input_tokens + output_tokens if total_input_tokens is not None and output_tokens is not None else None
)
context_lengths = [
(span.get("input_tokens") or 0) + (span.get("cached_tokens") or 0)
for span in activities
if span.get("input_tokens") is not None
]
return {
"trace_index": trace_index,
"label": label,
"model": config.get("model") or client.get("renderer_model_name") or "",
"depth": depth,
"started_at": started,
"ended_at": ended,
"status": status,
"outcome": status if branch else (trace.get("stop_condition") or status),
"reward": timeline_reward(trace),
"usage": {
"model_calls": len(activities),
"input_tokens": input_tokens,
"cached_tokens": cached_tokens,
"total_input_tokens": total_input_tokens,
"output_tokens": output_tokens,
"reasoning_tokens": reasoning_tokens,
"max_context_tokens": max(context_lengths, default=None),
"total_tokens": total_tokens,
"cost": total("cost"),
},
"spans": spans,
}
def project_episode_timeline(episode: dict) -> dict:
lane_groups = []
for trace_index, trace in enumerate(episode.get("traces") or []):
nodes = trace.get("nodes") or []
branch_paths = trace_branch_paths(nodes)
node_branch_counts: dict[int, int] = {}
for path in branch_paths:
for node_index in path:
node_branch_counts[node_index] = node_branch_counts.get(node_index, 0) + 1
role = (trace.get("agent") or {}).get("name") or "agent"
parent = timeline_lane(
trace,
trace_index,
label=role,
depth=0,
branch=False,
lifecycle=lifecycle_spans(trace),
activities=activity_spans(trace, set(), include_unlinked=True),
started_at=(trace.get("timing") or {}).get("start"),
)
branches = []
for branch_index, path in enumerate(branch_paths):
node_indexes = set(path)
shared_node_indexes = {node_index for node_index in path if node_branch_counts.get(node_index, 0) > 1}
unique_node_indexes = node_indexes - shared_node_indexes
activities = activity_spans(
trace,
node_indexes,
shared_node_indexes=shared_node_indexes,
)
path_timestamps = [
nodes[node_index].get("timestamp")
for node_index in path
if nodes[node_index].get("timestamp") is not None
]
unique_timestamps = [
nodes[node_index].get("timestamp")
for node_index in unique_node_indexes
if nodes[node_index].get("timestamp") is not None
]
activity_starts = [span["started_at"] for span in activities if span["started_at"] is not None]
unique_activity_starts = [
span["started_at"] for span in activities if not span["shared"] and span["started_at"] is not None
]
branch_start = min(activity_starts or path_timestamps, default=None)
sort_start = min(
unique_activity_starts or unique_timestamps or activity_starts or path_timestamps, default=None
)
branch_end = max(
[span["ended_at"] for span in activities if span.get("ended_at") is not None] + path_timestamps,
default=None,
)
branch_completed = bool(trace.get("is_completed"))
label = f"branch {branch_index}"
branch_lifecycle = (
[
{
"kind": "agent",
"label": label,
"track": "lifecycle",
"started_at": branch_start,
"ended_at": branch_end if branch_completed else None,
"status": "completed" if branch_completed else "running",
"node_index": path[-1],
}
]
if branch_start is not None
else []
)
branches.append(
(
sort_start,
branch_index,
timeline_lane(
trace,
trace_index,
label=label,
depth=1,
branch=True,
lifecycle=branch_lifecycle,
activities=activities,
),
)
)
branches.sort(key=lambda item: (item[0] if item[0] is not None else float("inf"), item[1]))
lane_groups.append((parent, [lane for _, _, lane in branches]))
lane_groups.sort(key=lambda group: group[0]["started_at"] if group[0]["started_at"] is not None else float("inf"))
lanes = [lane for parent, children in lane_groups for lane in (parent, *children)]
return {"lanes": lanes}
@app.get("/api/runs/{run}/rollouts")
def list_rollouts(run: str) -> dict:
return {"steps": rollout_steps(get_run_dir(run))}
@@ -1147,6 +1447,11 @@ async def view_events() -> "StreamingResponse":
)
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/{line}/timeline")
def get_episode_timeline(run: str, step: int, kind: str, subset: str, line: int) -> dict:
return project_episode_timeline(read_episode_at(traces_path(run, step, kind, subset), line))
# -------------------------------------------------------------------------- static
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
+297 -32
View File
@@ -1962,6 +1962,10 @@ let currentTraceIdx = 0;
let currentBranchIdx = 0;
let episodeOpenVersion = 0;
let episodeEnrichmentVersion = 0;
let currentTimeline = null;
let traceView = prefs.traceView === "timeline" ? "timeline" : "transcript";
let pendingTimelineNode = null;
let pendingTimelineCall = null;
const COPY_SVG =
`<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">` +
@@ -2075,6 +2079,20 @@ function fetchEpisode(line, withTokens, withRendered = false) {
return api(`/api/runs/${encodeURIComponent(state.run)}/rollouts/${traces.step}/${traces.kind}/${traces.subset}/${line}${qs}`);
}
function fetchEpisodeTimeline(line) {
const traces = state.traces;
return api(`/api/runs/${encodeURIComponent(state.run)}/rollouts/${traces.step}/${traces.kind}/${traces.subset}/${line}/timeline`);
}
async function ensureTimeline() {
if (currentTimeline || currentLine == null) return;
const line = currentLine;
const requestVersion = episodeOpenVersion;
const timeline = await fetchEpisodeTimeline(line);
if (line !== currentLine || requestVersion !== episodeOpenVersion) return;
currentTimeline = timeline;
}
/* token strings multiply the payload of a big episode, so they are fetched only
for token signals or the rendered-token view — the plain view ships the raw record */
async function ensureTokens() {
@@ -2103,7 +2121,11 @@ async function openEpisode(line, target = {}) {
renderModalStep();
renderRolloutList();
$("#tm-messages").innerHTML = `<div class="chart-empty">loading episode…</div>`;
$("#tm-timeline").innerHTML = `<div class="chart-empty">loading timeline…</div>`;
$("#tm-meta").innerHTML = "";
currentTimeline = null;
pendingTimelineNode = null;
pendingTimelineCall = null;
const withTokens = !!$("#token-signal").value;
const withRendered = state.traces.viewMode === "rendered";
const episode = await fetchEpisode(line, withTokens, withRendered);
@@ -2113,6 +2135,7 @@ async function openEpisode(line, target = {}) {
currentEpisode = episode;
currentTraceIdx = target.trace ?? 0;
currentBranchIdx = target.branch ?? 0;
if (traceView === "timeline") await ensureTimeline();
renderEpisode();
await ensureTokens();
if (line === currentLine && requestVersion === episodeOpenVersion) renderEpisode();
@@ -2125,6 +2148,9 @@ function closeDrawer() {
$("#drawer-backdrop").hidden = true;
$("#tm-back").hidden = true;
currentEpisode = null;
currentTimeline = null;
pendingTimelineNode = null;
pendingTimelineCall = null;
currentLine = null;
pendingHighlight = null;
}
@@ -2367,6 +2393,22 @@ function errorBannersHtml(errors) {
);
}
function normalizedCallUsage(usage = {}) {
let input = usage.prompt_tokens;
let cached = usage.cached_input_tokens;
if (cached == null) {
cached = usage.prompt_tokens_details?.cached_tokens;
if (input != null && cached) input = Math.max(0, input - cached);
}
return {
input,
cached,
output: usage.completion_tokens,
reasoning: usage.reasoning_tokens ?? usage.completion_tokens_details?.reasoning_tokens,
cost: usage.cost,
};
}
function renderMessages(ep, trace, branches) {
const container = $("#tm-messages");
entriesObserver?.disconnect();
@@ -2387,7 +2429,22 @@ function renderMessages(ep, trace, branches) {
let maxAbsAdv = 0;
for (const node of trace.nodes || [])
for (const a of node.advantages || []) maxAbsAdv = Math.max(maxAbsAdv, Math.abs(a));
const callsByNode = new Map((trace.calls || []).map((c) => [c.node, c]));
const indexedCalls = (trace.calls || []).map((call, index) => ({ call, index }));
const callsByNode = new Map();
for (const item of indexedCalls) {
const calls = callsByNode.get(item.call.node) || [];
calls.push(item);
callsByNode.set(item.call.node, calls);
}
const callChipHtml = ({ call, index }) => {
const fields = [`call ${index + 1}`];
if (call.finish_reason) fields.push(call.finish_reason);
const { input, cached, output } = normalizedCallUsage(call.usage);
if (input != null) fields.push(`${fmtCompact(input)} in`);
if (cached != null) fields.push(`${fmtCompact(cached)} cache`);
if (output != null) fields.push(`${fmtCompact(output)} out`);
return `<span class="chip" data-call-index="${index}">${esc(fields.join(" · "))}</span>`;
};
// agent highlights (sticky until the next view command or drawer close)
const hl =
pendingHighlight &&
@@ -2407,14 +2464,12 @@ function renderMessages(ep, trace, branches) {
const entryHtml = (idx, i) => {
const node = trace.nodes[idx];
const role = node.message?.role ?? "?";
const call = callsByNode.get(idx);
const marks = hlByNode.get(idx) || [];
const chips = [];
if (concatenated && node.parent != null && node.parent !== idx - 1) chips.push(`↳ branches from ${node.parent + 1}`);
if (node.sampled) chips.push("sampled");
if (call?.finish_reason) chips.push(call.finish_reason);
if (call?.usage) chips.push(`${call.usage.prompt_tokens ?? "?"}→${call.usage.completion_tokens ?? "?"} tok`);
else if (node.token_ids?.length) chips.push(`${node.token_ids.length} tok`);
const nodeCalls = callsByNode.get(idx) || [];
if (!nodeCalls.length && node.token_ids?.length) chips.push(`${node.token_ids.length} tok`);
const text = messageText(node.message);
const contentMarks = marks.filter((h) => !h.field || h.field === "content");
const contentMarked = contentMarks.some((h) => h.quote && findQuote(text, h.quote, h.prefix, h.suffix));
@@ -2431,11 +2486,12 @@ function renderMessages(ep, trace, branches) {
if (reasoning) subs.push(reasoningBlock(reasoning, reasoningMarks));
const toolCalls = (node.message?.tool_calls || []).map(toolCallHtml);
const messageHtml =
`<details class="entry ${esc(role)}${marked ? " hl-entry" : ""}"${role === "system" && !marked ? "" : " open"}>` +
`<details class="entry ${esc(role)}${marked ? " hl-entry" : ""}" data-node="${idx}"${role === "system" && !marked ? "" : " open"}>` +
`<summary><span class="entry-num">${String(i + 1).padStart(2, "0")}</span>` +
`<span class="entry-role">${esc(role)}</span>` +
`<span class="entry-preview">${preview(text, 180)}</span>` +
chips.map((c) => `<span class="chip">${esc(c)}</span>`).join("") +
nodeCalls.map(callChipHtml).join("") +
`<button class="icon-btn" data-copy="${idx}" title="copy message">${COPY_SVG}</button>` +
`<span class="entry-chev">›</span></summary>` +
subs.join("") +
@@ -2449,11 +2505,23 @@ function renderMessages(ep, trace, branches) {
// first chunk forces enough entries into the DOM to scroll to
const CHUNK = 30;
const lastMark = Math.max(-1, ...[...hlByNode.keys()].map((n) => path.indexOf(n)));
let rendered = Math.min(path.length, Math.max(CHUNK, lastMark + 3));
const targetPosition = pendingTimelineNode == null ? -1 : path.indexOf(pendingTimelineNode);
let rendered = Math.min(path.length, Math.max(CHUNK, lastMark + 3, targetPosition + 1));
const unlinkedCallsHtml = indexedCalls
.filter(({ call }) => !Number.isInteger(call.node) || call.node < 0 || call.node >= (trace.nodes || []).length)
.map(
(item) =>
`<details class="entry model-call" data-call-index="${item.index}" open>` +
`<summary><span class="entry-num">C${String(item.index + 1).padStart(2, "0")}</span>` +
`<span class="entry-role">model call</span><span class="entry-preview">${esc(item.call.model || "unlinked call")}</span>` +
`${callChipHtml(item)}<span class="entry-chev">›</span></summary></details>`,
)
.join("");
container.innerHTML =
(systemPosition === -1 ? toolsHtml : "") +
path.slice(0, rendered).map(entryHtml).join("") +
(rendered < path.length ? `<div id="tm-more" class="chart-empty">scroll for ${path.length - rendered} more entries</div>` : "") +
unlinkedCallsHtml +
errorsHtml;
if (hl && !hl.scrolled) {
const first = container.querySelector(".hl-entry");
@@ -2537,28 +2605,35 @@ function renderMeta(ep, trace, branches) {
parts.push(metaRow("branches", branches.length));
parts.push(metaRow("tool calls", nodes.reduce((acc, n) => acc + (n.message?.tool_calls?.length || 0), 0)));
const usage = { input: 0, output: 0, reasoning: 0, cached: 0 };
let hasUsage = false;
const usage = { input: null, output: null, reasoning: null, cached: null, maxContext: null, cost: null };
const addUsage = (field, value) => {
if (value != null) usage[field] = (usage[field] ?? 0) + value;
};
for (const call of trace.calls || []) {
const u = call.usage || {};
if (u.prompt_tokens != null || u.completion_tokens != null) hasUsage = true;
usage.input += u.prompt_tokens ?? 0;
usage.output += u.completion_tokens ?? 0;
usage.reasoning += u.completion_tokens_details?.reasoning_tokens ?? 0;
usage.cached += u.prompt_tokens_details?.cached_tokens ?? 0;
const current = normalizedCallUsage(call.usage);
addUsage("input", current.input);
addUsage("cached", current.cached);
addUsage("output", current.output);
addUsage("reasoning", current.reasoning);
addUsage("cost", current.cost);
if (current.input != null) {
const context = current.input + (current.cached ?? 0);
usage.maxContext = Math.max(usage.maxContext ?? 0, context);
}
}
const totalInput = usage.input == null ? null : usage.input + (usage.cached ?? 0);
const totalTokens = totalInput == null || usage.output == null ? null : totalInput + usage.output;
const hasUsage = usage.input != null || usage.cached != null || usage.output != null;
if (hasUsage) {
parts.push(`<div class="meta-sec">usage</div>`);
parts.push(metaRow("input tokens", fmtCompact(usage.input)));
parts.push(metaRow("output tokens", fmtCompact(usage.output)));
if (usage.reasoning) parts.push(metaRow("reasoning tokens", fmtCompact(usage.reasoning)));
if (usage.cached) parts.push(metaRow("cached tokens", fmtCompact(usage.cached)));
// API-priced runs report per-call cost; local deployments usually don't
const traceCost = (t) => (t.calls || []).reduce((acc, c) => acc + (c.usage?.cost ?? 0), 0);
const allTraces = ep.traces || [];
if (allTraces.some((t) => (t.calls || []).some((c) => c.usage?.cost != null)))
parts.push(metaRow("cost", fmtCost(allTraces.reduce((acc, t) => acc + traceCost(t), 0))));
parts.push(metaRow("total tokens", fmtCompact(usage.input + usage.output)));
if (usage.input != null) parts.push(metaRow("input tokens", fmtCompact(usage.input)));
if (usage.cached != null) parts.push(metaRow("cached input", fmtCompact(usage.cached)));
if (totalInput != null) parts.push(metaRow("total input", fmtCompact(totalInput)));
if (usage.output != null) parts.push(metaRow("output tokens", fmtCompact(usage.output)));
if (usage.reasoning != null) parts.push(metaRow("reasoning tokens", fmtCompact(usage.reasoning)));
if (usage.maxContext != null) parts.push(metaRow("max context length", fmtCompact(usage.maxContext)));
if (usage.cost != null) parts.push(metaRow("cost", fmtCost(usage.cost)));
if (totalTokens != null) parts.push(metaRow("total tokens", fmtCompact(totalTokens)));
}
parts.push(`<div class="meta-sec">state</div>`);
@@ -2598,6 +2673,122 @@ function renderMeta(ep, trace, branches) {
$("#tm-meta").innerHTML = parts.join("");
}
function timelineClock(ts) {
if (ts == null) return "—";
return new Date(ts * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
}
function timelineTipAttr(payload) {
return ` data-timeline-tip="${esc(JSON.stringify(payload))}"`;
}
function appendTimelineUsage(rows, usage, aggregate = false) {
if (!usage) return;
if (aggregate && usage.model_calls != null) rows.push(["model calls", fmtNum(usage.model_calls)]);
if (usage.input_tokens != null) rows.push(["input tokens", fmtCompact(usage.input_tokens)]);
if (usage.cached_tokens != null) rows.push(["cached input", fmtCompact(usage.cached_tokens)]);
if (usage.total_input_tokens != null) rows.push(["total input", fmtCompact(usage.total_input_tokens)]);
if (usage.output_tokens != null) rows.push(["output tokens", fmtCompact(usage.output_tokens)]);
if (usage.reasoning_tokens != null) rows.push(["reasoning tokens", fmtCompact(usage.reasoning_tokens)]);
if (usage.max_context_tokens != null) rows.push(["max context length", fmtCompact(usage.max_context_tokens)]);
if (usage.total_tokens != null) rows.push(["total tokens", fmtCompact(usage.total_tokens)]);
if (usage.cost != null) rows.push(["cost", fmtCost(usage.cost)]);
}
function timelineSpanHtml(lane, span, start, total) {
const partial = span.started_at == null || span.ended_at == null;
const left = span.started_at == null ? 0 : Math.max(0, Math.min(100, ((span.started_at - start) / total) * 100));
const width = partial ? 0.35 : Math.max(0.35, Math.min(100 - left, ((span.ended_at - span.started_at) / total) * 100));
const rows = [
["start", span.started_at == null ? "unknown" : timelineClock(span.started_at)],
["end", span.ended_at == null ? (span.status === "running" ? "open" : "unknown") : timelineClock(span.ended_at)],
["duration", partial ? "—" : fmtDuration(span.ended_at - span.started_at)],
];
if (span.track === "activity") {
if (span.shared) rows.push(["branch role", "shared prefix"]);
const totalInput = span.input_tokens == null ? null : span.input_tokens + (span.cached_tokens || 0);
appendTimelineUsage(rows, {
input_tokens: span.input_tokens,
cached_tokens: span.cached_tokens,
total_input_tokens: totalInput,
output_tokens: span.output_tokens,
reasoning_tokens: span.reasoning_tokens,
max_context_tokens: totalInput,
total_tokens: totalInput == null || span.output_tokens == null ? null : totalInput + span.output_tokens,
cost: span.cost,
});
} else {
appendTimelineUsage(rows, lane.usage, true);
}
const tip = timelineTipAttr({
kind: span.track === "activity" ? "activity" : "lifecycle",
title: `${lane.label} — ${span.label}`,
snippet: span.snippet || "",
rows,
hint: span.track === "activity" ? "Click to open this call in the transcript." : "Click to open this trace transcript.",
});
const node = span.node_index == null ? "" : ` data-tl-node="${span.node_index}"`;
const call = span.call_index == null ? "" : ` data-tl-call="${span.call_index}"`;
return (
`<button class="tl-span ${esc(span.track)} ${esc(span.kind)} ${span.shared ? "shared" : ""} ${span.status === "running" ? "running" : ""} ${partial ? "untimed" : ""}"` +
` style="left:${left.toFixed(3)}%;width:${width.toFixed(3)}%" data-tl-trace="${lane.trace_index}"${node}${call}${tip}></button>`
);
}
function timelineLaneHtml(lane, start, total) {
const grids = [25, 50, 75].map((left) => `<i class="tl-gridline" style="left:${left}%"></i>`).join("");
const spans = (lane.spans || []).map((span) => timelineSpanHtml(lane, span, start, total)).join("");
const duration = lane.started_at == null || lane.ended_at == null ? "—" : fmtDuration(lane.ended_at - lane.started_at);
const ended = lane.ended_at == null ? (lane.status === "running" ? "open" : "unknown") : timelineClock(lane.ended_at);
const model = lane.model
? `<div class="tl-label-meta" title="${esc(lane.model)}">${esc(lane.model)}</div>`
: "";
return (
`<div class="tl-lane" data-tl-trace="${lane.trace_index}">` +
`<div class="tl-label" style="padding-left:${10 + (lane.depth || 0) * 18}px">` +
`${lane.depth ? '<span class="tl-tree">└</span>' : ""}<span class="tl-dot" style="background:${PALETTE[lane.trace_index % PALETTE.length]}"></span>` +
`<span class="tl-label-copy"><div class="tl-label-name" title="${esc(lane.label)}">${esc(lane.label)}</div>` +
`${model}</span></div>` +
`<div class="tl-track">${grids}${spans}</div>` +
`<div class="tl-time"><span>${duration}</span><span class="muted">${ended}</span></div>` +
`<div class="tl-outcome"><span class="tl-state ${esc(lane.status)}">${esc(lane.outcome || lane.status)}</span>` +
`${lane.reward == null ? "" : `<span class="tl-reward">reward ${fmtReward(lane.reward)}</span>`}</div></div>`
);
}
function renderTimeline() {
const target = $("#tm-timeline");
const timeline = currentTimeline;
if (!timeline) {
target.innerHTML = `<div class="chart-empty">loading timeline…</div>`;
return;
}
if (!(timeline.lanes || []).length) {
target.innerHTML = emptyState("no timeline", "this episode carries no agent traces");
return;
}
const starts = timeline.lanes.map((lane) => lane.started_at).filter((value) => value != null);
const ends = timeline.lanes.map((lane) => lane.ended_at ?? lane.started_at).filter((value) => value != null);
const start = starts.length ? Math.min(...starts) : 0;
const end = ends.length ? Math.max(...ends) : start + 1;
const total = Math.max(1, end - start);
const axis = [0, 0.25, 0.5, 0.75, 1]
.map((fraction) => `<span style="left:${fraction * 100}%">${fraction ? fmtDuration(total * fraction) : "0"}</span>`)
.join("");
target.innerHTML =
`<div class="tl-shell"><div class="tl-head"><span>branches</span><div class="tl-axis">${axis}</div><span>duration / end</span><span>state / outcome</span></div>` +
timeline.lanes.map((lane) => timelineLaneHtml(lane, start, total)).join("") +
`</div>`;
}
async function setTraceView(view) {
traceView = view;
setActive("#tm-view", "view", view);
if (view === "timeline") await ensureTimeline();
renderEpisode();
savePrefs();
}
function renderEpisode() {
const ep = currentEpisode;
if (!ep) return;
@@ -2608,14 +2799,10 @@ function renderEpisode() {
if (currentBranchIdx >= branches.length) currentBranchIdx = 0;
const traceTabs = $("#tm-trace-tabs");
traceTabs.hidden = traces.length <= 1;
// multi-agent episodes: label each trace by its agent name (seat), index only
// as a tiebreak when names repeat or are missing
const names = traces.map((t) => t.agent?.name);
const label = (i) => (names[i] && names.indexOf(names[i]) === names.lastIndexOf(names[i]) ? names[i] : `${names[i] ?? "trace"} ${i}`);
traceTabs.innerHTML =
traces.length > 1
? traces
.map((_, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}">${esc(label(i))}</button>`)
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}">${esc(trace.agent?.name || "agent")}</button>`)
.join("")
: "";
const branchTabs = $("#tm-branch-tabs");
@@ -2627,10 +2814,18 @@ function renderEpisode() {
.join("") +
`<button data-branch="-1" class="${currentBranchIdx === -1 ? "active" : ""}" title="all branches concatenated top to bottom">all</button>`
: "";
$("#tm-tabs-row").hidden = traceTabs.hidden && branchTabs.hidden;
setActive("#trace-view-mode", "mode", state.traces.viewMode);
renderRolloutList();
renderMessages(ep, trace, branches);
const timeline = traceView === "timeline";
$("#tm-tabs-row").hidden = timeline || (traceTabs.hidden && branchTabs.hidden);
$("#tm-messages").hidden = timeline;
$("#tm-timeline").hidden = !timeline;
$("#token-signal").closest(".dd-select").hidden = timeline;
$("#tm-collapse").hidden = timeline;
$("#tm-expand").hidden = timeline;
setActive("#tm-view", "view", traceView);
if (timeline) renderTimeline();
else renderMessages(ep, trace, branches);
renderMeta(ep, trace, branches);
}
@@ -3654,6 +3849,75 @@ $("#trace-view-mode").addEventListener("click", async (e) => {
renderEpisode();
savePrefs();
});
$("#tm-view").addEventListener("click", (e) => {
const button = e.target.closest("[data-view]");
if (button && button.dataset.view !== traceView) setTraceView(button.dataset.view);
});
$("#tm-timeline").addEventListener("click", async (e) => {
const target = e.target.closest("[data-tl-trace]");
if (!target) return;
e.stopPropagation();
currentTraceIdx = +target.dataset.tlTrace;
const node = target.dataset.tlNode == null ? null : +target.dataset.tlNode;
const call = target.dataset.tlCall == null ? null : +target.dataset.tlCall;
if (node != null) {
const trace = currentEpisode?.traces?.[currentTraceIdx];
const branches = trace ? traceBranches(trace) : [];
const branch = branches.findIndex((path) => path.includes(node));
currentBranchIdx = branch >= 0 ? branch : -1;
pendingTimelineNode = node;
pendingTimelineCall = call;
state.traces.viewMode = "messages";
} else {
currentBranchIdx = 0;
pendingTimelineNode = null;
pendingTimelineCall = call;
if (call != null) state.traces.viewMode = "messages";
}
await setTraceView("transcript");
requestAnimationFrame(() => {
const entry =
pendingTimelineCall == null
? pendingTimelineNode == null
? null
: $(`#tm-messages [data-node="${pendingTimelineNode}"]`)
: $(`#tm-messages [data-call-index="${pendingTimelineCall}"]`);
entry?.scrollIntoView({ block: "center" });
const details = entry?.closest("details");
if (details) details.open = true;
pendingTimelineNode = null;
pendingTimelineCall = null;
});
});
const timelineTip = document.createElement("div");
timelineTip.className = "tl-tooltip";
timelineTip.hidden = true;
document.body.appendChild(timelineTip);
function moveTimelineTip(e) {
const gap = 12;
const left = Math.min(e.clientX + gap, window.innerWidth - timelineTip.offsetWidth - 8);
const top = Math.min(e.clientY + gap, window.innerHeight - timelineTip.offsetHeight - 8);
timelineTip.style.left = `${Math.max(8, left)}px`;
timelineTip.style.top = `${Math.max(8, top)}px`;
}
$("#tm-timeline").addEventListener("mouseover", (e) => {
const target = e.target.closest("[data-timeline-tip]");
if (!target) return;
const payload = JSON.parse(target.dataset.timelineTip);
timelineTip.innerHTML =
`<div class="tl-tooltip-kind">${esc(payload.kind)}</div><div class="tl-tooltip-title">${esc(payload.title)}</div>` +
`${payload.snippet ? `<div class="tl-tooltip-snippet">${esc(payload.snippet)}</div>` : ""}` +
`<dl>${payload.rows.map(([key, value]) => `<dt>${esc(key)}</dt><dd>${esc(value)}</dd>`).join("")}</dl>` +
`<div class="tl-tooltip-hint">${esc(payload.hint)}</div>`;
timelineTip.hidden = false;
moveTimelineTip(e);
});
$("#tm-timeline").addEventListener("mousemove", (e) => {
if (!timelineTip.hidden) moveTimelineTip(e);
});
$("#tm-timeline").addEventListener("mouseout", (e) => {
if (e.target.closest("[data-timeline-tip]") && !e.relatedTarget?.closest?.("[data-timeline-tip]")) timelineTip.hidden = true;
});
$("#tm-trace-tabs").addEventListener("click", (e) => {
const btn = e.target.closest("[data-trace]");
if (btn) { currentTraceIdx = +btn.dataset.trace; currentBranchIdx = 0; renderEpisode(); }
@@ -3734,6 +3998,7 @@ function savePrefs() {
traceErrorsOnly: state.traces.errorsOnly,
traceSort: `${state.traces.sort}:${state.traces.order}`,
traceViewMode: state.traces.viewMode,
traceView,
logView: state.logs.view,
logComponents: state.logs.components ? [...state.logs.components] : null,
logLevel: state.logs.level,
+5
View File
@@ -203,6 +203,10 @@
<div class="tm-head">
<span class="tm-title">Trace Viewer</span>
<button id="tm-back" class="btn" hidden title="back to the report">← report</button>
<div class="seg" id="tm-view">
<button data-view="transcript" class="active">Transcript</button>
<button data-view="timeline">Timeline</button>
</div>
<div class="spacer"></div>
<div class="seg" id="trace-view-mode">
<button data-mode="messages" class="active">Messages</button>
@@ -224,6 +228,7 @@
<div id="tm-branch-tabs" class="seg" hidden></div>
</div>
<div id="tm-messages"></div>
<div id="tm-timeline" hidden></div>
</section>
<aside id="tm-right">
<div class="tm-head"><span class="tm-title">Overview</span></div>
+75
View File
@@ -643,6 +643,12 @@ mark.hit {
border-bottom: 1px solid var(--hairline);
min-height: 48px;
}
.tm-tabs-row {
min-width: 0;
overflow-x: auto;
overflow-y: hidden;
scrollbar-width: thin;
}
.tm-title { font-size: 12px; font-weight: 500; color: var(--grey-6); white-space: nowrap; }
#tm-left { border-right: 1px solid var(--hairline); display: flex; flex-direction: column; min-height: 0; }
#tm-left .search { margin: 10px 14px 6px; }
@@ -686,9 +692,78 @@ mark.hit {
#tm-main { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
#tm-messages { display: flex; flex: 1; flex-direction: column; overflow-y: auto; padding: 14px 16px; }
#tm-messages > * { flex-shrink: 0; }
#tm-timeline { flex: 1; min-height: 0; overflow: auto; padding: 14px 16px 24px; }
#tm-right { border-left: 1px solid var(--hairline); overflow-y: auto; min-height: 0; }
#tm-meta { padding: 12px 14px; }
/* episode timeline: lifecycle spans above exact model-call activity */
.tl-shell { min-width: 780px; border: 1px solid var(--hairline); }
.tl-head, .tl-lane {
display: grid;
grid-template-columns: minmax(160px, 220px) minmax(390px, 1fr) 105px 150px;
}
.tl-head {
min-height: 42px;
align-items: end;
color: var(--grey-4);
font-size: 9px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
border-bottom: 1px solid var(--grey-3);
}
.tl-head > span { padding: 8px 10px; }
.tl-axis { position: relative; align-self: stretch; min-width: 0; }
.tl-axis span { position: absolute; bottom: 8px; transform: translateX(-50%); white-space: nowrap; }
.tl-axis span:first-child { transform: none; }
.tl-axis span:last-child { transform: translateX(-100%); }
.tl-lane { min-height: 66px; border-bottom: 1px solid var(--hairline-faint); cursor: pointer; }
.tl-lane:last-child { border-bottom: 0; }
.tl-lane:hover { background: rgba(255, 255, 255, 0.025); }
.tl-label, .tl-time, .tl-outcome { padding: 11px 10px; min-width: 0; }
.tl-label { display: flex; align-items: flex-start; gap: 8px; }
.tl-tree { color: var(--grey-3); flex-shrink: 0; }
.tl-dot { width: 6px; height: 6px; margin-top: 5px; background: var(--chart-2); flex-shrink: 0; }
.tl-label-copy { min-width: 0; }
.tl-label-name { color: var(--grey-6); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tl-label-meta { color: var(--grey-4); font-size: 9.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tl-track { position: relative; height: 42px; margin: 11px 0; border: 1px solid var(--hairline); overflow: hidden; }
.tl-gridline { position: absolute; top: 0; bottom: 0; border-left: 1px solid var(--hairline-faint); pointer-events: none; }
.tl-span { position: absolute; min-width: 3px; cursor: pointer; border: 0; padding: 0; }
.tl-span.lifecycle { top: 7px; height: 13px; opacity: 0.78; }
.tl-span.activity { top: 28px; height: 6px; background: var(--grey-4); }
.tl-span.activity.shared { opacity: 0.28; }
.tl-span.untimed { border-left: 3px double var(--grey-6); }
.tl-span:hover, .tl-span:focus-visible { opacity: 1; outline: 1px solid var(--grey-6); outline-offset: 1px; }
.tl-span.boot, .tl-span.setup { background: var(--grey-4); }
.tl-span.agent { background: var(--chart-2); }
.tl-span.finalize { background: var(--chart-1); }
.tl-span.scoring { background: var(--chart-3); }
.tl-span.running { border-right: 2px solid var(--accent); }
.tl-time { color: var(--grey-5); font-size: 11px; }
.tl-time .muted { display: block; font-size: 9.5px; }
.tl-outcome { display: flex; flex-direction: column; align-items: flex-start; gap: 5px; font-size: 9.5px; }
.tl-state, .tl-reward { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
.tl-state.completed { color: var(--positive); }
.tl-state.failed { color: var(--negative); }
.tl-state.running { color: var(--infra); }
.tl-reward { color: var(--chart-3); }
.tl-tooltip {
position: fixed;
z-index: 60;
width: min(390px, calc(100vw - 24px));
padding: 12px 14px;
background: var(--grey-1);
border: 1px solid var(--grey-3);
pointer-events: none;
}
.tl-tooltip-kind { color: var(--accent); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
.tl-tooltip-title { color: var(--grey-6); font-size: 12px; margin: 3px 0 8px; }
.tl-tooltip-snippet { color: var(--grey-5); font-size: 11px; margin-bottom: 9px; white-space: normal; }
.tl-tooltip dl { display: grid; grid-template-columns: auto 1fr; gap: 2px 16px; margin: 0; font-size: 10.5px; }
.tl-tooltip dt { color: var(--grey-4); }
.tl-tooltip dd { color: var(--grey-6); margin: 0; }
.tl-tooltip-hint { color: var(--grey-4); border-top: 1px solid var(--hairline); margin-top: 9px; padding-top: 7px; font-size: 9.5px; }
.trace-errors { margin-top: auto; padding-top: 12px; }
.trace-error-banner {
border: 1px solid var(--negative);