Simplify terminal message shape to a uniform TermMsg
Move terminal-row classification server-side into a new
hive-agent/src/term_msg.rs, replacing the old JSON-mutation
enrich()/stamped-field approach in stream_enrich.rs with one
uniform wire shape: {icon?, level: debug|info|warn|error, summary,
body?, body_format?: markdown|diff, coalesce_key?}. No more per-row
`kind` tag or raw claude-JSON passthrough — every row is the same
shape, with structural identity carried by icon + summary text
instead of a CSS class per row kind.
hive-agent/src/web_ui/stream.rs's history + SSE endpoints now both
call term_msg::classify() and serve TermEnvelope{ts, seq?, msgs}
frames; events that classify to zero rows (agent-state changes,
drop-noise) never reach the wire.
Frontend: classifyEvent.ts collapses from a large per-tool dispatch
tree to a thin TermMsg -> StreamRow adapter. streamRow.ts/Row.tsx
drop the now-dead meta/childText fields. terminal.css switches from
a dozen-odd per-row-kind classes to four level-based color rules.
Expand/collapse of a bodied row is now a uniform client-side
decision (the operator's preference), no server-side per-tool
override.
docs/terminal-rendering.md rewritten to match.
This commit is contained in:
parent
daa6eb96f8
commit
5eefaa951d
13 changed files with 886 additions and 628 deletions
|
|
@ -240,7 +240,7 @@ export function Root() {
|
|||
{state.status === 'needs_login_idle' || state.status === 'needs_login_in_progress' ? (
|
||||
<LoginFlow status={state.status} session={state.session} onRefresh={refresh} />
|
||||
) : null}
|
||||
<LiveStream ref={liveStreamRef} onLiveTurnBoundary={refresh} />
|
||||
<LiveStream ref={liveStreamRef} />
|
||||
</main>
|
||||
{termInput}
|
||||
{panel}
|
||||
|
|
|
|||
|
|
@ -28,12 +28,6 @@ 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
|
||||
|
|
@ -43,11 +37,8 @@ export interface LiveStreamHandle {
|
|||
clear: () => void;
|
||||
}
|
||||
|
||||
export const LiveStream = forwardRef<LiveStreamHandle, LiveStreamProps>(function LiveStream(
|
||||
{ onLiveTurnBoundary },
|
||||
ref,
|
||||
) {
|
||||
const { rows, hasMore, loadingMore, loadMore, pushLocalNote, clearLocal } = useLiveStream({ onLiveTurnBoundary });
|
||||
export const LiveStream = forwardRef<LiveStreamHandle, object>(function LiveStream(_props, ref) {
|
||||
const { rows, hasMore, loadingMore, loadMore, pushLocalNote, clearLocal } = useLiveStream();
|
||||
useImperativeHandle(ref, () => ({ pushNote: pushLocalNote, clear: clearLocal }), [pushLocalNote, clearLocal]);
|
||||
const logRef = useRef<HTMLDivElement>(null);
|
||||
const [stickToBottom, setStickToBottom] = useState(true);
|
||||
|
|
|
|||
|
|
@ -59,12 +59,6 @@ export function Row({ row }: { row: StreamRow }) {
|
|||
<div className={`row ${row.cssClass}`}>
|
||||
{row.icon != null && row.icon !== '' && <span className="row-glyph">{row.icon}</span>}
|
||||
{row.text != null && linkifyToNodes(row.text)}
|
||||
{row.meta?.map((m) => (
|
||||
<span key={m.cls} className={m.cls}>
|
||||
{m.text}
|
||||
</span>
|
||||
))}
|
||||
{row.childText != null && <div className={row.childText.cls}>{row.childText.text}</div>}
|
||||
{row.markdownBody != null && <MarkdownBody text={row.markdownBody} />}
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -9,25 +9,28 @@
|
|||
// decides whether that should move the scroll position.
|
||||
//
|
||||
// Same subscribe → buffer → fetch-history → seq-dedupe → flush dance as
|
||||
// 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).
|
||||
// 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`.
|
||||
//
|
||||
// The old `onLiveTurnBoundary` callback (a snappier one-off `/api/state`
|
||||
// refresh right after a live turn_start/turn_end, instead of waiting for
|
||||
// the plain poll interval) is gone with the `kind` tag it relied on to
|
||||
// spot a turn boundary — per mara's own framing that trigger is an
|
||||
// agent-state concern, not a terminal-stream one, and this stream no
|
||||
// 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 } from '../lib/classifyEvent.js';
|
||||
import { classifyEvent, createClassifyCtx, type ClassifyCtx, type TermEnvelope } 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 {
|
||||
|
|
@ -75,40 +78,37 @@ export function useLiveStream(opts: UseLiveStreamOptions = {}): UseLiveStreamRes
|
|||
if (!ctxRef.current) ctxRef.current = createClassifyCtx();
|
||||
const minIdRef = useRef<number | null>(null);
|
||||
const liveRef = useRef(false);
|
||||
const bufferedRef = useRef<AnyEvent[]>([]);
|
||||
const onBoundaryRef = useRef(opts.onLiveTurnBoundary);
|
||||
onBoundaryRef.current = opts.onLiveTurnBoundary;
|
||||
const bufferedRef = useRef<TermEnvelope[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
function pushLive(ev: AnyEvent) {
|
||||
const newRows = classifyEvent(ev, false, ctxRef.current!);
|
||||
function pushLive(env: TermEnvelope) {
|
||||
const newRows = classifyEvent(env, 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 ev: AnyEvent;
|
||||
let env: TermEnvelope;
|
||||
try {
|
||||
ev = JSON.parse(e.data);
|
||||
env = JSON.parse(e.data);
|
||||
} catch {
|
||||
setRows((prev) => appendRow(prev, {
|
||||
key: 'parse-err-' + Date.now(), cssClass: 'note', fromHistory: false,
|
||||
key: 'parse-err-' + Date.now(), cssClass: 'level-warn', fromHistory: false,
|
||||
text: '[parse err] ' + e.data,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (!liveRef.current) {
|
||||
bufferedRef.current.push(ev);
|
||||
bufferedRef.current.push(env);
|
||||
return;
|
||||
}
|
||||
pushLive(ev);
|
||||
pushLive(env);
|
||||
};
|
||||
es.onerror = () => {
|
||||
setRows((prev) => appendRow(prev, {
|
||||
key: 'conn-note', cssClass: 'note', fromHistory: false, coalesceKey: 'conn-status',
|
||||
key: 'conn-note', cssClass: 'level-warn', fromHistory: false, coalesceKey: 'conn-status',
|
||||
text: es.readyState === 0 /* CONNECTING */ ? '[reconnecting…]' : '[disconnected]',
|
||||
}));
|
||||
};
|
||||
|
|
@ -118,30 +118,29 @@ 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: AnyEvent[] = Array.isArray(body) ? body : body.events || [];
|
||||
const events: TermEnvelope[] = 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: StreamRow[] = [];
|
||||
for (const ev of events) initial = appendMany(initial, classifyEvent(ev, true, ctxRef.current!));
|
||||
for (const env of events) initial = appendMany(initial, classifyEvent(env, true, ctxRef.current!));
|
||||
initial = events.length
|
||||
? appendRow(initial, { key: 'live-sep', cssClass: 'note', fromHistory: true, text: '─── live (older above) ───' })
|
||||
: [{ key: 'placeholder', cssClass: 'note', fromHistory: true, text: '(connected — waiting for events)' }];
|
||||
? 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)' }];
|
||||
setRows(initial);
|
||||
|
||||
const drained = bufferedRef.current;
|
||||
bufferedRef.current = [];
|
||||
liveRef.current = true;
|
||||
for (const ev of drained) {
|
||||
if (boundarySeq != null && typeof ev.seq === 'number' && ev.seq <= boundarySeq && historyKinds.has(ev.kind)) {
|
||||
continue;
|
||||
}
|
||||
pushLive(ev);
|
||||
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);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('history backfill failed', err);
|
||||
|
|
@ -149,7 +148,7 @@ export function useLiveStream(opts: UseLiveStreamOptions = {}): UseLiveStreamRes
|
|||
const drained = bufferedRef.current;
|
||||
bufferedRef.current = [];
|
||||
liveRef.current = true;
|
||||
for (const ev of drained) pushLive(ev);
|
||||
for (const env of drained) pushLive(env);
|
||||
}
|
||||
}
|
||||
backfill();
|
||||
|
|
@ -168,14 +167,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: AnyEvent[] = Array.isArray(body) ? body : body.events || [];
|
||||
const events: TermEnvelope[] = 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: StreamRow[] = [];
|
||||
for (const ev of events) older = appendMany(older, classifyEvent(ev, true, ctxRef.current!));
|
||||
for (const env of events) older = appendMany(older, classifyEvent(env, true, ctxRef.current!));
|
||||
older = appendRow(older, {
|
||||
key: 'older-sep-' + minIdRef.current, cssClass: 'note', fromHistory: true, text: '─── older above ───',
|
||||
key: 'older-sep-' + minIdRef.current, cssClass: 'level-debug', fromHistory: true, text: '─── older above ───',
|
||||
});
|
||||
setRows((prev) => [...older, ...prev]);
|
||||
}
|
||||
|
|
@ -189,7 +188,7 @@ 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: 'note', fromHistory: false, text }));
|
||||
setRows((prev) => appendRow(prev, { key: `local-${localKeyRef.current}`, cssClass: 'level-info', fromHistory: false, text }));
|
||||
}
|
||||
function clearLocal() {
|
||||
setRows([]);
|
||||
|
|
|
|||
|
|
@ -1,34 +1,38 @@
|
|||
// 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…
|
||||
// <N>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';
|
||||
// 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';
|
||||
|
||||
// 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;
|
||||
/** 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 {
|
||||
toolNameById: Map<string, string>;
|
||||
pendingTurnStartTs: { current: number | null };
|
||||
keySeq: { current: number };
|
||||
}
|
||||
|
||||
export function createClassifyCtx(): ClassifyCtx {
|
||||
return { toolNameById: new Map(), pendingTurnStartTs: { current: null }, keySeq: { current: 0 } };
|
||||
return { keySeq: { current: 0 } };
|
||||
}
|
||||
|
||||
function nextKey(ctx: ClassifyCtx): string {
|
||||
|
|
@ -36,233 +40,31 @@ function nextKey(ctx: ClassifyCtx): string {
|
|||
return 'r' + ctx.keySeq.current;
|
||||
}
|
||||
|
||||
function trim(s: string, n: number): string {
|
||||
return s.length > n ? s.slice(0, n) + '…' : s;
|
||||
/** `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));
|
||||
}
|
||||
|
||||
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 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 };
|
||||
}
|
||||
}
|
||||
|
||||
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) });
|
||||
// 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 };
|
||||
}
|
||||
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 <tool_use_error>…</tool_use_error> wrapper — implementation
|
||||
// detail claude emits on failed tool calls, adds nothing for the operator.
|
||||
const txt = isError
|
||||
? String(rawTxt).replace(/^<tool_use_error>([\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;
|
||||
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 };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,10 +15,3 @@ 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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,23 +1,28 @@
|
|||
// 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
|
||||
// `<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 exact taxonomy this mirrors.
|
||||
|
||||
export interface StreamRowMeta {
|
||||
cls: string;
|
||||
text: string;
|
||||
}
|
||||
// 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;
|
||||
/** 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. */
|
||||
/** Always `level-debug` / `level-info` / `level-warn` / `level-error` —
|
||||
* see @hive/shared/terminal.css's level-colour rules. */
|
||||
cssClass: string;
|
||||
icon?: string;
|
||||
fromHistory: boolean;
|
||||
|
|
@ -33,14 +38,8 @@ export interface StreamRow {
|
|||
/** Flat-row prefix text, or the details `<summary>` 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). */
|
||||
* 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;
|
||||
|
|
|
|||
|
|
@ -97,55 +97,34 @@
|
|||
display: inline-block;
|
||||
width: 1.4em;
|
||||
}
|
||||
/* 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;
|
||||
}
|
||||
/* 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); }
|
||||
}
|
||||
/* 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; }
|
||||
/* "↓ 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
|
||||
|
|
|
|||
Loading…
Reference in a new issue