Drop classifyEvent.ts, render TermMsg directly

Per review: StreamRow was meant to match what the server sends in
TermMsg, not be a separate model needing a translation step.

- classifyEvent.ts and streamRow.ts deleted; termMsg.ts holds the wire
  types (TermMsg/TermEnvelope) plus TermRow, a TermMsg with just the
  key/fromHistory bookkeeping Preact needs for list rendering.
- Row.tsx renders a TermRow directly: level -> CSS class, empty
  summary + markdown body -> flat row, everything else with a body ->
  expandable details gated by the operator's preference. No separate
  classification step.
- useLiveStream.ts drops ClassifyCtx (a single incrementing key
  counter didn't need a whole context object) and maps envelopes to
  rows inline.
- docs/terminal-rendering.md trimmed substantially — was documenting
  more implementation detail than useful; points at stream_enrich.rs
  for the per-tool specifics instead of duplicating them in prose.
This commit is contained in:
iris 2026-08-30 21:23:28 +02:00
commit cebf3c6ced
6 changed files with 156 additions and 436 deletions

View file

@ -1,13 +1,16 @@
// Renders one `StreamRow` — flat `<div class="row …">` or expandable
// `<details class="row …">`, 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.
// Renders one `TermRow` — flat `<div class="row …">` or expandable
// `<details class="row …">`, 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."
import { useEffect, useRef } from 'preact/hooks';
import type { StreamRow } from '../lib/streamRow.js';
import type { TermRow } from '../lib/termMsg.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<HTMLDivElement>(null);
@ -41,25 +44,39 @@ function DiffBody({ text }: { text: string }) {
);
}
export function Row({ row }: { row: StreamRow }) {
if (row.details) {
export function Row({ row }: { row: TermRow }) {
const cssClass = 'level-' + row.level;
const icon = row.icon != null && row.icon !== '' && <span className="row-glyph">{row.icon}</span>;
if (row.body == null) {
return (
<details className={`row ${row.cssClass}`} open={row.defaultOpen || undefined}>
<summary>
{row.icon != null && row.icon !== '' && <span className="row-glyph">{row.icon}</span>}
<span className="summary-text">{row.text}</span>
</summary>
{row.diffBody != null && <DiffBody text={row.diffBody} />}
{row.markdownBody != null && <MarkdownBody text={row.markdownBody} />}
{row.plainBody != null && <pre className="tool-body">{linkifyToNodes(row.plainBody)}</pre>}
</details>
<div className={`row ${cssClass}`}>
{icon}
{linkifyToNodes(row.summary)}
</div>
);
}
// 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 (
<div className={`row ${cssClass}`}>
{icon}
<MarkdownBody text={row.body} />
</div>
);
}
return (
<div className={`row ${row.cssClass}`}>
{row.icon != null && row.icon !== '' && <span className="row-glyph">{row.icon}</span>}
{row.text != null && linkifyToNodes(row.text)}
{row.markdownBody != null && <MarkdownBody text={row.markdownBody} />}
</div>
<details className={`row ${cssClass}`} open={getExpandDetailsPref() || undefined}>
<summary>
{icon}
<span className="summary-text">{row.summary}</span>
</summary>
{row.body_format === 'diff' && <DiffBody text={row.body} />}
{row.body_format === 'markdown' && <MarkdownBody text={row.body} />}
{row.body_format == null && <pre className="tool-body">{linkifyToNodes(row.body)}</pre>}
</details>
);
}

View file

@ -1,21 +1,21 @@
// Backfill + live SSE for the agent's event stream, reduced to a plain
// `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.
// `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.
//
// 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). Post mara's terminal-
// message redesign there's no per-row `kind` any more to sanity-check
// that against — `seq` alone is the whole dedup signal, see
// `TermEnvelope`'s doc in hive-agent's `web_ui/stream.rs`.
// initial history page, drop it from the buffer). There's no per-row
// `kind` any more to sanity-check that against — `seq` alone is the
// whole dedup signal, see `TermEnvelope`'s doc in hive-agent's
// `web_ui/stream.rs`.
//
// The old `onLiveTurnBoundary` callback (a snappier one-off `/api/state`
// refresh right after a live turn_start/turn_end, instead of waiting for
@ -25,8 +25,7 @@
// longer has the structure to single one out. `useAgentState`'s 4s poll
// is the only refresh path now.
import { useEffect, useRef, useState } from 'preact/hooks';
import { classifyEvent, createClassifyCtx, type ClassifyCtx, type TermEnvelope } from '../lib/classifyEvent.js';
import type { StreamRow } from '../lib/streamRow.js';
import type { TermEnvelope, TermRow } from '../lib/termMsg.js';
export interface UseLiveStreamOptions {
historyUrl?: string;
@ -34,7 +33,7 @@ export interface UseLiveStreamOptions {
}
export interface UseLiveStreamResult {
rows: StreamRow[];
rows: TermRow[];
hasMore: boolean;
loadingMore: boolean;
loadMore: () => void;
@ -47,12 +46,12 @@ export interface UseLiveStreamResult {
clearLocal: () => void;
}
function appendRow(rows: StreamRow[], row: StreamRow): StreamRow[] {
function appendRow(rows: TermRow[], row: TermRow): TermRow[] {
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.coalesceKey && last && last.coalesceKey === row.coalesceKey) {
if (row.coalesce_key && last && last.coalesce_key === row.coalesce_key) {
const next = rows.slice(0, -1);
next.push({ ...row, key: last.key });
return next;
@ -60,22 +59,28 @@ function appendRow(rows: StreamRow[], row: StreamRow): StreamRow[] {
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<StreamRow[]>([]);
const [rows, setRows] = useState<TermRow[]>([]);
const [hasMore, setHasMore] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
const ctxRef = useRef<ClassifyCtx | null>(null);
if (!ctxRef.current) ctxRef.current = createClassifyCtx();
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 minIdRef = useRef<number | null>(null);
const liveRef = useRef(false);
const bufferedRef = useRef<TermEnvelope[]>([]);
@ -84,8 +89,7 @@ export function useLiveStream(opts: UseLiveStreamOptions = {}): UseLiveStreamRes
let cancelled = false;
function pushLive(env: TermEnvelope) {
const newRows = classifyEvent(env, false, ctxRef.current!);
if (newRows.length) setRows((prev) => appendMany(prev, newRows));
if (env.msgs.length) setRows((prev) => appendEnvelope(prev, env, false));
}
const es = new EventSource(streamUrl);
@ -95,8 +99,7 @@ export function useLiveStream(opts: UseLiveStreamOptions = {}): UseLiveStreamRes
env = JSON.parse(e.data);
} catch {
setRows((prev) => appendRow(prev, {
key: 'parse-err-' + Date.now(), cssClass: 'level-warn', fromHistory: false,
text: '[parse err] ' + e.data,
key: 'parse-err-' + Date.now(), level: 'warn', summary: '[parse err] ' + e.data, fromHistory: false,
}));
return;
}
@ -108,8 +111,8 @@ export function useLiveStream(opts: UseLiveStreamOptions = {}): UseLiveStreamRes
};
es.onerror = () => {
setRows((prev) => appendRow(prev, {
key: 'conn-note', cssClass: 'level-warn', fromHistory: false, coalesceKey: 'conn-status',
text: es.readyState === 0 /* CONNECTING */ ? '[reconnecting…]' : '[disconnected]',
key: 'conn-note', level: 'warn', fromHistory: false, coalesce_key: 'conn-status',
summary: es.readyState === 0 /* CONNECTING */ ? '[reconnecting…]' : '[disconnected]',
}));
};
@ -126,11 +129,11 @@ export function useLiveStream(opts: UseLiveStreamOptions = {}): UseLiveStreamRes
}
if (cancelled) return;
let initial: StreamRow[] = [];
for (const env of events) initial = appendMany(initial, classifyEvent(env, true, ctxRef.current!));
let initial: TermRow[] = [];
for (const env of events) initial = appendEnvelope(initial, env, true);
initial = events.length
? appendRow(initial, { key: 'live-sep', cssClass: 'level-debug', fromHistory: true, text: '─── live (older above) ───' })
: [{ key: 'placeholder', cssClass: 'level-debug', fromHistory: true, text: '(connected — waiting for events)' }];
? appendRow(initial, { key: 'live-sep', level: 'debug', fromHistory: true, summary: '─── live (older above) ───' })
: [{ key: 'placeholder', level: 'debug', fromHistory: true, summary: '(connected — waiting for events)' }];
setRows(initial);
const drained = bufferedRef.current;
@ -171,10 +174,10 @@ export function useLiveStream(opts: UseLiveStreamOptions = {}): UseLiveStreamRes
setHasMore(!!body.has_more);
if (typeof body.min_id === 'number') minIdRef.current = body.min_id;
if (events.length) {
let older: StreamRow[] = [];
for (const env of events) older = appendMany(older, classifyEvent(env, true, ctxRef.current!));
let older: TermRow[] = [];
for (const env of events) older = appendEnvelope(older, env, true);
older = appendRow(older, {
key: 'older-sep-' + minIdRef.current, cssClass: 'level-debug', fromHistory: true, text: '─── older above ───',
key: 'older-sep-' + minIdRef.current, level: 'debug', fromHistory: true, summary: '─── older above ───',
});
setRows((prev) => [...older, ...prev]);
}
@ -185,10 +188,8 @@ export function useLiveStream(opts: UseLiveStreamOptions = {}): UseLiveStreamRes
}
}
const localKeyRef = useRef(0);
function pushLocalNote(text: string) {
localKeyRef.current += 1;
setRows((prev) => appendRow(prev, { key: `local-${localKeyRef.current}`, cssClass: 'level-info', fromHistory: false, text }));
setRows((prev) => appendRow(prev, { key: 'local-' + nextKey(), level: 'info', fromHistory: false, summary: text }));
}
function clearLocal() {
setRows([]);

View file

@ -1,70 +0,0 @@
// Thin adapter: turns one server-classified `TermEnvelope` (hive-agent's
// `web_ui/stream.rs`) into zero or more `StreamRow`s. Almost all
// classification now happens server-side (`hive-agent/src/term_msg.rs` +
// `stream_enrich.rs`) — this file used to be a large per-tool/per-event
// dispatch tree (see git history pre mara's terminal-message redesign);
// now it's just a shape translation.
import type { StreamRow } from './streamRow.js';
import { getExpandDetailsPref } from '@hive/shared/prefs.js';
/** One terminal row as served by `GET /api/events/{history,stream}`
* mirrors `hive-agent/src/term_msg.rs::TermMsg` field-for-field. */
export interface TermMsg {
icon?: string;
level: 'debug' | 'info' | 'warn' | 'error';
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[];
}
export interface ClassifyCtx {
keySeq: { current: number };
}
export function createClassifyCtx(): ClassifyCtx {
return { keySeq: { current: 0 } };
}
function nextKey(ctx: ClassifyCtx): string {
ctx.keySeq.current += 1;
return 'r' + ctx.keySeq.current;
}
/** `TermEnvelope` → zero or more `StreamRow`s (one per `TermMsg`). */
export function classifyEvent(env: TermEnvelope, fromHistory: boolean, ctx: ClassifyCtx): StreamRow[] {
return env.msgs.map((m) => termMsgToRow(m, fromHistory, ctx));
}
function termMsgToRow(msg: TermMsg, fromHistory: boolean, ctx: ClassifyCtx): StreamRow {
const cssClass = 'level-' + msg.level;
const base = { key: nextKey(ctx), cssClass, fromHistory, icon: msg.icon, coalesceKey: msg.coalesce_key };
if (msg.body == null) {
return { ...base, text: msg.summary };
}
// Empty summary + markdown body → the old `.text` row: no prefix line,
// the body itself is the whole row (assistant text). Every other
// bodied row is an expandable details row, gated uniformly by the
// operator's expand-tool-output preference — no server-side per-tool
// override any more (mara: "client pref covers every message type
// uniformly, no server override even for send/ask/answer/recv").
if (msg.body_format === 'markdown' && msg.summary === '') {
return { ...base, markdownBody: msg.body };
}
const opened = { ...base, text: msg.summary, details: true, defaultOpen: getExpandDetailsPref() };
if (msg.body_format === 'diff') return { ...opened, diffBody: msg.body };
if (msg.body_format === 'markdown') return { ...opened, markdownBody: msg.body };
return { ...opened, plainBody: msg.body };
}

View file

@ -1,48 +0,0 @@
// Row model for the live event stream. One `StreamRow` = one rendered
// line/panel in the terminal pane; `classifyEvent` (classifyEvent.ts)
// turns a server-classified `TermMsg` (hive-agent's `term_msg.rs`) into
// one of these, and `<Row>` (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
// taxonomy this mirrors.
//
// Post mara's terminal-message redesign, `cssClass` is always exactly
// `level-debug|info|warn|error` (derived 1:1 from the wire `level`, see
// classifyEvent.ts) rather than a free-text per-row-kind class — the
// server no longer tells the client "this is a turn-start" or "this is a
// tool call", only "this is icon+level+summary+body". `meta`/`childText`
// (turn-time, duration, unread-count spans) are gone with them: the
// signal that let the client single out a turn-boundary row to attach
// them to (the old `kind` tag) no longer exists on the wire, by design —
// see term_msg.rs's module doc.
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;
/** Always `level-debug` / `level-info` / `level-warn` / `level-error`
* see @hive/shared/terminal.css's level-colour rules. */
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 startedcompleted). */
coalesceKey?: string;
/** `false`/absent flat `<div class="row">`; `true` `<details
* class="row">` with `.summary-text` + optional body. */
details?: boolean;
defaultOpen?: boolean;
/** Flat-row prefix text, or the details `<summary>` text. Linkified,
* never markdown. */
text?: string;
/** Sanitized-markdown body: appended under a flat row (assistant
* text, no `text` set) or inside an open details row (tool bodies). */
markdownBody?: string;
/** Plain `<pre>` body inside a details row (generic long tool output). */
plainBody?: string;
/** `+`/`-`/context diff body inside a details row (Edit tool). */
diffBody?: string;
}

View file

@ -0,0 +1,33 @@
// 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;
}