Adds @hive/shared/tabs.js — createTabStrip(tabbar, {defaultId, onShow}):
a hash-routed tab strip that resolves controls by `[data-tab="<id>"]`
inside the passed container and panels by `[data-tab-pane="<id>"]`,
toggling `.hive-tab--active` + aria-selected + the panel's `hidden`, and
firing onShow(id) for per-tab side-effects. Always hash-routed (deep-
linkable + back/forward), no element-resolver callbacks (convention over
config), per the #1464 design review.
Wires it up: @hive/shared exports `./tabs.js` + `./tabs.css`, and
common.css @imports tabs.css (component structure, not a swap target, so
inlining is fine — unlike theme.css).
Migrates the logs sub-tabs as the first consumer: markup uses
`.hive-tab`/`data-tab`/`data-tab-pane`, logs.css drops the duplicated
base styles (keeps only its `flex:1` layout delta), and logs.js swaps its
activeTab/showTab/hashchange for createTabStrip (onShow lazy-loads the
SYSTEM tab). Behaviour-preserving. aria-selected is now standardised.
394 lines
17 KiB
JavaScript
394 lines
17 KiB
JavaScript
// /logs.html entry point: log viewer with three sub-tabs (BUILD, AGENT, SYSTEM).
|
|
// BUILD — all-agents build log history, backed by GET /api/build-logs
|
|
// AGENT — per-container journald viewer, backed by GET /api/journal/{name}
|
|
// SYSTEM — host service logs, backed by GET /api/journal-host
|
|
//
|
|
// Tab routing via URL hash (#build, #agent, #system). Default: #build.
|
|
//
|
|
// Live improvements:
|
|
// - Live build output auto-scrolls to the bottom (sticky-bottom) unless
|
|
// the operator has manually scrolled up.
|
|
// - Running builds show an elapsed-time counter in the row header that
|
|
// ticks every second.
|
|
// - The build list auto-refreshes (debounced 2s) when rebuild_queue_changed
|
|
// fires from the dashboard SSE stream, so new log entries appear without
|
|
// a manual page refresh.
|
|
//
|
|
// 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 { 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 ──────────────────────────────────────────────────────────
|
|
|
|
// started_at / finished_at are unix seconds (i64), not milliseconds.
|
|
function fmtTs(unixSecs) {
|
|
if (!unixSecs) return '';
|
|
const age = Math.floor(Date.now() / 1000) - unixSecs;
|
|
return fmtAgeSecs(Math.max(0, age)) + ' ago';
|
|
}
|
|
|
|
function fmtDuration(secs) {
|
|
if (secs < 60) return secs + 's';
|
|
const m = Math.floor(secs / 60), s = secs % 60;
|
|
return m + 'm ' + s + 's';
|
|
}
|
|
|
|
// ─── BUILD tab ────────────────────────────────────────────────────────
|
|
|
|
const buildList = $('build-list');
|
|
const buildRefresh = $('build-refresh');
|
|
|
|
async function fetchBuild() {
|
|
if (!buildList) return;
|
|
buildList.replaceChildren();
|
|
buildList.append(el('p', { class: 'meta' }, 'loading…'));
|
|
try {
|
|
const resp = await fetch('/api/build-logs?limit=30');
|
|
if (!resp.ok) throw new Error('http ' + resp.status);
|
|
const rows = await resp.json();
|
|
buildList.replaceChildren();
|
|
if (!rows || rows.length === 0) {
|
|
buildList.append(el('p', { class: 'meta' }, '(no build logs yet)'));
|
|
return;
|
|
}
|
|
const ul = el('ul', { class: 'build-logs-list' });
|
|
for (const h of rows) {
|
|
const li = el('li', { class: 'build-logs-item', 'data-log-id': String(h.id) });
|
|
// status is null while running, 'ok'/'fail' when finished.
|
|
const live = !h.status;
|
|
const ok = h.status === 'ok';
|
|
const statusClass = live ? 'badge badge-running' : ok ? 'badge badge-ok' : 'badge badge-fail';
|
|
const statusLabel = live ? 'live' : ok ? 'ok' : 'fail';
|
|
const age = h.finished_at ? fmtTs(h.finished_at) : (live ? '' : fmtTs(h.started_at));
|
|
const runtime = h.runtime_secs != null
|
|
? el('span', { class: 'build-logs-runtime meta' }, fmtDuration(Math.max(0, h.runtime_secs)))
|
|
: live
|
|
? el('span', { class: 'build-logs-runtime meta build-logs-live-dur' }, '…')
|
|
: el('span', { class: 'build-logs-runtime meta' }, '');
|
|
|
|
// For live builds, start an elapsed-time ticker immediately in the
|
|
// row header so the operator can see how long the build has been
|
|
// running without opening the log detail.
|
|
let durTimer = null;
|
|
if (live && h.started_at) {
|
|
const updateDur = () => {
|
|
const elapsed = Math.floor(Date.now() / 1000) - h.started_at;
|
|
runtime.textContent = fmtDuration(Math.max(0, elapsed));
|
|
};
|
|
updateDur(); // show initial value right away
|
|
durTimer = setInterval(updateDur, 1000);
|
|
}
|
|
|
|
const rowBtn = el('button', {
|
|
type: 'button',
|
|
class: 'build-logs-row-btn',
|
|
'aria-expanded': 'false',
|
|
},
|
|
el('span', { class: statusClass }, statusLabel),
|
|
el('span', { class: 'build-logs-agent' }, h.agent),
|
|
runtime,
|
|
el('span', { class: 'build-logs-kind' }, h.kind),
|
|
el('span', { class: 'build-logs-age meta' }, age),
|
|
el('span', { class: 'build-logs-cmdline meta' }, h.cmdline),
|
|
);
|
|
const detail = el('div', { class: 'build-logs-detail' });
|
|
detail.hidden = true;
|
|
|
|
let streamEs = null;
|
|
rowBtn.addEventListener('click', async () => {
|
|
const expanded = rowBtn.getAttribute('aria-expanded') === 'true';
|
|
rowBtn.setAttribute('aria-expanded', String(!expanded));
|
|
detail.hidden = expanded;
|
|
if (expanded) {
|
|
if (streamEs) { streamEs.close(); streamEs = null; }
|
|
return;
|
|
}
|
|
// already loaded?
|
|
if (detail.dataset.loaded) return;
|
|
detail.replaceChildren();
|
|
detail.append(
|
|
el('a', {
|
|
href: '/api/build-logs/id/' + h.id + '/raw',
|
|
download: 'build-log-' + h.id + '.txt',
|
|
class: 'build-logs-dl',
|
|
}, '↓ download raw'),
|
|
);
|
|
if (live) {
|
|
const pre = el('pre', { class: 'build-logs-output build-logs-live' }, '');
|
|
const badge = el('span', { class: 'build-logs-live-badge badge badge-running' }, 'live');
|
|
detail.append(badge, pre);
|
|
|
|
// Sticky-bottom: auto-scroll to the bottom as new lines arrive
|
|
// unless the operator has manually scrolled up. Track intent via
|
|
// the scroll event rather than recomputing on each append.
|
|
let atBottom = true;
|
|
pre.addEventListener('scroll', () => {
|
|
atBottom = pre.scrollHeight - pre.scrollTop - pre.clientHeight < 40;
|
|
});
|
|
|
|
streamEs = new EventSource('/api/build-logs/id/' + h.id + '/stream');
|
|
let stdoutLen = 0, stderrLen = 0;
|
|
streamEs.onmessage = (e) => {
|
|
let frame;
|
|
try { frame = JSON.parse(e.data); } catch { return; }
|
|
if (frame.stdout_append) {
|
|
pre.textContent += frame.stdout_append;
|
|
if (atBottom) pre.scrollTop = pre.scrollHeight;
|
|
stdoutLen += frame.stdout_append.length;
|
|
}
|
|
if (frame.stderr_append) {
|
|
if (stderrLen === 0) pre.textContent += '\n--- stderr ---\n';
|
|
pre.textContent += frame.stderr_append;
|
|
if (atBottom) pre.scrollTop = pre.scrollHeight;
|
|
stderrLen += frame.stderr_append.length;
|
|
}
|
|
if (frame.done) {
|
|
// Stop the elapsed-time ticker and show the final duration.
|
|
if (durTimer) { clearInterval(durTimer); durTimer = null; }
|
|
if (h.started_at) {
|
|
const elapsed = Math.floor(Date.now() / 1000) - h.started_at;
|
|
runtime.textContent = fmtDuration(Math.max(0, elapsed));
|
|
}
|
|
badge.className = frame.status === 'ok' ? 'badge badge-ok' : 'badge badge-fail';
|
|
badge.textContent = frame.status || 'done';
|
|
streamEs.close(); streamEs = null;
|
|
detail.dataset.loaded = '1';
|
|
}
|
|
};
|
|
streamEs.onerror = () => {
|
|
if (streamEs && streamEs.readyState === EventSource.CONNECTING) {
|
|
pre.textContent = ''; stdoutLen = 0; stderrLen = 0;
|
|
} else {
|
|
if (durTimer) { clearInterval(durTimer); durTimer = null; }
|
|
badge.textContent = 'stream error';
|
|
badge.className = 'badge badge-fail';
|
|
if (streamEs) { streamEs.close(); streamEs = null; }
|
|
}
|
|
};
|
|
} else {
|
|
const pre = el('pre', { class: 'build-logs-output' }, 'fetching…');
|
|
detail.append(pre);
|
|
try {
|
|
const r2 = await fetch('/api/build-logs/id/' + h.id);
|
|
if (!r2.ok) {
|
|
pre.textContent = 'error ' + r2.status;
|
|
} else {
|
|
const full = await r2.json();
|
|
const out = [full.stdout, full.stderr].filter(Boolean).join('\n--- stderr ---\n');
|
|
pre.textContent = out || '(empty)';
|
|
}
|
|
detail.dataset.loaded = '1';
|
|
} catch (err) {
|
|
pre.textContent = 'fetch failed: ' + err;
|
|
}
|
|
}
|
|
});
|
|
li.append(rowBtn, detail);
|
|
ul.append(li);
|
|
}
|
|
buildList.append(ul);
|
|
// Deep-link: if the URL contains ?id=N, auto-expand that log entry
|
|
// so a `logs →` link from the rebuild-queue panel drops the operator
|
|
// straight into the live output without extra clicks.
|
|
const deepId = new URLSearchParams(location.search).get('id');
|
|
if (deepId) {
|
|
const target = ul.querySelector('[data-log-id="' + deepId + '"]');
|
|
if (target) {
|
|
const btn = target.querySelector('.build-logs-row-btn');
|
|
if (btn) {
|
|
btn.click();
|
|
target.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
|
}
|
|
}
|
|
}
|
|
} catch (err) {
|
|
buildList.replaceChildren();
|
|
buildList.append(el('p', { class: 'meta' }, 'fetch failed: ' + err));
|
|
}
|
|
}
|
|
|
|
if (buildRefresh) buildRefresh.addEventListener('click', fetchBuild);
|
|
|
|
// Auto-refresh the build list when the dashboard SSE stream signals that
|
|
// the rebuild queue changed — this surfaces new log entries and status
|
|
// changes without needing a manual page refresh. Debounce 2s so a burst
|
|
// of rapid queue mutations only triggers one fetch.
|
|
{
|
|
let buildRefreshTimer = null;
|
|
const debouncedRefreshBuild = () => {
|
|
if (logTabs.active() !== 'build') return;
|
|
if (buildRefreshTimer) clearTimeout(buildRefreshTimer);
|
|
buildRefreshTimer = setTimeout(fetchBuild, 2000);
|
|
};
|
|
const es = openStream('/dashboard/stream');
|
|
if (es) {
|
|
es.onmessage = (e) => {
|
|
let ev;
|
|
try { ev = JSON.parse(e.data); } catch { return; }
|
|
if (ev.kind === 'rebuild_queue_changed') debouncedRefreshBuild();
|
|
};
|
|
}
|
|
}
|
|
|
|
// ─── 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');
|
|
}
|
|
|
|
// Populate agent selector from /api/state, 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));
|
|
}
|
|
// 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;
|
|
}
|
|
fetchAgent();
|
|
}
|
|
}
|
|
} catch { /**/ }
|
|
}
|
|
|
|
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 unit = 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);
|
|
|
|
// ─── 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, kicks off the lazy fetch via onShow.
|
|
logTabs = createTabStrip(document.getElementById('logs-tabbar'), {
|
|
defaultId: 'build',
|
|
onShow: (id) => { if (id === 'system') fetchSystem(); },
|
|
});
|
|
loadAgentList();
|
|
fetchBuild();
|
|
|
|
// 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);
|
|
}
|
|
}, 30_000);
|
|
|
|
})();
|