agent: LiveStream/Row/DetailsRow — Preact live event pane
Ports the row taxonomy in docs/terminal-rendering.md (app.js's renderStream/renderRichToolUse/renderToolResult/renderTaskEvent) to real Preact components + hooks: - lib/streamRow.ts: plain-data StreamRow model (one row = one line/ panel), lib/classifyEvent.ts: raw stream-json event -> StreamRow[], almost entirely dispatching on the backend's precomputed _icon/ _summary/_category/_body/_body_type fields, same as the old client. - lib/markdown.ts, lib/linkify.tsx: sanitized-markdown + auto-link helpers, same behavior as app.js's mdNode/terminal.js's linkify. - hooks/useLiveStream.ts: backfill + SSE + seq-dedupe + coalescing, reduced to a plain StreamRow[] — deliberately has no opinion on scroll position, only on what rows exist. - components/Row.tsx: renders one StreamRow (flat or details). - components/LiveStream.tsx: owns the scrollable DOM node + a from- scratch sticky-bottom implementation — not the old MutationObserver + rAF snap-animation + smoothScrollingUntil gate. stickToBottom is plain state driven by the scroll handler; snapping is an instant scrollTop write in a useLayoutEffect that runs after Preact has already committed the new rows, so it always sees the real scrollHeight. A load-older prepend is told apart from a normal append via an explicit ref set right before calling loadMore(), rather than inferred from DOM mutation shape after the fact. Wired into Root.tsx below Header/StatusChips; turn_start/turn_end also nudge useAgentState's refresh() for a snappier badge update than the plain poll interval. Reuses @hive/shared/terminal.css's existing row-kind classes as-is — the taxonomy's visual language isn't what changed, the component model underneath it is.
This commit is contained in:
parent
908f479372
commit
8521c6becb
9 changed files with 789 additions and 41 deletions
250
frontend/packages/agent/src/lib/classifyEvent.ts
Normal file
250
frontend/packages/agent/src/lib/classifyEvent.ts
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
// 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';
|
||||
|
||||
// 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<string, string>;
|
||||
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/ask/answer/recv-shaped), or a plain
|
||||
// collapsed body — 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, 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, 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, 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, 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;
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
39
frontend/packages/agent/src/lib/linkify.tsx
Normal file
39
frontend/packages/agent/src/lib/linkify.tsx
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// Auto-linkify bare http(s) URLs in plain (non-markdown) row text —
|
||||
// Preact-node port of @hive/shared/terminal.js's `linkify` (text-node
|
||||
// output there, JSX fragment here). Same regex + trailing-punctuation
|
||||
// strip; deliberately text-only, never innerHTML, so untrusted row text
|
||||
// (matrix-relayed bodies, tool args) can't inject markup this way.
|
||||
import type { JSX } from 'preact';
|
||||
|
||||
const LINKIFY_URL_RE = /https?:\/\/[^\s<>"']+/g;
|
||||
|
||||
export function linkifyToNodes(text: string | null | undefined): (string | JSX.Element)[] {
|
||||
const str = text == null ? '' : String(text);
|
||||
if (str.indexOf('://') === -1) return [str];
|
||||
const out: (string | JSX.Element)[] = [];
|
||||
let last = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
let key = 0;
|
||||
LINKIFY_URL_RE.lastIndex = 0;
|
||||
while ((m = LINKIFY_URL_RE.exec(str)) !== null) {
|
||||
let url = m[0];
|
||||
const trail = url.match(/[.,;:!?)\]}'"]+$/);
|
||||
const tail = trail ? trail[0] : '';
|
||||
if (tail) url = url.slice(0, -tail.length);
|
||||
if (m.index > last) out.push(str.slice(last, m.index));
|
||||
if (!url.slice(url.indexOf('://') + 3)) {
|
||||
// Nothing past the scheme — not a real URL, emit verbatim.
|
||||
out.push(m[0]);
|
||||
} else {
|
||||
out.push(
|
||||
<a key={key++} href={url} target="_blank" rel="noopener noreferrer">
|
||||
{url}
|
||||
</a>,
|
||||
);
|
||||
if (tail) out.push(tail);
|
||||
}
|
||||
last = m.index + m[0].length;
|
||||
}
|
||||
if (last < str.length) out.push(str.slice(last));
|
||||
return out;
|
||||
}
|
||||
25
frontend/packages/agent/src/lib/markdown.ts
Normal file
25
frontend/packages/agent/src/lib/markdown.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
// Markdown → sanitized HTML, ported from app.js's `mdNode`. Message
|
||||
// bodies rendered into the live stream (assistant text, send/ask/answer/
|
||||
// recv payloads) are untrusted (peer-agent / matrix-relayed content,
|
||||
// agent-authored files) — `marked` itself no longer sanitizes (v5+
|
||||
// dropped the built-in sanitizer), so every parse is run through
|
||||
// DOMPurify before it's ever handed to `dangerouslySetInnerHTML`.
|
||||
import { marked } from 'marked';
|
||||
import DOMPurify from 'dompurify';
|
||||
|
||||
marked.setOptions({ breaks: true, gfm: true });
|
||||
|
||||
const ESCAPE_RE = /[&<>"]/g;
|
||||
const ESCAPE_MAP: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"' };
|
||||
|
||||
/** Render `text` as sanitized markdown HTML. Falls back to escaped plain
|
||||
* text if `marked` throws (mirrors app.js's try/catch fallback). */
|
||||
export function renderMarkdown(text: string | null | undefined): string {
|
||||
const src = String(text ?? '');
|
||||
try {
|
||||
return DOMPurify.sanitize(marked.parse(src) as string);
|
||||
} catch (err) {
|
||||
console.warn('marked failed', err);
|
||||
return src.replace(ESCAPE_RE, (c) => ESCAPE_MAP[c] ?? c);
|
||||
}
|
||||
}
|
||||
49
frontend/packages/agent/src/lib/streamRow.ts
Normal file
49
frontend/packages/agent/src/lib/streamRow.ts
Normal file
|
|
@ -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
|
||||
// `<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;
|
||||
}
|
||||
|
||||
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 `<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;
|
||||
/** 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/ask/answer/recv 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;
|
||||
}
|
||||
Loading…
Reference in a new issue