Watch
0
0
Fork
You've already forked hyperhive
0

frontend: one time wording for the swarm UI and the dashboard, and no HTML strings in the dashboard's busy buttons

fmtAgo, fmtUntil and durationLabel move to @hive/shared/time.js. The swarm UI's util.ts is deleted and its importers (RelativeTime, ReviewRuns, BuildsPage) read the shared module directly. The dashboard's own copies are gone: its fmtAgeSecs (a third phrasing, used for two status lines) becomes the shared fmtAgo, and the dashboard util.js lost fmtAgo, fmtElapsed, epochSec and truncate, which nothing called. asyncBtn and the bulk action buttons mark themselves busy with markBusy: a spinner node before the label and aria-busy, in place of replacing the button's innerHTML with a string (and the label, so the button changed width and lost its name). The el() helper loses its html attribute.
This commit is contained in:
iris 2026-11-19 19:21:15 +01:00
commit 3be4ec069c
13 changed files with 84 additions and 96 deletions

View file

@ -223,9 +223,8 @@ integer (rolling-deploy skew, persisted blobs).
**Input-direction** fields agents compute as epoch (`remind`'s
`at_unix_timestamp`) stay integers. The
`*_unix` field *names* stay for now — renaming is the wire-types
refactor's concern. The dashboard frontend parses via
`util.js::epochSec` wherever it needs arithmetic and feeds the string
straight to `new Date(s)` for display.
refactor's concern. The dashboard frontend feeds the string straight
to `new Date(s)` for display and uses `Date.parse` for arithmetic.
### HTTP error bodies

View file

@ -4,8 +4,10 @@
// job-queue-rollup ops. See docs/4-implementation/web-ui/dashboard.md::Container row for the
// rendering contract.
import { $, buttonClass, form, fmtAgeSecs } from "./common.js";
import { fmtAgo } from "@hive/shared/time.js";
import { $, buttonClass, form } from "./common.js";
import { el } from "@hive/shared/dom.js";
import { markBusy } from "@hive/shared/forms.js";
import { themedConfirm, themedToast } from "@hive/shared/modal.js";
import { h, render } from "preact";
import { JobqRollup } from "@hive/shared/jobq-rollup.js";
@ -396,7 +398,7 @@ function buildContainerLi(c, opts) {
const nowUnix = Math.floor(Date.now() / 1000);
const ageStr =
ds.status_set_at != null
? ` (set ${fmtAgeSecs(nowUnix - ds.status_set_at)} ago)`
? ` (set ${fmtAgo(nowUnix - ds.status_set_at)})`
: "";
// Stamp data-set-at so the 30s ticker below keeps the age
// label current even when the row is reused from the cache.
@ -837,8 +839,7 @@ function addBulkButton(parent, tone, label, enabled, selected, opts) {
graceful = !!r.graceful;
}
btn.disabled = true;
const original = btn.innerHTML;
btn.innerHTML = '<span class="spinner">◐</span> ' + label;
const unbusy = markBusy(btn);
const failures = [];
// Sequential POSTs to keep server-side serialisation predictable
// (rebuild_queue dedups but other endpoints don't); the loop is
@ -875,7 +876,7 @@ function addBulkButton(parent, tone, label, enabled, selected, opts) {
}
}
btn.disabled = false;
btn.innerHTML = original;
unbusy();
if (failures.length) {
themedToast(
`${label} completed with ${failures.length} failure${failures.length === 1 ? "" : "s"}:\n\n` +
@ -896,13 +897,13 @@ function addBulkButton(parent, tone, label, enabled, selected, opts) {
// 30s ticker for agent status-age chips. Renderers stamp `data-set-at`
// (unix seconds) on the `.status-age` span. Keyed container rows persist
// across re-renders, so without this ticker the "(set N ago)" label would
// become stale as time passes. 30s granularity matches fmtAgeSecs precision
// become stale as time passes. 30s granularity matches fmtAgo precision
// (sub-minute values round to seconds, coarser above that).
setInterval(() => {
const now = Math.floor(Date.now() / 1000);
document.querySelectorAll(".status-age[data-set-at]").forEach((node) => {
const setAt = Number(node.dataset.setAt);
if (!Number.isFinite(setAt) || setAt === 0) return;
node.textContent = ` (set ${fmtAgeSecs(now - setAt)} ago)`;
node.textContent = ` (set ${fmtAgo(now - setAt)})`;
});
}, 30_000);

View file

@ -7,15 +7,6 @@ import "@hive/shared/hive-warn.js"; // registers <hive-warn> — side-effect imp
// ─── helpers ────────────────────────────────────────────────────────────
export const $ = (id) => document.getElementById(id);
export const fmtAgeSecs = (s) =>
s < 60
? `${s}s`
: s < 3600
? `${Math.floor(s / 60)}m`
: s < 86400
? `${Math.floor(s / 3600)}h`
: `${Math.floor(s / 86400)}d`;
export const esc = (s) =>
String(s).replace(
/[&<>"]/g,
@ -62,11 +53,8 @@ export const form = (
// `asyncBtn` live in `@hive/shared/forms.js`, not here — both the
// dashboard and the per-agent UI import them directly from there.
// `truncate`, `fmtAgo`, `fmtElapsed` + the `paintAtomic`
// render helper live in the dashboard-internal `./util.js`, not here —
// their phrasing ("X running", "X ago") is dashboard-specific, so they
// stay out of the cross-page `common.js` but are shared across the
// dashboard's own tab modules.
// The `paintAtomic` render helper lives in the dashboard-internal `./util.js`;
// relative times ("5m ago") come from `@hive/shared/time.js`.
// ─── shared-worker SSE pipe ─────────────────────────────────────────────
// Returns an EventSource-shaped facade backed by a SharedWorker that

View file

@ -1,14 +1,7 @@
// Shared dashboard render + format helpers.
//
// Small pure utilities used across most dashboard tabs (the container
// tree, the rebuild queue):
// an atomic-swap render helper and a handful of relative-time / duration
// formatters. They live here — a dashboard-internal module — rather than
// in the cross-page `common.js`, because they're specific to the
// dashboard's render style and not needed by the stand-alone pages.
//
// All pure: no DOM/module state captured, so any tab module can import
// them freely without ordering concerns.
// Dashboard render helper: `paintAtomic`, the atomic-swap render the tab modules
// use. Pure: no DOM or module state captured, so any tab module can import it
// without ordering concerns. Relative times and durations are
// `@hive/shared/time.js`.
// Atomic-swap render: build into an off-DOM DocumentFragment, then commit
// with a single `replaceChildren`. Avoids an intermediate empty-state
@ -18,39 +11,3 @@ export function paintAtomic(liveRoot, build) {
build(buf);
liveRoot.replaceChildren(buf);
}
// Epoch seconds from an API timestamp. The hive-c0re dashboard API
// ships timestamps as RFC 3339 strings; a few feeds (rebuild queue and
// turn stats) still carry unix-second numbers, so
// numbers pass through unchanged.
export function epochSec(ts) {
return typeof ts === "number" ? ts : Math.floor(Date.parse(ts) / 1000);
}
// Relative age of a timestamp (RFC 3339 string or unix seconds),
// coarsened to one unit ("5m ago").
export function fmtAgo(ts) {
const ageSec = Math.max(0, Math.floor(Date.now() / 1000 - epochSec(ts)));
if (ageSec < 60) return ageSec + "s ago";
if (ageSec < 3600) return Math.floor(ageSec / 60) + "m ago";
if (ageSec < 86400) return Math.floor(ageSec / 3600) + "h ago";
return Math.floor(ageSec / 86400) + "d ago";
}
// Truncate a string to `n` chars, appending an ellipsis when clipped.
export function truncate(s, n) {
return s.length <= n ? s : s.slice(0, n - 1) + "…";
}
// Running-duration label for in-flight items ("3m 12s running").
export function fmtElapsed(secs) {
if (secs < 60) return secs + "s running";
if (secs < 3600)
return Math.floor(secs / 60) + "m " + (secs % 60) + "s running";
return (
Math.floor(secs / 3600) +
"h " +
Math.floor((secs % 3600) / 60) +
"m running"
);
}

View file

@ -25,6 +25,7 @@
"./forms.js": "./src/forms.js",
"./prefs.js": "./src/prefs.ts",
"./use-dismiss.js": "./src/use-dismiss.ts",
"./time.js": "./src/time.ts",
"./dom.js": "./src/dom.js",
"./modal.js": "./src/modal.js",
"./shadow-css.js": "./src/shadow-css.js",

View file

@ -1,11 +1,9 @@
// Tiny DOM-builder helper shared by the dashboard and the per-agent UI —
// both packages built their own copy independently; this is the merged
// canonical version (dashboard's, which had the extra `data-` branch;
// functionally identical to the `class`/`html` handling either package
// used).
// Tiny DOM-builder helper shared by the dashboard and the per-agent UI. There
// is no `html` attribute on purpose: content is built from nodes and text, so a
// string from the API can never become markup.
//
// `el(tag, attrs, ...children)` creates an element, applying `attrs` as
// either the `class`/`html` special cases or plain attributes, and
// either the `class` special case or plain attributes, and
// appending `children` (strings become text nodes, `null`/`undefined`
// entries are skipped so callers can inline conditional children).
// `tag` can be any custom element's tag name too (e.g. `el('hive-btn',
@ -15,7 +13,6 @@ export const el = (tag, attrs = {}, ...children) => {
const e = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (k === "class") e.className = v;
else if (k === "html") e.innerHTML = v;
else e.setAttribute(k, v);
}
for (const c of children) {

View file

@ -8,11 +8,10 @@
// `asyncBtn(btn, fn)` — the single reusable component:
// 1. Guards double-click: returns immediately if `btn` is already
// disabled (prevents a second identical request from firing).
// 2. Saves `btn.innerHTML` and replaces it with a spinner during the
// async operation.
// 3. Re-enables the button and restores the original content when `fn`
// resolves or rejects (via `finally`), so callers don't need
// save/restore boilerplate.
// 2. Puts a spinner before the label (`markBusy`) during the async
// operation; the label stays, so the button keeps its width.
// 3. Re-enables the button and takes the spinner away when `fn`
// resolves or rejects (via `finally`).
//
// Usage:
// btn.addEventListener('click', () => asyncBtn(btn, async () => {
@ -30,15 +29,32 @@
// own catch — an unhandled rejection from `fn` will propagate normally.
export function asyncBtn(btn, fn) {
if (btn.disabled) return; // double-click guard
const orig = btn.innerHTML;
btn.disabled = true;
btn.innerHTML = '<span class="spinner">◐</span>';
const done = markBusy(btn);
return fn().finally(() => {
btn.disabled = false;
btn.innerHTML = orig;
done();
});
}
// A spinner before the button's label, and `aria-busy`; the label stays, so the
// button does not change width and a screen reader still has its name. Built
// from nodes, not an HTML string. Returns the function that takes it away.
export function markBusy(btn) {
const spinner = document.createElement("span");
spinner.className = "spinner";
spinner.setAttribute("aria-hidden", "true");
spinner.textContent = "◐";
const gap = document.createTextNode(" ");
btn.prepend(spinner, gap);
btn.setAttribute("aria-busy", "true");
return () => {
spinner.remove();
gap.remove();
btn.removeAttribute("aria-busy");
};
}
// Page-level submit interceptor for `data-async` forms — the pattern every
// dashboard/agent action button uses (spawn, cancel, purge,
// rebuild, …). Without this a `data-async` form POSTs natively and the

View file

@ -1,13 +1,10 @@
// Small pure render helpers shared across swarm-ui pages. Not folded
// into `@hive/shared` — swarm-ui's formatting choices aren't a
// cross-package contract, and there's nothing here worth sharing.
// Relative time and duration wording, for the swarm UI and the hive dashboard:
// one phrasing ("5m ago", "in 5m", "3m 12s") rather than a copy per package.
// Relative age, coarsened to one unit ("5m ago"). Built on the native
// `Intl.RelativeTimeFormat` (no dependency needed — mara asked whether
// a lightweight package was warranted; the runtime already ships this)
// with `style: 'narrow'`, which produces the same "5s/5m/5h/5d ago"
// shape the dashboard package's hand-rolled equivalent does, verified
// against a real `Intl` call rather than assumed from the spec.
// with `style: 'narrow'`, which produces the "5s/5m/5h/5d ago" shape.
const RTF = new Intl.RelativeTimeFormat("en", {
numeric: "always",
style: "narrow",

View file

@ -25,7 +25,7 @@ import {
import { fetchJson, usePolled } from "../../ui/polled/usePolled.js";
import { StaleNote } from "../../ui/polled/StaleNote.js";
import { RelativeTime } from "../../ui/relative-time/RelativeTime.js";
import { durationLabel } from "../../util.js";
import { durationLabel } from "@hive/shared/time.js";
import {
OUTCOME_LABEL,
OUTCOME_TONE,

View file

@ -23,7 +23,7 @@ import { fetchJson, usePolled } from "../../ui/polled/usePolled.js";
import { StaleNote } from "../../ui/polled/StaleNote.js";
import { RelativeTime } from "../../ui/relative-time/RelativeTime.js";
import { TryOutResult } from "../review-common/TryOutResult.js";
import { durationLabel } from "../../util.js";
import { durationLabel } from "@hive/shared/time.js";
import {
OUTCOME_LABEL,
OUTCOME_TONE,

View file

@ -9,7 +9,7 @@
// package's matrix-rain effect — and resyncs immediately on becoming
// visible again instead of waiting out the rest of a stale interval.
import { useEffect, useState } from "preact/hooks";
import { fmtAgo, fmtUntil } from "../../util.js";
import { fmtAgo, fmtUntil } from "@hive/shared/time.js";
// Cheap at the handful of rows/chips this renders for today, and coarse
// enough to be correct without visibly ticking every frame — the same

View file

@ -2,7 +2,7 @@
// paths one terminal is reached at.
import assert from "node:assert/strict";
import { test } from "node:test";
import { durationLabel } from "../src/util.ts";
import { durationLabel } from "../../shared/src/time.ts";
import { termPaths } from "../src/agent/terminal/term-paths.ts";
test("durationLabel names seconds, minutes and hours", () => {

View file

@ -0,0 +1,32 @@
// The relative-time wording both UIs share: one unit, clamped at zero, and the
// forward form. Run by `npm test`.
import assert from "node:assert/strict";
import { test } from "node:test";
import { fmtAgo, fmtUntil } from "../../shared/src/time.ts";
test("an age reads in its largest whole unit", () => {
assert.equal(fmtAgo(5), "5s ago");
assert.equal(fmtAgo(59), "59s ago");
assert.equal(fmtAgo(60), "1m ago");
assert.equal(fmtAgo(3599), "59m ago");
assert.equal(fmtAgo(3600), "1h ago");
assert.equal(fmtAgo(86399), "23h ago");
assert.equal(fmtAgo(86400), "1d ago");
assert.equal(fmtAgo(3 * 86400 + 5), "3d ago");
});
test("a clock a little ahead never reads as a negative age", () => {
assert.equal(fmtAgo(-3), "0s ago");
});
test("a fractional age is floored", () => {
assert.equal(fmtAgo(61.9), "1m ago");
});
test("an instant ahead reads in the same units, forward", () => {
assert.equal(fmtUntil(5), "in 5s");
assert.equal(fmtUntil(300), "in 5m");
assert.equal(fmtUntil(7200), "in 2h");
assert.equal(fmtUntil(2 * 86400), "in 2d");
assert.equal(fmtUntil(-4), "in 0s");
});