Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fcd407da11 | ||
|
|
f8f2ccff52 | ||
|
|
f827187341 | ||
|
|
8a3e8bfb7f |
13 changed files with 402 additions and 53 deletions
8
TODO.md
8
TODO.md
|
|
@ -18,7 +18,7 @@
|
|||
|
||||
## Dashboard
|
||||
|
||||
- **Per-agent terminal coherence pass**: row taxonomy + colour scheme has drifted — glyph reuse, ad-hoc `<details>` rules, undifferentiated stderr, `.sys` catch-all silently hiding unrecognised events. Full audit + proposed unified scheme in [`docs/terminal-rendering.md`](docs/terminal-rendering.md).
|
||||
- ~~**Per-agent terminal coherence pass**~~ ✓ landed — unified prefix column (padding-left + negative text-indent so every row kind aligns), `<details>` summaries drop directional glyph (CSS `▸/▾` sits in prefix column instead), turn boundaries de-weighted (border-left only, no bold/margin/tint), stderr lines render orange `!`, operator-initiated notes mauve italic, catch-all `.sys` escalated to orange so unrecognised stream-json surfaces. Message-bearing tool calls (`send`/`ask`/`answer`/`recv`) render default-open with markdown bodies via vendored `marked` v4.0.2; assistant text also markdown-rendered. Extra-MCP tools get a generic args pretty-printer instead of raw JSON. See [`docs/terminal-rendering.md`](docs/terminal-rendering.md) for the as-built taxonomy.
|
||||
- **Delivered-reminder rollups**: per-agent delivered-count chip (last 24h) + histogram of attempts-vs-successes on the container row. Needs `Broker::count_delivered_reminders_since(agent, ts)` (cheap COUNT against the `reminders` table, `WHERE agent = ?1 AND sent_at >= ?2`).
|
||||
|
||||
## Security
|
||||
|
|
@ -61,6 +61,12 @@ how often the friction bites in normal use.
|
|||
- **Surface per-turn stats on the agent web UI**: "N turns today" chip + rolling tool-call histogram tooltip on the model chip. (`open_threads` and `open_reminders` chips already landed via other paths — open-threads section on the page + reminder count chip on the container row.) Reads the per-agent `turn_stats.sqlite`.
|
||||
- **Stats UI on the main dashboard**: per-agent rollups (avg turn duration, tokens-since-boot, top 5 tools) on the container row. Same data source, host-side aggregation query.
|
||||
|
||||
## Harness Behaviour
|
||||
|
||||
- **Persist + cold-load current context size on the per-agent page**: the `ctx-badge` (Claude Code's bottom-right "N tokens" indicator) currently only populates after the first `TokenUsageChanged` SSE event arrives, which is the *next* turn — until then the badge is empty. Operator can't see "this agent is at 78% context" before deciding to manually compact / reset / message it. Last known token usage should be persisted (likely a small `/state/hyperhive-token-usage` blob, or a row in turn_stats already has it — pull last row's totals on cold load) and returned by `/api/state` so the badge paints with real numbers on first render.
|
||||
|
||||
- **Auto session-reset when context is large and cache is cold**: today every turn uses `--continue`, so a long-lived agent carries its entire transcript forward indefinitely. When the next turn's context is above some threshold (rough starting point: ~50% of the session limit — hive startup alone burned ~15%, so the headroom disappears fast) *and* the prompt cache is no longer warm (last turn ended past the cache TTL), it's cheaper to start fresh than to re-send the whole history uncached. Open question: drop `--continue` vs. trigger `--compact` first — needs measurement of what each actually costs (uncached re-read of N tokens vs. a compact turn's own token spend + the post-compact uncached re-read). Decision should be data-driven, not guessed. Needs: a context-size estimate per turn (turn_stats already tracks token usage), a cache-warmth heuristic (time since last turn vs. cache TTL), and a one-shot fresh-session path in `turn.rs` mirroring the existing `↻ new session` button.
|
||||
|
||||
## Bugs
|
||||
|
||||
- **Token-budget exhaustion crashes the harness**: when claude's account hits its rate/token cap, the in-flight `claude --print` invocation returns an error the harness doesn't recognise as recoverable, the serve loop exits, and the container stays up with a dead daemon. Operator only notices when an unrelated wake fails to drive a turn. Want: detect the budget-exceeded class of failure (likely a specific stderr line or stream-json `rate_limit_event` shape), fire a `LiveEvent::StatusChanged("rate_limited")` or new status, surface as a red badge + banner on the dashboard + per-agent UI, and have the serve loop park (sleep N minutes, retry) instead of returning Err. Operator can also see "this agent is rate-limited until ~HH:MM" if claude tells us when. Inspect `crate::turn::run_claude`'s `bail!` paths + claude's stderr conventions for the budget error string.
|
||||
|
|
|
|||
|
|
@ -71,6 +71,56 @@ shared `.live .<class>` styling).
|
|||
autonomous harness chatter; nothing flags them as "operator
|
||||
initiated."
|
||||
|
||||
7. **Turn-start / turn-end are visually overweight**: the
|
||||
triggering event row + the closing row both get bold text,
|
||||
top margins, and a full coloured background tint. The
|
||||
coloured left rule alone already says "this is a turn
|
||||
boundary" — the heavy chrome adds noise without information.
|
||||
Drop the bold/margin/tint, keep the left rule.
|
||||
|
||||
8. **Left-alignment is incoherent across row types**: the `▸`
|
||||
disclosure marker on expandable rows doesn't sit in the
|
||||
same column as flat-row prefix glyphs (`→`, `←`, `·`), so
|
||||
the prefix column wanders by row kind. Expandable tool_use
|
||||
(`→ Name …`) and expandable tool_result (`▸ ← Nl …`) use
|
||||
different layouts from each other too. Pick one prefix
|
||||
column and align every row kind into it; the disclosure
|
||||
marker should be visually inside that column, not pushed
|
||||
to the side.
|
||||
|
||||
9. **Continuation lines aren't inset**: when a row's body
|
||||
wraps (e.g. `→ foo bar baz quux …`), the second visual
|
||||
line starts at column 0 rather than under the `f` of
|
||||
`foo`, so wrapped content blurs into the next row. Want a
|
||||
`text-indent` / hanging-indent rule so continuation lines
|
||||
align with the start of the body, not the prefix glyph.
|
||||
|
||||
10. **Most message-bearing rows are collapsed by default**
|
||||
even when the body is the whole point: `send`, `recv`,
|
||||
`ask`, and friends hide their text behind a `<details>`
|
||||
summary. The summary headline is rarely enough context.
|
||||
Want these expanded by default, with collapse reserved
|
||||
for genuinely heavy payloads (multi-page diffs, long
|
||||
tool_result blocks).
|
||||
|
||||
11. **Tools from extra MCP servers aren't pretty-printed**:
|
||||
`renderRichToolUse` only special-cases the built-in
|
||||
hyperhive tools (Write/Edit/send). Anything coming from
|
||||
`extraMcpServers` (matrix, bitburner, …) falls through
|
||||
to the generic `→ Name args…` JSON dump. Either a
|
||||
plugin-style hook in the renderer map, or at minimum a
|
||||
nicer generic args-pretty-printer that handles common
|
||||
shapes (single string arg, single dict arg, etc.).
|
||||
|
||||
12. **No markdown rendering on message bodies**: `send` /
|
||||
`recv` / `ask` / `answer` / agent text content all
|
||||
arrive as markdown-flavoured prose (bullets, fenced
|
||||
code, bold, links) but render as raw text. Want a
|
||||
minimal markdown pass — at least lists, fenced code,
|
||||
inline code, bold/italic, links — applied to message
|
||||
bodies and probably to the `assistant.content[].text`
|
||||
`.text` row.
|
||||
|
||||
## Suggested coherence pass
|
||||
|
||||
Pick one scheme and audit all renderers to match. A concrete
|
||||
|
|
@ -96,6 +146,48 @@ The `.sys` catch-all should escalate visually — a louder
|
|||
shapes for future fix-up rather than hiding them in the muted
|
||||
note stream.
|
||||
|
||||
### Layout rules to apply uniformly
|
||||
|
||||
- **One prefix column for every row kind** — flat rows and
|
||||
expandable rows alike. The disclosure marker (`▸`) lives
|
||||
inside that column, not as a separate gutter, so glyph
|
||||
alignment doesn't shift between row types.
|
||||
- **Hanging indent on wrapped bodies** so continuation lines
|
||||
start under the first character of the body, not under the
|
||||
prefix glyph. Probably `display: grid` with
|
||||
`grid-template-columns: <prefix-col> 1fr` per row, or
|
||||
`text-indent`/`padding-left` with negative `text-indent`.
|
||||
- **Turn boundaries are rule-only** — drop the bold + margin
|
||||
+ tint on `.turn-start` / `.turn-body` / `.turn-end-*`.
|
||||
The coloured left rule alone carries the boundary signal.
|
||||
- **Default-expanded message rows**: `send`, `recv`, `ask`,
|
||||
`answer`, and short-ish `text` rows render their body
|
||||
inline (no `<details>`). Reserve collapse for genuinely
|
||||
heavy bodies — multi-page diffs, long tool_results,
|
||||
thinking blocks past N lines.
|
||||
|
||||
### Renderer surface for extra MCP tools
|
||||
|
||||
`renderRichToolUse` currently switches on hard-coded tool
|
||||
names. Replace with a registry keyed by
|
||||
`mcp__<server>__<tool>` (and the built-in claude tool names)
|
||||
that maps to a `(toolUse) -> Node` renderer. Per-agent extra
|
||||
MCPs can register their own renderers via a small JS hook
|
||||
(loaded the same way `extra-mcp.json` is loaded server-side);
|
||||
the fallback is a generic args-pretty-printer that handles
|
||||
single-string and single-dict shapes nicely instead of dumping
|
||||
raw JSON.
|
||||
|
||||
### Markdown rendering
|
||||
|
||||
Apply a minimal markdown pass to message bodies (`send` /
|
||||
`recv` / `ask` / `answer`) and to assistant `text` rows.
|
||||
Scope: paragraphs, lists, fenced + inline code, bold/italic,
|
||||
links. No HTML passthrough, no images, no tables —
|
||||
explicitly bounded so we don't import a kitchen-sink parser
|
||||
into the per-agent page. A small handwritten pass or a tiny
|
||||
dep (e.g. `micromark` / `marked`) both work.
|
||||
|
||||
## Dashboard side (not covered here)
|
||||
|
||||
The main dashboard's message-flow pane is a different beast:
|
||||
|
|
|
|||
|
|
@ -656,6 +656,79 @@
|
|||
log.innerHTML = '';
|
||||
|
||||
function trim(s, n) { return s.length > n ? s.slice(0, n) + '…' : s; }
|
||||
// Render a message body as markdown into a new <div class="md">.
|
||||
// Wraps `marked.parse` so the per-row body element carries the
|
||||
// `.md` class (CSS in TERMINAL_CSS scopes paragraph/code/list
|
||||
// styles to it). Falls back to a plain text node if marked isn't
|
||||
// loaded (network glitch, asset 404) so the body still renders.
|
||||
function mdNode(text) {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'md';
|
||||
const src = String(text || '');
|
||||
if (window.marked && typeof window.marked.parse === 'function') {
|
||||
try {
|
||||
marked.setOptions({ breaks: true, gfm: true });
|
||||
div.innerHTML = marked.parse(src);
|
||||
} catch (err) {
|
||||
console.warn('marked failed', err);
|
||||
div.textContent = src;
|
||||
}
|
||||
} else {
|
||||
div.textContent = src;
|
||||
}
|
||||
return div;
|
||||
}
|
||||
// Build a default-open details row whose body is markdown-rendered.
|
||||
// Used by send / ask / answer tool_use renderers and by `recv`
|
||||
// tool_result so message-bearing rows show their content inline
|
||||
// without an extra click.
|
||||
function detailsOpenMd(api, cls, summary, body) {
|
||||
const d = api.details(cls, summary, '');
|
||||
d.open = true;
|
||||
const pre = d.querySelector('pre.tool-body');
|
||||
if (pre) {
|
||||
pre.replaceWith(mdNode(body));
|
||||
} else {
|
||||
d.appendChild(mdNode(body));
|
||||
}
|
||||
return d;
|
||||
}
|
||||
// Generic args-pretty-printer for unknown / extra-MCP tools. The
|
||||
// built-in switch handles the common claude/hyperhive tools; this
|
||||
// is the fallback so an `mcp__matrix__send_message` or similar
|
||||
// doesn't dump raw JSON. Heuristics: single string-valued field →
|
||||
// `Name field: "value"`; single dict-valued field → `Name field
|
||||
// {…}`; otherwise compact JSON. Always trimmed to fit a row.
|
||||
function fmtArgsGeneric(name, input) {
|
||||
const keys = Object.keys(input || {});
|
||||
if (keys.length === 0) return name + '()';
|
||||
if (keys.length === 1) {
|
||||
const k = keys[0];
|
||||
const v = input[k];
|
||||
if (typeof v === 'string') {
|
||||
const oneline = v.replace(/\s+/g, ' ').trim();
|
||||
return name + ' ' + k + ': ' + JSON.stringify(trim(oneline, 100));
|
||||
}
|
||||
if (typeof v === 'number' || typeof v === 'boolean') {
|
||||
return name + ' ' + k + ': ' + JSON.stringify(v);
|
||||
}
|
||||
}
|
||||
// Multi-field: render `k: v` pairs with strings/numbers inlined and
|
||||
// anything else summarised by type so the row stays readable.
|
||||
const pretty = keys.slice(0, 4).map((k) => {
|
||||
const v = input[k];
|
||||
if (v == null) return k + ': null';
|
||||
if (typeof v === 'string') {
|
||||
const oneline = v.replace(/\s+/g, ' ').trim();
|
||||
return k + ': ' + JSON.stringify(trim(oneline, 40));
|
||||
}
|
||||
if (typeof v === 'number' || typeof v === 'boolean') return k + ': ' + v;
|
||||
if (Array.isArray(v)) return k + `: [${v.length}]`;
|
||||
return k + ': {…}';
|
||||
});
|
||||
const tail = keys.length > 4 ? ' …+' + (keys.length - 4) : '';
|
||||
return name + ' ' + pretty.join(' · ') + tail;
|
||||
}
|
||||
// Pretty-print a tool call: per-known-tool format, fallback to JSON
|
||||
// for unknown tools.
|
||||
function fmtToolUse(c) {
|
||||
|
|
@ -678,7 +751,7 @@
|
|||
case 'mcp__hyperhive__kill': return short + ' ' + (input.name || '');
|
||||
case 'mcp__hyperhive__request_apply_commit':
|
||||
return short + ' ' + (input.agent || '') + ' @ ' + (input.commit_ref || '').slice(0, 12);
|
||||
default: return name + ' ' + trim(JSON.stringify(input), 200);
|
||||
default: return fmtArgsGeneric(short, input);
|
||||
}
|
||||
}
|
||||
// Build a "rich" tool_use row for tools whose input has a body we
|
||||
|
|
@ -709,37 +782,73 @@
|
|||
+ '\n'
|
||||
+ newLines.map(l => '+ ' + l).join('\n');
|
||||
}
|
||||
const summary = '→ ' + name + ' ' + path + ' · '
|
||||
// Summaries on expandable rows omit the row's directional glyph
|
||||
// (`→`) — the disclosure marker (`▸/▾`) from CSS sits in the
|
||||
// prefix column for every row kind, and the row's cyan colour
|
||||
// already signals "outbound tool".
|
||||
const summary = name + ' ' + path + ' · '
|
||||
+ (minus ? '-' + minus + ' ' : '') + '+' + plus;
|
||||
return api.detailsDiff('tool-use', summary, body);
|
||||
}
|
||||
// Message-bearing tools render default-open with a markdown body so
|
||||
// the operator sees the content without an extra click. send / ask
|
||||
// address a target; answer attaches to an existing question id.
|
||||
if (name === 'mcp__hyperhive__send') {
|
||||
const to = input.to || '?';
|
||||
const body = String(input.body || '');
|
||||
const headline = body.replace(/\s+/g, ' ').trim().slice(0, 80);
|
||||
const lines = body.split('\n').length;
|
||||
const summary = '→ send → ' + to + (lines > 1 ? ` · ${lines}L` : '')
|
||||
+ (headline ? ' · ' + headline + (body.length > 80 ? '…' : '') : '');
|
||||
return api.details('tool-use', summary, body);
|
||||
return detailsOpenMd(api, 'tool-use',
|
||||
'send → ' + to + (lines > 1 ? ` · ${lines}L` : ''),
|
||||
body);
|
||||
}
|
||||
if (name === 'mcp__hyperhive__ask') {
|
||||
const to = input.to || 'operator';
|
||||
const q = String(input.question || '');
|
||||
const lines = q.split('\n').length;
|
||||
return detailsOpenMd(api, 'tool-use',
|
||||
'ask → ' + to + (lines > 1 ? ` · ${lines}L` : ''),
|
||||
q);
|
||||
}
|
||||
if (name === 'mcp__hyperhive__answer') {
|
||||
const id = input.id != null ? String(input.id) : '?';
|
||||
const a = String(input.answer || '');
|
||||
const lines = a.split('\n').length;
|
||||
return detailsOpenMd(api, 'tool-use',
|
||||
'answer #' + id + (lines > 1 ? ` · ${lines}L` : ''),
|
||||
a);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
// Track tool_use_id → tool name so we can decide on rendering when the
|
||||
// matching tool_result lands later. Lets us default-open the body for
|
||||
// message-bearing tools (`recv`) while keeping shell/file tool output
|
||||
// collapsed unless the operator clicks. Cleared on /clear; otherwise
|
||||
// grows with the session — entries are tiny strings.
|
||||
const toolNameById = new Map();
|
||||
function renderToolResult(c, api) {
|
||||
const txt = Array.isArray(c.content)
|
||||
? c.content.map(p => p.text || '').join('')
|
||||
: (c.content || '');
|
||||
const summary = '← ' + (() => {
|
||||
const trimmed = txt.replace(/\s+/g, ' ').trim();
|
||||
const sourceName = c.tool_use_id ? 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 => l.length).length;
|
||||
const headline = trimmed.slice(0, 90) + '…';
|
||||
return `${lines}L · ${headline}`;
|
||||
})();
|
||||
// Flat row: keep the `←` glyph in the prefix column. Details rows
|
||||
// drop it — the `▸/▾` disclosure marker sits in that column via CSS.
|
||||
if (isMessageBearing && txt.trim()) {
|
||||
return detailsOpenMd(api, 'tool-result-block',
|
||||
'recv ← ' + summaryBody, txt);
|
||||
}
|
||||
if (!txt.trim() || txt.length <= 120) {
|
||||
api.row('tool-result', summary);
|
||||
api.row('tool-result', '← ' + summaryBody);
|
||||
} else {
|
||||
api.details('tool-result-block', summary, txt);
|
||||
api.details('tool-result-block', summaryBody, txt);
|
||||
}
|
||||
}
|
||||
// Pretty-render claude's background-task subagent events
|
||||
|
|
@ -783,12 +892,19 @@
|
|||
}
|
||||
if (v.type === 'assistant' && v.message && v.message.content) {
|
||||
for (const c of v.message.content) {
|
||||
if (c.type === 'text' && c.text && c.text.trim()) api.row('text', c.text);
|
||||
if (c.type === 'text' && c.text && c.text.trim()) {
|
||||
// Assistant prose renders with markdown — claude often
|
||||
// emits bullets / fenced code / inline code; raw text
|
||||
// loses the structure.
|
||||
const row = api.row('text', '');
|
||||
row.appendChild(mdNode(c.text));
|
||||
}
|
||||
else if (c.type === 'thinking') {
|
||||
const txt = (c.thinking || c.text || '').trim();
|
||||
api.row('thinking', txt ? '· ' + txt : '· thinking …');
|
||||
}
|
||||
else if (c.type === 'tool_use') {
|
||||
if (c.id && c.name) toolNameById.set(c.id, c.name);
|
||||
if (!renderRichToolUse(c, api)) {
|
||||
api.row('tool-use', '→ ' + fmtToolUse(c));
|
||||
}
|
||||
|
|
@ -802,7 +918,10 @@
|
|||
}
|
||||
return;
|
||||
}
|
||||
api.row('sys', '· ' + trim(JSON.stringify(v), 200));
|
||||
// Catch-all for unrecognised stream-json shapes. Loud (orange) so
|
||||
// silently-dropped event types surface in the scrollback for
|
||||
// follow-up classification.
|
||||
api.row('sys', '! ' + trim(JSON.stringify(v), 200));
|
||||
}
|
||||
|
||||
// Count open turns across the backfill replay so the live banner +
|
||||
|
|
@ -844,7 +963,22 @@
|
|||
(ev.ok ? '✓' : '✗') + ' turn ' + (ev.ok ? 'ok' : 'fail')
|
||||
+ (ev.note ? ' — ' + ev.note : ''));
|
||||
},
|
||||
note(ev, api) { api.row('note', '· ' + ev.text); },
|
||||
note(ev, api) {
|
||||
const t = String(ev.text || '');
|
||||
// stderr lines coming off the claude pump get an orange `!`
|
||||
// glyph so they're not visually fused with ambient harness
|
||||
// chatter. Operator-initiated notes (/cancel, /compact,
|
||||
// /model, new-session) get a mauve italic affordance so the
|
||||
// scrollback distinguishes "the operator did this" from
|
||||
// "the harness did this on its own."
|
||||
if (t.startsWith('stderr:')) {
|
||||
api.row('note stderr', '! ' + t);
|
||||
} else if (t.startsWith('operator:')) {
|
||||
api.row('note op', '· ' + t);
|
||||
} else {
|
||||
api.row('note', '· ' + t);
|
||||
}
|
||||
},
|
||||
stream(ev, api) {
|
||||
const v = Object.assign({}, ev); delete v.kind;
|
||||
renderStream(v, api);
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@
|
|||
<div id="term-input" class="term-input"></div>
|
||||
</div>
|
||||
|
||||
<script src="/static/marked.js" defer></script>
|
||||
<script src="/static/hive-fr0nt.js" defer></script>
|
||||
<script src="/static/app.js" defer></script>
|
||||
</body>
|
||||
|
|
|
|||
|
|
@ -74,6 +74,11 @@ async fn main() -> Result<()> {
|
|||
let login_state = Arc::new(Mutex::new(initial));
|
||||
let bus = Bus::new();
|
||||
let stats = TurnStats::open_default();
|
||||
if let Some(s) = &stats
|
||||
&& let Some(u) = s.last_usage()
|
||||
{
|
||||
bus.seed_usage(u);
|
||||
}
|
||||
let files = turn::TurnFiles::prepare(&cli.socket, &label, mcp::Flavor::Agent).await?;
|
||||
let turn_lock: TurnLock = Arc::new(tokio::sync::Mutex::new(()));
|
||||
plugins::install_configured(&cli.socket, Some("manager")).await;
|
||||
|
|
|
|||
|
|
@ -64,6 +64,11 @@ async fn main() -> Result<()> {
|
|||
let login_state = Arc::new(Mutex::new(initial));
|
||||
let bus = Bus::new();
|
||||
let stats = TurnStats::open_default();
|
||||
if let Some(s) = &stats
|
||||
&& let Some(u) = s.last_usage()
|
||||
{
|
||||
bus.seed_usage(u);
|
||||
}
|
||||
let files = turn::TurnFiles::prepare(&cli.socket, &label, mcp::Flavor::Manager).await?;
|
||||
let turn_lock: TurnLock = Arc::new(tokio::sync::Mutex::new(()));
|
||||
plugins::install_configured(&cli.socket, None).await;
|
||||
|
|
|
|||
|
|
@ -378,6 +378,15 @@ impl Bus {
|
|||
self.emit(LiveEvent::ModelChanged { model: value });
|
||||
}
|
||||
|
||||
/// Seed `last_usage` at startup without emitting a SSE event.
|
||||
/// Used by the bin entrypoints to backfill from the most recent
|
||||
/// `turn_stats` row so the per-agent web UI's `ctx-badge` paints
|
||||
/// real numbers on cold load instead of staying empty until the
|
||||
/// next turn finishes.
|
||||
pub fn seed_usage(&self, usage: TokenUsage) {
|
||||
*self.last_usage.lock().unwrap() = Some(usage);
|
||||
}
|
||||
|
||||
/// Record the latest token usage from a completed turn.
|
||||
pub fn record_usage(&self, usage: TokenUsage) {
|
||||
*self.last_usage.lock().unwrap() = Some(usage);
|
||||
|
|
|
|||
|
|
@ -156,6 +156,34 @@ impl TurnStats {
|
|||
tracing::warn!(error = ?e, "turn_stats: insert failed");
|
||||
}
|
||||
}
|
||||
|
||||
/// Token counts from the most recently inserted row, if any. Lets
|
||||
/// the harness seed `Bus::last_usage` on startup so the per-agent
|
||||
/// web UI's `ctx-badge` paints with real numbers on cold load
|
||||
/// instead of waiting for the next `TokenUsageChanged` SSE event.
|
||||
/// Best-effort: any sqlite error returns `None` and the caller
|
||||
/// falls back to the empty state.
|
||||
#[must_use]
|
||||
pub fn last_usage(&self) -> Option<crate::events::TokenUsage> {
|
||||
let conn = self.inner.lock().unwrap();
|
||||
conn.query_row(
|
||||
"SELECT input_tokens, output_tokens,
|
||||
cache_read_input_tokens, cache_creation_input_tokens
|
||||
FROM turn_stats
|
||||
ORDER BY started_at DESC
|
||||
LIMIT 1",
|
||||
[],
|
||||
|row| {
|
||||
Ok(crate::events::TokenUsage {
|
||||
input_tokens: u64::try_from(row.get::<_, i64>(0)?).unwrap_or(0),
|
||||
output_tokens: u64::try_from(row.get::<_, i64>(1)?).unwrap_or(0),
|
||||
cache_read_input_tokens: u64::try_from(row.get::<_, i64>(2)?).unwrap_or(0),
|
||||
cache_creation_input_tokens: u64::try_from(row.get::<_, i64>(3)?).unwrap_or(0),
|
||||
})
|
||||
},
|
||||
)
|
||||
.ok()
|
||||
}
|
||||
}
|
||||
|
||||
fn default_path() -> PathBuf {
|
||||
|
|
|
|||
|
|
@ -94,6 +94,7 @@ pub async fn serve(
|
|||
.route("/static/agent.css", get(serve_css))
|
||||
.route("/static/app.js", get(serve_app_js))
|
||||
.route("/static/hive-fr0nt.js", get(serve_shared_js))
|
||||
.route("/static/marked.js", get(serve_marked_js))
|
||||
.route("/api/state", get(api_state))
|
||||
.route("/events/stream", get(events_stream))
|
||||
.route("/events/history", get(events_history))
|
||||
|
|
@ -190,6 +191,13 @@ async fn serve_shared_js() -> impl IntoResponse {
|
|||
)
|
||||
}
|
||||
|
||||
async fn serve_marked_js() -> impl IntoResponse {
|
||||
(
|
||||
[("content-type", "application/javascript")],
|
||||
hive_fr0nt::MARKED_JS,
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct StateSnapshot {
|
||||
/// Bus seq at the moment this snapshot was assembled. Clients dedupe
|
||||
|
|
|
|||
|
|
@ -668,6 +668,10 @@ summary:hover { color: var(--purple); }
|
|||
align-items: baseline;
|
||||
gap: 0.5em;
|
||||
padding: 0.1em 0;
|
||||
/* Override the per-agent-terminal's hanging-indent metrics from
|
||||
TERMINAL_CSS — the dashboard's broker rows are flex grids, not
|
||||
glyph-prefixed text, and don't want the prefix column. */
|
||||
text-indent: 0;
|
||||
}
|
||||
.live .msgrow .msg-body {
|
||||
flex: 1 1 0;
|
||||
|
|
|
|||
6
hive-fr0nt/assets/marked.min.js
vendored
Normal file
6
hive-fr0nt/assets/marked.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -60,41 +60,54 @@
|
|||
from { opacity: 0; transform: translateY(4px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
/* Unified prefix column for every row kind. The glyph (`→ ← · ◆ ✓ ✗ ⌁ !`)
|
||||
is the first character of the row's text content; `padding-left` reserves
|
||||
the column and `text-indent: -1.4em` pulls the glyph back into it. Wrapped
|
||||
continuation lines then start under the body, not under the glyph, so
|
||||
wraps don't blur into the next row. `details.row` summaries reuse the
|
||||
same metrics below. */
|
||||
.live .row {
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
padding: 0.05em 0;
|
||||
line-height: 1.45;
|
||||
border-left: 2px solid transparent;
|
||||
padding-left: 0.5em;
|
||||
padding-left: 1.9em;
|
||||
text-indent: -1.4em;
|
||||
margin: 0.1em 0;
|
||||
}
|
||||
.live .row + .row { border-top: 0; }
|
||||
/* Row-kind colours. Pages register renderers that emit these classes;
|
||||
any class no page emits is just dead CSS, which is fine. */
|
||||
.live .turn-start {
|
||||
color: var(--amber);
|
||||
font-weight: bold;
|
||||
margin-top: 1em;
|
||||
border-left-color: var(--amber);
|
||||
padding-top: 0.3em;
|
||||
}
|
||||
.live .turn-start:first-child { margin-top: 0; }
|
||||
.live .turn-body {
|
||||
color: var(--fg);
|
||||
font-weight: normal;
|
||||
margin-top: 0.15em;
|
||||
padding-left: 1.2em;
|
||||
opacity: 0.85;
|
||||
}
|
||||
.live .turn-end-ok { color: var(--green); border-left-color: var(--green); margin-bottom: 0.4em; }
|
||||
.live .turn-end-fail { color: var(--red); border-left-color: var(--red); margin-bottom: 0.4em; }
|
||||
.live .text { color: var(--fg); padding-left: 1.2em; }
|
||||
.live .thinking { color: var(--muted); font-style: italic; padding-left: 1.2em; }
|
||||
.live .tool-use { color: var(--cyan); padding-left: 1.2em; }
|
||||
.live .tool-result { color: var(--muted); padding-left: 1.2em; }
|
||||
.live .result { color: var(--green); padding-left: 0.5em; }
|
||||
.live .sys, .live .note { color: var(--muted); }
|
||||
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); }
|
||||
.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 .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;
|
||||
|
|
@ -137,28 +150,31 @@
|
|||
pointer-events: auto;
|
||||
}
|
||||
.tail-pill:hover { filter: brightness(1.1); }
|
||||
/* Expandable rows reuse the flat-row prefix metrics (padding-left +
|
||||
negative text-indent) so the disclosure glyph (`▸ / ▾`) lands in
|
||||
exactly the same column as flat-row prefix glyphs (`→ ← · ◆ ✓ ✗`).
|
||||
Summary text omits the per-row directional glyph (the row colour
|
||||
already carries cyan = outbound tool, muted = inbound result) so
|
||||
the prefix column doesn't have to fit two glyphs side-by-side. */
|
||||
details.row {
|
||||
white-space: normal;
|
||||
padding-left: 0.5em;
|
||||
}
|
||||
details.row > summary {
|
||||
cursor: pointer;
|
||||
color: var(--muted);
|
||||
list-style: none;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
details.row > summary::before {
|
||||
content: '▸ ';
|
||||
color: var(--muted);
|
||||
display: inline-block;
|
||||
width: 1em;
|
||||
color: inherit;
|
||||
}
|
||||
details.row[open] > summary::before { content: '▾ '; }
|
||||
details.row.tool-result-block > summary { color: var(--muted); }
|
||||
details.row > pre.diff-body {
|
||||
margin: 0.3em 0 0.4em 1.2em;
|
||||
details.row > pre.diff-body,
|
||||
details.row > pre.tool-body {
|
||||
margin: 0.3em 0 0.4em 0;
|
||||
padding: 0.4em 0.6em;
|
||||
text-indent: 0;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
border-left: 2px solid var(--purple-dim);
|
||||
white-space: pre-wrap;
|
||||
|
|
@ -166,17 +182,44 @@ details.row > pre.diff-body {
|
|||
max-height: 22em;
|
||||
overflow-y: auto;
|
||||
}
|
||||
details.row > pre.tool-body { color: var(--fg); }
|
||||
details.row > pre.diff-body .diff-add { color: var(--green); }
|
||||
details.row > pre.diff-body .diff-del { color: var(--red); }
|
||||
details.row > pre.diff-body .diff-ctx { color: var(--fg); }
|
||||
details.row > pre.tool-body {
|
||||
margin: 0.3em 0 0.4em 1.2em;
|
||||
/* Markdown body inside a row (assistant text, send/recv/ask/answer
|
||||
message bodies). Inline elements get muted accents; block elements
|
||||
reset the parent row's hanging indent so content lays out cleanly. */
|
||||
.live .row .md p { margin: 0.2em 0; }
|
||||
.live .row .md p:first-child { margin-top: 0; }
|
||||
.live .row .md p:last-child { margin-bottom: 0; }
|
||||
.live .row .md code {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
padding: 0.05em 0.3em;
|
||||
border-radius: 3px;
|
||||
font-size: 0.95em;
|
||||
}
|
||||
.live .row .md pre {
|
||||
margin: 0.3em 0;
|
||||
padding: 0.4em 0.6em;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
border-left: 2px solid var(--purple-dim);
|
||||
color: var(--fg);
|
||||
text-indent: 0;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
max-height: 22em;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.live .row .md pre code {
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
border-radius: 0;
|
||||
}
|
||||
.live .row .md a { color: var(--cyan); text-decoration: underline; }
|
||||
.live .row .md strong { color: inherit; font-weight: bold; }
|
||||
.live .row .md em { color: inherit; font-style: italic; }
|
||||
.live .row .md ul, .live .row .md ol { margin: 0.2em 0 0.2em 1.4em; padding: 0; }
|
||||
.live .row .md li { margin: 0.05em 0; }
|
||||
.live .row .md blockquote {
|
||||
margin: 0.2em 0;
|
||||
padding-left: 0.6em;
|
||||
border-left: 2px solid var(--purple-dim);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,3 +32,11 @@
|
|||
pub const BASE_CSS: &str = include_str!("../assets/base.css");
|
||||
pub const TERMINAL_CSS: &str = include_str!("../assets/terminal.css");
|
||||
pub const TERMINAL_JS: &str = include_str!("../assets/terminal.js");
|
||||
/// Vendored [marked](https://github.com/markedjs/marked) v4.0.2 UMD bundle.
|
||||
/// Exposes a global `marked` with `.parse(src, opts)` returning HTML. Used
|
||||
/// by the per-agent terminal to render message bodies (`send` / `recv` /
|
||||
/// `ask` / `answer` / assistant text) with basic markdown — paragraphs,
|
||||
/// lists, fenced + inline code, bold/italic, links. Vendored rather than
|
||||
/// CDN-loaded so the per-agent page works on operator machines without
|
||||
/// internet egress (the container itself never fetches it).
|
||||
pub const MARKED_JS: &str = include_str!("../assets/marked.min.js");
|
||||
|
|
|
|||
Loading…
Reference in a new issue