diff --git a/docs/terminal-rendering.md b/docs/terminal-rendering.md index 35798fa0..4e9ea9c0 100644 --- a/docs/terminal-rendering.md +++ b/docs/terminal-rendering.md @@ -1,51 +1,249 @@ # Per-agent terminal: row taxonomy (as built) -The per-agent web UI's live pane renders one row per `TermMsg` -(`hive-agent/src/term_msg.rs`): `{icon?, level: debug|info|warn|error, -summary, body?, body_format?: markdown|diff, coalesce_key?}`. Classification -(icon, summary text, whether a tool call gets an expandable body) happens -server-side, once — `term_msg.rs` + `stream_enrich.rs` — and is served -identically by both `GET /api/events/history` and `GET /api/events/stream` -as `TermEnvelope { ts, seq?, msgs: TermMsg[] }` frames -(`hive-agent/src/web_ui/stream.rs`). +Snapshot of how the per-agent web UI's live pane renders each +event kind today. The per-tool icon/summary/category (and, for a +few rich tools, the expandable body) are pre-computed server-side by +`hive-agent/src/stream_enrich.rs::enrich` and stamped onto the +stream-json value as `_icon`/`_summary`/`_category`/`_body`/ +`_body_type` before SSE delivery, so the frontend just dispatches on +those fields instead of re-deriving them. Frontend source of truth +lives in `frontend/packages/agent/src/app.js` (`renderStream`, +`renderRichToolUse`, `renderToolResult`, `renderTaskEvent`, +`mdNode`, `detailsOpenMd`) + +`frontend/packages/shared/src/terminal/terminal.css` (the shared +`.live .` styling) + the `marked` npm package (markdown). -The frontend renders a `TermMsg` close to as-is -(`frontend/packages/agent/src/components/Row.tsx`): `level` picks the -CSS colour (`terminal.css`'s `.live .level-*`), an empty `summary` + -markdown `body` renders as a flat row with just the body (assistant -text), and any other bodied row is an expandable `
`, opened by -default according to the operator's expand-tool-output preference -(`getExpandDetailsPref()`) — uniformly, no per-tool override. There's no -separate client-side row model or classification step. +## Layout contract -## Layout +Every row — flat `
` and expandable +`
` alike — shares one prefix column. +The mechanism is `padding-left + negative text-indent` on +`.live .row`: the row's first inline box gets pulled back +into the column at ~0.5em, and wrapped continuation lines +hang under the body, not under the glyph. -Every row shares one prefix column via `padding-left` + negative -`text-indent` on `.live .row`; an icon (when set) sits in a fixed-width -`.row-glyph` cell so icons of different rendered widths still line up. -`
` summaries reuse the same metrics, with the disclosure caret -leading the summary text rather than the icon. +Rows that carry an icon (the per-tool emoji, `🧠`/`💭` +thinking, etc.) pass it as the `icon` argument to +`row()` / `details()` / `detailsDiff()`, which puts it in a +fixed-width `.row-glyph` cell (`display: inline-block; +width: 1.4em`) rather than as a bare first character. The +constant cell width means every icon's left edge lines up in +the column regardless of the glyph's rendered width (emoji +differ; some carry a variation selector) — a flat row's `🧠` +and a `details` summary's `🖥️` align. Rows with a plain +single-char glyph (`◆ · ! ←`) still pass it inline; it lands +at the same ~0.5em left edge. -## Levels +`
` summaries inherit those metrics. The icon (when +present) sits in the `.row-glyph` cell; the summary text lives +in a `.summary-text` span and the disclosure caret (`▸` / `▾`) +is supplied by CSS `.summary-text::before` so it **leads the +text, not the icon** — a leading caret on the icon would push +it out of the shared column. Icon-less summaries have no +`.row-glyph`, so the caret falls into the prefix column like +the old directional glyph. The summary text carries no +`→` / `←`; the row colour (cyan = outbound, muted = inbound) +carries the direction. -| Level | Colour | Roughly | -|---|---|---| -| `debug` | muted | thinking, coalesced ticks, ambient harness chatter | -| `info` | default fg | turn start/ok, assistant text, tool calls + results | -| `warn` | amber, left rule | stderr, an unrecognised event shape, API retries | -| `error` | red, left rule | turn failed, a tool result with `is_error: true` | +Child blocks inside a row (the `.md` markdown wrapper, an +inner `
`) get `text-indent: 0` so their content +lays out from the body column instead of inheriting the +parent's negative pull. -Per-tool icon + summary formatting (what a `Read`/`Edit`/`send` call's row -actually says) lives in `stream_enrich.rs`'s `fmt_tool_use()` family — -read that when you need the specifics, this doc doesn't duplicate it. +## Row taxonomy + +| CSS class | Prefix glyph | Color | Triggered by | Source | +|---|---|---|---|---| +| `.turn-start` | `◆ TURN ← ` | amber, left rule | `LiveEvent::TurnStart` | harness wake | +| `.turn-body` | (child div under turn-start) | fg | same | the wake-prompt body | +| `.turn-end-ok` | `✅ turn ok` | green, left rule | `LiveEvent::TurnEnd { ok: true }` | harness | +| `.turn-end-fail` | `❌ turn fail — note` | red, left rule | `LiveEvent::TurnEnd { ok: false }` | harness | +| `.turn-time` | `· HH:MM:SS` on turn-start; `· HH:MM:SS · ` on turn-end (child span) | muted, smaller | per-event `ts` (unix seconds) on the live frame + history row | harness | +| `.text` | (no prefix; markdown body) | fg | claude `assistant.content[].text` | stream-json | +| `.thinking` | `💭 thinking …` | muted, italic | claude `assistant.content[].thinking` | stream-json | +| `.tool-use` (flat) | ` Name args…` | cyan | tool_use w/o rich renderer; `` from the backend's `tool_icon(name)` (`stream_enrich.rs`): 📤 send · 📥 recv · ⏰ remind · 🏷️ set_status · 🪢 loose-ends · ✂️ cancel_loose_end · ℹ️ get_agent_meta · ✅ ack_until · 📜 get_logs/get_host_journal · ↻ restart · ⏹️ kill · ▶️ start · 🔄 update · 📋 list_containers/list_rooms/list_room_members/list_invites · 📖 read_room/Read · 👁️ mark_read · 🛑 bash kill · 🖥️ bash other · 💬 matrix send/reply/dm · 📦 request_* · ⏱️ schedule · 🔧 default | stream-json | +| `.tool-use` `
` | `✏️ Edit · -N +N` (no `→`) | cyan, body is +/- diff | `renderRichToolUse` Edit | stream-json | +| `.tool-use` `
` | `📤 send → to · NL` | cyan, body is markdown | rich renderer for send | stream-json | +| `.tool-result` (flat) | `← ` | muted | short `tool_result` (≤120c, non-recv) | stream-json | +| `.tool-result-block` `
` | `Nl · headline` | muted, body is text | long generic `tool_result` | stream-json | +| `.tool-result-block` `
` | `recv ← ` | muted, body is markdown | `tool_result` correlated to a prior `recv` tool_use via id | stream-json | +| `.tool-result.error` (flat) | `✗ ` | red | `tool_result` with `is_error: true` (≤120c); `` wrapper stripped | stream-json | +| `.tool-result-block.error` `
` | `Nl · headline` | red, body is text | long error `tool_result` (`is_error: true`); wrapper stripped | stream-json | +| `.tool-use` | `⌁ task started · [type]` | cyan | claude Task-tool subagent start (dead path — `Task` omitted from agent allow-list) | `renderTaskEvent` | +| `.turn-end-ok` / `.turn-end-fail` / `.tool-result` | `⌁ task ✓/✗/◌ · · → ` | green / red / muted | claude Task-tool result (dead path for agents) | `renderTaskEvent` | +| `.note` | `· ⚙ plugin install · loading…` or `✓ done` | muted | `system/plugin_install` (`status` = started/completed) | stream-json | +| `.note` | `· ⚙ commands changed · N available` (expandable list of `/name` entries) | muted | `system/commands_changed` (slash-command set updated, usually post-plugin_install) | stream-json | +| `.note` | `· ⚙ compact · ·
 tokens · ` | muted | `system/compact_boundary` (compaction completed; metadata includes pre/post token counts, duration, trigger) | stream-json |
+| `.note` | `· ⚙ ` | muted | other `system` subtypes (context_window_exceeded, etc.) | stream-json catch-all |
+| `.note` | `· ` | muted | harness chatter | `LiveEvent::Note` |
+| `.note.stderr` | `! stderr: ` | amber/orange | stderr lines off claude | `LiveEvent::Note` (`text` starts `stderr:`) |
+| `.note.op` | `· operator: ` | mauve italic | operator-initiated notes (/cancel, /compact, /model, new-session) | `LiveEvent::Note` (`text` starts `operator:`) |
+| `.sys` | `! {json…}` | amber/orange | catch-all for stream shapes `renderStream` didn't classify | catch-all |
+| Banner shimmer | mauve | turn in flight (ref-counted) | — | `setBannerActive` |
+
+The `.turn-time` span is appended to the turn-start / turn-end rows from
+the event's `ts` (unix seconds), which the backend serializes as a
+flattened sibling of `kind` on both the live SSE frame and each history
+row — so the same renderer path stamps live tail and replayed scrollback
+identically. Turn-end also shows the elapsed duration (end − start),
+paired against the most recent open turn-start. The read is guarded on a
+numeric `ts`: if a frame omits it the rows render without the time
+suffix, so the terminal degrades cleanly against older event shapes.
+
+## Renderer dispatch
+
+`renderStream(v, api)` walks each stream-json line. Most of the
+per-event classification it used to do itself is now pre-computed
+server-side by `hive-agent/src/stream_enrich.rs::enrich` (stamped
+onto the value as `_category`/`_summary`/`_icon`/`_body`/
+`_body_type` at SSE-emit time, for both the live tail and history
+replay) — the client mostly just dispatches on those fields rather
+than re-deriving them from raw claude field names:
+
+1. `v._category === 'drop'` → dropped without rendering. Covers the
+   top-level `result` / `rate_limit_event` types (`result` powers the
+   `cost` badge elsewhere) and the `system` subtypes `init` /
+   `result` / `rate_limit_event`.
+1a. `system` events with `_category === 'thinking_tok'`
+   (`subtype == "thinking_tokens"`; claude streams a running
+   `estimated_tokens` counter while thinking — many per turn) →
+   collapses into a **single** `🧠 thinking … ~N tokens` `.note`
+   row that updates in place, text taken verbatim from the
+   backend-computed `_summary`. Consecutive ticks reuse the row only
+   while it's still the last one rendered (`nextElementSibling ==
+   null`); any other event after it makes the next tick start a
+   fresh row. Avoids a note-per-tick scrollback flood.
+1b. `system/plugin_install` (matched on `subtype`, not `_category`,
+   so start/complete can coalesce into one row) → muted note
+   `⚙ plugin install · loading…` (on `started`) or
+   `⚙ plugin install · ✓ done` (on `completed`), text from
+   `_summary`. Emitted in pairs: started fires before the plugin
+   loads, completed fires when it's ready.
+1c. `system/status` (matched on `subtype`) → muted note from
+   `_summary`, except while the harness's local `turn_state` is
+   `compacting`: the client overrides the text with an elapsed-time
+   counter (`⚙ compact · s…`) computed client-side from
+   `stateSince`, since the backend can't know client wall-clock time
+   at emit time.
+1d. `_category === 'details'` (currently just `system/commands_changed`)
+   → collapsible `.note` details row: `_summary` as the header
+   (`⚙ commands changed · N available`), `_body` (one `/name` per
+   line) as the expandable content.
+1e. Other `system/` subtypes (e.g. `compact_boundary`, `api_retry`,
+   `api_error`, or an unrecognised subtype) → `_category === 'note'`,
+   rendered as a single muted note from `_summary` — computed by
+   `system_fields()` in `stream_enrich.rs` (e.g. `compact_boundary`
+   → `⚙ compact ·  · 
 tokens · ` with each
+   field guarded individually; an unrecognised subtype falls back to
+   `⚙ `).
+2. `subtype == "task_started" | "task_notification"` →
+   `renderTaskEvent` (subagent activity gets the `⌁` glyph).
+3. `type == "assistant"` → walk `message.content[]`:
+   - `text` → `.text` row with a markdown body via `mdNode`.
+   - `thinking` → `.thinking` row.
+   - `tool_use` → record `id → name` in `toolNameById`. The backend
+     stamps every `tool_use` entry with `_icon` + `_summary` (via
+     `fmt_tool_use()` in `stream_enrich.rs` — see [salient-arg
+     formatting](#salient-arg-formatting) below) and, for a fixed set
+     of tools, `_category: "rich"` + `_body`/`_body_type`. When
+     `_category === "rich"`, `renderRichToolUse` dispatches on
+     `_body_type` (`"diff"` → `api.detailsDiff`, `"markdown"` →
+     `detailsOpenMd`, else `api.details`) to build the expandable
+     row; otherwise it falls through to a flat `.tool-use` row using
+     `_icon` + `_summary` as-is — no per-tool JS.
+4. `type == "user"` → walk `message.content[]` for
+   `tool_result`; `renderToolResult` correlates via
+   `tool_use_id → toolNameById` to default-open `recv`
+   results with a markdown body, else short = flat /
+   long = collapsed details.
+5. Unrecognised shape → `.sys` row (amber, `!` glyph).
+
+### Salient-arg formatting
+
+Server-side (`fmt_tool_use()` and its per-tool-family helpers in
+`hive-agent/src/stream_enrich.rs`), computed into `_summary` and
+read verbatim by the client. The `short` name strips the
+`mcp__hyperhive__` / `mcp__bash__` / `mcp__matrix__` prefix and
+appends `*` (e.g. `recv*`, `run*`, `send_message*`). Unprefixed
+tools (Read, Write, etc.) keep their name as-is.
+
+| Tool | Rendered as |
+|------|-------------|
+| **Claude built-ins** | |
+| `Read` | `Read ` |
+| `Write` | flat, same shape as Read: `Write ` — no diff/count (`content` can be megabytes and is one-sided; open the file to inspect it) |
+| `Edit` | rich diff row `Edit  · -N +N` (just `+N` for a pure insert, i.e. empty `old_string`) |
+| `Glob` | `Glob ` |
+| `Grep` | `Grep ` |
+| `Bash` | `Bash [bg] $ ` (dead path — built-in `Bash` isn't in the agent allow-list either; shell execution goes through `mcp__bash__run` / `run*` below instead) |
+| `TodoWrite` | `TodoWrite (N items)` (dead path — `TodoWrite` isn't in the agent allow-list; its state lives in claude's in-process session and evaporates on `/compact`, so agents plan in `/state` notes instead) |
+| **Core hyperhive** | |
+| `send*` | rich renderer: `send* → to · NL` (default-open body) |
+| `recv*` | `recv*()` · `recv* wait Ns` · `recv* max N` |
+| `remind*` | `remind* +Xm "preview"` or `remind* at HH:MMZ "preview"` |
+| `set_status*` | `set_status* "text"` |
+| `get_loose_ends*` | `get_loose_ends*()` or `get_loose_ends* [agent]` |
+| `get_agent_meta*` | `get_agent_meta*()` or `get_agent_meta* name` |
+| `cancel_loose_end*` | `cancel_loose_end* kind #id` |
+| `ack_until*` | `ack_until* ≤N` |
+| `mark_todos_done*` | `mark_todos_done* [id1, id2, …]` (first 8 ids, `…` past that) |
+| **Lifecycle** | |
+| `kill*/restart*/start*/update*` | `kill* name` (etc.) |
+| `get_logs*` | `get_logs* name` or `get_logs* name NL` |
+| `get_host_journal*` | `get_host_journal*()` or with `[container] · [/grep/] · NL` |
+| **Approvals / config** | |
+| `request_init_config*` | `request_init_config* name` |
+| `request_update_meta_inputs*` | `request_update_meta_inputs* [inp1, …]` or `all` |
+| **Scheduling** | |
+| `list_schedules*` | `list_schedules*()` |
+| `cancel_schedule*` | `cancel_schedule* #id all` or `#id [t1, t2]` |
+| `fire_schedule_now*` | `fire_schedule_now* #id` |
+| `edit_schedule*` | `edit_schedule* #id · body · interval · next · +N tgt · -N tgt` (only changed fields shown) |
+| `request_schedule_prompt*` | `request_schedule_prompt* → t1, t2 at HH:MMZ` (+ `+Ns` if recurring) |
+| **Bash MCP** | |
+| `run*` | `run* [bg] $ cmd` (also rich renderer for full cmd body) |
+| `status*` (bash) | `status* id:xyz` or `status* id:xyz · wait Ns` |
+| `kill*` (bash) | `kill* id` or `kill* id [force]` |
+| **Matrix MCP** | |
+| `send_message*/send_dm*/send_reply*` | `send_message* → room: "body"` / `send_dm* → @user: "body"` |
+| `send_reaction*` | `send_reaction* room emoji` |
+| `read_room*` | `read_room* room` or `read_room* room [N]` |
+| `mark_read*` | `mark_read* room` |
+| `join_room*/open_dm*` | `join_room* room` / `open_dm* @user` |
+| `invite_user*` | `invite_user* @user → room` |
+| `download_file*` | `download_file* room` |
+| **Everything else** | `fmt_args_generic` — see [Extra-MCP tools](#extra-mcp-tools) |
 
 ## Markdown
 
-`frontend/packages/agent/src/lib/markdown.ts`'s `renderMarkdown()` runs
-`marked.parse()` through DOMPurify into a `
`. Applied to -any `TermMsg` with `body_format: "markdown"`. +`mdNode(text)` wraps `marked.parse(text)` (the `marked` npm dep, +bundled by esbuild into the page's `app.js`) in a `
`. CSS in `terminal.css` scopes paragraph / code / +list / blockquote / link styling under `.live .row .md` so +the markdown body doesn't bleed into the row's own +text-indent. Falls back to plain text if `marked` didn't +load. Applied to `text` rows and to send / recv message bodies. + +## Extra-MCP tools + +`fmt_args_generic(name, input)` (`hive-agent/src/stream_enrich.rs`) +is the fallback when a tool isn't in the built-in `fmt_tool_use` +switch, computed into `_summary` server-side: + +- single string field → `name k: "v"` +- single number/bool field → `name k: v` +- multi-field → first 4 pairs trimmed to `k: "v"` / + `k: [N]` / `k: {…}` with a `…+N` overflow + +This keeps less-frequent tools that don't have a specific +`fmt_tool_use` case from dumping raw JSON. Common matrix and +hyperhive tools have their own cases and skip this path. ## Dashboard side (not covered here) -The main dashboard's message-flow pane is a different shape: broker -messages render as `.msgrow` grid lines, not agent-terminal rows. +The main dashboard's message-flow pane is a different +shape: broker messages render as `.msgrow` grid lines (ts / +arrow / from / → / to / body) with their own styling. +`.live .msgrow` explicitly resets `text-indent: 0` so the +per-agent terminal's hanging-indent metrics don't leak into +the flex-grid broker rows. diff --git a/frontend/packages/agent/src/Root.tsx b/frontend/packages/agent/src/Root.tsx index f3b15400..d18c7546 100644 --- a/frontend/packages/agent/src/Root.tsx +++ b/frontend/packages/agent/src/Root.tsx @@ -240,7 +240,7 @@ export function Root() { {state.status === 'needs_login_idle' || state.status === 'needs_login_in_progress' ? ( ) : null} - + {termInput} {panel} diff --git a/frontend/packages/agent/src/components/LiveStream.tsx b/frontend/packages/agent/src/components/LiveStream.tsx index a3453641..47b0832e 100644 --- a/frontend/packages/agent/src/components/LiveStream.tsx +++ b/frontend/packages/agent/src/components/LiveStream.tsx @@ -28,6 +28,12 @@ import { Row } from './Row.js'; const NEAR_BOTTOM_PX = 48; const LOAD_MORE_SCROLL_PX = 80; +export interface LiveStreamProps { + /** Forwarded to useLiveStream — fires on live turn_start/turn_end so + * the caller can refresh `/api/state` sooner than its poll interval. */ + onLiveTurnBoundary?: () => void; +} + /** Imperative escape hatch for TermInput's local-only slash commands * (`/help`, `/clear`) — same shape as app.js's old `termAPI` object, * kept as a ref handle rather than lifting the whole row array up to @@ -37,8 +43,11 @@ export interface LiveStreamHandle { clear: () => void; } -export const LiveStream = forwardRef(function LiveStream(_props, ref) { - const { rows, hasMore, loadingMore, loadMore, pushLocalNote, clearLocal } = useLiveStream(); +export const LiveStream = forwardRef(function LiveStream( + { onLiveTurnBoundary }, + ref, +) { + const { rows, hasMore, loadingMore, loadMore, pushLocalNote, clearLocal } = useLiveStream({ onLiveTurnBoundary }); useImperativeHandle(ref, () => ({ pushNote: pushLocalNote, clear: clearLocal }), [pushLocalNote, clearLocal]); const logRef = useRef(null); const [stickToBottom, setStickToBottom] = useState(true); diff --git a/frontend/packages/agent/src/components/Row.tsx b/frontend/packages/agent/src/components/Row.tsx index 8c435829..2f2c9900 100644 --- a/frontend/packages/agent/src/components/Row.tsx +++ b/frontend/packages/agent/src/components/Row.tsx @@ -1,16 +1,13 @@ -// Renders one `TermRow` — flat `
` or expandable -// `
`, driven straight off the wire shape -// (`lib/termMsg.ts`'s `TermMsg`, mirroring hive-agent's `term_msg.rs`): -// `level` picks the colour class, an empty `summary` + markdown `body` -// is a flat row with just the body (assistant text), anything else with -// a body is an expandable details row gated by the operator's -// expand-tool-output preference. No separate classification step — -// mara: "StreamRow should now match what the server sends in TermMsg." +// Renders one `StreamRow` — flat `
` or expandable +// `
`, matching @hive/shared/terminal.css's +// existing row-kind classes exactly (see docs/terminal-rendering.md). +// Reuses that stylesheet as-is (imported once by LiveStream.tsx) — the +// taxonomy's visual language isn't what mara asked to change, the +// component *model* underneath it is. import { useEffect, useRef } from 'preact/hooks'; -import type { TermRow } from '../lib/termMsg.js'; +import type { StreamRow } from '../lib/streamRow.js'; import { linkifyToNodes } from '../lib/linkify.js'; import { renderMarkdown } from '../lib/markdown.js'; -import { getExpandDetailsPref } from '@hive/shared/prefs.js'; function MarkdownBody({ text }: { text: string }) { const ref = useRef(null); @@ -44,39 +41,31 @@ function DiffBody({ text }: { text: string }) { ); } -export function Row({ row }: { row: TermRow }) { - const cssClass = 'level-' + row.level; - const icon = row.icon != null && row.icon !== '' && {row.icon}; - - if (row.body == null) { +export function Row({ row }: { row: StreamRow }) { + if (row.details) { return ( -
- {icon} - {linkifyToNodes(row.summary)} -
+
+ + {row.icon != null && row.icon !== '' && {row.icon}} + {row.text} + + {row.diffBody != null && } + {row.markdownBody != null && } + {row.plainBody != null &&
{linkifyToNodes(row.plainBody)}
} +
); } - - // Empty summary + markdown body → the body itself is the whole row - // (assistant text), no summary prefix line, never collapsible. - if (row.body_format === 'markdown' && row.summary === '') { - return ( -
- {icon} - -
- ); - } - return ( -
- - {icon} - {row.summary} - - {row.body_format === 'diff' && } - {row.body_format === 'markdown' && } - {row.body_format == null &&
{linkifyToNodes(row.body)}
} -
+
+ {row.icon != null && row.icon !== '' && {row.icon}} + {row.text != null && linkifyToNodes(row.text)} + {row.meta?.map((m) => ( + + {m.text} + + ))} + {row.childText != null &&
{row.childText.text}
} + {row.markdownBody != null && } +
); } diff --git a/frontend/packages/agent/src/hooks/useAgentState.ts b/frontend/packages/agent/src/hooks/useAgentState.ts index 306d8e49..99e08b57 100644 --- a/frontend/packages/agent/src/hooks/useAgentState.ts +++ b/frontend/packages/agent/src/hooks/useAgentState.ts @@ -1,5 +1,16 @@ -// useAgentState — polls `GET /api/state` every 4s and exposes the latest -// snapshot + loading/error status. +// useAgentState — polls `GET /api/state` and exposes the latest +// snapshot + loading/error status. Mirrors app.js's old `refreshState` +// data fetch (not yet its exact re-poll cadence — see the interval +// comment below). +// +// Cadence note: the old page only re-polls on a timer while a login is +// in flight, and otherwise waits for an SSE `turn_end` event to trigger +// one-shot refreshes — this avoids clobbering the operator's half-typed +// message in the term-input field. That field doesn't exist in this +// rewrite yet (a later commit on this same PR), so there's nothing to +// clobber yet; this hook uses a flat interval for now and switches to +// the SSE-triggered model in the commit that adds TermInput + the live +// stream, matching the original behavior once it's actually needed. import { useEffect, useRef, useState } from 'preact/hooks'; import type { AgentState } from '../types.js'; diff --git a/frontend/packages/agent/src/hooks/useLiveStream.ts b/frontend/packages/agent/src/hooks/useLiveStream.ts index 5aaa9a67..fbdab816 100644 --- a/frontend/packages/agent/src/hooks/useLiveStream.ts +++ b/frontend/packages/agent/src/hooks/useLiveStream.ts @@ -1,30 +1,37 @@ // Backfill + live SSE for the agent's event stream, reduced to a plain -// `TermRow[]` — the Preact-data sibling of @hive/shared/terminal.js's -// `create()`. Scroll behaviour is deliberately NOT this hook's job (see -// components/LiveStream.tsx): mara flagged the old page's scroll-while- -// streaming bug explicitly as something not to copy 1:1, and keeping -// "what rows exist" separate from "where the viewport is" is what makes -// that fixable — this hook only ever appends/prepends to `rows`, the -// DOM-owning component decides whether that should move the scroll -// position. +// `StreamRow[]` — the Preact-data sibling of +// @hive/shared/terminal.js's `create()`. Scroll behaviour is +// deliberately NOT this hook's job (see components/LiveStream.tsx): +// mara flagged the old page's scroll-while-streaming bug explicitly as +// something not to copy 1:1, and keeping "what rows exist" separate +// from "where the viewport is" is what makes that fixable — this hook +// only ever appends/prepends to `rows`, the DOM-owning component +// decides whether that should move the scroll position. // // Same subscribe → buffer → fetch-history → seq-dedupe → flush dance as -// terminal.js's `start()`: a live envelope landing between EventSource- -// open and the history response resolving is buffered, not dropped or -// double-counted (`envelope.seq <= history.seq` → already covered by the -// initial history page, drop it from the buffer). `seq` alone is the -// whole dedup signal, see `TermEnvelope`'s doc in hive-agent's -// `web_ui/stream.rs`. +// terminal.js's `start()`: a live event landing between EventSource-open +// and the history response resolving is buffered, not dropped or +// double-counted (seq <= history.seq AND the event's kind appeared in +// the history replay → already covered, drop it from the buffer). import { useEffect, useRef, useState } from 'preact/hooks'; -import type { TermEnvelope, TermRow } from '../lib/termMsg.js'; +import { classifyEvent, createClassifyCtx, type ClassifyCtx } from '../lib/classifyEvent.js'; +import type { StreamRow } from '../lib/streamRow.js'; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any -- raw SSE payload, dynamically shaped +type AnyEvent = any; export interface UseLiveStreamOptions { historyUrl?: string; streamUrl?: string; + /** Fired on every LIVE (not history-replay) turn_start/turn_end, so the + * caller can trigger a snappier `/api/state` refresh than the plain + * poll interval — mirrors app.js's turn_end → refreshState()/ + * refreshTodos(). */ + onLiveTurnBoundary?: () => void; } export interface UseLiveStreamResult { - rows: TermRow[]; + rows: StreamRow[]; hasMore: boolean; loadingMore: boolean; loadMore: () => void; @@ -37,12 +44,12 @@ export interface UseLiveStreamResult { clearLocal: () => void; } -function appendRow(rows: TermRow[], row: TermRow): TermRow[] { +function appendRow(rows: StreamRow[], row: StreamRow): StreamRow[] { const last = rows[rows.length - 1]; // Coalesce in place only while the coalescible row is still the last // one in the list — any other row landing in between starts a fresh // one, same rule as terminal.js's makeCoalescer. - if (row.coalesce_key && last && last.coalesce_key === row.coalesce_key) { + if (row.coalesceKey && last && last.coalesceKey === row.coalesceKey) { const next = rows.slice(0, -1); next.push({ ...row, key: last.key }); return next; @@ -50,60 +57,59 @@ function appendRow(rows: TermRow[], row: TermRow): TermRow[] { return [...rows, row]; } +function appendMany(rows: StreamRow[], newRows: StreamRow[]): StreamRow[] { + let next = rows; + for (const r of newRows) next = appendRow(next, r); + return next; +} + export function useLiveStream(opts: UseLiveStreamOptions = {}): UseLiveStreamResult { const historyUrl = opts.historyUrl ?? 'events/history'; const streamUrl = opts.streamUrl ?? 'events/stream'; - const [rows, setRows] = useState([]); + const [rows, setRows] = useState([]); const [hasMore, setHasMore] = useState(false); const [loadingMore, setLoadingMore] = useState(false); - const keySeqRef = useRef(0); - function nextKey(): string { - keySeqRef.current += 1; - return 'r' + keySeqRef.current; - } - function toRows(env: TermEnvelope, fromHistory: boolean): TermRow[] { - return env.msgs.map((m) => ({ ...m, key: nextKey(), fromHistory })); - } - function appendEnvelope(rows: TermRow[], env: TermEnvelope, fromHistory: boolean): TermRow[] { - let next = rows; - for (const row of toRows(env, fromHistory)) next = appendRow(next, row); - return next; - } - + const ctxRef = useRef(null); + if (!ctxRef.current) ctxRef.current = createClassifyCtx(); const minIdRef = useRef(null); const liveRef = useRef(false); - const bufferedRef = useRef([]); + const bufferedRef = useRef([]); + const onBoundaryRef = useRef(opts.onLiveTurnBoundary); + onBoundaryRef.current = opts.onLiveTurnBoundary; useEffect(() => { let cancelled = false; - function pushLive(env: TermEnvelope) { - if (env.msgs.length) setRows((prev) => appendEnvelope(prev, env, false)); + function pushLive(ev: AnyEvent) { + const newRows = classifyEvent(ev, false, ctxRef.current!); + if (newRows.length) setRows((prev) => appendMany(prev, newRows)); + if (ev.kind === 'turn_start' || ev.kind === 'turn_end') onBoundaryRef.current?.(); } const es = new EventSource(streamUrl); es.onmessage = (e) => { - let env: TermEnvelope; + let ev: AnyEvent; try { - env = JSON.parse(e.data); + ev = JSON.parse(e.data); } catch { setRows((prev) => appendRow(prev, { - key: 'parse-err-' + Date.now(), level: 'warn', summary: '[parse err] ' + e.data, fromHistory: false, + key: 'parse-err-' + Date.now(), cssClass: 'note', fromHistory: false, + text: '[parse err] ' + e.data, })); return; } if (!liveRef.current) { - bufferedRef.current.push(env); + bufferedRef.current.push(ev); return; } - pushLive(env); + pushLive(ev); }; es.onerror = () => { setRows((prev) => appendRow(prev, { - key: 'conn-note', level: 'warn', fromHistory: false, coalesce_key: 'conn-status', - summary: es.readyState === 0 /* CONNECTING */ ? '[reconnecting…]' : '[disconnected]', + key: 'conn-note', cssClass: 'note', fromHistory: false, coalesceKey: 'conn-status', + text: es.readyState === 0 /* CONNECTING */ ? '[reconnecting…]' : '[disconnected]', })); }; @@ -112,29 +118,30 @@ export function useLiveStream(opts: UseLiveStreamOptions = {}): UseLiveStreamRes const resp = await fetch(historyUrl); if (!resp.ok) throw new Error('http ' + resp.status); const body = await resp.json(); - const events: TermEnvelope[] = Array.isArray(body) ? body : body.events || []; + const events: AnyEvent[] = Array.isArray(body) ? body : body.events || []; const boundarySeq: number | null = Array.isArray(body) ? null : (body.seq ?? null); if (!Array.isArray(body)) { setHasMore(!!body.has_more); if (typeof body.min_id === 'number') minIdRef.current = body.min_id; } + const historyKinds = new Set(events.map((e) => e.kind)); if (cancelled) return; - let initial: TermRow[] = []; - for (const env of events) initial = appendEnvelope(initial, env, true); + let initial: StreamRow[] = []; + for (const ev of events) initial = appendMany(initial, classifyEvent(ev, true, ctxRef.current!)); initial = events.length - ? appendRow(initial, { key: 'live-sep', level: 'debug', fromHistory: true, summary: '─── live (older above) ───' }) - : [{ key: 'placeholder', level: 'debug', fromHistory: true, summary: '(connected — waiting for events)' }]; + ? appendRow(initial, { key: 'live-sep', cssClass: 'note', fromHistory: true, text: '─── live (older above) ───' }) + : [{ key: 'placeholder', cssClass: 'note', fromHistory: true, text: '(connected — waiting for events)' }]; setRows(initial); const drained = bufferedRef.current; bufferedRef.current = []; liveRef.current = true; - for (const env of drained) { - // Already covered by the initial history page — drop it from - // the buffer rather than rendering it twice. - if (boundarySeq != null && typeof env.seq === 'number' && env.seq <= boundarySeq) continue; - pushLive(env); + for (const ev of drained) { + if (boundarySeq != null && typeof ev.seq === 'number' && ev.seq <= boundarySeq && historyKinds.has(ev.kind)) { + continue; + } + pushLive(ev); } } catch (err) { console.warn('history backfill failed', err); @@ -142,7 +149,7 @@ export function useLiveStream(opts: UseLiveStreamOptions = {}): UseLiveStreamRes const drained = bufferedRef.current; bufferedRef.current = []; liveRef.current = true; - for (const env of drained) pushLive(env); + for (const ev of drained) pushLive(ev); } } backfill(); @@ -161,14 +168,14 @@ export function useLiveStream(opts: UseLiveStreamOptions = {}): UseLiveStreamRes const resp = await fetch(historyUrl + sep + 'before=' + minIdRef.current); if (!resp.ok) return; const body = await resp.json(); - const events: TermEnvelope[] = Array.isArray(body) ? body : body.events || []; + const events: AnyEvent[] = Array.isArray(body) ? body : body.events || []; setHasMore(!!body.has_more); if (typeof body.min_id === 'number') minIdRef.current = body.min_id; if (events.length) { - let older: TermRow[] = []; - for (const env of events) older = appendEnvelope(older, env, true); + let older: StreamRow[] = []; + for (const ev of events) older = appendMany(older, classifyEvent(ev, true, ctxRef.current!)); older = appendRow(older, { - key: 'older-sep-' + minIdRef.current, level: 'debug', fromHistory: true, summary: '─── older above ───', + key: 'older-sep-' + minIdRef.current, cssClass: 'note', fromHistory: true, text: '─── older above ───', }); setRows((prev) => [...older, ...prev]); } @@ -179,8 +186,10 @@ export function useLiveStream(opts: UseLiveStreamOptions = {}): UseLiveStreamRes } } + const localKeyRef = useRef(0); function pushLocalNote(text: string) { - setRows((prev) => appendRow(prev, { key: 'local-' + nextKey(), level: 'info', fromHistory: false, summary: text })); + localKeyRef.current += 1; + setRows((prev) => appendRow(prev, { key: `local-${localKeyRef.current}`, cssClass: 'note', fromHistory: false, text })); } function clearLocal() { setRows([]); diff --git a/frontend/packages/agent/src/lib/classifyEvent.ts b/frontend/packages/agent/src/lib/classifyEvent.ts new file mode 100644 index 00000000..743f02b4 --- /dev/null +++ b/frontend/packages/agent/src/lib/classifyEvent.ts @@ -0,0 +1,268 @@ +// Turns one raw harness/stream-json event into zero or more `StreamRow`s. +// Preact-data port of app.js's `renderStream` / `renderRichToolUse` / +// `renderToolResult` / `renderTaskEvent` — see docs/terminal-rendering.md +// for the row taxonomy this mirrors. Almost all per-tool classification +// is already done server-side (`hive-agent/src/stream_enrich.rs::enrich` +// stamps `_icon`/`_summary`/`_category`/`_body`/`_body_type`), so this +// mostly just dispatches on those fields rather than re-deriving them. +// +// One deliberate simplification vs. app.js: the client-side "compacting… +// s" live override on `system/status` ticks (computed from the +// harness's local `stateSince`) isn't ported — this just shows the +// backend's `_summary` as-is. `turn_state`/`state_since` (and therefore +// the "compacting" badge itself) still update correctly via +// useAgentState's poll; only that one status row's live elapsed-seconds +// text loses its client-side tick. Revisit if that's missed in practice. +import type { StreamRow, StreamRowMeta } from './streamRow.js'; +import { fmtAge, fmtClock } from './format.js'; +import { getExpandDetailsPref } from '@hive/shared/prefs.js'; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any -- stream-json +// content is dynamically-shaped JSON, same as app.js's untyped handling. +type AnyEvent = any; + +export interface ClassifyCtx { + toolNameById: Map; + pendingTurnStartTs: { current: number | null }; + keySeq: { current: number }; +} + +export function createClassifyCtx(): ClassifyCtx { + return { toolNameById: new Map(), pendingTurnStartTs: { current: null }, keySeq: { current: 0 } }; +} + +function nextKey(ctx: ClassifyCtx): string { + ctx.keySeq.current += 1; + return 'r' + ctx.keySeq.current; +} + +function trim(s: string, n: number): string { + return s.length > n ? s.slice(0, n) + '…' : s; +} + +export function classifyEvent(ev: AnyEvent, fromHistory: boolean, ctx: ClassifyCtx): StreamRow[] { + switch (ev.kind) { + case 'turn_start': + return [classifyTurnStart(ev, fromHistory, ctx)]; + case 'turn_end': + return [classifyTurnEnd(ev, fromHistory, ctx)]; + case 'note': + return [classifyNote(ev, fromHistory, ctx)]; + case 'stream': { + const v = { ...ev }; + delete v.kind; + return classifyStream(v, fromHistory, ctx); + } + default: + // status_changed / model_changed / effort_changed / + // token_usage_changed / turn_state_changed drive badges elsewhere + // (useAgentState's poll — see Root.tsx) rather than rows here. + return []; + } +} + +function classifyTurnStart(ev: AnyEvent, fromHistory: boolean, ctx: ClassifyCtx): StreamRow { + const meta: StreamRowMeta[] = []; + if (typeof ev.ts === 'number') { + ctx.pendingTurnStartTs.current = ev.ts; + meta.push({ cls: 'turn-time', text: '· ' + fmtClock(ev.ts) }); + } + if (ev.unread > 0) { + meta.push({ cls: 'unread-badge', text: '· ' + ev.unread + ' unread' }); + } + return { + key: nextKey(ctx), + cssClass: 'turn-start', + fromHistory, + text: '◆ TURN ← ' + ev.from, + meta, + childText: { cls: 'turn-body', text: String(ev.body ?? '') }, + }; +} + +function classifyTurnEnd(ev: AnyEvent, fromHistory: boolean, ctx: ClassifyCtx): StreamRow { + const meta: StreamRowMeta[] = []; + if (typeof ev.ts === 'number') { + let label = '· ' + fmtClock(ev.ts); + if (ctx.pendingTurnStartTs.current != null && ev.ts >= ctx.pendingTurnStartTs.current) { + label += ' · ' + fmtAge((ev.ts - ctx.pendingTurnStartTs.current) * 1000); + } + meta.push({ cls: 'turn-time', text: label }); + } + ctx.pendingTurnStartTs.current = null; + return { + key: nextKey(ctx), + cssClass: ev.ok ? 'turn-end-ok' : 'turn-end-fail', + fromHistory, + text: (ev.ok ? '✅' : '❌') + ' turn ' + (ev.ok ? 'ok' : 'fail') + (ev.note ? ' — ' + ev.note : ''), + meta, + }; +} + +function classifyNote(ev: AnyEvent, fromHistory: boolean, ctx: ClassifyCtx): StreamRow { + const t = String(ev.text ?? ''); + if (t.startsWith('stderr:')) return { key: nextKey(ctx), cssClass: 'note stderr', fromHistory, text: '! ' + t }; + if (t.startsWith('operator:')) return { key: nextKey(ctx), cssClass: 'note op', fromHistory, text: '· ' + t }; + return { key: nextKey(ctx), cssClass: 'note', fromHistory, text: '· ' + t }; +} + +function classifyStream(v: AnyEvent, fromHistory: boolean, ctx: ClassifyCtx): StreamRow[] { + if (v._category === 'drop') return []; + + if (v.type === 'system') { + const cat = v._category; + const summary = v._summary; + if (cat === 'thinking_tok') { + return [{ + key: nextKey(ctx), cssClass: 'note', icon: '🧠', fromHistory, + text: summary || 'thinking…', coalesceKey: 'thinking-tok', + }]; + } + if (v.subtype === 'plugin_install') { + return [{ + key: nextKey(ctx), cssClass: 'note', fromHistory, + text: summary || '⚙ plugin install', coalesceKey: 'plugin-install', + }]; + } + if (v.subtype === 'status') { + return [{ + key: nextKey(ctx), cssClass: 'note', fromHistory, + text: summary || '⚙ status', coalesceKey: 'status-tick', + }]; + } + if (cat === 'details') { + return [{ + key: nextKey(ctx), cssClass: 'note', fromHistory, details: true, + text: summary || '⚙ ' + (v.subtype || ''), plainBody: v._body || '', + }]; + } + return [{ key: nextKey(ctx), cssClass: 'note', fromHistory, text: summary || '⚙ ' + (v.subtype || 'system') }]; + } + + if (v.subtype === 'task_started' || v.subtype === 'task_notification') { + const row = classifyTaskEvent(v, fromHistory, ctx); + if (row) return [row]; + } + + if (v.type === 'assistant' && v.message && v.message.content) { + const rows: StreamRow[] = []; + for (const c of v.message.content) { + if (c.type === 'text' && c.text && String(c.text).trim()) { + rows.push({ key: nextKey(ctx), cssClass: 'text', fromHistory, markdownBody: c.text }); + } else if (c.type === 'thinking') { + const txt = String(c.thinking || c.text || '').trim(); + rows.push({ key: nextKey(ctx), cssClass: 'thinking', icon: '💭', fromHistory, text: txt || 'thinking …' }); + } else if (c.type === 'tool_use') { + if (c.id && c.name) ctx.toolNameById.set(c.id, c.name); + rows.push(classifyToolUse(c, fromHistory, ctx)); + } + } + return rows; + } + + if (v.type === 'user' && v.message && v.message.content) { + const rows: StreamRow[] = []; + for (const c of v.message.content) { + if (c.type === 'tool_result') rows.push(classifyToolResult(c, fromHistory, ctx)); + } + return rows; + } + + return [{ key: nextKey(ctx), cssClass: 'sys', fromHistory, text: '! ' + trim(JSON.stringify(v), 200) }]; +} + +// `_category === 'rich'` tools get an expandable row: diff body (Edit), +// default-open markdown body (send/recv-shaped, always open regardless +// of the preference below — matches app.js), or a plain +// body (collapsed unless the operator's "expand tool output" preference +// says otherwise — @hive/shared/prefs.js's getExpandDetailsPref(), read +// fresh per row so a mid-session preference change applies going +// forward without a reload) — all pre-computed server-side, no per-tool +// JS needed. +function classifyToolUse(c: AnyEvent, fromHistory: boolean, ctx: ClassifyCtx): StreamRow { + const icon = c._icon || '🔧'; + const name = c.name || ''; + if (c._category === 'rich' && c._body != null) { + const summary = c._summary || name || '?'; + if (c._body_type === 'diff') { + return { + key: nextKey(ctx), cssClass: 'tool-use', fromHistory, details: true, defaultOpen: getExpandDetailsPref(), + icon, text: summary, diffBody: c._body, + }; + } + if (c._body_type === 'markdown') { + return { + key: nextKey(ctx), cssClass: 'tool-use', fromHistory, details: true, defaultOpen: true, + icon, text: summary, markdownBody: c._body, + }; + } + return { + key: nextKey(ctx), cssClass: 'tool-use', fromHistory, details: true, defaultOpen: getExpandDetailsPref(), + icon, text: summary, plainBody: c._body, + }; + } + return { key: nextKey(ctx), cssClass: 'tool-use', fromHistory, icon, text: c._summary || name || '?' }; +} + +function classifyToolResult(c: AnyEvent, fromHistory: boolean, ctx: ClassifyCtx): StreamRow { + const rawTxt = Array.isArray(c.content) ? c.content.map((p: AnyEvent) => p.text || '').join('') : c.content || ''; + const isError = !!c.is_error; + // Strip the wrapper — implementation + // detail claude emits on failed tool calls, adds nothing for the operator. + const txt = isError + ? String(rawTxt).replace(/^([\s\S]*)<\/tool_use_error>$/, '$1').trim() + : String(rawTxt); + const sourceName = c.tool_use_id ? ctx.toolNameById.get(c.tool_use_id) : null; + const isMessageBearing = sourceName === 'mcp__hyperhive__recv'; + const trimmed = txt.replace(/\s+/g, ' ').trim(); + const summaryBody = (() => { + if (!trimmed) return '(empty)'; + if (trimmed.length <= 120) return trimmed; + const lines = txt.split('\n').filter((l: string) => l.length).length; + const headline = trimmed.slice(0, 90) + '…'; + return `${lines}L · ${headline}`; + })(); + if (isError) { + if (!txt.trim() || txt.length <= 120) { + return { key: nextKey(ctx), cssClass: 'tool-result error', fromHistory, text: '✗ ' + summaryBody }; + } + return { + key: nextKey(ctx), cssClass: 'tool-result-block error', fromHistory, details: true, + defaultOpen: getExpandDetailsPref(), text: summaryBody, plainBody: txt, + }; + } + if (isMessageBearing && txt.trim()) { + return { + key: nextKey(ctx), cssClass: 'tool-result-block', fromHistory, details: true, defaultOpen: true, + text: 'recv ← ' + summaryBody, markdownBody: txt, + }; + } + if (!txt.trim() || txt.length <= 120) { + return { key: nextKey(ctx), cssClass: 'tool-result', fromHistory, text: '← ' + summaryBody }; + } + return { + key: nextKey(ctx), cssClass: 'tool-result-block', fromHistory, details: true, + defaultOpen: getExpandDetailsPref(), text: summaryBody, plainBody: txt, + }; +} + +// Subagent (claude `Task`-tool) activity — dead path for agents today +// (`Task` is omitted from the allow-list) but kept for parity, same as +// app.js's `renderTaskEvent`. Glyph stays embedded in the row text +// (not routed through the icon column) — matches the original exactly. +function classifyTaskEvent(v: AnyEvent, fromHistory: boolean, ctx: ClassifyCtx): StreamRow | null { + const id = String(v.task_id || '').slice(0, 8); + const kind = v.task_type ? ` [${v.task_type}]` : ''; + const desc = v.description || v.summary || '(no description)'; + if (v.subtype === 'task_started') { + return { key: nextKey(ctx), cssClass: 'tool-use', fromHistory, text: `⌁ task ${id} started · ${desc}${kind}` }; + } + if (v.subtype === 'task_notification') { + const status = v.status || 'unknown'; + const glyph = status === 'completed' ? '✓' : status === 'failed' ? '✗' : '◌'; + const cssClass = status === 'completed' ? 'turn-end-ok' : status === 'failed' ? 'turn-end-fail' : 'tool-result'; + const out = v.output_file ? ` · → ${v.output_file}` : ''; + return { key: nextKey(ctx), cssClass, fromHistory, text: `⌁ task ${id} ${glyph} ${status} · ${desc}${out}` }; + } + return null; +} diff --git a/frontend/packages/agent/src/lib/format.ts b/frontend/packages/agent/src/lib/format.ts index 11201359..37797e8c 100644 --- a/frontend/packages/agent/src/lib/format.ts +++ b/frontend/packages/agent/src/lib/format.ts @@ -15,3 +15,10 @@ export function fmtAge(ms: number): string { const h = Math.floor(m / 60); return h + 'h ' + (m % 60) + 'm'; } + +/** Wall-clock HH:MM:SS (UTC) from a unix-seconds value — labels + * turn-start / turn-end rows in the live stream (ported from app.js's + * `fmtClock`). */ +export function fmtClock(sec: number): string { + return new Date(sec * 1000).toISOString().slice(11, 19); +} diff --git a/frontend/packages/agent/src/lib/streamRow.ts b/frontend/packages/agent/src/lib/streamRow.ts new file mode 100644 index 00000000..53328c4f --- /dev/null +++ b/frontend/packages/agent/src/lib/streamRow.ts @@ -0,0 +1,49 @@ +// Row model for the live event stream. One `StreamRow` = one rendered +// line/panel in the terminal pane; `classifyEvent` (classifyEvent.ts) +// turns a raw harness/stream-json event into zero or more of these, and +// `` (components/Row.tsx) renders one. Kept as plain data (not JSX) +// so the append/coalesce bookkeeping in useLiveStream.ts stays pure — +// see docs/terminal-rendering.md for the exact taxonomy this mirrors. + +export interface StreamRowMeta { + cls: string; + text: string; +} + +export interface StreamRow { + /** Stable across re-renders; reused in place when a row is coalesced + * (e.g. the thinking-token counter) so Preact updates rather than + * remounts it. */ + key: string; + /** Space-joined class names appended after "row" / "row details", e.g. + * "turn-start", "tool-result error" — taken verbatim from + * @hive/shared/terminal.css's row-kind taxonomy. */ + cssClass: string; + icon?: string; + fromHistory: boolean; + /** When set, an event that maps to the same coalesceKey and lands + * while this row is still the last one in the list replaces it in + * place instead of appending a new row (thinking-token ticks, status + * ticks, plugin_install started→completed). */ + coalesceKey?: string; + /** `false`/absent → flat `
`; `true` → `
` with `.summary-text` + optional body. */ + details?: boolean; + defaultOpen?: boolean; + /** Flat-row prefix text, or the details `` text. Linkified, + * never markdown. */ + text?: string; + /** Small trailing spans after the prefix text (turn-time, unread + * count) — flat rows only. */ + meta?: StreamRowMeta[]; + /** Plain-text child block under a flat row (just the turn-start wake + * body today) — its own class, no markdown parsing. */ + childText?: StreamRowMeta; + /** Sanitized-markdown body: appended under a flat row (assistant + * text) or inside an open details row (send/recv bodies). */ + markdownBody?: string; + /** Plain `
` body inside a details row (generic long tool output). */
+  plainBody?: string;
+  /** `+`/`-`/context diff body inside a details row (Edit tool). */
+  diffBody?: string;
+}
diff --git a/frontend/packages/agent/src/lib/termMsg.ts b/frontend/packages/agent/src/lib/termMsg.ts
deleted file mode 100644
index ecfdb717..00000000
--- a/frontend/packages/agent/src/lib/termMsg.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-// Wire types for the agent's terminal stream — mirrors hive-agent's
-// `term_msg.rs`/`web_ui/stream.rs` field-for-field. The frontend renders
-// a `TermMsg` close to as-is (see components/Row.tsx); there's no
-// separate client-side row model or classification step any more —
-// mara: "StreamRow should now match what the server sends in TermMsg."
-export type Level = 'debug' | 'info' | 'warn' | 'error';
-
-export interface TermMsg {
-  icon?: string;
-  level: Level;
-  summary: string;
-  body?: string;
-  body_format?: 'markdown' | 'diff';
-  coalesce_key?: string;
-}
-
-/** One SSE frame / history array entry — `hive-agent`'s `TermEnvelope`.
- * `seq` is the live per-event dedup counter (`BusEvent::seq`); absent on
- * history-replayed envelopes, see useLiveStream.ts's backfill dance. */
-export interface TermEnvelope {
-  ts: number;
-  seq?: number;
-  msgs: TermMsg[];
-}
-
-/** A `TermMsg` plus the bookkeeping Preact needs to render a list —
- * stable identity for coalescing/keys, and whether it came from history
- * replay vs. the live tail. Not a separate model: everything content-wise
- * is still exactly the wire shape. */
-export interface TermRow extends TermMsg {
-  key: string;
-  fromHistory: boolean;
-}
diff --git a/frontend/packages/shared/src/terminal/terminal.css b/frontend/packages/shared/src/terminal/terminal.css
index 32e03010..da1832f4 100644
--- a/frontend/packages/shared/src/terminal/terminal.css
+++ b/frontend/packages/shared/src/terminal/terminal.css
@@ -97,34 +97,55 @@
   display: inline-block;
   width: 1.4em;
 }
-/* Row colours, keyed by severity `level` (hive-agent's `term_msg.rs`),
-   not by row kind any more — mara's terminal-message redesign dropped
-   the server-side `kind` tag (turn-start/tool-use/tool-result/etc) in
-   favour of one uniform shape, `{icon, level, summary, body,
-   body_format, coalesce_key}`. What used to be a dozen-odd per-kind
-   classes (`.turn-start`, `.tool-use`, `.tool-result.error`, `.sys`, …)
-   is now four: the four severities every row already carries. Structural
-   identity (this is a turn boundary, this is a tool call) is carried by
-   the row's icon (`◆`, `🔧`, `✅`, …) and summary text instead of colour —
-   see docs/terminal-rendering.md. */
-.live .level-debug { color: var(--muted); }
-.live .level-info  { color: var(--fg); }
-.live .level-warn  { color: var(--amber); border-left-color: var(--amber); }
-.live .level-error { color: var(--red);   border-left-color: var(--red);  }
-/* `badge-pulse` itself is no longer used by any terminal row (the
-   turn-start `unread` count it animated is gone — see term_msg.rs's
-   module doc), but agent.css's `.state-badge.state-thinking`/
-   `.state-compacting` badges still reuse this keyframe via
-   `@import "@hive/shared/terminal.css"` — keep the definition here, drop
-   only the terminal-specific `.unread-badge` selector that used it. */
-@keyframes badge-pulse {
-  0%, 100% { opacity: 1;   text-shadow: 0 0 6px color-mix(in srgb, var(--amber) 55%, transparent); }
-  50%      { opacity: 0.7; text-shadow: 0 0 14px color-mix(in srgb, var(--amber) 95%, transparent); }
-}
+/* Row-kind colours. Pages register renderers that emit these classes;
+   any class no page emits is just dead CSS, which is fine. Turn-framing
+   classes carry their signal entirely on the coloured border-left rule —
+   no bold, no top/bottom margins, no background tint. The chrome was
+   overweight for what's just a "this is a boundary" marker. */
+.live .turn-start    { color: var(--amber); border-left-color: var(--amber); }
+/* turn-body is a child block under turn-start carrying the wake-prompt
+   body; reset text-indent so wrapped content stays under its own column
+   instead of pulling back into the parent's prefix. */
+.live .turn-body     { color: var(--fg); text-indent: 0; margin-top: 0.15em; }
 /* Any child block (markdown body, nested details) resets the parent
    row's hanging indent so the content lays out from column 0 of the
    body area. */
 .live .row .md, .live .row > details { text-indent: 0; }
+.live .turn-end-ok   { color: var(--green); border-left-color: var(--green); }
+.live .turn-end-fail { color: var(--red);   border-left-color: var(--red); }
+/* Wall-clock time (+ duration on turn-end) appended to the turn-start /
+   turn-end rows. Dim + smaller so the boundary glyph stays the focus and
+   the timestamp reads as metadata. */
+.live .turn-time   { color: var(--muted); font-size: 0.85em; margin-left: 0.5em; }
+.live .text        { color: var(--fg);    }
+.live .thinking    { color: var(--muted); font-style: italic; }
+.live .tool-use    { color: var(--cyan);  }
+.live .tool-result              { color: var(--muted); }
+.live .tool-result.error        { color: var(--red);   }
+.live .tool-result-block.error  { color: var(--red);   }
+.live .result      { color: var(--green); }
+.live .note        { color: var(--muted); }
+/* Distinguish stderr lines (orange) and operator-initiated notes
+   (mauve, lightly emphasised) from ambient harness chatter so the
+   eye picks out anomalies + operator actions in the scrollback. */
+.live .note.stderr { color: var(--amber); }
+.live .note.op     { color: var(--purple); font-style: italic; }
+/* The .sys catch-all fires when renderStream landed an event shape it
+   couldn't classify. Make it visually loud so silently-dropped event
+   types surface for follow-up. */
+.live .sys         { color: var(--amber); }
+.live .unread-badge {
+  color: var(--amber);
+  font-weight: normal;
+  margin-left: 0.6em;
+  font-size: 0.85em;
+  text-shadow: 0 0 6px color-mix(in srgb, var(--amber) 55%, transparent);
+  animation: badge-pulse 1.4s ease-in-out infinite;
+}
+@keyframes badge-pulse {
+  0%, 100% { opacity: 1;   text-shadow: 0 0 6px color-mix(in srgb, var(--amber) 55%, transparent); }
+  50%      { opacity: 0.7; text-shadow: 0 0 14px color-mix(in srgb, var(--amber) 95%, transparent); }
+}
 /* "↓ N new" pill: shown when new rows arrive while the operator is
    scrolled up; click to jump to bottom. Positioned by the wrapper's
    `position: relative` (terminal-wrap supplies it; pages that skip the
diff --git a/hive-agent/src/main.rs b/hive-agent/src/main.rs
index 26619a86..a0ecf104 100644
--- a/hive-agent/src/main.rs
+++ b/hive-agent/src/main.rs
@@ -28,7 +28,6 @@ mod serve_common;
 mod state_entry_watch;
 mod stats;
 mod stream_enrich;
-mod term_msg;
 mod todo_server;
 mod todos;
 mod turn;
diff --git a/hive-agent/src/stream_enrich.rs b/hive-agent/src/stream_enrich.rs
index 39921b9d..089a72b7 100644
--- a/hive-agent/src/stream_enrich.rs
+++ b/hive-agent/src/stream_enrich.rs
@@ -1,97 +1,75 @@
-//! Classify raw claude stream-json values into [`crate::term_msg::TermMsg`]
-//! rows before SSE delivery.
+//! Enrich raw claude stream-json values before SSE delivery.
 //!
-//! [`classify_stream_value`] is the entry point — it walks one raw claude
-//! `stream-json` line (the payload of a [`crate::events::LiveEvent::Stream`])
-//! and returns zero or more terminal rows. Applied at SSE-emit time in
-//! `crate::web_ui::stream` so both the live tail (`events/stream`) and the
-//! history replay (`events/history`) endpoints deliver the same classified
-//! shape — the sqlite event log stores the raw, unclassified event, so the
-//! DB never needs migration when classification logic changes.
+//! A single [`enrich`] function stamps `_icon`, `_summary`, `_category`,
+//! and optionally `_body` onto [`crate::events::LiveEvent::Stream`] payloads
+//! so the frontend can read pre-computed fields instead of duplicating the
+//! dispatch logic in JavaScript.
 //!
-//! The per-tool icon/summary formatting below (`tool_icon`, `fmt_tool_use`
-//! and its per-family helpers, `rich_tool_body`) is reused as-is from
-//! before mara's terminal-message redesign — that logic (what does
-//! `mcp__hyperhive__send`'s row say, which tools get an expandable body)
-//! didn't change; only the shape it gets packed into did.
+//! The sqlite event log stores raw (un-enriched) events — the DB never needs
+//! migration when the enrichment logic changes. Enrichment is applied at
+//! SSE-emit time in `crate::web_ui::stream` so both the live tail
+//! (`events/stream`) and the history replay (`events/history`) endpoints
+//! deliver the same enriched shape.
+//!
+//! # Migration (two-phase)
+//!
+//! **Phase 1** (this change): backend stamps `_icon`/`_summary`/`_category`
+//! fields; the client reads them when present and falls back to its own JS
+//! tables when absent. Zero user-visible change — a no-op for clients that
+//! haven't yet been updated.
+//!
+//! **Phase 2** (follow-up): the client drops the JS tables once phase 1 is
+//! deployed everywhere.
 
-use crate::term_msg::{BodyFormat, ClassifyCtx, Level, TermMsg};
 use serde_json::{Value, json};
 
-/// Classify one raw claude stream-json line into zero or more terminal rows.
+/// Stamp enrichment fields onto a raw claude stream-json [`Value`].
 ///
-/// Dispatch order mirrors the old client-side `classifyEvent.ts` (before
-/// this classification moved server-side):
-/// top-level drop-noise types first, then `type="system"`, then task events
-/// (matched on `subtype` regardless of `type`), then `assistant`/`user`
-/// content, with an unrecognised shape falling through to a loud
-/// warn-level catch-all so a silently-dropped event type stays visible.
-pub fn classify_stream_value(v: &Value, ctx: &mut ClassifyCtx) -> Vec {
-    let vtype = v.get("type").and_then(Value::as_str).unwrap_or("");
-    if matches!(vtype, "result" | "rate_limit_event") {
-        return vec![];
+/// - `type="system"` events get `_category` + `_summary` (and `_body` for
+///   expandable detail, e.g. `commands_changed`).
+/// - `type="assistant"` events get `_icon`, `_summary`, and optionally
+///   `_category: "rich"` stamped onto each `message.content[]` entry that
+///   has `type="tool_use"`.
+///
+/// No-ops for unknown/unhandled top-level types. Existing `_`-prefixed fields
+/// are left unchanged so the call is idempotent (history replay may hit
+/// already-enriched values if the DB is ever pre-populated by a future phase).
+pub fn enrich(v: &mut Value) {
+    match v.get("type").and_then(Value::as_str).unwrap_or("") {
+        // Top-level result/rate_limit_event are drop-category noise — stamp
+        // the same category the frontend uses to silently discard them.
+        "result" | "rate_limit_event" => {
+            if let Some(obj) = v.as_object_mut() {
+                obj.entry("_category").or_insert_with(|| json!("drop"));
+            }
+        }
+        "system" => enrich_system(v),
+        "assistant" => enrich_assistant(v),
+        _ => {}
     }
-    if vtype == "system" {
-        return classify_system(v);
-    }
-    let subtype = v.get("subtype").and_then(Value::as_str);
-    if matches!(subtype, Some("task_started" | "task_notification")) {
-        return classify_task_event(v).into_iter().collect();
-    }
-    if vtype == "assistant" {
-        return v
-            .get("message")
-            .and_then(|m| m.get("content"))
-            .and_then(Value::as_array)
-            .map_or_else(Vec::new, |content| classify_assistant_content(content, ctx));
-    }
-    if vtype == "user" {
-        return v
-            .get("message")
-            .and_then(|m| m.get("content"))
-            .and_then(Value::as_array)
-            .map_or_else(Vec::new, |content| classify_user_content(content, ctx));
-    }
-    vec![TermMsg::new(Level::Warn, trim_str(&v.to_string(), 200)).icon("!")]
 }
 
 // ---------------------------------------------------------------------------
 // system events
 // ---------------------------------------------------------------------------
 
-fn classify_system(v: &Value) -> Vec {
-    let subtype = v.get("subtype").and_then(Value::as_str).unwrap_or("");
-    let (category, summary, body) = system_fields(v, subtype);
-    match category {
-        "drop" => vec![],
-        "thinking_tok" => vec![
-            TermMsg::new(
-                Level::Debug,
-                summary.unwrap_or_else(|| "thinking…".to_owned()),
-            )
-            .icon("🧠")
-            .coalesce("thinking-tok"),
-        ],
-        "details" => {
-            let mut m = TermMsg::new(Level::Debug, summary.unwrap_or_default());
-            if let Some(b) = body {
-                m = m.body(b, None);
-            }
-            vec![m]
-        }
-        // "note" category — ambient harness/system chatter. Level + coalesce
-        // key vary by subtype; everything else defaults to a plain debug note.
-        _ => {
-            let s = summary.unwrap_or_default();
-            let m = match subtype {
-                "api_error" => TermMsg::new(Level::Error, s),
-                "api_retry" => TermMsg::new(Level::Warn, s),
-                "plugin_install" => TermMsg::new(Level::Debug, s).coalesce("plugin-install"),
-                "status" => TermMsg::new(Level::Debug, s).coalesce("status-tick"),
-                _ => TermMsg::new(Level::Debug, s),
-            };
-            vec![m]
-        }
+fn enrich_system(v: &mut Value) {
+    if v.get("_category").is_some() {
+        return; // idempotent
+    }
+    let subtype = v
+        .get("subtype")
+        .and_then(Value::as_str)
+        .unwrap_or("")
+        .to_owned();
+    let (category, summary, body) = system_fields(v, &subtype);
+    let Some(obj) = v.as_object_mut() else { return };
+    obj.insert("_category".to_owned(), json!(category));
+    if let Some(s) = summary {
+        obj.insert("_summary".to_owned(), json!(s));
+    }
+    if let Some(b) = body {
+        obj.insert("_body".to_owned(), json!(b));
     }
 }
 
@@ -219,197 +197,51 @@ fn system_fields(v: &Value, subtype: &str) -> (&'static str, Option, Opt
 }
 
 // ---------------------------------------------------------------------------
-// assistant events (claude's own output: text / thinking / tool calls)
+// assistant events
 // ---------------------------------------------------------------------------
 
-fn classify_assistant_content(content: &[Value], ctx: &mut ClassifyCtx) -> Vec {
-    let mut rows = Vec::new();
-    for c in content {
-        match c.get("type").and_then(Value::as_str) {
-            Some("text") => {
-                let text = c.get("text").and_then(Value::as_str).unwrap_or("");
-                if !text.trim().is_empty() {
-                    // No separate summary line — the markdown body is the
-                    // whole row, matching the old `.text` row shape.
-                    rows.push(
-                        TermMsg::new(Level::Info, String::new())
-                            .body(text.to_owned(), Some(BodyFormat::Markdown)),
-                    );
-                }
-            }
-            Some("thinking") => {
-                let txt = c
-                    .get("thinking")
-                    .or_else(|| c.get("text"))
-                    .and_then(Value::as_str)
-                    .unwrap_or("")
-                    .trim()
-                    .to_owned();
-                let summary = if txt.is_empty() {
-                    "thinking …".to_owned()
-                } else {
-                    txt
-                };
-                rows.push(TermMsg::new(Level::Debug, summary).icon("💭"));
-            }
-            Some("tool_use") => {
-                if let (Some(id), Some(name)) = (
-                    c.get("id").and_then(Value::as_str),
-                    c.get("name").and_then(Value::as_str),
-                ) {
-                    ctx.record_tool_use(id, name);
-                }
-                rows.push(classify_tool_use(c));
-            }
-            _ => {}
-        }
-    }
-    rows
-}
-
-/// `_category === 'rich'` tools used to get an expandable row (diff body
-/// for Edit, markdown body for send, plain for everything else with a
-/// body). That's now just "does this row have a body" — `body.is_some()`
-/// on the returned [`TermMsg`] *is* the expandable signal, no separate
-/// flag.
-fn classify_tool_use(c: &Value) -> TermMsg {
-    let name = c.get("name").and_then(Value::as_str).unwrap_or("");
-    let input = c.get("input").cloned().unwrap_or_else(|| json!({}));
-    let mut m = TermMsg::new(Level::Info, fmt_tool_use(name, &input)).icon(tool_icon(name));
-    if let Some((body, body_type)) = rich_tool_body(name, &input) {
-        let format = match body_type {
-            "diff" => Some(BodyFormat::Diff),
-            "markdown" => Some(BodyFormat::Markdown),
-            _ => None, // "plain"
-        };
-        m = m.body(body, format);
-    }
-    m
-}
-
-// ---------------------------------------------------------------------------
-// user events (tool_result — claude's own tool calls answered)
-// ---------------------------------------------------------------------------
-
-fn classify_user_content(content: &[Value], ctx: &ClassifyCtx) -> Vec {
-    content
-        .iter()
-        .filter(|c| c.get("type").and_then(Value::as_str) == Some("tool_result"))
-        .map(|c| classify_tool_result(c, ctx))
-        .collect()
-}
-
-/// `` is claude's own wrapper on failed
-/// tool calls — implementation detail, adds nothing for the operator.
-fn strip_tool_use_error_wrapper(s: &str) -> String {
-    let trimmed = s.trim();
-    trimmed
-        .strip_prefix("")
-        .and_then(|rest| rest.strip_suffix(""))
-        .map_or_else(|| trimmed.to_owned(), |inner| inner.trim().to_owned())
-}
-
-fn classify_tool_result(c: &Value, ctx: &ClassifyCtx) -> TermMsg {
-    let raw_txt = match c.get("content") {
-        Some(Value::Array(parts)) => parts
-            .iter()
-            .filter_map(|p| p.get("text").and_then(Value::as_str))
-            .collect::(),
-        Some(Value::String(s)) => s.clone(),
-        _ => String::new(),
+fn enrich_assistant(v: &mut Value) {
+    // Navigate message.content[] — absent on text-only turns.
+    let Some(content) = v
+        .get_mut("message")
+        .and_then(|m| m.get_mut("content"))
+        .and_then(Value::as_array_mut)
+    else {
+        return;
     };
-    let is_error = c.get("is_error").and_then(Value::as_bool).unwrap_or(false);
-    let txt = if is_error {
-        strip_tool_use_error_wrapper(&raw_txt)
-    } else {
-        raw_txt
-    };
-
-    let tool_use_id = c.get("tool_use_id").and_then(Value::as_str);
-    let source_name = tool_use_id.and_then(|id| ctx.tool_name(id));
-    let is_message_bearing = source_name == Some("mcp__hyperhive__recv");
-
-    let trimmed: String = txt.split_whitespace().collect::>().join(" ");
-    let summary = summarize_tool_result(&txt, &trimmed);
-    let short = txt.trim().is_empty() || txt.chars().count() <= 120;
-
-    if is_error {
-        let m = TermMsg::new(Level::Error, summary);
-        return if short {
-            m.icon("✗")
-        } else {
-            m.body(txt, None)
-        };
-    }
-    if is_message_bearing && !txt.trim().is_empty() {
-        return TermMsg::new(Level::Info, format!("recv ← {summary}"))
-            .body(txt, Some(BodyFormat::Markdown));
-    }
-    let m = TermMsg::new(Level::Info, summary);
-    if short {
-        m.icon("←")
-    } else {
-        m.body(txt, None)
+    for entry in content.iter_mut() {
+        enrich_tool_use_entry(entry);
     }
 }
 
-/// `(empty)` / a short trimmed line / `"NL · headline…"` for a long one —
-/// matches the old client-side `summaryBody` computation exactly.
-fn summarize_tool_result(txt: &str, trimmed: &str) -> String {
-    if trimmed.is_empty() {
-        return "(empty)".to_owned();
+fn enrich_tool_use_entry(entry: &mut Value) {
+    if entry.get("type").and_then(Value::as_str) != Some("tool_use") {
+        return;
     }
-    if trimmed.chars().count() <= 120 {
-        return trimmed.to_owned();
+    if entry.get("_icon").is_some() {
+        return; // idempotent
     }
-    let lines = txt.lines().filter(|l| !l.is_empty()).count();
-    let headline: String = trimmed.chars().take(90).collect();
-    format!("{lines}L · {headline}…")
-}
-
-// ---------------------------------------------------------------------------
-// subagent (claude Task-tool) activity — dead path for agents today (`Task`
-// is omitted from the allow-list) but kept for parity with the old
-// client-side `classifyTaskEvent`.
-// ---------------------------------------------------------------------------
-
-fn classify_task_event(v: &Value) -> Option {
-    let id: String = v
-        .get("task_id")
+    let name = entry
+        .get("name")
         .and_then(Value::as_str)
         .unwrap_or("")
-        .chars()
-        .take(8)
-        .collect();
-    let kind = v
-        .get("task_type")
-        .and_then(Value::as_str)
-        .map(|t| format!(" [{t}]"))
-        .unwrap_or_default();
-    let desc = v
-        .get("description")
-        .or_else(|| v.get("summary"))
-        .and_then(Value::as_str)
-        .unwrap_or("(no description)");
-    match v.get("subtype").and_then(Value::as_str) {
-        Some("task_started") => {
-            Some(TermMsg::new(Level::Info, format!("task {id} started · {desc}{kind}")).icon("⌁"))
-        }
-        Some("task_notification") => {
-            let status = v.get("status").and_then(Value::as_str).unwrap_or("unknown");
-            let (glyph, level) = match status {
-                "completed" => ("✓", Level::Info),
-                "failed" => ("✗", Level::Error),
-                _ => ("◌", Level::Info),
-            };
-            let out = v
-                .get("output_file")
-                .and_then(Value::as_str)
-                .map(|f| format!(" · → {f}"))
-                .unwrap_or_default();
-            Some(TermMsg::new(level, format!("task {id} {glyph} {status} · {desc}{out}")).icon("⌁"))
-        }
-        _ => None,
+        .to_owned();
+    let input = entry.get("input").cloned().unwrap_or_else(|| json!({}));
+    let icon = tool_icon(&name);
+    let summary = fmt_tool_use(&name, &input);
+    let rich = is_rich_tool(&name);
+    let body = rich_tool_body(&name, &input);
+    let Some(obj) = entry.as_object_mut() else {
+        return;
+    };
+    obj.insert("_icon".to_owned(), json!(icon));
+    obj.insert("_summary".to_owned(), json!(summary));
+    if rich {
+        obj.insert("_category".to_owned(), json!("rich"));
+    }
+    if let Some((b, bt)) = body {
+        obj.insert("_body".to_owned(), json!(b));
+        obj.insert("_body_type".to_owned(), json!(bt));
     }
 }
 
@@ -417,14 +249,22 @@ fn classify_task_event(v: &Value) -> Option {
 // tool helpers
 // ---------------------------------------------------------------------------
 
+/// Whether this tool is rendered by the frontend's *rich* renderer (diff
+/// view, body expansion) rather than the flat `_summary` row. Flagged with
+/// `_category: "rich"` so the client can distinguish without re-implementing
+/// the tool name list.
+fn is_rich_tool(name: &str) -> bool {
+    matches!(name, "Edit" | "mcp__bash__run" | "mcp__hyperhive__send")
+}
+
 /// Pre-compute the expandable body for rich tool entries.
 ///
-/// Returns `Some((body, body_type))` where `body_type` becomes the
-/// `TermMsg`'s `body_format` and tells the frontend which renderer to use:
-/// - `"diff"` → colour-coded `+`/`-` lines
-/// - `"plain"` (`None` on the wire) → a plain `
` block
-/// - `"markdown"` → rendered via `marked` + `DOMPurify`; used for
-///   message-bearing tools: `send`
+/// Returns `Some((body, body_type))` where `body_type` tells the frontend
+/// which renderer to use:
+/// - `"diff"` → `api.detailsDiff` (colour-coded `+`/`-` lines)
+/// - `"plain"` → `api.details` (plain `
` block)
+/// - `"markdown"` → `api.detailsOpenMd` (markdown rendered via marked + `DOMPurify`,
+///   default-open; used for message-bearing tools: `send`)
 ///
 /// Returns `None` for tools that have no body at all.
 ///
diff --git a/hive-agent/src/term_msg.rs b/hive-agent/src/term_msg.rs
deleted file mode 100644
index df4da3d7..00000000
--- a/hive-agent/src/term_msg.rs
+++ /dev/null
@@ -1,283 +0,0 @@
-//! Terminal-message wire shape: what the per-agent web UI's live/history
-//! endpoints actually serve for the "terminal" event stream, as opposed to
-//! agent-state changes (`StatusChanged`/`ModelChanged`/`EffortChanged`/
-//! `TokenUsageChanged`/`TurnStateChanged`), which have never rendered as
-//! terminal rows (the header/badges poll `/api/state`, not this stream) and
-//! produce zero [`TermMsg`]s here.
-//!
-//! One [`crate::events::LiveEvent`] maps to zero or more `TermMsg`s — most
-//! map to exactly one, but `LiveEvent::Stream` (one raw claude
-//! `stream-json` line) can expand to several: an `assistant` message with
-//! both a text block and a `tool_use` block produces two rows.
-//!
-//! Design history: mara's terminal-message redesign (six rounds of
-//! negotiation on the forge) collapsed what was an 11-field frontend-side
-//! row shape (`StreamRow`, `frontend/packages/agent/src/lib/streamRow.ts`)
-//! plus raw claude-JSON passthrough into this 6-field shape, with
-//! classification moved server-side so the client-side `classifyEvent.ts` —
-//! a large per-tool dispatch table — mostly goes away. `kind`, `unread`,
-//! `from`, and `expanded_default` were all considered and dropped along the
-//! way; `level` replaces free-text CSS-class styling.
-
-use serde::Serialize;
-use std::collections::HashMap;
-
-use crate::events::LiveEvent;
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
-#[serde(rename_all = "snake_case")]
-pub enum Level {
-    /// Low-signal / ambient chatter — thinking, progress ticks, harness
-    /// housekeeping. The client's default rendering can dim/de-emphasize
-    /// these without hiding them outright.
-    Debug,
-    /// Routine substantive content — turn boundaries, assistant text, tool
-    /// calls/results, message bodies.
-    Info,
-    /// Heads-up, not necessarily broken — stderr lines, an unclassified
-    /// event shape landing (the old `.sys` catch-all), API retries.
-    Warn,
-    /// Something actually failed — a turn ending non-ok, a tool result with
-    /// `is_error: true`.
-    Error,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
-#[serde(rename_all = "snake_case")]
-pub enum BodyFormat {
-    Markdown,
-    Diff,
-}
-
-/// One terminal row. `body_format: None` with `body: Some(_)` means plain
-/// text (the common case — no explicit tag on the wire for it, same logic
-/// as `body` itself being absent meaning "nothing to expand").
-#[derive(Debug, Clone, Serialize)]
-pub struct TermMsg {
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub icon: Option,
-    pub level: Level,
-    pub summary: String,
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub body: Option,
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub body_format: Option,
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub coalesce_key: Option,
-}
-
-impl TermMsg {
-    pub fn new(level: Level, summary: impl Into) -> Self {
-        Self {
-            icon: None,
-            level,
-            summary: summary.into(),
-            body: None,
-            body_format: None,
-            coalesce_key: None,
-        }
-    }
-
-    #[must_use]
-    pub fn icon(mut self, icon: impl Into) -> Self {
-        self.icon = Some(icon.into());
-        self
-    }
-
-    #[must_use]
-    pub fn body(mut self, body: impl Into, format: Option) -> Self {
-        self.body = Some(body.into());
-        self.body_format = format;
-        self
-    }
-
-    #[must_use]
-    pub fn coalesce(mut self, key: impl Into) -> Self {
-        self.coalesce_key = Some(key.into());
-        self
-    }
-}
-
-/// Per-connection/per-request classification state. A live SSE stream keeps
-/// one of these alive for the connection's lifetime — `tool_use` id → name
-/// correlation, so a `tool_result` can tell it's answering a `recv` call and
-/// render its body as markdown instead of plain text. The history endpoint
-/// uses a fresh one per page: correlation only works within the page
-/// actually returned, not across the live/history boundary. Accepted
-/// degradation — the only user-visible effect is a `recv` result whose
-/// `tool_use` fell on the other side of a page/reconnect boundary rendering
-/// its body as plain text instead of markdown.
-#[derive(Default)]
-pub struct ClassifyCtx {
-    tool_name_by_id: HashMap,
-}
-
-impl ClassifyCtx {
-    pub fn record_tool_use(&mut self, id: &str, name: &str) {
-        self.tool_name_by_id.insert(id.to_owned(), name.to_owned());
-    }
-
-    #[must_use]
-    pub fn tool_name(&self, id: &str) -> Option<&str> {
-        self.tool_name_by_id.get(id).map(String::as_str)
-    }
-}
-
-/// Classify one [`LiveEvent`] into zero or more terminal rows.
-pub fn classify(ev: &LiveEvent, ctx: &mut ClassifyCtx) -> Vec {
-    match ev {
-        LiveEvent::TurnStart { from, body, .. } => {
-            // `unread` (the third field) was dropped — mara: "i can see
-            // the todo/inbox count in toolbar and dont need the N unread".
-            let mut m = TermMsg::new(Level::Info, format!("TURN ← {from}")).icon("◆");
-            if !body.trim().is_empty() {
-                m = m.body(body.clone(), None);
-            }
-            vec![m]
-        }
-        LiveEvent::TurnEnd { ok, note } => {
-            let msg = if *ok {
-                TermMsg::new(Level::Info, "turn ok").icon("✅")
-            } else {
-                let summary = note
-                    .as_deref()
-                    .filter(|n| !n.is_empty())
-                    .map_or_else(|| "turn fail".to_owned(), |n| format!("turn fail — {n}"));
-                TermMsg::new(Level::Error, summary).icon("❌")
-            };
-            vec![msg]
-        }
-        LiveEvent::Note { text } => vec![classify_note(text)],
-        LiveEvent::Stream(v) => crate::stream_enrich::classify_stream_value(v, ctx),
-        // Agent-state transitions never render as terminal rows — the
-        // header/badges read `/api/state`, not this stream (see module doc).
-        LiveEvent::StatusChanged { .. }
-        | LiveEvent::ModelChanged { .. }
-        | LiveEvent::EffortChanged { .. }
-        | LiveEvent::TokenUsageChanged { .. }
-        | LiveEvent::TurnStateChanged { .. } => vec![],
-    }
-}
-
-fn classify_note(text: &str) -> TermMsg {
-    if let Some(rest) = text.strip_prefix("stderr:") {
-        TermMsg::new(Level::Warn, format!("stderr:{rest}"))
-    } else if let Some(rest) = text.strip_prefix("operator:") {
-        TermMsg::new(Level::Info, format!("operator:{rest}"))
-    } else {
-        // Ambient harness chatter (session archived, plugin loaded, etc.) —
-        // routine, not worth the same visual weight as a tool call or
-        // assistant text.
-        TermMsg::new(Level::Debug, text.to_owned())
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use super::{ClassifyCtx, Level, classify};
-    use crate::events::LiveEvent;
-
-    #[test]
-    fn turn_start_carries_from_and_body_no_unread() {
-        let ev = LiveEvent::TurnStart {
-            from: "operator".into(),
-            body: "sweep the backlog".into(),
-            unread: 3,
-        };
-        let mut ctx = ClassifyCtx::default();
-        let msgs = classify(&ev, &mut ctx);
-        assert_eq!(msgs.len(), 1);
-        assert_eq!(msgs[0].summary, "TURN ← operator");
-        assert_eq!(msgs[0].body.as_deref(), Some("sweep the backlog"));
-        assert_eq!(msgs[0].level, Level::Info);
-    }
-
-    #[test]
-    fn turn_start_empty_body_has_no_body() {
-        let ev = LiveEvent::TurnStart {
-            from: "reminder".into(),
-            body: String::new(),
-            unread: 0,
-        };
-        let mut ctx = ClassifyCtx::default();
-        let msgs = classify(&ev, &mut ctx);
-        assert!(msgs[0].body.is_none());
-    }
-
-    #[test]
-    fn turn_end_ok_is_info() {
-        let ev = LiveEvent::TurnEnd {
-            ok: true,
-            note: None,
-        };
-        let mut ctx = ClassifyCtx::default();
-        let msgs = classify(&ev, &mut ctx);
-        assert_eq!(msgs[0].level, Level::Info);
-        assert_eq!(msgs[0].summary, "turn ok");
-    }
-
-    #[test]
-    fn turn_end_fail_is_error_with_note() {
-        let ev = LiveEvent::TurnEnd {
-            ok: false,
-            note: Some("rate limited".into()),
-        };
-        let mut ctx = ClassifyCtx::default();
-        let msgs = classify(&ev, &mut ctx);
-        assert_eq!(msgs[0].level, Level::Error);
-        assert_eq!(msgs[0].summary, "turn fail — rate limited");
-    }
-
-    #[test]
-    fn note_stderr_is_warn() {
-        let ev = LiveEvent::Note {
-            text: "stderr: warning: deprecated flag".into(),
-        };
-        let mut ctx = ClassifyCtx::default();
-        let msgs = classify(&ev, &mut ctx);
-        assert_eq!(msgs[0].level, Level::Warn);
-    }
-
-    #[test]
-    fn note_operator_is_info() {
-        let ev = LiveEvent::Note {
-            text: "operator: /compact requested".into(),
-        };
-        let mut ctx = ClassifyCtx::default();
-        let msgs = classify(&ev, &mut ctx);
-        assert_eq!(msgs[0].level, Level::Info);
-    }
-
-    #[test]
-    fn note_plain_is_debug() {
-        let ev = LiveEvent::Note {
-            text: "created fresh session".into(),
-        };
-        let mut ctx = ClassifyCtx::default();
-        let msgs = classify(&ev, &mut ctx);
-        assert_eq!(msgs[0].level, Level::Debug);
-    }
-
-    #[test]
-    fn agent_state_events_produce_no_rows() {
-        let mut ctx = ClassifyCtx::default();
-        assert!(
-            classify(
-                &LiveEvent::StatusChanged {
-                    status: "online".into()
-                },
-                &mut ctx
-            )
-            .is_empty()
-        );
-        assert!(
-            classify(
-                &LiveEvent::ModelChanged {
-                    model: "opus".into()
-                },
-                &mut ctx
-            )
-            .is_empty()
-        );
-    }
-}
diff --git a/hive-agent/src/web_ui/stream.rs b/hive-agent/src/web_ui/stream.rs
index 99402942..89c4ba31 100644
--- a/hive-agent/src/web_ui/stream.rs
+++ b/hive-agent/src/web_ui/stream.rs
@@ -9,36 +9,13 @@ use serde::{Deserialize, Serialize};
 use tokio_stream::{Stream, StreamExt, wrappers::BroadcastStream};
 
 use super::AppState;
-use crate::term_msg::{ClassifyCtx, Level, TermMsg, classify};
-
-/// One classified envelope on the wire: transport-level metadata (a sibling
-/// of the terminal-row payload, not part of it) plus the zero-or-more rows
-/// the raw event classified into. An event that classifies to zero rows (an
-/// agent-state change — `StatusChanged`/`ModelChanged`/etc. — or
-/// drop-category noise) never reaches the wire at all; see
-/// `crate::term_msg` for why.
-///
-/// `seq` is the live per-event dedup counter (`BusEvent::seq`) — `Some` on
-/// the SSE path, `None` on history replay (a stored row has no live seq).
-/// Same category of plumbing as `ts`: the client already used it to drop
-/// buffered live traffic it's about to see again in the initial history
-/// page, and that need didn't go away just because rows lost their `kind`
-/// tag — dropping it here would silently reintroduce duplicate rows across
-/// the live/history boundary.
-#[derive(Serialize)]
-pub(super) struct TermEnvelope {
-    ts: i64,
-    #[serde(skip_serializing_if = "Option::is_none")]
-    seq: Option,
-    msgs: Vec,
-}
 
 /// Response body for `GET /api/events/history`. `seq` is omitted from the
 /// wire entirely on a paginated (non-initial) load — matches the old
 /// `json!` shape, which only ever set the `"seq"` key when `Some`.
 #[derive(Serialize)]
 pub(super) struct EventsHistoryBody {
-    events: Vec,
+    events: Vec,
     min_id: Option,
     has_more: bool,
     #[serde(skip_serializing_if = "Option::is_none")]
@@ -75,28 +52,15 @@ pub(super) async fn events_history(
     };
 
     let (events, min_id, has_more) = state.bus.history_page(before, limit);
-    // Classify with the same function the live SSE path uses so history
-    // replay and live tail deliver identical shapes. The DB stores raw
-    // events; classification is applied at read time here (see
-    // `crate::term_msg`). One `ClassifyCtx` for the whole page — tool_use→
-    // name correlation (for markdown-vs-plain `recv` result bodies) only
-    // works within a single page/connection, not across the live/history
-    // boundary; see that module's doc for why that's an accepted
-    // degradation.
-    let mut ctx = ClassifyCtx::default();
-    let events: Vec = events
+    // Apply the same enrichment as the live SSE path so history replay
+    // and live tail deliver identical shapes. The DB stores raw events.
+    let events: Vec<_> = events
         .into_iter()
-        .filter_map(|se| {
-            let msgs = classify(&se.event, &mut ctx);
-            if msgs.is_empty() {
-                None
-            } else {
-                Some(TermEnvelope {
-                    ts: se.ts,
-                    seq: None,
-                    msgs,
-                })
+        .map(|mut se| {
+            if let crate::events::LiveEvent::Stream(ref mut v) = se.event {
+                crate::stream_enrich::enrich(v);
             }
+            se
         })
         .collect();
     Json(EventsHistoryBody {
@@ -117,29 +81,23 @@ pub(super) async fn events_stream(
     // stream rather than emitted to the bus — a bus emit would spam every
     // already-connected client with a spurious note each time anyone opens
     // the stream.
-    let hello_envelope = TermEnvelope {
-        ts: chrono::Utc::now().timestamp(),
-        seq: None,
-        msgs: vec![TermMsg::new(Level::Debug, "live stream attached")],
-    };
-    let hello = Event::default().data(serde_json::to_string(&hello_envelope).unwrap_or_default());
-    // One `ClassifyCtx` per connection, moved into the closure — tool_use→
-    // name correlation persists for the connection's lifetime (see
-    // `crate::term_msg::ClassifyCtx`'s doc for the history-page boundary
-    // this doesn't cross).
-    let mut ctx = ClassifyCtx::default();
-    let live = BroadcastStream::new(rx).filter_map(move |res| {
-        let ev = res.ok()?;
-        let msgs = classify(&ev.event, &mut ctx);
-        if msgs.is_empty() {
-            return None;
+    let hello = Event::default().data(
+        serde_json::to_string(&crate::events::LiveEvent::Note {
+            text: "live stream attached".into(),
+        })
+        .unwrap_or_default(),
+    );
+    let live = BroadcastStream::new(rx).filter_map(|res| {
+        let mut ev = res.ok()?;
+        // Enrich stream-json values with pre-computed display fields
+        // (`_icon`, `_summary`, `_category`) so the frontend doesn't need to
+        // duplicate the dispatch logic. The DB stores raw events; enrichment
+        // is applied here so both the live tail and the history endpoint
+        // deliver the same shape (see `events_history` above).
+        if let crate::events::LiveEvent::Stream(ref mut v) = ev.event {
+            crate::stream_enrich::enrich(v);
         }
-        let envelope = TermEnvelope {
-            ts: ev.ts,
-            seq: Some(ev.seq),
-            msgs,
-        };
-        let json = serde_json::to_string(&envelope).ok()?;
+        let json = serde_json::to_string(&ev).ok()?;
         Some(Ok(Event::default().data(json)))
     });
     let stream = tokio_stream::once(Ok(hello)).chain(live);