Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(workbench): Chat Agent Activity panel (Web Chat intermediate progress) (#934)

Call White7d7752b62568
diff --git a/config/v2_config.py b/config/v2_config.py
index 9555a2805..557ef5104 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -310,6 +310,11 @@ class UiConfig:
setup_port: int = 5123
open_browser: bool = True
chat_message_font_size: int = DEFAULT_CHAT_MESSAGE_FONT_SIZE_PX
+ # When true, the Web Chat renders each agent turn's intermediate activity
+ # (interim ``assistant`` messages + ``tool_call`` summaries) as a collapsible
+ # group, and the message mirror streams those rows live. Default off: a strict
+ # no-op — the live stream and transcript stay exactly as they are today.
+ show_agent_activity: bool = False
trusted_public_origins: List[str] = field(default_factory=list)
# Display name appended to the browser tab title ("Avibe - <name>"). When
# blank the UI falls back to the read-only ``default_instance_name`` field
@@ -574,6 +579,13 @@ class V2Config:
)
except (TypeError, ValueError):
ui.chat_message_font_size = DEFAULT_CHAT_MESSAGE_FONT_SIZE_PX
+ # Accept real booleans; parse known string forms explicitly (a config file
+ # or API client may supply "false"/"0", and ``bool("false")`` is True).
+ raw_show_activity = ui.show_agent_activity
+ if isinstance(raw_show_activity, str):
+ ui.show_agent_activity = raw_show_activity.strip().lower() in ("1", "true", "yes", "on")
+ else:
+ ui.show_agent_activity = bool(raw_show_activity)
remote_access_payload = payload.get("remote_access") or {}
if not isinstance(remote_access_payload, dict):
diff --git a/core/message_mirror.py b/core/message_mirror.py
index 38484719b..f772d4957 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -23,6 +23,7 @@ the live IM reply path.
from __future__ import annotations
import logging
+import time
from datetime import datetime, timezone
from typing import Any, Optional
@@ -105,6 +106,82 @@ def _publish_session_message(row: Optional[dict]) -> None:
logger.debug("message_mirror: message.new publish failed", exc_info=True)
+# Streaming intermediate activity (interim ``assistant`` messages + ``tool_call``
+# trace) to an open Chat page is gated on ``config.ui.show_agent_activity`` (default
+# off). Reading the config parses a file, and this path runs once per agent emit —
+# many times per turn — so the flag is cached briefly, keyed by config path so a
+# fresh AVIBE_HOME (e.g. per-test) never reads a stale value. On any error the flag
+# is OFF: a config glitch degrades to today's strict no-op (no extra stream).
+_ACTIVITY_FLAG_TTL_SECONDS = 3.0
+_activity_flag_cache: dict[str, tuple[float, bool]] = {}
+
+
+def reset_activity_flag_cache() -> None:
+ """Drop the cached ``show_agent_activity`` flag (test hook / config-change)."""
+ _activity_flag_cache.clear()
+
+
+def _activity_streaming_enabled() -> bool:
+ try:
+ from config import paths
+
+ key = str(paths.get_config_path())
+ except Exception:
+ key = ""
+ now = time.monotonic()
+ cached = _activity_flag_cache.get(key)
+ if cached is not None and (now - cached[0]) < _ACTIVITY_FLAG_TTL_SECONDS:
+ return cached[1]
+ enabled = False
+ try:
+ from core.services import settings as settings_svc
+
+ enabled = bool(settings_svc.load_config_or_default().ui.show_agent_activity)
+ except Exception:
+ logger.debug("message_mirror: activity flag read failed", exc_info=True)
+ enabled = False
+ _activity_flag_cache[key] = (now, enabled)
+ return enabled
+
+
+def _publish_activity_event(event_row: Optional[dict]) -> None:
+ """Publish a session-scoped ``message.new`` for a ``tool_call`` trace event.
+
+ Tool-call rows live in ``agent_events`` (never in ``messages`` / the transcript),
+ so synthesize a ``messages``-shaped payload the Chat activity group can render
+ live. Called only when ``show_agent_activity`` is on; the payload carries its own
+ display data (no read-after-announce), so the browser never re-queries the row.
+ """
+ if not event_row or not event_row.get("session_id"):
+ return
+ payload = {
+ "id": event_row.get("id"),
+ "scope_id": event_row.get("scope_id"),
+ "session_id": event_row.get("session_id"),
+ "platform": event_row.get("platform") or "avibe",
+ "author": "agent",
+ "type": "tool_call",
+ "source": "agent",
+ "author_id": None,
+ "author_name": event_row.get("agent_name"),
+ "native_message_id": None,
+ "parent_native_message_id": None,
+ "text": event_row.get("text") or "",
+ "content": event_row.get("content") or {},
+ "metadata": event_row.get("metadata") or {},
+ "created_at": event_row.get("created_at"),
+ "updated_at": event_row.get("updated_at") or event_row.get("created_at"),
+ "delivered_at": None,
+ "read_at": None,
+ }
+ try:
+ from core.inbox_events import bus
+
+ bus.publish("message.new", payload)
+ except Exception:
+ logger.debug("message_mirror: activity tool_call publish failed", exc_info=True)
+
+
def _session_row(conn, session_id: str) -> Optional[dict]:
"""Resolve scope/provenance from an agent session."""
from sqlalchemy import select
@@ -208,6 +285,9 @@ def persist_agent_message(
engine = get_cached_sqlite_engine()
inbox_row = None
appended_row = None
+ tool_event_row = None
+ message_type = None
+ is_tool_call = _is_tool_call_type(canonical_type)
with engine.begin() as conn:
if context.platform == "avibe":
# Inbox groups by the avibe session's project scope; never invent
@@ -234,9 +314,11 @@ def persist_agent_message(
# session's agent (from the dispatch context). source_id (author_id)
# is left to the agent-id wiring later; the session already carries it.
agent_name, backend = _agent_provenance_from_context(context, session_row)
- if _is_tool_call_type(canonical_type):
+ if is_tool_call:
turn_id, run_id = _trace_ids_from_context(context)
- agent_events_service.append(
+ # Captured for the (gated) live activity publish after commit; the
+ # row itself is trace data in ``agent_events`` (never in ``messages``).
+ tool_event_row = agent_events_service.append(
conn,
scope_id=scope_id,
session_id=row_session_id,
@@ -251,59 +333,71 @@ def persist_agent_message(
turn_id=turn_id,
run_id=run_id,
)
- return
- message_type = _AGENT_TYPE_BY_CANONICAL.get(canonical_type or "", "assistant")
- # Workbench Chat only: rewrite ``file://`` links in the persisted copy
- # to same-origin media-proxy URLs so the browser renders agent images
- # inline + files as download cards. IM rows keep the raw ``file://``
- # (the dispatcher uploads those to the platform separately). Scoped to
- # the user-visible result/notify rows so we don't mint tokens for the
- # hidden intermediate assistant stream.
- if context.platform == "avibe" and message_type in ("result", "notify", "error") and row_session_id:
- try:
- from core.workbench_media import rewrite_agent_media
-
- text = rewrite_agent_media(
- conn, scope_id=scope_id, session_id=row_session_id, text=text
- )
- except Exception:
- logger.exception("persist_agent_message: media rewrite failed")
- content: Optional[dict] = {"kind": canonical_type} if canonical_type else None
- # Quick-reply buttons (avibe result): the trailing ``---\n[label]…``
- # block was already parsed + stripped upstream; carry the labels in
- # ``content`` so the workbench renders the button group (IM channels
- # render their own native buttons from the same parse).
- if quick_replies:
- content = {**(content or {}), "quick_replies": list(quick_replies)}
- appended_row = _append_quietly(
- conn,
- scope_id=scope_id,
- session_id=row_session_id,
- platform=context.platform,
- author="agent",
- source="agent",
- author_name=agent_name,
- message_type=message_type,
- text=text,
- metadata=metadata,
- native_message_id=native_message_id,
- parent_native_message_id=context.thread_id,
- content=content,
- )
- # Recompute the session's inbox row so the realtime event can patch
- # the browser without a refetch. avibe-only: the workbench inbox is
- # scoped to avibe sessions (IM rows persist but aren't shown there).
- if context.platform == "avibe" and session_id:
- inbox_row = messages_service.get_inbox_session(conn, session_id)
+ else:
+ message_type = _AGENT_TYPE_BY_CANONICAL.get(canonical_type or "", "assistant")
+ # Workbench Chat only: rewrite ``file://`` links in the persisted copy
+ # to same-origin media-proxy URLs so the browser renders agent images
+ # inline + files as download cards. IM rows keep the raw ``file://``
+ # (the dispatcher uploads those to the platform separately). Scoped to
+ # the user-visible result/notify rows so we don't mint tokens for the
+ # hidden intermediate assistant stream.
+ if context.platform == "avibe" and message_type in ("result", "notify", "error") and row_session_id:
+ try:
+ from core.workbench_media import rewrite_agent_media
+
+ text = rewrite_agent_media(
+ conn, scope_id=scope_id, session_id=row_session_id, text=text
+ )
+ except Exception:
+ logger.exception("persist_agent_message: media rewrite failed")
+ content: Optional[dict] = {"kind": canonical_type} if canonical_type else None
+ # Quick-reply buttons (avibe result): the trailing ``---\n[label]…``
+ # block was already parsed + stripped upstream; carry the labels in
+ # ``content`` so the workbench renders the button group (IM channels
+ # render their own native buttons from the same parse).
+ if quick_replies:
+ content = {**(content or {}), "quick_replies": list(quick_replies)}
+ appended_row = _append_quietly(
+ conn,
+ scope_id=scope_id,
+ session_id=row_session_id,
+ platform=context.platform,
+ author="agent",
+ source="agent",
+ author_name=agent_name,
+ message_type=message_type,
+ text=text,
+ metadata=metadata,
+ native_message_id=native_message_id,
+ parent_native_message_id=context.thread_id,
+ content=content,
+ )
+ # Recompute the session's inbox row so the realtime event can patch
+ # the browser without a refetch. avibe-only: the workbench inbox is
+ # scoped to avibe sessions (IM rows persist but aren't shown there).
+ if context.platform == "avibe" and session_id:
+ inbox_row = messages_service.get_inbox_session(conn, session_id)
+ # tool_call rows never enter ``messages``/TRANSCRIPT_TYPES; when the Chat
+ # activity panel is enabled they fan out here as a synthesized
+ # ``message.new`` so an open Chat page shows the step live. Default off →
+ # no publish (strict no-op). Return None to preserve the tool_call contract.
+ if is_tool_call:
+ if context.platform == "avibe" and _activity_streaming_enabled():
+ _publish_activity_event(tool_event_row)
+ return None
# Fan the row out to an open Chat page (session-scoped stream), then bump
# the inbox card. Both ride the controller→browser bridge. Only publish
# transcript-visible types so the live stream carries EXACTLY what the
- # history fetch returns (assistant / tool_call process-log rows are
- # persisted for debugging but neither streamed nor fetched) (user request).
+ # history fetch returns — EXCEPT interim ``assistant`` rows, which stream
+ # only when the Chat activity panel is enabled (they still stay out of the
+ # transcript + inbox; the activity group renders them separately).
# avibe-only: IM rows now carry a session_id too, but the workbench Chat is
# avibe-only, so keep the live fan-out scoped to avibe (an IM session has no
# open Chat consumer; publishing it would be dead traffic).
- if context.platform == "avibe" and message_type in messages_service.TRANSCRIPT_TYPES:
+ if context.platform == "avibe" and (
+ message_type in messages_service.TRANSCRIPT_TYPES
+ or (message_type == "assistant" and _activity_streaming_enabled())
+ ):
_publish_session_message(appended_row)
if inbox_row is not None:
from core.inbox_events import bus
diff --git a/docs/plans/chat-agent-activity-panel.md b/docs/plans/chat-agent-activity-panel.md
new file mode 100644
index 000000000..04274088e
--- /dev/null
+++ b/docs/plans/chat-agent-activity-panel.md
@@ -0,0 +1,257 @@
+# Chat Agent Activity Panel (intermediate progress in Web Chat)
+
+Status: approved design, implementation dispatched (2026-07-17)
+Owner decisions locked: global toggle in Settings › Messaging; history turns included;
+assistant interim text shown in full; tool calls summary-first with expandable detail;
+no token-level streaming; no IM-side changes.
+
+## Background
+
+Research-desk users want to watch what the agent is doing during a turn:
+intermediate assistant messages and tool calls. Today the Web Chat shows only a
+three-dot ThinkingBubble while `working`, and the reply arrives atomically.
+
+Key fact (verified 2026-07-17): the data pipeline already exists end-to-end.
+All three backends emit intermediate `assistant` / `toolcall` via
+`controller.emit_agent_message` → `core/message_mirror.py persist_agent_message`
+persists them (`assistant` → `messages` table; `toolcall` → `agent_events` table
+with `turn_id`/`sequence`/`content_json`) → `message.new` is published on the bus
+→ SSE `/api/events` reaches the browser. The frontend currently **drops** these
+rows in `isTranscriptMessage` (`ui/src/components/workbench/ChatPage.tsx`).
+This feature is therefore: group-and-render what is already flowing + one
+settings toggle + a small history read endpoint. Default off = exact current UI.
+
+## Design source of truth
+
+- design.pen frames (avibe-docs `design.pen`): `BoX4o` "Chat · Agent 执行过程 Activity Panel (P1)"
+ spec board (states A–F + anatomy + interaction rules) and `s3SZt` full-page
+ in-context mock. Exported PNGs for implementation reference:
+ `~/vibe-remote-project/_tmp/activity-design/BoX4o.png` and `s3SZt.png`.
+- Match the existing chat visual language: message avatar block, `bg-mint/[0.09]`-family
+ tints, muted borders, JetBrains Mono for timings/metadata. Map to existing
+ tokens/classes; no hardcoded one-off colors.
+
+## UX specification
+
+One new transcript row kind: **ActivityGroup** — one per agent turn, positioned
+where that turn's reply renders (directly above the terminal message).
+
+States:
+
+1. **Running · compact (default)** — replaces ThinkingBubble when the toggle is
+ on and the running turn has ≥1 activity row (falls back to ThinkingBubble
+ while empty). Card = header + fixed-height viewport (~3 rows, ≈110px):
+ header: spinner + "Running" + step count + elapsed + chevron;
+ body: newest rows scroll in from the bottom, older rows fade upward;
+ auto-follows the tail. The card itself never grows: no transcript reflow,
+ existing scroll anchoring untouched.
+2. **Running · expanded** — click header: max-height ≈40vh, internal scroll,
+ auto-follow latest; manual scroll-up pauses follow and shows a "jump to
+ latest" pill (reuse Transcript's existing jump logic/pattern). Stays
+ expanded for the rest of the turn until collapsed.
+3. **Done · collapsed (default)** — on terminal `result`: collapse to a single
+ chip "✓ Activity · N steps · 1m 23s" hugging the final reply from above.
+ Click to expand/collapse anytime. Expansion state is not persisted.
+4. **History turns** — same chip on past turns (including after refresh).
+ Detail is lazy-loaded on first expand; never loaded for the initial
+ transcript render.
+5. **Interrupted / failed** — chip variants: "Interrupted · stopped at step N"
+ (gold icon) when the turn ends without a terminal result (Stop/override);
+ "Failed · N steps" (destructive icon) on error result. Error details keep
+ flowing through the existing error bubble — never into the activity panel.
+
+Event rows:
+
+- **Tool row**: icon (by tool-name prefix: terminal/file-text/pencil/globe/bot,
+ fallback wrench) + tool name (mono) + one-line summary + duration when
+ available. Summary = first line of the already-formatted toolcall text
+ (`format_toolcall` output) — never raw tool input/output dumps.
+ **Click row → expand/collapse inline detail block** showing the full stored
+ toolcall text (mono, from `agent_events.content_json`). v1 does not read
+ native transcripts; if only the summary line was stored, that is what shows.
+- **Assistant interim row**: sparkles icon + **full text** (owner decision —
+ users read the content). Wrapped, rendered with the existing `Markdown`
+ component in a compact style (smaller font); no truncation. In the compact
+ running viewport the fixed window simply follows the tail.
+
+Grouping rules:
+
+- Anchor by turn boundaries, not by user messages: a group collects
+ `assistant`/`tool_call` rows between the previous terminal row and the next
+ terminal (`result`/error) row; live turn = rows arriving while `working`.
+ This also covers agent-initiated turns (no inbound user message) and queued
+ turns (each turn groups independently).
+- Reconnect/refresh mid-turn: persisted interim rows of the running turn
+ re-hydrate the group; empty group falls back to ThinkingBubble.
+
+Settings:
+
+- `config.ui.show_agent_activity` (bool, default `false`), server-persisted via
+ the existing `config.ui.*` path (same as `chat_message_font_size`), edited in
+ Settings › Messaging with `SettingsRow` + `ToggleSwitch`.
+- Independent from IM `agent_progress_style` / status bubble — no IM changes.
+
+Out of scope (v1): token-level streaming (all three backends' delta handlers
+are unimplemented), drill-down beyond the stored toolcall text, IM platforms,
+per-chat override toggle, persistence of expand/collapse state.
+
+## Implementation notes (grounded pointers, verify before relying)
+
+Frontend (`ui/src`):
+
+- `components/workbench/ChatPage.tsx`: `isTranscriptMessage` currently filters
+ `assistant`/`tool_call`; `Transcript`/`MessageRow`/`ThinkingBubble`;
+ `working` state; jump-to-latest + scroll-anchor logic; `MAX_RETAINED_MESSAGES = 300`
+ (mind the retained-window interplay — activity rows must not silently evict
+ visible conversation rows; group or cap accordingly).
+- SSE: `context/ApiContext.tsx` `connectWorkbenchEvents` (`message.new`,
+ `turn.start`, `turn.end`, `session.status`).
+- Settings page: `components/settings/SettingsMessagingPage.tsx`,
+ primitives in `components/settings/SettingsPrimitives.tsx`.
+- i18n: every new string in both `ui/src/i18n/en.json` and `zh.json`.
+- Collapse pattern precedent: the harness chip branch in `MessageRow`.
+
+Backend:
+
+- **Verify early (evidence-first, run it, don't assume)**: whether `tool_call`
+ rows currently arrive at the browser via `message.new` and/or the transcript
+ fetch, and what `content_json` carries for each backend. Adapt: live path
+ should reuse `message.new`; if tool_call rows are absent from any needed
+ path, extend at the chokepoint (`message_mirror` publish / transcript API),
+ not per-backend.
+- History lazy-load: a small read endpoint on `vibe/ui_server.py` (native
+ FastAPI async, no per-request `asyncio.run()`) serving a turn's activity rows
+ from `messages` + `agent_events` (`agent_events_service`). Endpoint shape is
+ the lane's choice; document it in the PR description.
+- Config default + plumbing for `ui.show_agent_activity` through bootstrap
+ config like `chat_message_font_size`.
+
+## Acceptance criteria (owner ~10 min)
+
+1. Toggle exists in Settings › Messaging, default off; off = pixel-identical
+ current behavior (ThinkingBubble and all).
+2. On: sending a message shows the compact card in the reply position, live
+ tool summaries + full interim assistant text, fixed height, no layout jump.
+3. Header click expands (~40vh, internal scroll); scroll-up pauses follow and
+ shows jump-to-latest; tool row click toggles full call text.
+4. On completion the card collapses to the one-line chip above the final reply;
+ chip toggles open/closed.
+5. Past turns (after refresh) show chips; first expand lazy-loads detail.
+6. Stop mid-run → "Interrupted" chip; failing turn → "Failed" chip with error
+ bubble unchanged.
+7. IM platforms behave exactly as before; `npm run build` green; touched
+ backend files' per-file pytest green; ruff clean.
+
+## As-built implementation notes (PR #934)
+
+Implemented on branch `feat/chat-agent-activity-panel`. The three items below
+record where the build diverged from or sharpened the plan above.
+
+### (a) The `message.new` live-push gap → gated publish at the chokepoint
+
+The plan's "Key fact" assumed intermediate `assistant` / `tool_call` rows already
+reach the browser via `message.new`. **Verified false.** `persist_agent_message`
+(`core/message_mirror.py`) persists them but publishes **no** `message.new` — the
+live stream deliberately carries only transcript types
+(`TRANSCRIPT_TYPES = user/harness/result/notify/error`). Proven by the persist
+contract tests `test_persist_agent_intermediate_persisted_but_not_streamed` and
+`test_persist_agent_toolcall_avibe_writes_event_without_streaming`.
+
+Per the plan's own "verify early / extend at the chokepoint, not per-backend"
+guidance, the live path is extended **only** in `core/message_mirror.py`, gated on
+`config.ui.show_agent_activity`:
+
+- **off (default) → byte-identical no-op.** No extra publish; `tool_call` still
+ writes only to `agent_events`, `assistant` still stays out of the stream; the
+ existing mirror contract tests are unchanged.
+- **on →** interim `assistant` rows publish `message.new` (the persisted row), and
+ `tool_call` events (which live in `agent_events`, never `messages`) publish a
+ **synthesized** `message.new` payload shaped like a `messages` row
+ (`type='tool_call'`), so the one existing browser consumer (ChatPage) can route
+ it into the activity store. `inbox.session.updated` and web-push are **not**
+ emitted for these rows (still process log, not a reply).
+
+The gate reads `settings.load_config_or_default().ui.show_agent_activity` behind a
+short TTL cache keyed by config path (no per-emit disk parse; the path key keeps a
+fresh `AVIBE_HOME` — e.g. per test — from reading a stale value). No IM /
+`core/message_dispatcher.py` / per-adapter edits.
+
+Config plumbing mirrors `chat_message_font_size`: `UiConfig.show_agent_activity:
+bool = False` in `config/v2_config.py` (+ a `bool(...)` coercion in `from_payload`),
+surfaced automatically through `to_dict` / `api.config_to_payload`, saved via the
+deep-merged `POST /api/config` (a partial `{"ui": {...}}` patch preserves siblings),
+read by ChatPage from `bootstrap.config.ui.show_agent_activity`.
+
+### (b) History read endpoint
+
+`GET /api/sessions/<id>/activity` (native async FastAPI in `vibe/ui_server.py`,
+reads `messages` + `agent_events` via storage services; 404 on unknown session):
+
+- **summary** (no params) — one entry per turn with ≥1 activity row, no row text:
+ `{"groups": [{"id", "anchor_message_id", "status", "steps", "started_at",
+ "ended_at", "duration_ms"}]}`. Loaded once on chat open so past turns show a chip.
+- **detail** (`?group_id=<id>`) — that one group plus `"rows": [{"id", "kind"
+ (`assistant`|`tool_call`), "text", "created_at"}]`. The lazy expand; 404 on an
+ unknown group id.
+
+`status ∈ done | failed | interrupted`. `id` is the group's first-activity-row id
+(stable key across summary/detail). `anchor_message_id` is the transcript message
+the chip renders above — the terminal reply for done/failed, the next turn's opening
+message for a history-interrupted turn, or `null` when the interrupted turn trails
+the transcript. Grouping logic lives in `storage/agent_activity_service.py`; the
+low-level read is `agent_events_service.list_session_events`.
+
+### (c) Timestamp-parsed turn-boundary grouping
+
+`messages` has **no `turn_id`** column (only `agent_events` does), so a turn cannot
+be reconstructed by id. Instead a turn is bounded by transcript markers: it ends at
+the agent's terminal reply (`result` / `error` / backend-failure `notify`), or — if
+the user opened a new turn without one — is reported `interrupted`. Activity rows
+between boundaries form the group.
+
+Both tables write **whole-second** `...Z` timestamps, so a fast turn's tool call
+and the terminal reply that followed it tie on time. The two sources are merged
+into one timeline sorted by `(parsed_timestamp, phase)` where phase orders
+turn-start < activity < terminal — this keeps a same-second tool call inside its
+completed turn instead of sorting it after the terminal (which would orphan it to
+the next turn or a spurious interrupted chip). Timestamps are **parsed**, not
+string-compared, so the ordering stays correct if a writer ever changes precision.
+Show-Page `assistant` marks (`metadata.source == 'show_page'`) are excluded from
+activity (they belong to the transcript). The scan is bounded to the recent tail
+(most-recent 500 messages / 2000 tool-call events, cap documented not silent), and
+tool-call events that predate the oldest scanned message are dropped — otherwise an
+event whose turn boundary was cut off would anchor a bogus chip to the first
+visible turn.
+
+Frontend (single-source-of-truth model — the durable endpoint owns all SETTLED
+groups; the live SSE buffer drives ONLY the in-flight running card). The running
+card is a pure function of ``working`` AND the current-generation buffer
+(`shouldShowRunningCard`) — so a stale buffer is invisible the moment ``working``
+goes false. The live buffer never leaves that card: there is deliberately no
+client-side group reconstruction. On every settle signal — a terminal
+`message.new`, `turn.end`, SSE reconnect, visibilitychange, OR the `/turn-state`
+idle poll recovering a dropped terminal (the fifth signal, same contract) —
+`refreshActivity` rebuilds `activityGroups` from `GET /activity` and, when no
+in-flight turn remains, clears the live buffer so the finished card swaps to the
+storage-derived chip (and its rows can't leak into the next turn). When a turn IS in flight, refresh re-hydrates the running card's rows
+from storage only if the live stream hasn't already filled them. Settle bursts are
+coalesced to one in-flight + at most one trailing fetch (`scheduleActivityRefresh`),
+a transient fetch failure schedules exactly one bounded retry, and nothing fetches
+when the toggle is off. The live buffer is a pure **generation** state machine
+(`liveActivityReducer`, unit-tested): a monotonic generation bumps on every
+turn.start (and on the first agent-initiated row after a settle), so a stale buffer
+is invisible by construction and a late settle-refresh only clears/rehydrates its
+OWN generation — a newer turn's resolution is a structural no-op (no
+promise-cancellation or grace-timer bookkeeping). This structure closes the whole
+class of live-state edge cases (lossy/stale/partial buffer, interrupted anchoring,
+duration source, settle-vs-next-turn races) that iterative patching kept surfacing:
+the chip's steps, status, anchor, and duration always come from the well-tested
+backend grouping. Activity rows still live in a **separate store** (never the
+`messages` array), so they never count against `MAX_RETAINED_MESSAGES`. Show-Page
+transcript rows (`user` AND `assistant`, `metadata.source='show_page'`) are excluded
+from both the backend grouping (never turn openers / activity) and live ingestion.
+A lazy detail-fetch failure surfaces a retry affordance rather than a false "no
+activity". The activity-streaming flag cache is reset on config save so the toggle
+takes effect immediately. Presentation is `ActivityCard` / `ActivityChip` in
+`ui/src/components/workbench/AgentActivityGroup.tsx`; pure helpers + the live
+generation reducer + wire mapping in `ui/src/lib/agentActivity.ts`.
diff --git a/storage/agent_activity_service.py b/storage/agent_activity_service.py
new file mode 100644
index 000000000..9270d14b1
--- /dev/null
+++ b/storage/agent_activity_service.py
@@ -0,0 +1,307 @@
+"""Turn-grouped agent activity for the Web Chat Activity panel.
+
+Composes the two persisted trace sources into per-turn groups:
+
+* interim ``assistant`` messages (``messages`` table, ``type='assistant'``), and
+* ``tool_call`` events (``agent_events`` table, ``event_type='tool_call'``).
+
+A *turn* is bounded by transcript markers rather than an id: it ends at the
+agent's terminal reply (``result`` / ``error`` / backend-failure ``notify``) or,
+when the user starts a new turn without one, is reported as ``interrupted``.
+Grouping is chronological because ``messages`` carries no ``turn_id`` (only
+``agent_events`` does). Both tables persist WHOLE-SECOND ``...Z`` ``created_at``,
+which cannot order same-second rows — but both also mint ids with a MICROSECOND
+clock prefix (``<pfx>_<15-hex microsecond epoch><uuid8>``), so the merge sorts by
+that decoded microsecond, recovering the true emission order ACROSS tables (a fast
+turn's tool call before its same-second terminal; one turn's terminal before the
+next turn's same-second opener). A phase tiebreak (turn-start < activity <
+terminal) only applies when the microsecond can't be decoded (format drift), and
+the whole-second ``created_at`` still bounds the event scan.
+
+Each group is keyed by the id of its first activity row (stable across summary
+and detail reads). ``anchor_message_id`` is the transcript message the chip
+renders against: the terminal reply for done/failed turns, or the next turn's
+opening message for an interrupted turn (``None`` when the interrupted turn is
+the last thing in the session — the chip trails the transcript).
+
+Reads are bounded (recent tail) so a pathological session never triggers an
+unbounded scan; the Chat loads the recent transcript first, so the recent turns
+are exactly the ones covered.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from typing import Any, Optional
+
+from storage import agent_events_service, messages_service
+
+# Bound the scan. The Chat retains ~300 recent messages and pages older on
+# demand; covering the most-recent MESSAGE_SCAN_LIMIT transcript messages (and
+# EVENT_SCAN_LIMIT tool-call events) keeps every recent turn while capping work.
+# Groups older than this window are omitted (documented, not silent — see the PR).
+MESSAGE_SCAN_LIMIT = 500
+EVENT_SCAN_LIMIT = 2000
+
+# Message types that participate in turn structure: turn openers (user/harness),
+# terminals (result/error/notify), and the interim assistant activity rows.
+_RELEVANT_MESSAGE_TYPES = (
+ "user",
+ messages_service.HARNESS_TYPE,
+ "result",
+ "error",
+ "notify",
+ "assistant",
+)
+
+
+def _parse_ts(value: Optional[str]) -> datetime:
+ """Parse an ISO timestamp from either table into an aware UTC datetime.
+
+ Both tables currently write ``...Z`` (whole seconds); normalize the trailing
+ ``Z`` and assume UTC when no offset is present, and tolerate a fractional /
+ offset form too (future-proofing). Unparseable values sort first.
+ """
+ if not value:
+ return datetime.min.replace(tzinfo=timezone.utc)
+ text = value.strip()
+ if text.endswith("Z"):
+ text = text[:-1] + "+00:00"
+ try:
+ parsed = datetime.fromisoformat(text)
+ except ValueError:
+ return datetime.min.replace(tzinfo=timezone.utc)
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed
+
+
+def _duration_ms(started_iso: Optional[str], ended_iso: Optional[str]) -> Optional[int]:
+ if not started_iso or not ended_iso:
+ return None
+ delta = (_parse_ts(ended_iso) - _parse_ts(started_iso)).total_seconds() * 1000.0
+ if delta < 0:
+ return 0
+ return int(delta)
+
+
+def _is_terminal(msg_type: Any, author: Any, metadata: Optional[dict]) -> bool:
+ """Mirror the frontend ``isTerminalAgentMessage`` predicate."""
+ if author != "agent":
+ return False
+ if msg_type in ("result", "error"):
+ return True
+ if msg_type == "notify" and (metadata or {}).get("event") == "backend_failure":
+ return True
+ return False
+
+
+def _terminal_status(msg_type: Any) -> str:
+ return "done" if msg_type == "result" else "failed"
+
+
+# Fallback tiebreak only (used when a row's microsecond id prefix can't be decoded,
+# e.g. format drift): within a single turn the order is open → work → close.
+_PHASE_RANK = {"turn_start": 0, "activity": 1, "terminal": 2, "ignore": 3}
+
+
+def _emit_micros(row_id: Optional[str], ts: datetime) -> int:
+ """The row's emission microsecond, decoded from the id's clock prefix.
+
+ Both tables mint ids as ``<pfx>_<15-hex microsecond epoch><uuid8>`` (see
+ ``messages_service`` / ``agent_events_service``), so this recovers the true
+ sub-second emission order ACROSS tables — which whole-second ``created_at``
+ cannot. Falls back to the parsed timestamp when an id doesn't match the format.
+ """
+ if row_id and len(row_id) >= 19 and row_id[3] == "_":
+ try:
+ return int(row_id[4:19], 16)
+ except ValueError:
+ pass
+ return int(ts.timestamp() * 1_000_000)
+
+
+def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, Any]]:
+ """Merge the recent tail of relevant messages + tool-call events into one
+ chronologically-ordered list of classified items."""
+ msgs = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ limit=MESSAGE_SCAN_LIMIT,
+ tail=True,
+ types=_RELEVANT_MESSAGE_TYPES,
+ )["messages"]
+ events = agent_events_service.list_session_events(
+ conn,
+ session_id=session_id,
+ event_types=("tool_call",),
+ limit=EVENT_SCAN_LIMIT,
+ newest_first=True,
+ )
+
+ items: list[dict[str, Any]] = []
+ for msg in msgs:
+ mtype = msg.get("type")
+ author = msg.get("author")
+ metadata = msg.get("metadata") or {}
+ # Show-Page annotations/intents persist as transcript rows (``user`` AND
+ # ``assistant``) with metadata.source='show_page'; they are display-only and
+ # must never act as a turn opener (would split an in-flight turn) nor as
+ # activity — always ignore them in the grouping.
+ show_page = metadata.get("source") == "show_page"
+ if _is_terminal(mtype, author, metadata):
+ kind = "terminal"
+ elif mtype in ("user", messages_service.HARNESS_TYPE) and not show_page:
+ kind = "turn_start"
+ elif mtype == "assistant" and not show_page:
+ kind = "activity"
+ else:
+ kind = "ignore"
+ mts = _parse_ts(msg.get("created_at"))
+ items.append(
+ {
+ "ts": mts,
+ "sort": _emit_micros(msg.get("id"), mts),
+ "rank": _PHASE_RANK[kind],
+ "created_at": msg.get("created_at"),
+ "kind": kind,
+ "id": msg.get("id"),
+ "mtype": mtype,
+ "row_kind": "assistant",
+ "text": msg.get("text") if include_text else None,
+ }
+ )
+ # Bound events to the scanned message window: in a long session the 500-message
+ # tail can start after some of the fetched events, and an event whose turn
+ # boundary was NOT fetched would otherwise be grouped as pending and anchored to
+ # the first visible turn — surfacing an earlier turn's tool calls above the wrong
+ # message. Compare by the decoded microsecond sort key (not just the whole
+ # second), so a same-second event emitted BEFORE the oldest scanned message is
+ # dropped too.
+ oldest_msg_sort = min((item["sort"] for item in items), default=None)
+ for event in events:
+ event_ts = _parse_ts(event.get("created_at"))
+ event_sort = _emit_micros(event.get("id"), event_ts)
+ if oldest_msg_sort is not None and event_sort < oldest_msg_sort:
+ continue
+ items.append(
+ {
+ "ts": event_ts,
+ "sort": event_sort,
+ "rank": _PHASE_RANK["activity"],
+ "created_at": event.get("created_at"),
+ "kind": "activity",
+ "id": event.get("id"),
+ "mtype": "tool_call",
+ "row_kind": "tool_call",
+ "text": event.get("text") if include_text else None,
+ }
+ )
+ # Sort by decoded emission microsecond (true cross-table order); the phase rank
+ # is a fallback for undecodable ids, and the id a final deterministic tiebreak.
+ items.sort(key=lambda item: (item["sort"], item["rank"], item["id"]))
+ return items
+
+
+def _make_group(
+ pending: list[dict[str, Any]],
+ *,
+ status: str,
+ anchor_id: Optional[str],
+ started_iso: Optional[str],
+ ended_iso: Optional[str],
+ include_rows: bool,
+) -> dict[str, Any]:
+ started = started_iso or pending[0]["created_at"]
+ group: dict[str, Any] = {
+ "id": pending[0]["id"],
+ "anchor_message_id": anchor_id,
+ "status": status,
+ "steps": len(pending),
+ "started_at": started,
+ "ended_at": ended_iso,
+ "duration_ms": _duration_ms(started, ended_iso),
+ }
+ if include_rows:
+ group["rows"] = [
+ {
+ "id": item["id"],
+ "kind": item["row_kind"],
+ "text": item.get("text") or "",
+ "created_at": item["created_at"],
+ }
+ for item in pending
+ ]
+ return group
+
+
+def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[dict[str, Any]]:
+ groups: list[dict[str, Any]] = []
+ pending: list[dict[str, Any]] = []
+ turn_start_iso: Optional[str] = None
+ for item in items:
+ kind = item["kind"]
+ if kind == "activity":
+ pending.append(item)
+ elif kind == "turn_start":
+ if pending:
+ # Activity with no terminal before a new turn opened → interrupted;
+ # anchor the chip against the opening message of the next turn.
+ groups.append(
+ _make_group(
+ pending,
+ status="interrupted",
+ anchor_id=item["id"],
+ started_iso=turn_start_iso,
+ ended_iso=pending[-1]["created_at"],
+ include_rows=include_rows,
+ )
+ )
+ pending = []
+ turn_start_iso = item["created_at"]
+ elif kind == "terminal":
+ if pending:
+ groups.append(
+ _make_group(
+ pending,
+ status=_terminal_status(item["mtype"]),
+ anchor_id=item["id"],
+ started_iso=turn_start_iso,
+ ended_iso=item["created_at"],
+ include_rows=include_rows,
+ )
+ )
+ pending = []
+ turn_start_iso = None
+ # kind == "ignore": leave pending + turn_start untouched
+ if pending:
+ # Trailing interrupted turn (no following message): chip trails the transcript.
+ groups.append(
+ _make_group(
+ pending,
+ status="interrupted",
+ anchor_id=None,
+ started_iso=turn_start_iso,
+ ended_iso=pending[-1]["created_at"],
+ include_rows=include_rows,
+ )
+ )
+ return groups
+
+
+def list_turn_groups(conn, *, session_id: str) -> dict[str, Any]:
+ """Summary of every activity group in the recent window: one entry per turn
+ that produced ≥1 activity row, without the (potentially large) row text."""
+ groups = _build_groups(_timeline(conn, session_id, include_text=False), include_rows=False)
+ return {"groups": groups}
+
+
+def get_turn_group(conn, *, session_id: str, group_id: str) -> Optional[dict[str, Any]]:
+ """One group's full rows (interim assistant text + tool-call text), for the
+ lazy expand. ``group_id`` is the group's first-activity-row id (from the
+ summary). Returns ``None`` when no group matches."""
+ groups = _build_groups(_timeline(conn, session_id, include_text=True), include_rows=True)
+ for group in groups:
+ if group["id"] == group_id:
+ return group
+ return None
diff --git a/storage/agent_events_service.py b/storage/agent_events_service.py
index 34559069b..5f6950d40 100644
--- a/storage/agent_events_service.py
+++ b/storage/agent_events_service.py
@@ -14,6 +14,7 @@ import uuid
from datetime import datetime, timezone
from typing import Any, Optional
+from sqlalchemy import select
from sqlalchemy.engine import Connection
from storage.models import agent_events
@@ -104,3 +105,33 @@ def append(
}
conn.execute(agent_events.insert().values(**payload))
return _row_to_payload(payload)
+
+
+def list_session_events(
+ conn: Connection,
+ *,
+ session_id: str,
+ event_types: Optional[tuple[str, ...]] = None,
+ limit: Optional[int] = None,
+ newest_first: bool = False,
+) -> list[dict[str, Any]]:
+ """Return this session's ``agent_events`` as payload dicts, oldest first.
+
+ Backed by the ``ix_agent_events_session_created_id`` index. ``event_types``
+ filters by ``event_type`` (e.g. ``("tool_call",)``). ``newest_first`` fetches
+ the most-recent ``limit`` rows (then returns them oldest-first), so a bounded
+ scan still yields the recent tail — the result order is always chronological.
+ """
+ stmt = select(agent_events).where(agent_events.c.session_id == session_id)
+ if event_types:
+ stmt = stmt.where(agent_events.c.event_type.in_(tuple(event_types)))
+ if newest_first:
+ stmt = stmt.order_by(agent_events.c.created_at.desc(), agent_events.c.id.desc())
+ else:
+ stmt = stmt.order_by(agent_events.c.created_at, agent_events.c.id)
+ if limit is not None:
+ stmt = stmt.limit(limit)
+ rows = [_row_to_payload(dict(row)) for row in conn.execute(stmt).mappings().all()]
+ if newest_first:
+ rows.reverse()
+ return rows
diff --git a/tests/test_agent_activity_service.py b/tests/test_agent_activity_service.py
new file mode 100644
index 000000000..0683e0d30
--- /dev/null
+++ b/tests/test_agent_activity_service.py
@@ -0,0 +1,348 @@
+"""Unit tests for turn-grouped agent activity (Chat Activity panel history read).
+
+Covers the grouping contract in ``storage/agent_activity_service.py``:
+
+* a turn with ≥1 activity row + a terminal reply → a ``done`` / ``failed`` group
+ anchored at the terminal message,
+* interim ``assistant`` rows and ``tool_call`` events are merged into one group
+ ordered by PARSED timestamp (the two tables store different ISO precisions),
+* a turn whose activity is followed by a NEW turn (no terminal) → ``interrupted``
+ anchored at the next turn's opening message; a trailing one → anchor ``None``,
+* a turn with no activity rows produces no group,
+* Show-Page ``assistant`` marks (metadata.source='show_page') are not activity,
+* detail mode returns the ordered rows; an unknown group id returns ``None``.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+from sqlalchemy import select # noqa: F401 (kept parallel to sibling tests)
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from storage import agent_activity_service
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import agent_events, agent_sessions, messages
+from storage.settings_service import upsert_scope
+
+
+def isolated_state(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ yield tmp_path
+
+
+def _seed_session(conn, *, session_id="ses_act"):
+ scope_id = upsert_scope(
+ conn, platform="avibe", scope_type="project", native_id="proj_act", now="2026-06-01T10:00:00Z"
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor=f"anchor_{session_id}",
+ native_session_id="",
+ status="active",
+ metadata_json="{}",
+ created_at="2026-06-01T10:00:00Z",
+ updated_at="2026-06-01T10:00:00Z",
+ last_active_at="2026-06-01T10:00:00Z",
+ )
+ )
+ return scope_id
+
+
+def _msg(conn, scope_id, session_id, *, mid, mtype, author, created_at, text="", source="agent", metadata=None):
+ conn.execute(
+ messages.insert().values(
+ id=mid,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author=author,
+ type=mtype,
+ source=source,
+ content_text=text,
+ content_json="{}",
+ metadata_json=json.dumps(metadata or {}),
+ created_at=created_at,
+ updated_at=created_at,
+ )
+ )
+
+
+def _evt(conn, scope_id, session_id, *, eid, created_at, text):
+ conn.execute(
+ agent_events.insert().values(
+ id=eid,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ event_type="tool_call",
+ visibility="trace",
+ content_text=text,
+ content_json=json.dumps({"kind": "tool_call", "text": text}),
+ metadata_json="{}",
+ source="agent",
+ created_at=created_at,
+ updated_at=created_at,
+ )
+ )
+
+
+def test_done_failed_interrupted_and_trailing_groups(isolated_state):
+ engine = create_sqlite_engine()
+ sid = "ses_act"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ # Turn 1 — done: user, assistant, tool_call, result.
+ _msg(conn, scope, sid, mid="m_u1", mtype="user", author="user", created_at="2026-06-01T10:00:00.000000+00:00", text="q1", source="user")
+ _msg(conn, scope, sid, mid="m_a1", mtype="assistant", author="agent", created_at="2026-06-01T10:00:01.000000+00:00", text="thinking")
+ _evt(conn, scope, sid, eid="e_t1", created_at="2026-06-01T10:00:02Z", text="🔧 `Bash` `{\"command\":\"ls\"}`")
+ _msg(conn, scope, sid, mid="m_r1", mtype="result", author="agent", created_at="2026-06-01T10:00:03.000000+00:00", text="answer 1")
+ # Turn 2 — no activity: user + result only → no group.
+ _msg(conn, scope, sid, mid="m_u2", mtype="user", author="user", created_at="2026-06-01T10:01:00.000000+00:00", text="q2", source="user")
+ _msg(conn, scope, sid, mid="m_r2", mtype="result", author="agent", created_at="2026-06-01T10:01:01.000000+00:00", text="answer 2")
+ # Turn 3 — failed: user, tool_call, error.
+ _msg(conn, scope, sid, mid="m_u3", mtype="user", author="user", created_at="2026-06-01T10:02:00.000000+00:00", text="q3", source="user")
+ _evt(conn, scope, sid, eid="e_t3", created_at="2026-06-01T10:02:01Z", text="🔧 `Read` `{\"path\":\"x\"}`")
+ _msg(conn, scope, sid, mid="m_er3", mtype="error", author="agent", created_at="2026-06-01T10:02:02.000000+00:00", text="boom")
+ # Turn 4 — interrupted (no terminal), then Turn 5 opens.
+ _msg(conn, scope, sid, mid="m_u4", mtype="user", author="user", created_at="2026-06-01T10:03:00.000000+00:00", text="q4", source="user")
+ _msg(conn, scope, sid, mid="m_a4", mtype="assistant", author="agent", created_at="2026-06-01T10:03:01.000000+00:00", text="partial")
+ # Turn 5 — trailing interrupted (activity, no terminal, end of session).
+ _msg(conn, scope, sid, mid="m_u5", mtype="user", author="user", created_at="2026-06-01T10:04:00.000000+00:00", text="q5", source="user")
+ _evt(conn, scope, sid, eid="e_t5", created_at="2026-06-01T10:04:01Z", text="🔧 `Bash` `{\"command\":\"sleep\"}`")
+
+ with engine.connect() as conn:
+ summary = agent_activity_service.list_turn_groups(conn, session_id=sid)
+ groups = summary["groups"]
+ # Turn 2 has no activity → excluded. So 4 groups: done, failed, interrupted, trailing.
+ assert [g["status"] for g in groups] == ["done", "failed", "interrupted", "interrupted"]
+
+ done = groups[0]
+ assert done["anchor_message_id"] == "m_r1"
+ assert done["steps"] == 2 # assistant + tool_call
+ assert done["duration_ms"] == 3000 # 10:00:00 → 10:00:03 (turn start → terminal)
+
+ failed = groups[1]
+ assert failed["anchor_message_id"] == "m_er3"
+ assert failed["steps"] == 1
+
+ interrupted = groups[2]
+ # Anchored at the NEXT turn's opening message (chip sits above it).
+ assert interrupted["anchor_message_id"] == "m_u5"
+ assert interrupted["steps"] == 1
+
+ trailing = groups[3]
+ assert trailing["anchor_message_id"] is None # trails the transcript
+ assert trailing["steps"] == 1
+
+ # ``id`` is the first activity row's id (stable key for lazy detail).
+ assert done["id"] == "m_a1"
+ assert failed["id"] == "e_t3"
+
+
+def test_rows_merge_across_tables_by_parsed_timestamp(isolated_state):
+ """A ``tool_call`` at ``...:02Z`` (= .000000) precedes an ``assistant`` at
+ ``...:02.500000+00:00`` in real time even though a raw string sort would
+ order them the other way — the group rows must reflect parsed order."""
+ engine = create_sqlite_engine()
+ sid = "ses_merge"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(conn, scope, sid, mid="m_u", mtype="user", author="user", created_at="2026-06-01T10:00:00.000000+00:00", text="q", source="user")
+ # Insert assistant FIRST so a naive/stable insertion order would be wrong.
+ _msg(conn, scope, sid, mid="m_a", mtype="assistant", author="agent", created_at="2026-06-01T10:00:02.500000+00:00", text="second")
+ _evt(conn, scope, sid, eid="e_t", created_at="2026-06-01T10:00:02Z", text="first")
+ _msg(conn, scope, sid, mid="m_r", mtype="result", author="agent", created_at="2026-06-01T10:00:05.000000+00:00", text="done")
+
+ with engine.connect() as conn:
+ detail = agent_activity_service.get_turn_group(conn, session_id=sid, group_id="e_t")
+ assert detail is not None
+ assert detail["status"] == "done"
+ assert detail["anchor_message_id"] == "m_r"
+ assert [(r["kind"], r["text"]) for r in detail["rows"]] == [
+ ("tool_call", "first"),
+ ("assistant", "second"),
+ ]
+
+
+def test_show_page_assistant_marks_are_not_activity(isolated_state):
+ engine = create_sqlite_engine()
+ sid = "ses_sp"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(conn, scope, sid, mid="m_u", mtype="user", author="user", created_at="2026-06-01T10:00:00.000000+00:00", text="q", source="user")
+ _msg(
+ conn, scope, sid, mid="m_sp", mtype="assistant", author="agent",
+ created_at="2026-06-01T10:00:01.000000+00:00", text="show page mark",
+ metadata={"source": "show_page"},
+ )
+ _msg(conn, scope, sid, mid="m_r", mtype="result", author="agent", created_at="2026-06-01T10:00:02.000000+00:00", text="done")
+
+ with engine.connect() as conn:
+ summary = agent_activity_service.list_turn_groups(conn, session_id=sid)
+ # The only ``assistant`` row is a Show-Page mark → no activity → no group.
+ assert summary["groups"] == []
+
+
+def test_same_second_tool_call_stays_in_completed_turn(isolated_state):
+ """A fast turn emits a tool_call and its terminal result in the SAME whole
+ second (both tables store second precision). The phase tiebreak must keep the
+ tool call inside the done group, not orphan it after the terminal."""
+ engine = create_sqlite_engine()
+ sid = "ses_ss"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(conn, scope, sid, mid="m_u", mtype="user", author="user", created_at="2026-06-01T10:00:00Z", text="q", source="user")
+ # tool_call and result both at :05Z — the tie the fix resolves.
+ _evt(conn, scope, sid, eid="e_t", created_at="2026-06-01T10:00:05Z", text="🔧 `Bash`")
+ _msg(conn, scope, sid, mid="m_r", mtype="result", author="agent", created_at="2026-06-01T10:00:05Z", text="answer")
+
+ with engine.connect() as conn:
+ summary = agent_activity_service.list_turn_groups(conn, session_id=sid)
+ groups = summary["groups"]
+ assert len(groups) == 1
+ assert groups[0]["status"] == "done"
+ assert groups[0]["anchor_message_id"] == "m_r"
+ assert groups[0]["steps"] == 1 # the tool_call belongs to THIS turn, not orphaned
+
+
+def _clock_id(prefix: str, micros: int) -> str:
+ """Realistic row id: ``<pfx>_<15-hex microsecond epoch><uuid8>`` (matches
+ messages_service / agent_events_service), so the grouping decodes emission order."""
+ return f"{prefix}_{micros:015x}{'0' * 8}"
+
+
+def test_back_to_back_turns_same_second_keep_done_status(isolated_state):
+ """Turn A's result and turn B's opener land in the SAME whole second. Ordering
+ by the id microsecond keeps A ``done`` (its result precedes B's opener) instead
+ of flipping A to ``interrupted`` anchored on B's prompt."""
+ engine = create_sqlite_engine()
+ sid = "ses_b2b"
+ base = 1_800_000_000_000_000 # arbitrary microsecond epoch
+ result_id = _clock_id("msg", base + 2_000_000)
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(conn, scope, sid, mid=_clock_id("msg", base), mtype="user", author="user", created_at="2026-06-01T10:00:00Z", text="q1", source="user")
+ _evt(conn, scope, sid, eid=_clock_id("evt", base + 1_000_000), created_at="2026-06-01T10:00:01Z", text="🔧 `Bash`")
+ # A's result and B's opener both at :02Z; the result was emitted ~1ms first.
+ _msg(conn, scope, sid, mid=result_id, mtype="result", author="agent", created_at="2026-06-01T10:00:02Z", text="answer 1")
+ _msg(conn, scope, sid, mid=_clock_id("msg", base + 2_001_000), mtype="user", author="user", created_at="2026-06-01T10:00:02Z", text="q2", source="user")
+ _evt(conn, scope, sid, eid=_clock_id("evt", base + 3_000_000), created_at="2026-06-01T10:00:03Z", text="🔧 `Read`")
+
+ with engine.connect() as conn:
+ summary = agent_activity_service.list_turn_groups(conn, session_id=sid)
+ groups = summary["groups"]
+ # A stays done (result precedes B's opener); B trails with its own tool call.
+ assert [g["status"] for g in groups] == ["done", "interrupted"]
+ assert groups[0]["anchor_message_id"] == result_id
+ assert groups[0]["steps"] == 1 # the Bash tool_call belongs to A, not orphaned to B
+
+
+def test_events_before_message_window_are_dropped(isolated_state):
+ """An event that predates the scanned message window (its turn boundary was not
+ fetched) must not be grouped, or it would anchor a bogus interrupted chip to the
+ first visible turn. Here the only event predates the oldest message."""
+ engine = create_sqlite_engine()
+ sid = "ses_win"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ # Event an hour before the oldest scanned message → outside the window.
+ _evt(conn, scope, sid, eid="e_old", created_at="2026-06-01T09:00:00Z", text="🔧 `Bash`")
+ _msg(conn, scope, sid, mid="m_u", mtype="user", author="user", created_at="2026-06-01T10:00:00Z", text="q", source="user")
+ _msg(conn, scope, sid, mid="m_r", mtype="result", author="agent", created_at="2026-06-01T10:00:01Z", text="answer")
+
+ with engine.connect() as conn:
+ summary = agent_activity_service.list_turn_groups(conn, session_id=sid)
+ # The stale pre-window event is dropped; the user+result turn has no activity.
+ assert summary["groups"] == []
+
+
+def test_same_second_pre_window_event_dropped_by_id(isolated_state):
+ """A tool event in the SAME whole second as the oldest scanned message, but
+ emitted BEFORE it (smaller microsecond id), is outside the window and must be
+ dropped — the whole-second cutoff alone would wrongly keep it."""
+ engine = create_sqlite_engine()
+ sid = "ses_winid"
+ base = 1_800_000_000_000_000
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ # Event emitted a millisecond BEFORE the oldest message, same second.
+ _evt(conn, scope, sid, eid=_clock_id("evt", base + 1_000), created_at="2026-06-01T10:00:00Z", text="🔧 `Bash`")
+ _msg(conn, scope, sid, mid=_clock_id("msg", base + 5_000), mtype="user", author="user", created_at="2026-06-01T10:00:00Z", text="q", source="user")
+ _msg(conn, scope, sid, mid=_clock_id("msg", base + 10_000), mtype="result", author="agent", created_at="2026-06-01T10:00:00Z", text="answer")
+
+ with engine.connect() as conn:
+ summary = agent_activity_service.list_turn_groups(conn, session_id=sid)
+ # The pre-window event is dropped → the user+result turn has no activity.
+ assert summary["groups"] == []
+
+
+def test_duration_measured_from_turn_opener(isolated_state):
+ """The chip duration spans the turn opener → terminal (what the history endpoint
+ reports), not first-activity → terminal — so live and reloaded chips agree."""
+ engine = create_sqlite_engine()
+ sid = "ses_dur"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(conn, scope, sid, mid="m_u", mtype="user", author="user", created_at="2026-06-01T10:00:00Z", text="q", source="user")
+ _evt(conn, scope, sid, eid="e_t", created_at="2026-06-01T10:00:05Z", text="🔧 `Bash`") # first activity 5s in
+ _msg(conn, scope, sid, mid="m_r", mtype="result", author="agent", created_at="2026-06-01T10:00:10Z", text="answer")
+
+ with engine.connect() as conn:
+ summary = agent_activity_service.list_turn_groups(conn, session_id=sid)
+ assert len(summary["groups"]) == 1
+ # 10s opener→terminal, NOT 5s first-activity→terminal.
+ assert summary["groups"][0]["duration_ms"] == 10_000
+
+
+def test_show_page_user_marks_do_not_split_a_turn(isolated_state):
+ """A Show-Page annotation persists as a user row mid-turn; it must NOT be treated
+ as a turn opener (which would mark the turn interrupted and orphan its terminal)."""
+ engine = create_sqlite_engine()
+ sid = "ses_spuser"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(conn, scope, sid, mid="m_u", mtype="user", author="user", created_at="2026-06-01T10:00:00Z", text="q", source="user")
+ _evt(conn, scope, sid, eid="e_1", created_at="2026-06-01T10:00:01Z", text="🔧 `Bash`")
+ # A Show-Page user mark lands WHILE the turn is still producing activity.
+ _msg(
+ conn, scope, sid, mid="m_sp", mtype="user", author="user",
+ created_at="2026-06-01T10:00:02Z", text="pinned an element", source="user",
+ metadata={"source": "show_page"},
+ )
+ _evt(conn, scope, sid, eid="e_2", created_at="2026-06-01T10:00:03Z", text="🔧 `Read`")
+ _msg(conn, scope, sid, mid="m_r", mtype="result", author="agent", created_at="2026-06-01T10:00:04Z", text="answer")
+
+ with engine.connect() as conn:
+ summary = agent_activity_service.list_turn_groups(conn, session_id=sid)
+ groups = summary["groups"]
+ # One done group with BOTH tool calls — the Show-Page mark did not split it.
+ assert [g["status"] for g in groups] == ["done"]
+ assert groups[0]["anchor_message_id"] == "m_r"
+ assert groups[0]["steps"] == 2
+
+
+def test_get_turn_group_unknown_id_returns_none(isolated_state):
+ engine = create_sqlite_engine()
+ sid = "ses_none"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(conn, scope, sid, mid="m_u", mtype="user", author="user", created_at="2026-06-01T10:00:00.000000+00:00", text="q", source="user")
+ _evt(conn, scope, sid, eid="e_t", created_at="2026-06-01T10:00:01Z", text="tool")
+ _msg(conn, scope, sid, mid="m_r", mtype="result", author="agent", created_at="2026-06-01T10:00:02.000000+00:00", text="done")
+
+ with engine.connect() as conn:
+ assert agent_activity_service.get_turn_group(conn, session_id=sid, group_id="nope") is None
+ found = agent_activity_service.get_turn_group(conn, session_id=sid, group_id="e_t")
+ assert found is not None and found["steps"] == 1
diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.py
index 8bc62a9fb..9daea818d 100644
--- a/tests/test_message_mirror.py
+++ b/tests/test_message_mirror.py
@@ -473,6 +473,112 @@ def test_persist_agent_toolcall_avibe_writes_event_without_streaming(isolated_st
assert event_row["content_text"] == "Tool input failed to parse"
+def test_persist_agent_toolcall_publishes_when_activity_enabled(isolated_state, monkeypatch):
+ """With ``show_agent_activity`` on, a ``tool_call`` fans out a synthesized
+ ``message.new`` (type='tool_call') so an open Chat page's activity panel shows
+ the step live — while still landing ONLY in ``agent_events`` (not ``messages``)
+ and never bumping the inbox."""
+ import core.message_mirror as mm
+ from core import inbox_events
+
+ monkeypatch.setattr(mm, "_activity_streaming_enabled", lambda: True)
+
+ engine = create_sqlite_engine()
+ now = "2026-05-30T12:00:00Z"
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_ta", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_ta", scope_id=scope_id, agent_name="Atlas", agent_backend="claude",
+ agent_variant="default", session_anchor="anchor_ses_ta", native_session_id="",
+ status="active", metadata_json="{}", created_at=now, updated_at=now, last_active_at=now,
+ )
+ )
+
+ ctx = MessageContext(
+ user_id="workbench", channel_id="ses_ta", platform="avibe",
+ platform_specific={"agent_session_id": "ses_ta", "turn_token": "turn_9"},
+ )
+
+ async def scenario():
+ sub_id, queue = inbox_events.bus.subscribe()
+ events: dict[str, dict] = {}
+ try:
+ persist_agent_message(ctx, "tool_call", "🔧 `Bash` `{\"command\":\"ls\"}`")
+ evt = await asyncio.wait_for(queue.get(), timeout=1.0)
+ events[evt[0]] = evt[1]
+ # Only ONE event — no inbox bump for a trace row.
+ with pytest.raises(asyncio.TimeoutError):
+ await asyncio.wait_for(queue.get(), timeout=0.1)
+ finally:
+ inbox_events.bus.unsubscribe(sub_id)
+ return events
+
+ events = asyncio.run(scenario())
+ assert "message.new" in events and "inbox.session.updated" not in events
+ msg = events["message.new"]
+ assert msg["type"] == "tool_call"
+ assert msg["session_id"] == "ses_ta"
+ assert msg["author"] == "agent"
+ assert msg["text"] == "🔧 `Bash` `{\"command\":\"ls\"}`"
+
+ # Still a trace event only — no messages row.
+ with engine.connect() as conn:
+ assert conn.execute(select(messages).where(messages.c.session_id == "ses_ta")).first() is None
+ assert conn.execute(select(agent_events).where(agent_events.c.session_id == "ses_ta")).first() is not None
+
+
+def test_persist_agent_assistant_publishes_when_activity_enabled(isolated_state, monkeypatch):
+ """With ``show_agent_activity`` on, an interim ``assistant`` row streams as
+ ``message.new`` (type='assistant') for the activity panel, but still does NOT
+ bump the inbox (process log, not a reply)."""
+ import core.message_mirror as mm
+ from core import inbox_events
+ from storage import messages_service
+
+ monkeypatch.setattr(mm, "_activity_streaming_enabled", lambda: True)
+
+ engine = create_sqlite_engine()
+ now = "2026-05-30T12:00:00Z"
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_ia", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_ia", scope_id=scope_id, agent_backend="claude", agent_variant="default",
+ session_anchor="anchor_ses_ia", native_session_id="", status="active",
+ metadata_json="{}", created_at=now, updated_at=now, last_active_at=now,
+ )
+ )
+
+ ctx = MessageContext(
+ user_id="workbench", channel_id="ses_ia", platform="avibe",
+ platform_specific={"agent_session_id": "ses_ia"},
+ )
+
+ async def scenario():
+ sub_id, queue = inbox_events.bus.subscribe()
+ events: dict[str, dict] = {}
+ try:
+ persist_agent_message(ctx, "assistant", "thinking out loud")
+ evt = await asyncio.wait_for(queue.get(), timeout=1.0)
+ events[evt[0]] = evt[1]
+ with pytest.raises(asyncio.TimeoutError):
+ await asyncio.wait_for(queue.get(), timeout=0.1)
+ finally:
+ inbox_events.bus.unsubscribe(sub_id)
+ return events
+
+ events = asyncio.run(scenario())
+ assert "message.new" in events and "inbox.session.updated" not in events
+ assert events["message.new"]["type"] == "assistant"
+ assert events["message.new"]["text"] == "thinking out loud"
+
+ # Persisted as an assistant row (unchanged from the off case).
+ with engine.connect() as conn:
+ every = messages_service.list_session_messages(conn, session_id="ses_ia", types=("assistant",))
+ assert [m["type"] for m in every["messages"]] == ["assistant"]
+
+
def test_persist_system_message_is_not_persisted(isolated_state):
"""A canonical ``system`` message (init banner / status line — generated by
us, not the agent) is NOT persisted at all and publishes nothing (user
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 29b8e88ee..ad53fbc69 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -77,6 +77,64 @@ def test_status_endpoint_uses_fast_runtime_status(monkeypatch):
assert calls == [False]
+def test_sessions_activity_endpoint_summary_detail_and_404(monkeypatch, tmp_path):
+ """GET /api/sessions/<id>/activity: summary (no params) lists turn groups;
+ ``?group_id=`` returns that group's rows; an unknown session is 404."""
+ import json as _json
+
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_events, agent_sessions, messages
+ from storage.settings_service import upsert_scope
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ sid = "ses_ep"
+ with engine.begin() as conn:
+ scope = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_ep", now="2026-06-01T10:00:00Z")
+ conn.execute(agent_sessions.insert().values(
+ id=sid, scope_id=scope, agent_backend="claude", agent_variant="default",
+ session_anchor="anchor_ep", native_session_id="", status="active",
+ metadata_json="{}", created_at="2026-06-01T10:00:00Z", updated_at="2026-06-01T10:00:00Z",
+ last_active_at="2026-06-01T10:00:00Z",
+ ))
+
+ def _m(mid, mtype, author, ts, text):
+ conn.execute(messages.insert().values(
+ id=mid, scope_id=scope, session_id=sid, platform="avibe", author=author,
+ type=mtype, source=("user" if author == "user" else "agent"), content_text=text,
+ content_json="{}", metadata_json="{}", created_at=ts, updated_at=ts,
+ ))
+
+ _m("m_u", "user", "user", "2026-06-01T10:00:00.000000+00:00", "q")
+ _m("m_a", "assistant", "agent", "2026-06-01T10:00:01.000000+00:00", "thinking")
+ conn.execute(agent_events.insert().values(
+ id="e_t", scope_id=scope, session_id=sid, platform="avibe", event_type="tool_call",
+ visibility="trace", content_text="🔧 `Bash`", content_json=_json.dumps({"kind": "tool_call", "text": "🔧 `Bash`"}),
+ metadata_json="{}", source="agent", created_at="2026-06-01T10:00:02Z", updated_at="2026-06-01T10:00:02Z",
+ ))
+ _m("m_r", "result", "agent", "2026-06-01T10:00:03.000000+00:00", "answer")
+
+ client = app.test_client()
+
+ summary = client.get(f"/api/sessions/{sid}/activity")
+ assert summary.status_code == 200
+ groups = summary.get_json()["groups"]
+ assert len(groups) == 1
+ assert groups[0]["status"] == "done"
+ assert groups[0]["anchor_message_id"] == "m_r"
+ assert groups[0]["steps"] == 2
+ group_id = groups[0]["id"]
+
+ detail = client.get(f"/api/sessions/{sid}/activity?group_id={group_id}")
+ assert detail.status_code == 200
+ rows = detail.get_json()["rows"]
+ assert [r["kind"] for r in rows] == ["assistant", "tool_call"]
+
+ assert client.get(f"/api/sessions/{sid}/activity?group_id=nope").status_code == 404
+ assert client.get("/api/sessions/ses_missing/activity").status_code == 404
+
+
def test_doctor_post_runs_fast_diagnostics_by_default(monkeypatch):
from vibe import cli
diff --git a/tests/test_v2_config_platform_registry.py b/tests/test_v2_config_platform_registry.py
index 85e97441a..d4555e57b 100644
--- a/tests/test_v2_config_platform_registry.py
+++ b/tests/test_v2_config_platform_registry.py
@@ -268,6 +268,31 @@ def test_chat_message_font_size_is_clamped() -> None:
assert config.ui.chat_message_font_size == 14
+def test_show_agent_activity_defaults_off_and_round_trips() -> None:
+ # Default off: absent from the ui payload → False, and serializes into the
+ # payload so the Web UI + ChatPage bootstrap can read it (like the font size).
+ payload = api.config_to_payload(_base_config())
+ assert payload["ui"]["show_agent_activity"] is False
+
+ payload["ui"]["show_agent_activity"] = True
+ config = V2Config.from_payload(payload)
+ assert config.ui.show_agent_activity is True
+ assert api.config_to_payload(config)["ui"]["show_agent_activity"] is True
+
+ # Non-bool values coerce to a real bool (config file hand-edit robustness).
+ payload["ui"]["show_agent_activity"] = 1
+ assert V2Config.from_payload(payload).ui.show_agent_activity is True
+
+ # String forms are parsed explicitly — ``bool("false")`` would be True, which
+ # must NOT enable streaming. Known truthy/falsey strings resolve correctly.
+ for truthy in ("true", "True", "1", "yes", "on"):
+ payload["ui"]["show_agent_activity"] = truthy
+ assert V2Config.from_payload(payload).ui.show_agent_activity is True, truthy
+ for falsey in ("false", "False", "0", "no", "off", ""):
+ payload["ui"]["show_agent_activity"] = falsey
+ assert V2Config.from_payload(payload).ui.show_agent_activity is False, falsey
+
+
def test_config_payload_includes_vibe_cloud_remote_access() -> None:
config = _base_config()
config.remote_access.vibe_cloud.enabled = True
diff --git a/ui/src/components/settings/SettingsMessagingPage.tsx b/ui/src/components/settings/SettingsMessagingPage.tsx
index d4e3f7e41..721d9dd48 100644
--- a/ui/src/components/settings/SettingsMessagingPage.tsx
+++ b/ui/src/components/settings/SettingsMessagingPage.tsx
@@ -486,6 +486,27 @@ export const SettingsMessagingPage: React.FC = () => {
</div>
}
/>
+
+ <SettingsRow
+ title={t('dashboard.showAgentActivity')}
+ description={t('dashboard.showAgentActivityHint')}
+ control={
+ <ToggleSwitch
+ enabled={Boolean(config.ui?.show_agent_activity)}
+ onClick={() => {
+ const next = !config.ui?.show_agent_activity;
+ // Same path as the font size: full ui in local state, minimal
+ // ``ui`` patch on the wire (save_config deep-merges, so other ui
+ // fields are preserved).
+ const nextConfig = {
+ ...config,
+ ui: { ...(config.ui || {}), show_agent_activity: next },
+ };
+ void persist(nextConfig, { ui: { show_agent_activity: next } });
+ }}
+ />
+ }
+ />
</SettingsPanel>
<SettingsPanel
diff --git a/ui/src/components/workbench/AgentActivityGroup.tsx b/ui/src/components/workbench/AgentActivityGroup.tsx
new file mode 100644
index 000000000..1f229b6c3
--- /dev/null
+++ b/ui/src/components/workbench/AgentActivityGroup.tsx
@@ -0,0 +1,303 @@
+import { memo, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import {
+ AlertTriangle,
+ Bot,
+ CheckCircle2,
+ ChevronDown,
+ ChevronRight,
+ CircleSlash,
+ FileText,
+ Globe,
+ Loader2,
+ Pencil,
+ Sparkles,
+ Terminal,
+ Wrench,
+} from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
+import clsx from 'clsx';
+
+import { Markdown } from '../ui/markdown';
+import {
+ activityDurationParts,
+ parseToolName,
+ toolIconKind,
+ toolSummary,
+ type ActivityGroup,
+ type ActivityRow,
+ type ActivityStatus,
+ type ToolIconKind,
+} from '../../lib/agentActivity';
+
+// Shared status → icon + tint. ``running`` and ``done`` are mint (success family),
+// ``failed`` destructive, ``interrupted`` gold — mirrors the design states A–E.
+const STATUS_TINT: Record<ActivityStatus, string> = {
+ running: 'text-mint',
+ done: 'text-mint',
+ failed: 'text-destructive',
+ interrupted: 'text-gold',
+};
+
+// Static tool-icon table (looked up by kind, never constructed during render).
+const TOOL_ICON: Record<ToolIconKind, LucideIcon> = {
+ terminal: Terminal,
+ edit: Pencil,
+ file: FileText,
+ web: Globe,
+ agent: Bot,
+ wrench: Wrench,
+};
+
+const stepLabel = (t: (k: string, o?: Record<string, unknown>) => string, count: number): string =>
+ t(count === 1 ? 'chat.agentActivity.step' : 'chat.agentActivity.steps', { count });
+
+// ----- One tool-call row: icon + tool name (mono) + one-line summary; click to
+// reveal the full stored call text (from agent_events.content_json). -----
+const ActivityToolRow: React.FC<{ row: ActivityRow }> = ({ row }) => {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const name = parseToolName(row.text);
+ const summary = toolSummary(row.text);
+ const Icon = TOOL_ICON[toolIconKind(name)];
+ return (
+ <div className="flex flex-col">
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ title={open ? t('chat.agentActivity.hideCall') : t('chat.agentActivity.showCall')}
+ className="group/act flex w-full items-center gap-2 rounded-md px-1.5 py-1 text-left transition-colors hover:bg-foreground/[0.04]"
+ >
+ <Icon className="size-3.5 shrink-0 text-muted" aria-hidden="true" />
+ <span className="shrink-0 font-mono text-[11px] font-medium text-foreground">{name || '—'}</span>
+ {summary ? (
+ <span className="min-w-0 flex-1 truncate text-[12px] text-muted">{summary}</span>
+ ) : (
+ <span className="min-w-0 flex-1" />
+ )}
+ <ChevronRight
+ className={clsx('size-3.5 shrink-0 text-muted transition-transform', open && 'rotate-90')}
+ aria-hidden="true"
+ />
+ </button>
+ {open && (
+ <pre className="mx-1.5 mb-1 mt-0.5 max-h-56 overflow-auto whitespace-pre-wrap break-words rounded-md border border-border bg-foreground/[0.03] px-2.5 py-2 font-mono text-[11px] leading-relaxed text-muted">
+ {row.text}
+ </pre>
+ )}
+ </div>
+ );
+};
+
+// ----- One interim assistant row: sparkles + full text (owner decision), the
+// existing Markdown renderer in a compact style. -----
+const ActivityAssistantRow: React.FC<{ row: ActivityRow }> = ({ row }) => (
+ <div className="flex items-start gap-2 px-1.5 py-1">
+ <Sparkles className="mt-0.5 size-3.5 shrink-0 text-mint" aria-hidden="true" />
+ <div className="min-w-0 flex-1 text-[12px] leading-relaxed text-foreground/90 [&_p]:my-0.5 [&_pre]:max-w-full [&_pre]:overflow-x-auto">
+ {row.text ? (
+ <Markdown content={row.text} className="vr-markdown--inherit-size" />
+ ) : (
+ <span className="text-muted">—</span>
+ )}
+ </div>
+ </div>
+);
+
+const ActivityRowItem = memo(function ActivityRowItem({ row }: { row: ActivityRow }) {
+ return row.kind === 'tool_call' ? <ActivityToolRow row={row} /> : <ActivityAssistantRow row={row} />;
+});
+
+const ActivityRows: React.FC<{ rows: ActivityRow[] }> = ({ rows }) => (
+ <div className="flex flex-col gap-0.5">
+ {rows.map((row) => (
+ <ActivityRowItem key={row.id} row={row} />
+ ))}
+ </div>
+);
+
+// ===== Running card (states A/B): compact fixed-height viewport that never grows,
+// or an expanded ~40vh internal scroller that auto-follows the tail. =====
+export const ActivityCard: React.FC<{
+ rows: ActivityRow[];
+ startedAtMs: number | null;
+ expanded: boolean;
+ onToggleExpanded: () => void;
+}> = ({ rows, startedAtMs, expanded, onToggleExpanded }) => {
+ const { t } = useTranslation();
+ const [nowMs, setNowMs] = useState(() => Date.now());
+ // Fallback start if the turn's start time is unknown (defensive — the card only
+ // shows once a live row has set it): the card's mount time.
+ const [mountedAt] = useState(() => Date.now());
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const [following, setFollowing] = useState(true);
+
+ // Tick the elapsed clock once a second while mounted (the card only mounts
+ // while a live turn is running).
+ useEffect(() => {
+ const id = window.setInterval(() => setNowMs(Date.now()), 1000);
+ return () => window.clearInterval(id);
+ }, []);
+
+ // Auto-follow the tail in the expanded scroller unless the reader scrolled up.
+ useEffect(() => {
+ if (expanded && following && scrollRef.current) {
+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
+ }
+ }, [rows.length, expanded, following]);
+
+ const elapsedMs = Math.max(0, nowMs - (startedAtMs ?? mountedAt));
+ const mm = Math.floor(elapsedMs / 60000);
+ const ss = Math.floor((elapsedMs % 60000) / 1000);
+ const clock = `${String(mm).padStart(2, '0')}:${String(ss).padStart(2, '0')}`;
+
+ return (
+ <div className="flex w-full justify-start">
+ <div className="flex w-full max-w-[min(92%,860px)] flex-col overflow-hidden rounded-2xl rounded-tl-md border border-mint/25 bg-background">
+ {/* Header — click toggles compact ↔ expanded (design interaction rule). */}
+ <button
+ type="button"
+ onClick={onToggleExpanded}
+ aria-expanded={expanded}
+ className="flex items-center gap-2 border-b border-mint/20 bg-mint/[0.09] px-3 py-2 text-left"
+ >
+ <Loader2 className="size-3.5 shrink-0 animate-spin text-mint" aria-hidden="true" />
+ <span className="text-[12px] font-medium text-mint">{t('chat.agentActivity.running')}</span>
+ {rows.length > 0 && (
+ <span className="text-[12px] text-muted">· {stepLabel(t, rows.length)}</span>
+ )}
+ <span className="ml-auto shrink-0 font-mono text-[11px] text-muted">{clock}</span>
+ <ChevronDown
+ className={clsx('size-3.5 shrink-0 text-muted transition-transform', expanded && 'rotate-180')}
+ aria-hidden="true"
+ />
+ </button>
+ {expanded ? (
+ <div className="relative">
+ <div
+ ref={scrollRef}
+ onScroll={() => {
+ const el = scrollRef.current;
+ if (!el) return;
+ setFollowing(el.scrollHeight - el.scrollTop - el.clientHeight < 40);
+ }}
+ className="max-h-[40vh] overflow-y-auto px-1.5 py-1.5 [overflow-anchor:none]"
+ >
+ <ActivityRows rows={rows} />
+ </div>
+ {!following && (
+ <button
+ type="button"
+ onClick={() => {
+ const el = scrollRef.current;
+ if (el) el.scrollTop = el.scrollHeight;
+ setFollowing(true);
+ }}
+ className="absolute bottom-2 left-1/2 -translate-x-1/2 rounded-full border border-mint/40 bg-background/90 px-2.5 py-1 text-[11px] font-medium text-mint shadow-sm backdrop-blur"
+ >
+ {t('chat.agentActivity.jumpToLatest')}
+ </button>
+ )}
+ </div>
+ ) : (
+ // Compact: a fixed ~110px viewport, content pinned to the bottom so the
+ // newest rows show and older rows are clipped + faded upward. The box
+ // never grows → no transcript reflow.
+ <div className="relative h-[110px] overflow-hidden">
+ <div className="flex h-full flex-col justify-end px-1.5 py-1.5">
+ <ActivityRows rows={rows} />
+ </div>
+ <div className="pointer-events-none absolute inset-x-0 top-0 h-8 bg-gradient-to-b from-background to-transparent" />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
+// ===== Collapsed chip (states C/D/E): a one-line summary that hugs the reply from
+// above; click to expand the stored rows (lazy-loaded by the parent). =====
+export const ActivityChip: React.FC<{
+ group: ActivityGroup;
+ expanded: boolean;
+ loading: boolean;
+ error?: boolean;
+ onToggle: () => void;
+ onRetry?: () => void;
+}> = ({ group, expanded, loading, error, onToggle, onRetry }) => {
+ const { t } = useTranslation();
+ const StatusIcon =
+ group.status === 'failed' ? AlertTriangle : group.status === 'interrupted' ? CircleSlash : CheckCircle2;
+
+ let label: string;
+ if (group.status === 'failed') {
+ label = t('chat.agentActivity.failed', { count: group.steps });
+ } else if (group.status === 'interrupted') {
+ label = t('chat.agentActivity.interrupted', { count: group.steps });
+ } else {
+ const parts = activityDurationParts(group.durationMs);
+ const duration = parts
+ ? parts.minutes > 0
+ ? t('chat.agentActivity.durationMin', { minutes: parts.minutes, seconds: parts.seconds })
+ : t('chat.agentActivity.durationSec', { seconds: parts.seconds })
+ : '';
+ label = `${t('chat.agentActivity.label')} · ${stepLabel(t, group.steps)}${duration ? ` · ${duration}` : ''}`;
+ }
+
+ return (
+ <div className="flex w-full justify-start">
+ <div className="flex w-full max-w-[min(92%,860px)] flex-col gap-1">
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-expanded={expanded}
+ title={expanded ? t('chat.agentActivity.collapse') : t('chat.agentActivity.expand')}
+ className={clsx(
+ 'inline-flex w-fit max-w-full items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] transition-colors',
+ group.status === 'failed'
+ ? 'border-destructive/30 bg-destructive/[0.06] hover:bg-destructive/[0.1]'
+ : group.status === 'interrupted'
+ ? 'border-gold/30 bg-gold/[0.07] hover:bg-gold/[0.12]'
+ : 'border-mint/25 bg-mint/[0.07] hover:bg-mint/[0.12]',
+ )}
+ >
+ <StatusIcon className={clsx('size-3.5 shrink-0', STATUS_TINT[group.status])} aria-hidden="true" />
+ <span className="min-w-0 truncate font-medium text-foreground/90">{label}</span>
+ <ChevronDown
+ className={clsx('size-3.5 shrink-0 text-muted transition-transform', expanded && 'rotate-180')}
+ aria-hidden="true"
+ />
+ </button>
+ {expanded && (
+ <div className="w-full rounded-xl rounded-tl-md border border-border bg-foreground/[0.02] px-1.5 py-1.5">
+ {loading ? (
+ <div className="flex items-center justify-center py-3 text-muted">
+ <Loader2 className="size-4 animate-spin" />
+ </div>
+ ) : group.rows && group.rows.length > 0 ? (
+ <ActivityRows rows={group.rows} />
+ ) : error ? (
+ // A transient detail-fetch failure — show a retry, not a misleading
+ // "no activity", since the summary already counted steps.
+ <div className="flex items-center justify-between gap-2 px-1.5 py-2 text-[12px] text-muted">
+ <span>{t('chat.agentActivity.loadFailed')}</span>
+ {onRetry && (
+ <button
+ type="button"
+ onClick={onRetry}
+ className="shrink-0 rounded-md border border-border px-2 py-0.5 text-[11px] font-medium text-cyan transition-colors hover:bg-surface-2"
+ >
+ {t('chat.agentActivity.retry')}
+ </button>
+ )}
+ </div>
+ ) : (
+ <div className="px-1.5 py-2 text-[12px] text-muted">{t('chat.agentActivity.empty')}</div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 09f759d77..c663307b9 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -1,4 +1,4 @@
-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Activity, ArrowLeft, ArrowRight, Bell, Bot, ChevronDown, ChevronRight, Clock, Eye, GitFork, Info, Loader2, MessageSquare, Pencil, Presentation, Terminal, Undo2, UploadCloud, X } from 'lucide-react';
@@ -40,6 +40,20 @@ import { hasInAppBackEntry } from '../../lib/navigationHistory';
import { Composer, type ComposerAttachment, type ComposerHandle, type ComposerProps } from './Composer';
import type { MentionReference } from '../../lib/mentions';
import { QuickReplies } from './QuickReplies';
+import { ActivityCard, ActivityChip } from './AgentActivityGroup';
+import {
+ activityRowFromMessage,
+ groupFromWire,
+ initialLiveActivity,
+ isActivityMessageType,
+ liveActivityReducer,
+ shouldShowRunningCard,
+ type ActivityGroup,
+ type ActivityRow,
+ type LiveActivityEvent,
+ type LiveActivityState,
+ type TurnActivityGroupWire,
+} from '../../lib/agentActivity';
// While a turn is in flight, reconcile the working/Stop state against the
// controller on this cadence (the backend ``GET /turn-state`` is authoritative).
@@ -296,12 +310,62 @@ export const ChatPage: React.FC = () => {
// ``working`` = a turn is in flight for this session (from our send, or any
// other origin we observe). Drives the thinking bubble + the Send→Stop swap.
const [working, setWorking] = useState(false);
+ // Mirror ``working`` into a ref so recovery paths (reconcile) can tell the
+ // activity resync whether a turn is still in flight without re-running on it.
+ const workingRef = useRef(working);
+ workingRef.current = working;
const [runtimeState, setRuntimeState] = useState<SessionRuntimeState>(emptyRuntimeState);
// Global background-work banner toggle (spec req 2), persisted server-side.
// Tri-state: null = not yet known → suppress the banner so a stored "off"
// never flashes on first paint; resolves to the stored value (ON when absent),
// or ON on a fetch error so a transient failure can't hide live work.
const [bannerEnabled, setBannerEnabled] = useState<boolean | null>(null);
+ // Chat Agent Activity panel (config.ui.show_agent_activity). Default off = a
+ // strict no-op: the backend never streams assistant/tool_call rows and this UI
+ // never renders anything, so the transcript is byte-for-byte today's.
+ //
+ // SINGLE SOURCE OF TRUTH: the durable ``GET /api/sessions/<id>/activity`` endpoint
+ // owns ALL settled groups (done / failed / interrupted, their anchors, step
+ // counts, durations). The live SSE buffer drives ONLY the in-flight running card.
+ // On every settle signal (terminal message.new, turn.end, reconnect, visibility)
+ // we clear the buffer and rebuild groups from storage via ``refreshActivity`` —
+ // so a lossy/gappy stream can never corrupt a settled chip. There is deliberately
+ // NO client-side group reconstruction from the buffer.
+ // - ``activityGroups``: settled turns, set ONLY from the endpoint.
+ // - ``liveState``: the in-flight running-card buffer, a pure generation state
+ // machine (see ``liveActivityReducer``). ``liveStateRef`` is the synchronous
+ // source of truth; ``liveRows`` / ``liveStartedAt`` mirror it for rendering.
+ const [showAgentActivity, setShowAgentActivity] = useState(false);
+ const showAgentActivityRef = useRef(false);
+ showAgentActivityRef.current = showAgentActivity;
+ const [activityGroups, setActivityGroups] = useState<ActivityGroup[]>([]);
+ const liveStateRef = useRef<LiveActivityState>(initialLiveActivity());
+ const [liveRows, setLiveRows] = useState<ActivityRow[]>([]);
+ const [liveStartedAt, setLiveStartedAt] = useState<number | null>(null);
+ const [activityCardExpanded, setActivityCardExpanded] = useState(false);
+ const [expandedActivity, setExpandedActivity] = useState<Record<string, boolean>>({});
+ const [loadingActivity, setLoadingActivity] = useState<Record<string, boolean>>({});
+ // Groups whose lazy detail fetch failed — the chip shows a retry affordance
+ // instead of a misleading "no activity" empty state (transient endpoint failure).
+ const [activityError, setActivityError] = useState<Record<string, boolean>>({});
+ // Coalesce settle-triggered refreshes: a settle burst (terminal + turn.end) runs
+ // one in-flight refresh + at most one trailing refresh, never N fetches. A failed
+ // settle fetch schedules exactly one bounded retry (the next settle also rebuilds).
+ const activityRefreshInFlightRef = useRef(false);
+ const activityRefreshPendingRef = useRef(false);
+ const activityRunningRef = useRef(false);
+ const activityRetryTimerRef = useRef<number | null>(null);
+ // Latest ``scheduleActivityRefresh`` (assigned below) so its own async resolution
+ // can re-enter for the trailing / retry pass without a definition cycle.
+ const scheduleActivityRefreshRef = useRef<(running: boolean, isRetry?: boolean) => void>(() => {});
+ // Advance the live-buffer state machine + mirror it into render state. The ref is
+ // updated synchronously so same-tick reads (generation, settled) are current.
+ const dispatchLive = useCallback((event: LiveActivityEvent) => {
+ const next = liveActivityReducer(liveStateRef.current, event);
+ liveStateRef.current = next;
+ setLiveRows(next.rows);
+ setLiveStartedAt(next.startedAt);
+ }, []);
// Bumped on resume (tab visible again / network back) to force the transcript
// subscription effect to reopen a possibly-dead SSE stream — see the
// visibility effect below.
@@ -323,12 +387,110 @@ export const ChatPage: React.FC = () => {
const graceResyncRef = useRef<number | null>(null);
const syncTurnStateRef = useRef<(() => void) | null>(null);
// Mark a turn as live: bump the epoch + stamp the time, then show Stop. Used by
- // every "a turn is starting now" path so clear-on-idle stays race-safe.
+ // every "a turn is starting now" path so clear-on-idle stays race-safe. Also sets
+ // ``workingRef`` synchronously so a settle refresh in the same tick reads it.
const markWorking = useCallback(() => {
turnEpochRef.current += 1;
workingSetAtRef.current = Date.now();
+ workingRef.current = true;
setWorking(true);
}, []);
+
+ // ----- Agent Activity: the live buffer feeds ONLY the in-flight running card, as
+ // a pure generation state machine (see liveActivityReducer). Settled groups come
+ // exclusively from the durable endpoint (refreshActivity). -----
+ const ingestActivityRow = useCallback(
+ (msg: WorkbenchMessage) => {
+ dispatchLive({ type: 'row', row: activityRowFromMessage(msg), now: Date.now() });
+ },
+ [dispatchLive],
+ );
+ // Rebuild ALL settled groups from durable storage — the single source of truth —
+ // for the generation ``issuedGen`` this refresh was scheduled for. Returns false
+ // when the fetch fails so the caller can schedule a bounded retry. The live buffer
+ // is only touched when the resolution is still for the CURRENT generation (a newer
+ // turn.start bumped it → a late resolution is a structural no-op).
+ const refreshActivity = useCallback(
+ async (running: boolean, issuedGen: number): Promise<boolean> => {
+ const sid = sessionIdRef.current;
+ if (!sid || !showAgentActivityRef.current) return true;
+ let res: { groups: TurnActivityGroupWire[] };
+ try {
+ res = await api.getSessionActivity(sid);
+ } catch {
+ return false; // transient failure → caller retries; a stale card is hidden by the working gate
+ }
+ if (sid !== sessionIdRef.current) return true;
+ const fetched = (res.groups ?? []).map(groupFromWire);
+ const inflightIdx = running ? fetched.findIndex((g) => g.anchorMessageId === null) : -1;
+ const inflight = inflightIdx >= 0 ? fetched[inflightIdx] : null;
+ const groups = inflight ? fetched.filter((_, i) => i !== inflightIdx) : fetched;
+ // Settled groups are always safe to replace (storage is authoritative);
+ // preserve already-loaded rows so a resync doesn't force a re-fetch on expand.
+ setActivityGroups((prev) => {
+ const prevRows = new Map(prev.filter((g) => g.rows).map((g) => [g.id, g.rows] as const));
+ return groups.map((g) => (g.rows || !prevRows.has(g.id) ? g : { ...g, rows: prevRows.get(g.id) }));
+ });
+ if (inflight) {
+ // Still running: re-hydrate the card's rows only if the live stream hasn't
+ // already filled them (the reducer also drops a stale-generation rehydrate).
+ if (liveStateRef.current.rows.length === 0) {
+ try {
+ const wire = await api.getSessionActivityGroup(sid, inflight.id);
+ if (sid !== sessionIdRef.current) return true;
+ const rows = groupFromWire(wire).rows ?? [];
+ if (rows.length > 0) {
+ const startMs = Date.parse(rows[0].created_at);
+ dispatchLive({
+ type: 'rehydrate_for_gen',
+ gen: issuedGen,
+ rows,
+ startedAt: Number.isFinite(startMs) ? startMs : Date.now(),
+ });
+ }
+ } catch {
+ /* re-hydrate is best-effort; live streaming still fills the card */
+ }
+ }
+ } else {
+ // No in-flight turn: clear the finished buffer so the card swaps to its chip
+ // — but only if still the same generation (a newer turn's rows are kept).
+ dispatchLive({ type: 'clear_for_gen', gen: issuedGen });
+ }
+ return true;
+ },
+ [api, dispatchLive],
+ );
+ // Coalesce settle-triggered refreshes: one in-flight + at most one trailing (with
+ // the latest ``running`` and the current generation), never N fetches for a settle
+ // burst. On a transient fetch failure schedule exactly one bounded retry (the next
+ // settle also rebuilds). No fetch when the toggle is off (strict no-op).
+ const scheduleActivityRefresh = useCallback(
+ (running: boolean, isRetry = false) => {
+ if (!showAgentActivityRef.current) return;
+ activityRunningRef.current = running;
+ if (activityRefreshInFlightRef.current) {
+ activityRefreshPendingRef.current = true;
+ return;
+ }
+ activityRefreshInFlightRef.current = true;
+ const issuedGen = liveStateRef.current.gen;
+ void refreshActivity(activityRunningRef.current, issuedGen).then((ok) => {
+ activityRefreshInFlightRef.current = false;
+ if (activityRefreshPendingRef.current) {
+ activityRefreshPendingRef.current = false;
+ scheduleActivityRefreshRef.current(activityRunningRef.current, false);
+ } else if (ok === false && !isRetry && activityRetryTimerRef.current === null) {
+ activityRetryTimerRef.current = window.setTimeout(() => {
+ activityRetryTimerRef.current = null;
+ scheduleActivityRefreshRef.current(activityRunningRef.current, true);
+ }, 1500);
+ }
+ });
+ },
+ [refreshActivity],
+ );
+ scheduleActivityRefreshRef.current = scheduleActivityRefresh;
// Send-while-busy queue (messages sent while a turn runs, shown above the
// composer) + the loaded draft to seed the composer with.
const [queue, setQueue] = useState<WorkbenchMessage[]>([]);
@@ -478,7 +640,11 @@ export const ChatPage: React.FC = () => {
} catch {
/* keep the current transcript; the next reconnect retries */
}
- }, [api, sessionId]);
+ // Resync activity too: an SSE gap can drop the terminal/turn.end, so rebuild
+ // settled groups from storage (a recovered turn gets its chip; a still-running
+ // turn keeps/re-hydrates its card). Coalesced + no-op when the toggle is off.
+ scheduleActivityRefresh(workingRef.current);
+ }, [api, sessionId, scheduleActivityRefresh]);
// The send-while-busy queue (pending messages shown above the composer).
// Re-fetched on mount + on every ``queue.updated`` (enqueue / flush / remove).
@@ -542,11 +708,15 @@ export const ChatPage: React.FC = () => {
setMessages(tailMessages);
setOlderCursor(res.next_before_id ?? null);
setHistoricalWindow(false);
+ // Returning to the live tail from a historical window: activity ingestion was
+ // suppressed while scrolled away, so resync groups from storage — a turn that
+ // finished in history still gets its chip without a full reload.
+ scheduleActivityRefresh(workingRef.current);
return true;
} catch {
return false;
}
- }, [api, sessionId]);
+ }, [api, sessionId, scheduleActivityRefresh]);
// Persist the composer's unsent text server-side (debounced) so it survives a
// reload / device switch. The send path clears it server-side; this only
@@ -614,7 +784,17 @@ export const ChatPage: React.FC = () => {
if (turnEpochRef.current !== epochAtRequest) return;
const sinceSet = Date.now() - workingSetAtRef.current;
if (sinceSet > WORKING_SETTLE_GRACE_MS) {
+ workingRef.current = false;
setWorking(false);
+ // Agent Activity: the idle poll recovering a dropped terminal/turn.end is a
+ // FIFTH settle signal (same contract as terminal message.new / turn.end /
+ // reconnect / visibility) — mark the generation settled and rebuild from
+ // storage so the finished turn gets its chip and the stale buffer clears.
+ // The card is already hidden by the working gate; this produces the chip.
+ if (showAgentActivityRef.current) {
+ dispatchLive({ type: 'settle' });
+ scheduleActivityRefresh(false);
+ }
} else if (graceResyncRef.current === null) {
// Idle INSIDE the grace: either the registration gap (don't clear) or a
// quick turn that already finished and whose turn.end we missed (a
@@ -628,7 +808,7 @@ export const ChatPage: React.FC = () => {
} catch {
/* controller unreachable — leave the indicator as-is */
}
- }, [api, sessionId, markWorking]);
+ }, [api, sessionId, markWorking, dispatchLive, scheduleActivityRefresh]);
// Keep a ref to the latest syncTurnState so the grace-resync timer can call the
// current closure without baking it into a dependency cycle.
@@ -651,11 +831,22 @@ export const ChatPage: React.FC = () => {
setAgents(bootstrap.agents);
setDefaultAgentName(bootstrap.default_agent_name);
setMessageFontSize(normalizeChatMessageFontSize(bootstrap.config?.ui?.chat_message_font_size));
+ const activityEnabled = Boolean(bootstrap.config?.ui?.show_agent_activity);
+ setShowAgentActivity(activityEnabled);
+ showAgentActivityRef.current = activityEnabled;
// Merge (not replace) so a row that arrived over the stream during the
// load isn't clobbered; the session-change reset keeps prior sessions out.
setMessages((prev) => mergeById(bootstrap.messages, prev));
setOlderCursor(bootstrap.next_before_id ?? null);
setHistoricalWindow(false);
+ // Chat Activity chips for past turns: resync the per-turn summary (row text
+ // lazy-loads on expand). If a turn is in flight, the refresh re-hydrates the
+ // running card instead of showing it as interrupted.
+ if (activityEnabled) {
+ scheduleActivityRefresh(bootstrap.turn_state.foreground === 'running');
+ } else {
+ setActivityGroups([]);
+ }
setQueue(bootstrap.queued ?? []);
setInitialDraft(bootstrap.draft?.text ?? '');
setRuntimeState(bootstrap.turn_state);
@@ -674,7 +865,7 @@ export const ChatPage: React.FC = () => {
// its own loading state into a premature not-found / error view (Codex P2).
if (sessionId === sessionIdRef.current) setLoading(false);
}
- }, [api, sessionId, markWorking]);
+ }, [api, sessionId, markWorking, scheduleActivityRefresh]);
// Clear per-session state the instant the session changes (React Router swaps
// only :sessionId, reusing this instance), before the new session's
@@ -710,6 +901,21 @@ export const ChatPage: React.FC = () => {
setRuntimeState(emptyRuntimeState());
setQueue([]);
setInitialDraft(null);
+ // Clear all Agent Activity state so the previous session's groups / live buffer
+ // never leak into the new chat (refresh re-reads the toggle + summary).
+ setActivityGroups([]);
+ liveStateRef.current = initialLiveActivity();
+ setLiveRows([]);
+ setLiveStartedAt(null);
+ setActivityCardExpanded(false);
+ setExpandedActivity({});
+ setLoadingActivity({});
+ setActivityError({});
+ activityRefreshPendingRef.current = false;
+ if (activityRetryTimerRef.current !== null) {
+ window.clearTimeout(activityRetryTimerRef.current);
+ activityRetryTimerRef.current = null;
+ }
// Drop any pending grace-resync so it can't fire against the new session.
if (graceResyncRef.current !== null) {
window.clearTimeout(graceResyncRef.current);
@@ -732,6 +938,17 @@ export const ChatPage: React.FC = () => {
// new chat (Codex P2).
onMessageNew: (msg) => {
if (msg.session_id !== sessionIdRef.current) return;
+ // Agent Activity rows (assistant / tool_call) only reach the browser when
+ // the toggle streams them (message_mirror). Route them to the running
+ // buffer — never the transcript. ``isTranscriptMessage`` already excludes
+ // them, so the feature-off path is unchanged. Show-Page marks are ALSO
+ // ``assistant`` rows but are transcript-visible (isTranscriptMessage keeps
+ // them) — let them fall through so they render in the chat, not the panel.
+ const isShowPage = (msg.metadata as { source?: string } | null)?.source === 'show_page';
+ if (showAgentActivityRef.current && isActivityMessageType(msg.type) && !isShowPage) {
+ if (!historicalWindowRef.current) ingestActivityRow(msg);
+ return;
+ }
if (!isTranscriptMessage(msg)) return;
if (historicalWindowRef.current) return;
// Reader scrolled up in an already-capped window: don't grow the DOM with a
@@ -744,6 +961,13 @@ export const ChatPage: React.FC = () => {
return;
}
appendMessage(msg);
+ // Agent Activity: a terminal reply settles the turn → mark the generation
+ // settled and rebuild groups from storage (chip, rows, status, duration all
+ // come from the endpoint, never the lossy live buffer).
+ if (showAgentActivityRef.current && isTerminalAgentMessage(msg)) {
+ dispatchLive({ type: 'settle' });
+ scheduleActivityRefresh(workingRef.current);
+ }
// Don't clear ``working`` from a result row here: with the queue, a
// result can belong to an EARLIER turn while a newer queued turn is
// already running, so clearing on it would hide Stop on the live turn
@@ -756,6 +980,10 @@ export const ChatPage: React.FC = () => {
// reading already in flight can't clear this freshly-started turn.
if (data.session_id === sessionIdRef.current) {
setRuntimeState((current) => ({ ...current, in_flight: true, foreground: 'running' }));
+ // Agent Activity: a new turn begins → bump the generation (fresh empty
+ // buffer). Any stale rows from the previous turn become invisible by
+ // construction and can never merge with the new turn's rows.
+ if (showAgentActivityRef.current) dispatchLive({ type: 'turn_start' });
markWorking();
}
},
@@ -765,7 +993,17 @@ export const ChatPage: React.FC = () => {
// no turn-duration timeout, so this only fires on a REAL terminal signal.
if (data.session_id === sessionIdRef.current) {
setRuntimeState((current) => ({ ...current, in_flight: false, foreground: 'idle' }));
+ workingRef.current = false;
setWorking(false);
+ // Agent Activity: the turn settled (result / error / interrupt) → mark the
+ // generation settled and rebuild from storage. running=false so a trailing
+ // (no-terminal) turn renders as its interrupted chip and the finished
+ // card's buffer clears — the interrupt case is covered structurally, with
+ // no client-side snapshot or grace timer.
+ if (showAgentActivityRef.current) {
+ dispatchLive({ type: 'settle' });
+ scheduleActivityRefresh(false);
+ }
// The first turn binds the native; pick it up so the header's backend
// lock engages without a reload. A failed first turn leaves no native
// (the refresh confirms that), keeping the backend switchable so the
@@ -810,7 +1048,7 @@ export const ChatPage: React.FC = () => {
},
}, { reconnect: connectionEpoch > 0 });
return disconnect;
- }, [api, sessionId, appendMessage, reconcile, refreshQueue, syncTurnState, refreshSessionRowUntilNativeBound, markWorking, connectionEpoch, goBack]);
+ }, [api, sessionId, appendMessage, reconcile, refreshQueue, syncTurnState, refreshSessionRowUntilNativeBound, markWorking, connectionEpoch, goBack, ingestActivityRow, scheduleActivityRefresh, dispatchLive]);
// Mobile tabs (the common case for IM users) get backgrounded mid-turn; the
// SSE feed can be suspended without a clean reconnect, dropping the reply.
@@ -1399,6 +1637,57 @@ export const ChatPage: React.FC = () => {
return urls;
}, [messages]);
+ // Agent Activity chips are positioned by anchor message id; a null-anchor group
+ // is the one interrupted turn that trails the transcript.
+ const activityByAnchor = useMemo(() => {
+ const map = new Map<string, ActivityGroup>();
+ for (const group of activityGroups) {
+ if (group.anchorMessageId) map.set(group.anchorMessageId, group);
+ }
+ return map;
+ }, [activityGroups]);
+ const trailingActivity = useMemo(
+ () => activityGroups.find((group) => group.anchorMessageId === null) ?? null,
+ [activityGroups],
+ );
+ // Lazy-load a group's rows from the endpoint (history chips arrive as summary
+ // only). On failure, record an error so the chip offers retry instead of showing
+ // a misleading "no activity" empty state.
+ const loadActivityDetail = useCallback(
+ (group: ActivityGroup) => {
+ if (!sessionId || loadingActivity[group.id]) return;
+ const sid = sessionId;
+ setLoadingActivity((prev) => ({ ...prev, [group.id]: true }));
+ setActivityError((prev) => (prev[group.id] ? { ...prev, [group.id]: false } : prev));
+ api
+ .getSessionActivityGroup(sid, group.id)
+ .then((wire) => {
+ if (sid !== sessionIdRef.current) return;
+ const full = groupFromWire(wire);
+ setActivityGroups((prev) =>
+ prev.map((g) => (g.id === group.id ? { ...g, rows: full.rows ?? [] } : g)),
+ );
+ })
+ .catch(() => {
+ if (sid === sessionIdRef.current) setActivityError((prev) => ({ ...prev, [group.id]: true }));
+ })
+ .finally(() => {
+ setLoadingActivity((prev) => ({ ...prev, [group.id]: false }));
+ });
+ },
+ [api, sessionId, loadingActivity],
+ );
+ // Toggle a chip open/closed; lazy-load its rows on first expand (live-completed
+ // groups already carry their rows, so no fetch there).
+ const toggleActivityGroup = useCallback(
+ (group: ActivityGroup) => {
+ const willExpand = !expandedActivity[group.id];
+ setExpandedActivity((prev) => ({ ...prev, [group.id]: willExpand }));
+ if (willExpand && !group.rows) loadActivityDetail(group);
+ },
+ [expandedActivity, loadActivityDetail],
+ );
+
if (!sessionId) {
return <ChatMissing onBack={goBack} />;
}
@@ -1541,6 +1830,20 @@ export const ChatPage: React.FC = () => {
onQuoteSelection={quoteSelectionToComposer}
onAskInNewSession={askInNewSession}
followingTailRef={followingTailRef}
+ activity={{
+ enabled: showAgentActivity,
+ byAnchor: activityByAnchor,
+ trailing: trailingActivity,
+ liveRows,
+ liveStartedAt,
+ cardExpanded: activityCardExpanded,
+ onToggleCard: () => setActivityCardExpanded((v) => !v),
+ expanded: expandedActivity,
+ loading: loadingActivity,
+ error: activityError,
+ onToggleGroup: toggleActivityGroup,
+ onRetryGroup: loadActivityDetail,
+ }}
footer={
sessionId ? (
<VaultChatRequests
@@ -2146,6 +2449,22 @@ interface TranscriptProps {
// tail. Lifted so the retained-window trim (ChatPage.appendMessage) can tell
// when dropping the oldest rows is safe (reader pinned to the bottom).
followingTailRef: React.MutableRefObject<boolean>;
+ // Agent Activity panel state (undefined-safe: when ``enabled`` is false the
+ // transcript renders exactly as before — the ThinkingBubble and nothing else).
+ activity?: {
+ enabled: boolean;
+ byAnchor: Map<string, ActivityGroup>;
+ trailing: ActivityGroup | null;
+ liveRows: ActivityRow[];
+ liveStartedAt: number | null;
+ cardExpanded: boolean;
+ onToggleCard: () => void;
+ expanded: Record<string, boolean>;
+ loading: Record<string, boolean>;
+ error: Record<string, boolean>;
+ onToggleGroup: (group: ActivityGroup) => void;
+ onRetryGroup: (group: ActivityGroup) => void;
+ };
// Rendered at the end of the scroll content, after the last message (e.g. the in-scroll
// vault request cards). Part of the timeline, so it scrolls with the conversation.
footer?: React.ReactNode;
@@ -2168,6 +2487,7 @@ const Transcript: React.FC<TranscriptProps> = ({
onQuoteSelection,
onAskInNewSession,
followingTailRef,
+ activity,
footer,
}) => {
const { t } = useTranslation();
@@ -2257,7 +2577,13 @@ const Transcript: React.FC<TranscriptProps> = ({
// an older Turn cannot clear Stop for a newer one.
const lastIsAgentTerminal =
messages.length > 0 && isTerminalAgentMessage(messages[messages.length - 1]);
- const showThinking = working && !lastIsAgentTerminal;
+ // The running Activity card replaces the ThinkingBubble. It renders only while a
+ // turn is in flight (``working``) AND the live buffer is non-empty and current-gen
+ // (round-4 clause). Gating on ``working`` makes a stale buffer — e.g. one left by
+ // a dropped turn.end that the idle poll recovered — invisible by construction.
+ const liveActive = !!activity?.enabled && activity.liveRows.length > 0;
+ const showActivityCard = shouldShowRunningCard(!!activity?.enabled, working, activity?.liveRows.length ?? 0);
+ const showThinking = working && !lastIsAgentTerminal && !liveActive;
const empty = messages.length === 0 && !working;
// Capture the topmost (partly) visible row as the restore anchor. Viewport-
@@ -2506,17 +2832,52 @@ const Transcript: React.FC<TranscriptProps> = ({
<Loader2 className="size-4 animate-spin" />
</div>
)}
- {messages.map((message) => (
- <MessageRow
- key={message.id}
- message={message}
- session={session}
- messageFontSize={messageFontSize}
- onQuickReply={onQuickReply}
- highlighted={message.id === highlightedId}
+ {messages.map((message) => {
+ // Agent Activity chip for the turn whose reply (or next opening
+ // message) is THIS row — rendered directly above it.
+ const chip = activity?.enabled ? activity.byAnchor.get(message.id) : undefined;
+ return (
+ <Fragment key={message.id}>
+ {chip && (
+ <ActivityChip
+ group={chip}
+ expanded={!!activity!.expanded[chip.id]}
+ loading={!!activity!.loading[chip.id]}
+ error={!!activity!.error[chip.id]}
+ onToggle={() => activity!.onToggleGroup(chip)}
+ onRetry={() => activity!.onRetryGroup(chip)}
+ />
+ )}
+ <MessageRow
+ message={message}
+ session={session}
+ messageFontSize={messageFontSize}
+ onQuickReply={onQuickReply}
+ highlighted={message.id === highlightedId}
+ />
+ </Fragment>
+ );
+ })}
+ {showActivityCard && activity ? (
+ <ActivityCard
+ rows={activity.liveRows}
+ startedAtMs={activity.liveStartedAt}
+ expanded={activity.cardExpanded}
+ onToggleExpanded={activity.onToggleCard}
/>
- ))}
- {showThinking && <ThinkingBubble session={session} />}
+ ) : showThinking ? (
+ <ThinkingBubble session={session} />
+ ) : null}
+ {activity?.enabled && activity.trailing && (
+ <ActivityChip
+ group={activity.trailing}
+ expanded={!!activity.expanded[activity.trailing.id]}
+ loading={!!activity.loading[activity.trailing.id]}
+ error={!!activity.error[activity.trailing.id]}
+ onToggle={() => activity.onToggleGroup(activity.trailing!)}
+ onRetry={() => activity.onRetryGroup(activity.trailing!)}
+ />
+ )}
{footer}
</div>
</div>
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 3acd07c91..e96bf096e 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -2,6 +2,7 @@ import React, { createContext, useContext, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useToast } from './ToastContext';
import { apiFetch } from '../lib/apiFetch';
+import type { TurnActivityGroupWire } from '../lib/agentActivity';
import type { VaultSessionPolicy } from '../lib/vaultSandboxPolicy';
import type { DockDoc } from './DockContext';
@@ -576,6 +577,11 @@ export type ApiContextType = {
* (bound tasks/watches + active runs) — drives the irreversible-confirm dialog. */
getArchivePreview: (sessionId: string) => Promise<{ tasks: number; watches: number; runs: number; queued: number }>;
listSessionMessages: (sessionId: string, params?: { afterId?: string; beforeId?: string; aroundId?: string; limit?: number; tail?: boolean; cache?: boolean }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null; next_before_id?: string | null }>;
+ // Chat Activity panel (GET /api/sessions/<id>/activity): summary of turn groups
+ // for chips, and one group's rows for lazy expand. Only used when the
+ // ``ui.show_agent_activity`` toggle is on (see lib/agentActivity).
+ getSessionActivity: (sessionId: string) => Promise<{ groups: TurnActivityGroupWire[] }>;
+ getSessionActivityGroup: (sessionId: string, groupId: string) => Promise<TurnActivityGroupWire>;
// Full-text search over message content across all sessions. Backed by the
// non-cached GET /api/search/messages (the query string varies per keystroke,
// so caching would only bloat the read cache). Results group matches by
@@ -2441,6 +2447,14 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const path = qs ? `${base}?${qs}` : base;
return params?.cache === false ? getJson(path) : getCachedJson(path);
},
+ getSessionActivity: (sessionId) =>
+ // Uncached: this is also the gap-recovery resync path, so it must reflect
+ // durable state (not a stale read served after a missed message.new).
+ getJson(`/api/sessions/${encodeURIComponent(sessionId)}/activity`),
+ getSessionActivityGroup: (sessionId, groupId) =>
+ getJson(
+ `/api/sessions/${encodeURIComponent(sessionId)}/activity?group_id=${encodeURIComponent(groupId)}`,
+ ),
searchMessages: (q, opts) => {
const search = new URLSearchParams();
search.set('q', q);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 1b930dd17..f5a63911d 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1728,6 +1728,8 @@
"agentProgressStyleOff": "Off",
"chatMessageFontSize": "Chat Message Font Size",
"chatMessageFontSizeHint": "Font size for user and agent message bubbles in the Web UI chat",
+ "showAgentActivity": "Show Agent Activity",
+ "showAgentActivityHint": "Show the agent's intermediate steps — interim messages and tool calls — live in Web chat, collapsing to a one-line summary when the reply arrives. Web chat only; does not affect IM platforms. Default off.",
"slackLinkPreviews": "Suppress Slack Link Previews",
"slackLinkPreviewsHint": "Disable Slack URL and media preview cards for messages sent by Avibe",
"allowedChannels": "Allowed Groups",
@@ -2355,6 +2357,24 @@
"disconnected": "Disconnected"
}
},
+ "agentActivity": {
+ "running": "Running",
+ "step": "{{count}} step",
+ "steps": "{{count}} steps",
+ "label": "Activity",
+ "failed": "Failed · {{count}} steps",
+ "interrupted": "Interrupted · stopped at step {{count}}",
+ "expand": "Show activity",
+ "collapse": "Hide activity",
+ "showCall": "Show details",
+ "hideCall": "Hide details",
+ "jumpToLatest": "Jump to latest",
+ "loadFailed": "Couldn't load activity detail.",
+ "retry": "Retry",
+ "durationMin": "{{minutes}}m {{seconds}}s",
+ "durationSec": "{{seconds}}s",
+ "empty": "No activity recorded for this turn."
+ },
"queue": {
"title": "Queued · {{count}}",
"sendNow": "Send now",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 4aec238df..9b9f397b7 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1728,6 +1728,8 @@
"agentProgressStyleOff": "关闭",
"chatMessageFontSize": "聊天消息字号",
"chatMessageFontSizeHint": "Web UI 聊天页里用户和 Agent 消息气泡的文字大小",
+ "showAgentActivity": "显示 Agent 执行过程",
+ "showAgentActivityHint": "在 Web 聊天中实时显示 Agent 的中间步骤——中间消息与工具调用摘要,回复到达后自动折叠为一行摘要。仅 Web 聊天,不影响 IM 平台。默认关闭。",
"slackLinkPreviews": "关闭 Slack 链接预览",
"slackLinkPreviewsHint": "关闭 Avibe 发送到 Slack 的 URL 和媒体预览卡片",
"allowedChannels": "允许的群组",
@@ -2355,6 +2357,24 @@
"disconnected": "已断开"
}
},
+ "agentActivity": {
+ "running": "正在执行",
+ "step": "{{count}} 步",
+ "steps": "{{count}} 步",
+ "label": "执行过程",
+ "failed": "执行失败 · {{count}} 步",
+ "interrupted": "已中断 · 第 {{count}} 步停止",
+ "expand": "展开执行过程",
+ "collapse": "收起执行过程",
+ "showCall": "展开详情",
+ "hideCall": "收起详情",
+ "jumpToLatest": "跳到最新",
+ "loadFailed": "无法加载执行详情。",
+ "retry": "重试",
+ "durationMin": "{{minutes}} 分 {{seconds}} 秒",
+ "durationSec": "{{seconds}} 秒",
+ "empty": "本轮没有执行过程记录。"
+ },
"queue": {
"title": "排队中 · {{count}}",
"sendNow": "立即发送",
diff --git a/ui/src/lib/agentActivity.test.ts b/ui/src/lib/agentActivity.test.ts
new file mode 100644
index 000000000..754babc71
--- /dev/null
+++ b/ui/src/lib/agentActivity.test.ts
@@ -0,0 +1,198 @@
+import { describe, expect, it } from 'vitest';
+
+import type { WorkbenchMessage } from '../context/ApiContext';
+import {
+ activityDurationParts,
+ activityRowFromMessage,
+ groupFromWire,
+ initialLiveActivity,
+ isActivityMessageType,
+ liveActivityReducer,
+ parseToolName,
+ shouldShowRunningCard,
+ toolIconKind,
+ toolSummary,
+ type ActivityRow,
+} from './agentActivity';
+
+// ``format_toolcall`` stores one string: "🔧 `ToolName` `{json params}`".
+const BASH = '🔧 `Bash` `{"command":"pdftotext report.pdf"}`';
+const READ = '🔧 `Read` `{"path":"notes.md"}`';
+const NO_PARAMS = '🔧 `TodoWrite`';
+
+describe('parseToolName', () => {
+ it('extracts the backtick-wrapped tool name after the wrench', () => {
+ expect(parseToolName(BASH)).toBe('Bash');
+ expect(parseToolName(READ)).toBe('Read');
+ expect(parseToolName(NO_PARAMS)).toBe('TodoWrite');
+ });
+
+ it('falls back to the first token when there is no backtick', () => {
+ expect(parseToolName('🔧 WebSearch results')).toBe('WebSearch');
+ expect(parseToolName('')).toBe('');
+ });
+});
+
+describe('toolSummary', () => {
+ it('returns the first-line remainder after the tool name, unwrapped', () => {
+ expect(toolSummary(BASH)).toBe('{"command":"pdftotext report.pdf"}');
+ expect(toolSummary(NO_PARAMS)).toBe('');
+ });
+
+ it('keeps only the first line', () => {
+ expect(toolSummary('🔧 `Bash` `ls`\nsecond line')).toBe('ls');
+ });
+});
+
+describe('toolIconKind', () => {
+ it('maps tool-name families to a stable icon key', () => {
+ expect(toolIconKind('Bash')).toBe('terminal');
+ expect(toolIconKind('Read')).toBe('file');
+ expect(toolIconKind('Edit')).toBe('edit');
+ expect(toolIconKind('Write')).toBe('edit');
+ expect(toolIconKind('WebSearch')).toBe('web');
+ expect(toolIconKind('Task')).toBe('agent');
+ expect(toolIconKind('SomethingElse')).toBe('wrench');
+ });
+});
+
+describe('activityDurationParts', () => {
+ it('splits into whole-second minutes/seconds (units applied via i18n)', () => {
+ expect(activityDurationParts(45000)).toEqual({ minutes: 0, seconds: 45 });
+ expect(activityDurationParts(83000)).toEqual({ minutes: 1, seconds: 23 });
+ expect(activityDurationParts(600000)).toEqual({ minutes: 10, seconds: 0 });
+ });
+
+ it('returns null for null/negative', () => {
+ expect(activityDurationParts(null)).toBeNull();
+ expect(activityDurationParts(-5)).toBeNull();
+ });
+});
+
+describe('shouldShowRunningCard', () => {
+ const rows = [{ id: 'a', kind: 'tool_call', text: 'x', created_at: 't' }] as ActivityRow[];
+ it('renders only while enabled AND working AND the buffer is non-empty', () => {
+ expect(shouldShowRunningCard(true, true, rows.length)).toBe(true);
+ expect(shouldShowRunningCard(false, true, rows.length)).toBe(false);
+ expect(shouldShowRunningCard(true, true, 0)).toBe(false);
+ });
+ it('hides a stale buffer by construction once working goes false (R5: idle-recovered turn)', () => {
+ // A dropped turn.end recovered by the idle poll clears ``working`` while the
+ // buffer still holds the finished turn's rows — the card must not linger.
+ expect(shouldShowRunningCard(true, false, rows.length)).toBe(false);
+ });
+});
+
+describe('isActivityMessageType', () => {
+ it('is true only for assistant + tool_call', () => {
+ expect(isActivityMessageType('assistant')).toBe(true);
+ expect(isActivityMessageType('tool_call')).toBe(true);
+ expect(isActivityMessageType('result')).toBe(false);
+ expect(isActivityMessageType('user')).toBe(false);
+ });
+});
+
+describe('groupFromWire', () => {
+ it('maps snake_case wire fields to the camelCase group', () => {
+ const group = groupFromWire({
+ id: 'm_a1',
+ anchor_message_id: 'm_r1',
+ status: 'done',
+ steps: 3,
+ duration_ms: 83000,
+ started_at: '2026-06-01T10:00:00Z',
+ rows: [{ id: 'm_a1', kind: 'assistant', text: 'hi', created_at: '2026-06-01T10:00:01Z' }],
+ });
+ expect(group.anchorMessageId).toBe('m_r1');
+ expect(group.durationMs).toBe(83000);
+ expect(group.rows).toHaveLength(1);
+ expect(group.rows?.[0].kind).toBe('assistant');
+ });
+
+ it('normalizes null anchor + missing duration/rows', () => {
+ const group = groupFromWire({
+ id: 'e_t1',
+ anchor_message_id: null,
+ status: 'interrupted',
+ steps: 1,
+ duration_ms: null,
+ });
+ expect(group.anchorMessageId).toBeNull();
+ expect(group.durationMs).toBeNull();
+ expect(group.rows).toBeUndefined();
+ });
+});
+
+describe('activityRowFromMessage', () => {
+ it('derives kind from the message type', () => {
+ const assistant = activityRowFromMessage({ id: 'm1', type: 'assistant', text: 'thinking', created_at: 't1' } as WorkbenchMessage);
+ expect(assistant).toEqual({ id: 'm1', kind: 'assistant', text: 'thinking', created_at: 't1' });
+ const tool = activityRowFromMessage({ id: 'e1', type: 'tool_call', text: '🔧 `Bash`', created_at: 't2' } as WorkbenchMessage);
+ expect(tool.kind).toBe('tool_call');
+ });
+});
+
+describe('liveActivityReducer (generation invariant)', () => {
+ const row = (id: string): ActivityRow => ({ id, kind: 'tool_call', text: id, created_at: `t-${id}` });
+
+ it('turn_start bumps the generation and clears the buffer', () => {
+ let s = initialLiveActivity();
+ s = liveActivityReducer(s, { type: 'row', row: row('a'), now: 1 });
+ s = liveActivityReducer(s, { type: 'turn_start' });
+ expect(s.gen).toBe(1);
+ expect(s.rows).toEqual([]);
+ expect(s.startedAt).toBeNull();
+ });
+
+ it('rows append within a generation; the first stamps startedAt', () => {
+ let s = liveActivityReducer(initialLiveActivity(), { type: 'turn_start' });
+ s = liveActivityReducer(s, { type: 'row', row: row('a'), now: 100 });
+ s = liveActivityReducer(s, { type: 'row', row: row('b'), now: 200 });
+ expect(s.rows.map((r) => r.id)).toEqual(['a', 'b']);
+ expect(s.startedAt).toBe(100); // unchanged by the second row
+ });
+
+ it('a row after settle opens a new agent-initiated generation', () => {
+ let s = liveActivityReducer(initialLiveActivity(), { type: 'turn_start' });
+ s = liveActivityReducer(s, { type: 'row', row: row('a'), now: 1 });
+ s = liveActivityReducer(s, { type: 'settle' });
+ const genAfterSettle = s.gen;
+ s = liveActivityReducer(s, { type: 'row', row: row('b'), now: 5 });
+ expect(s.gen).toBe(genAfterSettle + 1);
+ expect(s.rows.map((r) => r.id)).toEqual(['b']); // fresh buffer, not merged with 'a'
+ expect(s.settled).toBe(false);
+ });
+
+ it('clear_for_gen only clears its own generation — a late refresh after the next turn is a no-op (#499)', () => {
+ let s = liveActivityReducer(initialLiveActivity(), { type: 'turn_start' }); // gen 1
+ s = liveActivityReducer(s, { type: 'row', row: row('a'), now: 1 });
+ const gen1 = s.gen;
+ s = liveActivityReducer(s, { type: 'settle' });
+ s = liveActivityReducer(s, { type: 'turn_start' }); // gen 2, buffer cleared
+ s = liveActivityReducer(s, { type: 'row', row: row('b'), now: 2 }); // gen 2's live row
+ // The gen-1 settle refresh resolves LATE:
+ const after = liveActivityReducer(s, { type: 'clear_for_gen', gen: gen1 });
+ expect(after.rows.map((r) => r.id)).toEqual(['b']); // gen 2's live row is NOT wiped
+ // The current-gen clear does clear it:
+ const cleared = liveActivityReducer(s, { type: 'clear_for_gen', gen: s.gen });
+ expect(cleared.rows).toEqual([]);
+ });
+
+ it('rehydrate_for_gen fills only an empty buffer of the current generation', () => {
+ let s = liveActivityReducer(initialLiveActivity(), { type: 'turn_start' });
+ const gen = s.gen;
+ const hydrated = liveActivityReducer(s, {
+ type: 'rehydrate_for_gen',
+ gen,
+ rows: [row('x'), row('y')],
+ startedAt: 50,
+ });
+ expect(hydrated.rows.map((r) => r.id)).toEqual(['x', 'y']);
+ // Does not clobber an already-filled buffer, nor a stale generation:
+ const withLive = liveActivityReducer(hydrated, { type: 'row', row: row('z'), now: 60 });
+ const noClobber = liveActivityReducer(withLive, { type: 'rehydrate_for_gen', gen, rows: [row('w')], startedAt: 70 });
+ expect(noClobber.rows.map((r) => r.id)).toEqual(['x', 'y', 'z']);
+ const staleGen = liveActivityReducer(hydrated, { type: 'rehydrate_for_gen', gen: gen - 1, rows: [row('w')], startedAt: 70 });
+ expect(staleGen.rows.map((r) => r.id)).toEqual(['x', 'y']);
+ });
+});
diff --git a/ui/src/lib/agentActivity.ts b/ui/src/lib/agentActivity.ts
new file mode 100644
index 000000000..4e69f73a2
--- /dev/null
+++ b/ui/src/lib/agentActivity.ts
@@ -0,0 +1,197 @@
+import type { WorkbenchMessage } from '../context/ApiContext';
+
+// One turn's activity, as rendered by the Chat Activity panel. Mirrors the
+// backend ``storage/agent_activity_service.py`` shape (see the /activity endpoint).
+export type ActivityStatus = 'running' | 'done' | 'failed' | 'interrupted';
+
+export type ActivityRow = {
+ id: string;
+ kind: 'assistant' | 'tool_call';
+ text: string;
+ created_at: string;
+};
+
+// A group is positioned in the transcript by ``anchorMessageId`` (the chip renders
+// directly above that message: the terminal reply for done/failed, the next turn's
+// opening message for a history-interrupted turn). ``null`` = trails the transcript
+// (the live running card, or an interrupted turn with no following message).
+// ``rows`` is present once loaded (live snapshot or lazy fetch); absent = summary
+// only (fetch on expand).
+export type ActivityGroup = {
+ id: string;
+ anchorMessageId: string | null;
+ status: ActivityStatus;
+ steps: number;
+ durationMs: number | null;
+ startedAt?: string | null;
+ rows?: ActivityRow[];
+};
+
+// Wire shape from GET /api/sessions/<id>/activity (summary group + optional rows).
+export type TurnActivityGroupWire = {
+ id: string;
+ anchor_message_id: string | null;
+ status: ActivityStatus;
+ steps: number;
+ duration_ms: number | null;
+ started_at?: string | null;
+ ended_at?: string | null;
+ rows?: Array<{ id: string; kind: 'assistant' | 'tool_call'; text: string; created_at: string }>;
+};
+
+export const groupFromWire = (wire: TurnActivityGroupWire): ActivityGroup => ({
+ id: wire.id,
+ anchorMessageId: wire.anchor_message_id ?? null,
+ status: wire.status,
+ steps: wire.steps,
+ durationMs: wire.duration_ms ?? null,
+ startedAt: wire.started_at ?? null,
+ rows: wire.rows?.map((r) => ({ id: r.id, kind: r.kind, text: r.text, created_at: r.created_at })),
+});
+
+// A live ``message.new`` of type assistant/tool_call → an activity row (the live
+// stream only carries these when ``show_agent_activity`` is on, see message_mirror).
+export const activityRowFromMessage = (msg: WorkbenchMessage): ActivityRow => ({
+ id: msg.id,
+ kind: msg.type === 'tool_call' ? 'tool_call' : 'assistant',
+ text: msg.text ?? '',
+ created_at: msg.created_at,
+});
+
+// ===== Live running-card buffer: a pure state machine (state, not timing) =====
+// The live buffer drives ONLY the in-flight running card; all SETTLED groups come
+// from the durable endpoint. Each turn is tagged with a monotonic GENERATION so
+// that a stale buffer is invisible by construction and a late settle-refresh is a
+// structural no-op for a newer turn:
+// - the running card renders only while ``working`` AND ``rows`` are non-empty,
+// and ``rows`` always belong to the current generation (cleared on every bump);
+// - a settle refresh is issued for a generation and only clears/rehydrates the
+// buffer when it resolves for that SAME generation (a newer turn bumped it → the
+// resolution is dropped). This subsumes the "stale/late buffer" class without
+// promise-cancellation or grace-timer bookkeeping.
+export type LiveActivityState = {
+ gen: number; // current turn generation (monotonic)
+ settled: boolean; // the current generation has settled (terminal / turn.end seen)
+ rows: ActivityRow[]; // current-generation buffer (empty ⇒ nothing to show)
+ startedAt: number | null; // elapsed-clock start for the running card
+};
+
+export const initialLiveActivity = (): LiveActivityState => ({
+ gen: 0,
+ settled: false,
+ rows: [],
+ startedAt: null,
+});
+
+export type LiveActivityEvent =
+ | { type: 'turn_start' }
+ | { type: 'row'; row: ActivityRow; now: number }
+ | { type: 'settle' }
+ | { type: 'clear_for_gen'; gen: number }
+ | { type: 'rehydrate_for_gen'; gen: number; rows: ActivityRow[]; startedAt: number };
+
+// The running card is a PURE FUNCTION of (working, current-generation buffer): it
+// shows only while a turn is in flight AND the buffer is non-empty. The buffer is
+// always the CURRENT generation when non-empty (the reducer clears it on every
+// bump), so a stale buffer left by a failed/late refresh is invisible by
+// construction the moment ``working`` goes false — no separate generation check
+// is needed at the render site.
+export const shouldShowRunningCard = (
+ enabled: boolean,
+ working: boolean,
+ liveRowCount: number,
+): boolean => enabled && working && liveRowCount > 0;
+
+export const liveActivityReducer = (
+ state: LiveActivityState,
+ event: LiveActivityEvent,
+): LiveActivityState => {
+ switch (event.type) {
+ case 'turn_start':
+ // New turn → new generation with a fresh empty buffer (any stale rows from the
+ // previous generation are dropped by construction).
+ return { gen: state.gen + 1, settled: false, rows: [], startedAt: null };
+ case 'row':
+ if (state.settled) {
+ // First row after a settle with no turn.start = an agent-initiated new turn.
+ return { gen: state.gen + 1, settled: false, rows: [event.row], startedAt: event.now };
+ }
+ return {
+ ...state,
+ rows: [...state.rows, event.row],
+ startedAt: state.rows.length === 0 ? event.now : state.startedAt,
+ };
+ case 'settle':
+ return state.settled ? state : { ...state, settled: true };
+ case 'clear_for_gen':
+ // A settle refresh resolved with no in-flight turn: clear the finished buffer
+ // — but ONLY if still the same generation (a newer turn.start bumped gen, so
+ // this resolution is a stale no-op and must not wipe the new turn's rows).
+ return event.gen === state.gen ? { ...state, rows: [], startedAt: null } : state;
+ case 'rehydrate_for_gen':
+ // In-flight re-hydrate from storage, only if still the current generation and
+ // the live stream hasn't already filled the buffer.
+ return event.gen === state.gen && state.rows.length === 0
+ ? { ...state, rows: event.rows, startedAt: event.startedAt }
+ : state;
+ default:
+ return state;
+ }
+};
+
+export const isActivityMessageType = (type: string): boolean =>
+ type === 'assistant' || type === 'tool_call';
+
+// ``format_toolcall`` stores "🔧 `ToolName` `{json params}`" (one string, backend
+// formatter output). Parse the tool name (first backtick token, else first word
+// after the wrench) and a one-line summary (the remainder of the first line).
+const TOOL_GLYPH = /^\s*🔧\s*/u;
+
+export const parseToolName = (text: string): string => {
+ const firstLine = (text || '').split('\n')[0].replace(TOOL_GLYPH, '').trim();
+ const backtick = firstLine.match(/^`([^`]+)`/);
+ if (backtick) return backtick[1].trim();
+ const word = firstLine.split(/\s+/)[0] || '';
+ return word.replace(/[`:]/g, '').trim();
+};
+
+export const toolSummary = (text: string): string => {
+ let firstLine = (text || '').split('\n')[0].replace(TOOL_GLYPH, '').trim();
+ // Drop the leading tool-name token (backtick-wrapped or bare word).
+ const backtick = firstLine.match(/^`[^`]+`\s*/);
+ if (backtick) firstLine = firstLine.slice(backtick[0].length);
+ else firstLine = firstLine.replace(/^\S+\s*/, '');
+ // Unwrap a single surrounding backtick pair for readability.
+ const wrapped = firstLine.match(/^`(.*)`$/);
+ return (wrapped ? wrapped[1] : firstLine).trim();
+};
+
+// Icon category by tool-name prefix (spec: terminal/file-text/pencil/globe/bot,
+// fallback wrench). Returns a stable KEY, not a component, so the renderer maps it
+// through a static table (avoids creating a component during render).
+export type ToolIconKind = 'terminal' | 'edit' | 'file' | 'web' | 'agent' | 'wrench';
+
+export const toolIconKind = (toolName: string): ToolIconKind => {
+ // Match by PREFIX, not substring: tool names lead with their category (``Bash``,
+ // ``Read``, ``WebSearch``, ``file_change``…). Substring matching mis-fires — e.g.
+ // ``ls`` inside "SomethingElse", ``run`` inside "current".
+ const name = (toolName || '').trim().toLowerCase();
+ const startsWithAny = (prefixes: string[]) => prefixes.some((p) => name.startsWith(p));
+ if (startsWithAny(['bash', 'shell', 'terminal', 'exec', 'command', 'run', 'sh'])) return 'terminal';
+ if (startsWithAny(['write', 'edit', 'patch', 'create', 'update', 'apply', 'notebook', 'todo', 'file'])) return 'edit';
+ if (startsWithAny(['read', 'cat', 'grep', 'glob', 'ls', 'open', 'view', 'list', 'find'])) return 'file';
+ if (startsWithAny(['web', 'fetch', 'http', 'browse', 'url'])) return 'web';
+ if (startsWithAny(['task', 'agent', 'mcp', 'sub', 'delegate'])) return 'agent';
+ return 'wrench';
+};
+
+// Duration as {minutes, seconds} (null when unavailable). The unit text is applied
+// by the component through i18n (AGENTS.md: no hardcoded user-facing units), so the
+// zh chip renders localized units rather than a hardcoded "1m 23s".
+export const activityDurationParts = (
+ ms: number | null | undefined,
+): { minutes: number; seconds: number } | null => {
+ if (ms == null || !Number.isFinite(ms) || ms < 0) return null;
+ const totalSeconds = Math.round(ms / 1000);
+ return { minutes: Math.floor(totalSeconds / 60), seconds: totalSeconds % 60 };
+};
diff --git a/vibe/api.py b/vibe/api.py
index 72e443540..6c4c238b8 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -877,6 +877,15 @@ def save_config(payload: dict) -> V2Config:
if existing_update is not None:
_save_discord_guild_scope_update(*existing_update, store=store)
config.save()
+ # The activity-streaming gate (ui.show_agent_activity) is cached in-process
+ # by the message mirror; a save that flips it must take effect immediately,
+ # not after the cache TTL. Reset it here (same process) — best-effort.
+ try:
+ from core.message_mirror import reset_activity_flag_cache
+
+ reset_activity_flag_cache()
+ except Exception:
+ pass
_ensure_builtin_default_agents(config)
return config
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index c659e22be..7975d2fc4 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -6254,6 +6254,47 @@ def sessions_messages_list(session_id: str):
return jsonify(result)
[email protected]("/api/sessions/<session_id>/activity", methods=["GET"])
+def sessions_activity(session_id: str):
+ """Turn-grouped agent activity for the Chat Activity panel.
+
+ Two modes on one route (mirrors the ``chat_message_font_size`` /
+ ``show_agent_activity`` display feature; the panel is a display-only view of
+ already-persisted rows — no gating here, the gate is the UI toggle):
+
+ * no query params → SUMMARY: ``{"groups": [{id, anchor_message_id, status,
+ steps, started_at, ended_at, duration_ms}, ...]}`` — one entry per turn that
+ produced ≥1 activity row, WITHOUT the row text. Loaded once when the Chat
+ opens so past turns can show their collapsed chip.
+ * ``?group_id=<id>`` → DETAIL: that one group plus ``"rows": [{id, kind,
+ text, created_at}, ...]`` (``kind`` is ``assistant`` | ``tool_call``) — the
+ lazy expand. 404 when the group id is unknown.
+
+ ``status`` ∈ ``done`` | ``failed`` | ``interrupted``. See
+ ``storage/agent_activity_service.py`` for the grouping contract and the
+ bounded-scan window.
+ """
+ from core.services import sessions as workbench_sessions_service
+ from storage import agent_activity_service
+
+ group_id = request.args.get("group_id") or None
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ try:
+ workbench_sessions_service.get_session(conn, session_id)
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+ if group_id:
+ group = agent_activity_service.get_turn_group(
+ conn, session_id=session_id, group_id=group_id
+ )
+ if group is None:
+ return jsonify({"error": "activity group not found"}), 404
+ return jsonify(group)
+ result = agent_activity_service.list_turn_groups(conn, session_id=session_id)
+ return jsonify(result)
+
+
@app.route("/api/search/messages", methods=["GET"])
def search_messages_list():
"""Global message-content search across Workbench sessions, grouped by session.