Extends GET /api/journal/{name} to also accept the four hive infra
container names (hive-ci, hive-forge, hive-gateway, hive-matrix —
hive_priv_sock::InfraContainer is the allowlist), reusing the same
journalctl -M / hive-priv delegation path already used for agent
containers. Infra containers don't run the per-agent hive daemons, so
the unit filter is skipped for them — always the full machine journal.
Frontend: the AGENT tab's agent selector now lists infra containers
in a separate optgroup (sourced from /api/state's existing
infra_containers field), and disables the unit-filter select when one
is chosen.
360 lines
15 KiB
JavaScript
360 lines
15 KiB
JavaScript
// /logs.html entry point: log viewer with three sub-tabs (AGENT, SYSTEM,
|
|
// AUDIT). Build log history has moved to /builds.html.
|
|
// AGENT — per-container journald viewer, backed by GET /api/journal/{name}
|
|
// SYSTEM — host service logs, backed by GET /api/journal-host
|
|
// AUDIT — agent-initiated privileged-action trail, GET /api/audit-log;
|
|
// live-appends via the `audit_entry_added` /dashboard/stream event
|
|
//
|
|
// Tab routing via URL hash (#agent, #system, #audit). Default: #agent.
|
|
//
|
|
// URL params `?agent=name` and `?unit=svc` pre-select the agent + unit on
|
|
// the AGENT tab (deep-link from other pages, e.g. the per-agent ⋮ menu).
|
|
// Last-fetched timestamp is shown next to the refresh button on AGENT +
|
|
// SYSTEM tabs so the operator knows how stale the output is.
|
|
|
|
import {
|
|
$, el, fmtAgeSecs, openStream, initServerWarnings,
|
|
} from './common.js';
|
|
import { epochSec } from './util.js';
|
|
import { createTabStrip } from '@hive/shared/tabs.js';
|
|
|
|
(() => {
|
|
initServerWarnings();
|
|
|
|
// ─── tab routing ──────────────────────────────────────────────────────
|
|
// The shared hash-routed tab strip (@hive/shared/tabs.js) handles the
|
|
// active toggle + aria-selected + pane visibility + the SYSTEM lazy
|
|
// fetch via onShow. Constructed in the init block below (after the
|
|
// fetch fns + element refs it depends on exist). `logTabs.active()`
|
|
// replaces the old `activeTab()`.
|
|
let logTabs;
|
|
|
|
// ─── helpers ──────────────────────────────────────────────────────────
|
|
|
|
// ─── AGENT tab ────────────────────────────────────────────────────────
|
|
|
|
const agentSelect = $('agent-select');
|
|
const agentUnitSelect = $('agent-unit-select');
|
|
const agentRefresh = $('agent-refresh');
|
|
const agentOutput = $('agent-output');
|
|
const agentFetchTs = $('agent-fetch-ts');
|
|
|
|
// Format a last-fetched timestamp: "fetched just now" / "fetched 3m ago".
|
|
function fmtFetchTs(fetchedAt) {
|
|
const ageSecs = Math.floor((Date.now() - fetchedAt) / 1000);
|
|
return 'fetched ' + (ageSecs < 5 ? 'just now' : fmtAgeSecs(ageSecs) + ' ago');
|
|
}
|
|
|
|
// Names from `state.infra_containers` (hive-ci / hive-forge / hive-gateway
|
|
// / hive-matrix) — kept in sync with the fetched list so fetchAgent() can
|
|
// tell an infra container apart from an agent and skip the (inapplicable)
|
|
// unit filter for it.
|
|
let infraContainerNames = new Set();
|
|
|
|
// Populate agent selector from /api/state (agents, then the four infra
|
|
// containers in their own optgroup), then honour any `?agent=` / `?unit=`
|
|
// URL params (used by the per-agent ⋮ menu's deep-link).
|
|
async function loadAgentList() {
|
|
try {
|
|
const resp = await fetch('/api/state');
|
|
if (!resp.ok) return;
|
|
const state = await resp.json();
|
|
if (!agentSelect) return;
|
|
agentSelect.replaceChildren();
|
|
agentSelect.append(el('option', { value: '' }, '— select agent —'));
|
|
for (const c of (state.containers || [])) {
|
|
agentSelect.append(el('option', { value: c.name }, c.name));
|
|
}
|
|
infraContainerNames = new Set((state.infra_containers || []).map((c) => c.name));
|
|
if (infraContainerNames.size) {
|
|
const infraGroup = el('optgroup', { label: 'infra' });
|
|
for (const name of infraContainerNames) {
|
|
infraGroup.append(el('option', { value: name }, name));
|
|
}
|
|
agentSelect.append(infraGroup);
|
|
}
|
|
// Deep-link: honour ?agent= and ?unit= URL params.
|
|
const urlAgent = new URLSearchParams(location.search).get('agent');
|
|
const urlUnit = new URLSearchParams(location.search).get('unit');
|
|
if (urlAgent) {
|
|
const found = Array.from(agentSelect.options).some((o) => o.value === urlAgent);
|
|
if (found) {
|
|
agentSelect.value = urlAgent;
|
|
if (urlUnit && agentUnitSelect) {
|
|
const unitFound = Array.from(agentUnitSelect.options)
|
|
.some((o) => o.value === urlUnit);
|
|
if (unitFound) agentUnitSelect.value = urlUnit;
|
|
}
|
|
syncUnitSelectForSelection();
|
|
fetchAgent();
|
|
}
|
|
}
|
|
} catch { /**/ }
|
|
}
|
|
|
|
// Infra containers don't run the per-agent hive daemons, so the unit
|
|
// filter is meaningless for them — disable the selector and always fetch
|
|
// the full machine journal to avoid a picked unit silently doing nothing.
|
|
function syncUnitSelectForSelection() {
|
|
if (!agentUnitSelect) return;
|
|
const isInfra = infraContainerNames.has(agentSelect ? agentSelect.value : '');
|
|
agentUnitSelect.disabled = isInfra;
|
|
if (isInfra) agentUnitSelect.value = '';
|
|
}
|
|
if (agentSelect) agentSelect.addEventListener('change', syncUnitSelectForSelection);
|
|
|
|
let agentFetching = false;
|
|
let agentLastFetch = 0;
|
|
async function fetchAgent() {
|
|
if (!agentSelect || !agentOutput) return;
|
|
const name = agentSelect.value;
|
|
if (!name) { agentOutput.textContent = 'select an agent above'; return; }
|
|
if (agentFetching) return;
|
|
agentFetching = true;
|
|
agentOutput.textContent = 'fetching…';
|
|
if (agentFetchTs) agentFetchTs.hidden = true;
|
|
const isInfra = infraContainerNames.has(name);
|
|
const unit = (!isInfra && agentUnitSelect) ? agentUnitSelect.value : '';
|
|
const params = new URLSearchParams({ lines: '500' });
|
|
if (unit) params.set('unit', unit);
|
|
try {
|
|
const resp = await fetch('/api/journal/' + encodeURIComponent(name) + '?' + params);
|
|
const text = await resp.text();
|
|
agentOutput.textContent = resp.ok ? (text || '(empty)') : 'error ' + resp.status + '\n' + text;
|
|
agentOutput.scrollTop = agentOutput.scrollHeight;
|
|
if (resp.ok) {
|
|
agentLastFetch = Date.now();
|
|
if (agentFetchTs) {
|
|
agentFetchTs.textContent = fmtFetchTs(agentLastFetch);
|
|
agentFetchTs.hidden = false;
|
|
}
|
|
}
|
|
} catch (err) {
|
|
agentOutput.textContent = 'fetch failed: ' + err;
|
|
} finally {
|
|
agentFetching = false;
|
|
}
|
|
}
|
|
|
|
if (agentSelect) agentSelect.addEventListener('change', fetchAgent);
|
|
if (agentUnitSelect) agentUnitSelect.addEventListener('change', fetchAgent);
|
|
if (agentRefresh) agentRefresh.addEventListener('click', fetchAgent);
|
|
|
|
// ─── SYSTEM tab ───────────────────────────────────────────────────────
|
|
|
|
const systemUnitSelect = $('system-unit-select');
|
|
const systemRefresh = $('system-refresh');
|
|
const systemOutput = $('system-output');
|
|
const systemFetchTs = $('system-fetch-ts');
|
|
|
|
let systemFetching = false;
|
|
let systemLastFetch = 0;
|
|
async function fetchSystem() {
|
|
if (!systemOutput) return;
|
|
if (systemFetching) return;
|
|
systemFetching = true;
|
|
systemOutput.textContent = 'fetching…';
|
|
if (systemFetchTs) systemFetchTs.hidden = true;
|
|
const unit = systemUnitSelect ? systemUnitSelect.value : 'hive-c0re.service';
|
|
const params = new URLSearchParams({ lines: '500' });
|
|
if (unit) params.set('unit', unit);
|
|
try {
|
|
const resp = await fetch('/api/journal-host?' + params);
|
|
const text = await resp.text();
|
|
systemOutput.textContent = resp.ok ? (text || '(empty)') : 'error ' + resp.status + '\n' + text;
|
|
systemOutput.scrollTop = systemOutput.scrollHeight;
|
|
if (resp.ok) {
|
|
systemLastFetch = Date.now();
|
|
if (systemFetchTs) {
|
|
systemFetchTs.textContent = fmtFetchTs(systemLastFetch);
|
|
systemFetchTs.hidden = false;
|
|
}
|
|
}
|
|
} catch (err) {
|
|
systemOutput.textContent = 'fetch failed: ' + err;
|
|
} finally {
|
|
systemFetching = false;
|
|
}
|
|
}
|
|
|
|
if (systemUnitSelect) systemUnitSelect.addEventListener('change', fetchSystem);
|
|
if (systemRefresh) systemRefresh.addEventListener('click', fetchSystem);
|
|
|
|
// ─── AUDIT tab ──────────────────────────────────────────────────────
|
|
// Operator-visible trail of agent-initiated privileged actions, backed
|
|
// by GET /api/audit-log → { entries: [...], total: N } (entries
|
|
// newest-first, server-clamped to 500; `total` drives "latest 500 of N").
|
|
// Per-entry: { id, ts_unix (secs), agent, action, target, outcome, detail }.
|
|
// outcome is 'ok' | 'err'; a capability denial is 'err' with detail
|
|
// starting "denied:" — coloured amber to read apart from an execution
|
|
// failure. Lazy-fetched on tab show (like SYSTEM); filter is a
|
|
// client-side substring on the cached rows.
|
|
|
|
const auditList = $('audit-list');
|
|
const auditFilter = $('audit-filter');
|
|
const auditRefresh = $('audit-refresh');
|
|
const auditCount = $('audit-count');
|
|
|
|
let auditEntries = [];
|
|
let auditTotal = 0;
|
|
let auditFetching = false;
|
|
|
|
// ts_unix arrives as an RFC 3339 string — fmtAgeSecs wants an age
|
|
// in seconds, so normalize via epochSec first.
|
|
function auditFmtWhen(ts) {
|
|
if (!ts) return '';
|
|
const age = Math.floor(Date.now() / 1000) - epochSec(ts);
|
|
return fmtAgeSecs(Math.max(0, age)) + ' ago';
|
|
}
|
|
|
|
// outcome → badge. 'ok' green; an 'err' whose detail starts "denied:" is a
|
|
// capability refusal (amber, labelled "denied"); other 'err' red. The
|
|
// literal outcome is the fallback label so a new value still renders.
|
|
function auditOutcomeBadge(outcome, detail) {
|
|
const denied = outcome === 'err'
|
|
&& typeof detail === 'string' && detail.startsWith('denied:');
|
|
const cls = outcome === 'ok'
|
|
? 'audit-outcome audit-outcome-ok'
|
|
: denied
|
|
? 'audit-outcome audit-outcome-denied'
|
|
: 'audit-outcome audit-outcome-err';
|
|
return el('span', { class: cls }, denied ? 'denied' : (outcome || '?'));
|
|
}
|
|
|
|
function auditMatches(e, q) {
|
|
if (!q) return true;
|
|
return `${e.agent || ''} ${e.action || ''} ${e.target || ''} ${e.detail || ''}`
|
|
.toLowerCase().includes(q);
|
|
}
|
|
|
|
function renderAudit() {
|
|
if (!auditList) return;
|
|
const q = (auditFilter ? auditFilter.value : '').trim().toLowerCase();
|
|
const rows = auditEntries.filter((e) => auditMatches(e, q));
|
|
|
|
if (auditCount) {
|
|
const shown = auditEntries.length;
|
|
const clamped = auditTotal > shown;
|
|
let txt = clamped
|
|
? `latest ${shown} of ${auditTotal}`
|
|
: `${shown} entr${shown === 1 ? 'y' : 'ies'}`;
|
|
if (q) txt += ` · ${rows.length} match${rows.length === 1 ? '' : 'es'}`;
|
|
auditCount.textContent = txt;
|
|
}
|
|
|
|
auditList.replaceChildren();
|
|
if (rows.length === 0) {
|
|
auditList.append(el('p', { class: 'meta' },
|
|
q ? '(no matching entries)' : '(no privileged actions recorded yet)'));
|
|
return;
|
|
}
|
|
|
|
const table = el('table', { class: 'audit-table' });
|
|
table.append(el('thead', {},
|
|
el('tr', {},
|
|
el('th', { class: 'audit-when-th' }, 'when'),
|
|
el('th', {}, 'agent'),
|
|
el('th', {}, 'action'),
|
|
el('th', {}, 'target'),
|
|
el('th', { class: 'audit-outcome-th' }, 'outcome'),
|
|
el('th', {}, 'detail'),
|
|
)));
|
|
const tbody = el('tbody', {});
|
|
for (const e of rows) {
|
|
tbody.append(el('tr', {},
|
|
el('td', {
|
|
class: 'audit-when meta',
|
|
title: e.ts_unix ? new Date(e.ts_unix).toISOString() : '',
|
|
}, auditFmtWhen(e.ts_unix)),
|
|
el('td', { class: 'audit-agent' }, e.agent || ''),
|
|
el('td', { class: 'audit-action' }, e.action || ''),
|
|
el('td', { class: 'audit-target' }, e.target || ''),
|
|
el('td', { class: 'audit-outcome-td' }, auditOutcomeBadge(e.outcome, e.detail)),
|
|
el('td', { class: 'audit-detail meta' }, e.detail || ''),
|
|
));
|
|
}
|
|
table.append(tbody);
|
|
const wrap = el('div', { class: 'audit-table-wrap' });
|
|
wrap.append(table);
|
|
auditList.append(wrap);
|
|
}
|
|
|
|
async function fetchAudit() {
|
|
if (!auditList || auditFetching) return;
|
|
auditFetching = true;
|
|
try {
|
|
const resp = await fetch('/api/audit-log');
|
|
if (!resp.ok) throw new Error('http ' + resp.status);
|
|
const data = await resp.json();
|
|
auditEntries = Array.isArray(data.entries) ? data.entries : [];
|
|
auditTotal = typeof data.total === 'number' ? data.total : auditEntries.length;
|
|
renderAudit();
|
|
} catch (err) {
|
|
auditList.replaceChildren();
|
|
auditList.append(el('p', { class: 'meta' }, 'fetch failed: ' + err));
|
|
} finally {
|
|
auditFetching = false;
|
|
}
|
|
}
|
|
|
|
if (auditRefresh) auditRefresh.addEventListener('click', fetchAudit);
|
|
if (auditFilter) auditFilter.addEventListener('input', renderAudit);
|
|
|
|
// Live-append: an `audit_entry_added` event on /dashboard/stream carries a
|
|
// new row flattened at the top level ({ kind, seq, id, ts_unix, agent,
|
|
// action, target, outcome, detail }). Prepend it (newest-first), de-duped
|
|
// by id against whatever the cold fetch already returned, and bump the
|
|
// total so the "latest N of M" header stays right. Re-render only while
|
|
// the AUDIT tab is in view; otherwise the next tab-show fetch is
|
|
// authoritative anyway. Wired into the shared stream onmessage above.
|
|
function onAuditEntryAdded(ev) {
|
|
if (auditEntries.some((e) => e.id === ev.id)) return;
|
|
auditEntries.unshift({
|
|
id: ev.id, ts_unix: ev.ts_unix, agent: ev.agent, action: ev.action,
|
|
target: ev.target, outcome: ev.outcome, detail: ev.detail,
|
|
});
|
|
auditTotal += 1;
|
|
if (logTabs.active() === 'audit') renderAudit();
|
|
}
|
|
|
|
// ─── init ─────────────────────────────────────────────────────────────
|
|
|
|
// Wire the shared tab strip now that fetchSystem + the element refs it
|
|
// needs are defined. Its initial show() paints the active pane and, if
|
|
// the deep-linked tab is SYSTEM/AUDIT, kicks off the lazy fetch via onShow.
|
|
// Default: AGENT (build logs moved to /builds.html).
|
|
logTabs = createTabStrip(document.getElementById('logs-tabbar'), {
|
|
defaultId: 'agent',
|
|
onShow: (id) => {
|
|
if (id === 'system') fetchSystem();
|
|
else if (id === 'audit') fetchAudit();
|
|
},
|
|
});
|
|
loadAgentList();
|
|
|
|
// Subscribe to the dashboard SSE stream for audit live-appends.
|
|
{
|
|
const es = openStream('/api/dashboard/stream');
|
|
if (es) {
|
|
es.onmessage = (e) => {
|
|
let ev;
|
|
try { ev = JSON.parse(e.data); } catch { return; }
|
|
if (ev.kind === 'audit_entry_added') onAuditEntryAdded(ev);
|
|
};
|
|
}
|
|
}
|
|
|
|
// Tick the last-fetched timestamps every 30s so "fetched 1m ago" stays
|
|
// accurate without a manual refresh.
|
|
setInterval(() => {
|
|
if (agentLastFetch && agentFetchTs && !agentFetchTs.hidden) {
|
|
agentFetchTs.textContent = fmtFetchTs(agentLastFetch);
|
|
}
|
|
if (systemLastFetch && systemFetchTs && !systemFetchTs.hidden) {
|
|
systemFetchTs.textContent = fmtFetchTs(systemLastFetch);
|
|
}
|
|
// Keep the audit "ago" column honest while that tab is in view.
|
|
if (auditEntries.length && logTabs.active() === 'audit') renderAudit();
|
|
}, 30_000);
|
|
|
|
})();
|