Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(runs): turn the Run Inspector into a real developer forensics view

Ruben Lütke22aab71f95be
diff --git a/jarvis/runs/analyzer.py b/jarvis/runs/analyzer.py
index 7b3dfb0051..5668538928 100644
--- a/jarvis/runs/analyzer.py
+++ b/jarvis/runs/analyzer.py
@@ -12,6 +12,9 @@ from jarvis.runs.constants import (
DECISION_RISK,
DECISION_ROUTE,
DECISION_TIER,
+ EVENT_CAT_SYSTEM,
+ EVENT_CATEGORY_BY_KIND,
+ MAX_RAW_EVENTS_PER_TURN,
OUTCOME_FAILED,
OUTCOME_PARTIAL,
OUTCOME_SUCCESS,
@@ -30,15 +33,17 @@ from jarvis.runs.model import (
DecisionStep,
ErrorEntry,
LatencyEntry,
+ RawEvent,
RunActivity,
RunAnalytics,
+ RunEnvironment,
RunTurn,
ToolCall,
TraceEvent,
TranscriptLine,
TurnExtras,
)
-from jarvis.sessions.models import VoiceEventRow
+from jarvis.sessions.models import VoiceEventRow, VoiceSessionRow
# Per-phase SLO budget in ms. Phases not listed have no gate (always SLO_OK).
# Budgets mirror the documented voice SLOs: wake->ACK < 1.2s, intent->ACK < 3.0s,
@@ -170,9 +175,68 @@ def build_decision_path(events: list[VoiceEventRow]) -> list[DecisionStep]:
rationale="Handed the task to a background sub-agent.",
rationale_source=RATIONALE_RULE,
))
+ elif e.kind == "JarvisAgentTaskCompleted":
+ ok = bool(p.get("success"))
+ steps.append(DecisionStep(
+ kind=DECISION_MISSION,
+ label=("sub-agent finished" if ok else "sub-agent FAILED"),
+ detail=str(p.get("summary", ""))[:120] or None,
+ rationale=(
+ "The background sub-agent returned a result."
+ if ok else
+ f"The background sub-agent failed — {p.get('error', 'no reason recorded')}."
+ ),
+ rationale_source=RATIONALE_RULE,
+ ))
+ elif e.kind == "RealtimeSessionReady":
+ # The duplex path never emits BrainTurnStarted, so without this the
+ # whole decision path of a realtime turn was empty — the single
+ # biggest blind spot of the old inspector, since realtime is the
+ # default mode.
+ provider = str(p.get("provider", ""))
+ model = str(p.get("model", ""))
+ if provider:
+ providers_seen.append(provider)
+ steps.append(DecisionStep(
+ kind=DECISION_BRAIN,
+ label=f"realtime session: {provider or '?'}",
+ detail=(f"model={model}" if model else None),
+ rationale=(
+ f"A duplex (speech-to-speech) session with {provider}"
+ + (f" ({model})" if model else "")
+ + " accepted the configuration — this turn is answered live, "
+ "not through the classic transcribe → think → speak chain."
+ ),
+ rationale_source=RATIONALE_RULE,
+ ))
+ elif e.kind == "LatencySpan" and str(p.get("phase", "")) == "realtime_routing_decision":
+ # Honest reading: the span proves WHEN the router decided and how
+ # long it took — never WHAT it decided. Do not invent the verdict.
+ dur = _fmt_ms(p.get("duration_ms"))
+ steps.append(DecisionStep(
+ kind=DECISION_ROUTE,
+ label="realtime routing decision",
+ detail=dur or None,
+ rationale=f"The realtime router reached its decision in {dur or 'n/a'}.",
+ rationale_source=RATIONALE_RULE,
+ ))
+ elif e.kind == "BrainProviderSwitched":
+ frm = str(p.get("from_provider", "") or "?")
+ to = str(p.get("to_provider", "") or "?")
+ steps.append(DecisionStep(
+ kind=DECISION_FALLBACK,
+ label="provider switched",
+ detail=f"{frm} -> {to}",
+ rationale=(
+ f"The brain moved from {frm} to {to} — the configured provider "
+ "was unavailable, out of quota, or rejected the request, so the "
+ "key-aware fallback chain crossed to the next reachable one."
+ ),
+ rationale_source=RATIONALE_RULE,
+ ))
# A second distinct provider across the turn means the smart-fallback fired.
distinct = [p for i, p in enumerate(providers_seen) if p and p not in providers_seen[:i]]
- if len(distinct) > 1:
+ if len(distinct) > 1 and not any(s.kind == DECISION_FALLBACK for s in steps):
steps.append(DecisionStep(
kind=DECISION_FALLBACK,
label="provider fallback",
@@ -183,6 +247,33 @@ def build_decision_path(events: list[VoiceEventRow]) -> list[DecisionStep]:
return steps
+def ensure_brain_step(steps: list[DecisionStep], turn: RunTurn) -> list[DecisionStep]:
+ """Guarantee the path names WHO answered, even with no brain event captured.
+
+ Some turns (realtime, cached, tool-only) record no ``BrainTurnStarted`` and
+ no ``RealtimeSessionReady`` of their own, yet the aggregated turn row does
+ know the provider/model. Falling back to that row is honest — it is the
+ recorded answer — and keeps every turn from claiming "no decisions"."""
+ if any(s.kind == DECISION_BRAIN for s in steps) or not turn.provider:
+ return steps
+ tier = f"tier={turn.tier}" if turn.tier else ""
+ model = f"model={turn.model}" if turn.model else ""
+ steps.insert(0, DecisionStep(
+ kind=DECISION_BRAIN,
+ label=f"brain: {turn.provider}",
+ detail=_join([tier, model]) or None,
+ rationale=(
+ f"Answered by {turn.provider}"
+ + (f" ({turn.model})" if turn.model else "")
+ + ("" if not turn.tier else f" on the {turn.tier} tier")
+ + " — recorded on the turn aggregate; this turn emitted no separate "
+ "brain-start event."
+ ),
+ rationale_source=RATIONALE_RULE,
+ ))
+ return steps
+
+
def attach_tool_io(events: list[VoiceEventRow], tools: list[ToolCall]) -> list[ToolCall]:
"""Surface the already-captured command + result onto the tool rows.
@@ -571,27 +662,295 @@ def build_analytics(turns: list[RunTurn], *, started_ms: int,
)
-def _summarize(e: VoiceEventRow) -> str:
+def _fmt_ms(value: object) -> str:
+ try:
+ ms = float(value) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return ""
+ return f"{ms / 1000:.2f}s" if ms >= 1000 else f"{ms:.0f}ms"
+
+
+def _join(parts: list[str]) -> str:
+ return " · ".join(p for p in parts if p)
+
+
+def summarize_event(e: VoiceEventRow) -> str:
+ """A one-line human reading of ANY recorded event.
+
+ Before this, only six kinds had a summary and every other row in the
+ timeline rendered as a bare kind name with an empty right-hand column — in
+ a typical realtime run that was ~70% of all rows, which is exactly why the
+ timeline read as noise.
+
+ The contract now is a hard one: **a row is never blank while its event
+ carries a payload.** A kind-specific reading is tried first; when that comes
+ out empty — an unknown kind, or a known kind whose expected fields are
+ absent because the publisher changed — the payload itself is rendered
+ compactly instead of nothing."""
+ specific = _specific_summary(e)
+ if specific:
+ return specific
+ return _join([f"{key}={_short(val)}" for key, val in list(e.payload.items())[:4]])
+
+
+def _specific_summary(e: VoiceEventRow) -> str:
p = e.payload
- if e.kind == "TranscriptFinal":
- return str(p.get("text", ""))[:80]
- if e.kind == "ResponseGenerated":
- return str(p.get("text", ""))[:80]
- if e.kind == "IntentClassified":
- return f"{p.get('intent', '')} (risk={p.get('risk_tier', '')})"
- if e.kind in ("ActionProposed", "ActionApproved", "ActionDenied"):
- return str(p.get("tool_name", ""))
- if e.kind == "BrainTurnStarted":
- return f"{p.get('provider', '')}/{p.get('model', '')}"
- if e.kind == "SystemStateChanged":
- return f"{p.get('previous', '')} -> {p.get('new_state', '')}"
+ k = e.kind
+
+ # --- speech / transcript -----------------------------------------
+ if k in ("TranscriptFinal", "TranscriptPartial", "ResponseGenerated"):
+ return str(p.get("text", ""))[:160]
+ if k == "TranscriptionUpdate":
+ final = " (final)" if p.get("is_final") else ""
+ return f"{str(p.get('text', ''))[:120]}{final}"
+ if k == "SpeechSpoken":
+ kind = str(p.get("spoken_kind", "") or "spoken")
+ voice = str(p.get("voice", "") or "")
+ head = f"[{kind}]" + (f" {voice}" if voice else "")
+ return _join([head, str(p.get("text", ""))[:120], str(p.get("detail", ""))[:80]])
+ if k == "AudioOutFirst":
+ return "first audio frame reached the speaker"
+ if k == "ListeningStarted":
+ return "microphone open"
+ if k in ("WakeWordDetected", "HotkeyPressed"):
+ conf = p.get("confidence")
+ return _join([
+ str(p.get("keyword", "") or k),
+ f"confidence {float(conf):.2f}" if isinstance(conf, int | float) else "",
+ ])
+
+ # --- brain --------------------------------------------------------
+ if k == "IntentClassified":
+ return _join([str(p.get("intent", "")), f"risk={p.get('risk_tier', '')}"])
+ if k == "BrainTurnStarted":
+ return _join([
+ f"{p.get('provider', '?')}/{p.get('model', '?')}",
+ f"tier={p.get('intent_level', '')}" if p.get("intent_level") else "",
+ ])
+ if k == "BrainTurnCompleted":
+ return _join([
+ f"{p.get('provider', '')}/{p.get('model', '')}".strip("/"),
+ f"{p.get('tokens_in', 0)}+{p.get('tokens_out', 0)} tok",
+ f"${float(p.get('cost_usd', 0) or 0):.4f}",
+ f"finish={p.get('finish_reason', '')}" if p.get("finish_reason") else "",
+ ])
+ if k == "BrainTTFT":
+ return _join([
+ str(p.get("model", "")),
+ "prompt cache HIT" if p.get("cache_hit") else "prompt cache miss",
+ ])
+ if k == "BrainProviderSwitched":
+ return f"{p.get('from_provider', '?')} → {p.get('to_provider', '?')}"
+ if k == "FrontierModelSwitched":
+ return _join([
+ str(p.get("provider", "")),
+ f"{p.get('old_model', '?')} → {p.get('new_model', '?')}",
+ ])
+ if k == "BrainToolsChanged":
+ return str(p.get("reason", "") or "tool set refreshed")
+
+ # --- tools --------------------------------------------------------
+ if k == "ActionProposed":
+ return _join([
+ str(p.get("tool_name", "?")),
+ f"action={p.get('action', '')}" if p.get("action") else "",
+ f"risk={p.get('risk_tier', '')}" if p.get("risk_tier") else "",
+ str(p.get("args_preview", ""))[:80],
+ ])
+ if k in ("ActionApproved", "ActionApprovalRequired"):
+ return _join([str(p.get("tool_name", "?")), f"by={p.get('approved_by', '')}"])
+ if k == "ActionDenied":
+ return _join([str(p.get("tool_name", "?")), str(p.get("reason", ""))])
+ if k == "ActionExecuted":
+ ok = "ok" if p.get("success", True) else "FAILED"
+ return _join([str(p.get("tool_name", "?")), ok, str(p.get("error", ""))[:80]])
+ if k == "ToolCallStarted":
+ return _join([str(p.get("tool_name", "?")), str(p.get("args_preview", ""))[:100]])
+ if k == "ToolCallCompleted":
+ ok = "ok" if p.get("success", True) else "FAILED"
+ return _join([ok, _fmt_ms(p.get("duration_ms")),
+ str(p.get("output_preview", ""))[:100]])
+ if k == "CliInvoked":
+ return _join([str(p.get("cli_name", "?")), f"by {p.get('caller', '')}",
+ str(p.get("command_preview", ""))[:80]])
+ if k == "CliInvocationFinished":
+ return _join([str(p.get("cli_name", "?")), f"exit {p.get('exit_code')}",
+ _fmt_ms(p.get("duration_ms"))])
+
+ # --- agent / mission ----------------------------------------------
+ if k == "JarvisAgentTaskStarted":
+ return _join([f"{p.get('provider', '')}/{p.get('model', '')}".strip("/"),
+ str(p.get("utterance", ""))[:100]])
+ if k == "JarvisAgentReviewTriggered":
+ return f"critic loop iteration {p.get('iteration', '?')}"
+ if k == "JarvisAgentTaskCompleted":
+ ok = "success" if p.get("success") else "FAILED"
+ return _join([ok, _fmt_ms(float(p.get("duration_s", 0) or 0) * 1000),
+ str(p.get("summary", ""))[:100], str(p.get("error", "") or "")[:80]])
+ if k == "JarvisAgentAnnouncement":
+ return _join([str(p.get("action", "")), str(p.get("target", ""))])
+ if k in ("HarnessDispatched", "HarnessCompleted"):
+ return str(p.get("harness", "") or k)
+ if k == "MissionCompleted":
+ return _join([str(p.get("status", "")), str(p.get("summary_en", ""))[:100],
+ str(p.get("reason", ""))[:80]])
+
+ # --- vision / Computer-Use ----------------------------------------
+ if k == "ObservationCaptured":
+ return _join([str(p.get("source", "")), str(p.get("window_title", ""))[:60],
+ f"{p.get('node_count', 0)} UI nodes"])
+ if k == "VisionInjected":
+ return _join([f"{int(p.get('bytes_size', 0) or 0) // 1024} KB screenshot",
+ f"age {_fmt_ms(p.get('capture_age_ms'))}"])
+ if k == "ActionPlanned":
+ return _join([str(p.get("action_kind", "")), str(p.get("target_hint", ""))[:80]])
+ if k == "ActionVerified":
+ ok = "verified" if p.get("success") else "VERIFY FAILED"
+ return _join([str(p.get("action_kind", "")), ok, str(p.get("reason", ""))[:80]])
+ if k == "CUStepProfiled":
+ return _join([f"step {p.get('step_idx', '?')}", str(p.get("phase", "")),
+ _fmt_ms(p.get("duration_ms")), str(p.get("engine", ""))])
+ if k == "CUControlStarted":
+ return "took control of mouse + keyboard"
+ if k == "CUControlEnded":
+ return f"released control ({p.get('reason', '')})"
+
+ # --- lifecycle / system -------------------------------------------
+ if k == "SystemStateChanged":
+ return f"{p.get('previous', '')} → {p.get('new_state', '')}"
+ if k == "VoiceSessionStarted":
+ return _join([str(p.get("wake_keyword", "")), str(p.get("language", ""))])
+ if k == "VoiceSessionEnded":
+ return _join([f"hangup: {p.get('hangup_reason', '')}",
+ f"{p.get('turn_count', 0)} turns"])
+ if k == "VoiceTurnStarted":
+ return f"turn {int(p.get('turn_index', 0) or 0) + 1} opened"
+ if k == "VoiceTurnCompleted":
+ return _join([str(p.get("tier", "")), _fmt_ms(p.get("latency_total_ms")),
+ str(p.get("voice", ""))])
+ if k == "RealtimeSessionReady":
+ return _join([f"{p.get('provider', '')}/{p.get('model', '')}".strip("/"),
+ str(p.get("surface", "")),
+ f"{p.get('input_sample_rate', 0)}→{p.get('output_sample_rate', 0)} Hz"])
+
+ # --- latency / errors ---------------------------------------------
+ if k == "LatencySpan":
+ # The realtime path stamps the session id into ``detail``; repeating it
+ # on every span would bury the phase name under a UUID. The full
+ # payload stays one click away in the raw view.
+ detail = str(p.get("detail", ""))
+ if detail.startswith("session_id="):
+ detail = ""
+ return _join([str(p.get("phase", "")), _fmt_ms(p.get("duration_ms")), detail[:60]])
+ if k == "ErrorOccurred":
+ recov = "recoverable" if p.get("recoverable") else "UNRECOVERABLE"
+ return _join([f"{p.get('layer', '')}: {p.get('error_type', '')}".strip(": "),
+ str(p.get("message", ""))[:100], recov])
+
+ # No kind-specific reading — summarize_event falls back to the payload.
return ""
+def _short(v: object) -> str:
+ s = str(v)
+ return s if len(s) <= 40 else s[:37] + "…"
+
+
+# Back-compat alias — the module previously exposed the private name.
+_summarize = summarize_event
+
+
+def event_category(kind: str) -> str:
+ """UI lane for a raw event kind; unknown kinds degrade to "system"."""
+ return EVENT_CATEGORY_BY_KIND.get(kind, EVENT_CAT_SYSTEM)
+
+
+def build_raw_events(
+ events: list[VoiceEventRow], *, turn_started_ms: int = 0,
+ limit: int = MAX_RAW_EVENTS_PER_TURN,
+) -> tuple[list[RawEvent], bool]:
+ """The verbatim event stream + whether it had to be truncated.
+
+ Returns ``(rows, truncated)``. Truncation keeps the FIRST ``limit`` events
+ (chronological), because a run's opening is where routing/setup decisions
+ live; the caller reports the cut instead of hiding it."""
+ ordered = sorted(events, key=lambda x: (x.ts_ms, x.seq or 0))
+ truncated = len(ordered) > limit
+ rows = [
+ RawEvent(
+ seq=e.seq or 0,
+ kind=e.kind,
+ category=event_category(e.kind),
+ ts_ms=e.ts_ms,
+ offset_ms=max(0, e.ts_ms - turn_started_ms),
+ summary=summarize_event(e),
+ payload=dict(e.payload),
+ )
+ for e in ordered[:limit]
+ ]
+ return rows, truncated
+
+
+def build_event_counts(events: list[VoiceEventRow]) -> dict[str, int]:
+ """Event-kind histogram — the fastest read on "what dominated this run"."""
+ counts: dict[str, int] = {}
+ for e in events:
+ counts[e.kind] = counts.get(e.kind, 0) + 1
+ return dict(sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])))
+
+
+def build_environment(
+ session: VoiceSessionRow, events: list[VoiceEventRow], turns: list[RunTurn]
+) -> RunEnvironment:
+ """The run's configuration, read back from what was RECORDED.
+
+ Deliberately never consults the live config: a run inspected tomorrow must
+ show the setup it actually ran under, not today's settings."""
+ env = RunEnvironment(
+ voice_mode=session.voice_mode or "",
+ wake_source=wake_source(session.wake_keyword),
+ wake_keyword=session.wake_keyword or "",
+ language=session.language or "",
+ hangup_reason=session.hangup_reason or "",
+ providers=list(session.providers_used),
+ )
+ for e in sorted(events, key=lambda x: x.ts_ms):
+ p = e.payload
+ if e.kind == "RealtimeSessionReady":
+ env.surface = str(p.get("surface", "") or env.surface)
+ env.input_sample_rate = int(p.get("input_sample_rate", 0) or 0) or None
+ env.output_sample_rate = int(p.get("output_sample_rate", 0) or 0) or None
+ voice = str(p.get("voice", "") or "")
+ if voice and voice not in env.voices:
+ env.voices.append(voice)
+ for t in turns:
+ if t.provider and t.provider not in env.providers:
+ env.providers.append(t.provider)
+ if t.model and t.model not in env.models:
+ env.models.append(t.model)
+ if t.tier and t.tier not in env.tiers:
+ env.tiers.append(t.tier)
+ return env
+
+
+def wake_source(wake_keyword: str) -> str:
+ """voice | hotkey | channel:<name> — derived from the recorded keyword."""
+ kw = (wake_keyword or "").lower()
+ if "hotkey" in kw:
+ return "hotkey"
+ if kw.startswith("channel:"):
+ return kw
+ if kw in ("telegram", "discord", "web"):
+ return f"channel:{kw}"
+ return "voice"
+
+
__all__ = [
"classify_latency", "build_latency", "build_decision_path", "build_errors",
"build_extras", "build_transcript", "build_timeline", "tools_from_usage",
"merge_action_tools", "attach_tool_io", "build_analytics",
"turn_outcome", "build_outcome", "outcome_from_events", "build_activity",
"feature_tags_from_events",
+ "summarize_event", "event_category", "build_raw_events", "build_event_counts",
+ "build_environment", "ensure_brain_step", "wake_source",
]
diff --git a/jarvis/runs/constants.py b/jarvis/runs/constants.py
index 8a3efce037..50af5ca29a 100644
--- a/jarvis/runs/constants.py
+++ b/jarvis/runs/constants.py
@@ -69,6 +69,94 @@ TRANSCRIPT_ROLES: Final[tuple[str, ...]] = (
ROLE_USER, ROLE_JARVIS, ROLE_SYSTEM, ROLE_TOOL, ROLE_ERROR,
)
+# --- Raw-event lanes (the developer event stream) ---------------------
+# The Run Inspector's raw stream shows EVERY persisted bus event of a turn.
+# A flat list of 200 rows is unreadable, so each event kind is assigned one
+# lane the UI can colour and filter by. An unknown kind degrades to
+# EVENT_CAT_SYSTEM — never an error (BUG-008 string contract).
+EVENT_CAT_LIFECYCLE: Final[str] = "lifecycle" # session/turn boundaries, wake, state
+EVENT_CAT_SPEECH: Final[str] = "speech" # STT in, TTS out, audio marks
+EVENT_CAT_BRAIN: Final[str] = "brain" # provider/model/tokens/routing
+EVENT_CAT_TOOL: Final[str] = "tool" # tool + CLI calls and their approval
+EVENT_CAT_AGENT: Final[str] = "agent" # Jarvis-Agent / harness / mission
+EVENT_CAT_VISION: Final[str] = "vision" # Computer-Use observe/plan/act/verify
+EVENT_CAT_LATENCY: Final[str] = "latency" # measured spans
+EVENT_CAT_ERROR: Final[str] = "error" # errors, denials, budget stops
+EVENT_CAT_SYSTEM: Final[str] = "system" # everything else
+
+RUN_EVENT_CATEGORIES: Final[tuple[str, ...]] = (
+ EVENT_CAT_LIFECYCLE, EVENT_CAT_SPEECH, EVENT_CAT_BRAIN, EVENT_CAT_TOOL,
+ EVENT_CAT_AGENT, EVENT_CAT_VISION, EVENT_CAT_LATENCY, EVENT_CAT_ERROR,
+ EVENT_CAT_SYSTEM,
+)
+
+# kind -> lane. Kinds absent here fall back to EVENT_CAT_SYSTEM.
+EVENT_CATEGORY_BY_KIND: Final[dict[str, str]] = {
+ # lifecycle
+ "VoiceSessionStarted": EVENT_CAT_LIFECYCLE,
+ "VoiceSessionEnded": EVENT_CAT_LIFECYCLE,
+ "VoiceTurnStarted": EVENT_CAT_LIFECYCLE,
+ "VoiceTurnCompleted": EVENT_CAT_LIFECYCLE,
+ "RealtimeSessionReady": EVENT_CAT_LIFECYCLE,
+ "WakeWordDetected": EVENT_CAT_LIFECYCLE,
+ "HotkeyPressed": EVENT_CAT_LIFECYCLE,
+ "ListeningStarted": EVENT_CAT_LIFECYCLE,
+ "SystemStateChanged": EVENT_CAT_LIFECYCLE,
+ # speech
+ "TranscriptFinal": EVENT_CAT_SPEECH,
+ "TranscriptionUpdate": EVENT_CAT_SPEECH,
+ "UtteranceCaptured": EVENT_CAT_SPEECH,
+ "SpeechSpoken": EVENT_CAT_SPEECH,
+ "ResponseGenerated": EVENT_CAT_SPEECH,
+ "AudioOutFirst": EVENT_CAT_SPEECH,
+ # brain
+ "IntentClassified": EVENT_CAT_BRAIN,
+ "BrainTurnStarted": EVENT_CAT_BRAIN,
+ "BrainTurnCompleted": EVENT_CAT_BRAIN,
+ "BrainTTFT": EVENT_CAT_BRAIN,
+ "BrainProviderSwitched": EVENT_CAT_BRAIN,
+ "FrontierModelSwitched": EVENT_CAT_BRAIN,
+ "BrainToolsChanged": EVENT_CAT_BRAIN,
+ # tool
+ "ActionProposed": EVENT_CAT_TOOL,
+ "ActionApprovalRequired": EVENT_CAT_TOOL,
+ "ActionApproved": EVENT_CAT_TOOL,
+ "ActionExecuted": EVENT_CAT_TOOL,
+ "ToolCallStarted": EVENT_CAT_TOOL,
+ "ToolCallCompleted": EVENT_CAT_TOOL,
+ "CliInvoked": EVENT_CAT_TOOL,
+ "CliInvocationFinished": EVENT_CAT_TOOL,
+ # agent
+ "JarvisAgentTaskStarted": EVENT_CAT_AGENT,
+ "JarvisAgentReviewTriggered": EVENT_CAT_AGENT,
+ "JarvisAgentTaskCompleted": EVENT_CAT_AGENT,
+ "JarvisAgentAnnouncement": EVENT_CAT_AGENT,
+ "HarnessDispatched": EVENT_CAT_AGENT,
+ "HarnessCompleted": EVENT_CAT_AGENT,
+ "MissionCompleted": EVENT_CAT_AGENT,
+ # vision / Computer-Use
+ "ObservationCaptured": EVENT_CAT_VISION,
+ "VisionInjected": EVENT_CAT_VISION,
+ "ActionPlanned": EVENT_CAT_VISION,
+ "ActionVerified": EVENT_CAT_VISION,
+ "CUStepProfiled": EVENT_CAT_VISION,
+ "CUControlStarted": EVENT_CAT_VISION,
+ "CUControlEnded": EVENT_CAT_VISION,
+ # latency
+ "LatencySpan": EVENT_CAT_LATENCY,
+ # error
+ "ErrorOccurred": EVENT_CAT_ERROR,
+ "ActionDenied": EVENT_CAT_ERROR,
+ "BudgetWarning": EVENT_CAT_ERROR,
+ "BudgetExceeded": EVENT_CAT_ERROR,
+ "TaskCancelled": EVENT_CAT_ERROR,
+}
+
+# Hard cap on raw events surfaced per turn. A long Computer-Use turn can emit
+# thousands of steps; the payload stays bounded and the UI states plainly that
+# it truncated (never a silent cut).
+MAX_RAW_EVENTS_PER_TURN: Final[int] = 500
+
__all__ = [
"SLO_OK", "SLO_WARN", "SLO_BREACH", "SLO_STATUSES",
"DECISION_TIER", "DECISION_ROUTE", "DECISION_RISK",
@@ -78,4 +166,9 @@ __all__ = [
"OUTCOME_SUCCESS", "OUTCOME_PARTIAL", "OUTCOME_FAILED", "RUN_OUTCOMES",
"ROLE_USER", "ROLE_JARVIS", "ROLE_SYSTEM", "ROLE_TOOL", "ROLE_ERROR",
"TRANSCRIPT_ROLES",
+ "EVENT_CAT_LIFECYCLE", "EVENT_CAT_SPEECH", "EVENT_CAT_BRAIN",
+ "EVENT_CAT_TOOL", "EVENT_CAT_AGENT", "EVENT_CAT_VISION",
+ "EVENT_CAT_LATENCY", "EVENT_CAT_ERROR", "EVENT_CAT_SYSTEM",
+ "RUN_EVENT_CATEGORIES", "EVENT_CATEGORY_BY_KIND",
+ "MAX_RAW_EVENTS_PER_TURN",
]
diff --git a/jarvis/runs/loader.py b/jarvis/runs/loader.py
index 73a3802f27..807a733a5e 100644
--- a/jarvis/runs/loader.py
+++ b/jarvis/runs/loader.py
@@ -20,6 +20,21 @@ log = logging.getLogger(__name__)
# Optional callable: session_id -> list[MissionRef]. None disables the slice.
MissionsLookup = Callable[[str], list[MissionRef]]
+# The ONLY event kinds the run LIST derives from — error count, worst SLO,
+# outcome, feature tags. Keeping this narrow is what makes the list query cheap;
+# the full stream is loaded only when a single run is opened. Adding a kind here
+# is fine, adding "all kinds" is the regression this replaced.
+_LIST_EVENT_KINDS: list[str] = [
+ "ErrorOccurred",
+ "ActionDenied",
+ "LatencySpan",
+ "ResponseGenerated",
+ "SpeechSpoken",
+ "ActionProposed",
+ "ActionExecuted",
+ "JarvisAgentTaskStarted",
+]
+
class RunLoader:
def __init__(
@@ -34,9 +49,17 @@ class RunLoader:
self._missions = missions_lookup
def list_runs(self, *, limit: int = 100) -> list[RunListItem]:
+ sessions = self._sessions.list_sessions(limit=limit)
+ # ONE narrow query for all sessions instead of a full event fetch per
+ # session. The list only needs the kinds below; pulling everything cost
+ # 100 store-lock acquisitions, which stalled for tens of seconds
+ # whenever a live voice session held that lock through the recorder.
+ events_by_session = self._sessions.get_events_for_sessions(
+ [s.id for s in sessions], kinds=_LIST_EVENT_KINDS
+ )
items: list[RunListItem] = []
- for s in self._sessions.list_sessions(limit=limit):
- events = self._sessions.get_events(s.id)
+ for s in sessions:
+ events = events_by_session.get(s.id, [])
error_count = sum(
1 for e in events if e.kind in ("ErrorOccurred", "ActionDenied")
)
@@ -84,6 +107,12 @@ class RunLoader:
analytics = analyzer.build_analytics(
run_turns, started_ms=session.started_ms, ended_ms=session.ended_ms
)
+ # Events the recorder stored WITHOUT a turn id are the session frame
+ # (wake, session start/end, provider switches between turns). They used
+ # to be dropped entirely because the turn join never matched them.
+ session_events, _ = analyzer.build_raw_events(
+ events_by_turn.get(None, []), turn_started_ms=session.started_ms
+ )
return Run(
session=session,
outcome=analyzer.build_outcome(run_turns),
@@ -91,6 +120,9 @@ class RunLoader:
missions=missions,
activity=analyzer.build_activity(run_turns),
analytics=analytics,
+ environment=analyzer.build_environment(session, events, run_turns),
+ session_events=session_events,
+ event_counts=analyzer.build_event_counts(events),
)
def _build_turn(self, tr: VoiceTurnRow, events: list[VoiceEventRow]) -> RunTurn:
@@ -108,6 +140,9 @@ class RunLoader:
tools = analyzer.merge_action_tools(events, cli_tools)
# Surface the already-captured command + result onto each tool row.
analyzer.attach_tool_io(events, tools)
+ raw_events, truncated = analyzer.build_raw_events(
+ events, turn_started_ms=tr.started_ms
+ )
turn = RunTurn(
idx=tr.idx,
trace_id=tr.id,
@@ -122,15 +157,25 @@ class RunLoader:
think_ms=tr.think_ms,
speak_ms=tr.speak_ms,
transcript=analyzer.build_transcript(events, turn_started_ms=tr.started_ms),
- timeline=analyzer.build_timeline(events, turn_started_ms=tr.started_ms),
latency=analyzer.build_latency(events),
decision_path=analyzer.build_decision_path(events),
tools=tools,
errors=analyzer.build_errors(events),
extras=analyzer.build_extras(events, tokens_in=tr.tokens_in),
+ events=raw_events,
+ event_counts=analyzer.build_event_counts(events),
+ events_truncated=truncated,
+ # "Not measured" is a different fact from "measured as zero" — a
+ # realtime turn billed at session level records neither tokens nor
+ # cost, and printing a bare 0 would misreport that as free.
+ usage_recorded=bool(
+ tr.tokens_in or tr.tokens_out or tr.cost_usd
+ or any(e.kind == "BrainTurnCompleted" for e in events)
+ ),
)
turn.outcome = analyzer.turn_outcome(turn)
turn.activity = analyzer.build_activity([turn])
+ analyzer.ensure_brain_step(turn.decision_path, turn)
return turn
def _safe_missions(self, session_id: str) -> list[MissionRef]:
@@ -143,13 +188,9 @@ class RunLoader:
return []
-def _wake_source(wake_keyword: str) -> str:
- kw = (wake_keyword or "").lower()
- if "hotkey" in kw:
- return "hotkey"
- if kw.startswith("channel:") or kw in ("telegram", "discord", "web"):
- return f"channel:{kw}" if not kw.startswith("channel:") else kw
- return "voice"
+# One implementation, shared with build_environment — the list card and the
+# run header must never disagree about how a run was started.
+_wake_source = analyzer.wake_source
__all__ = ["RunLoader", "MissionsLookup"]
diff --git a/jarvis/runs/model.py b/jarvis/runs/model.py
index c12395c5b6..3ad4f3e92a 100644
--- a/jarvis/runs/model.py
+++ b/jarvis/runs/model.py
@@ -6,12 +6,61 @@ degrades to a UI fallback instead of an HTTP 500 — see jarvis/runs/constants.p
and the BUG-008 history."""
from __future__ import annotations
+from typing import Any
+
from pydantic import BaseModel, ConfigDict, Field
from jarvis.sessions.models import VoiceSessionRow
+class RawEvent(BaseModel):
+ """One persisted bus event, verbatim — the developer's ground truth.
+
+ Everything else in this module is a *derivation*; this is the source those
+ derivations were built from. Surfacing it means a developer can always ask
+ "but what actually happened?" and get the recorded answer instead of a
+ summary. ``payload`` is the already-redacted dict the recorder persisted
+ (whitelist-filtered at capture time — see recorder._payload_for), so no new
+ privacy surface is opened by showing it."""
+ model_config = ConfigDict(extra="ignore")
+ seq: int = 0 # store sequence — stable chronological order
+ kind: str
+ category: str = "system" # see RUN_EVENT_CATEGORIES — a UI lane
+ ts_ms: int = 0
+ offset_ms: int = 0 # relative to the turn's start
+ summary: str = "" # one-line human reading of the payload
+ payload: dict[str, Any] = Field(default_factory=dict)
+
+
+class RunEnvironment(BaseModel):
+ """How this run was configured — the "which Jarvis am I looking at" header.
+
+ A forensic report is unusable without it: the same utterance behaves
+ differently in realtime vs. pipeline mode, on a different provider, or with
+ a different wake source. Every field is READ from the recorded run, never
+ from the host's live config (which may have changed since)."""
+ model_config = ConfigDict(extra="ignore")
+ voice_mode: str = "" # realtime | pipeline
+ surface: str = "" # desktop | web | channel surface
+ wake_source: str = "" # voice | hotkey | channel:<name>
+ wake_keyword: str = ""
+ language: str = ""
+ hangup_reason: str = ""
+ providers: list[str] = Field(default_factory=list)
+ models: list[str] = Field(default_factory=list)
+ tiers: list[str] = Field(default_factory=list)
+ voices: list[str] = Field(default_factory=list)
+ input_sample_rate: int | None = None
+ output_sample_rate: int | None = None
+
+
class TraceEvent(BaseModel):
+ """Compact timeline row (kind + offset + one-line summary).
+
+ Superseded on the wire by ``RawEvent``, which carries the same information
+ plus the verbatim payload and a UI lane — a run no longer ships both, so a
+ long Computer-Use turn is not serialized twice. Kept as a public helper
+ (``analyzer.build_timeline``) for callers that only want the light shape."""
model_config = ConfigDict(extra="ignore")
kind: str
offset_ms: int = 0 # relative to the turn's start
@@ -114,13 +163,22 @@ class RunTurn(BaseModel):
think_ms: int = 0
speak_ms: int = 0
transcript: list[TranscriptLine] = Field(default_factory=list)
- timeline: list[TraceEvent] = Field(default_factory=list)
latency: list[LatencyEntry] = Field(default_factory=list)
decision_path: list[DecisionStep] = Field(default_factory=list)
tools: list[ToolCall] = Field(default_factory=list)
errors: list[ErrorEntry] = Field(default_factory=list)
extras: TurnExtras = Field(default_factory=TurnExtras)
activity: RunActivity = Field(default_factory=RunActivity) # what THIS turn triggered
+ # The raw, verbatim event stream of this turn + its per-lane histogram.
+ # ``events_truncated`` is set when the turn exceeded MAX_RAW_EVENTS_PER_TURN
+ # so the UI can say so instead of implying it showed everything.
+ events: list[RawEvent] = Field(default_factory=list)
+ event_counts: dict[str, int] = Field(default_factory=dict)
+ events_truncated: bool = False
+ # False when NO usage was recorded for this turn (realtime turns billed at
+ # session level emit no BrainTurnCompleted). Lets the UI distinguish
+ # "cost zero" from "not measured" instead of printing a misleading 0.
+ usage_recorded: bool = False
class RunAnalytics(BaseModel):
@@ -161,9 +219,15 @@ class Run(BaseModel):
missions: list[MissionRef] = Field(default_factory=list)
activity: RunActivity = Field(default_factory=RunActivity)
analytics: RunAnalytics = Field(default_factory=RunAnalytics)
+ environment: RunEnvironment = Field(default_factory=RunEnvironment)
+ # Session-scoped events (those the recorder stored without a turn id) plus
+ # the run-wide event-kind histogram.
+ session_events: list[RawEvent] = Field(default_factory=list)
+ event_counts: dict[str, int] = Field(default_factory=dict)
__all__ = [
+ "RawEvent", "RunEnvironment",
"TraceEvent", "TranscriptLine", "ToolCall", "LatencyEntry", "DecisionStep",
"ErrorEntry", "TurnExtras", "MissionRef", "RunActivity", "RunTurn",
"RunAnalytics", "RunListItem", "Run",
diff --git a/jarvis/runs/routes.py b/jarvis/runs/routes.py
index 5f7bb2b6c9..88d833e3c2 100644
--- a/jarvis/runs/routes.py
+++ b/jarvis/runs/routes.py
@@ -7,6 +7,7 @@ Read-only; reuses app.state.session_store (set by bootstrap_sessions) and a
process-local UsageLog. Loopback-only, no auth token (mirrors sessions_routes)."""
from __future__ import annotations
+import asyncio
import logging
from fastapi import APIRouter, HTTPException, Query, Request
@@ -47,12 +48,19 @@ async def list_runs(
request: Request,
limit: int = Query(default=100, ge=1, le=500),
) -> list[RunListItem]:
- return _loader(request).list_runs(limit=limit)
+ # OFF the event loop. SessionStore is synchronous SQLite behind a lock the
+ # live recorder also writes through; awaiting that lock on the loop thread
+ # freezes the WHOLE server, not just this request — the observed symptom
+ # was every API call (and therefore the desktop UI) stalling for tens of
+ # seconds whenever a voice session was active while the inspector polled.
+ loader = _loader(request)
+ return await asyncio.to_thread(loader.list_runs, limit=limit)
@router.get("/{session_id}", response_model=Run)
async def get_run(session_id: str, request: Request) -> Run:
- run = _loader(request).load_run(session_id)
+ loader = _loader(request)
+ run = await asyncio.to_thread(loader.load_run, session_id)
if run is None:
raise HTTPException(status_code=404, detail="run-not-found")
return run
diff --git a/jarvis/runs/runs_ws.py b/jarvis/runs/runs_ws.py
index 3188ce1147..0a4c9e6249 100644
--- a/jarvis/runs/runs_ws.py
+++ b/jarvis/runs/runs_ws.py
@@ -27,40 +27,17 @@ import logging
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
+# Event kinds the inspector cares about live. DERIVED from the recorder's
+# persisted set instead of being a hand-copied twin: the two lists drifted apart
+# once already (the recorder gained forensic kinds the live stream never
+# forwarded, so an in-flight run showed less than the same run did after a
+# reload). One source, no sync ritual.
+from jarvis.sessions.recorder import _RAW_EVENT_KINDS as _LIVE_KINDS
+
log = logging.getLogger(__name__)
router = APIRouter()
-# Event kinds the inspector cares about live (superset of the recorder forensic
-# additions). Keep in sync with jarvis/sessions/recorder.py::_RAW_EVENT_KINDS.
-_LIVE_KINDS: frozenset[str] = frozenset({
- "VoiceSessionStarted",
- "VoiceSessionEnded",
- "VoiceTurnStarted",
- "VoiceTurnCompleted",
- "RealtimeSessionReady",
- "WakeWordDetected",
- "ListeningStarted",
- "TranscriptFinal",
- "IntentClassified",
- "ActionProposed",
- "ActionApproved",
- "ActionDenied",
- "BrainTurnStarted",
- "BrainTurnCompleted",
- "BrainTTFT",
- "ToolCallStarted",
- "ToolCallCompleted",
- "ActionExecuted",
- "ResponseGenerated",
- "SystemStateChanged",
- "LatencySpan",
- "ErrorOccurred",
- "SpeechSpoken",
- "JarvisAgentTaskStarted",
- "JarvisAgentTaskCompleted",
-})
-
def _resolve_bus(ws: WebSocket):
"""Pull the shared EventBus off ``app.state``.
diff --git a/jarvis/sessions/recorder.py b/jarvis/sessions/recorder.py
index d6f1af68f1..c103ec0c65 100644
--- a/jarvis/sessions/recorder.py
+++ b/jarvis/sessions/recorder.py
@@ -115,6 +115,42 @@ _RAW_EVENT_KINDS: frozenset[str] = frozenset(
"ActionDenied",
"ErrorOccurred",
"LatencySpan",
+ # Developer forensics, wave 2 (2026-07-25). The Run Inspector is the
+ # developer's window into HOW a turn was handled, and the three most
+ # asked questions there — "which provider actually answered and why did
+ # it change?", "what did the Computer-Use loop see and do?", "what did
+ # the sub-agent run?" — were unanswerable because their events were
+ # never persisted. All of these are low-frequency (per turn, per CU
+ # step, per mission), never per audio frame; the genuinely chatty
+ # streams (TerminalOutput, CliInstallProgress, HarnessProgress) stay
+ # excluded on purpose, and the read side caps a turn at
+ # MAX_RAW_EVENTS_PER_TURN.
+ "HotkeyPressed",
+ "UtteranceCaptured",
+ # The key-aware fallback chain (AP-22) is invisible without this pair.
+ "BrainProviderSwitched",
+ "FrontierModelSwitched",
+ "BrainToolsChanged",
+ "ActionApprovalRequired",
+ "CliInvoked",
+ "CliInvocationFinished",
+ "JarvisAgentReviewTriggered",
+ "JarvisAgentAnnouncement",
+ "HarnessDispatched",
+ "HarnessCompleted",
+ "MissionCompleted",
+ # Computer-Use observe -> plan -> act -> verify loop.
+ "ObservationCaptured",
+ "VisionInjected",
+ "ActionPlanned",
+ "ActionVerified",
+ "CUStepProfiled",
+ "CUControlStarted",
+ "CUControlEnded",
+ # Cost / kill-switch stops that silently end a turn.
+ "BudgetWarning",
+ "BudgetExceeded",
+ "TaskCancelled",
}
)
@@ -1035,6 +1071,51 @@ def _payload_for(event: Event) -> dict[str, Any]:
"error_type", # ErrorOccurred
"message", # ErrorOccurred
"recoverable", # ErrorOccurred (bool — _payload_for skips None, keeps False)
+ # --- Developer forensics, wave 2 (2026-07-25) -------------------
+ # Field names only; _payload_for pulls them by hasattr, so an event
+ # class that lacks one is simply skipped. Nothing here is a credential:
+ # secrets ride on SecretConfigured, which is NOT a recorded kind, and
+ # every *_preview field is redacted + length-capped by its publisher.
+ "combo", # HotkeyPressed
+ "audio_ref", # UtteranceCaptured (content hash, not audio)
+ "from_provider", # BrainProviderSwitched — the fallback chain
+ "to_provider",
+ "old_model", # FrontierModelSwitched
+ "new_model",
+ "system_prompt_preview", # BrainTurnStarted — which persona/prompt ran
+ "harness", # HarnessDispatched / HarnessCompleted
+ "mission_id", # MissionCompleted / CUControl*
+ "status", # MissionCompleted
+ "summary", # JarvisAgentTaskCompleted
+ "summary_en", # MissionCompleted
+ "result_uri",
+ "iteration", # JarvisAgentReviewTriggered (critic loop)
+ "utterance", # JarvisAgentTaskStarted — the delegated task
+ "depth",
+ "max_duration_s",
+ "cost_estimate_usd", # JarvisAgentTaskCompleted
+ "full_log_len",
+ "action", # JarvisAgentAnnouncement (also set from args below)
+ "target",
+ "cli_name", # CliInvoked / CliInvocationFinished
+ "caller",
+ "command_preview",
+ "exit_code",
+ "source", # ObservationCaptured
+ "window_title",
+ "node_count",
+ "screenshot_hash",
+ "bytes_size", # VisionInjected
+ "capture_age_ms",
+ "action_kind", # ActionPlanned / ActionVerified
+ "target_hint",
+ "step_idx", # CUStepProfiled
+ "engine",
+ "cache_read_tokens",
+ "scope", # BudgetWarning / BudgetExceeded
+ "spent_eur",
+ "limit_eur",
+ "task_id", # TaskCancelled
}
payload: dict[str, Any] = {}
for k in fields_whitelist:
diff --git a/jarvis/sessions/store.py b/jarvis/sessions/store.py
index 938c640e67..cf6490b582 100644
--- a/jarvis/sessions/store.py
+++ b/jarvis/sessions/store.py
@@ -544,6 +544,47 @@ class SessionStore:
for r in rows
]
+ def get_events_for_sessions(
+ self, session_ids: list[str], *, kinds: list[str] | None = None
+ ) -> dict[str, list[VoiceEventRow]]:
+ """Events for MANY sessions in ONE query, optionally narrowed by kind.
+
+ The run list needs a handful of event kinds from each of up to 100
+ sessions. Doing that as 100 separate ``get_events`` calls costs 100
+ acquisitions of the store lock — which is fine on an idle box and
+ catastrophic while a live voice session has the recorder writing
+ through that same lock: the list endpoint stalled for tens of seconds.
+ One narrow query takes one lock, once.
+
+ Returns a mapping keyed by session id; a session with no matching
+ events is absent from the mapping (callers use ``.get(id, [])``).
+ """
+ if not session_ids:
+ return {}
+ id_marks = ",".join("?" for _ in session_ids)
+ sql = f"SELECT * FROM voice_events WHERE session_id IN ({id_marks})" # noqa: S608
+ params: list[str] = list(session_ids)
+ if kinds:
+ kind_marks = ",".join("?" for _ in kinds)
+ sql += f" AND kind IN ({kind_marks})" # noqa: S608
+ params.extend(kinds)
+ sql += " ORDER BY session_id, seq ASC"
+ with self._lock:
+ rows = self._c.execute(sql, params).fetchall()
+ out: dict[str, list[VoiceEventRow]] = {}
+ for r in rows:
+ out.setdefault(r["session_id"], []).append(
+ VoiceEventRow(
+ seq=r["seq"],
+ session_id=r["session_id"],
+ turn_id=r["turn_id"],
+ ts_ms=r["ts_ms"],
+ kind=r["kind"],
+ payload=json.loads(r["payload_json"] or "{}"),
+ )
+ )
+ return out
+
def list_open_sessions(self) -> list[str]:
"""IDs of all sessions without ``ended_ms`` — for crash recovery."""
with self._lock:
diff --git a/jarvis/ui/web/frontend/src/components/runs/DecisionPath.tsx b/jarvis/ui/web/frontend/src/components/runs/DecisionPath.tsx
index e0c086c4b7..b6c2ce7d33 100644
--- a/jarvis/ui/web/frontend/src/components/runs/DecisionPath.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/DecisionPath.tsx
@@ -1,20 +1,64 @@
+/**
+ * Why this turn went the way it did — one row per recorded decision.
+ *
+ * The backend has carried a `rationale` + its provenance since the
+ * Session-Decision-Log, but the UI only ever rendered the terse label, so the
+ * honest "why" was invisible. The provenance tag matters: "model" is the
+ * brain's OWN words captured next to its tool call, "rule" is a deterministic
+ * explanation derived from a recorded fact. Neither is ever invented — a step
+ * with no recorded rationale says so instead of guessing.
+ */
+import { useT } from "@/i18n";
+
import type { DecisionStep } from "./types";
-const KIND_ICON: Record<string, string> = {
- tier: "◆", route: "→", risk: "⚖", brain: "🧠", mission: "⚙", fallback: "↺",
+const KIND_META: Record<string, { icon: string; cls: string }> = {
+ tier: { icon: "◆", cls: "text-slate-300" },
+ route: { icon: "→", cls: "text-amber-300" },
+ risk: { icon: "⚖", cls: "text-rose-300" },
+ brain: { icon: "🧠", cls: "text-violet-300" },
+ mission: { icon: "⚙", cls: "text-fuchsia-300" },
+ fallback: { icon: "↺", cls: "text-cyan-300" },
+};
+
+const SOURCE_STYLE: Record<string, string> = {
+ model: "bg-violet-400/10 text-violet-300 ring-violet-400/25",
+ rule: "bg-muted/40 text-muted-foreground ring-border",
};
export function DecisionPath({ steps }: { steps: DecisionStep[] }) {
- if (steps.length === 0) return <span className="text-muted-foreground/60">n/a</span>;
+ const t = useT();
+ if (steps.length === 0) {
+ return <span className="text-muted-foreground/60">{t("run_inspector.decision.empty")}</span>;
+ }
return (
- <ol className="space-y-0.5 text-[11px]">
- {steps.map((s, i) => (
- <li key={i} className="flex gap-2">
- <span className="w-4 shrink-0 text-center text-muted-foreground">{KIND_ICON[s.kind] ?? "·"}</span>
- <span>{s.label}</span>
- {s.detail && <span className="text-muted-foreground">— {s.detail}</span>}
- </li>
- ))}
+ <ol className="space-y-1.5" data-testid="decision-path">
+ {steps.map((s, i) => {
+ const meta = KIND_META[s.kind] ?? { icon: "·", cls: "text-muted-foreground" };
+ return (
+ <li
+ key={i}
+ data-decision-kind={s.kind}
+ className="rounded-md border border-border/50 bg-background/40 px-2 py-1.5"
+ >
+ <div className="flex flex-wrap items-baseline gap-1.5 text-[11px]">
+ <span className={`w-4 shrink-0 text-center ${meta.cls}`}>{meta.icon}</span>
+ <span className="font-medium text-foreground/90">{s.label}</span>
+ {s.detail && (
+ <span className="font-mono text-[10px] text-muted-foreground">{s.detail}</span>
+ )}
+ <span
+ className={`ml-auto rounded-full px-1.5 py-px text-[9px] uppercase tracking-wide ring-1 ring-inset ${SOURCE_STYLE[s.rationale_source] ?? SOURCE_STYLE.rule}`}
+ >
+ {s.rationale_source || t("run_inspector.decision.no_source")}
+ </span>
+ </div>
+ <p className="mt-1 pl-[22px] text-[11px] leading-relaxed text-muted-foreground [overflow-wrap:anywhere]">
+ {s.rationale || t("run_inspector.decision.no_rationale")}
+ </p>
+ </li>
+ );
+ })}
</ol>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/runs/EnvironmentPanel.tsx b/jarvis/ui/web/frontend/src/components/runs/EnvironmentPanel.tsx
new file mode 100644
index 0000000000..38b06ec1e3
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/runs/EnvironmentPanel.tsx
@@ -0,0 +1,62 @@
+/**
+ * "Which Jarvis am I looking at?" — the run's recorded configuration.
+ *
+ * A forensic report without it is unreadable: the same sentence takes a
+ * completely different path in realtime vs. pipeline mode, on another provider,
+ * or started by hotkey instead of the wake word. Every value is read back from
+ * what the run RECORDED, never from the host's current config — a run inspected
+ * tomorrow must show the setup it actually ran under.
+ */
+import { useT } from "@/i18n";
+
+import type { RunEnvironment } from "./types";
+
+function Row({ label, value }: { label: string; value: string }) {
+ return (
+ <div className="flex min-w-0 items-baseline gap-2">
+ <span className="w-24 shrink-0 text-[9px] font-medium uppercase tracking-[0.12em] text-muted-foreground">
+ {label}
+ </span>
+ <span className="min-w-0 flex-1 break-words font-mono text-[11px] text-foreground/90 [overflow-wrap:anywhere]">
+ {value}
+ </span>
+ </div>
+ );
+}
+
+export function EnvironmentPanel({ env }: { env: RunEnvironment }) {
+ const t = useT();
+ const rows: Array<[string, string]> = [];
+ const push = (label: string, value: string | number | null | undefined): void => {
+ if (value === null || value === undefined || value === "") return;
+ rows.push([label, String(value)]);
+ };
+
+ push(t("run_inspector.env.mode"), env.voice_mode);
+ push(t("run_inspector.env.surface"), env.surface);
+ push(t("run_inspector.env.started_by"), env.wake_keyword
+ ? `${env.wake_source} · "${env.wake_keyword}"`
+ : env.wake_source);
+ push(t("run_inspector.env.ended_by"), env.hangup_reason);
+ push(t("run_inspector.env.language"), env.language);
+ push(t("run_inspector.env.providers"), env.providers.join(", "));
+ push(t("run_inspector.env.models"), env.models.join(", "));
+ push(t("run_inspector.env.tiers"), env.tiers.join(", "));
+ push(t("run_inspector.env.voices"), env.voices.join(", "));
+ if (env.input_sample_rate || env.output_sample_rate) {
+ push(t("run_inspector.env.audio"),
+ `${env.input_sample_rate ?? "?"} Hz in · ${env.output_sample_rate ?? "?"} Hz out`);
+ }
+
+ if (rows.length === 0) {
+ return <span className="text-muted-foreground/60">{t("run_inspector.env.empty")}</span>;
+ }
+
+ return (
+ <div className="grid gap-1.5 sm:grid-cols-2" data-testid="environment-panel">
+ {rows.map(([label, value]) => (
+ <Row key={label} label={label} value={value} />
+ ))}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/runs/EventStream.tsx b/jarvis/ui/web/frontend/src/components/runs/EventStream.tsx
new file mode 100644
index 0000000000..44cbe09e97
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/runs/EventStream.tsx
@@ -0,0 +1,210 @@
+/**
+ * The raw, verbatim bus-event stream of a turn (or of the session frame).
+ *
+ * Every other panel in the inspector is a *derivation* — latency, decision
+ * path, tools. Derivations have blind spots: a realtime turn used to produce an
+ * empty decision path, and a developer had no way to tell "nothing happened"
+ * from "the analyzer does not model this path". This panel removes that
+ * ambiguity by showing exactly what was recorded, in order, with the payload
+ * one click away.
+ *
+ * Completeness only becomes readable through the lane split (speech / brain /
+ * tool / vision / …) plus a text filter, so a 500-event Computer-Use turn is
+ * still navigable.
+ */
+import { useMemo, useState } from "react";
+import { ChevronDown, ChevronRight, Copy, Search } from "lucide-react";
+
+import { robustCopy } from "@/lib/clipboard";
+import { useEventStore } from "@/store/events";
+import { useT } from "@/i18n";
+
+import type { RawEvent } from "./types";
+
+// Lane -> colour. An unknown category degrades to the neutral system tone
+// instead of rendering unstyled (BUG-008 string contract).
+const LANE: Record<string, { dot: string; chip: string; text: string }> = {
+ lifecycle: { dot: "bg-slate-400", chip: "bg-slate-400/10 text-slate-300 ring-slate-400/25", text: "text-slate-300" },
+ speech: { dot: "bg-emerald-400", chip: "bg-emerald-400/10 text-emerald-300 ring-emerald-400/25", text: "text-emerald-300" },
+ brain: { dot: "bg-violet-400", chip: "bg-violet-400/10 text-violet-300 ring-violet-400/25", text: "text-violet-300" },
+ tool: { dot: "bg-amber-400", chip: "bg-amber-400/10 text-amber-300 ring-amber-400/25", text: "text-amber-300" },
+ agent: { dot: "bg-fuchsia-400", chip: "bg-fuchsia-400/10 text-fuchsia-300 ring-fuchsia-400/25", text: "text-fuchsia-300" },
+ vision: { dot: "bg-sky-400", chip: "bg-sky-400/10 text-sky-300 ring-sky-400/25", text: "text-sky-300" },
+ latency: { dot: "bg-cyan-400", chip: "bg-cyan-400/10 text-cyan-300 ring-cyan-400/25", text: "text-cyan-300" },
+ error: { dot: "bg-rose-500", chip: "bg-rose-500/10 text-rose-300 ring-rose-500/25", text: "text-rose-300" },
+ system: { dot: "bg-muted-foreground/50", chip: "bg-muted/40 text-muted-foreground ring-border", text: "text-muted-foreground" },
+};
+
+function lane(category: string) {
+ return LANE[category] ?? LANE.system;
+}
+
+function fmtOffset(ms: number): string {
+ if (ms < 1000) return `+${ms}ms`;
+ return `+${(ms / 1000).toFixed(2)}s`;
+}
+
+export function EventStream({
+ events,
+ truncated = false,
+}: {
+ events: RawEvent[];
+ truncated?: boolean;
+}) {
+ const t = useT();
+ const pushToast = useEventStore((s) => s.pushToast);
+ const [lanes, setLanes] = useState<Set<string>>(new Set());
+ const [needle, setNeedle] = useState("");
+ const [open, setOpen] = useState<Set<number>>(new Set());
+
+ const counts = useMemo(() => {
+ const c: Record<string, number> = {};
+ for (const e of events) c[e.category] = (c[e.category] ?? 0) + 1;
+ return c;
+ }, [events]);
+
+ const visible = useMemo(() => {
+ const q = needle.trim().toLowerCase();
+ return events.filter((e) => {
+ if (lanes.size > 0 && !lanes.has(e.category)) return false;
+ if (!q) return true;
+ return (
+ e.kind.toLowerCase().includes(q) ||
+ e.summary.toLowerCase().includes(q) ||
+ JSON.stringify(e.payload).toLowerCase().includes(q)
+ );
+ });
+ }, [events, lanes, needle]);
+
+ if (events.length === 0) {
+ return <span className="text-muted-foreground/60">{t("run_inspector.stream.empty")}</span>;
+ }
+
+ const toggleLane = (name: string) =>
+ setLanes((prev) => {
+ const next = new Set(prev);
+ if (next.has(name)) next.delete(name);
+ else next.add(name);
+ return next;
+ });
+
+ const toggleRow = (seq: number) =>
+ setOpen((prev) => {
+ const next = new Set(prev);
+ if (next.has(seq)) next.delete(seq);
+ else next.add(seq);
+ return next;
+ });
+
+ const copyStream = async () => {
+ // JSONL: one event per line — the shape a developer can pipe into jq.
+ const text = visible
+ .map((e) => JSON.stringify({ offset_ms: e.offset_ms, kind: e.kind, ...e.payload }))
+ .join("\n");
+ const ok = await robustCopy(text);
+ pushToast(ok ? "success" : "error", ok
+ ? `${visible.length} ${t("run_inspector.stream.copied")}`
+ : t("run_inspector.stream.copy_failed"));
+ };
+
+ return (
+ <div className="space-y-2" data-testid="event-stream">
+ {/* Lane filters + search */}
+ <div className="flex flex-wrap items-center gap-1.5">
+ {Object.entries(counts)
+ .sort((a, b) => b[1] - a[1])
+ .map(([cat, n]) => {
+ const active = lanes.size === 0 || lanes.has(cat);
+ return (
+ <button
+ key={cat}
+ type="button"
+ data-testid={`lane-${cat}`}
+ data-active={lanes.has(cat)}
+ onClick={() => toggleLane(cat)}
+ className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium ring-1 ring-inset transition-opacity ${lane(cat).chip} ${active ? "" : "opacity-35"}`}
+ >
+ <span className={`h-1.5 w-1.5 rounded-full ${lane(cat).dot}`} />
+ {cat}
+ <span className="tabular-nums opacity-70">{n}</span>
+ </button>
+ );
+ })}
+ <div className="ml-auto flex items-center gap-1.5">
+ <div className="relative">
+ <Search className="pointer-events-none absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-muted-foreground" />
+ <input
+ type="text"
+ value={needle}
+ onChange={(e) => setNeedle(e.target.value)}
+ placeholder={t("run_inspector.stream.filter")}
+ data-testid="event-filter"
+ className="h-6 w-40 rounded-md border border-border/70 bg-background/60 pl-6 pr-2 text-[11px] outline-none placeholder:text-muted-foreground/70 focus:border-border"
+ />
+ </div>
+ <button
+ type="button"
+ onClick={copyStream}
+ title={t("run_inspector.stream.copy")}
+ className="inline-flex h-6 items-center gap-1 rounded-md border border-border/70 px-2 text-[10px] text-muted-foreground transition-colors hover:border-border hover:text-foreground"
+ >
+ <Copy className="h-3 w-3" />
+ JSONL
+ </button>
+ </div>
+ </div>
+
+ {truncated && (
+ <div className="rounded-md border border-amber-400/30 bg-amber-400/5 px-2 py-1 text-[10px] text-amber-300">
+ {t("run_inspector.stream.truncated")}
+ </div>
+ )}
+
+ {/* Rows */}
+ <ol className="divide-y divide-border/40 overflow-hidden rounded-md border border-border/50">
+ {visible.map((e) => {
+ const isOpen = open.has(e.seq);
+ const hasPayload = Object.keys(e.payload ?? {}).length > 0;
+ return (
+ <li key={`${e.seq}-${e.ts_ms}`} data-kind={e.kind} data-category={e.category}>
+ <button
+ type="button"
+ onClick={() => hasPayload && toggleRow(e.seq)}
+ className={`flex w-full items-start gap-2 px-2 py-1 text-left transition-colors hover:bg-muted/30 ${hasPayload ? "" : "cursor-default"}`}
+ >
+ <span className="mt-[3px] w-4 shrink-0 text-muted-foreground">
+ {hasPayload ? (
+ isOpen ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />
+ ) : null}
+ </span>
+ <span className="w-16 shrink-0 text-right font-mono text-[10px] tabular-nums text-muted-foreground">
+ {fmtOffset(e.offset_ms)}
+ </span>
+ <span className={`mt-[5px] h-1.5 w-1.5 shrink-0 rounded-full ${lane(e.category).dot}`} />
+ <span className={`w-48 shrink-0 font-mono text-[11px] ${lane(e.category).text}`}>
+ {e.kind}
+ </span>
+ {/* No truncation: the summary IS the information. Long lines
+ wrap instead of being cut at the container edge. */}
+ <span className="min-w-0 flex-1 break-words text-[11px] text-foreground/80 [overflow-wrap:anywhere]">
+ {e.summary}
+ </span>
+ </button>
+ {isOpen && (
+ <pre className="overflow-x-auto border-t border-border/40 bg-background/60 px-3 py-2 font-mono text-[10px] leading-relaxed text-muted-foreground">
+ {JSON.stringify(e.payload, null, 2)}
+ </pre>
+ )}
+ </li>
+ );
+ })}
+ </ol>
+
+ <div className="text-[10px] text-muted-foreground">
+ {visible.length === events.length
+ ? `${events.length} ${t("run_inspector.stream.events")}`
+ : `${visible.length} / ${events.length} ${t("run_inspector.stream.events")}`}
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/runs/MetricsPanel.tsx b/jarvis/ui/web/frontend/src/components/runs/MetricsPanel.tsx
index cc7ead715c..b5d9f2cfa6 100644
--- a/jarvis/ui/web/frontend/src/components/runs/MetricsPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/MetricsPanel.tsx
@@ -1,4 +1,6 @@
import type { ReactNode } from "react";
+
+import { fmtInt, fmtMs, useRunLocale } from "./format";
import type { Run } from "./types";
/** A compact labelled metric: small uppercase label over a mono value. */
@@ -23,23 +25,20 @@ export function StatChip({
);
}
-function fmtMs(ms: number): string {
- if (ms >= 1000) return `${(ms / 1000).toFixed(1)}s`;
- return `${Math.round(ms)}ms`;
-}
-
/** Deep-dive analytics grid for a single run. */
export function MetricsPanel({ run }: { run: Run }) {
+ const locale = useRunLocale();
const a = run.analytics;
const providers = Object.entries(a.cost_by_provider);
const tools = Object.entries(a.tool_counts).sort((x, y) => y[1] - x[1]);
+ const eventKinds = Object.entries(run.event_counts ?? {}).sort((x, y) => y[1] - x[1]);
return (
<div className="space-y-3" data-testid="metrics-panel">
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4">
<StatChip label="Think" value={fmtMs(a.total_think_ms)} />
<StatChip label="Speak" value={fmtMs(a.total_speak_ms)} />
- <StatChip label="Tokens in" value={a.total_tokens_in.toLocaleString()} />
- <StatChip label="Tokens out" value={a.total_tokens_out.toLocaleString()} />
+ <StatChip label="Tokens in" value={fmtInt(a.total_tokens_in, locale)} />
+ <StatChip label="Tokens out" value={fmtInt(a.total_tokens_out, locale)} />
<StatChip
label="Interruptions"
value={a.interruptions}
@@ -68,6 +67,28 @@ export function MetricsPanel({ run }: { run: Run }) {
</div>
)}
+ {/* Event-kind histogram — the fastest read on what dominated this run.
+ A run that is 90% LatencySpan looks very different from one that is
+ 40% CUStepProfiled, and the shape alone often locates a problem. */}
+ {eventKinds.length > 0 && (
+ <div>
+ <div className="mb-1 text-[9px] font-medium uppercase tracking-[0.12em] text-muted-foreground">
+ Recorded events
+ </div>
+ <div className="flex flex-wrap gap-1" data-testid="event-histogram">
+ {eventKinds.map(([kind, n]) => (
+ <span
+ key={kind}
+ className="inline-flex items-center gap-1 rounded-md bg-muted/40 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground ring-1 ring-inset ring-border/60"
+ >
+ {kind}
+ <span className="text-foreground/80">×{n}</span>
+ </span>
+ ))}
+ </div>
+ </div>
+ )}
+
{tools.length > 0 && (
<div>
<div className="mb-1 text-[9px] font-medium uppercase tracking-[0.12em] text-muted-foreground">
diff --git a/jarvis/ui/web/frontend/src/components/runs/RunDetail.tsx b/jarvis/ui/web/frontend/src/components/runs/RunDetail.tsx
index 84a4f10f01..7496baa393 100644
--- a/jarvis/ui/web/frontend/src/components/runs/RunDetail.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/RunDetail.tsx
@@ -7,13 +7,25 @@ import { RunTurnCard } from "@/components/runs/RunTurnCard";
import { OutcomeBadge } from "@/components/runs/OutcomeBadge";
import { FeatureBadges } from "@/components/runs/FeatureBadges";
import { MetricsPanel } from "@/components/runs/MetricsPanel";
-import { useT, useUiLanguage } from "@/i18n";
+import { EnvironmentPanel } from "@/components/runs/EnvironmentPanel";
+import { EventStream } from "@/components/runs/EventStream";
+import type { RunEnvironment } from "@/components/runs/types";
+import { useRunLocale } from "@/components/runs/format";
+import { useT } from "@/i18n";
+
+const EMPTY_ENV: RunEnvironment = {
+ voice_mode: "", surface: "", wake_source: "", wake_keyword: "", language: "",
+ hangup_reason: "", providers: [], models: [], tiers: [], voices: [],
+ input_sample_rate: null, output_sample_rate: null,
+};
export function RunDetail({ sessionId }: { sessionId: string }) {
const t = useT();
- const locale = localeForUiLanguage(useUiLanguage());
+ const locale = useRunLocale();
const { data: run, isLoading } = useRunDetail(sessionId);
const [showMetrics, setShowMetrics] = useState(false);
+ const [showEnv, setShowEnv] = useState(false);
+ const [showSessionEvents, setShowSessionEvents] = useState(false);
if (isLoading || !run) {
return <div className="p-6 text-sm text-muted-foreground">…</div>;
}
@@ -26,6 +38,14 @@ export function RunDetail({ sessionId }: { sessionId: string }) {
...run.activity.tools.filter((x) => !run.activity.agents.includes(x)),
];
const tokens = a.total_tokens_in + a.total_tokens_out;
+ // Defaulted, not assumed: the desktop shell can briefly talk to a backend
+ // that predates these fields (mid-update, or a run loaded from an older
+ // store). A missing slice must render as "nothing to show", never crash the
+ // whole inspector — the BUG-008 degrade-don't-throw contract.
+ const env: RunEnvironment = run.environment ?? EMPTY_ENV;
+ const eventCounts = run.event_counts ?? {};
+ const sessionEvents = run.session_events ?? [];
+ const totalEvents = Object.values(eventCounts).reduce((s, n) => s + n, 0);
return (
<div className="flex h-full min-h-0 flex-col" data-testid="run-detail">
@@ -56,8 +76,27 @@ export function RunDetail({ sessionId }: { sessionId: string }) {
{run.session.hangup_reason && (
<Badge variant="outline">{run.session.hangup_reason}</Badge>
)}
+ {totalEvents > 0 && (
+ <Badge variant="outline" className="text-[10px]">
+ {totalEvents.toLocaleString(locale)} {t("run_inspector.stream.events")}
+ </Badge>
+ )}
<LatencyChip status={a.worst_slo_status} />
</div>
+ {/* The run's recorded setup, always visible: mode + provider decide
+ how every number below should be read. */}
+ <div className="flex flex-wrap items-center gap-1.5 pt-0.5 text-[10px] text-muted-foreground">
+ {[env.voice_mode, env.wake_source, env.language, ...env.providers, ...env.models]
+ .filter(Boolean)
+ .map((v, i) => (
+ <span
+ key={`${v}-${i}`}
+ className="rounded bg-muted/40 px-1.5 py-px font-mono ring-1 ring-inset ring-border/60"
+ >
+ {v}
+ </span>
+ ))}
+ </div>
{tags.length > 0 && (
<div className="pt-0.5">
<FeatureBadges tags={tags} />
@@ -79,6 +118,15 @@ export function RunDetail({ sessionId }: { sessionId: string }) {
{/* ── Scrollable body (centered reading column) ───────────── */}
<div className="min-h-0 flex-1 overflow-y-auto">
<div className="mx-auto w-full max-w-5xl space-y-3 p-5">
+ <Collapsible
+ label={t("run_inspector.environment")}
+ open={showEnv}
+ onToggle={() => setShowEnv((v) => !v)}
+ testId="environment-toggle"
+ >
+ <EnvironmentPanel env={env} />
+ </Collapsible>
+
<Collapsible
label={t("run_inspector.deep_dive")}
open={showMetrics}
@@ -87,6 +135,20 @@ export function RunDetail({ sessionId }: { sessionId: string }) {
<MetricsPanel run={run} />
</Collapsible>
+ {/* Events the recorder stored WITHOUT a turn id — the session frame
+ (wake, session open/close, provider switches between turns). They
+ belong to no turn card and were previously dropped entirely. */}
+ {sessionEvents.length > 0 && (
+ <Collapsible
+ label={`${t("run_inspector.session_events")} · ${sessionEvents.length}`}
+ open={showSessionEvents}
+ onToggle={() => setShowSessionEvents((v) => !v)}
+ testId="session-events-toggle"
+ >
+ <EventStream events={sessionEvents} />
+ </Collapsible>
+ )}
+
{run.turns.map((turn) => (
<RunTurnCard key={turn.trace_id} turn={turn} />
))}
@@ -96,12 +158,6 @@ export function RunDetail({ sessionId }: { sessionId: string }) {
);
}
-function localeForUiLanguage(language: string): string {
- if (language === "de") return "de-DE";
- if (language === "es") return "es-ES";
- return "en-US";
-}
-
function LatencyChip({ status }: { status: string }) {
if (status === "ok") return null;
const cls =
@@ -116,15 +172,15 @@ function LatencyChip({ status }: { status: string }) {
}
function Collapsible({
- label, open, onToggle, children,
+ label, open, onToggle, children, testId = "metrics-toggle",
}: {
- label: string; open: boolean; onToggle: () => void; children: ReactNode;
+ label: string; open: boolean; onToggle: () => void; children: ReactNode; testId?: string;
}) {
return (
<div className="rounded-lg border border-border/70">
<button
type="button"
- data-testid="metrics-toggle"
+ data-testid={testId}
onClick={onToggle}
className="flex w-full items-center gap-2 px-3 py-2 text-left text-xs font-medium text-foreground/90 transition-colors hover:text-foreground"
>
@@ -132,7 +188,10 @@ function Collapsible({
{label}
</button>
{open && (
- <div data-testid="metrics" className="border-t border-border/60 px-3 py-3 text-xs">
+ <div
+ data-testid={testId.replace(/-toggle$/, "")}
+ className="border-t border-border/60 px-3 py-3 text-xs"
+ >
{children}
</div>
)}
diff --git a/jarvis/ui/web/frontend/src/components/runs/RunTurnCard.tsx b/jarvis/ui/web/frontend/src/components/runs/RunTurnCard.tsx
index 26d1dccb91..2a91815828 100644
--- a/jarvis/ui/web/frontend/src/components/runs/RunTurnCard.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/RunTurnCard.tsx
@@ -1,9 +1,12 @@
/**
- * One Run-turn, fully visible (modeled on the Transcription TurnCard) and
- * enriched with the forensic lens: what the user said, what Jarvis answered,
- * and — the headline — exactly WHICH capabilities/agents/tools this turn
- * triggered. Deep forensics (latency, decision path, timeline, errors) stay one
- * click away so the card reads cleanly at a glance.
+ * One Run-turn, from the developer's angle.
+ *
+ * The top of the card stays readable (what was said, what came back, which
+ * capabilities fired); everything a developer needs to reconstruct HOW the turn
+ * was handled lives in the forensic tab strip below it — decisions with their
+ * recorded rationale, the latency waterfall, tool I/O, the raw event stream and
+ * errors. Tabs rather than five stacked sections, because the useful move is
+ * "show me the events for THIS turn", not "scroll past four panels".
*/
import { useState } from "react";
import type { ReactNode } from "react";
@@ -14,13 +17,15 @@ import { Card, CardContent } from "@/components/ui/card";
import { useEventStore } from "@/store/events";
import { useT } from "@/i18n";
+import { fmtInt, fmtMs, useRunLocale } from "./format";
+
import { OutcomeBadge } from "./OutcomeBadge";
import { FeatureBadges } from "./FeatureBadges";
-import { TimelinePanel } from "./TimelinePanel";
import { LatencyWaterfall } from "./LatencyWaterfall";
import { DecisionPath } from "./DecisionPath";
import { ToolTable } from "./ToolTable";
import { ErrorPanel } from "./ErrorPanel";
+import { EventStream } from "./EventStream";
import type { RunTurn, TranscriptLine } from "./types";
const ROLE_TONE: Record<string, string> = {
@@ -37,15 +42,19 @@ const ROLE_LABEL: Record<string, string> = {
error: "error",
};
+type TabId = "decisions" | "latency" | "tools" | "events" | "errors";
+
export function RunTurnCard({ turn }: { turn: RunTurn }) {
const t = useT();
const assistantName = useEventStore((s) => s.assistantName);
+ const locale = useRunLocale();
const [showForensics, setShowForensics] = useState(false);
+ const [tab, setTab] = useState<TabId>("events");
// "What happened" = every transcript line that is NOT the headline user
// utterance or the headline Jarvis reply (those get their own blocks), and
// not raw state-machine churn. Carries intermediate phrases, tool/CU outcomes
- // and system outputs (exit codes, "das hat nicht geklappt", denials). i18n-allow
+ // and system outputs (exit codes, denials).
const trace = (turn.transcript ?? []).filter(
(l) =>
l.kind !== "SystemStateChanged" &&
@@ -54,11 +63,17 @@ export function RunTurnCard({ turn }: { turn: RunTurn }) {
);
const triggered = [...turn.activity.agents, ...turn.activity.tools];
- const hasForensics =
- turn.latency.length > 0 ||
- turn.decision_path.length > 0 ||
- turn.timeline.length > 0 ||
- turn.errors.length > 0;
+ // Defaulted, not assumed — a run served by an older backend must render a
+ // quiet empty tab, never crash the inspector (BUG-008 degrade contract).
+ const events = turn.events ?? [];
+ const tabs: Array<{ id: TabId; label: string; count: number }> = [
+ { id: "decisions", label: t("run_inspector.panel.decision"), count: turn.decision_path.length },
+ { id: "latency", label: t("run_inspector.panel.latency"), count: turn.latency.length },
+ { id: "tools", label: t("run_inspector.panel.tools"), count: turn.tools.length },
+ { id: "events", label: t("run_inspector.panel.events"), count: events.length },
+ { id: "errors", label: t("run_inspector.panel.errors"), count: turn.errors.length },
+ ];
+ const hasForensics = tabs.some((x) => x.count > 0);
return (
<Card className="bg-background/40" data-testid="run-turn-card">
@@ -78,10 +93,19 @@ export function RunTurnCard({ turn }: { turn: RunTurn }) {
{turn.model || turn.provider}
</Badge>
)}
- {(turn.tokens_in > 0 || turn.tokens_out > 0) && (
- <span>{turn.tokens_in}+{turn.tokens_out} tok</span>
+ {/* "Not measured" and "measured as zero" are different facts —
+ printing a bare 0 for a realtime turn billed at session level
+ would misreport it as free. */}
+ {turn.usage_recorded ? (
+ <>
+ <span>{fmtInt(turn.tokens_in, locale)}+{fmtInt(turn.tokens_out, locale)} tok</span>
+ {turn.cost_usd > 0 && <span>· ${turn.cost_usd.toFixed(4)}</span>}
+ </>
+ ) : (
+ <span className="italic text-muted-foreground/70">
+ {t("run_inspector.no_usage")}
+ </span>
)}
- {turn.cost_usd > 0 && <span>· ${turn.cost_usd.toFixed(3)}</span>}
</div>
</div>
@@ -124,6 +148,11 @@ export function RunTurnCard({ turn }: { turn: RunTurn }) {
</div>
)}
+ {/* Turn facts — the small machine-readable truths that used to be
+ recorded but never shown (endpoint reason, prompt-cache hit,
+ barge-in, prompt size, the trace id you need to grep a log for). */}
+ <TurnFacts turn={turn} />
+
{/* Think / speak */}
{(turn.think_ms > 0 || turn.speak_ms > 0) && (
<div className="flex flex-wrap items-center gap-3 text-[11px] text-muted-foreground">
@@ -147,26 +176,44 @@ export function RunTurnCard({ turn }: { turn: RunTurn }) {
>
<span>{showForensics ? "▾" : "▸"}</span>
{t("run_inspector.forensics")}
+ <span className="text-[10px] text-muted-foreground/70">
+ · {events.length} {t("run_inspector.stream.events")}
+ </span>
</button>
{showForensics && (
- <div className="mt-2 space-y-3 text-xs">
- <Section label={t("run_inspector.panel.latency")}>
- <LatencyWaterfall entries={turn.latency} />
- </Section>
- <Section label={t("run_inspector.panel.decision")}>
- <DecisionPath steps={turn.decision_path} />
- </Section>
- <Section label={t("run_inspector.panel.tools")}>
- <ToolTable tools={turn.tools} />
- </Section>
- <Section label={t("run_inspector.panel.timeline")}>
- <TimelinePanel turn={turn} />
- </Section>
- {turn.errors.length > 0 && (
- <Section label={t("run_inspector.panel.errors")}>
- <ErrorPanel errors={turn.errors} />
- </Section>
- )}
+ <div className="mt-2 space-y-2">
+ <div className="flex flex-wrap gap-1" role="tablist">
+ {tabs.map((x) => (
+ <button
+ key={x.id}
+ type="button"
+ role="tab"
+ aria-selected={tab === x.id}
+ data-testid={`forensic-tab-${x.id}`}
+ onClick={() => setTab(x.id)}
+ disabled={x.count === 0}
+ className={`rounded-md px-2 py-1 text-[11px] font-medium transition-colors ${
+ tab === x.id
+ ? "bg-primary/15 text-foreground ring-1 ring-inset ring-primary/30"
+ : x.count === 0
+ ? "text-muted-foreground/40"
+ : "text-muted-foreground hover:bg-muted/40 hover:text-foreground"
+ }`}
+ >
+ {x.label}
+ <span className="ml-1 tabular-nums opacity-70">{x.count}</span>
+ </button>
+ ))}
+ </div>
+ <div className="rounded-md border border-border/50 bg-background/30 p-2 text-xs">
+ {tab === "decisions" && <DecisionPath steps={turn.decision_path} />}
+ {tab === "latency" && <LatencyWaterfall entries={turn.latency} />}
+ {tab === "tools" && <ToolTable tools={turn.tools} />}
+ {tab === "events" && (
+ <EventStream events={events} truncated={turn.events_truncated} />
+ )}
+ {tab === "errors" && <ErrorPanel errors={turn.errors} />}
+ </div>
</div>
)}
</div>
@@ -176,6 +223,38 @@ export function RunTurnCard({ turn }: { turn: RunTurn }) {
);
}
+function TurnFacts({ turn }: { turn: RunTurn }) {
+ const t = useT();
+ const locale = useRunLocale();
+ const facts: Array<[string, string]> = [];
+ if (turn.extras.endpoint_reason) {
+ facts.push([t("run_inspector.facts.endpoint"), turn.extras.endpoint_reason]);
+ }
+ if (turn.extras.cache_hit !== null) {
+ facts.push([
+ t("run_inspector.facts.cache"),
+ turn.extras.cache_hit ? t("run_inspector.facts.cache_hit") : t("run_inspector.facts.cache_miss"),
+ ]);
+ }
+ if (turn.extras.interrupted) {
+ facts.push([t("run_inspector.facts.interrupted"), "yes"]);
+ }
+ if (turn.extras.context_tokens) {
+ facts.push([t("run_inspector.facts.context"), `${fmtInt(turn.extras.context_tokens, locale)} tok`]);
+ }
+ facts.push(["trace_id", turn.trace_id]);
+ return (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[10px] text-muted-foreground">
+ {facts.map(([k, v]) => (
+ <span key={k} className="inline-flex items-center gap-1">
+ <span className="uppercase tracking-[0.1em] opacity-70">{k}</span>
+ <span className="font-mono text-foreground/70">{v}</span>
+ </span>
+ ))}
+ </div>
+ );
+}
+
function Block({
icon, label, accent, box, children,
}: {
@@ -205,17 +284,3 @@ function TraceLine({ line }: { line: TranscriptLine }) {
);
}
-function Section({ label, children }: { label: string; children: ReactNode }) {
- return (
- <div>
- <div className="mb-1 text-[10px] uppercase tracking-wider text-muted-foreground">{label}</div>
- {children}
- </div>
- );
-}
-
-function fmtMs(ms: number): string {
- if (ms <= 0) return "0ms";
- if (ms >= 1000) return `${(ms / 1000).toFixed(1)}s`;
- return `${ms}ms`;
-}
diff --git a/jarvis/ui/web/frontend/src/components/runs/TimelinePanel.tsx b/jarvis/ui/web/frontend/src/components/runs/TimelinePanel.tsx
deleted file mode 100644
index 8853c4d096..0000000000
--- a/jarvis/ui/web/frontend/src/components/runs/TimelinePanel.tsx
+++ /dev/null
@@ -1,16 +0,0 @@
-import type { RunTurn } from "./types";
-
-export function TimelinePanel({ turn }: { turn: RunTurn }) {
- if (turn.timeline.length === 0) return <span className="text-muted-foreground/60">n/a</span>;
- return (
- <ol className="space-y-0.5 font-mono text-[10px]">
- {turn.timeline.map((ev, i) => (
- <li key={i} className="flex gap-2">
- <span className="w-12 shrink-0 text-right text-muted-foreground">+{(ev.offset_ms / 1000).toFixed(2)}s</span>
- <span className="w-44 shrink-0 truncate">{ev.kind}</span>
- <span className="flex-1 truncate text-muted-foreground">{ev.summary}</span>
- </li>
- ))}
- </ol>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/runs/ToolTable.tsx b/jarvis/ui/web/frontend/src/components/runs/ToolTable.tsx
index d2bccc2c87..606c5b2468 100644
--- a/jarvis/ui/web/frontend/src/components/runs/ToolTable.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/ToolTable.tsx
@@ -1,29 +1,124 @@
+/**
+ * Every tool / CLI this turn actually ran — with what it was given and what it
+ * returned.
+ *
+ * `command` and `output` have been captured on the wire for a while (from
+ * ToolCallStarted.args_preview / ToolCallCompleted.output_preview, both
+ * redacted + length-capped by their publisher) but were never rendered, so the
+ * table could only say "some tool ran, exit 0" — which is precisely the
+ * question a developer does NOT have. They expand on click so the common case
+ * stays a compact row.
+ */
+import { useState } from "react";
+import { ChevronDown, ChevronRight } from "lucide-react";
+
+import { useT } from "@/i18n";
+
import type { ToolCall } from "./types";
+const RISK_STYLE: Record<string, string> = {
+ safe: "text-emerald-400/80",
+ monitor: "text-sky-300/80",
+ ask: "text-amber-300/90",
+ block: "text-rose-300",
+};
+
export function ToolTable({ tools }: { tools: ToolCall[] }) {
- if (tools.length === 0) return <span className="text-muted-foreground/60">—</span>;
+ const t = useT();
+ const [open, setOpen] = useState<Set<number>>(new Set());
+ if (tools.length === 0) {
+ return <span className="text-muted-foreground/60">{t("run_inspector.tools.empty")}</span>;
+ }
+ const toggle = (i: number) =>
+ setOpen((prev) => {
+ const next = new Set(prev);
+ if (next.has(i)) next.delete(i);
+ else next.add(i);
+ return next;
+ });
+
return (
- <table className="w-full text-[11px]">
- <tbody>
- {tools.map((t, i) => (
- <tr key={i} className="border-t border-border/40 align-top">
- <td className="py-0.5 font-mono">
- {t.name}
- {t.error_line && (
- <div className="max-w-[420px] truncate font-sans text-[10px] text-destructive/80">
- {t.error_line}
- </div>
+ <ul className="space-y-1" data-testid="tool-table">
+ {tools.map((tool, i) => {
+ const detail = tool.command || tool.output || tool.error_line;
+ const isOpen = open.has(i);
+ return (
+ <li
+ key={`${tool.name}-${i}`}
+ data-tool={tool.name}
+ data-success={tool.success}
+ className="rounded-md border border-border/50 bg-background/40"
+ >
+ <button
+ type="button"
+ onClick={() => detail && toggle(i)}
+ className={`flex w-full items-center gap-2 px-2 py-1.5 text-left text-[11px] ${detail ? "hover:bg-muted/30" : "cursor-default"}`}
+ >
+ <span className="w-3 shrink-0 text-muted-foreground">
+ {detail ? (
+ isOpen ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />
+ ) : null}
+ </span>
+ <span className="min-w-0 flex-1 truncate font-mono text-foreground/90">{tool.name}</span>
+ {tool.caller && (
+ <span className="shrink-0 text-[10px] text-muted-foreground">{tool.caller}</span>
+ )}
+ {tool.risk_tier && (
+ <span className={`shrink-0 text-[10px] ${RISK_STYLE[tool.risk_tier] ?? "text-muted-foreground"}`}>
+ {tool.risk_tier}
+ </span>
+ )}
+ {tool.approved_by && (
+ <span className="shrink-0 text-[10px] text-muted-foreground">
+ ✓ {tool.approved_by}
+ </span>
)}
- </td>
- <td className="text-muted-foreground">{t.risk_tier || "—"}</td>
- <td className="text-muted-foreground">{t.approved_by ?? ""}</td>
- <td className="text-right">{t.duration_ms != null ? `${t.duration_ms}ms` : ""}</td>
- <td className={`text-right ${t.success ? "text-emerald-500" : "text-destructive"}`}>
- {t.exit_code != null ? `exit ${t.exit_code}` : (t.success ? "ok" : "fail")}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
+ {tool.duration_ms != null && (
+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground">
+ {tool.duration_ms}ms
+ </span>
+ )}
+ <span
+ className={`shrink-0 font-mono text-[10px] ${tool.success ? "text-emerald-400" : "text-rose-300"}`}
+ >
+ {tool.exit_code != null ? `exit ${tool.exit_code}` : tool.success ? "ok" : "fail"}
+ </span>
+ </button>
+ {isOpen && detail && (
+ <div className="space-y-1.5 border-t border-border/40 px-3 py-2">
+ {tool.command && (
+ <Field label={t("run_inspector.tools.command")} value={tool.command} />
+ )}
+ {tool.output && (
+ <Field label={t("run_inspector.tools.output")} value={tool.output} />
+ )}
+ {tool.error_line && (
+ <Field label={t("run_inspector.tools.error")} value={tool.error_line} tone="error" />
+ )}
+ </div>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
+
+function Field({
+ label, value, tone = "default",
+}: {
+ label: string; value: string; tone?: "default" | "error";
+}) {
+ return (
+ <div>
+ <div className="mb-0.5 text-[9px] font-medium uppercase tracking-[0.12em] text-muted-foreground">
+ {label}
+ </div>
+ <pre
+ className={`overflow-x-auto whitespace-pre-wrap break-words rounded bg-background/70 px-2 py-1 font-mono text-[10px] leading-relaxed [overflow-wrap:anywhere] ${tone === "error" ? "text-rose-300" : "text-foreground/80"}`}
+ >
+ {value}
+ </pre>
+ </div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/runs/__tests__/eventStream.test.tsx b/jarvis/ui/web/frontend/src/components/runs/__tests__/eventStream.test.tsx
new file mode 100644
index 0000000000..eb438c6bf5
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/runs/__tests__/eventStream.test.tsx
@@ -0,0 +1,80 @@
+import { describe, it, expect, vi } from "vitest";
+import { render, fireEvent } from "@testing-library/react";
+
+vi.mock("@/i18n", () => ({
+ useT: () => (k: string) => k,
+ useUiLanguage: () => "en",
+}));
+vi.mock("@/store/events", () => ({
+ useEventStore: (sel: (s: { pushToast: () => void }) => unknown) =>
+ sel({ pushToast: () => undefined }),
+}));
+
+import { EventStream } from "../EventStream";
+import type { RawEvent } from "../types";
+
+const events: RawEvent[] = [
+ { seq: 1, kind: "VoiceTurnStarted", category: "lifecycle", ts_ms: 1000, offset_ms: 0,
+ summary: "turn 1 opened", payload: { turn_index: 0 } },
+ { seq: 2, kind: "LatencySpan", category: "latency", ts_ms: 1041, offset_ms: 41,
+ summary: "realtime_routing_decision · 41ms", payload: { phase: "realtime_routing_decision", duration_ms: 40.7 } },
+ { seq: 3, kind: "BrainTurnCompleted", category: "brain", ts_ms: 8000, offset_ms: 7000,
+ summary: "grok/grok-4.3 · 72729+142 tok · $0.0913", payload: { provider: "grok", tokens_in: 72729 } },
+];
+
+describe("EventStream", () => {
+ it("renders every event with its offset, kind and summary", () => {
+ const { container } = render(<EventStream events={events} />);
+ const text = container.textContent ?? "";
+ expect(text).toContain("VoiceTurnStarted");
+ expect(text).toContain("+41ms");
+ expect(text).toContain("realtime_routing_decision · 41ms");
+ expect(text).toContain("$0.0913");
+ expect(container.querySelectorAll("li")).toHaveLength(3);
+ });
+
+ it("filters by lane", () => {
+ const { container, getByTestId } = render(<EventStream events={events} />);
+ fireEvent.click(getByTestId("lane-brain"));
+ expect(container.querySelectorAll("li")).toHaveLength(1);
+ expect(container.textContent).toContain("BrainTurnCompleted");
+ expect(container.textContent).not.toContain("VoiceTurnStarted");
+ });
+
+ it("filters by free text across kind, summary and payload", () => {
+ const { container, getByTestId } = render(<EventStream events={events} />);
+ fireEvent.change(getByTestId("event-filter"), { target: { value: "grok" } });
+ expect(container.querySelectorAll("li")).toHaveLength(1);
+ expect(container.textContent).toContain("BrainTurnCompleted");
+ });
+
+ it("reveals the verbatim payload on click — the ground truth behind a summary", () => {
+ const { container, getByText } = render(<EventStream events={events} />);
+ expect(container.querySelector("pre")).toBeNull();
+ fireEvent.click(getByText("LatencySpan"));
+ const pre = container.querySelector("pre");
+ expect(pre).not.toBeNull();
+ expect(pre?.textContent).toContain("realtime_routing_decision");
+ expect(pre?.textContent).toContain("40.7");
+ });
+
+ it("states truncation instead of silently cutting the stream", () => {
+ const { container } = render(<EventStream events={events} truncated />);
+ expect(container.textContent).toContain("run_inspector.stream.truncated");
+ });
+
+ it("degrades to an empty marker with no events", () => {
+ const { container } = render(<EventStream events={[]} />);
+ expect(container.textContent).toContain("run_inspector.stream.empty");
+ });
+
+ it("styles an unknown lane instead of failing", () => {
+ const odd: RawEvent[] = [
+ { seq: 9, kind: "FutureEvent", category: "quantum", ts_ms: 0, offset_ms: 0,
+ summary: "something new", payload: {} },
+ ];
+ const { container } = render(<EventStream events={odd} />);
+ expect(container.textContent).toContain("FutureEvent");
+ expect(container.querySelector('[data-category="quantum"]')).not.toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/runs/__tests__/runDetail.test.tsx b/jarvis/ui/web/frontend/src/components/runs/__tests__/runDetail.test.tsx
index 12890367c0..7d20567066 100644
--- a/jarvis/ui/web/frontend/src/components/runs/__tests__/runDetail.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/__tests__/runDetail.test.tsx
@@ -11,7 +11,8 @@ vi.mock("@/hooks/useRuns", () => ({
outcome: "success",
turns: [{ idx: 0, trace_id: "t1", outcome: "success", user_text: "hi", jarvis_text: "yo",
tier: "router", provider: "claude-api", model: "opus", tokens_in: 0, tokens_out: 0,
- cost_usd: 0.012, think_ms: 0, speak_ms: 0, transcript: [], timeline: [], latency: [],
+ cost_usd: 0.012, think_ms: 0, speak_ms: 0, transcript: [], latency: [],
+ events: [], event_counts: {}, events_truncated: false, usage_recorded: true,
decision_path: [], tools: [], errors: [],
extras: { interrupted: false, cache_hit: null, endpoint_reason: null, context_tokens: null },
activity: { tools: [], agents: [] } }],
diff --git a/jarvis/ui/web/frontend/src/components/runs/__tests__/runEnumParity.test.ts b/jarvis/ui/web/frontend/src/components/runs/__tests__/runEnumParity.test.ts
index 1829dce7a5..f46517e07a 100644
--- a/jarvis/ui/web/frontend/src/components/runs/__tests__/runEnumParity.test.ts
+++ b/jarvis/ui/web/frontend/src/components/runs/__tests__/runEnumParity.test.ts
@@ -1,5 +1,8 @@
import { describe, it, expect } from "vitest";
-import { SLO_STATUSES, RUN_DECISION_KINDS, TRANSCRIPT_ROLES, RUN_OUTCOMES } from "../types";
+import {
+ SLO_STATUSES, RUN_DECISION_KINDS, TRANSCRIPT_ROLES, RUN_OUTCOMES,
+ RATIONALE_SOURCES, RUN_EVENT_CATEGORIES,
+} from "../types";
describe("run enum parity", () => {
it("SLO statuses match the Python SSOT order", () => {
@@ -16,4 +19,13 @@ describe("run enum parity", () => {
it("run outcomes match the Python SSOT order", () => {
expect(RUN_OUTCOMES).toEqual(["success", "partial", "failed"]);
});
+ it("rationale sources match the Python SSOT order", () => {
+ expect(RATIONALE_SOURCES).toEqual(["model", "rule"]);
+ });
+ it("event-stream lanes match the Python SSOT order", () => {
+ expect(RUN_EVENT_CATEGORIES).toEqual([
+ "lifecycle", "speech", "brain", "tool", "agent", "vision",
+ "latency", "error", "system",
+ ]);
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/runs/__tests__/runTurnCard.test.tsx b/jarvis/ui/web/frontend/src/components/runs/__tests__/runTurnCard.test.tsx
index b28c7701ee..d7a6a8e52b 100644
--- a/jarvis/ui/web/frontend/src/components/runs/__tests__/runTurnCard.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/__tests__/runTurnCard.test.tsx
@@ -1,7 +1,10 @@
import { describe, it, expect, vi } from "vitest";
import { render } from "@testing-library/react";
-vi.mock("@/i18n", () => ({ useT: () => (k: string) => k }));
+vi.mock("@/i18n", () => ({
+ useT: () => (k: string) => k,
+ useUiLanguage: () => "en",
+}));
import { RunTurnCard } from "../RunTurnCard";
import type { RunTurn } from "../types";
@@ -17,7 +20,8 @@ const turn: RunTurn = {
{ role: "system", kind: "SystemStateChanged", text: "LISTENING -> THINKING", offset_ms: 5, ts_ms: 5, spoken_kind: null },
{ role: "system", kind: "SpeechSpoken", text: "exit 5 - harness reported failure", offset_ms: 50, ts_ms: 50, spoken_kind: null },
],
- timeline: [], latency: [], decision_path: [], tools: [], errors: [],
+ latency: [], decision_path: [], tools: [], errors: [],
+ events: [], event_counts: {}, events_truncated: false, usage_recorded: true,
extras: { interrupted: false, cache_hit: null, endpoint_reason: null, context_tokens: null },
activity: { tools: ["search_web"], agents: ["computer_use"] },
};
diff --git a/jarvis/ui/web/frontend/src/components/runs/__tests__/toolTable.test.tsx b/jarvis/ui/web/frontend/src/components/runs/__tests__/toolTable.test.tsx
index 463cf6d409..f74f97af38 100644
--- a/jarvis/ui/web/frontend/src/components/runs/__tests__/toolTable.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/__tests__/toolTable.test.tsx
@@ -1,26 +1,52 @@
-import { describe, it, expect } from "vitest";
-import { render } from "@testing-library/react";
+import { describe, it, expect, vi } from "vitest";
+import { render, fireEvent } from "@testing-library/react";
+
+vi.mock("@/i18n", () => ({
+ useT: () => (k: string) => k,
+ useUiLanguage: () => "en",
+}));
+
import { ToolTable } from "../ToolTable";
import type { ToolCall } from "../types";
const tools: ToolCall[] = [
- { name: "computer_use", caller: "", risk_tier: "monitor", approved_by: null,
- duration_ms: null, exit_code: null, success: true, error_line: null },
+ { name: "computer_use", caller: "router_tool", risk_tier: "monitor", approved_by: "whitelist",
+ duration_ms: 420, exit_code: null, success: true, error_line: null,
+ command: "open_app(name='settings')", output: "window focused" },
{ name: "open_app", caller: "", risk_tier: "safe", approved_by: null,
duration_ms: null, exit_code: null, success: false,
- error_line: "Anwendung 'settings' nicht gefunden" },
+ error_line: "application 'settings' not found",
+ command: "", output: "" },
];
describe("ToolTable", () => {
- it("shows a failed tool as 'fail' and surfaces the reason", () => {
+ it("shows each tool with its caller, risk tier, approval and outcome", () => {
const { container } = render(<ToolTable tools={tools} />);
- expect(container.textContent).toContain("computer_use");
- expect(container.textContent).toContain("fail");
- expect(container.textContent).toContain("settings' nicht gefunden");
+ const text = container.textContent ?? "";
+ expect(text).toContain("computer_use");
+ expect(text).toContain("router_tool");
+ expect(text).toContain("monitor");
+ expect(text).toContain("whitelist");
+ expect(text).toContain("fail");
+ });
+
+ it("reveals the command and the result on expand", () => {
+ const { container, getByText } = render(<ToolTable tools={tools} />);
+ // Collapsed: the captured I/O is not rendered yet.
+ expect(container.textContent).not.toContain("window focused");
+ fireEvent.click(getByText("computer_use"));
+ expect(container.textContent).toContain("open_app(name='settings')");
+ expect(container.textContent).toContain("window focused");
+ });
+
+ it("reveals a failed tool's reason on expand", () => {
+ const { container, getByText } = render(<ToolTable tools={tools} />);
+ fireEvent.click(getByText("open_app"));
+ expect(container.textContent).toContain("application 'settings' not found");
});
it("renders the empty marker for no tools", () => {
const { container } = render(<ToolTable tools={[]} />);
- expect(container.textContent).toContain("—");
+ expect(container.textContent).toContain("run_inspector.tools.empty");
});
});
diff --git a/jarvis/ui/web/frontend/src/components/runs/format.ts b/jarvis/ui/web/frontend/src/components/runs/format.ts
new file mode 100644
index 0000000000..e43edcb7b8
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/runs/format.ts
@@ -0,0 +1,34 @@
+/**
+ * One number/locale policy for the whole Run Inspector.
+ *
+ * Bare `toLocaleString()` follows the BROWSER's locale, not the app's UI
+ * language. On a German-locale machine running the English UI that rendered
+ * "3.613" for 3613 tokens — which an English reader parses as three-point-six.
+ * Worse, the same run showed the value three different ways (raw "3613", German
+ * "3.613", and a locale-aware "3,613") depending on which panel drew it.
+ * Everything here routes through the UI language instead.
+ */
+import { useUiLanguage } from "@/i18n";
+
+export function localeForUiLanguage(language: string): string {
+ if (language === "de") return "de-DE";
+ if (language === "es") return "es-ES";
+ return "en-US";
+}
+
+/** The BCP-47 locale matching the app's current UI language. */
+export function useRunLocale(): string {
+ return localeForUiLanguage(useUiLanguage());
+}
+
+/** Thousands-grouped integer in the UI language. */
+export function fmtInt(n: number, locale: string): string {
+ return n.toLocaleString(locale);
+}
+
+/** Compact duration: sub-second in ms, otherwise seconds with one decimal. */
+export function fmtMs(ms: number): string {
+ if (ms <= 0) return "0ms";
+ if (ms >= 1000) return `${(ms / 1000).toFixed(1)}s`;
+ return `${Math.round(ms)}ms`;
+}
diff --git a/jarvis/ui/web/frontend/src/components/runs/types.ts b/jarvis/ui/web/frontend/src/components/runs/types.ts
index 4a070b5a1f..fadc901f6e 100644
--- a/jarvis/ui/web/frontend/src/components/runs/types.ts
+++ b/jarvis/ui/web/frontend/src/components/runs/types.ts
@@ -7,12 +7,44 @@ export const SLO_STATUSES = ["ok", "warn", "breach"] as const;
export const RUN_DECISION_KINDS = [
"tier", "route", "risk", "brain", "mission", "fallback",
] as const;
+export const RATIONALE_SOURCES = ["model", "rule"] as const;
export const TRANSCRIPT_ROLES = ["user", "jarvis", "system", "tool", "error"] as const;
export const RUN_OUTCOMES = ["success", "partial", "failed"] as const;
+// Lanes of the raw developer event stream — colour + filter groups.
+export const RUN_EVENT_CATEGORIES = [
+ "lifecycle", "speech", "brain", "tool", "agent", "vision", "latency", "error", "system",
+] as const;
export type SloStatus = string;
export interface RunActivity { tools: string[]; agents: string[]; }
+/** One persisted bus event, verbatim — the developer's ground truth. */
+export interface RawEvent {
+ seq: number;
+ kind: string;
+ category: string; // see RUN_EVENT_CATEGORIES
+ ts_ms: number;
+ offset_ms: number;
+ summary: string;
+ payload: Record<string, unknown>;
+}
+
+/** How the run was configured, read back from what was recorded. */
+export interface RunEnvironment {
+ voice_mode: string;
+ surface: string;
+ wake_source: string;
+ wake_keyword: string;
+ language: string;
+ hangup_reason: string;
+ providers: string[];
+ models: string[];
+ tiers: string[];
+ voices: string[];
+ input_sample_rate: number | null;
+ output_sample_rate: number | null;
+}
+
export interface TraceEvent { kind: string; offset_ms: number; ts_ms: number; summary: string; }
export interface TranscriptLine {
role: string; kind: string; text: string;
@@ -22,9 +54,16 @@ export interface ToolCall {
name: string; caller: string; risk_tier: string;
approved_by: string | null; duration_ms: number | null;
exit_code: number | null; success: boolean; error_line: string | null;
+ // What was actually run and what came back — both redacted + capped upstream.
+ command: string; output: string;
}
export interface LatencyEntry { phase: string; duration_ms: number; slo_status: SloStatus; }
-export interface DecisionStep { kind: string; label: string; detail: string | null; }
+export interface DecisionStep {
+ kind: string; label: string; detail: string | null;
+ // The honest "why". rationale_source: "model" = the brain's own words,
+ // "rule" = deterministic explanation from a captured fact, "" = none recorded.
+ rationale: string; rationale_source: string;
+}
export interface ErrorEntry { source: string; layer: string | null; message: string; recoverable: boolean | null; }
export interface TurnExtras {
interrupted: boolean; cache_hit: boolean | null;
@@ -39,9 +78,14 @@ export interface RunTurn {
tokens_in: number; tokens_out: number; cost_usd: number;
think_ms: number; speak_ms: number;
transcript: TranscriptLine[];
- timeline: TraceEvent[]; latency: LatencyEntry[]; decision_path: DecisionStep[];
+ latency: LatencyEntry[]; decision_path: DecisionStep[];
tools: ToolCall[]; errors: ErrorEntry[]; extras: TurnExtras;
activity: RunActivity;
+ events: RawEvent[];
+ event_counts: Record<string, number>;
+ events_truncated: boolean;
+ // false = no usage was measured for this turn (≠ "it cost zero").
+ usage_recorded: boolean;
}
export interface RunAnalytics {
total_duration_s: number | null; total_think_ms: number; total_speak_ms: number;
@@ -63,4 +107,7 @@ export interface Run {
missions: MissionRef[];
activity: RunActivity;
analytics: RunAnalytics;
+ environment: RunEnvironment;
+ session_events: RawEvent[];
+ event_counts: Record<string, number>;
}
diff --git a/tests/unit/runs/test_constants_parity.py b/tests/unit/runs/test_constants_parity.py
index 5c7ffe572d..4fb508e88e 100644
--- a/tests/unit/runs/test_constants_parity.py
+++ b/tests/unit/runs/test_constants_parity.py
@@ -3,6 +3,10 @@ from jarvis.runs.constants import (
RUN_DECISION_KINDS, DECISION_TIER, DECISION_ROUTE, DECISION_RISK,
DECISION_BRAIN, DECISION_MISSION, DECISION_FALLBACK,
RATIONALE_SOURCES, RATIONALE_MODEL, RATIONALE_RULE,
+ RUN_EVENT_CATEGORIES, EVENT_CATEGORY_BY_KIND,
+ EVENT_CAT_LIFECYCLE, EVENT_CAT_SPEECH, EVENT_CAT_BRAIN, EVENT_CAT_TOOL,
+ EVENT_CAT_AGENT, EVENT_CAT_VISION, EVENT_CAT_LATENCY, EVENT_CAT_ERROR,
+ EVENT_CAT_SYSTEM,
)
@@ -26,3 +30,23 @@ def test_rationale_sources_complete_and_stable():
# "rule" = a deterministic explanation built from a captured fact.
assert RATIONALE_SOURCES == (RATIONALE_MODEL, RATIONALE_RULE)
assert set(RATIONALE_SOURCES) == {"model", "rule"}
+
+
+def test_event_categories_complete_and_stable():
+ # Lanes of the raw developer event stream; crosses Python -> TS -> UI.
+ assert RUN_EVENT_CATEGORIES == (
+ EVENT_CAT_LIFECYCLE, EVENT_CAT_SPEECH, EVENT_CAT_BRAIN, EVENT_CAT_TOOL,
+ EVENT_CAT_AGENT, EVENT_CAT_VISION, EVENT_CAT_LATENCY, EVENT_CAT_ERROR,
+ EVENT_CAT_SYSTEM,
+ )
+ assert set(RUN_EVENT_CATEGORIES) == {
+ "lifecycle", "speech", "brain", "tool", "agent", "vision",
+ "latency", "error", "system",
+ }
+
+
+def test_every_mapped_kind_uses_a_declared_category():
+ # A typo in the map would silently drop an event into an unstyled lane.
+ unknown = {c for c in EVENT_CATEGORY_BY_KIND.values()
+ if c not in RUN_EVENT_CATEGORIES}
+ assert unknown == set()
diff --git a/tests/unit/runs/test_event_stream.py b/tests/unit/runs/test_event_stream.py
new file mode 100644
index 0000000000..199cb8b24c
--- /dev/null
+++ b/tests/unit/runs/test_event_stream.py
@@ -0,0 +1,210 @@
+"""The developer event stream: summaries, lanes, environment, realtime path.
+
+These guard the fix for the Run Inspector's central defect — it derived a
+handful of panels and dropped everything else, so a realtime turn (the default
+mode) rendered an empty decision path and a timeline of blank rows.
+"""
+from __future__ import annotations
+
+from jarvis.runs import analyzer
+from jarvis.runs.constants import (
+ EVENT_CAT_BRAIN,
+ EVENT_CAT_LATENCY,
+ EVENT_CAT_SYSTEM,
+ EVENT_CAT_VISION,
+ MAX_RAW_EVENTS_PER_TURN,
+ RUN_EVENT_CATEGORIES,
+)
+from jarvis.runs.model import RunTurn
+from jarvis.sessions.models import VoiceEventRow, VoiceSessionRow
+from jarvis.sessions.recorder import _RAW_EVENT_KINDS
+
+
+def _ev(kind: str, ts: int = 0, seq: int = 0, **payload) -> VoiceEventRow:
+ return VoiceEventRow(seq=seq, session_id="s1", turn_id="t1", ts_ms=ts,
+ kind=kind, payload=payload)
+
+
+# --- summaries --------------------------------------------------------
+
+
+def test_every_recorded_kind_gets_a_non_empty_summary():
+ """The regression that made the timeline unreadable.
+
+ Only six kinds used to have a summary; everything else rendered as a bare
+ kind name with an empty right-hand column — ~70% of rows in a real run.
+ """
+ blank = [k for k in sorted(_RAW_EVENT_KINDS)
+ if not analyzer.summarize_event(_ev(k, phase="x", duration_ms=1))]
+ assert blank == [], f"kinds with no summary: {blank}"
+
+
+def test_latency_span_summary_names_the_phase_and_duration():
+ s = analyzer.summarize_event(
+ _ev("LatencySpan", phase="realtime_first_audio", duration_ms=45.9)
+ )
+ assert "realtime_first_audio" in s
+ assert "46ms" in s
+
+
+def test_latency_span_summary_drops_the_redundant_session_id_detail():
+ # The realtime path stamps the session id into `detail`; repeating a UUID on
+ # every span buries the phase name. The full payload stays in the raw view.
+ s = analyzer.summarize_event(
+ _ev("LatencySpan", phase="realtime_turn_complete", duration_ms=8127.6,
+ detail="session_id=e97522ea-2c2e-4ae8-8b41-3441f257c96e")
+ )
+ assert "e97522ea" not in s
+ assert "8.13s" in s
+
+
+def test_brain_completed_summary_carries_provider_tokens_and_cost():
+ s = analyzer.summarize_event(
+ _ev("BrainTurnCompleted", provider="grok", model="grok-4.3",
+ tokens_in=72729, tokens_out=142, cost_usd=0.0913, finish_reason="stop")
+ )
+ assert "grok/grok-4.3" in s
+ assert "72729+142 tok" in s
+ assert "$0.0913" in s
+
+
+def test_provider_switch_summary_shows_the_direction():
+ s = analyzer.summarize_event(
+ _ev("BrainProviderSwitched", from_provider="gemini", to_provider="grok")
+ )
+ assert "gemini" in s and "grok" in s
+
+
+def test_unknown_kind_falls_back_to_a_compact_payload_rendering():
+ s = analyzer.summarize_event(_ev("SomeFutureEvent", alpha="one", beta=2))
+ assert "alpha=one" in s and "beta=2" in s
+
+
+# --- lanes ------------------------------------------------------------
+
+
+def test_event_category_maps_known_kinds_and_degrades_unknown_ones():
+ assert analyzer.event_category("BrainTurnStarted") == EVENT_CAT_BRAIN
+ assert analyzer.event_category("LatencySpan") == EVENT_CAT_LATENCY
+ assert analyzer.event_category("CUStepProfiled") == EVENT_CAT_VISION
+ # Unknown kind degrades to a neutral lane, never raises (BUG-008 contract).
+ assert analyzer.event_category("TotallyNewEvent") == EVENT_CAT_SYSTEM
+
+
+def test_every_recorded_kind_has_a_valid_lane():
+ for kind in _RAW_EVENT_KINDS:
+ assert analyzer.event_category(kind) in RUN_EVENT_CATEGORIES
+
+
+# --- raw stream -------------------------------------------------------
+
+
+def test_raw_events_are_chronological_with_offsets_and_payloads():
+ rows, truncated = analyzer.build_raw_events(
+ [_ev("SpeechSpoken", ts=1200, seq=2, text="hi", spoken_kind="reply"),
+ _ev("VoiceTurnStarted", ts=1000, seq=1, turn_index=0)],
+ turn_started_ms=1000,
+ )
+ assert truncated is False
+ assert [r.kind for r in rows] == ["VoiceTurnStarted", "SpeechSpoken"]
+ assert [r.offset_ms for r in rows] == [0, 200]
+ # The verbatim payload rides along — that is the whole point of the panel.
+ assert rows[1].payload["text"] == "hi"
+
+
+def test_raw_events_truncation_is_reported_never_silent():
+ many = [_ev("LatencySpan", ts=i, seq=i, phase="p", duration_ms=1)
+ for i in range(MAX_RAW_EVENTS_PER_TURN + 25)]
+ rows, truncated = analyzer.build_raw_events(many)
+ assert len(rows) == MAX_RAW_EVENTS_PER_TURN
+ assert truncated is True
+
+
+def test_event_counts_are_sorted_by_frequency():
+ counts = analyzer.build_event_counts(
+ [_ev("LatencySpan"), _ev("LatencySpan"), _ev("SpeechSpoken")]
+ )
+ assert list(counts) == ["LatencySpan", "SpeechSpoken"]
+ assert counts["LatencySpan"] == 2
+
+
+# --- realtime decision path -------------------------------------------
+
+
+def test_realtime_turn_gets_a_decision_path_instead_of_nothing():
+ """The single biggest blind spot: realtime emits no BrainTurnStarted, so
+ build_decision_path returned [] for the default voice mode."""
+ steps = analyzer.build_decision_path([
+ _ev("RealtimeSessionReady", ts=1, provider="gemini-live",
+ model="gemini-3.1-flash-live-preview", surface="desktop"),
+ _ev("LatencySpan", ts=2, phase="realtime_routing_decision", duration_ms=41.0),
+ ])
+ kinds = [s.kind for s in steps]
+ assert "brain" in kinds and "route" in kinds
+ brain = next(s for s in steps if s.kind == "brain")
+ assert "gemini-live" in brain.rationale
+ route = next(s for s in steps if s.kind == "route")
+ # Honest: the span proves WHEN and how long, never WHAT was decided.
+ assert "41ms" in route.rationale
+
+
+def test_explicit_provider_switch_becomes_a_fallback_step():
+ steps = analyzer.build_decision_path([
+ _ev("BrainProviderSwitched", ts=1, from_provider="gemini", to_provider="grok"),
+ ])
+ fb = next(s for s in steps if s.kind == "fallback")
+ assert "gemini" in fb.rationale and "grok" in fb.rationale
+
+
+def test_ensure_brain_step_falls_back_to_the_turn_aggregate():
+ turn = RunTurn(idx=0, trace_id="t1", provider="gemini-live",
+ model="gemini-3.1-flash-live-preview", tier="realtime")
+ steps = analyzer.ensure_brain_step([], turn)
+ assert steps[0].kind == "brain"
+ assert "gemini-live" in steps[0].rationale
+ assert steps[0].rationale_source == "rule"
+
+
+def test_ensure_brain_step_never_duplicates_a_captured_brain_step():
+ turn = RunTurn(idx=0, trace_id="t1", provider="grok")
+ steps = analyzer.build_decision_path([
+ _ev("BrainTurnStarted", ts=1, provider="grok", model="grok-4.3"),
+ ])
+ before = len(steps)
+ analyzer.ensure_brain_step(steps, turn)
+ assert len(steps) == before
+
+
+# --- environment ------------------------------------------------------
+
+
+def test_environment_reads_the_recorded_setup_not_the_live_config():
+ session = VoiceSessionRow(
+ id="s1", started_ms=0, ended_ms=1000, hangup_reason="hotkey",
+ providers_used=["gemini-live"], language="de", wake_keyword="ruben",
+ voice_mode="realtime",
+ )
+ turn = RunTurn(idx=0, trace_id="t1", provider="grok", model="grok-4.3", tier="realtime")
+ env = analyzer.build_environment(
+ session,
+ [_ev("RealtimeSessionReady", surface="desktop",
+ input_sample_rate=16000, output_sample_rate=24000),
+ _ev("SpeechSpoken", voice="Fenrir", text="hi")],
+ [turn],
+ )
+ assert env.voice_mode == "realtime"
+ assert env.surface == "desktop"
+ assert env.wake_source == "voice"
+ assert env.hangup_reason == "hotkey"
+ assert env.input_sample_rate == 16000 and env.output_sample_rate == 24000
+ assert env.voices == ["Fenrir"]
+ # Providers/models seen on the turns are folded in beside the session's.
+ assert "gemini-live" in env.providers and "grok" in env.providers
+ assert env.models == ["grok-4.3"]
+
+
+def test_wake_source_classification():
+ assert analyzer.wake_source("hotkey") == "hotkey"
+ assert analyzer.wake_source("telegram") == "channel:telegram"
+ assert analyzer.wake_source("channel:discord") == "channel:discord"
+ assert analyzer.wake_source("ruben") == "voice"
diff --git a/tests/unit/runs/test_list_performance.py b/tests/unit/runs/test_list_performance.py
new file mode 100644
index 0000000000..d31b802aea
--- /dev/null
+++ b/tests/unit/runs/test_list_performance.py
@@ -0,0 +1,118 @@
+"""The run LIST must stay cheap and must not block the event loop.
+
+Both guards exist because of one live failure (2026-07-25): with a voice
+session running, ``GET /api/runs?limit=100`` took 45 s and froze every other
+API call — the desktop UI looked dead. Two causes, one test each:
+
+ 1. the list pulled EVERY event of EVERY session (100 store-lock acquisitions
+ while the recorder wrote through the same lock),
+ 2. the route did that synchronous work directly on the asyncio loop, so the
+ wait blocked the whole server rather than just this request.
+"""
+from __future__ import annotations
+
+import asyncio
+import threading
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.runs.loader import _LIST_EVENT_KINDS, RunLoader
+from jarvis.runs.routes import router as runs_router
+
+
+class _RecordingStore:
+ """Session store stub that records HOW it was queried."""
+
+ def __init__(self, sessions: list) -> None:
+ self._sessions = sessions
+ self.per_session_calls: list[str] = []
+ self.bulk_calls: list[tuple[int, list[str] | None]] = []
+
+ def list_sessions(self, *, limit: int = 100, **_: object) -> list:
+ return self._sessions[:limit]
+
+ def get_events(self, session_id: str) -> list:
+ self.per_session_calls.append(session_id)
+ return []
+
+ def get_events_for_sessions(
+ self, session_ids: list[str], *, kinds: list[str] | None = None
+ ) -> dict[str, list]:
+ self.bulk_calls.append((len(session_ids), kinds))
+ return {}
+
+ def get_session(self, session_id: str): # pragma: no cover - unused here
+ return None
+
+ def get_turns(self, session_id: str) -> list: # pragma: no cover
+ return []
+
+
+def _session(idx: int):
+ from jarvis.sessions.models import SessionListItem
+ return SessionListItem(id=f"s{idx}", started_ms=idx, ended_ms=idx + 1,
+ duration_s=0.001, preview="")
+
+
+def test_list_runs_uses_one_narrow_bulk_query_not_a_fetch_per_session():
+ store = _RecordingStore([_session(i) for i in range(100)])
+ RunLoader(session_store=store, usage_log=None).list_runs(limit=100)
+ assert store.per_session_calls == [], "regressed to a full fetch per session"
+ assert len(store.bulk_calls) == 1
+ count, kinds = store.bulk_calls[0]
+ assert count == 100
+ # Narrow by kind — "all kinds" is exactly the regression this replaced.
+ assert kinds == _LIST_EVENT_KINDS
+ assert "TranscriptionUpdate" not in (kinds or [])
+
+
+def test_run_routes_do_their_blocking_work_off_the_event_loop():
+ """A slow store must not stall a concurrent request on another route."""
+ loop_thread_ids: list[int] = []
+ barrier = threading.Event()
+
+ class _SlowStore(_RecordingStore):
+ def get_events_for_sessions(self, session_ids, *, kinds=None):
+ loop_thread_ids.append(threading.get_ident())
+ barrier.wait(timeout=5.0)
+ return {}
+
+ app = FastAPI()
+ app.include_router(runs_router)
+ app.state.session_store = _SlowStore([_session(0)])
+
+ @app.get("/probe")
+ async def probe() -> dict: # the "is the server still alive?" call
+ return {"alive": True}
+
+ with TestClient(app) as client:
+ # Capture the loop's own thread id, then prove the store ran elsewhere.
+ loop_ident: dict[str, int] = {}
+
+ @app.get("/whoami")
+ async def whoami() -> dict:
+ loop_ident["id"] = threading.get_ident()
+ return loop_ident
+
+ client.get("/whoami")
+
+ done: list[int] = []
+
+ def _call_runs() -> None:
+ done.append(client.get("/api/runs?limit=1").status_code)
+
+ t = threading.Thread(target=_call_runs, daemon=True)
+ t.start()
+ # While the store is blocked, an unrelated route must still answer.
+ for _ in range(50):
+ if loop_thread_ids:
+ break
+ asyncio.run(asyncio.sleep(0.02))
+ assert loop_thread_ids, "store was never called"
+ assert client.get("/probe").json() == {"alive": True}
+ # And the blocking work genuinely ran on a worker thread.
+ assert loop_thread_ids[0] != loop_ident["id"]
+ barrier.set()
+ t.join(timeout=5.0)
+ assert done == [200]
diff --git a/tests/unit/runs/test_model.py b/tests/unit/runs/test_model.py
index 5d87b8a7bb..37df94a5f7 100644
--- a/tests/unit/runs/test_model.py
+++ b/tests/unit/runs/test_model.py
@@ -6,7 +6,7 @@ from jarvis.runs.model import (
def test_run_turn_defaults_are_safe():
t = RunTurn(idx=0, trace_id="t1")
- assert t.timeline == [] and t.latency == [] and t.tools == []
+ assert t.events == [] and t.latency == [] and t.tools == []
assert t.decision_path == [] and t.errors == []
assert t.extras.interrupted is False