Compare commits

..
5 changed files with 209 additions and 86 deletions

View file

@ -338,7 +338,7 @@ h2, h3 {
background: color-mix(in srgb, var(--red) 18%, transparent); background: color-mix(in srgb, var(--red) 18%, transparent);
color: var(--red); color: var(--red);
} }
.header-pill-todos .header-pill-count { .header-pill-tasks .header-pill-count {
background: color-mix(in srgb, var(--green) 18%, transparent); background: color-mix(in srgb, var(--green) 18%, transparent);
color: var(--green); color: var(--green);
} }

View file

@ -130,11 +130,18 @@ window.marked = marked;
buildInboxList(lastInbox)); buildInboxList(lastInbox));
}); });
} }
const todosPill = $('todos-pill'); const loosePill = $('loose-ends-pill');
if (todosPill) { if (loosePill) {
todosPill.addEventListener('click', () => { loosePill.addEventListener('click', () => {
Panel.open('todos', 'todos · ' + lastTodos.length, Panel.open('loose-ends', 'loose ends · ' + lastLooseEnds.length,
buildTodosList(lastTodos)); buildLooseEndsList(lastLooseEnds));
});
}
const bashPill = $('bash-tasks-pill');
if (bashPill) {
bashPill.addEventListener('click', () => {
Panel.open('bash-tasks', 'tasks · ' + lastBashTasks.length,
buildBashTasksList(lastBashTasks));
}); });
} }
})(); })();
@ -822,26 +829,26 @@ window.marked = marked;
} }
renderStateBadge(); renderStateBadge();
} }
// Todos section: in-agent todos (loose-ends v2) pushed by subsystems // Loose-ends section: same data the get_loose_ends MCP tool
// (matrix, forge, bash). Best-effort fetch on cold load + after every // returns. Best-effort fetch on cold load + after every turn_end
// turn_end. Silent failure keeps the pill at zero. // (a turn likely answered or asked something). Silent failure
async function refreshTodos() { // keeps the pill count at zero rather than surfacing a stale chrome.
async function refreshLooseEnds() {
try { try {
const resp = await fetch('api/todos'); const resp = await fetch('api/loose-ends');
if (!resp.ok) { if (!resp.ok) {
renderTodos([]); renderLooseEnds([]);
return; return;
} }
const data = await resp.json(); const data = await resp.json();
renderTodos(data.todos || []); renderLooseEnds(data.loose_ends || []);
} catch (err) { } catch (err) {
console.warn('todos fetch failed', err); console.warn('loose-ends fetch failed', err);
renderTodos([]); renderLooseEnds([]);
} }
} }
/** Latest snapshot kept in module state so the pill click handler /** Latest snapshot kept in module state so the pill click handler
* has fresh data to render into the panel without re-fetching. */ * has fresh data to render into the panel without re-fetching. */
let lastTodos = [];
let lastLooseEnds = []; let lastLooseEnds = [];
let lastInbox = []; let lastInbox = [];
@ -916,13 +923,47 @@ window.marked = marked;
return wrap; return wrap;
} }
/** Build the todos side-panel list. Each entry is a LooseEnd::Todo /** Pill-count + open-panel-refresh wiring for loose-ends. The legacy
* (subsystem, summary, source, age_seconds). */ * in-page `<details>` block is gone operator clicks the header
function buildTodosList(todos) { * pill to surface the list in the side panel. */
function renderLooseEnds(threads) {
lastLooseEnds = threads;
const pill = $('loose-ends-pill');
const count = $('loose-ends-count');
if (count) count.textContent = threads.length;
if (pill) pill.hidden = threads.length === 0;
Panel.refresh('loose-ends', 'loose ends · ' + threads.length,
buildLooseEndsList(threads));
// Wire inline answer forms into any `ask → operator` rows
// waiting on a broker-assigned question id.
reconcileAskBinds();
}
// Running bash tasks: `GET /api/bash-tasks` returns the in-flight
// (Pending/Running) TaskFiles from the in-container bash-tasks dir. Same
// best-effort, silent-failure contract as loose-ends — a fetch miss keeps
// the pill at zero rather than surfacing stale chrome.
let lastBashTasks = [];
async function refreshBashTasks() {
try {
const resp = await fetch('api/bash-tasks');
if (!resp.ok) {
renderBashTasks([]);
return;
}
const data = await resp.json();
renderBashTasks(data.tasks || []);
} catch (err) {
console.warn('bash-tasks fetch failed', err);
renderBashTasks([]);
}
}
function buildBashTasksList(tasks) {
const wrap = el('div', { class: 'agent-inbox' }); const wrap = el('div', { class: 'agent-inbox' });
if (!todos.length) { if (!tasks.length) {
wrap.append(el('p', { class: 'side-panel-empty' }, wrap.append(el('p', { class: 'side-panel-empty' },
'no todos — all subsystem queues are clear.')); 'no running bash tasks.'));
return wrap; return wrap;
} }
const list = el('ul'); const list = el('ul');
@ -932,13 +973,20 @@ window.marked = marked;
if (s < 86400) return Math.floor(s / 3600) + 'h'; if (s < 86400) return Math.floor(s / 3600) + 'h';
return Math.floor(s / 86400) + 'd'; return Math.floor(s / 86400) + 'd';
}; };
for (const t of todos) { const now = Math.floor(Date.now() / 1000);
for (const t of tasks) {
const li = el('li'); const li = el('li');
const label = t.source ? t.subsystem + ' · ' + t.source : t.subsystem; const running = t.status === 'running';
// Elapsed since the task started (running) or was queued (pending).
const since = running ? (t.started_at || t.created_at || now) : (t.created_at || now);
const elapsed = Math.max(0, now - since);
// Single-line, truncated command preview (the cmd can be multi-line).
const cmdPreview = (t.cmd || '').replace(/\s+/g, ' ').trim().slice(0, 100);
li.append( li.append(
el('span', { class: 'inbox-from' }, label), ' ', el('span', { class: 'bash-task-status bash-task-' + t.status }, running ? '▶ running' : '◷ queued'), ' ',
el('span', { class: 'inbox-ts' }, fmtAge(t.age_seconds || 0) + ' ago'), el('span', { class: 'inbox-from' }, t.id), ' ',
el('div', { class: 'inbox-body' }, t.summary || ''), el('span', { class: 'inbox-ts' }, (running ? '' : 'queued ') + fmtAge(elapsed) + (running ? ' elapsed' : '')),
el('div', { class: 'inbox-body bash-task-cmd' }, cmdPreview),
); );
list.append(li); list.append(li);
} }
@ -946,15 +994,14 @@ window.marked = marked;
return wrap; return wrap;
} }
/** Pill-count + open-panel-refresh wiring for todos. */ function renderBashTasks(tasks) {
function renderTodos(todos) { lastBashTasks = tasks;
lastTodos = todos; const pill = $('bash-tasks-pill');
const pill = $('todos-pill'); const count = $('bash-tasks-count');
const count = $('todos-count'); if (count) count.textContent = tasks.length;
if (count) count.textContent = todos.length; if (pill) pill.hidden = tasks.length === 0;
if (pill) pill.hidden = todos.length === 0; Panel.refresh('bash-tasks', 'tasks · ' + tasks.length,
Panel.refresh('todos', 'todos · ' + todos.length, buildBashTasksList(tasks));
buildTodosList(todos));
} }
/** Walk `pendingAskBinds` against the latest `lastLooseEnds` /** Walk `pendingAskBinds` against the latest `lastLooseEnds`
@ -1019,6 +1066,7 @@ window.marked = marked;
}); });
if (resp.ok) { if (resp.ok) {
status.textContent = 'answered ✓'; status.textContent = 'answered ✓';
refreshLooseEnds();
} else { } else {
status.textContent = 'failed: ' + (await resp.text()); status.textContent = 'failed: ' + (await resp.text());
} }
@ -1315,8 +1363,16 @@ window.marked = marked;
renderModelChip(s.model); renderModelChip(s.model);
renderEffortChip(s.effort); renderEffortChip(s.effort);
renderTokenUsage({ ctx: s.ctx_usage, cost: s.cost_usage }); renderTokenUsage({ ctx: s.ctx_usage, cost: s.cost_usage });
// Todos pill: cold-load populate; turn_end refreshes via renderTodos. // Open-threads aren't part of /api/state (kept on the broker
refreshTodos(); // db, fetched via the per-agent socket). Cold-load fetches
// it here; turn_end refreshes it via the renderer below.
refreshLooseEnds();
// Cold-load populate of the running-bash-tasks pill. Tasks complete
// asynchronously between turns (independent of turn_end SSE) and
// /api/state isn't polled while online, so a dedicated interval (set
// up next to the initial refreshState() below) keeps the count live;
// this call just fills it immediately on first paint.
refreshBashTasks();
// Skip the re-render if nothing structurally changed. The most // Skip the re-render if nothing structurally changed. The most
// common case is `online` polling itself — without this guard, the // common case is `online` polling itself — without this guard, the
// operator's <input value> gets clobbered every cycle. // operator's <input value> gets clobbered every cycle.
@ -1346,10 +1402,12 @@ window.marked = marked;
} }
} }
refreshState(); refreshState();
// Keep the todos pill live. Todos change asynchronously (matrix syncs, // Keep the running-bash-tasks pill live. Unlike loose-ends (refreshed on
// bash task starts/completions) independent of turn_end SSE, so poll // turn_end SSE), bash tasks start + finish asynchronously between turns and
// the snapshot endpoint on a light interval. Fails silently when offline. // /api/state isn't polled while online — so poll the cheap snapshot endpoint
setInterval(refreshTodos, 4000); // on a light interval. Fails silently (renders zero) when offline. v1 is
// polling; an SSE push for task state could replace this later.
setInterval(refreshBashTasks, 4000);
// ─── live event stream ────────────────────────────────────────────────── // ─── live event stream ──────────────────────────────────────────────────
// Scrolling, pill, backfill + SSE plumbing live in hive-fr0nt::TERMINAL_JS // Scrolling, pill, backfill + SSE plumbing live in hive-fr0nt::TERMINAL_JS
@ -1447,7 +1505,11 @@ window.marked = marked;
slot._askQuestion = c._body; slot._askQuestion = c._body;
d.appendChild(slot); d.appendChild(slot);
pendingAskBinds.push(slot); pendingAskBinds.push(slot);
if (api.fromHistory) reconcileAskBinds(); // Mid-turn refresh — the standard `turn_end` refresh
// won't fire until the agent's turn finishes; we want
// the form to show up as soon as the ask lands.
if (!api.fromHistory) refreshLooseEnds();
else reconcileAskBinds();
} }
} }
return d; return d;
@ -1476,6 +1538,15 @@ window.marked = marked;
const sourceName = c.tool_use_id ? toolNameById.get(c.tool_use_id) : null; const sourceName = c.tool_use_id ? toolNameById.get(c.tool_use_id) : null;
const isMessageBearing = sourceName === 'mcp__hyperhive__recv'; const isMessageBearing = sourceName === 'mcp__hyperhive__recv';
// When an ask's tool_result lands the broker has just // When an ask's tool_result lands the broker has just
// persisted the question with its assigned id. Refresh
// loose-ends so reconcileAskBinds finds the new entry and
// mounts the inline answer form under the rendered ask row.
// Skipped during history replay (the question's likely
// long-resolved; turn_end refresh on cold-load covers
// reconciliation).
if (sourceName === 'mcp__hyperhive__ask' && !api.fromHistory) {
refreshLooseEnds();
}
const trimmed = txt.replace(/\s+/g, ' ').trim(); const trimmed = txt.replace(/\s+/g, ' ').trim();
const summaryBody = (() => { const summaryBody = (() => {
if (!trimmed) return '(empty)'; if (!trimmed) return '(empty)';
@ -1695,7 +1766,8 @@ window.marked = marked;
openTurnsFromHistory = Math.max(0, openTurnsFromHistory - 1); openTurnsFromHistory = Math.max(0, openTurnsFromHistory - 1);
} else { } else {
setBannerActive(false); setState('idle'); setBannerActive(false); setState('idle');
refreshTodos(); // Likely answered/asked/scheduled something — refresh.
refreshLooseEnds();
} }
const cls = ev.ok ? 'turn-end-ok' : 'turn-end-fail'; const cls = ev.ok ? 'turn-end-ok' : 'turn-end-fail';
const row = api.row(cls, const row = api.row(cls,

View file

@ -58,11 +58,17 @@
<span class="header-pill-label">inbox</span> <span class="header-pill-label">inbox</span>
<span class="header-pill-count" id="inbox-count">0</span> <span class="header-pill-count" id="inbox-count">0</span>
</button> </button>
<button type="button" id="todos-pill" class="header-pill header-pill-todos" hidden <button type="button" id="loose-ends-pill" class="header-pill header-pill-loose" hidden
title="open todos flyout"> title="open loose-ends flyout">
<span class="header-pill-icon" aria-hidden="true">📋</span> <span class="header-pill-icon" aria-hidden="true">🪢</span>
<span class="header-pill-label">todos</span> <span class="header-pill-label">loose ends</span>
<span class="header-pill-count" id="todos-count">0</span> <span class="header-pill-count" id="loose-ends-count">0</span>
</button>
<button type="button" id="bash-tasks-pill" class="header-pill header-pill-tasks" hidden
title="open running bash-tasks flyout">
<span class="header-pill-icon" aria-hidden="true"></span>
<span class="header-pill-label">tasks</span>
<span class="header-pill-count" id="bash-tasks-count">0</span>
</button> </button>
<button type="button" id="overflow-btn" class="overflow-btn" <button type="button" id="overflow-btn" class="overflow-btn"
aria-haspopup="menu" aria-expanded="false" aria-haspopup="menu" aria-expanded="false"

View file

@ -115,7 +115,8 @@ pub async fn serve(
.route("/api/effort", post(actions::post_set_effort)) .route("/api/effort", post(actions::post_set_effort))
.route("/api/new-session", post(actions::post_new_session)) .route("/api/new-session", post(actions::post_new_session))
.route("/api/logout", post(auth::post_logout)) .route("/api/logout", post(auth::post_logout))
.route("/api/todos", get(stats::api_todos)) .route("/api/loose-ends", get(stats::api_loose_ends))
.route("/api/bash-tasks", get(stats::api_bash_tasks))
.route("/api/stats", get(stats::api_stats)) .route("/api/stats", get(stats::api_stats))
.route("/screen/ws", get(screen::screen_ws)) .route("/screen/ws", get(screen::screen_ws))
.route("/icon", get(screen::serve_icon)); .route("/icon", get(screen::serve_icon));

View file

@ -1,10 +1,11 @@
//! Stats + loose-ends + todos read endpoints. //! Stats + loose-ends + bash-tasks read endpoints.
use axum::extract::State; use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response}; use axum::response::{IntoResponse, Response};
use serde::Deserialize; use serde::Deserialize;
use super::AppState; use super::{AppState, error_response};
#[derive(Deserialize)] #[derive(Deserialize)]
pub(super) struct StatsQuery { pub(super) struct StatsQuery {
@ -46,43 +47,86 @@ async fn fetch_reminder_stats(
} }
} }
/// `GET /api/todos` — snapshot of this agent's local todos (loose-ends v2). /// Proxy this agent's loose-ends list via the per-agent socket. The
/// /// web UI surfaces the result as a collapsible section in the page
/// Connects to the in-agent harness socket (`HIVE_AGENT_SOCKET`) and calls /// so the operator can see at a glance what's pending against the
/// `ListTodos`. Returns `{ "todos": [...] }` where each entry is a /// agent (questions asked by it, peer questions targeting it,
/// `LooseEnd::Todo` (subsystem, key, summary, source, `age_seconds`). Returns /// reminders it scheduled, approvals for the manager). Same data
/// an empty array when the socket is unavailable — best-effort, silent failure. /// the `mcp__hyperhive__get_loose_ends` tool sees from inside the
pub(super) async fn api_todos() -> Response { /// container.
use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader}; pub(super) async fn api_loose_ends(State(state): State<AppState>) -> Response {
use tokio::net::UnixStream; match super::broker_request(
&state.socket,
let socket_path = match std::env::var_os("HIVE_AGENT_SOCKET") { &hive_core_agent_sock::Request::GetLooseEnds { agent: None },
Some(p) => std::path::PathBuf::from(p), )
None => return axum::Json(serde_json::json!({ "todos": [] })).into_response(), .await
}; {
if !socket_path.exists() { Ok(hive_core_agent_sock::Response::LooseEnds { loose_ends }) => {
return axum::Json(serde_json::json!({ "todos": [] })).into_response(); axum::Json(serde_json::json!({ "loose_ends": loose_ends })).into_response()
}
Ok(hive_core_agent_sock::Response::Err { message }) => error_response(
StatusCode::INTERNAL_SERVER_ERROR,
&format!("get_loose_ends: {message}"),
),
Ok(other) => error_response(
StatusCode::INTERNAL_SERVER_ERROR,
&format!("get_loose_ends: unexpected response: {other:?}"),
),
Err(e) => super::broker_error_response(&e, "get_loose_ends"),
} }
let todos = tokio::time::timeout(std::time::Duration::from_secs(3), async move { }
let mut stream = UnixStream::connect(&socket_path).await?;
let req = hive_agent_sock::Request::ListTodos { subsystem: None }; /// `GET /api/bash-tasks` — snapshot of this agent's in-flight bash tasks.
let mut line = serde_json::to_string(&req)?; ///
line.push('\n'); /// The `hive-bash-mcp` daemon runs in this same container and writes one
stream.write_all(line.as_bytes()).await?; /// `<id>.json` ([`hive_sh4re::TaskFile`]) per task under the harness
stream.flush().await?; /// `bash-tasks/` dir. This reads that dir and returns the tasks still
let mut lines = BufReader::new(stream).lines(); /// `Pending` or `Running`, so the agent page can show what's running without
let resp_line = lines /// going through the broker. Snapshot only — the page polls/refreshes it like
.next_line() /// `/api/loose-ends`; there's no live SSE push for task state yet. Unreadable
.await? /// or malformed files (incl. the daemon's `.json.tmp` scratch writes, which
.ok_or_else(|| anyhow::anyhow!("agent socket closed without response"))?; /// don't match the `.json` extension) are skipped so one stray file can't
let resp: hive_agent_sock::Response = serde_json::from_str(&resp_line)?; /// fail the whole list.
anyhow::Ok(match resp { pub(super) async fn api_bash_tasks() -> Response {
hive_agent_sock::Response::LooseEnds { loose_ends } => loose_ends, let dir = crate::paths::harness_dir().join("bash-tasks");
_ => Vec::new(), // The dir scan + per-file reads are blocking fs I/O; run them off the
}) // async executor so a slow or large tasks dir can't stall other requests.
let tasks = tokio::task::spawn_blocking(move || {
let mut tasks: Vec<hive_sh4re::TaskFile> = Vec::new();
let Ok(rd) = std::fs::read_dir(&dir) else {
return tasks;
};
for entry in rd.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(task) = serde_json::from_str::<hive_sh4re::TaskFile>(&text) else {
continue;
};
if matches!(
task.status,
hive_sh4re::TaskStatus::Pending | hive_sh4re::TaskStatus::Running
) {
tasks.push(task);
}
}
// Running before Pending, then oldest-first so a long-runner sits on top.
tasks.sort_by(|a, b| {
let rank = |s: &hive_sh4re::TaskStatus| match s {
hive_sh4re::TaskStatus::Running => 0,
_ => 1,
};
rank(&a.status)
.cmp(&rank(&b.status))
.then(a.created_at.cmp(&b.created_at))
});
tasks
}) })
.await .await
.unwrap_or_else(|_| Err(anyhow::anyhow!("timeout")))
.unwrap_or_default(); .unwrap_or_default();
axum::Json(serde_json::json!({ "todos": todos })).into_response() axum::Json(serde_json::json!({ "tasks": tasks })).into_response()
} }