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(traces): readable reasoning traces — every feature names itself, the answer streams word by word, and the steps survive the turn

rubenluetke10-beepd6a9a0495a85
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index 850c7a0941..7cfb037140 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -1821,6 +1821,34 @@ class ToolCallCompleted(Event):
error: str | None = None
+@dataclass(frozen=True, slots=True)
+class AssistantTextDelta(Event):
+ """The assistant's reply while it is still being produced — word by word.
+
+ Published by every reply path that sees text before the whole answer is
+ in: the typed-chat bridge (``BrainManager.generate(text_consumer=…)``),
+ the classic speech pipeline's brain stream, and the realtime session's
+ output transcript. The UI shows it as the growing, muted answer and
+ replaces it with the authoritative final text (``MessageSent`` /
+ ``SpeechSpoken``) when the turn closes — so nothing here is history, and
+ a snapshot that never gets its ``done`` is simply discarded.
+
+ ``text`` is the CUMULATIVE snapshot so far, never a chunk: WebSocket
+ delivery is at-least-once and the desktop may run several windows, and a
+ snapshot is idempotent where a chunk would double up. Publishers coalesce
+ through :class:`jarvis.core.text_stream.TextDeltaPublisher` so the bus
+ sees a handful of events per second, not one per token (AP-9: nothing
+ here may weigh on the voice hot path).
+ """
+
+ text: str = ""
+ thread_id: str = ""
+ # Which reply path produced it: "chat" | "voice" | "realtime".
+ channel: str = ""
+ # The last snapshot of this turn — the UI may stop waiting for more.
+ done: bool = False
+
+
@dataclass(frozen=True, slots=True)
class JarvisAgentBackgroundCompleted(Event):
"""A background Jarvis-Agent task finished — TTS should speak proactively.
diff --git a/jarvis/core/text_stream.py b/jarvis/core/text_stream.py
new file mode 100644
index 0000000000..ed5f67afc8
--- /dev/null
+++ b/jarvis/core/text_stream.py
@@ -0,0 +1,168 @@
+"""Coalesced publisher for :class:`~jarvis.core.events.AssistantTextDelta`.
+
+A brain stream hands over text in token-sized pieces, twenty to fifty times a
+second. Publishing one bus event per piece would wake every wildcard
+subscriber (the session recorder, every WebSocket window, the deck) that
+often — measurable on the voice hot path (AP-9) and pointless on screen,
+where anything under ~60 ms reads as "live" anyway. This publisher buffers
+the pieces and publishes the CUMULATIVE text at most once per
+``interval_s``; the final ``flush(done=True)`` publishes whatever is left with
+the turn's closing flag.
+
+Pure asyncio, no threads of its own: ``feed`` is synchronous (the brain's
+``text_consumer`` callback is), schedules a timer on the loop it was created
+on, and is safe to call from another thread (``call_soon_threadsafe``). Every
+publish is best-effort — a failing subscriber must never reach the caller,
+who is in the middle of producing the answer.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import TYPE_CHECKING, Any
+from uuid import UUID
+
+from jarvis.core.events import AssistantTextDelta
+
+if TYPE_CHECKING:
+ from jarvis.core.bus import EventBus
+
+log = logging.getLogger(__name__)
+
+#: Default coalescing window — four to five snapshots per second reads as
+#: word-by-word on screen without flooding the bus.
+DEFAULT_INTERVAL_S = 0.08
+
+
+class TextDeltaPublisher:
+ """Turn a stream of text pieces into a few cumulative ``AssistantTextDelta`` events."""
+
+ def __init__(
+ self,
+ bus: EventBus | None,
+ *,
+ channel: str,
+ thread_id: str = "",
+ trace_id: UUID | None = None,
+ source_layer: str = "",
+ interval_s: float = DEFAULT_INTERVAL_S,
+ loop: asyncio.AbstractEventLoop | None = None,
+ ) -> None:
+ self._bus = bus
+ self._channel = channel
+ self._thread_id = thread_id
+ self._trace_id = trace_id
+ self._source_layer = source_layer or f"text_stream.{channel}"
+ self._interval_s = max(0.0, float(interval_s))
+ self._loop = loop
+ self._text = ""
+ self._published = ""
+ self._dirty = False
+ self._handle: asyncio.TimerHandle | None = None
+ self._closed = False
+
+ # ------------------------------------------------------------------
+ # Producer side (sync, may be off-loop)
+ # ------------------------------------------------------------------
+
+ @property
+ def text(self) -> str:
+ """Everything fed so far."""
+ return self._text
+
+ def feed(self, chunk: str) -> None:
+ """Append ``chunk`` and schedule a publish within the interval."""
+ if not chunk or self._closed:
+ return
+ self._text += chunk
+ self._mark_dirty()
+
+ def set_text(self, snapshot: str) -> None:
+ """Replace the whole text (for producers that already keep a running snapshot)."""
+ if self._closed or snapshot == self._text:
+ return
+ self._text = snapshot
+ self._mark_dirty()
+
+ def _mark_dirty(self) -> None:
+ self._dirty = True
+ if self._bus is None or self._handle is not None:
+ return
+ loop = self._resolve_loop()
+ if loop is None:
+ return
+ try:
+ running = asyncio.get_running_loop()
+ except RuntimeError:
+ running = None
+ if running is loop:
+ self._handle = loop.call_later(self._interval_s, self._tick)
+ else:
+ loop.call_soon_threadsafe(self._arm_on_loop)
+
+ def _arm_on_loop(self) -> None:
+ if self._handle is None and not self._closed and self._loop is not None:
+ self._handle = self._loop.call_later(self._interval_s, self._tick)
+
+ def _resolve_loop(self) -> asyncio.AbstractEventLoop | None:
+ if self._loop is None:
+ try:
+ self._loop = asyncio.get_running_loop()
+ except RuntimeError:
+ return None
+ return self._loop
+
+ def _tick(self) -> None:
+ self._handle = None
+ if self._closed or not self._dirty or self._loop is None:
+ return
+ self._loop.create_task(self._publish(done=False))
+
+ # ------------------------------------------------------------------
+ # Publishing
+ # ------------------------------------------------------------------
+
+ async def _publish(self, *, done: bool) -> None:
+ self._dirty = False
+ if self._bus is None:
+ return
+ text = self._text
+ if not done and text == self._published:
+ return
+ self._published = text
+ kwargs: dict[str, Any] = {
+ "source_layer": self._source_layer,
+ "text": text,
+ "thread_id": self._thread_id,
+ "channel": self._channel,
+ "done": done,
+ }
+ if self._trace_id is not None:
+ kwargs["trace_id"] = self._trace_id
+ try:
+ await self._bus.publish(AssistantTextDelta(**kwargs))
+ except Exception: # noqa: BLE001 — a live preview must never break the turn
+ log.debug("AssistantTextDelta publish failed", exc_info=True)
+
+ async def flush(self, *, done: bool = True) -> None:
+ """Publish what is pending now; ``done=True`` also closes the publisher."""
+ if self._handle is not None:
+ self._handle.cancel()
+ self._handle = None
+ if self._closed:
+ return
+ if done:
+ self._closed = True
+ # A turn that never produced a word has nothing to close on screen.
+ if not self._text and not self._published:
+ return
+ await self._publish(done=done)
+
+ def cancel(self) -> None:
+ """Drop pending text without a closing event (the turn was aborted)."""
+ if self._handle is not None:
+ self._handle.cancel()
+ self._handle = None
+ self._closed = True
+ self._dirty = False
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 042acc7e50..c0edd4882a 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -2690,6 +2690,10 @@ class RealtimeVoiceSession:
self._call_had_semantic_turn = False
self._failure_already_spoken = False
self._output_transcript: list[str] = []
+ # The reply as it grows, for the UI (AssistantTextDelta) — one
+ # coalescing publisher per turn, closed when the turn completes.
+ self._reply_delta: Any = None
+ self._reply_delta_turn: str | None = None
# BUG-089: text-level self-echo backstop. The realtime path's acoustic
# gates leak on open speakers next to a built-in mic (macOS), so every
# text this session makes audible is registered here and each final
@@ -5606,6 +5610,7 @@ class RealtimeVoiceSession:
self._gate.drain()
continue
self._output_transcript.append(display)
+ self._note_reply_delta()
if (
delegate_state is None
and self._external_update is None
@@ -7655,6 +7660,38 @@ class RealtimeVoiceSession:
except Exception: # noqa: BLE001, S110
pass
+ def _note_reply_delta(self) -> None:
+ """Hand the UI the reply as it grows (word by word, coalesced)."""
+ if self._bus is None:
+ return
+ try:
+ from jarvis.core.text_stream import TextDeltaPublisher
+
+ turn = str(self._turn_id or "")
+ if self._reply_delta is None or self._reply_delta_turn != turn:
+ self._reply_delta = TextDeltaPublisher(
+ self._bus,
+ channel="realtime",
+ thread_id=self.session_id,
+ trace_id=self._turn_trace_id,
+ source_layer=f"realtime.{self.active_provider}",
+ )
+ self._reply_delta_turn = turn
+ self._reply_delta.set_text("".join(self._output_transcript))
+ except Exception: # noqa: BLE001 — a live preview must never touch the turn
+ log.debug("realtime[%s] reply delta skipped", self.session_id, exc_info=True)
+
+ async def _close_reply_delta(self) -> None:
+ """Publish the last snapshot of the turn's reply with ``done=True``."""
+ publisher, self._reply_delta = self._reply_delta, None
+ self._reply_delta_turn = None
+ if publisher is None:
+ return
+ try:
+ await publisher.flush(done=True)
+ except Exception: # noqa: BLE001
+ log.debug("realtime[%s] reply delta close skipped", self.session_id, exc_info=True)
+
async def _publish_transcription(self, text: str, is_final: bool) -> None:
if self._bus is None:
return
@@ -9055,6 +9092,7 @@ class RealtimeVoiceSession:
self._last_user_text = self._last_user_text_preview
self._last_user_text_preview = ""
answer = "".join(self._output_transcript).strip()
+ await self._close_reply_delta()
delegate_state = self._delegate_turns.pop(self._turn_id, None)
external_update = self._external_update
if external_update is not None and delegate_state is not None:
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 769933bfc3..d7bd54df64 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -15136,6 +15136,21 @@ class SpeechPipeline:
lookahead = max(1, int(lookahead))
sentence_channels: asyncio.Queue = asyncio.Queue(maxsize=lookahead)
synth_tasks: list[asyncio.Task] = []
+ # The answer as it forms, for the screen: each scrubbed sentence is
+ # handed to the UI the moment the brain finishes it — seconds before
+ # its audio is synthesised and SpeechSpoken confirms it. Scrubbed
+ # text only, so a leaked tool call or raw repr never flashes on screen.
+ reply_delta = None
+ if self._bus is not None:
+ from jarvis.core.text_stream import TextDeltaPublisher
+
+ _tracker = getattr(self, "_latency_tracker", None)
+ reply_delta = TextDeltaPublisher(
+ self._bus,
+ channel="voice",
+ trace_id=getattr(_tracker, "trace_id", None),
+ source_layer="speech.pipeline",
+ )
async def _synth_into(channel: asyncio.Queue, sentence: str) -> None:
"""Synthesize one sentence, stream its chunks into ``channel``.
@@ -15251,6 +15266,8 @@ class SpeechPipeline:
lang, scrubbed.actions, sentence[:120],
)
return
+ if reply_delta is not None:
+ reply_delta.feed(cleaned if not reply_delta.text else f" {cleaned}")
await _speak_sentence(cleaned)
async def _produce() -> None:
@@ -15355,6 +15372,8 @@ class SpeechPipeline:
# in the finally guarantees playback of what was produced.
log.exception("Brain-Stream-Produktion fehlgeschlagen: %s", exc)
finally:
+ if reply_delta is not None:
+ await reply_delta.flush(done=True)
# End-of-turn sentinel — awaited so it lands even when the
# channel queue is at capacity (consumer keeps draining).
await sentence_channels.put(None)
diff --git a/jarvis/state/chat_store.py b/jarvis/state/chat_store.py
index 5e3136537b..8b887a76a5 100644
--- a/jarvis/state/chat_store.py
+++ b/jarvis/state/chat_store.py
@@ -22,6 +22,7 @@ appends and make message/thread order non-deterministic.
"""
from __future__ import annotations
+import json
import sqlite3
import threading
import uuid
@@ -43,6 +44,9 @@ class ChatMessage:
role: str # "user" | "assistant" | "system"
text: str
timestamp_ns: int
+ # The reasoning trace that produced an assistant reply (the event list
+ # ``jarvis.state.turn_trace`` records); None for every other message.
+ trace: dict[str, Any] | None = None
# Titles we treat as auto-derivable: the first user message replaces them.
@@ -71,6 +75,14 @@ CREATE INDEX IF NOT EXISTS idx_chat_messages_thread
ON chat_messages(thread_id);
"""
+# Columns added after the first release, applied by ``_migrate`` when missing.
+# ``trace_json`` (2026-08-23): the reasoning trace behind an assistant reply —
+# tool calls, worker dispatch, the brain's rationale — as the JSON event list
+# the UI replays into "Thought for 4s" + steps when a chat is reopened.
+_COLUMN_MIGRATIONS: tuple[tuple[str, str, str], ...] = (
+ ("chat_messages", "trace_json", "TEXT"),
+)
+
def default_chats_db_path(data_dir: str = "./data") -> Path:
"""Resolve ``chats.db`` to sit beside ``sessions.db``: inside ``data_dir``.
@@ -94,6 +106,39 @@ def _derive_title(text: str) -> str:
return single[: _TITLE_MAX_CHARS - 1].rstrip() + "…"
+def _migrate(conn: sqlite3.Connection) -> None:
+ """Add the columns a pre-existing ``chats.db`` lacks. Idempotent."""
+ for table, column, decl in _COLUMN_MIGRATIONS:
+ have = {row["name"] for row in conn.execute(f"PRAGMA table_info({table})")}
+ if column not in have:
+ conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {decl}")
+
+
+def _dump_trace(trace: dict[str, Any] | None) -> str | None:
+ # A trace without events has nothing to show — store nothing.
+ if not trace or not trace.get("events"):
+ return None
+ try:
+ return json.dumps(trace, ensure_ascii=False, default=str)
+ except (TypeError, ValueError):
+ import logging
+
+ logging.getLogger(__name__).warning(
+ "chat trace not serialisable — stored the message without it"
+ )
+ return None
+
+
+def _load_trace(raw: Any) -> dict[str, Any] | None:
+ if not raw or not isinstance(raw, str):
+ return None
+ try:
+ data = json.loads(raw)
+ except ValueError:
+ return None
+ return data if isinstance(data, dict) else None
+
+
class ChatStore:
"""sqlite3-backed thread/message store. Sync DB ops under a threading.Lock,
async public mutators (they also publish on the EventBus)."""
@@ -132,6 +177,7 @@ class ChatStore:
conn.execute("PRAGMA foreign_keys=ON")
conn.row_factory = sqlite3.Row
conn.executescript(_SCHEMA)
+ _migrate(conn)
self._conn = conn
return conn
@@ -212,7 +258,7 @@ class ChatStore:
if head is None:
return None
msgs = conn.execute(
- "SELECT message_id, thread_id, role, text, timestamp_ns "
+ "SELECT message_id, thread_id, role, text, timestamp_ns, trace_json "
"FROM chat_messages WHERE thread_id = ? ORDER BY rowid",
(thread_id,),
).fetchall()
@@ -229,6 +275,7 @@ class ChatStore:
"role": m["role"],
"text": m["text"],
"timestamp_ns": m["timestamp_ns"],
+ "trace": _load_trace(m["trace_json"]),
}
for m in msgs
],
@@ -287,7 +334,15 @@ class ChatStore:
role: str,
text: str,
publish_event: bool = True,
+ trace: dict[str, Any] | None = None,
) -> ChatMessage:
+ """Append a message; ``trace`` is the reasoning trace behind a reply.
+
+ The trace is stored as JSON next to the text and handed back by
+ :meth:`get_thread` so a reopened chat shows the steps again. It is
+ UI sugar, never history: a trace that fails to serialise is dropped
+ with a log line, the message itself always lands.
+ """
await self.ensure_thread(thread_id)
msg = ChatMessage(
message_id=str(uuid.uuid4()),
@@ -295,14 +350,16 @@ class ChatStore:
role=role,
text=text,
timestamp_ns=time_ns(),
+ trace=trace if trace and trace.get("events") else None,
)
+ trace_json = _dump_trace(trace)
conn = self._ensure_conn()
with self._lock:
conn.execute(
"INSERT INTO chat_messages "
- "(message_id, thread_id, role, text, timestamp_ns) "
- "VALUES (?, ?, ?, ?, ?)",
- (msg.message_id, thread_id, role, text, msg.timestamp_ns),
+ "(message_id, thread_id, role, text, timestamp_ns, trace_json) "
+ "VALUES (?, ?, ?, ?, ?, ?)",
+ (msg.message_id, thread_id, role, text, msg.timestamp_ns, trace_json),
)
conn.execute(
"UPDATE chat_threads SET updated_at_ns = ? WHERE thread_id = ?",
diff --git a/jarvis/state/turn_trace.py b/jarvis/state/turn_trace.py
new file mode 100644
index 0000000000..024438a4f4
--- /dev/null
+++ b/jarvis/state/turn_trace.py
@@ -0,0 +1,230 @@
+"""The reasoning trace of one turn, as a record that survives the turn.
+
+While a turn runs, the UI watches the bus and draws the steps live — the
+brain call, every tool the assistant reached for, the worker it delegated
+to, what it looked at on screen, the sentence it wrote next to each call
+(``ActionProposed.rationale``). Until now that picture lived only in the
+window that happened to be open: reopen the chat and the answer stood there
+with no sign of how it came about.
+
+This module keeps the same events the UI reads, in a bounded ring, so the
+reply path can attach the slice that belongs to its turn to the stored
+message (``ChatStore.add_message(trace=…)``). The stored shape is the EVENT
+LIST — ``{name, ts_ms, payload}`` — not pre-rendered steps: the frontend
+already owns the one mapping from events to human-readable rows
+(``lib/thinkingSteps.ts``), and a stored trace is replayed through exactly
+that mapping, so live and archived traces can never drift apart.
+
+Payloads are reduced to the handful of keys the mapping reads and every
+free-text value passes :func:`jarvis.core.redact.safe_preview` — a tool's
+arguments can carry anything the user typed, and the trace lands in a file.
+
+Read-only wildcard subscriber, never on the hot path (AP-9); every hook is
+wrapped so a malformed event can never reach the publisher (AP-18).
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+from collections import deque
+from collections.abc import Mapping
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any
+
+from jarvis.core.redact import safe_preview
+
+if TYPE_CHECKING:
+ from jarvis.core.bus import EventBus
+ from jarvis.core.events import Event
+
+log = logging.getLogger(__name__)
+
+#: The event kinds a trace is made of — the same set ``reduceThinkingSteps``
+#: in the frontend reads. Anything else never enters the ring.
+TRACE_EVENT_KINDS: frozenset[str] = frozenset(
+ {
+ "BrainTurnStarted",
+ "BrainTurnCompleted",
+ "ToolCallStarted",
+ "ToolCallCompleted",
+ "ActionProposed",
+ "ActionExecuted",
+ "ActionDenied",
+ "ObservationCaptured",
+ "ActionPlanned",
+ "CUStepProfiled",
+ "JarvisAgentTaskStarted",
+ "JarvisAgentTaskCompleted",
+ "AnnouncementRequested",
+ }
+)
+
+#: Per event kind, the payload keys worth keeping. Free text is previewed.
+_PAYLOAD_KEYS: dict[str, tuple[str, ...]] = {
+ "BrainTurnStarted": ("provider", "model", "intent_level"),
+ "BrainTurnCompleted": ("provider", "model", "finish_reason", "tokens_in", "tokens_out"),
+ "ToolCallStarted": ("tool_name", "args_preview"),
+ "ToolCallCompleted": ("success", "duration_ms", "output_preview", "error"),
+ "ActionProposed": ("tool_name", "args", "risk_tier", "rationale"),
+ "ActionExecuted": ("tool_name", "success", "duration_ms", "error", "output_preview"),
+ "ActionDenied": ("tool_name", "reason"),
+ "ObservationCaptured": ("window_title",),
+ "ActionPlanned": ("action_kind", "target_hint"),
+ "CUStepProfiled": ("phase", "step_idx"),
+ "JarvisAgentTaskStarted": ("utterance", "provider", "model"),
+ "JarvisAgentTaskCompleted": ("success", "duration_s"),
+ "AnnouncementRequested": ("kind", "text"),
+}
+
+#: Free-text caps: long enough to read, short enough for a row in a file.
+_TEXT_MAX = 240
+_ARG_MAX = 160
+_ARGS_MAX_KEYS = 8
+#: How many events the ring keeps. A turn rarely exceeds a few dozen; the
+#: ring spans the last several turns so a slow reply still finds its slice.
+DEFAULT_RING_SIZE = 600
+
+
+def _scalar(value: Any, *, max_chars: int) -> Any:
+ """Numbers and booleans stay typed; everything else is a redacted preview."""
+ if value is None or isinstance(value, bool | int | float):
+ return value
+ return safe_preview(value, max_chars=max_chars)
+
+
+def trace_payload_for(name: str, event: Any) -> dict[str, Any]:
+ """The stored payload of one event: whitelisted keys, redacted free text."""
+ out: dict[str, Any] = {}
+ for key in _PAYLOAD_KEYS.get(name, ()):
+ if isinstance(event, Mapping):
+ if key not in event:
+ continue
+ value = event[key]
+ else:
+ if not hasattr(event, key):
+ continue
+ value = getattr(event, key)
+ if key == "args":
+ if isinstance(value, Mapping):
+ args: dict[str, Any] = {}
+ for i, (k, v) in enumerate(value.items()):
+ if i >= _ARGS_MAX_KEYS:
+ break
+ args[str(k)] = _scalar(v, max_chars=_ARG_MAX)
+ out[key] = args
+ continue
+ out[key] = _scalar(value, max_chars=_TEXT_MAX)
+ return out
+
+
+@dataclass(frozen=True, slots=True)
+class TraceEvent:
+ ts_ms: int
+ name: str
+ trace_id: str
+ payload: dict[str, Any]
+
+ def as_dict(self) -> dict[str, Any]:
+ return {"name": self.name, "ts_ms": self.ts_ms, "payload": self.payload}
+
+
+class TurnTraceCollector:
+ """Bounded ring of trace events; ``slice`` hands a turn its own."""
+
+ def __init__(self, bus: EventBus | None = None, *, ring_size: int = DEFAULT_RING_SIZE) -> None:
+ self._ring: deque[TraceEvent] = deque(maxlen=max(1, ring_size))
+ self._lock = threading.Lock()
+ if bus is not None:
+ bus.subscribe_all(self._on_event)
+
+ async def _on_event(self, event: Event) -> None:
+ try:
+ name = type(event).__name__
+ if name not in TRACE_EVENT_KINDS:
+ return
+ self.record(name, event)
+ except Exception: # noqa: BLE001 — a trace must never reach the publisher (AP-18)
+ log.debug("turn trace: event dropped", exc_info=True)
+
+ def record(self, name: str, event: Any) -> None:
+ """Append one event (also the seam tests use, without a bus)."""
+ ts_ns = getattr(event, "timestamp_ns", None)
+ if not isinstance(ts_ns, int):
+ import time
+
+ ts_ns = time.time_ns()
+ item = TraceEvent(
+ ts_ms=ts_ns // 1_000_000,
+ name=name,
+ trace_id=str(getattr(event, "trace_id", "") or ""),
+ payload=trace_payload_for(name, event),
+ )
+ with self._lock:
+ self._ring.append(item)
+
+ def slice(self, since_ms: int, until_ms: int | None = None) -> list[dict[str, Any]]:
+ """Events with ``since_ms <= ts_ms <= until_ms``, oldest first."""
+ with self._lock:
+ items = list(self._ring)
+ out = []
+ for item in items:
+ if item.ts_ms < since_ms:
+ continue
+ if until_ms is not None and item.ts_ms > until_ms:
+ continue
+ out.append(item.as_dict())
+ return out
+
+ def snapshot(self, since_ms: int, until_ms: int | None = None) -> dict[str, Any] | None:
+ """The stored trace of a turn — ``None`` when nothing happened in it."""
+ events = self.slice(since_ms, until_ms)
+ if not events:
+ return None
+ ended = until_ms if until_ms is not None else events[-1]["ts_ms"]
+ return {"started_ms": since_ms, "ended_ms": ended, "events": events}
+
+
+def trace_from_events(
+ events: list[Any],
+ *,
+ since_ms: int,
+ until_ms: int | None = None,
+) -> dict[str, Any] | None:
+ """Build a stored trace from already-persisted event rows.
+
+ The voice session recorder keeps every event of a session in
+ ``voice_events`` (kind + payload); this turns the rows of one turn into
+ the same shape the collector produces, so a voice turn in the history
+ shows its steps exactly like a typed one. Rows are anything with
+ ``kind``/``ts_ms``/``payload`` attributes or keys.
+ """
+ out: list[dict[str, Any]] = []
+ for row in events:
+ kind = _field(row, "kind")
+ if kind not in TRACE_EVENT_KINDS:
+ continue
+ ts = _field(row, "ts_ms")
+ if not isinstance(ts, int | float):
+ continue
+ ts_ms = int(ts)
+ if ts_ms < since_ms or (until_ms is not None and ts_ms > until_ms):
+ continue
+ payload = _field(row, "payload")
+ out.append(
+ {
+ "name": kind,
+ "ts_ms": ts_ms,
+ "payload": trace_payload_for(kind, payload if isinstance(payload, Mapping) else {}),
+ }
+ )
+ if not out:
+ return None
+ ended = until_ms if until_ms is not None else out[-1]["ts_ms"]
+ return {"started_ms": since_ms, "ended_ms": ended, "events": out}
+
+
+def _field(row: Any, key: str) -> Any:
+ if isinstance(row, Mapping):
+ return row.get(key)
+ return getattr(row, key, None)
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 3128facc6a..78557f0690 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -1718,6 +1718,12 @@ class DesktopApp:
bus=server.bus, db_path=default_chats_db_path(self.cfg.memory.data_dir)
)
chat_store.open()
+ # The reasoning trace of a chat turn (tool calls, worker dispatch, the
+ # brain's rationale) is recorded off the bus and stored next to the
+ # reply, so a reopened chat shows "Thought for 4s" + steps again.
+ from jarvis.state.turn_trace import TurnTraceCollector
+
+ turn_traces = TurnTraceCollector(server.bus)
# Cap unbounded growth at startup (mirrors the session-store prune in
# sessions/init.py). 365d is deliberately generous — the user wants "all
# my chats"; voice sessions already prune at 30d and text is tiny — so
@@ -2035,6 +2041,9 @@ class DesktopApp:
return
thread_id = evt.thread_id or "default"
+ # The turn's trace window opens with the user's words; everything
+ # the bus sees from here until the reply lands is this turn's.
+ turn_started_ms = time.time_ns() // 1_000_000
# Persist the initiating turn before the reply. Older builds stored
# only the assistant half, producing anonymous "New Thread" rows
# that looked like text messages the user never sent.
@@ -2134,6 +2143,18 @@ class DesktopApp:
)
except Exception: # noqa: BLE001 — a missing ack must never block chat
logger.opt(exception=True).debug("chat instant ack not armed")
+ # Word-by-word preview of the reply for the chat column: the
+ # brain's text_consumer feeds a coalescing publisher, the UI
+ # shows the growing text and swaps in the final message.
+ from jarvis.core.text_stream import TextDeltaPublisher
+
+ delta_publisher = TextDeltaPublisher(
+ server.bus,
+ channel="chat",
+ thread_id=thread_id,
+ trace_id=evt.trace_id,
+ source_layer="ui.desktop.chat",
+ )
try:
await supervisor.set_state("THINKING")
generate = getattr(brain, "generate", None)
@@ -2161,6 +2182,7 @@ class DesktopApp:
"source_layer": evt.source_layer,
"conversation_id": thread_id,
"allow_voice_confirm": True,
+ "text_consumer": delta_publisher.feed,
}
reply = await _await_cancellable_chat_turn(
generate(
@@ -2177,6 +2199,7 @@ class DesktopApp:
detail = f"{type(exc).__name__}: {exc}"
message = f"Brain error: {detail}"
logger.opt(exception=exc).warning("BrainManager call failed")
+ delta_publisher.cancel()
if ack_task is not None and not ack_task.done():
ack_task.cancel()
await server.bus.publish(
@@ -2210,15 +2233,22 @@ class DesktopApp:
# The user pressed the bar's X mid-think — honour it and drop
# back to IDLE instead of speaking a half-finished turn.
logger.info("Chat turn aborted by the bar's X — back to IDLE.")
+ delta_publisher.cancel()
await supervisor.set_state("IDLE")
return
+ await delta_publisher.flush(done=True)
try:
await supervisor.set_state("SPEAKING")
if reply:
role = "system" if _is_brain_diagnostic(reply) else "assistant"
+ trace = (
+ turn_traces.snapshot(turn_started_ms)
+ if role == "assistant"
+ else None
+ )
await chat_store.add_message(
- thread_id=thread_id, role=role, text=reply
+ thread_id=thread_id, role=role, text=reply, trace=trace
)
finally:
await supervisor.set_state("IDLE")
diff --git a/jarvis/ui/web/chats_routes.py b/jarvis/ui/web/chats_routes.py
index d724d0c944..c075557288 100644
--- a/jarvis/ui/web/chats_routes.py
+++ b/jarvis/ui/web/chats_routes.py
@@ -37,6 +37,7 @@ from jarvis.state.conversation_constants import (
CONVERSATION_KIND_VOICE,
ConversationKind,
)
+from jarvis.state.turn_trace import trace_from_events
log = logging.getLogger(__name__)
@@ -74,6 +75,11 @@ class ChatTurn(BaseModel):
role: str
text: str
ts_ms: int = 0
+ # The reasoning trace behind an assistant reply — the event list
+ # ``jarvis.state.turn_trace`` stores (``{started_ms, ended_ms, events}``),
+ # replayed by the UI into the "Thought for Ns" steps. None for user and
+ # system lines and for replies recorded before traces were kept.
+ trace: dict[str, Any] | None = None
class ConversationDetail(BaseModel):
@@ -175,6 +181,7 @@ def _normalized_messages(
role=m["role"],
text=m["text"],
ts_ms=int(m["timestamp_ns"]) // 1_000_000,
+ trace=m.get("trace") if m["role"] == "assistant" else None,
)
for m in thread["messages"]
]
@@ -185,6 +192,7 @@ def _normalized_messages(
if session is None:
return None
turns = session_store.get_turns(cid)
+ events = _voice_events(session_store, cid)
out: list[ChatTurn] = []
for turn in turns:
if getattr(turn, "user_text", ""):
@@ -197,12 +205,49 @@ def _normalized_messages(
role="assistant",
text=turn.jarvis_text,
ts_ms=int(turn.ended_ms or turn.started_ms),
+ trace=_voice_turn_trace(turn, events),
)
)
return out
return None
+def _voice_events(session_store: Any, session_id: str) -> list[Any]:
+ """Every recorded event of a voice session; [] when the store cannot say."""
+ getter = getattr(session_store, "get_events", None)
+ if not callable(getter):
+ return []
+ try:
+ return list(getter(session_id) or [])
+ except Exception as exc: # noqa: BLE001 — a trace is sugar, the transcript must load
+ log.debug("voice events unavailable for %s: %s", session_id, exc)
+ return []
+
+
+def _voice_turn_trace(turn: Any, events: list[Any]) -> dict[str, Any] | None:
+ """The reasoning trace of one voice turn, from the session recorder's rows.
+
+ Rows carry the turn they belong to; the ones that do not (a tool event
+ published before the recorder opened the turn) fall back to the turn's
+ time window. Either way the result is the same shape a typed turn stores,
+ so the history shows both alike.
+ """
+ turn_id = str(getattr(turn, "id", "") or "")
+ started = int(getattr(turn, "started_ms", 0) or 0)
+ ended = getattr(turn, "ended_ms", None)
+ until = int(ended) if ended else None
+ own = [e for e in events if turn_id and getattr(e, "turn_id", None) == turn_id]
+ if own:
+ # Keep the window generous around the recorder's turn bounds: a trace
+ # row tagged with this turn belongs to it wherever its clock says.
+ lo = min(started, min(int(getattr(e, "ts_ms", started)) for e in own))
+ hi = max(int(getattr(e, "ts_ms", lo)) for e in own)
+ return trace_from_events(own, since_ms=lo, until_ms=max(hi, until or hi))
+ if not started:
+ return None
+ return trace_from_events(events, since_ms=started, until_ms=until)
+
+
def _seed_pairs(messages: list[ChatTurn]) -> list[tuple[str, str]]:
"""Trailing seedable (role, text) pairs for BrainManager.seed_history."""
pairs = [
diff --git a/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx b/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx
index 31d770fe14..f9aec8b3b7 100644
--- a/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx
+++ b/jarvis/ui/web/frontend/src/components/ThinkingTrace.tsx
@@ -37,6 +37,7 @@ const VISIBLE_STEPS = 5;
const KIND_ICON: Record<ThinkingStepKind, typeof Wrench> = {
brain: Brain,
+ thought: Brain,
tool: Wrench,
computer: MonitorDot,
worker: Bot,
diff --git a/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsx b/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsx
index 5423a7abf8..3bbdb3c81f 100644
--- a/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/TurnSteps.test.tsx
@@ -60,25 +60,93 @@ describe("TurnSteps", () => {
expect(screen.getAllByTestId("turn-step")).toHaveLength(2);
});
- it("renders tool rows with the brand tile, the humanised label and the raw tool name", () => {
+ it("renders tool rows with the brand tile or the feature's icon and a readable line", () => {
render(<TurnSteps steps={FINISHED} durationMs={10_400} />);
const [gmail, shell] = screen.getAllByTestId("turn-step");
+ // A service tool: the brand logo and the brand's own label.
const gmailTile = within(gmail).getByTestId("turn-step-brand");
expect(gmailTile.getAttribute("data-brand-tier")).toBe("logo");
expect(gmailTile.querySelector("img")?.getAttribute("src")).toMatch(/svg/);
expect(gmail.textContent).toContain("Gmail · search");
- expect(gmail.textContent).toContain("gmail_search");
expect(gmail.textContent).toContain("0.8s");
+ expect(gmail.getAttribute("data-family")).toBe("service");
+ // A Jarvis tool: the family's icon (never a monogram) and the verb line.
const shellTile = within(shell).getByTestId("turn-step-brand");
- expect(shellTile.getAttribute("data-brand-tier")).toBe("monogram");
- expect(shellTile.textContent).toBe("RS");
+ expect(shellTile.getAttribute("data-brand-tier")).toBe("icon");
+ expect(shellTile.querySelector("svg")).not.toBeNull();
+ expect(shell.getAttribute("data-family")).toBe("shell");
expect(shell.getAttribute("data-status")).toBe("error");
// The key may or may not be in the locale yet; both forms contain "failed".
expect(shell.textContent).toMatch(/failed/i);
});
+ it("shows the model's own sentence as a muted thought row above the tool", () => {
+ const steps: ThinkingStep[] = [
+ step({
+ id: "th",
+ kind: "thought",
+ labelKey: "thinking.step_thought",
+ detail: "I'll check the wiki for that.",
+ durationMs: 0,
+ }),
+ step({ id: "w", kind: "tool", detail: "wiki-recall", args: { query: "Urlaub" }, durationMs: 400 }),
+ ];
+ render(<TurnSteps steps={steps} durationMs={2_000} defaultOpen />);
+ const rows = screen.getAllByTestId("turn-step");
+ expect(rows[0].getAttribute("data-kind")).toBe("thought");
+ expect(rows[0].textContent).toContain("I'll check the wiki for that.");
+ // The wiki row: family icon + the call's detail.
+ expect(rows[1].getAttribute("data-family")).toBe("wiki");
+ expect(rows[1].textContent).toContain("Urlaub");
+ // Folded, only tool rows stay — the thought goes with the header.
+ fireEvent.click(screen.getByTestId("turn-steps-toggle"));
+ expect(screen.getAllByTestId("turn-step")).toHaveLength(1);
+ });
+
+ it("unfolds a finished tool row into its arguments, result and error", () => {
+ const steps: ThinkingStep[] = [
+ step({
+ id: "s",
+ kind: "tool",
+ detail: "search_web",
+ args: { query: "weather Berlin", limit: 3 },
+ result: "3 results",
+ durationMs: 900,
+ }),
+ step({
+ id: "f",
+ kind: "tool",
+ detail: "open_app",
+ status: "error",
+ args: { app: "Spotify" },
+ error: "not installed",
+ durationMs: 50,
+ }),
+ ];
+ render(<TurnSteps steps={steps} durationMs={3_000} />);
+ const [search, app] = screen.getAllByTestId("turn-step");
+ expect(screen.queryByTestId("turn-step-details")).toBeNull();
+
+ fireEvent.click(within(search).getByTestId("turn-step-toggle"));
+ const details = within(search).getByTestId("turn-step-details");
+ expect(details.textContent).toContain("query");
+ expect(details.textContent).toContain("weather Berlin");
+ expect(details.textContent).toContain("3");
+ expect(details.textContent).toContain("3 results");
+
+ fireEvent.click(within(app).getByTestId("turn-step-toggle"));
+ expect(within(app).getByTestId("turn-step-details").textContent).toContain("not installed");
+ });
+
+ it("names the model in the unfolded header of a finished turn", () => {
+ render(<TurnSteps steps={FINISHED} durationMs={4_000} model="openai · gpt-5" />);
+ expect(screen.queryByTestId("turn-steps-model")).toBeNull();
+ fireEvent.click(screen.getByTestId("turn-steps-toggle"));
+ expect(screen.getByTestId("turn-steps-model").textContent).toContain("openai · gpt-5");
+ });
+
it("is open in live mode and spins on the active row", () => {
const live: ThinkingStep[] = [
step({ id: "a", kind: "brain", durationMs: 900 }),
diff --git a/jarvis/ui/web/frontend/src/components/home/TurnSteps.tsx b/jarvis/ui/web/frontend/src/components/home/TurnSteps.tsx
index 5112d642d6..de3ce59ebb 100644
--- a/jarvis/ui/web/frontend/src/components/home/TurnSteps.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/TurnSteps.tsx
@@ -1,36 +1,66 @@
/**
* The reasoning steps of one turn, the way the Claude desktop app shows
* them: a muted "Thought for 10s" line that folds and unfolds the list, rows
- * hung on a thin vertical connector, and tool calls as rows carrying the
- * service's brand mark in a small tile. Not the model's thinking text — the
- * maintainer asked for the steps and the tool calls, nothing more.
+ * hung on a thin vertical connector, and every step as a line a person can
+ * read — "Looking in Wiki · Urlaub", "Creating artifact · Sales deck",
+ * "Running skill · daily-brief" — with the feature's own mark in front of
+ * it, or the service's brand logo for Gmail, Spotify, an MCP server…
+ *
+ * Row kinds:
+ * thought — the sentence the model wrote next to a tool call (its own
+ * words for why it reaches for the tool); muted, italic.
+ * tool — the call: verb + detail, a spinner while it runs, the time
+ * it took, red with "failed" when it did. Click a finished row
+ * to unfold what went in (arguments) and what came back.
+ * brain / computer / worker / note — the rest of the turn.
*
* Two modes share one renderer:
* live — the turn is still running; the list is open, the active row
* spins, the header counts the seconds.
* finished — folded to the header by default, BUT the tool rows stay
* visible under it: what the assistant reached for is the part
- * worth seeing without a click. Unfolding shows every row.
+ * worth seeing without a click. Unfolding shows every row and,
+ * when the turn said, which model answered.
*
* Presentational only: steps come in as props (the store keeps the live
* list and the per-message snapshots), time comes in as `durationMs` — the
- * caller ticks. That keeps this usable from the chat column and the voice
- * lane alike, and testable without a store.
+ * caller ticks. That keeps this usable from the chat column, the voice lane
+ * and the history alike, and testable without a store.
*/
import { useId, useState } from "react";
import {
+ AppWindow,
+ BookMarked,
+ BookOpen,
+ Bookmark,
Bot,
Brain,
ChevronRight,
CircleAlert,
Clock,
+ Compass,
+ Contact,
+ Cpu,
+ FilePlus2,
+ Globe,
Info,
MonitorDot,
+ MousePointerClick,
+ Phone,
+ Plug,
+ Puzzle,
+ ScanEye,
+ Settings2,
+ ShieldCheck,
+ Sparkles,
+ Terminal,
+ UserRound,
+ Wand2,
type LucideIcon,
} from "lucide-react";
import type { ThinkingStep, ThinkingStepKind } from "@/lib/thinkingSteps";
-import { resolveToolBrand } from "@/lib/toolBrand";
+import { describeToolStep, type ToolFamily } from "@/lib/toolStepLabel";
import { fill, useT } from "@/i18n";
import { cn } from "@/lib/utils";
@@ -40,6 +70,8 @@ export interface TurnStepsProps {
live?: boolean;
/** Total thinking time (finished: of the turn; live: elapsed so far), for the header. */
durationMs?: number;
+ /** "provider · model" that answered, shown in the unfolded header of a finished turn. */
+ model?: string;
/** Tighter rows (the voice lane). */
compact?: boolean;
/** Finished traces start folded; live ones start open. */
@@ -62,13 +94,41 @@ function formatStepDuration(ms: number): string {
return formatThoughtDuration(ms);
}
-const KIND_ICON: Record<Exclude<ThinkingStepKind, "tool">, LucideIcon> = {
+const KIND_ICON: Record<Exclude<ThinkingStepKind, "tool" | "thought">, LucideIcon> = {
brain: Brain,
computer: MonitorDot,
worker: Bot,
note: Info,
};
+/** The feature's own mark for a tool row that has no brand logo. */
+const FAMILY_ICON: Record<ToolFamily, LucideIcon> = {
+ wiki: BookOpen,
+ wiki_write: BookMarked,
+ artifact: FilePlus2,
+ skill: Wand2,
+ skill_create: Sparkles,
+ web: Globe,
+ screen: ScanEye,
+ screen_recall: ScanEye,
+ control: MousePointerClick,
+ navigate: Compass,
+ app: AppWindow,
+ memory: Bookmark,
+ profile: UserRound,
+ contact: Contact,
+ call: Phone,
+ worker: Bot,
+ shell: Terminal,
+ model: Cpu,
+ mcp_admin: Plug,
+ settings: Settings2,
+ verify: ShieldCheck,
+ mcp: Plug,
+ service: Puzzle,
+ other: Puzzle,
+};
+
/**
* The small spinner shown on an active row. A plain ring instead of an
* animated SVG so it stays crisp at 14px; under reduced motion it stands
@@ -87,53 +147,61 @@ function Spinner({ className }: { className?: string }) {
);
}
-/** The tile at the left of a tool row: the brand SVG, or a two-letter monogram. */
-function BrandTile({
+/** The gutter box every mark sits in: opaque, so it masks the connector line. */
+function markBox(compact: boolean): string {
+ return cn(
+ "relative z-10 grid shrink-0 place-items-center bg-background",
+ compact ? "h-[18px] w-[18px]" : "h-5 w-5",
+ );
+}
+
+/** The tile at the left of a tool row: the brand SVG, or the family's icon. */
+function ToolMark({
logoUrl,
- monogram,
+ Icon,
label,
+ active,
+ error,
compact,
}: {
logoUrl?: string;
- monogram: string;
+ Icon: LucideIcon;
label: string;
+ active: boolean;
+ error: boolean;
compact: boolean;
}) {
const [failed, setFailed] = useState(false);
const showLogo = Boolean(logoUrl) && !failed;
- return (
- <span
- data-testid="turn-step-brand"
- data-brand-tier={showLogo ? "logo" : "monogram"}
- title={label}
- className={cn(
- // Opaque page background first, so the tile masks the connector line
- // behind it; the tint is a translucent plate on top of that.
- "relative z-10 grid shrink-0 place-items-center overflow-hidden rounded-md bg-background",
- compact ? "h-[18px] w-[18px]" : "h-5 w-5",
- )}
- >
+ const size = compact ? "h-3 w-3" : "h-3.5 w-3.5";
+ if (showLogo) {
+ return (
<span
- aria-hidden
- className={cn(
- "absolute inset-0 rounded-md border",
- // A full-colour mark sits on a light plate (its own colours carry the
- // brand); the monogram sits on the page's own secondary surface.
- showLogo ? "border-sheen/10 bg-sheen/[0.07]" : "border-border/70 bg-secondary",
- )}
- />
- {showLogo ? (
+ data-testid="turn-step-brand"
+ data-brand-tier="logo"
+ title={label}
+ className={cn(markBox(compact), "overflow-hidden rounded-md")}
+ >
+ <span aria-hidden className="absolute inset-0 rounded-md border border-sheen/10 bg-sheen/[0.07]" />
<img
src={logoUrl}
alt=""
- className={cn("relative", compact ? "h-3 w-3" : "h-3.5 w-3.5")}
+ className={cn("relative", size)}
loading="lazy"
onError={() => setFailed(true)}
/>
+ </span>
+ );
+ }
+ return (
+ <span data-testid="turn-step-brand" data-brand-tier="icon" title={label} className={markBox(compact)}>
+ {active ? (
+ <Spinner className={size} />
) : (
- <span className="relative font-mono text-[8px] font-semibold leading-none text-muted-foreground">
- {monogram}
- </span>
+ <Icon
+ aria-hidden
+ className={cn(size, error ? "text-destructive" : "text-muted-foreground/80")}
+ />
)}
</span>
);
@@ -142,10 +210,7 @@ function BrandTile({
/** The gutter mark of a non-tool row: spinner while active, the kind's icon otherwise. */
function KindMark({ step, compact }: { step: ThinkingStep; compact: boolean }) {
const size = compact ? "h-3 w-3" : "h-3.5 w-3.5";
- const box = cn(
- "relative z-10 grid shrink-0 place-items-center bg-background",
- compact ? "h-[18px] w-[18px]" : "h-5 w-5",
- );
+ const box = markBox(compact);
if (step.status === "active") {
return (
<span className={box}>
@@ -160,7 +225,7 @@ function KindMark({ step, compact }: { step: ThinkingStep; compact: boolean }) {
</span>
);
}
- const Icon = KIND_ICON[step.kind as Exclude<ThinkingStepKind, "tool">] ?? Info;
+ const Icon = KIND_ICON[step.kind as Exclude<ThinkingStepKind, "tool" | "thought">] ?? Info;
return (
<span className={box}>
<Icon aria-hidden className={cn(size, "text-muted-foreground/70")} />
@@ -168,12 +233,181 @@ function KindMark({ step, compact }: { step: ThinkingStep; compact: boolean }) {
);
}
+/** A muted, italic line in the model's own words — no mark, a quiet dot in the gutter. */
+function ThoughtRow({ step, compact }: { step: ThinkingStep; compact: boolean }) {
+ return (
+ <li
+ data-testid="turn-step"
+ data-kind="thought"
+ data-status={step.status}
+ className={cn("relative flex min-w-0 items-start", compact ? "gap-2 py-[3px]" : "gap-2.5 py-1")}
+ >
+ <span className={markBox(compact)}>
+ <span aria-hidden className="h-1 w-1 rounded-full bg-muted-foreground/50" />
+ </span>
+ <span
+ className={cn(
+ "min-w-0 flex-1 italic leading-5 text-muted-foreground/85",
+ compact ? "text-xs" : "text-[13px]",
+ )}
+ >
+ {step.detail}
+ </span>
+ </li>
+ );
+}
+
+/** Arguments / result / error of a finished tool call, shown when a row is unfolded. */
+function ToolDetails({ step, compact }: { step: ThinkingStep; compact: boolean }) {
+ const t = useT();
+ const args = step.args ? Object.entries(step.args) : [];
+ return (
+ <div
+ data-testid="turn-step-details"
+ className={cn(
+ "mb-1 ml-[30px] mr-1 flex flex-col gap-1 rounded-md border border-border/70 bg-secondary/40 px-2.5 py-2",
+ compact ? "text-[11px]" : "text-xs",
+ )}
+ >
+ {args.length > 0 && (
+ <dl className="grid grid-cols-[max-content_1fr] gap-x-3 gap-y-0.5">
+ {args.map(([k, v]) => (
+ <div key={k} className="contents">
+ <dt className="font-mono text-muted-foreground/70">{k}</dt>
+ <dd className="min-w-0 break-words text-foreground/85">{formatArg(v)}</dd>
+ </div>
+ ))}
+ </dl>
+ )}
+ {step.result && (
+ <div className="flex min-w-0 gap-2">
+ <span className="shrink-0 text-muted-foreground/70">{t("turn_steps.result")}</span>
+ <span className="min-w-0 break-words text-foreground/85">{step.result}</span>
+ </div>
+ )}
+ {step.error && (
+ <div className="flex min-w-0 gap-2">
+ <span className="shrink-0 text-destructive/80">{t("turn_steps.error")}</span>
+ <span className="min-w-0 break-words text-destructive">{step.error}</span>
+ </div>
+ )}
+ {args.length === 0 && !step.result && !step.error && (
+ <span className="text-muted-foreground/70">{t("turn_steps.no_details")}</span>
+ )}
+ </div>
+ );
+}
+
+function formatArg(v: unknown): string {
+ if (typeof v === "string") return v;
+ if (v === null || v === undefined) return "—";
+ if (typeof v === "number" || typeof v === "boolean") return String(v);
+ try {
+ return JSON.stringify(v);
+ } catch {
+ return String(v);
+ }
+}
+
+function ToolRow({ step, compact }: { step: ThinkingStep; compact: boolean }) {
+ const t = useT();
+ const [open, setOpen] = useState(false);
+ const active = step.status === "active";
+ const error = step.status === "error";
+ const view = describeToolStep(step.detail ?? "", step.args);
+ const line = view.labelKey ? t(view.labelKey) : view.label;
+ const hasDetails = !active && (Boolean(step.args) || Boolean(step.result) || Boolean(step.error));
+ const Icon = FAMILY_ICON[view.family];
+ const detailsId = useId();
+
+ const body = (
+ <>
+ <ToolMark
+ logoUrl={view.brand?.logoUrl}
+ Icon={Icon}
+ label={line}
+ active={active}
+ error={error}
+ compact={compact}
+ />
+ <span
+ className={cn(
+ "min-w-0 flex-1 truncate leading-5",
+ compact ? "text-xs" : "text-[13px]",
+ error ? "text-destructive" : "text-foreground/85",
+ active && "thinking-shimmer font-medium",
+ )}
+ >
+ {line}
+ {view.detail && (
+ <span className={cn("ml-1.5 font-normal text-muted-foreground/80")}>· {view.detail}</span>
+ )}
+ </span>
+ {active && <Spinner className={compact ? "h-3 w-3" : "h-3.5 w-3.5"} />}
+ {error && (
+ <span className="shrink-0 text-[10px] uppercase tracking-[0.08em] text-destructive/80">
+ {t("turn_steps.failed")}
+ </span>
+ )}
+ {!active && step.durationMs !== undefined && step.durationMs > 0 && (
+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground/60">
+ {formatStepDuration(step.durationMs)}
+ </span>
+ )}
+ {hasDetails && (
+ <ChevronRight
+ aria-hidden
+ className={cn(
+ "h-3 w-3 shrink-0 opacity-0 transition-transform duration-200 group-hover/row:opacity-60 motion-reduce:transition-none",
+ open && "rotate-90 opacity-60",
+ )}
+ />
+ )}
+ </>
+ );
+
+ return (
+ <li
+ data-testid="turn-step"
+ data-kind="tool"
+ data-family={view.family}
+ data-status={step.status}
+ className="relative flex min-w-0 flex-col"
+ >
+ {hasDetails ? (
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ aria-controls={detailsId}
+ data-testid="turn-step-toggle"
+ className={cn(
+ "group/row -mx-1 flex min-w-0 items-center rounded-md px-1 text-left hover:bg-secondary/50",
+ compact ? "gap-2 py-[3px]" : "gap-2.5 py-1",
+ )}
+ >
+ {body}
+ </button>
+ ) : (
+ <div className={cn("flex min-w-0 items-center", compact ? "gap-2 py-[3px]" : "gap-2.5 py-1")}>
+ {body}
+ </div>
+ )}
+ {hasDetails && open && (
+ <div id={detailsId}>
+ <ToolDetails step={step} compact={compact} />
+ </div>
+ )}
+ </li>
+ );
+}
+
function StepRow({ step, compact }: { step: ThinkingStep; compact: boolean }) {
const t = useT();
- const isTool = step.kind === "tool";
+ if (step.kind === "tool") return <ToolRow step={step} compact={compact} />;
+ if (step.kind === "thought") return <ThoughtRow step={step} compact={compact} />;
const active = step.status === "active";
const error = step.status === "error";
- const brand = isTool ? resolveToolBrand(step.detail ?? "") : null;
return (
<li
@@ -185,45 +419,23 @@ function StepRow({ step, compact }: { step: ThinkingStep; compact: boolean }) {
compact ? "gap-2 py-[3px]" : "gap-2.5 py-1",
)}
>
- {isTool && brand ? (
- <BrandTile
- logoUrl={brand.logoUrl}
- monogram={brand.monogram}
- label={brand.label}
- compact={compact}
- />
- ) : (
- <KindMark step={step} compact={compact} />
- )}
-
+ <KindMark step={step} compact={compact} />
<span
className={cn(
"min-w-0 flex-1 truncate leading-5",
compact ? "text-xs" : "text-[13px]",
- error ? "text-destructive" : isTool ? "text-foreground/85" : "text-muted-foreground",
- active && !isTool && "thinking-shimmer font-medium",
+ error ? "text-destructive" : "text-muted-foreground",
+ active && "thinking-shimmer font-medium",
)}
>
- {isTool && brand ? (
- <>
- {brand.label}
- {step.detail && (
- <span className="ml-2 font-mono text-[10px] text-muted-foreground/70">
- {step.detail}
- </span>
- )}
- </>
- ) : (
- <>
- {t(step.labelKey)}
- {step.detail && (
- <span className="ml-1.5 font-normal text-muted-foreground/80">{step.detail}</span>
- )}
- </>
+ {t(step.labelKey)}
+ {step.detail && (
+ <span className="ml-1.5 font-normal text-muted-foreground/80">{step.detail}</span>
+ )}
+ {error && step.error && (
+ <span className="ml-1.5 font-normal text-destructive/80">{step.error}</span>
)}
</span>
-
- {isTool && active && <Spinner className={compact ? "h-3 w-3" : "h-3.5 w-3.5"} />}
{error && (
<span className="shrink-0 text-[10px] uppercase tracking-[0.08em] text-destructive/80">
{t("turn_steps.failed")}
@@ -261,6 +473,7 @@ export function TurnSteps({
steps,
live = false,
durationMs,
+ model,
compact = false,
defaultOpen,
className,
@@ -279,6 +492,7 @@ export function TurnSteps({
? t("thinking.label")
: thoughtFor(t("turn_steps.thought_for"), formatThoughtDuration(durationMs ?? 0));
const elapsed = live && durationMs !== undefined ? formatThoughtDuration(durationMs) : null;
+ const modelLine = !live && open && model ? model : null;
return (
<div
@@ -311,6 +525,14 @@ export function TurnSteps({
{elapsed}
</span>
)}
+ {modelLine && (
+ <span
+ data-testid="turn-steps-model"
+ className="truncate font-mono text-[10px] text-muted-foreground/60"
+ >
+ · {modelLine}
+ </span>
+ )}
<ChevronRight
aria-hidden
className={cn(
diff --git a/jarvis/ui/web/frontend/src/components/home/VoiceStage.tsx b/jarvis/ui/web/frontend/src/components/home/VoiceStage.tsx
index 6ff8b73247..aaa7ac6d20 100644
--- a/jarvis/ui/web/frontend/src/components/home/VoiceStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/VoiceStage.tsx
@@ -12,6 +12,7 @@ import { cn } from "@/lib/utils";
import { Greeting } from "@/components/home/Greeting";
import { JarvisBar } from "@/components/home/JarvisBar";
import { TurnSteps, traceWorthShowing } from "@/components/home/TurnSteps";
+import { traceModel } from "@/lib/thinkingSteps";
/** How many finished lines the lane keeps above the bar. */
const TRANSCRIPT_LINES = 8;
@@ -39,6 +40,7 @@ export function VoiceStage() {
const assistantName = useEventStore((s) => s.assistantName);
const voiceState = useEventStore((s) => s.voiceState);
const transcript = useHomeStore((s) => s.transcript);
+ const liveReply = useHomeStore((s) => s.liveReply);
const transcription = useEventStore((s) => s.transcription);
const transcriptionFinal = useEventStore((s) => s.transcriptionFinal);
const { connected, warming } = useVoiceReadiness();
@@ -60,13 +62,21 @@ export function VoiceStage() {
[transcript],
);
const liveLine = transcription && !transcriptionFinal ? transcription : "";
+ // The answer as it is produced, until its spoken line replaces it. Hidden
+ // once the lane's last line already IS the answer (the final arrived and
+ // a late snapshot would only repeat it).
+ const lastLine = lines[lines.length - 1];
+ const liveAnswer =
+ liveReply && !(lastLine?.who === "assistant" && lastLine.text.startsWith(liveReply))
+ ? liveReply
+ : "";
// A live turn keeps the lane pinned to its end as steps arrive.
const liveSteps = lines.some((m) => m.who === "steps" && m.live);
const laneEnd = useRef<HTMLDivElement | null>(null);
useEffect(() => {
laneEnd.current?.scrollIntoView({ block: "end" });
- }, [lines, liveLine, liveSteps]);
+ }, [lines, liveLine, liveAnswer, liveSteps]);
const phase = waveformPhase(voiceState, connected);
const hint = hintFor({ connected, warming, connecting, voiceState, wakePhrase, t });
@@ -88,6 +98,7 @@ export function VoiceStage() {
steps={m.steps}
live={m.live}
durationMs={m.durationMs}
+ model={traceModel(m.steps)}
compact
defaultOpen={m.live}
/>
@@ -104,6 +115,9 @@ export function VoiceStage() {
{liveLine && (
<TranscriptLine who={t("home.transcript_you")} text={liveLine} user live />
)}
+ {liveAnswer && (
+ <TranscriptLine who={assistantName} text={liveAnswer} user={false} live />
+ )}
<div ref={laneEnd} />
</div>
@@ -113,6 +127,11 @@ export function VoiceStage() {
);
}
+/**
+ * One line of the lane. A LIVE line (words still being said, an answer still
+ * being produced) is muted and italic with a cursor; the finished line it
+ * becomes is in full colour — the same words, settled.
+ */
function TranscriptLine({
who,
text,
@@ -127,7 +146,8 @@ function TranscriptLine({
return (
<div
className="grid grid-cols-[64px_1fr] items-baseline gap-x-4"
- data-testid={live ? "transcript-live" : "transcript-line"}
+ data-testid={live ? (user ? "transcript-live" : "transcript-live-answer") : "transcript-line"}
+ data-who={user ? "user" : "assistant"}
>
<span className="truncate text-right font-mono text-[10px] uppercase tracking-[0.12em] text-muted-foreground">
{who}
@@ -135,7 +155,12 @@ function TranscriptLine({
<span
className={cn(
"whitespace-pre-wrap",
- user ? "text-[15px] text-muted-foreground" : "font-display text-[17px] leading-snug text-foreground",
+ user
+ ? cn("text-[15px]", live ? "text-muted-foreground/70" : "text-muted-foreground")
+ : cn(
+ "font-display text-[17px] leading-snug",
+ live ? "text-muted-foreground" : "text-foreground",
+ ),
live && "italic",
)}
>
diff --git a/jarvis/ui/web/frontend/src/hooks/useConversations.ts b/jarvis/ui/web/frontend/src/hooks/useConversations.ts
index ec10470cb3..5d5ce24714 100644
--- a/jarvis/ui/web/frontend/src/hooks/useConversations.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useConversations.ts
@@ -4,6 +4,7 @@ import { useEventStore, type ChatMessage, type ConversationKind } from "@/store/
import {
deleteTextConversation,
detailToMessages,
+ detailToTraces,
fetchConversations,
resumeConversation,
} from "@/lib/chatsApi";
@@ -29,6 +30,7 @@ export function useConversations({ poll = false }: { poll?: boolean } = {}) {
const setConversations = useEventStore((s) => s.setConversations);
const setActiveConversation = useEventStore((s) => s.setActiveConversation);
const setMessages = useEventStore((s) => s.setMessages);
+ const seedThinkingTraces = useEventStore((s) => s.seedThinkingTraces);
const refresh = useCallback(async () => {
try {
@@ -55,21 +57,28 @@ export function useConversations({ poll = false }: { poll?: boolean } = {}) {
async (kind: ConversationKind, id: string): Promise<ChatMessage[]> => {
setActiveConversation(kind, id);
let messages: ChatMessage[] = [];
+ let traces = {};
try {
- messages = detailToMessages(await resumeConversation(kind, id));
+ const detail = await resumeConversation(kind, id);
+ messages = detailToMessages(detail);
+ traces = detailToTraces(detail);
} catch {
/* unreachable / gone — an empty thread is the honest view */
}
+ // The stored traces replace the previous conversation's, so a reply
+ // in the new thread never wears the steps of an old one.
+ seedThinkingTraces(traces);
setMessages(messages);
return messages;
},
- [setActiveConversation, setMessages],
+ [seedThinkingTraces, setActiveConversation, setMessages],
);
const newChat = useCallback(() => {
setActiveConversation("text", null);
+ seedThinkingTraces({});
setMessages([]);
- }, [setActiveConversation, setMessages]);
+ }, [seedThinkingTraces, setActiveConversation, setMessages]);
const removeConversation = useCallback(
async (id: string) => {
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
index 12f35fba00..86ef1220cd 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
@@ -312,6 +312,27 @@ export function useWebSocket(): void {
}
}
+ // The typed chat's reply as it is written: cumulative snapshots
+ // from the chat bridge, shown muted under the live steps until the
+ // final MessageSent replaces them. Voice channels feed the home
+ // store's lane through `ingest` above.
+ if (env.event_name === "AssistantTextDelta") {
+ const p = env.payload as {
+ text?: string;
+ thread_id?: string;
+ channel?: string;
+ done?: boolean;
+ };
+ if (p.channel === "chat" && typeof p.text === "string") {
+ useEventStore.getState().setLiveReply({
+ text: p.text,
+ threadId: p.thread_id ?? "",
+ done: Boolean(p.done),
+ ts: Math.floor(env.timestamp_ns / 1_000_000),
+ });
+ }
+ }
+
if (env.event_name === "DictationTranscript") {
// In-app dictation. Interim partials overwrite the live tail; the
// final one is delivered. Separate from TranscriptionUpdate so
diff --git a/jarvis/ui/web/frontend/src/lib/chatsApi.ts b/jarvis/ui/web/frontend/src/lib/chatsApi.ts
index 846776188e..393c87e206 100644
--- a/jarvis/ui/web/frontend/src/lib/chatsApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/chatsApi.ts
@@ -1,12 +1,19 @@
// Thin client for the Chats conversation-manager REST API
// (jarvis/ui/web/chats_routes.py).
import type { ChatMessage, ConversationKind, ConversationSummary } from "@/store/events";
+import {
+ replayTrace,
+ type StoredTrace,
+ type ThinkingTraceSnapshot,
+} from "@/lib/thinkingSteps";
import type { MessageRole } from "@/types/messages";
export interface ChatTurn {
role: string;
text: string;
ts_ms: number;
+ /** The stored reasoning trace behind an assistant reply, when one was kept. */
+ trace?: StoredTrace | null;
}
export interface ConversationDetail {
@@ -59,14 +66,41 @@ export async function deleteTextConversation(id: string): Promise<void> {
if (!res.ok) throw new ChatsApiError("delete-failed", res.status);
}
+/** The stable id of the i-th message of a loaded conversation. */
+function historyMessageId(detail: ConversationDetail, index: number): string {
+ return `hist-${detail.kind}-${detail.id}-${index}`;
+}
+
/** Map a normalized transcript into store ChatMessages with stable ids
* (so the live pushMessage dedup never collides with a loaded transcript). */
export function detailToMessages(detail: ConversationDetail): ChatMessage[] {
- return detail.messages.map((m, i) => ({
- id: `hist-${detail.kind}-${detail.id}-${i}`,
- role: m.role as MessageRole,
- content: m.text,
- ts: m.ts_ms,
- thread_id: detail.id,
- }));
+ return detail.messages.map((m, i) => {
+ const message: ChatMessage = {
+ id: historyMessageId(detail, i),
+ role: m.role as MessageRole,
+ content: m.text,
+ ts: m.ts_ms,
+ thread_id: detail.id,
+ };
+ const trace = m.role === "assistant" && m.trace ? replayTrace(m.trace) : null;
+ if (trace) message.trace = trace;
+ return message;
+ });
+}
+
+/**
+ * The stored traces of a loaded conversation, keyed by the same ids
+ * `detailToMessages` hands out — replayed through the live reducer so the
+ * history shows "Thought for 4s" + steps exactly like the live turn did.
+ */
+export function detailToTraces(
+ detail: ConversationDetail,
+): Record<string, ThinkingTraceSnapshot> {
+ const out: Record<string, ThinkingTraceSnapshot> = {};
+ detail.messages.forEach((m, i) => {
+ if (m.role !== "assistant" || !m.trace) return;
+ const snapshot = replayTrace(m.trace);
+ if (snapshot) out[historyMessageId(detail, i)] = snapshot;
+ });
+ return out;
}
diff --git a/jarvis/ui/web/frontend/src/lib/homeTranscript.test.ts b/jarvis/ui/web/frontend/src/lib/homeTranscript.test.ts
index 51bb91dac8..3ea306db17 100644
--- a/jarvis/ui/web/frontend/src/lib/homeTranscript.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/homeTranscript.test.ts
@@ -256,3 +256,40 @@ describe("transcriptFromMessages", () => {
]);
});
});
+
+describe("transcriptFromMessages with stored traces", () => {
+ it("puts a folded steps line in front of a reply that carries a trace", () => {
+ const lines = transcriptFromMessages([
+ { role: "user", content: "Search my mail", ts: 1_000 },
+ {
+ role: "assistant",
+ content: "Found two.",
+ ts: 5_000,
+ trace: {
+ durationMs: 3_500,
+ steps: [
+ {
+ id: "x",
+ kind: "tool",
+ labelKey: "thinking.step_tool",
+ detail: "gmail_search",
+ status: "done",
+ startedTs: 1_200,
+ durationMs: 800,
+ },
+ ],
+ },
+ },
+ { role: "assistant", content: "No trace here.", ts: 9_000 },
+ ]);
+ expect(lines.map((l) => l.who)).toEqual(["user", "steps", "assistant", "assistant"]);
+ const steps = lines[1];
+ expect(steps.who).toBe("steps");
+ if (steps.who === "steps") {
+ expect(steps.live).toBe(false);
+ expect(steps.durationMs).toBe(3_500);
+ expect(steps.startedTs).toBe(1_500);
+ expect(steps.steps[0].detail).toBe("gmail_search");
+ }
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/homeTranscript.ts b/jarvis/ui/web/frontend/src/lib/homeTranscript.ts
index d216c2a734..82c825c79d 100644
--- a/jarvis/ui/web/frontend/src/lib/homeTranscript.ts
+++ b/jarvis/ui/web/frontend/src/lib/homeTranscript.ts
@@ -330,20 +330,41 @@ function reduceSteps(
* A stored conversation as transcript lines — what the voice stage shows
* when a past voice session is reopened WITHOUT leaving the voice surface
* (sidebar recent chats, 2026-08-23): you pick up where you left off and
- * keep talking. Only the words survive (user / assistant); a stored thread
- * carries no step trace, and UI-only roles (a preamble bubble, a system
- * note) are not part of the conversation. The reducer appends live events
- * after these lines as usual — their timestamps are old, so no live piece
- * ever joins or dedups against an archived line.
+ * keep talking. The words survive (user / assistant) and, since the
+ * backend keeps the reasoning trace next to a reply, so do the steps: a
+ * reply that carries a replayed trace gets its steps line in front of it,
+ * folded, exactly as the live turn showed them. UI-only roles (a preamble
+ * bubble, a system note) are not part of the conversation. The reducer
+ * appends live events after these lines as usual — their timestamps are
+ * old, so no live piece ever joins or dedups against an archived line.
*/
export function transcriptFromMessages(
- messages: ReadonlyArray<{ role: string; content: string; ts: number }>,
+ messages: ReadonlyArray<{
+ role: string;
+ content: string;
+ ts: number;
+ trace?: { steps: ThinkingStep[]; durationMs: number };
+ }>,
): TranscriptLine[] {
const lines: TranscriptLine[] = [];
for (const m of messages) {
if (m.role !== "user" && m.role !== "assistant") continue;
const text = clean(m.content);
if (!text) continue;
+ if (m.role === "assistant" && m.trace && m.trace.steps.length > 0) {
+ const startedTs = Math.max(0, m.ts - m.trace.durationMs);
+ lines.push({
+ id: nextId(m.ts),
+ ts: m.ts,
+ who: "steps",
+ text: "",
+ steps: m.trace.steps,
+ live: false,
+ startedTs,
+ lastTs: m.ts,
+ durationMs: m.trace.durationMs,
+ });
+ }
lines.push({ id: nextId(m.ts), ts: m.ts, who: m.role, text });
}
return cap(lines);
diff --git a/jarvis/ui/web/frontend/src/lib/thinkingSteps.test.ts b/jarvis/ui/web/frontend/src/lib/thinkingSteps.test.ts
index 40cd987fff..fcefa09f89 100644
--- a/jarvis/ui/web/frontend/src/lib/thinkingSteps.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/thinkingSteps.test.ts
@@ -7,6 +7,8 @@ import {
finalizeThinkingSteps,
MAX_THINKING_STEPS,
reduceThinkingSteps,
+ replayTrace,
+ traceModel,
type ThinkingStep,
} from "@/lib/thinkingSteps";
@@ -183,3 +185,85 @@ describe("finalizeThinkingSteps", () => {
expect(finalized[1]).toMatchObject({ status: "done", durationMs: 80 });
});
});
+
+describe("rationale, arguments and results", () => {
+ it("puts the model's rationale as a thought row in front of the tool row", () => {
+ const steps = run([
+ [
+ "ActionProposed",
+ {
+ tool_name: "wiki-recall",
+ args: { query: "Urlaub" },
+ rationale: "I'll look that up in the wiki.",
+ },
+ ],
+ ["ActionExecuted", { tool_name: "wiki-recall", success: true, duration_ms: 40, output_preview: "2 pages" }],
+ ]);
+ expect(steps).toHaveLength(2);
+ expect(steps[0]).toMatchObject({
+ kind: "thought",
+ detail: "I'll look that up in the wiki.",
+ status: "done",
+ });
+ expect(steps[1]).toMatchObject({
+ kind: "tool",
+ detail: "wiki-recall",
+ args: { query: "Urlaub" },
+ result: "2 pages",
+ status: "done",
+ });
+ });
+
+ it("keeps the error text of a failed or denied call", () => {
+ const failed = run([
+ ["ActionProposed", { tool_name: "open_app", args: { app: "Foo" } }],
+ ["ActionExecuted", { tool_name: "open_app", success: false, error: "not installed" }],
+ ]);
+ expect(failed[0]).toMatchObject({ status: "error", error: "not installed" });
+ const denied = run([
+ ["ActionProposed", { tool_name: "run_shell" }],
+ ["ActionDenied", { tool_name: "run_shell", reason: "blocked by policy" }],
+ ]);
+ expect(denied[0]).toMatchObject({ status: "error", error: "blocked by policy" });
+ });
+
+ it("names the provider that actually answered on the brain row", () => {
+ const steps = run([
+ ["BrainTurnStarted", { provider: "openai", model: "gpt-5" }],
+ ["BrainTurnStarted", { provider: "anthropic", model: "claude" }],
+ ["BrainTurnCompleted", { provider: "anthropic", model: "claude" }],
+ ]);
+ expect(traceModel(steps)).toBe("anthropic · claude");
+ });
+});
+
+describe("replayTrace", () => {
+ it("rebuilds a stored trace through the same reducer", () => {
+ const snapshot = replayTrace({
+ started_ms: T0,
+ ended_ms: T0 + 3_000,
+ events: [
+ { name: "ActionProposed", ts_ms: T0 + 100, payload: { tool_name: "search_web", args: { query: "x" } } },
+ { name: "ActionExecuted", ts_ms: T0 + 900, payload: { tool_name: "search_web", success: true } },
+ { name: "BrainTurnStarted", ts_ms: T0 + 1_000, payload: { provider: "p", model: "m" } },
+ { name: "BrainTurnCompleted", ts_ms: T0 + 2_900, payload: { provider: "p", model: "m" } },
+ ],
+ });
+ expect(snapshot).not.toBeNull();
+ expect(snapshot!.durationMs).toBe(3_000);
+ expect(snapshot!.model).toBe("p · m");
+ expect(snapshot!.steps.map((s) => s.kind)).toEqual(["tool", "brain"]);
+ expect(snapshot!.steps[0]).toMatchObject({ detail: "search_web", status: "done", durationMs: 800 });
+ expect(snapshot!.steps.every((s) => s.status !== "active")).toBe(true);
+ });
+
+ it("is null for nothing, and closes steps a stored turn never finished", () => {
+ expect(replayTrace(null)).toBeNull();
+ expect(replayTrace({ events: [] })).toBeNull();
+ expect(replayTrace({ events: [{ name: "MessageSent", ts_ms: 1, payload: {} }] })).toBeNull();
+ const open = replayTrace({
+ events: [{ name: "ActionProposed", ts_ms: T0, payload: { tool_name: "a" } }],
+ });
+ expect(open!.steps[0].status).toBe("done");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/thinkingSteps.ts b/jarvis/ui/web/frontend/src/lib/thinkingSteps.ts
index a0ed7fd948..a630fcc581 100644
--- a/jarvis/ui/web/frontend/src/lib/thinkingSteps.ts
+++ b/jarvis/ui/web/frontend/src/lib/thinkingSteps.ts
@@ -12,10 +12,15 @@
* Labels are i18n keys (resolved at render time so a live language switch
* re-labels past steps too); `detail` carries raw runtime text (tool names,
* window titles) that is not translated.
+ *
+ * The same reducer replays a STORED trace (the event list the backend keeps
+ * next to a reply, jarvis/state/turn_trace.py) — `replayTrace` below — so a
+ * reopened chat shows exactly what the live turn showed.
*/
export type ThinkingStepKind =
| "brain"
+ | "thought"
| "tool"
| "computer"
| "worker"
@@ -28,19 +33,37 @@ export interface ThinkingStep {
kind: ThinkingStepKind;
/** i18n key under "thinking.*" — resolved at render time. */
labelKey: string;
- /** Raw runtime detail (tool name, window title, ...). Never translated. */
+ /**
+ * Raw runtime detail, never translated: the tool's registry name for a
+ * tool row, the model's own sentence for a thought row, a window title…
+ */
detail?: string;
status: ThinkingStepStatus;
/** Wall-clock ms when the step appeared (drives live duration). */
startedTs: number;
/** Filled when the step completes. */
durationMs?: number;
+ /** Tool rows: the call's arguments (already redacted by the backend). */
+ args?: Record<string, unknown>;
+ /** Tool rows: a short preview of what came back. */
+ result?: string;
+ /** Tool / worker rows: why it failed, when it did. */
+ error?: string;
}
/** Finished trace attached to the assistant message that ended the turn. */
export interface ThinkingTraceSnapshot {
steps: ThinkingStep[];
durationMs: number;
+ /** The model that answered ("anthropic · claude-sonnet-5"), when the turn said. */
+ model?: string;
+}
+
+/** A stored trace as the backend keeps it: the event list of one turn. */
+export interface StoredTrace {
+ started_ms?: number;
+ ended_ms?: number;
+ events: Array<{ name: string; ts_ms: number; payload?: unknown }>;
}
/** Hard cap — a runaway turn must not grow the array unbounded. */
@@ -122,7 +145,7 @@ function completeTool(
steps: ThinkingStep[],
name: string,
tsMs: number,
- opts: { durationMs?: number; error?: boolean },
+ opts: { durationMs?: number; error?: boolean; result?: string; errorText?: string },
): ThinkingStep[] | null {
let idx = -1;
for (let i = steps.length - 1; i >= 0; i--) {
@@ -140,10 +163,17 @@ function completeTool(
...next[idx],
status: opts.error ? "error" : "done",
durationMs: opts.durationMs ?? Math.max(0, tsMs - next[idx].startedTs),
+ ...(opts.result ? { result: opts.result } : {}),
+ ...(opts.errorText ? { error: opts.errorText } : {}),
};
return next;
}
+function record(v: unknown): Record<string, unknown> | undefined {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return undefined;
+ return Object.keys(v as object).length ? (v as Record<string, unknown>) : undefined;
+}
+
/**
* Computer-Use phases fire many times per turn (observe→plan→act→...). One
* mutating row reads far calmer than 30 appended rows, so the active
@@ -204,8 +234,20 @@ export function reduceThinkingSteps(
});
}
- case "BrainTurnCompleted":
- return complete(steps, "brain", tsMs);
+ case "BrainTurnCompleted": {
+ // Completed names the provider that actually answered (Started fires
+ // once per fallback attempt); carry it onto the brain row.
+ const completed = complete(steps, "brain", tsMs);
+ const who = [str(p.provider), str(p.model)].filter(Boolean).join(" · ");
+ if (!completed || !who) return completed;
+ for (let i = completed.length - 1; i >= 0; i--) {
+ if (completed[i].kind === "brain") {
+ completed[i] = { ...completed[i], detail: who };
+ break;
+ }
+ }
+ return completed;
+ }
// ActionProposed/Executed/Denied are what the ToolExecutor actually
// publishes today; ToolCallStarted/Completed is the (currently unwired)
@@ -215,13 +257,30 @@ export function reduceThinkingSteps(
const name = str(p.tool_name);
// Dedupe in case both event families ever fire for the same call.
if (name && hasActiveTool(steps, name)) return null;
- return push(steps, {
+ // The sentence the model wrote next to the call ("I'll check the wiki
+ // for that") is the closest thing to its thinking we get for free —
+ // one muted line above the tool row, never spoken.
+ const rationale = clip(str(p.rationale), 200);
+ const withThought = rationale
+ ? push(steps, {
+ id: nextId(),
+ kind: "thought",
+ labelKey: "thinking.step_thought",
+ detail: rationale,
+ status: "done",
+ startedTs: tsMs,
+ durationMs: 0,
+ })
+ : steps;
+ const args = record(p.args);
+ return push(withThought, {
id: nextId(),
kind: "tool",
labelKey: "thinking.step_tool",
detail: name || undefined,
status: "active",
startedTs: tsMs,
+ ...(args ? { args } : {}),
});
}
@@ -231,6 +290,8 @@ export function reduceThinkingSteps(
const opts = {
durationMs: num(p.duration_ms) || undefined,
error: p.success === false,
+ result: clip(str(p.output_preview), 200) || undefined,
+ errorText: clip(str(p.error), 200) || undefined,
};
const completed = completeTool(steps, name, tsMs, opts);
if (completed) return completed;
@@ -245,6 +306,8 @@ export function reduceThinkingSteps(
status: opts.error ? "error" : "done",
startedTs: tsMs,
durationMs: opts.durationMs,
+ ...(opts.result ? { result: opts.result } : {}),
+ ...(opts.errorText ? { error: opts.errorText } : {}),
});
}
return null;
@@ -252,7 +315,10 @@ export function reduceThinkingSteps(
case "ActionDenied": {
const name = str(p.tool_name);
- return completeTool(steps, name, tsMs, { error: true });
+ return completeTool(steps, name, tsMs, {
+ error: true,
+ errorText: clip(str(p.reason), 200) || undefined,
+ });
}
case "ObservationCaptured":
@@ -287,11 +353,21 @@ export function reduceThinkingSteps(
startedTs: tsMs,
});
- case "JarvisAgentTaskCompleted":
- return complete(steps, "worker", tsMs, {
+ case "JarvisAgentTaskCompleted": {
+ const completed = complete(steps, "worker", tsMs, {
durationMs: num(p.duration_s) * 1000 || undefined,
error: p.success === false,
});
+ const why = clip(str(p.error), 200);
+ if (!completed || !why) return completed;
+ for (let i = completed.length - 1; i >= 0; i--) {
+ if (completed[i].kind === "worker") {
+ completed[i] = { ...completed[i], error: why };
+ break;
+ }
+ }
+ return completed;
+ }
case "AnnouncementRequested": {
// Progress announcements only — preambles already render as their own
@@ -326,3 +402,41 @@ export function finalizeThinkingSteps(
: s,
);
}
+
+/** "provider · model" of the brain row that answered, if the turn said. */
+export function traceModel(steps: ThinkingStep[]): string | undefined {
+ for (let i = steps.length - 1; i >= 0; i--) {
+ const s = steps[i];
+ if (s.kind === "brain" && s.detail) return s.detail;
+ }
+ return undefined;
+}
+
+/**
+ * Replay a stored trace (jarvis/state/turn_trace.py) into the snapshot the
+ * trace views render — the SAME reducer the live turn used, so history and
+ * live never disagree. Null when the record holds nothing to show.
+ */
+export function replayTrace(trace: StoredTrace | null | undefined): ThinkingTraceSnapshot | null {
+ if (!trace || !Array.isArray(trace.events) || trace.events.length === 0) return null;
+ let steps: ThinkingStep[] = [];
+ let first = Number.POSITIVE_INFINITY;
+ let last = 0;
+ for (const ev of trace.events) {
+ if (!ev || typeof ev.name !== "string") continue;
+ const ts = typeof ev.ts_ms === "number" ? ev.ts_ms : 0;
+ first = Math.min(first, ts);
+ last = Math.max(last, ts);
+ const next = reduceThinkingSteps(steps, ev.name, ev.payload ?? {}, ts);
+ if (next) steps = next;
+ }
+ if (steps.length === 0) return null;
+ const started = typeof trace.started_ms === "number" ? trace.started_ms : first;
+ const ended = typeof trace.ended_ms === "number" ? trace.ended_ms : last;
+ const end = Math.max(ended, last);
+ return {
+ steps: finalizeThinkingSteps(steps, end),
+ durationMs: Math.max(0, end - (Number.isFinite(started) ? started : end)),
+ model: traceModel(steps),
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/lib/toolStepLabel.test.ts b/jarvis/ui/web/frontend/src/lib/toolStepLabel.test.ts
new file mode 100644
index 0000000000..5f43b54f64
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/toolStepLabel.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+
+import { describeToolStep, pickToolDetail } from "@/lib/toolStepLabel";
+
+describe("describeToolStep", () => {
+ it("turns Jarvis tools into a family verb plus the call's detail", () => {
+ const wiki = describeToolStep("wiki-recall", { query: "Urlaub 2026" });
+ expect(wiki.family).toBe("wiki");
+ expect(wiki.labelKey).toBe("tool_steps.wiki");
+ expect(wiki.detail).toBe("Urlaub 2026");
+ expect(wiki.brand).toBeNull();
+
+ expect(describeToolStep("create_artifact", { title: "Sales deck" })).toMatchObject({
+ family: "artifact",
+ labelKey: "tool_steps.artifact",
+ detail: "Sales deck",
+ });
+ expect(describeToolStep("run-skill", { name: "daily-brief" })).toMatchObject({
+ family: "skill",
+ detail: "daily-brief",
+ });
+ expect(describeToolStep("search_web", { query: "weather" }).family).toBe("web");
+ expect(describeToolStep("screenshot").family).toBe("screen");
+ expect(describeToolStep("click_element", { selector: "OK" }).family).toBe("control");
+ expect(describeToolStep("spawn_worker", { task: "refactor" })).toMatchObject({
+ family: "worker",
+ detail: "refactor",
+ });
+ expect(describeToolStep("run_shell", { command: "ls -la" })).toMatchObject({
+ family: "shell",
+ detail: "ls -la",
+ });
+ });
+
+ it("treats 'server/tool' as an MCP call named after the server", () => {
+ const github = describeToolStep("github/create_issue", { title: "Bug" });
+ expect(github.family).toBe("mcp");
+ expect(github.labelKey).toBeNull();
+ expect(github.brand?.logoUrl).toBeTruthy();
+ expect(github.label).toBe("GitHub · Create Issue");
+ expect(github.detail).toBe("Bug");
+
+ const custom = describeToolStep("my-server/do_thing");
+ expect(custom.family).toBe("mcp");
+ expect(custom.brand?.logoUrl).toBeFalsy();
+ expect(custom.label).toBe("My Server · Do Thing");
+ });
+
+ it("lets a branded service tool speak through its logo and label", () => {
+ const gmail = describeToolStep("gmail_search", { query: "invoices" });
+ expect(gmail.family).toBe("service");
+ expect(gmail.labelKey).toBeNull();
+ expect(gmail.brand?.logoUrl).toBeTruthy();
+ expect(gmail.label).toBe("Gmail · search");
+ expect(gmail.detail).toBe("invoices");
+ });
+
+ it("never leaves an unknown tool nameless", () => {
+ const odd = describeToolStep("frobnicate_widgets", { target: "x" });
+ expect(odd.family).toBe("other");
+ expect(odd.label).toBe("frobnicate widgets");
+ expect(describeToolStep("").label).toBe("?");
+ });
+});
+
+describe("pickToolDetail", () => {
+ it("prefers the family's keys, clips long text, and falls back to any short string", () => {
+ expect(pickToolDetail("web", { limit: 3, query: "x".repeat(100) })).toHaveLength(72);
+ expect(pickToolDetail("web", { foo: "bar" })).toBe("bar");
+ expect(pickToolDetail("web", { n: 2 })).toBe("");
+ expect(pickToolDetail("web", null)).toBe("");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/toolStepLabel.ts b/jarvis/ui/web/frontend/src/lib/toolStepLabel.ts
new file mode 100644
index 0000000000..60afd9dc46
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/toolStepLabel.ts
@@ -0,0 +1,261 @@
+/**
+ * Tool call → the line a person reads in the reasoning trace.
+ *
+ * A tool step knows the registry name and the arguments of the call
+ * ("wiki-recall" + {query}), nothing more. The trace wants what the Claude
+ * desktop app shows: a sentence in the product's own words — "Looking in
+ * Wiki · Urlaub 2026", "Creating artifact · Sales deck", "Running skill ·
+ * daily-brief" — with the feature's own mark in front of it, or the
+ * service's brand logo when the tool belongs to Gmail, Spotify, an MCP
+ * server… This module is that pure mapping, so every surface that renders a
+ * tool row (chat column, voice lane, history) says the same thing.
+ *
+ * Families, not tool names, carry the wording: thirty tools fold into a
+ * dozen lines a non-developer understands. A tool nobody listed falls back
+ * to its brand (lib/toolBrand) or a humanised name — never to nothing.
+ */
+
+import { resolveToolBrand, type ToolBrand } from "@/lib/toolBrand";
+
+/** What a tool row is about — picks the icon and the verb. */
+export type ToolFamily =
+ | "wiki"
+ | "wiki_write"
+ | "artifact"
+ | "skill"
+ | "skill_create"
+ | "web"
+ | "screen"
+ | "screen_recall"
+ | "control"
+ | "navigate"
+ | "app"
+ | "memory"
+ | "profile"
+ | "contact"
+ | "call"
+ | "worker"
+ | "shell"
+ | "model"
+ | "mcp_admin"
+ | "settings"
+ | "verify"
+ | "mcp"
+ | "service"
+ | "other";
+
+export interface ToolStepView {
+ family: ToolFamily;
+ /** i18n key under "tool_steps.*" for the verb line; null when the brand label IS the line. */
+ labelKey: string | null;
+ /** The brand mark when the tool belongs to a known service (or MCP server). */
+ brand: ToolBrand | null;
+ /** Human line when there is no i18n key (brand label, MCP "Server · tool", humanised name). */
+ label: string;
+ /** Short runtime detail — the query, title, url, app, command… Untranslated. */
+ detail: string;
+}
+
+/** Registry name (normalised: lower, "-"/"_" equal) → family. */
+const FAMILY_BY_TOOL: Record<string, ToolFamily> = {
+ wiki_recall: "wiki",
+ wiki_list: "wiki",
+ wiki_page_read: "wiki",
+ ultrawiki_search: "wiki",
+ wiki_ingest: "wiki_write",
+ create_artifact: "artifact",
+ run_skill: "skill",
+ create_skill: "skill_create",
+ search_web: "web",
+ search_backends: "web",
+ screenshot: "screen",
+ screen_snapshot: "screen",
+ awareness_snapshot: "screen",
+ read_visible_ui_state: "screen",
+ inspect_pointer: "screen",
+ awareness_recall: "screen_recall",
+ computer_use: "control",
+ click: "control",
+ click_element: "control",
+ type_text: "control",
+ scroll: "control",
+ drag: "control",
+ move_mouse: "control",
+ hotkey: "control",
+ switch_window: "control",
+ wait_for_element: "control",
+ wait_for_ui_state: "control",
+ reset_orb_position: "control",
+ navigate: "navigate",
+ open_app: "app",
+ app_command: "app",
+ remember: "memory",
+ update_profile: "profile",
+ contact_lookup: "contact",
+ contact_upsert: "contact",
+ call_contact: "call",
+ spawn_worker: "worker",
+ spawn_subagents: "worker",
+ multi_spawn: "worker",
+ dispatch_to_harness: "worker",
+ dispatch_with_review: "worker",
+ dispatch_to_admin: "worker",
+ run_shell: "shell",
+ switch_provider: "model",
+ manage_mcp_server: "mcp_admin",
+ describe_app_settings: "settings",
+ whoami: "settings",
+ reveal_key_preview: "settings",
+ start_preview_server: "verify",
+ verify_localhost: "verify",
+ verify_via_curl: "verify",
+};
+
+/** Families whose line is a verb from i18n (the rest speak through their brand). */
+const LABEL_KEY: Partial<Record<ToolFamily, string>> = {
+ wiki: "tool_steps.wiki",
+ wiki_write: "tool_steps.wiki_write",
+ artifact: "tool_steps.artifact",
+ skill: "tool_steps.skill",
+ skill_create: "tool_steps.skill_create",
+ web: "tool_steps.web",
+ screen: "tool_steps.screen",
+ screen_recall: "tool_steps.screen_recall",
+ control: "tool_steps.control",
+ navigate: "tool_steps.navigate",
+ app: "tool_steps.app",
+ memory: "tool_steps.memory",
+ profile: "tool_steps.profile",
+ contact: "tool_steps.contact",
+ call: "tool_steps.call",
+ worker: "tool_steps.worker",
+ shell: "tool_steps.shell",
+ model: "tool_steps.model",
+ mcp_admin: "tool_steps.mcp_admin",
+ settings: "tool_steps.settings",
+ verify: "tool_steps.verify",
+};
+
+/** Argument keys tried, in order, for the detail of each family. */
+const DETAIL_KEYS: Partial<Record<ToolFamily, string[]>> = {
+ wiki: ["query", "slug", "title", "page", "topic"],
+ wiki_write: ["title", "slug", "url", "path"],
+ artifact: ["title", "name", "kind", "type"],
+ skill: ["name", "skill", "skill_name"],
+ skill_create: ["name", "title"],
+ web: ["query", "q", "url"],
+ screen: ["window", "window_title", "region"],
+ screen_recall: ["query", "question"],
+ control: ["text", "target", "selector", "keys", "title", "direction"],
+ navigate: ["url", "target", "section", "path"],
+ app: ["app", "name", "command", "app_name"],
+ memory: ["key", "text", "fact", "content"],
+ profile: ["field", "key"],
+ contact: ["name", "query", "contact"],
+ call: ["name", "contact", "number"],
+ worker: ["task", "utterance", "prompt", "goal", "instruction"],
+ shell: ["command", "cmd"],
+ model: ["provider", "model", "name"],
+ mcp_admin: ["name", "server", "action"],
+ settings: ["key", "section"],
+ verify: ["url", "port", "path"],
+ mcp: ["query", "q", "title", "name", "path", "url", "id"],
+ service: ["query", "q", "subject", "title", "name", "playlist", "track", "url"],
+ other: ["query", "text", "name", "title", "url"],
+};
+
+const DETAIL_MAX = 72;
+
+function normalise(toolName: string): string {
+ return toolName.trim().toLowerCase().replace(/[-\s.]+/g, "_");
+}
+
+function clip(text: string, max = DETAIL_MAX): string {
+ const clean = text.replace(/\s+/g, " ").trim();
+ return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
+}
+
+/** First short, readable argument of the call, by the family's preferred keys. */
+export function pickToolDetail(family: ToolFamily, args: unknown): string {
+ if (!args || typeof args !== "object") return "";
+ const record = args as Record<string, unknown>;
+ const keys = DETAIL_KEYS[family] ?? DETAIL_KEYS.other ?? [];
+ for (const key of keys) {
+ const v = record[key];
+ if (typeof v === "string" && v.trim()) return clip(v);
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
+ }
+ // Nothing by name: the first string value that reads like something.
+ for (const v of Object.values(record)) {
+ if (typeof v === "string" && v.trim() && v.trim().length <= 120) return clip(v);
+ }
+ return "";
+}
+
+/** "Cursor · Word" — the humanised last token(s) of a control tool name. */
+function humanise(name: string): string {
+ return name
+ .split("_")
+ .filter(Boolean)
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
+ .join(" ");
+}
+
+/**
+ * Describe one tool call for the trace.
+ *
+ * Order of resolution:
+ * 1. a listed Jarvis tool → its family's verb + the call's detail;
+ * 2. "server/tool" → an MCP call: the server's brand (when bundled) and
+ * "Server · tool" as the line;
+ * 3. a tool whose name carries a bundled brand (gmail_search, plugin-spotify)
+ * → the brand's logo and label (the service IS the line);
+ * 4. anything else → humanised name, monogram tile.
+ */
+export function describeToolStep(toolName: string, args?: unknown): ToolStepView {
+ const raw = (toolName ?? "").trim();
+ const key = normalise(raw);
+ const family = FAMILY_BY_TOOL[key];
+ if (family) {
+ return {
+ family,
+ labelKey: LABEL_KEY[family] ?? null,
+ brand: null,
+ label: humanise(key),
+ detail: pickToolDetail(family, args),
+ };
+ }
+
+ const slash = raw.indexOf("/");
+ if (slash > 0) {
+ const server = raw.slice(0, slash);
+ const tool = raw.slice(slash + 1);
+ const brand = resolveToolBrand(server);
+ const serverLabel = brand.logoUrl ? brand.label : humanise(normalise(server));
+ return {
+ family: "mcp",
+ labelKey: null,
+ brand: { ...brand, label: serverLabel },
+ label: tool ? `${serverLabel} · ${humanise(normalise(tool))}` : serverLabel,
+ detail: pickToolDetail("mcp", args),
+ };
+ }
+
+ const brand = resolveToolBrand(raw);
+ if (brand.logoUrl) {
+ return {
+ family: "service",
+ labelKey: null,
+ brand,
+ label: brand.label,
+ detail: pickToolDetail("service", args),
+ };
+ }
+ return {
+ family: "other",
+ labelKey: null,
+ brand,
+ label: brand.label || humanise(key) || "?",
+ detail: pickToolDetail("other", args),
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.ts
index 0c966fb5da..32f5a00428 100644
--- a/jarvis/ui/web/frontend/src/store/events.ts
+++ b/jarvis/ui/web/frontend/src/store/events.ts
@@ -4,10 +4,20 @@ import { readCachedAssistantName } from "@/lib/assistantNameCache";
import {
finalizeThinkingSteps,
reduceThinkingSteps,
+ traceModel,
type ThinkingStep,
type ThinkingTraceSnapshot,
} from "@/lib/thinkingSteps";
+/** The typed chat's reply while it is still being written. */
+export interface LiveReply {
+ text: string;
+ threadId: string;
+ /** The publisher said this is the last snapshot of the turn. */
+ done: boolean;
+ ts: number;
+}
+
/**
* Mirror of `jarvis/state/supervisor.py::SupervisorState`, lowercased.
*
@@ -263,6 +273,14 @@ export interface ChatMessage {
content: string;
ts: number;
thread_id?: string;
+ /**
+ * The reasoning trace behind a stored assistant reply (replayed from the
+ * backend's record when a conversation is opened). Live replies carry
+ * theirs in `thinkingTraces` instead; this travels with a loaded message
+ * so every surface that seeds itself from the list — the voice lane, the
+ * chat column — can show the steps without a second lookup.
+ */
+ trace?: ThinkingTraceSnapshot;
}
// Mirror of jarvis/state/conversation_constants.py (5-layer anti-drift: this
@@ -423,7 +441,14 @@ interface EventStore {
thinkingStartedTs: number | null;
// Finished traces keyed by the assistant message id that ended the turn —
// renders as the collapsible "Thought for Xs" disclosure above the reply.
+ // Seeded from the stored traces when a conversation is opened, so the
+ // history shows the steps behind each answer too.
thinkingTraces: Record<string, ThinkingTraceSnapshot>;
+ // The reply of the typed chat while it is still being written —
+ // AssistantTextDelta snapshots (channel "chat"), shown muted under the
+ // live steps and replaced by the final MessageSent. Null when nothing
+ // is streaming.
+ liveReply: LiveReply | null;
brainProvider: string;
// The model id the active provider is configured to use (e.g.
// "claude-opus-4-8"). Seeded from /api/brain/status on mount and refreshed on
@@ -498,6 +523,10 @@ interface EventStore {
ingestThinkingEvent: (name: string, payload: unknown, tsMs: number) => void;
/** Turn ended with an assistant reply: snapshot the trace onto that message. */
finishThinking: (messageId: string) => void;
+ /** Stored traces of an opened conversation, keyed like its messages. */
+ seedThinkingTraces: (traces: Record<string, ThinkingTraceSnapshot>) => void;
+ /** An AssistantTextDelta for the typed chat: the reply so far. */
+ setLiveReply: (reply: LiveReply | null) => void;
setBrainProvider: (p: string) => void;
setBrainModel: (m: string) => void;
setCodingMode: (m: CodingModeState) => void;
@@ -568,6 +597,7 @@ export const useEventStore = create<EventStore>((set, get) => ({
thinkingSteps: [],
thinkingStartedTs: null,
thinkingTraces: {},
+ liveReply: null,
brainProvider: "unknown",
codingMode: { active: false, hasWorkspace: false, workspace: "" },
brainModel: "",
@@ -720,9 +750,14 @@ export const useEventStore = create<EventStore>((set, get) => ({
thinking
? // New turn: arm the live trace. A re-send while already thinking
// restarts the trace — the old steps belonged to the superseded turn.
- { chatThinking: true, thinkingSteps: [], thinkingStartedTs: Date.now() }
+ {
+ chatThinking: true,
+ thinkingSteps: [],
+ thinkingStartedTs: Date.now(),
+ liveReply: null,
+ }
: // Timeout / brain error: discard the live trace without a snapshot.
- { chatThinking: false, thinkingSteps: [], thinkingStartedTs: null },
+ { chatThinking: false, thinkingSteps: [], thinkingStartedTs: null, liveReply: null },
),
ingestThinkingEvent: (name, payload, tsMs) => {
@@ -740,6 +775,8 @@ export const useEventStore = create<EventStore>((set, get) => ({
chatThinking: false,
thinkingSteps: [] as ThinkingStep[],
thinkingStartedTs: null,
+ // The final message replaces the streamed preview.
+ liveReply: null,
};
// Fast turns with zero observed steps get no disclosure — a "Thought for
// 0.4s · 0 steps" row on every smalltalk reply would be pure noise.
@@ -750,6 +787,7 @@ export const useEventStore = create<EventStore>((set, get) => ({
const snapshot: ThinkingTraceSnapshot = {
steps: finalizeThinkingSteps(thinkingSteps, now),
durationMs: Math.max(0, now - (thinkingStartedTs ?? now)),
+ model: traceModel(thinkingSteps),
};
const traces = { ...thinkingTraces, [messageId]: snapshot };
const keys = Object.keys(traces);
@@ -759,6 +797,15 @@ export const useEventStore = create<EventStore>((set, get) => ({
set({ ...idle, thinkingTraces: traces });
},
+ seedThinkingTraces: (traces) => set({ thinkingTraces: { ...traces } }),
+
+ setLiveReply: (reply) => {
+ // The preview belongs to the turn in flight; a stray snapshot after the
+ // reply landed (at-least-once delivery) must not resurrect it.
+ if (reply && !get().chatThinking) return;
+ set({ liveReply: reply });
+ },
+
setBrainProvider: (p) => set({ brainProvider: p }),
setBrainModel: (m) => set({ brainModel: m }),
setCodingMode: (m) => set({ codingMode: m }),
diff --git a/jarvis/ui/web/frontend/src/store/home.test.ts b/jarvis/ui/web/frontend/src/store/home.test.ts
new file mode 100644
index 0000000000..e7b19685ac
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/store/home.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+
+import { reduceLiveReply } from "@/store/home";
+
+describe("reduceLiveReply — the voice lane's answer as it forms", () => {
+ it("grows with voice/realtime snapshots and ignores the typed chat's", () => {
+ let live = reduceLiveReply("", "AssistantTextDelta", { channel: "realtime", text: "Ich" });
+ expect(live).toBe("Ich");
+ live = reduceLiveReply(live, "AssistantTextDelta", { channel: "voice", text: "Ich schaue" });
+ expect(live).toBe("Ich schaue");
+ expect(reduceLiveReply(live, "AssistantTextDelta", { channel: "chat", text: "typed" })).toBe(
+ "Ich schaue",
+ );
+ });
+
+ it("goes away once the spoken line, the turn's end or idle replaces it", () => {
+ expect(reduceLiveReply("x", "SpeechSpoken", { text: "x", spoken_kind: "reply" })).toBe("");
+ expect(reduceLiveReply("x", "SpeechSpoken", { text: "moment", spoken_kind: "preamble" })).toBe(
+ "x",
+ );
+ expect(reduceLiveReply("x", "MessageSent", { role: "assistant", text: "x" })).toBe("");
+ expect(reduceLiveReply("x", "MessageSent", { role: "user", text: "y" })).toBe("x");
+ expect(reduceLiveReply("x", "VoiceTurnCompleted", {})).toBe("");
+ expect(reduceLiveReply("x", "SystemStateChanged", { new_state: "IDLE" })).toBe("");
+ expect(reduceLiveReply("x", "SystemStateChanged", { new_state: "SPEAKING" })).toBe("x");
+ expect(reduceLiveReply("x", "HotkeyPressed", {})).toBe("x");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/store/home.ts b/jarvis/ui/web/frontend/src/store/home.ts
index 8793ccd5fe..d64aeb9ac7 100644
--- a/jarvis/ui/web/frontend/src/store/home.ts
+++ b/jarvis/ui/web/frontend/src/store/home.ts
@@ -19,6 +19,12 @@ interface HomeStore {
setSurface: (surface: HomeSurface) => void;
/** What was said and answered, oldest first (lib/homeTranscript.ts). */
transcript: TranscriptLine[];
+ /**
+ * The assistant's answer while it is still being spoken / produced —
+ * AssistantTextDelta snapshots from the voice paths, shown as a muted
+ * live line under the lane until the spoken line (SpeechSpoken) lands.
+ */
+ liveReply: string;
ingest: (name: string, payload: unknown, tsMs: number) => void;
/**
* Replace the lane with a stored conversation (a reopened voice session);
@@ -29,6 +35,42 @@ interface HomeStore {
resetTranscript: () => void;
}
+/**
+ * The voice stage's live answer line: grows with every AssistantTextDelta
+ * of a voice path, and goes away once the authoritative spoken line has
+ * replaced it or the turn is over. Same string back for every other event.
+ */
+export function reduceLiveReply(current: string, name: string, payload: unknown): string {
+ const p = (payload ?? {}) as Record<string, unknown>;
+ switch (name) {
+ case "AssistantTextDelta": {
+ const channel = typeof p.channel === "string" ? p.channel : "";
+ if (channel === "chat") return current;
+ return typeof p.text === "string" ? p.text : current;
+ }
+ case "SpeechSpoken":
+ case "MessageSent": {
+ // The final words arrived as a transcript line — the preview has
+ // served. (A preamble said mid-turn leaves the growing answer alone.)
+ const kind = typeof p.spoken_kind === "string" ? p.spoken_kind : "";
+ const role = typeof p.role === "string" ? p.role : "assistant";
+ if (name === "MessageSent" && role !== "assistant") return current;
+ if (name === "SpeechSpoken" && kind && kind !== "reply" && kind !== "other") {
+ return current;
+ }
+ return "";
+ }
+ case "VoiceTurnCompleted":
+ return "";
+ case "SystemStateChanged": {
+ const next = typeof p.new_state === "string" ? p.new_state.toLowerCase() : "";
+ return next === "idle" ? "" : current;
+ }
+ default:
+ return current;
+ }
+}
+
export const useHomeStore = create<HomeStore>((set, get) => ({
surface: readHomeSurface(),
setSurface: (surface) => {
@@ -36,11 +78,15 @@ export const useHomeStore = create<HomeStore>((set, get) => ({
set({ surface });
},
transcript: [],
+ liveReply: "",
ingest: (name, payload, tsMs) => {
const before = get().transcript;
const after = reduceTranscript(before, name, payload, tsMs);
- if (after !== before) set({ transcript: after });
+ const live = reduceLiveReply(get().liveReply, name, payload);
+ if (after !== before || live !== get().liveReply) {
+ set({ transcript: after, liveReply: live });
+ }
},
- seedTranscript: (lines) => set({ transcript: lines }),
- resetTranscript: () => set({ transcript: [] }),
+ seedTranscript: (lines) => set({ transcript: lines, liveReply: "" }),
+ resetTranscript: () => set({ transcript: [], liveReply: "" }),
}));
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index d9eae05463..3046031555 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -566,6 +566,11 @@ async def _run_headless(args) -> int:
# conversation manager has durable, segmented history across restarts.
chat_store = ChatStore(bus=server.bus, db_path=default_chats_db_path(cfg.memory.data_dir))
chat_store.open()
+ # The reasoning trace of a chat turn, stored next to the reply (the desktop
+ # bridge does the same) so the history shows the steps behind an answer.
+ from jarvis.state.turn_trace import TurnTraceCollector
+
+ turn_traces = TurnTraceCollector(server.bus)
# Cap unbounded growth at startup (mirrors the session-store prune in
# sessions/init.py). 365d is deliberately generous — the user wants "all my
# chats"; voice sessions already prune at 30d and text is tiny — so this only
@@ -620,6 +625,7 @@ async def _run_headless(args) -> int:
if evt.source_layer in ("chat", "brain:mock"):
return
thread_id = evt.thread_id or "default"
+ turn_started_ms = time.time_ns() // 1_000_000
# Persist the initiating turn before the reply. Older builds stored only
# the assistant half, producing anonymous "New Thread" rows that looked
# like text messages the user never sent.
@@ -684,6 +690,15 @@ async def _run_headless(args) -> int:
import logging as _ack_logging
_ack_logging.getLogger(__name__).debug("chat instant ack not armed", exc_info=True)
+ from jarvis.core.text_stream import TextDeltaPublisher
+
+ delta_publisher = TextDeltaPublisher(
+ server.bus,
+ channel="chat",
+ thread_id=thread_id,
+ trace_id=evt.trace_id,
+ source_layer="ui.web.chat",
+ )
try:
generate = getattr(brain, "generate", None)
if callable(generate):
@@ -691,15 +706,26 @@ async def _run_headless(args) -> int:
# recap (ui.web.ws.mission_inject) from force-spawn — discussed
# inline, never re-dispatched (doom-loop fix 2026-06-16). This
# is the headless/web (VPS) bridge; desktop_app.py mirrors it.
- reply = await generate(
- evt.text,
- trace_id=evt.trace_id,
- source_layer=evt.source_layer,
- conversation_id=thread_id,
- )
+ try:
+ reply = await generate(
+ evt.text,
+ trace_id=evt.trace_id,
+ source_layer=evt.source_layer,
+ conversation_id=thread_id,
+ text_consumer=delta_publisher.feed,
+ )
+ except TypeError:
+ # An older brain shape without the streaming hook.
+ reply = await generate(
+ evt.text,
+ trace_id=evt.trace_id,
+ source_layer=evt.source_layer,
+ conversation_id=thread_id,
+ )
else:
reply = await brain(evt.text)
except Exception as exc: # noqa: BLE001
+ delta_publisher.cancel()
if ack_task is not None and not ack_task.done():
ack_task.cancel()
detail = f"{type(exc).__name__}: {exc}"
@@ -720,9 +746,13 @@ async def _run_headless(args) -> int:
return
if ack_task is not None and not ack_task.done():
ack_task.cancel()
+ await delta_publisher.flush(done=True)
if reply:
role = "system" if _is_brain_diagnostic(reply) else "assistant"
- await chat_store.add_message(thread_id=thread_id, role=role, text=reply)
+ trace = turn_traces.snapshot(turn_started_ms) if role == "assistant" else None
+ await chat_store.add_message(
+ thread_id=thread_id, role=role, text=reply, trace=trace
+ )
server.bus.subscribe(MessageSent, _on_user_message)
diff --git a/tests/unit/core/test_text_stream.py b/tests/unit/core/test_text_stream.py
new file mode 100644
index 0000000000..7ee883aa91
--- /dev/null
+++ b/tests/unit/core/test_text_stream.py
@@ -0,0 +1,83 @@
+"""TextDeltaPublisher: token pieces become a few cumulative AssistantTextDelta events."""
+
+from __future__ import annotations
+
+import asyncio
+
+from jarvis.core.bus import EventBus
+from jarvis.core.events import AssistantTextDelta
+from jarvis.core.text_stream import TextDeltaPublisher
+
+
+async def _collect(bus: EventBus) -> list[AssistantTextDelta]:
+ seen: list[AssistantTextDelta] = []
+
+ async def _on(event: AssistantTextDelta) -> None:
+ seen.append(event)
+
+ bus.subscribe(AssistantTextDelta, _on)
+ return seen
+
+
+async def test_pieces_coalesce_into_cumulative_snapshots() -> None:
+ bus = EventBus()
+ seen = await _collect(bus)
+ pub = TextDeltaPublisher(bus, channel="chat", thread_id="t1", interval_s=0.02)
+ for piece in ("Hal", "lo", " Welt", ","):
+ pub.feed(piece)
+ await asyncio.sleep(0.08)
+ pub.feed(" wie geht's?")
+ await pub.flush(done=True)
+
+ assert seen, "nothing published"
+ # Far fewer events than pieces, every one a growing prefix of the next.
+ assert len(seen) <= 3
+ texts = [e.text for e in seen]
+ for earlier, later in zip(texts, texts[1:], strict=False):
+ assert later.startswith(earlier)
+ assert seen[-1].text == "Hallo Welt, wie geht's?"
+ assert seen[-1].done is True
+ assert all(e.thread_id == "t1" and e.channel == "chat" for e in seen)
+ assert all(not e.done for e in seen[:-1])
+
+
+async def test_flush_without_text_publishes_nothing() -> None:
+ bus = EventBus()
+ seen = await _collect(bus)
+ pub = TextDeltaPublisher(bus, channel="voice")
+ await pub.flush(done=True)
+ assert seen == []
+ # Closed: later pieces are ignored.
+ pub.feed("late")
+ await asyncio.sleep(0.1)
+ assert seen == []
+
+
+async def test_set_text_replaces_the_snapshot() -> None:
+ bus = EventBus()
+ seen = await _collect(bus)
+ pub = TextDeltaPublisher(bus, channel="realtime", interval_s=0.01)
+ pub.set_text("Ich")
+ pub.set_text("Ich schaue")
+ await asyncio.sleep(0.05)
+ pub.set_text("Ich schaue nach.")
+ await pub.flush(done=True)
+ assert seen[-1].text == "Ich schaue nach."
+ assert seen[-1].done is True
+
+
+async def test_cancel_drops_pending_text_silently() -> None:
+ bus = EventBus()
+ seen = await _collect(bus)
+ pub = TextDeltaPublisher(bus, channel="chat", interval_s=0.05)
+ pub.feed("half an ans")
+ pub.cancel()
+ await asyncio.sleep(0.1)
+ assert seen == []
+
+
+async def test_no_bus_is_a_quiet_no_op() -> None:
+ pub = TextDeltaPublisher(None, channel="chat")
+ pub.feed("x")
+ await pub.flush(done=True)
+ assert pub.text == "x"
diff --git a/tests/unit/state/test_turn_trace.py b/tests/unit/state/test_turn_trace.py
new file mode 100644
index 0000000000..8fa2d03f26
--- /dev/null
+++ b/tests/unit/state/test_turn_trace.py
@@ -0,0 +1,213 @@
+"""The reasoning trace of a turn survives the turn (jarvis/state/turn_trace.py).
+
+A trace is the event list the UI replays into "Thought for 4s" + steps. The
+collector keeps the bus's trace-relevant events in a ring, hands a turn its
+slice, and redacts what it stores; ``ChatStore`` keeps it next to the reply
+and migrates an older ``chats.db`` that has no column for it.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+from uuid import uuid4
+
+from jarvis.core.bus import EventBus
+from jarvis.core.events import (
+ ActionExecuted,
+ ActionProposed,
+ BrainTurnCompleted,
+ BrainTurnStarted,
+ HotkeyPressed,
+ MessageSent,
+)
+from jarvis.state.chat_store import ChatStore
+from jarvis.state.turn_trace import (
+ TRACE_EVENT_KINDS,
+ TurnTraceCollector,
+ trace_from_events,
+ trace_payload_for,
+)
+
+
+async def test_collector_keeps_only_trace_events_in_order() -> None:
+ bus = EventBus()
+ collector = TurnTraceCollector(bus)
+ t0 = 1_700_000_000_000
+ await bus.publish(HotkeyPressed(timestamp_ns=(t0 + 1) * 1_000_000))
+ await bus.publish(
+ ActionProposed(
+ timestamp_ns=(t0 + 2) * 1_000_000,
+ tool_name="wiki-recall",
+ args={"query": "Urlaub"},
+ rationale="Ich schaue im Wiki nach.",
+ )
+ )
+ await bus.publish(
+ ActionExecuted(
+ timestamp_ns=(t0 + 5) * 1_000_000,
+ tool_name="wiki-recall",
+ success=True,
+ duration_ms=3,
+ output_preview="2 pages",
+ )
+ )
+ await bus.publish(MessageSent(timestamp_ns=(t0 + 6) * 1_000_000, role="assistant", text="x"))
+
+ trace = collector.snapshot(t0)
+ assert trace is not None
+ assert [e["name"] for e in trace["events"]] == ["ActionProposed", "ActionExecuted"]
+ assert trace["events"][0]["payload"]["args"] == {"query": "Urlaub"}
+ assert trace["events"][0]["payload"]["rationale"] == "Ich schaue im Wiki nach."
+ assert trace["events"][1]["payload"]["output_preview"] == "2 pages"
+ assert trace["started_ms"] == t0
+ assert trace["ended_ms"] == t0 + 5
+
+
+async def test_snapshot_is_none_for_a_quiet_window() -> None:
+ collector = TurnTraceCollector(EventBus())
+ assert collector.snapshot(0) is None
+
+
+def test_slice_respects_the_window() -> None:
+ collector = TurnTraceCollector()
+ for ms in (10, 20, 30):
+ collector.record(
+ "BrainTurnStarted",
+ BrainTurnStarted(timestamp_ns=ms * 1_000_000, provider="p", model="m"),
+ )
+ assert [e["ts_ms"] for e in collector.slice(15, 25)] == [20]
+ assert [e["ts_ms"] for e in collector.slice(20)] == [20, 30]
+
+
+def test_payload_is_redacted_and_capped() -> None:
+ secret = "sk-ant-api03-" + "A" * 40
+ payload = trace_payload_for(
+ "ActionProposed",
+ ActionProposed(
+ tool_name="run_shell",
+ args={
+ "command": f"export KEY={secret}",
+ "long": "x" * 500,
+ **{f"k{i}": i for i in range(20)},
+ },
+ rationale="r" * 1000,
+ ),
+ )
+ assert secret not in payload["args"]["command"]
+ assert len(payload["args"]["long"]) < 200
+ assert len(payload["args"]) <= 8
+ assert len(payload["rationale"]) < 300
+ # Numbers stay numbers, so the UI can format durations.
+ done = trace_payload_for(
+ "ActionExecuted", ActionExecuted(tool_name="x", success=False, duration_ms=42)
+ )
+ assert done["duration_ms"] == 42 and done["success"] is False
+
+
+def test_trace_from_recorded_voice_rows_matches_collector_shape() -> None:
+ rows = [
+ {"kind": "TranscriptFinal", "ts_ms": 100, "payload": {}},
+ {
+ "kind": "ActionProposed",
+ "ts_ms": 120,
+ "payload": {"tool_name": "search_web", "args": {"query": "Wetter"}},
+ },
+ {
+ "kind": "ActionExecuted",
+ "ts_ms": 900,
+ "payload": {"tool_name": "search_web", "success": True},
+ },
+ {"kind": "ActionExecuted", "ts_ms": 5000, "payload": {"tool_name": "later"}},
+ ]
+ trace = trace_from_events(rows, since_ms=100, until_ms=1000)
+ assert trace is not None
+ assert [e["name"] for e in trace["events"]] == ["ActionProposed", "ActionExecuted"]
+ assert trace["events"][0]["payload"]["args"] == {"query": "Wetter"}
+ assert trace_from_events([], since_ms=0) is None
+
+
+def test_every_trace_kind_has_a_payload_whitelist() -> None:
+ from jarvis.state.turn_trace import _PAYLOAD_KEYS
+
+ assert TRACE_EVENT_KINDS == frozenset(_PAYLOAD_KEYS)
+
+
+async def test_chat_store_round_trips_the_trace(tmp_path) -> None:
+ path = str(tmp_path / "chats.db")
+ trace = {
+ "started_ms": 1,
+ "ended_ms": 9,
+ "events": [{"name": "BrainTurnCompleted", "ts_ms": 9, "payload": {"model": "m"}}],
+ }
+ s1 = ChatStore(bus=EventBus(), db_path=path)
+ await s1.add_message(thread_id="t", role="user", text="hi")
+ await s1.add_message(thread_id="t", role="assistant", text="hello", trace=trace)
+
+ s2 = ChatStore(bus=EventBus(), db_path=path)
+ msgs = s2.get_thread("t")["messages"]
+ assert msgs[0]["trace"] is None
+ assert msgs[1]["trace"] == trace
+
+
+async def test_chat_store_migrates_a_db_without_the_trace_column(tmp_path) -> None:
+ """An existing chats.db from before traces opens and stores traces."""
+ path = tmp_path / "chats.db"
+ conn = sqlite3.connect(path)
+ conn.executescript(
+ """
+ CREATE TABLE chat_threads (
+ thread_id TEXT PRIMARY KEY, title TEXT NOT NULL DEFAULT '',
+ kind TEXT NOT NULL DEFAULT 'text',
+ created_at_ns INTEGER NOT NULL, updated_at_ns INTEGER NOT NULL);
+ CREATE TABLE chat_messages (
+ message_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, role TEXT NOT NULL,
+ text TEXT NOT NULL, timestamp_ns INTEGER NOT NULL);
+ INSERT INTO chat_threads VALUES ('old', 'Old', 'text', 1, 1);
+ INSERT INTO chat_messages VALUES ('m1', 'old', 'assistant', 'legacy', 1);
+ """
+ )
+ conn.commit()
+ conn.close()
+
+ store = ChatStore(bus=EventBus(), db_path=str(path))
+ legacy = store.get_thread("old")["messages"]
+ assert legacy[0]["trace"] is None
+ await store.add_message(thread_id="old", role="assistant", text="new", trace={"events": []})
+ # An empty trace is stored as nothing — there is no trace to show.
+ assert store.get_thread("old")["messages"][-1]["trace"] is None
+ await store.add_message(
+ thread_id="old",
+ role="assistant",
+ text="traced",
+ trace={"events": [{"name": "BrainTurnStarted", "ts_ms": 1, "payload": {}}]},
+ )
+ assert (
+ store.get_thread("old")["messages"][-1]["trace"]["events"][0]["name"] == "BrainTurnStarted"
+ )
+
+
+async def test_chat_store_drops_an_unserialisable_trace_but_keeps_the_message() -> None:
+ store = ChatStore(bus=EventBus())
+ bad = {"events": [{"name": "x", "ts_ms": 1, "payload": {"u": uuid4()}}]}
+ msg = await store.add_message(thread_id="t", role="assistant", text="ok", trace=bad)
+ assert msg.text == "ok"
+ stored = store.get_thread("t")["messages"][-1]["trace"]
+ # ``default=str`` makes the UUID a string rather than losing the trace.
+ assert stored is not None and isinstance(stored["events"][0]["payload"]["u"], str)
+
+
+async def test_completed_turn_is_in_the_collector_too() -> None:
+ bus = EventBus()
+ collector = TurnTraceCollector(bus)
+ await bus.publish(
+ BrainTurnCompleted(provider="anthropic", model="claude", timestamp_ns=5_000_000)
+ )
+ trace = collector.snapshot(0)
+ assert trace is not None
+ assert trace["events"][0]["payload"] == {
+ "provider": "anthropic",
+ "model": "claude",
+ "finish_reason": "",
+ "tokens_in": 0,
+ "tokens_out": 0,
+ }