Watch
0
0
Fork
You've already forked hyperhive
0

remove the agent's live terminal page and the endpoints only it used

This commit is contained in:
iris 2026-11-16 04:31:36 +01:00 • committed by mara
commit 6289b8d64b
28 changed files with 127 additions and 4053 deletions

View file

@ -1,18 +1,10 @@
// esbuild build for @hive/agent. Output layout (`dist/`):
//
// dist/index.html served at GET / (the Preact rewrite —
// the old vanilla-JS app.js is deleted)
// dist/stats.html served at GET /stats
// dist/screen.html served at GET /screen
// dist/static/stats.js served at /static/stats.js (pulls in
// chart.js/auto)
// dist/static/stats.js.map source map sibling
// dist/static/main.js served at /static/main.js (the Preact
// bundle — see main.tsx)
// dist/static/main.js.map source map sibling
// dist/static/main.css served at /static/main.css (bundled
// component CSS — see main.tsx's build
// step below)
// dist/static/agent.css served at /static/agent.css (@import
// resolved from @hive/shared)
//
@ -50,31 +42,10 @@ await build({
loader: { ".css": "text" },
});
// The main agent page (the Preact rewrite — the old vanilla-JS app.js,
// which used to share this build step, is deleted). A separate bundle
// from stats.js above rather than folded in: different loader needs
// (`.css: 'css'`, real stylesheets a component imports, vs. the raw-
// text shadow-DOM CSS `stats.js` still needs for `@hive/shared/
// modal.js`) and JSX transpilation, same split swarm-ui's own build
// already makes.
await build({
entryPoints: [src("main.tsx")],
outfile: staticDir("main.js"),
bundle: true,
format: "esm",
platform: "browser",
target: ["es2022"],
sourcemap: true,
logLevel: "info",
jsx: "automatic",
jsxImportSource: "preact",
loader: { ".css": "css" },
});
// Bundle the CSS. `colors.css` re-exports the standalone base16 palette
// (the theme swap contract — its own output file so a swap replaces only
// it, no bundle rebuild); `theme.css` is the semantic derivation layer;
// `agent.css`'s @import lines pull in shared base.css + terminal.css from
// `agent.css`'s @import lines pull in the shared base.css, chrome.css and pill.css from
// the @hive/shared workspace dep.
for (const entry of ["colors.css", "theme.css", "agent.css"]) {
await build({
@ -86,7 +57,7 @@ for (const entry of ["colors.css", "theme.css", "agent.css"]) {
});
}
for (const html of ["index.html", "stats.html", "screen.html"]) {
for (const html of ["stats.html", "screen.html"]) {
copyFileSync(src(html), dist(html));
}

View file

@ -1,339 +0,0 @@
// <Root> — root of the Preact rewrite. Wires `Header` + `StatusChips`
// to the real `/api/state` snapshot via `useAgentState`. Covers
// everything `app.js` did. An agent without credentials shows the
// `needs_login_idle` badge; it logs in from the swarm UI, not here.
import { useEffect, useRef, useState } from "preact/hooks";
import type { BadgeTone } from "@hive/shared/badge.js";
import { SettingsMenu } from "@hive/shared/settings-menu.js";
import { useApplyThemeOverride } from "@hive/shared/theme-apply.js";
import { useApplyMotionOverride } from "@hive/shared/motion-apply.js";
import { Header } from "./components/Header.js";
import { MetaNav } from "./components/MetaNav.js";
import { AgentUserMenu } from "./components/AgentUserMenu.js";
import { ExpandDetailsSetting } from "@hive/shared/expand-details-setting.js";
import { HideDebugSetting } from "@hive/shared/hide-debug-setting.js";
import { StatusChips } from "./components/StatusChips.js";
import { LiveStream, type LiveStreamHandle } from "./components/LiveStream.js";
import { HeaderPill } from "./components/HeaderPill.js";
import { SidePanel } from "./components/SidePanel.js";
import { InboxPanel } from "./components/InboxPanel.js";
import { TodosPanel } from "./components/TodosPanel.js";
import { useAgentState } from "./hooks/useAgentState.js";
import { useTodos } from "./hooks/useTodos.js";
import { fmtAge, fmtTokens } from "./lib/format.js";
import { resolveDashboardBase } from "./lib/dashboardBase.js";
import { submitPauseResume } from "./lib/pauseAction.js";
import {
postCancelTurn,
postLogout,
postNewSession,
} from "./lib/termActions.js";
import type { TokenUsage } from "./types.js";
type OpenPanel = "inbox" | "todos" | null;
// Storage keys this page owns for `@hive/shared`'s settings mechanism —
// kept here, not derived, so `useApplyThemeOverride`/`useApplyMotionOverride`
// (mounted once below) and `<SettingsMenu>` (in `pills`, further down)
// always agree on which browser-local key they're reading/writing.
const THEME_KEY = "agent:theme-override";
const MOTION_KEY = "agent:motion-override";
const ALIVE_LABELS: Record<
string,
{ glyph: string; text: string; tone: BadgeTone }
> = {
online: { glyph: "●", text: "alive", tone: "positive" },
rate_limited: { glyph: "⊘", text: "rate limited", tone: "warning" },
needs_login_idle: { glyph: "◌", text: "needs login", tone: "warning" },
};
const STATE_LABELS: Record<
string,
{ glyph: string; text: string; tone: BadgeTone }
> = {
idle: { glyph: "💤", text: "idle", tone: "neutral" },
thinking: { glyph: "🧠", text: "thinking", tone: "accent" },
compacting: { glyph: "📦", text: "compacting", tone: "warning" },
};
const STATE_TOOLTIPS: Record<string, string> = {
offline: "harness unreachable or claude not logged in",
idle: "turn loop running, no claude invocation in flight",
thinking: "claude is executing the current turn",
compacting: "agent-requested /compact running on the persistent session",
};
// `total` here matches app.js's `renderOneUsage` exactly: input + both
// cache buckets, output_tokens deliberately excluded (it's shown in the
// title breakdown, not folded into the headline number).
function tokenTotal(u: TokenUsage | null): number | null {
if (!u) return null;
return (
(u.input_tokens ?? 0) +
(u.cache_read_input_tokens ?? 0) +
(u.cache_creation_input_tokens ?? 0)
);
}
// `?hide=header` — an embedding companion window (e.g. a native desktop
// shell) supplies its own header chrome around this page, so it asks for
// just the terminal feed. Read once per load (the value can't change without
// a navigation); comma-separated so more parts can be hidden in one param.
const hideParam = new URLSearchParams(window.location.search).get("hide");
const HIDDEN = new Set(hideParam ? hideParam.split(",").filter(Boolean) : []);
export function Root() {
useApplyThemeOverride(THEME_KEY);
useApplyMotionOverride(MOTION_KEY);
const { state, refresh } = useAgentState();
const { todos, refresh: refreshTodos } = useTodos();
const [openPanel, setOpenPanel] = useState<OpenPanel>(null);
const liveStreamRef = useRef<LiveStreamHandle>(null);
const hideHeader = HIDDEN.has("header");
// Body classes, not inline styles: agent.css's `--agent-header-h`/
// `--agent-header-real-h` custom properties already drive every
// dependent calc() (overlay offset, terminal scroll padding) — zeroing
// them here collapses all of that in one place instead of touching each rule.
useEffect(() => {
document.body.classList.toggle("agent-hide-header", hideHeader);
}, [hideHeader]);
// Ticks the status badge's "thinking Xm Ys" age once a second,
// independent of the ~4s `/api/state` poll cadence — without its own
// clock the age text only advances when a poll happens to land, so it
// visibly stair-steps instead of counting up, and freezes outright for
// however long a poll is delayed (e.g. a backgrounded tab).
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const id = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(id);
}, []);
// Browser tab title — ports app.js's setHeader logic verbatim: prefer
// the human display name + hive_name ("iris // pr1ma") so tabs read
// naturally; fall back to the qualified domain label for multi-hive
// disambiguation when hive_name is unset, then to plain label for
// single-hive deploys. Without this every agent's tab reads the
// static index.html <title> forever — can't tell tabs apart with
// several open.
useEffect(() => {
if (!state) return;
const tab =
state.qualified_label && state.qualified_label !== state.label
? state.qualified_label
: state.label;
document.title = state.hive_name
? `${state.label} // ${state.hive_name}`
: `${tab} // hyperhive`;
}, [state?.label, state?.qualified_label, state?.hive_name]);
const pills = (
<>
<HeaderPill
kind="inbox"
icon="📬"
label="inbox"
count={state?.inbox.length ?? 0}
onClick={() => setOpenPanel("inbox")}
/>
<HeaderPill
kind="todos"
icon="📋"
label="todos"
count={todos.length}
onClick={() => setOpenPanel("todos")}
/>
{/* Needs a loaded snapshot for its data (links,
* dashboard_port) — omitted until the first /api/state resolves,
* same as the old page's populateOverflowMenu (now deleted —
* dashboard-link moved here, rebuild removed outright, see
* MetaNav.tsx's file comment). */}
{state ? (
<MetaNav
links={state.links}
dashboardBase={resolveDashboardBase(state.dashboard_port)}
/>
) : null}
<SettingsMenu themeKey={THEME_KEY} motionKey={MOTION_KEY}>
<ExpandDetailsSetting />
<HideDebugSetting />
</SettingsMenu>
{state ? (
<AgentUserMenu
dashboardBase={resolveDashboardBase(state.dashboard_port)}
/>
) : null}
</>
);
// Kept mounted regardless of `openPanel` (open/closed toggles just the
// `open` prop) rather than conditionally rendering the whole
// component — SidePanel's slide/fade CSS transitions only fire on a
// class change after mount, not on an already-open initial render, so
// mount-on-open would skip both the open AND the close animation.
const panelTitle =
openPanel === "inbox"
? `inbox · ${state?.inbox.length ?? 0}`
: openPanel === "todos"
? `todos · ${todos.length}`
: "";
const panel = (
<SidePanel
open={openPanel !== null}
title={panelTitle}
onClose={() => setOpenPanel(null)}
>
{openPanel === "inbox" ? (
<InboxPanel
rows={state?.inbox ?? []}
label={state?.label ?? ""}
dashboardBase={
state ? resolveDashboardBase(state.dashboard_port) : ""
}
onCleared={refresh}
/>
) : openPanel === "todos" ? (
<TodosPanel todos={todos} onCleared={refreshTodos} />
) : null}
</SidePanel>
);
if (!state) {
return (
<>
{hideHeader ? null : (
<Header label="…" pills={pills}>
<StatusChips
statusLabel="… connecting"
statusTone="neutral"
model=""
paused={false}
onTogglePause={() => {}}
thinking={false}
onCancelTurn={() => Promise.resolve()}
onNewSession={() => Promise.resolve()}
onLogout={() => Promise.resolve()}
/>
</Header>
)}
<main className="agent-main">
<LiveStream ref={liveStreamRef} />
</main>
{panel}
</>
);
}
const alive = ALIVE_LABELS[state.status] ?? {
glyph: "○",
text: "offline",
tone: "negative" as BadgeTone,
};
// Mirrors app.js's refreshState: any non-'online' status forces the
// turn-state badge to 'offline' regardless of the server's last-known
// turn_state (login/rate-limit takes visual priority over a stale
// idle/thinking reading from before the harness went offline).
const effectiveTurnState =
state.status === "online" ? state.turn_state : "offline";
const turnDef = STATE_LABELS[effectiveTurnState] ?? {
glyph: "○",
text: "offline",
tone: "negative" as BadgeTone,
};
const stateAge = fmtAge(now - state.turn_state_since * 1000);
// Consolidated status badge (mara: "why do we have separate alive
// badge? ... one badge that shows thinking / idle / paused").
// Not online → the alive-table's own reading (rate-limited/needs-login/
// offline), no age (nothing to age). Online + paused → 'paused'
// overrides the turn-state reading, since a paused agent won't be
// thinking regardless of its last turn_state. Online + running →
// turn-state + age, same as before.
const primaryStatus =
state.status !== "online"
? {
glyph: alive.glyph,
text: alive.text,
tone: alive.tone,
tooltip: undefined as string | undefined,
}
: state.paused
? {
glyph: "⏸",
text: "paused",
tone: "warning" as BadgeTone,
tooltip: undefined,
}
: {
glyph: turnDef.glyph,
text: `${turnDef.text} · ${stateAge}`,
tone: turnDef.tone,
tooltip: STATE_TOOLTIPS[effectiveTurnState],
};
const ctx = tokenTotal(state.ctx_usage);
const cost = tokenTotal(state.cost_usage);
return (
<>
{hideHeader ? null : (
<Header
label={state.label}
hiveLabel={
[state.swarm_name, state.hive_name].filter(Boolean).join(" / ") ||
null
}
pills={pills}
>
<StatusChips
statusLabel={`${primaryStatus.glyph} ${primaryStatus.text}`}
statusTone={primaryStatus.tone}
statusTooltip={primaryStatus.tooltip}
model={state.model}
resolvedModel={state.resolved_model ?? undefined}
modelSource={state.model_source}
effort={state.effort}
effortSource={state.effort_source}
ctxLabel={ctx !== null ? fmtTokens(ctx) : undefined}
costLabel={cost !== null ? fmtTokens(cost) : undefined}
paused={state.paused}
onTogglePause={() => {
submitPauseResume(
resolveDashboardBase(state.dashboard_port),
state.label,
state.paused ? "resume" : "pause",
).then(() => refresh());
}}
thinking={effectiveTurnState === "thinking"}
onCancelTurn={() =>
postCancelTurn().then((r) => {
if (!r.ok)
liveStreamRef.current?.pushNote(
`✗ /cancel failed${r.detail ? ": " + r.detail : ""}`,
);
refresh();
})
}
onNewSession={() =>
postNewSession().then((r) => {
if (!r.ok)
liveStreamRef.current?.pushNote(
`✗ /new-session failed${r.detail ? ": " + r.detail : ""}`,
);
refresh();
})
}
onLogout={() =>
postLogout().then((r) => {
if (!r.ok)
liveStreamRef.current?.pushNote(
`✗ /logout failed${r.detail ? ": " + r.detail : ""}`,
);
refresh();
})
}
/>
</Header>
)}
<main className="agent-main">
<LiveStream ref={liveStreamRef} />
</main>
{panel}
</>
);
}

View file

@ -1,10 +1,9 @@
/* Shared Catppuccin palette + body typography + terminal pane styles.
Bundled in front of the agent-only rules below via esbuild. */
/* Shared Catppuccin palette + body typography.
Bundled in front of the stats and screen pages' rules below via esbuild. */
@import "@hive/shared/base.css";
@import "@hive/shared/terminal.css";
/* Shared page-header chrome (page-header / page-back / page-title) — gives the
agent SUB-pages (stats, screen) the same back-link nav the dashboard's
standalone pages use. The live terminal page keeps its own header. */
standalone pages use. */
@import "@hive/shared/chrome.css";
/* Shared pill/chip/badge shape (the "extract pill component" issue,
resolved as shared CSS rather than a JS component) — see pill.css
@ -14,653 +13,20 @@
component's own shadow root (adoptedStyleSheets), not a global
stylesheet — nothing to @import here. */
/* ─── full-screen layout overrides ─────────────────────────────────
The agent page mounts a full-viewport terminal under a fixed
frosted-glass header. See docs/4-implementation/web-ui/agent-page.md::Per-agent
page for the layer / pill / side-panel structure; rules below
override the in-page defaults from @hive/shared. */
:root {
/* 6em min-height accommodates the full-height agent icon (5em +
padding) alongside the two-row main column (title + nav-links
on top, state strip below). */
--agent-header-h: 6em;
--agent-frost-bg: color-mix(in srgb, var(--bg) 72%, transparent);
--agent-frost-blur: blur(12px) saturate(140%);
}
/* `?hide=header` (per-agent-page embed mode): `Root.tsx` toggles
this body class when it omits `<Header>`.
Zeroing the custom properties here — rather than overriding each
dependent rule — collapses every calc() that reads them (overlay
offset, terminal scroll padding) in one place. */
body.agent-hide-header {
--agent-header-h: 0px;
--agent-header-real-h: 0px;
}
html,
body {
height: 100%;
margin: 0;
}
/* Legacy in-page layout retained for the sibling stats page
(`stats.html`) which doesn't apply `body.agent-shell` and stays
on a normal-document scroll. screen-shell is also excluded — it
/* Normal-document scroll for the stats page. screen-shell is excluded: it
manages its own full-viewport layout below. */
body:not(.agent-shell):not(.screen-shell) {
body:not(.screen-shell) {
max-width: 110em;
margin: 1.5em auto;
padding: 0 1.5em;
height: auto;
}
.banner {
text-align: center;
margin: 0 0 1em 0;
font-size: 0.95em;
overflow-x: auto;
background: linear-gradient(
90deg,
var(--purple-dim) 0%,
var(--purple) 50%,
var(--purple-dim) 100%
);
background-size: 200% 100%;
background-position: 50% 0;
-webkit-background-clip: text;
background-clip: text;
color: transparent;
filter: drop-shadow(
0 0 6px color-mix(in srgb, var(--purple) 45%, transparent)
);
}
body.agent-shell {
background: var(--bg);
color: var(--fg);
/* Body itself doesn't scroll; the terminal does inside .agent-main. */
overflow: hidden;
/* Subtle radial accent to give the otherwise-flat full-screen
surface some depth and reinforce the vibec0re mood. */
background:
radial-gradient(
ellipse 80% 60% at 50% 0%,
color-mix(in srgb, var(--purple) 6%, transparent) 0%,
transparent 60%
),
var(--bg);
}
.agent-header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 30;
min-height: var(--agent-header-h);
display: flex;
/* align-items: stretch lets the icon take the full header height
(it sizes itself via aspect-ratio off the stretched height). The
main column + pills column self-centre via inner layout. */
align-items: stretch;
gap: 0.9em;
padding: 0.5em 1em;
background: var(--agent-frost-bg);
-webkit-backdrop-filter: var(--agent-frost-blur);
backdrop-filter: var(--agent-frost-blur);
border-bottom: 1px solid var(--purple-dim);
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.35);
}
/* Main column: title row on top, state strip below. Centred
vertically against the full-height icon on the left. */
.agent-header-main {
display: flex;
flex-direction: column;
justify-content: center;
gap: 0.45em;
min-width: 0;
flex: 1 1 auto;
}
.agent-header-row {
display: flex;
align-items: center;
gap: 0.8em;
flex-wrap: wrap;
min-width: 0;
}
.agent-header-title-row h2 {
margin: 0;
line-height: 1;
}
.agent-nav {
display: flex;
flex-wrap: wrap;
gap: 0.4em 0.8em;
margin: 0;
}
.agent-state-row {
margin: 0;
gap: 0.5em;
}
/* Right cluster — flyout pills, and (new Preact page only) the status
badges (`StatusChips`) too — mara, live: "move badges to where the
dropdowns are". `flex-wrap: wrap` alone doesn't help if this
container can't itself shrink: the old `flex-shrink: 0` here (fine
for app.js's 2-3-small-pills case, which never needed to shrink)
told the flex layout "give this its full natural width no matter
what," so once badges made that natural width wider than the
viewport, it just overflowed past the edge instead of ever getting
narrow enough to trigger its own wrap — mara, live, on the 500px
screenshot: "does not overflow properly". Dropping `flex-shrink: 0`
(default is `1`) is the whole fix — deliberately NOT pairing it
with `min-width: 0` (tried that first, made it worse: an unset
`min-width` still floors shrinking at this container's own
min-content — the widest single wrapped child, e.g. one badge, not
the full unwrapped row — which is the correct floor; `min-width: 0`
removes that floor entirely, so at a narrow enough viewport the
container shrinks past what its own content needs and the content
overflows its box sideways, landing on top of `.agent-header-main`
instead of wrapping cleanly — confirmed live, reproducible at
320px, not a one-off capture glitch). */
.agent-header-pills {
display: flex;
align-items: center;
gap: 0.5em;
flex-wrap: wrap;
justify-content: flex-end;
align-self: center;
}
h2,
h3 {
color: var(--purple);
text-transform: uppercase;
letter-spacing: 0.15em;
text-shadow: 0 0 8px color-mix(in srgb, var(--purple) 40%, transparent);
}
.agent-icon {
/* Square identity anchor — explicit 5em sizing + align-self.
See docs/4-implementation/web-ui/agent-page.md::Per-agent page (Agent icon) for the
intrinsic-dim-pushes-parent-flex-open + sticks-to-top
rationale. */
width: 5em;
height: 5em;
flex-shrink: 0;
align-self: flex-start;
border-radius: 8px;
box-shadow: 0 0 18px -2px color-mix(in srgb, var(--purple) 40%, transparent);
object-fit: cover;
}
/* Meta-nav links (stats / screen / dashboard / extras) —
no underline; hover lights with cyan glow + subtle background
tint. Reads as a row of soft tabs rather than default-styled
inline anchors. */
.agent-nav-link {
color: var(--cyan);
text-decoration: none;
font-size: 0.85em;
letter-spacing: 0.04em;
padding: 0.1em 0.35em;
border-radius: 3px;
text-shadow: 0 0 4px color-mix(in srgb, var(--cyan) 40%, transparent);
transition:
color 0.15s ease,
text-shadow 0.15s ease,
background 0.15s ease;
}
.agent-nav-link:hover {
color: var(--fg);
background: color-mix(in srgb, var(--cyan) 8%, transparent);
text-shadow: 0 0 10px color-mix(in srgb, var(--cyan) 85%, transparent);
}
/* Header pill (inbox / loose-ends triggers) — no CSS of its own any
more. `HeaderPill.tsx` renders `@hive/shared`'s `Badge` directly now
(mara: "cant we reuse the badge component") instead of a hand-styled
pill matched to Badge's own values; nothing left to override here. */
.agent-main {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
overflow: hidden;
}
.meta {
color: var(--muted);
font-size: 0.85em;
}
.status-online {
color: var(--green);
text-shadow: 0 0 6px color-mix(in srgb, var(--green) 55%, transparent);
}
.status-needs-login {
color: var(--amber);
text-shadow: 0 0 6px color-mix(in srgb, var(--amber) 55%, transparent);
}
code {
background: color-mix(in srgb, var(--purple) 12%, transparent);
padding: 0.05em 0.3em;
border-radius: 2px;
}
a {
color: var(--cyan);
text-shadow: 0 0 4px color-mix(in srgb, var(--cyan) 50%, transparent);
}
a:hover {
color: var(--fg);
text-shadow: 0 0 12px color-mix(in srgb, var(--cyan) 90%, transparent);
}
.btn {
font-family: inherit;
font-size: 1em;
background: var(--bg);
border: 1px solid var(--purple);
color: var(--purple);
padding: 0.25em 0.8em;
cursor: pointer;
letter-spacing: 0.1em;
}
.btn {
text-shadow: 0 0 4px currentColor;
transition:
box-shadow 0.15s ease,
text-shadow 0.15s ease;
}
.btn:hover {
background: color-mix(in srgb, var(--fg) 6%, transparent);
text-shadow: 0 0 10px currentColor;
box-shadow: 0 0 10px -2px currentColor;
}
/* Orphaned rules — left here as a tombstone so a search for the
class name finds them. Live consumers gone:
- `.btn-rebuild` was a per-agent header chip, then briefly an
overflow-menu item (`.overflow-item-rebuild`, also since deleted,
see MetaNav.tsx's file comment) — the button itself is gone
outright now, no replacement.
- `.btn-send` was a green send-button variant — the dashboard's
compose form that used it is retired. */
.sendform {
display: flex;
gap: 0.6em;
margin-top: 0.5em;
}
.sendform input {
font-family: inherit;
font-size: 1em;
background: rgba(255, 255, 255, 0.04);
color: var(--fg);
border: 1px solid var(--purple-dim);
padding: 0.4em 0.6em;
flex: 1;
}
.sendform input:focus {
outline: 1px solid var(--purple);
}
pre.diff {
background: rgba(255, 255, 255, 0.03);
border: 1px solid var(--purple-dim);
padding: 0.6em 0.8em;
overflow-x: auto;
white-space: pre-wrap;
word-break: break-all;
max-height: 30em;
}
/* Per-agent inbox section — collapsible, dim, lives between the
state row and the terminal so the operator can peek at what
landed without scrolling through the live tail. */
.agent-inbox {
margin: 0.4em 0;
font-size: 0.85em;
color: var(--muted);
}
.agent-inbox > summary {
cursor: pointer;
letter-spacing: 0.05em;
list-style: none;
}
.agent-inbox > summary::marker {
content: "";
}
.agent-inbox[open] > summary > span::before {
content: "";
}
.agent-inbox ul {
list-style: none;
padding: 0.4em 0.8em;
margin: 0.3em 0 0;
background: rgba(255, 255, 255, 0.02);
border-left: 2px solid var(--purple-dim);
max-height: 16em;
overflow-y: auto;
}
/* Inbox / loose-ends rows: header (from / sep / ts) on one line,
body on its own line below — gives the body the full panel width
instead of squeezing it into a fourth grid column that wrapped
long messages over many narrow lines. */
.agent-inbox li {
padding: 0.4em 0;
display: block;
}
.agent-inbox .inbox-ts {
color: var(--muted);
font-size: 0.9em;
margin-left: 0.5em;
}
.agent-inbox .inbox-from {
color: var(--amber);
}
.agent-inbox .inbox-sep {
color: var(--muted);
margin-left: 0.4em;
}
/* Todos flyout per-row checkbox (bulk mark-done) — sits inline before the
existing `.inbox-from` label, same row. */
.agent-inbox .todo-cb {
vertical-align: middle;
margin-right: 0.2em;
}
.agent-inbox .inbox-body {
display: block;
color: var(--fg);
white-space: pre-wrap;
word-break: break-word;
margin-top: 0.3em;
padding-left: 0.8em;
border-left: 2px solid var(--purple-dim);
}
/* Running bash-tasks flyout rows (buildBashTasksList). */
.agent-inbox .bash-task-status {
font-weight: bold;
font-size: 0.9em;
}
.agent-inbox .bash-task-running {
color: var(--green);
}
.agent-inbox .bash-task-pending {
color: var(--blue);
}
.agent-inbox .bash-task-cmd {
font-family: monospace;
font-size: 0.92em;
}
.agent-inbox li.inbox-reply {
padding-left: 1em;
border-left: 2px solid var(--border);
margin-left: 0.4em;
}
.agent-inbox .inbox-reply-tag {
color: var(--muted);
font-size: 0.85em;
}
/* Bulk-action header row: "mark all read" above the recent-messages
list in the inbox flyout, and "select all / select none / mark
done" above the list in the todos flyout — same classes, shared
look (mauve hover, bg-elev background) so both read as part of
the same affordance family. */
.agent-inbox .inbox-mark-all-row {
display: flex;
gap: 0.6em;
align-items: center;
padding: 0.4em 0.2em 0.6em;
margin-bottom: 0.5em;
border-bottom: 1px solid var(--border);
}
.agent-inbox .inbox-mark-all-btn {
font-family: inherit;
font-size: inherit;
background: var(--bg-elev);
color: var(--fg);
border: 1px solid var(--border);
border-radius: 3px;
padding: 0.3em 0.7em;
cursor: pointer;
white-space: nowrap;
}
.agent-inbox .inbox-mark-all-btn:hover:not(:disabled) {
border-color: var(--purple);
color: var(--purple);
}
.agent-inbox .inbox-mark-all-btn:disabled {
opacity: 0.5;
cursor: default;
}
.agent-inbox .inbox-mark-status {
color: var(--muted);
font-size: 0.9em;
}
.last-turn {
color: var(--muted);
font-size: 0.8em;
letter-spacing: 0.05em;
}
/* Markup carries `hive-pill-sm` alongside each of these (shared
pill.css supplies the shape); rules below are colour only. */
.model-chip,
.effort-chip {
border-color: var(--purple-dim);
}
.model-chip {
color: var(--cyan);
}
.effort-chip {
color: var(--amber);
}
/* Context-window badge. Mirrors Claude Code's bottom-right "N tokens"
chip — single primary number (total prompt tokens in use), full
breakdown on hover. Sized/coloured like a peer of model-chip so
the state row reads as one row of chrome. */
.ctx-badge {
border-color: var(--purple-dim);
color: var(--green);
cursor: default;
white-space: pre-line;
}
/* Harness reachability badge. Markup carries `hive-pill` alongside
`status-badge` (shared pill.css supplies the shape); colour
communicates the actual reachability state. */
.status-badge.status-loading {
color: var(--muted);
border-color: var(--purple-dim);
}
.status-badge.status-online {
color: var(--green);
border-color: var(--green);
text-shadow: 0 0 6px color-mix(in srgb, var(--green) 55%, transparent);
}
.status-badge.status-rate-limited {
color: var(--red);
border-color: var(--red);
text-shadow: 0 0 6px color-mix(in srgb, var(--red) 55%, transparent);
}
.status-badge.status-needs-login {
color: var(--amber);
border-color: var(--amber);
}
.status-badge.status-offline {
color: var(--muted);
border-color: var(--muted);
}
/* Orphaned tombstone — `.btn-dashlink` chip that lived beside the
title moved into the overflow menu, then into `MetaNav`'s `🔗`
popover (the `↑ dashboard` item) once the overflow menu itself was
deleted — see MetaNav.tsx's file comment. */
/* Orphaned tombstone — `.btn-cancel-turn` standalone button moved into
the consolidated status badge's dropdown as a danger-toned row
(StatusChips.tsx's `StatusMenu`, `@hive/shared`'s
`.ui-dropdown-item-danger`). */
/* Orphaned tombstone — `.btn-new-session` round-pill moved into the
overflow menu, then out of the header entirely: it's a row of the
state badge's menu now, no button/chip left to style. */
/* Markup carries `hive-pill` alongside `state-badge` (shared pill.css
supplies the shape); this rule is only the transition + state-
specific colour below. */
.state-badge {
transition:
color 280ms ease,
border-color 280ms ease,
box-shadow 280ms ease,
background 280ms ease;
}
.state-badge.state-loading {
color: var(--muted);
border-color: var(--purple-dim);
}
.state-badge.state-offline {
color: var(--muted);
border-color: var(--muted);
}
.state-badge.state-idle {
color: var(--cyan);
border-color: var(--cyan);
text-shadow: 0 0 6px color-mix(in srgb, var(--cyan) 55%, transparent);
}
.state-badge.state-thinking {
color: var(--amber);
border-color: var(--amber);
text-shadow: 0 0 6px color-mix(in srgb, var(--amber) 65%, transparent);
animation: badge-pulse 1.8s ease-in-out infinite;
}
.state-badge.state-compacting {
color: var(--purple);
border-color: var(--purple);
text-shadow: 0 0 6px color-mix(in srgb, var(--purple) 65%, transparent);
animation: badge-pulse 1.8s ease-in-out infinite;
}
.state-badge.state-just-changed {
animation: state-flash 600ms ease-out;
}
@keyframes state-flash {
0% {
box-shadow:
0 0 0 0 currentColor,
0 0 0 0 currentColor;
}
60% {
box-shadow:
0 0 18px -4px currentColor,
0 0 4px 0 currentColor;
}
100% {
box-shadow:
0 0 0 0 currentColor,
0 0 0 0 currentColor;
}
}
/* Full-screen overrides for the shared terminal rules. The base
`.terminal-wrap` (in shared/src/terminal.css) ships a crust-on-
black frame for the in-page case; the agent page now owns the
whole viewport so the frame chrome would be redundant noise.
`.live.terminal` similarly drops the in-page max-height cap so
it can fill the main area top-to-bottom; the floating header
overlays it via fixed positioning. */
.agent-main .terminal-wrap {
position: absolute;
inset: 0;
border: 0;
background: transparent;
box-shadow: none;
border-radius: 0;
margin: 0;
padding: 0;
}
.agent-main .live.terminal {
position: absolute;
inset: 0;
height: auto;
max-height: none;
/* Scroll behind the floating header, but keep the first
and last rows reachable with extra padding inside the scroll
area. scroll-padding-* keeps anchor-jumps (the `↓ N new` pill,
focus restore) clear of the floats too. */
padding-top: calc(var(--agent-header-real-h, var(--agent-header-h)) + 0.8em);
padding-bottom: 0.8em;
scroll-padding-top: calc(
var(--agent-header-real-h, var(--agent-header-h)) + 0.8em
);
scroll-padding-bottom: 0.8em;
overflow: auto;
}
/* Tail pill (↓ N new): z-index bumped above the floating chrome so the
pill sits on the top layer instead of being clipped by it. (Pill is anchored in
`.agent-main` rather than `.terminal-wrap` — see
docs/4-implementation/web-ui/agent-page.md::Per-agent page Terminal-wrap paragraph for the
backdrop-filter stacking-context rationale.) */
.agent-main .tail-pill {
bottom: 0.6em;
z-index: 35;
}
/* ─── side panel (singleton drawer) ────────────────────────────────
Inbox + loose-ends details open here instead of expanding inline. The
drawer chrome itself (backdrop, drawer, resize handle, header, title,
close button) is the shared `<hive-side-panel>` element
(@hive/shared/side-panel.js, including drag-to-resize); what's left
here is the drag cursor-override escape hatch (has to be a global,
light-DOM rule — it reaches every element on the page during a
drag, not just the shared element's own shadow tree) and the
styling for the panel's own content types, which the shared
element's shadow tree can never reach (see
@hive/shared/side-panel/hive-side-panel.css's header comment). The
`hive-side-panel .agent-inbox …` rules below use the element's own
tag name as the selector root — no compatibility class needed, the
tag name already uniquely identifies the light-DOM instance app.js's
`sidePanel` creates. */
body.side-panel-resizing {
user-select: none;
}
body.side-panel-resizing * {
cursor: ew-resize !important;
}
/* Inbox / loose-ends lists rendered into the side-panel body: strip
the inbox-only chrome (background, border-left) here and let the
panel body's own padding own the framing. */
hive-side-panel .agent-inbox {
margin: 0;
font-size: inherit;
color: var(--fg);
}
hive-side-panel .agent-inbox ul {
background: transparent;
border-left: 0;
padding: 0;
max-height: none;
overflow: visible;
}
/* Empty-state placeholders for the side panel (when count drops to 0
between the click and the render — rare, but possible). */
.side-panel-empty {
color: var(--muted);
font-style: italic;
padding: 1em 0;
}
/* Hive identity row — shows "swarm / hive" label beneath the title.
Hidden until JS populates from /api/state (hive_name + swarm_name).
Mirrors the `.banner-thin` style in dashboard.css but kept tight
(no letter-spacing, smaller text) so it reads as a sub-label. */
.agent-hive-row {
/* Omit the default row gap when the row is hidden to avoid a
blank gap between the title row and the state row. */
gap: 0;
}
.agent-hive-label {
font-size: 0.72em;
letter-spacing: 0.1em;
color: var(--purple-dim);
text-transform: uppercase;
}
/* ─── /stats page ────────────────────────────────────────────────────────── */
/* The stats page header (back link + title) uses the shared

View file

@ -1,44 +0,0 @@
// <AgentUserMenu> — the profile menu (`@hive/shared/user-menu.js`) in this
// page's header. Only behind the gateway: the page is then on the dashboard's
// own origin, where the session cookie is valid and nginx proxies
// `/api/whoami` to authelia. Opened directly on the agent's own port there is
// no sign-in to show, so the page has no menu.
//
// Authelia's URL, for the settings and sign-out links, comes from the
// dashboard's `/api/state` (`authelia_public_url`), the one place hive-c0re
// states it.
import { useEffect, useState } from "preact/hooks";
import { UserMenu } from "@hive/shared/user-menu.js";
import "@hive/shared/user-menu.css";
import { isBehindGateway } from "../lib/dashboardBase.js";
export function AgentUserMenu({ dashboardBase }: { dashboardBase: string }) {
const behind = isBehindGateway();
const [autheliaUrl, setAutheliaUrl] = useState<string | null>(null);
useEffect(() => {
if (!behind) return;
let cancelled = false;
fetch(`${dashboardBase}api/state`)
.then((r) =>
r.ok ? r.json() : Promise.reject(new Error(`http ${r.status}`)),
)
.then((state: { authelia_public_url?: string | null }) => {
if (!cancelled) setAutheliaUrl(state.authelia_public_url ?? null);
})
.catch(() => {
/* cosmetic only: the menu then shows the name without the links */
});
return () => {
cancelled = true;
};
}, [behind, dashboardBase]);
if (!behind) return null;
return (
<UserMenu
whoamiUrl={`${dashboardBase}api/whoami`}
autheliaUrl={autheliaUrl}
/>
);
}

View file

@ -1,96 +0,0 @@
// <Header> — the agent page's identity strip: icon, glyphic title, the
// "swarm / hive" label row, and a slot for the status row
// (`<StatusChips>` — ../status-chips/, kept separate so this component
// has no opinion on what badges exist). Three columns: icon, main
// (title + hive-label), pills — see the `pills` prop doc below for why
// the third column is the one that grows. Reuses `agent.css`'s
// existing `.agent-header*`/`.agent-icon` rules (loaded globally by
// index.html) rather than a component-scoped stylesheet — no new
// visual language needed for the chrome itself.
// Measures its own rendered height via ResizeObserver, writes it to
// `--agent-header-real-h` (`.agent-main`'s scroll padding, in agent.css,
// prefers this over the static `--agent-header-h` guess). A static guess
// broke whenever header content wrapped an extra line, at whatever width
// triggered it, and no width can be promised safe. Deliberately a SEPARATE var, not an overwrite
// of `--agent-header-h` in place: `.agent-header`'s own `min-height`
// also reads that var — overwriting it in place would make the
// header's own size react to its own just-measured height every
// tick, a real ResizeObserver feedback loop (confirmed live on the
// first pass of this fix). `--agent-header-h` stays the static floor;
// `--agent-header-real-h` is output-only.
import { useEffect, useRef } from "preact/hooks";
import type { ComponentChildren } from "preact";
// Icon 404s when the agent has no `services.hyperhive.agent.icon` override (no
// bundled server-side default any more — see
// `hive_agent::web_ui::screen::serve_icon`). Ports app.js's
// `bindHeaderIconFallback` exactly: fire-and-forget load, swap to
// `/favicon.svg` on failure, `dataset.fallback` guards against a
// 404-on-the-fallback-itself loop.
function handleIconError(e: Event) {
const img = e.currentTarget as HTMLImageElement;
if (img.dataset.fallback) return;
img.dataset.fallback = "1";
img.src = "/favicon.svg";
}
export interface HeaderProps {
label: string;
hiveLabel?: string | null;
/** The status/badge row (`<StatusChips>`) — lives in the
* `.agent-header-pills` cluster alongside `pills` (see below), not
* stacked as its own row under the title. */
children?: ComponentChildren;
/** Flyout triggers (inbox/todos/links pills, the overflow menu
* button) plus `children` (the status badges), all in
* `.agent-header-pills`. `.agent-header-main` only ever holds the
* title + hive-label rows, which don't wrap in practice and so stay
* a stable height; only this pills-cluster column (already sized for
* a variable pill count) grows to fit badges+pills together, keeping
* the header a stable height even on widescreen. Meta-nav
* (`<MetaNav>`) lives here too, as a fixed-size trigger, not an
* inline link list in the title row (docs/4-implementation/web-ui/agent-page.md). */
pills?: ComponentChildren;
}
export function Header({ label, hiveLabel, children, pills }: HeaderProps) {
const ref = useRef<HTMLElement>(null);
useEffect(() => {
const el = ref.current;
if (!el || typeof ResizeObserver === "undefined") return;
// getBoundingClientRect() (not ResizeObserver's own contentRect) —
// we want the full visual box padding+border included, the thing
// content below the fixed header actually needs to clear, not the
// content-box-only measurement ResizeObserver's entry defaults to.
const ro = new ResizeObserver(() => {
document.documentElement.style.setProperty(
"--agent-header-real-h",
`${el.getBoundingClientRect().height}px`,
);
});
ro.observe(el);
return () => ro.disconnect();
}, []);
return (
<header class="agent-header" ref={ref}>
<img class="agent-icon" src="icon" alt="" onError={handleIconError} />
<div class="agent-header-main">
<div class="agent-header-row agent-header-title-row">
<h2 class="agent-header-title">◆ {label} ◆</h2>
</div>
{hiveLabel ? (
<div class="agent-header-row agent-hive-row">{hiveLabel}</div>
) : null}
</div>
{children || pills ? (
<div class="agent-header-pills">
{children}
{pills}
</div>
) : null}
</header>
);
}

View file

@ -1,44 +0,0 @@
// <HeaderPill> — the inbox/todos flyout triggers in the header's right
// cluster. A thin wrapper over `@hive/shared`'s `Badge` (icon+label+
// value+onClick already covers this shape exactly) rather than a
// bespoke pill — mara, reviewing the first cut of this (a hand-styled
// `.header-pill` matched to `Badge`'s own CSS values rather than the
// component itself): "cant we reuse the badge component". Only two
// things this wrapper still owns: hiding at count 0 (`pill.hidden =
// count === 0` in the old page) and picking the inbox/todos tone so
// the count reads amber/green like it always has (`Badge`'s `tone`
// colours the value, which here is the count).
import { Badge, type BadgeTone } from "@hive/shared/badge.js";
export interface HeaderPillProps {
kind: "inbox" | "todos";
icon: string;
label: string;
count: number;
onClick: () => void;
}
const TONE: Record<HeaderPillProps["kind"], BadgeTone> = {
inbox: "warning",
todos: "positive",
};
export function HeaderPill({
kind,
icon,
label,
count,
onClick,
}: HeaderPillProps) {
if (count === 0) return null;
return (
<Badge
icon={icon}
label={label}
value={count}
tone={TONE[kind]}
onClick={onClick}
title={`open ${label} flyout`}
/>
);
}

View file

@ -1,104 +0,0 @@
// <InboxPanel> — content rendered inside <SidePanel> for the inbox
// flyout. "mark all read" POSTs to the *dashboard's* origin (not this
// agent's own backend) via a plain `fetch()`, same as app.js's
// `buildInboxMarkAllRow` — unlike pause/resume this one's fine as a
// fetch even when the two are genuinely cross-origin, because
// `hive-c0re`'s `/api/agent/{name}/mark-all-read` route replies with
// JSON, not a redirect; in the common gateway-fronted deployment
// `dashboardBase` already resolves to `location.origin` anyway (see
// dashboardBase.ts), so it's same-origin in practice.
import { useState } from "preact/hooks";
import { useConfirmClick } from "../lib/useConfirmClick.js";
import type { InboxRow } from "../types.js";
export interface InboxPanelProps {
rows: InboxRow[];
label: string;
dashboardBase: string;
onCleared: () => void;
}
function fmtTs(unixSeconds: number): string {
return new Date(unixSeconds * 1000)
.toISOString()
.replace("T", " ")
.slice(5, 19);
}
export function InboxPanel({
rows,
label,
dashboardBase,
onCleared,
}: InboxPanelProps) {
const [status, setStatus] = useState("");
const [busy, setBusy] = useState(false);
async function markAllRead() {
if (!dashboardBase || !label) {
setStatus("dashboard url / label unknown");
return;
}
setBusy(true);
setStatus("clearing…");
try {
const resp = await fetch(
`${dashboardBase}api/agent/${encodeURIComponent(label)}/mark-all-read`,
{
method: "POST",
},
);
if (resp.ok) {
const data = await resp.json().catch(() => ({}));
const n = Number((data as { marked?: number }).marked) || 0;
setStatus(`✓ marked ${n} as read`);
onCleared();
} else {
setStatus(`failed: http ${resp.status}`);
}
} catch (err) {
setStatus(`failed: ${err instanceof Error ? err.message : String(err)}`);
} finally {
setBusy(false);
}
}
const { armed, trigger } = useConfirmClick(markAllRead);
if (!rows.length) {
return <p class="side-panel-empty">inbox empty.</p>;
}
return (
<div class="agent-inbox">
<div class="inbox-mark-all-row">
<button
type="button"
class="inbox-mark-all-btn"
onClick={trigger}
disabled={busy}
title="mark every queued message for this agent as read — drains the host broker's pending + delivered-unacked rows. history shown here is the most-recent-N regardless of state, so the list itself stays visible."
>
{armed ? "sure? click again" : "✓ mark all read"}
</button>
<span class="inbox-mark-status">{status}</span>
</div>
<ul>
{rows.map((m) => (
<li
key={m.id}
class={m.in_reply_to != null ? "inbox-reply" : undefined}
>
{m.in_reply_to != null && (
<span class="inbox-reply-tag">↳ reply · </span>
)}
<span class="inbox-ts">{fmtTs(m.at)}</span>{" "}
<span class="inbox-from">{m.from}</span>{" "}
<span class="inbox-sep">→</span>{" "}
<span class="inbox-body">{m.body}</span>
</li>
))}
</ul>
</div>
);
}

View file

@ -1,137 +0,0 @@
// Live event pane — Preact owner of the DOM node `useLiveStream`'s rows
// get rendered into. Deliberately NOT the old MutationObserver + rAF
// snap-animation + `smoothScrollingUntil` gate machinery
// (@hive/shared/terminal.js) — mara explicitly flagged that the old
// page's autoscroll breaks when new events land while the operator has
// scrolled up, and not to copy it 1:1. This is the "do it properly the
// preact way" version:
//
// - `stickToBottom` is plain state, updated synchronously from the
// scroll handler (near-bottom → true, scrolled away → false). No
// separate "am I mid-animation" gate to fight with it — there's no
// animation to fight, snapping is an instant `scrollTop` write in a
// `useLayoutEffect` that runs once after Preact has already
// committed the new rows to the DOM, so it always sees the real
// `scrollHeight`, never a stale pre-mutation one.
// - A "load older" prepend is told apart from a normal append via
// `prependingRef` (set immediately before calling `loadMore()`) so
// the effect can choose the right response: viewport-preserving
// scrollTop compensation for a prepend, stick-to-bottom-or-count-
// unseen for an append. The old code inferred this from DOM
// mutation shape after the fact; here the caller already knows
// which one it did, so there's nothing to infer.
import {
useLayoutEffect,
useRef,
useState,
useImperativeHandle,
} from "preact/hooks";
import { forwardRef } from "preact/compat";
import { useLiveStream } from "../hooks/useLiveStream.js";
import { Row } from "@hive/shared/term-row.js";
const NEAR_BOTTOM_PX = 48;
const LOAD_MORE_SCROLL_PX = 80;
/** Imperative escape hatch for the page's local-only notes (the result of
* a state-badge action) — kept as a ref handle rather than lifting the whole
* row array up to Root so LiveStream/useLiveStream still own their state
* privately. */
export interface LiveStreamHandle {
pushNote: (text: string) => void;
}
export const LiveStream = forwardRef<LiveStreamHandle, object>(
function LiveStream(_props, ref) {
const { rows, hasMore, loadingMore, loadMore, pushLocalNote } =
useLiveStream();
useImperativeHandle(ref, () => ({ pushNote: pushLocalNote }), [
pushLocalNote,
]);
const logRef = useRef<HTMLDivElement>(null);
const [stickToBottom, setStickToBottom] = useState(true);
const [unseen, setUnseen] = useState(0);
const prevRowCount = useRef(0);
const prependingRef = useRef(false);
const preScrollHeightRef = useRef(0);
function isNearBottom(el: HTMLDivElement): boolean {
return el.scrollHeight - el.scrollTop - el.clientHeight <= NEAR_BOTTOM_PX;
}
function handleScroll() {
const el = logRef.current;
if (!el) return;
const nearBottom = isNearBottom(el);
setStickToBottom(nearBottom);
if (nearBottom) setUnseen(0);
if (el.scrollTop <= LOAD_MORE_SCROLL_PX && hasMore && !loadingMore)
startLoadMore();
}
function startLoadMore() {
const el = logRef.current;
if (!el || loadingMore || !hasMore) return;
prependingRef.current = true;
preScrollHeightRef.current = el.scrollHeight;
loadMore();
}
function jumpToBottom() {
const el = logRef.current;
if (el) el.scrollTop = el.scrollHeight - el.clientHeight;
setStickToBottom(true);
setUnseen(0);
}
// Runs after every commit that changed `rows` — i.e. after the browser
// has already laid out the new/coalesced content, so `scrollHeight`
// below is always current.
useLayoutEffect(() => {
const el = logRef.current;
if (!el) return;
const added = rows.length - prevRowCount.current;
prevRowCount.current = rows.length;
if (prependingRef.current) {
prependingRef.current = false;
el.scrollTop += el.scrollHeight - preScrollHeightRef.current;
return;
}
if (stickToBottom) {
el.scrollTop = el.scrollHeight - el.clientHeight;
} else if (added > 0) {
setUnseen((n) => n + added);
}
}, [rows, stickToBottom]);
return (
<div className="terminal-wrap">
<div className="live terminal" ref={logRef} onScroll={handleScroll}>
{hasMore && (
<button
type="button"
className="load-more-pill"
disabled={loadingMore}
onClick={startLoadMore}
>
{loadingMore ? "↑ loading…" : "↑ load older"}
</button>
)}
{rows.map((row) => (
<Row key={row.key} row={row} />
))}
</div>
{unseen > 0 && (
<button
type="button"
className="tail-pill visible"
onClick={jumpToBottom}
>
↓ {unseen} new
</button>
)}
</div>
);
},
);

View file

@ -1,39 +0,0 @@
/* <MetaNav> popover — matches `@hive/shared`'s `Dropdown` (`.ui-dropdown`)
values exactly (background/border/radius/shadow, item padding/hover),
a "reuse the values, not the component" call: this popover's
items are real `<a>` tags, not `Dropdown`'s command-dispatch
`<button>`s. Right-anchored — MetaNav sits in the header's right-hand
pills cluster, so a left anchor would push it off-screen. */
.meta-nav-anchor {
position: relative;
display: inline-block;
}
.meta-nav-popover {
position: absolute;
top: calc(100% + 0.25em);
right: 0;
left: auto;
z-index: 20;
display: flex;
flex-direction: column;
min-width: 10em;
padding: 0.25em;
background: var(--bg-elev);
border: 1px solid var(--border);
border-radius: 0.5em;
box-shadow: 0 0.4em 1em rgba(0, 0, 0, 0.35);
}
.meta-nav-item {
display: flex;
align-items: center;
gap: 0.5em;
min-height: 2.75em;
padding: 0.4em 0.7em;
border-radius: 0.35em;
color: var(--fg);
text-decoration: none;
white-space: nowrap;
}
.meta-nav-item:hover {
background: var(--border);
}

View file

@ -1,105 +0,0 @@
// <MetaNav> — the header's meta-nav trigger: a single fixed-size Badge
// (`@hive/shared/icons.js`'s `LinkIcon` — an emoji glyph can't match a
// neighbouring icon's size/weight on any platform, see that file's
// comment) in the pills cluster that opens a popover listing
// stats/screen + any `services.hyperhive.agent.dashboardLinks` extras,
// sourced from the backend's `agent_links()` (the single source of
// truth — same list also feeds the dashboard card's icon strip) — plus
// a `🧭 dashboard` back-link.
//
// `variant="quiet"` — mara: "link and settings button should not have
// the badge bg". `Badge`'s default filled-pill look is right for a
// status/picker chip, wrong for this icon-only trigger, which should
// read as header chrome. See `@hive/shared/badge.js`'s `BadgeVariant`.
//
// A popover keeps the header height fixed — a variable-width inline
// link list would grow the title row past the fixed `--agent-header-h`
// the rest of the page is offset against (see Header.tsx's comment).
// Real `<a>` items, not `@hive/shared`'s `Dropdown` (its items are
// always `<button>`s for command dispatch, which would lose real link
// semantics like ctrl/middle-click and "copy link address"), but
// matching its `.ui-dropdown` visual values exactly (see MetaNav.css) —
// a "reuse the values, not the component" call.
import { useEffect, useRef, useState } from "preact/hooks";
import { Badge } from "@hive/shared/badge.js";
import { LinkIcon } from "@hive/shared/icons.js";
import type { AgentLink } from "../types.js";
import "./MetaNav.css";
export interface MetaNavProps {
links: AgentLink[];
/** Absolute base URL of the host dashboard (`resolveDashboardBase`)
* — the `🧭 dashboard` item links to `${dashboardBase}`. */
dashboardBase: string;
}
export function MetaNav({ links, dashboardBase }: MetaNavProps) {
const [open, setOpen] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
// Same "outside click or Escape closes" contract as Dropdown/OverflowMenu.
useEffect(() => {
if (!open) return;
function onPointerDown(e: PointerEvent) {
if (
rootRef.current &&
e.target instanceof Node &&
!rootRef.current.contains(e.target)
)
setOpen(false);
}
function onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") setOpen(false);
}
document.addEventListener("pointerdown", onPointerDown, true);
document.addEventListener("keydown", onKeyDown);
return () => {
document.removeEventListener("pointerdown", onPointerDown, true);
document.removeEventListener("keydown", onKeyDown);
};
}, [open]);
// `external` is already absolute; `container` is a same-origin path.
// No early-return-on-empty: the dashboard link below is always
// present, so the trigger always has at least one item.
return (
<div class="meta-nav-anchor" ref={rootRef}>
<Badge
value={<LinkIcon />}
title="agent links"
variant="quiet"
onClick={() => setOpen((o) => !o)}
expanded={open}
/>
{open ? (
<div class="meta-nav-popover" role="menu" aria-label="agent links">
<a
class="meta-nav-item"
href={dashboardBase}
target="_blank"
rel="noopener"
role="menuitem"
onClick={() => setOpen(false)}
>
🧭 dashboard
</a>
{links.map((lnk) => (
<a
key={lnk.url}
class="meta-nav-item"
href={lnk.url}
target="_blank"
rel="noopener"
role="menuitem"
onClick={() => setOpen(false)}
>
{lnk.icon ? <span aria-hidden="true">{lnk.icon}</span> : null}
{lnk.label}
</a>
))}
</div>
) : null}
</div>
);
}

View file

@ -1,80 +0,0 @@
/* Drawer chrome for <SidePanel> — backdrop, drawer box, header, close
button. Content styling (.agent-inbox, .inbox-*, .side-panel-empty)
already ships globally via agent.css; the two rules at the bottom
here re-target agent.css's old `hive-side-panel .agent-inbox …`
flatten-when-inside-a-panel overrides at this component's own class
instead, since this is a plain Preact tree, not a custom element. */
.agent-side-panel-backdrop {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
z-index: 60;
opacity: 0;
pointer-events: none;
transition: opacity 160ms ease;
}
.agent-side-panel-backdrop.open {
opacity: 1;
pointer-events: auto;
}
.agent-side-panel-drawer {
position: fixed;
top: 0;
right: 0;
bottom: 0;
width: min(26em, 96vw);
background: var(--bg-elev);
border-left: 1px solid var(--border);
box-shadow: -8px 0 24px rgba(0, 0, 0, 0.4);
z-index: 61;
display: flex;
flex-direction: column;
transform: translateX(100%);
transition: transform 200ms ease;
}
.agent-side-panel-drawer.open {
transform: translateX(0);
}
.agent-side-panel-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.6em 0.8em;
border-bottom: 1px solid var(--border);
color: var(--fg);
}
.agent-side-panel-title {
font-weight: bold;
letter-spacing: 0.03em;
}
.agent-side-panel-close {
background: none;
border: 0;
color: var(--muted);
font-size: 1.1em;
line-height: 1;
cursor: pointer;
padding: 0.3em 0.5em;
min-width: 2.75em;
min-height: 2.75em;
}
.agent-side-panel-close:hover {
color: var(--fg);
}
.agent-side-panel-body {
flex: 1;
overflow-y: auto;
padding: 0.8em;
}
.agent-side-panel-body .agent-inbox {
margin: 0;
font-size: inherit;
color: var(--fg);
}
.agent-side-panel-body .agent-inbox ul {
background: transparent;
border-left: 0;
padding: 0;
max-height: none;
overflow: visible;
}

View file

@ -1,64 +0,0 @@
// <SidePanel> — the slide-in drawer for the inbox/todos flyouts.
// Deliberately a new Preact component, not the shared
// `<hive-side-panel>` shadow-DOM custom element (@hive/shared/
// side-panel.js) — same rationale as StatusChips' Badge/Dropdown:
// mara's ask was real Preact components for this rewrite, not a port
// of the old widget family. Drops that element's drag-to-resize +
// localStorage width persistence for this first slice (fixed width via
// CSS, see SidePanel.css) — a real simplification, not an oversight;
// revisit if a fixed width proves cramped in practice.
//
// Content styling (`.agent-inbox`, `.inbox-*`, `.side-panel-empty`)
// already ships globally via `agent.css` and is reused verbatim by
// InboxPanel/TodosPanel — only the drawer chrome itself is new here.
import { useEffect } from "preact/hooks";
import type { ComponentChildren } from "preact";
import "./SidePanel.css";
export interface SidePanelProps {
open: boolean;
title: string;
onClose: () => void;
children?: ComponentChildren;
}
export function SidePanel({ open, title, onClose, children }: SidePanelProps) {
useEffect(() => {
if (!open) return;
function onKey(e: KeyboardEvent) {
if (e.key === "Escape") onClose();
}
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [open, onClose]);
return (
<>
<div
class={`agent-side-panel-backdrop${open ? " open" : ""}`}
onClick={onClose}
aria-hidden="true"
/>
<div
class={`agent-side-panel-drawer${open ? " open" : ""}`}
role="dialog"
aria-modal="true"
aria-hidden={!open}
aria-label={title}
>
<div class="agent-side-panel-head">
<span class="agent-side-panel-title">{title}</span>
<button
type="button"
class="agent-side-panel-close"
title="close (esc)"
onClick={onClose}
>
✕
</button>
</div>
<div class="agent-side-panel-body">{children}</div>
</div>
</>
);
}

View file

@ -1,42 +0,0 @@
/* <StatusChips> layout. Colours all come from Badge/Dropdown's own CSS
(@hive/shared) — nothing here overrides a base16 slot. */
.status-chips {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5em;
}
.status-chip-anchor {
position: relative;
display: inline-block;
}
/* mara, live, on a screenshot of this row: "badges and interactive
elements on same row have inconsistent size." Real cause: Badge.css's
`.ui-badge-interactive` grows to a 2.75em WCAG touch-target floor
(pause) while a plain display `<span>` badge (model, effort,
alive, state, ctx, cost — no `onClick`) stays compact, so the row
reads as two different pill sizes even though every badge here is
the same `<Badge>` component. Scoped to this row rather than
Badge.css itself — display-only badges elsewhere (e.g. the dashboard)
have no reason to grow, this is specifically about badges and
buttons sitting side by side in one row needing to read as one
family. */
.status-chips .ui-badge {
min-height: 2.75em;
padding-inline: 0.8em;
/* Badge.css's base `.ui-badge` radius (`1em`) is only guaranteed to
reach a full stadium at its own compact display-only height — this
rule stretches every badge in the row (including plain, non-
interactive ones like "ctx"/"cost") to the 2.75em touch-target
floor above, well past that, so it needs the same `999px`
stadium-radius trick `.ui-badge-interactive` (Badge.css) and
`.hive-pill`/`.hive-pill-sm` (pill.css) already use — otherwise a
stretched non-interactive badge renders as a rounded rectangle
instead of a pill (mara: "badge-with-label still not pill shaped,
eg agent term ctx"). */
border-radius: 999px;
}
.status-chips-last-turn {
font-size: 0.8em;
color: var(--muted);
}

View file

@ -1,250 +0,0 @@
// <StatusChips> — the agent page's status row: the consolidated status
// badge (alive/thinking/paused/etc., with pause/resume + cancel-turn in
// its dropdown), the model and effort (display-only: the swarm sets
// them), and context/cost usage.
// This is the concrete fix for the design guide's own named anti-example
// (the old page's model/effort *pickers* lived in the `⋯` overflow menu
// while the current model/effort only showed as a disconnected chip) —
// every badge here IS the control for what it displays, composed from
// `@hive/shared`'s `Badge`/`Dropdown` (../../shared/src/badge,
// ../../shared/src/dropdown). Presentational only: formatting +
// selection state live in the caller (`Root.tsx`, via the
// `useAgentState` hook), so this component can still be demoed and
// reviewed against plain sample data independent of live `/api/state`.
import { useRef, useState } from "preact/hooks";
import { Badge, type BadgeTone } from "@hive/shared/badge.js";
import { Dropdown, type DropdownOption } from "@hive/shared/dropdown.js";
import type { InferenceSource } from "../types.js";
import "./StatusChips.css";
export interface StatusChipsProps {
statusLabel: string;
statusTone: BadgeTone;
statusTooltip?: string;
model: string;
/** Concrete model id the last completed turn actually ran on, e.g.
* "claude-sonnet-4-5-20260805" — shown as the badge's tooltip so the
* operator can tell what an alias resolved to. `undefined` before any
* turn has completed. */
resolvedModel?: string;
/** Where `model` comes from (`/api/state` `model_source`). */
modelSource?: InferenceSource;
/** Hidden when empty: an ACP session that offers no effort now. */
effort?: string | null;
effortSource?: InferenceSource;
ctxLabel?: string;
costLabel?: string;
paused: boolean;
onTogglePause: () => void;
lastTurnLabel?: string;
thinking: boolean;
onCancelTurn: () => Promise<void>;
/** Drops all prior `--continue` context and starts fresh. Always
* offered, same as logout — the old app.js overflow menu had it as
* an unconditional click target too, this is just the click path
* catching up to what `/new-session` already does. See
* `termActions.ts`'s `postNewSession`. */
onNewSession: () => Promise<void>;
/** Rotates OAuth creds + parks the agent in needs-login. Always
* offered (unlike cancel-turn, not gated on `thinking`) — the old
* page's overflow menu had it unconditionally too. See
* `termActions.ts`'s `postLogout` for what it actually does. */
onLogout: () => Promise<void>;
}
const SOURCE_LABEL: Record<InferenceSource, string> = {
swarm: "set on the swarm",
agent_nix: "from agent.nix",
local_file: "from its own earlier pick",
default: "the built-in default",
};
// The consolidated alive/thinking/paused badge (mara: "why do we
// have separate alive badge? ... it could be one badge that shows
// thinking / idle / paused / ... with a dropdown that opens when
// clicked to pause/unpause or cancel turn"). Cancel-turn is a
// click-again-to-confirm row rather than a native confirm dialog (mara:
// "make the menu entry a 'click again to confirm'") — armed state resets
// whenever the dropdown closes, so a stray reopen never fires it early.
function StatusMenu({
statusLabel,
statusTone,
statusTooltip,
paused,
onTogglePause,
thinking,
onCancelTurn,
onNewSession,
onLogout,
}: Pick<
StatusChipsProps,
| "statusLabel"
| "statusTone"
| "statusTooltip"
| "paused"
| "onTogglePause"
| "thinking"
| "onCancelTurn"
| "onNewSession"
| "onLogout"
>) {
const [open, setOpen] = useState(false);
const [confirmCancel, setConfirmCancel] = useState(false);
const [confirmNewSession, setConfirmNewSession] = useState(false);
const [confirmLogout, setConfirmLogout] = useState(false);
const anchorRef = useRef<HTMLDivElement>(null);
function close() {
setOpen(false);
setConfirmCancel(false);
setConfirmNewSession(false);
setConfirmLogout(false);
}
const options: DropdownOption[] = [
{ value: "toggle-pause", label: paused ? "▶ resume" : "⏸ pause" },
];
if (thinking) {
options.push({
value: "cancel-turn",
label: confirmCancel ? "■ click again to confirm" : "■ cancel turn",
danger: true,
});
}
// Always offered, regardless of turn state — same as the old overflow
// menu's unconditional ↻ new-session and 🔓 logout entries.
options.push({
value: "new-session",
label: confirmNewSession ? "↻ click again to confirm" : "↻ new session",
danger: true,
});
options.push({
value: "logout",
label: confirmLogout ? "🔓 click again to confirm" : "🔓 logout",
danger: true,
});
return (
<div class="status-chip-anchor" ref={anchorRef}>
<Badge
value={statusLabel}
tone={statusTone}
title={statusTooltip}
onClick={() => setOpen((o) => !o)}
expanded={open}
/>
<Dropdown
open={open}
options={options}
label="agent status"
onSelect={(value) => {
if (value === "toggle-pause") {
onTogglePause();
close();
return;
}
if (value === "cancel-turn") {
// First click arms it, second fires.
if (!confirmCancel) {
setConfirmCancel(true);
return;
}
onCancelTurn();
close();
return;
}
if (value === "new-session") {
// Same arm-then-fire shape as cancel-turn/logout.
if (!confirmNewSession) {
setConfirmNewSession(true);
return;
}
onNewSession();
close();
return;
}
// value === 'logout': same arm-then-fire shape as cancel-turn.
if (!confirmLogout) {
setConfirmLogout(true);
return;
}
onLogout();
close();
}}
onClose={close}
anchorRef={anchorRef}
/>
</div>
);
}
export function StatusChips({
statusLabel,
statusTone,
statusTooltip,
model,
resolvedModel,
modelSource,
effort,
effortSource,
ctxLabel,
costLabel,
paused,
onTogglePause,
lastTurnLabel,
thinking,
onCancelTurn,
onNewSession,
onLogout,
}: StatusChipsProps) {
return (
<div class="status-chips">
<StatusMenu
statusLabel={statusLabel}
statusTone={statusTone}
statusTooltip={statusTooltip}
paused={paused}
onTogglePause={onTogglePause}
thinking={thinking}
onCancelTurn={onCancelTurn}
onNewSession={onNewSession}
onLogout={onLogout}
/>
<Badge
label="model"
value={model}
title={
[
modelSource ? SOURCE_LABEL[modelSource] : null,
resolvedModel ? `resolved to ${resolvedModel}` : null,
]
.filter(Boolean)
.join(" · ") || undefined
}
/>
{effort ? (
<Badge
label="effort"
value={effort}
title={effortSource ? SOURCE_LABEL[effortSource] : undefined}
/>
) : null}
{ctxLabel ? (
<Badge
label="ctx"
value={ctxLabel}
title="tokens used in the current context window"
/>
) : null}
{costLabel ? (
<Badge
label="cost"
value={costLabel}
title="cumulative tokens billed across the last turn (sum across every inference; tool-heavy turns rebill the cached prompt per call)"
/>
) : null}
{lastTurnLabel ? (
<span class="status-chips-last-turn">{lastTurnLabel}</span>
) : null}
</div>
);
}

View file

@ -1,113 +0,0 @@
// <TodosPanel> — content rendered inside <SidePanel> for the todos
// flyout. "mark done" POSTs to this agent's own backend
// (`api/todos/mark-done`, same-origin), unlike InboxPanel's cross-agent
// mark-all-read.
import { useState } from "preact/hooks";
import type { TodoRow } from "../types.js";
export interface TodosPanelProps {
todos: TodoRow[];
onCleared: () => void;
}
function fmtAge(seconds: number): string {
if (seconds < 60) return `${seconds}s`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`;
return `${Math.floor(seconds / 86400)}d`;
}
export function TodosPanel({ todos, onCleared }: TodosPanelProps) {
const [checked, setChecked] = useState<Set<number>>(new Set());
const [status, setStatus] = useState("");
const [busy, setBusy] = useState(false);
function toggle(id: number) {
setChecked((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
async function markDone() {
const ids = [...checked];
if (!ids.length) return;
setBusy(true);
setStatus("marking…");
try {
const resp = await fetch("api/todos/mark-done", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `ids=${encodeURIComponent(ids.join(","))}`,
});
if (resp.ok) {
setStatus("✓ marked done");
setChecked(new Set());
onCleared();
} else {
setStatus(`failed: ${await resp.text()}`);
}
} catch (err) {
setStatus(`failed: ${err instanceof Error ? err.message : String(err)}`);
} finally {
setBusy(false);
}
}
if (!todos.length) {
return (
<p class="side-panel-empty">no todos — all subsystem queues are clear.</p>
);
}
const allChecked = todos.length > 0 && todos.every((t) => checked.has(t.id));
return (
<div class="agent-inbox">
<div class="inbox-mark-all-row">
<button
type="button"
class="inbox-mark-all-btn"
onClick={() =>
setChecked(allChecked ? new Set() : new Set(todos.map((t) => t.id)))
}
>
{allChecked ? "select none" : "select all"}
</button>
<button
type="button"
class="inbox-mark-all-btn"
onClick={markDone}
disabled={busy || checked.size === 0}
>
✓ mark done
</button>
<span class="inbox-mark-status">{status}</span>
</div>
<ul>
{todos.map((t) => {
const cbId = `todo-cb-${t.id}`;
const label = t.source ? `${t.subsystem} · ${t.source}` : t.subsystem;
return (
<li key={t.id}>
<input
type="checkbox"
id={cbId}
class="todo-cb"
checked={checked.has(t.id)}
onChange={() => toggle(t.id)}
/>{" "}
<label for={cbId} class="inbox-from">
{label}
</label>{" "}
<span class="inbox-ts">{fmtAge(t.age_seconds)} ago</span>
<div class="inbox-body">{t.summary}</div>
</li>
);
})}
</ul>
</div>
);
}

View file

@ -1,90 +0,0 @@
// useAgentState — polls `GET /api/state` every 4s and exposes the latest
// snapshot + loading/error status. Also resyncs immediately whenever the
// tab regains visibility: a backgrounded tab's `setTimeout` chain gets
// throttled/frozen by the browser, so the last snapshot — and anything
// the UI derives from it, like the turn-state badge's elapsed-time text —
// goes stale until something proactively refetches; without this the
// only way back to a live reading was a full page reload.
import { useEffect, useRef, useState } from "preact/hooks";
import type { AgentState } from "../types.js";
const POLL_MS = 4000;
const RETRY_MS = 5000;
export interface UseAgentStateResult {
state: AgentState | null;
error: string | null;
/** Force an immediate refresh (e.g. right after a pause/resume POST). */
refresh: () => void;
}
export function useAgentState(): UseAgentStateResult {
const [state, setState] = useState<AgentState | null>(null);
const [error, setError] = useState<string | null>(null);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const stoppedRef = useRef(false);
// Holds the mount effect's self-rescheduling `poll` so `refresh()` can
// invoke the *same* function instead of a parallel one-off fetch — a
// fresh call still runs through `poll`'s own `setTimeout(poll, …)` tail,
// so the loop stays alive afterwards instead of dying silently the
// first time something calls `refresh()` (see the review discussion on
// this file's PR: an earlier version of `refresh()` did its own
// one-off fetch with no reschedule, which permanently killed periodic
// polling the first time a caller invoked it).
const pollRef = useRef<() => void>(() => {});
useEffect(() => {
stoppedRef.current = false;
async function poll() {
try {
const resp = await fetch("api/state");
if (!resp.ok) throw new Error(`http ${resp.status}`);
const s = (await resp.json()) as AgentState;
if (stoppedRef.current) return;
setState(s);
setError(null);
timerRef.current = setTimeout(poll, POLL_MS);
} catch (err) {
if (stoppedRef.current) return;
setError(err instanceof Error ? err.message : String(err));
timerRef.current = setTimeout(poll, RETRY_MS);
}
}
pollRef.current = poll;
poll();
return () => {
stoppedRef.current = true;
if (timerRef.current) clearTimeout(timerRef.current);
};
}, []);
function refresh() {
if (timerRef.current) clearTimeout(timerRef.current);
stoppedRef.current = false;
pollRef.current();
}
// A backgrounded/hidden tab has its `setTimeout` chain throttled by the
// browser (Chrome et al throttle nested timers heavily once hidden, and
// may suspend the page outright) — the `poll()` loop above effectively
// stalls, and everything derived from `state` (not just the fetch
// itself) goes stale until it happens to fire again. Force a resync the
// moment the tab becomes visible so switching back doesn't leave a
// reading that's minutes old. Empty deps: `refresh` only closes over
// refs and setState setters, both stable across renders, so the first
// render's closure stays correct for the component's whole lifetime —
// and, unlike re-subscribing on every render, doesn't re-attach this
// listener every second now that `Root`'s own 1s ticker re-renders the
// component that calls this hook.
useEffect(() => {
function onVisible() {
if (document.visibilityState === "visible") refresh();
}
document.addEventListener("visibilitychange", onVisible);
return () => document.removeEventListener("visibilitychange", onVisible);
}, []);
return { state, error, refresh };
}

View file

@ -1,234 +0,0 @@
// Backfill + live SSE for the agent's event stream, reduced to a plain
// `TermRow[]` — the Preact-data sibling of @hive/shared/terminal.js's
// `create()`. Scroll behaviour is deliberately NOT this hook's job (see
// components/LiveStream.tsx): mara flagged the old page's scroll-while-
// streaming bug explicitly as something not to copy 1:1, and keeping
// "what rows exist" separate from "where the viewport is" is what makes
// that fixable — this hook only ever appends/prepends to `rows`, the
// DOM-owning component decides whether that should move the scroll
// position.
//
// Same subscribe → buffer → fetch-history → seq-dedupe → flush dance as
// terminal.js's `start()`: a live envelope landing between EventSource-
// open and the history response resolving is buffered, not dropped or
// double-counted (`envelope.seq <= history.seq` → already covered by the
// initial history page, drop it from the buffer). `seq` alone is the
// whole dedup signal, see `TermEnvelope`'s doc in hive-agent's
// `web_ui/stream.rs`.
import { useEffect, useRef, useState } from "preact/hooks";
import type { TermEnvelope, TermRow } from "@hive/shared/term-msg.js";
export interface UseLiveStreamOptions {
historyUrl?: string;
streamUrl?: string;
}
export interface UseLiveStreamResult {
rows: TermRow[];
hasMore: boolean;
loadingMore: boolean;
loadMore: () => void;
/** Append a local-only note row (error feedback on a failed state-badge
* action) — never sent anywhere, purely a client-side echo. */
pushLocalNote: (text: string) => void;
}
function appendRow(rows: TermRow[], row: TermRow): TermRow[] {
const last = rows[rows.length - 1];
// Coalesce in place only while the coalescible row is still the last
// one in the list — any other row landing in between starts a fresh
// one, same rule as terminal.js's makeCoalescer.
if (row.coalesce_key && last && last.coalesce_key === row.coalesce_key) {
const next = rows.slice(0, -1);
next.push({ ...row, key: last.key });
return next;
}
return [...rows, row];
}
export function useLiveStream(
opts: UseLiveStreamOptions = {},
): UseLiveStreamResult {
const historyUrl = opts.historyUrl ?? "events/history";
const streamUrl = opts.streamUrl ?? "events/stream";
const [rows, setRows] = useState<TermRow[]>([]);
const [hasMore, setHasMore] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
const keySeqRef = useRef(0);
function nextKey(): string {
keySeqRef.current += 1;
return "r" + keySeqRef.current;
}
function toRows(env: TermEnvelope, fromHistory: boolean): TermRow[] {
return env.msgs.map((m) => ({ ...m, key: nextKey(), fromHistory }));
}
function appendEnvelope(
rows: TermRow[],
env: TermEnvelope,
fromHistory: boolean,
): TermRow[] {
let next = rows;
for (const row of toRows(env, fromHistory)) next = appendRow(next, row);
return next;
}
const minIdRef = useRef<number | null>(null);
const liveRef = useRef(false);
const bufferedRef = useRef<TermEnvelope[]>([]);
useEffect(() => {
let cancelled = false;
function pushLive(env: TermEnvelope) {
if (env.msgs.length) setRows((prev) => appendEnvelope(prev, env, false));
}
const es = new EventSource(streamUrl);
es.onmessage = (e) => {
let env: TermEnvelope;
try {
env = JSON.parse(e.data);
} catch {
setRows((prev) =>
appendRow(prev, {
key: "parse-err-" + Date.now(),
level: "warn",
summary: "[parse err] " + e.data,
fromHistory: false,
}),
);
return;
}
if (!liveRef.current) {
bufferedRef.current.push(env);
return;
}
pushLive(env);
};
es.onerror = () => {
setRows((prev) =>
appendRow(prev, {
key: "conn-note",
level: "warn",
fromHistory: false,
coalesce_key: "conn-status",
summary:
es.readyState === 0 /* CONNECTING */
? "[reconnecting…]"
: "[disconnected]",
}),
);
};
async function backfill() {
try {
const resp = await fetch(historyUrl);
if (!resp.ok) throw new Error("http " + resp.status);
const body = await resp.json();
const events: TermEnvelope[] = Array.isArray(body)
? body
: body.events || [];
const boundarySeq: number | null = Array.isArray(body)
? null
: (body.seq ?? null);
if (!Array.isArray(body)) {
setHasMore(!!body.has_more);
if (typeof body.min_id === "number") minIdRef.current = body.min_id;
}
if (cancelled) return;
let initial: TermRow[] = [];
for (const env of events) initial = appendEnvelope(initial, env, true);
initial = events.length
? appendRow(initial, {
key: "live-sep",
level: "debug",
fromHistory: true,
summary: "─── live (older above) ───",
})
: [
{
key: "placeholder",
level: "debug",
fromHistory: true,
summary: "(connected — waiting for events)",
},
];
setRows(initial);
const drained = bufferedRef.current;
bufferedRef.current = [];
liveRef.current = true;
for (const env of drained) {
// Already covered by the initial history page — drop it from
// the buffer rather than rendering it twice.
if (
boundarySeq != null &&
typeof env.seq === "number" &&
env.seq <= boundarySeq
)
continue;
pushLive(env);
}
} catch (err) {
console.warn("history backfill failed", err);
if (cancelled) return;
const drained = bufferedRef.current;
bufferedRef.current = [];
liveRef.current = true;
for (const env of drained) pushLive(env);
}
}
backfill();
return () => {
cancelled = true;
es.close();
};
}, [historyUrl, streamUrl]);
async function loadMore() {
if (!hasMore || loadingMore || minIdRef.current == null) return;
setLoadingMore(true);
try {
const sep = historyUrl.includes("?") ? "&" : "?";
const resp = await fetch(historyUrl + sep + "before=" + minIdRef.current);
if (!resp.ok) return;
const body = await resp.json();
const events: TermEnvelope[] = Array.isArray(body)
? body
: body.events || [];
setHasMore(!!body.has_more);
if (typeof body.min_id === "number") minIdRef.current = body.min_id;
if (events.length) {
let older: TermRow[] = [];
for (const env of events) older = appendEnvelope(older, env, true);
older = appendRow(older, {
key: "older-sep-" + minIdRef.current,
level: "debug",
fromHistory: true,
summary: "─── older above ───",
});
setRows((prev) => [...older, ...prev]);
}
} catch (err) {
console.warn("loadMore failed", err);
} finally {
setLoadingMore(false);
}
}
function pushLocalNote(text: string) {
setRows((prev) =>
appendRow(prev, {
key: "local-" + nextKey(),
level: "info",
fromHistory: false,
summary: text,
}),
);
}
return { rows, hasMore, loadingMore, loadMore, pushLocalNote };
}

View file

@ -1,48 +0,0 @@
// useTodos — polls `GET /api/todos` on a light interval, same cadence
// as app.js's `setInterval(refreshTodos, 4000)`. Kept separate from
// useAgentState: todos change asynchronously (matrix syncs, bash task
// starts/completions) independent of the state snapshot, and the old
// page polled them independently too.
import { useEffect, useRef, useState } from "preact/hooks";
import type { TodoRow } from "../types.js";
const POLL_MS = 4000;
export interface UseTodosResult {
todos: TodoRow[];
refresh: () => void;
}
export function useTodos(): UseTodosResult {
const [todos, setTodos] = useState<TodoRow[]>([]);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const stoppedRef = useRef(false);
async function poll() {
try {
const resp = await fetch("api/todos");
if (!resp.ok) throw new Error(`http ${resp.status}`);
const body = (await resp.json()) as { todos?: TodoRow[] };
if (stoppedRef.current) return;
// Defensive filter: the wire type is the general `LooseEnd` tagged
// enum even though this endpoint only ever emits the `todo` variant
// today — see types.ts's TodoRow comment.
setTodos((body.todos ?? []).filter((t) => t.kind === "todo"));
} catch (err) {
console.warn("todos fetch failed", err);
if (!stoppedRef.current) setTodos([]);
}
}
useEffect(() => {
stoppedRef.current = false;
poll();
timerRef.current = setInterval(poll, POLL_MS);
return () => {
stoppedRef.current = true;
if (timerRef.current) clearInterval(timerRef.current);
};
}, []);
return { todos, refresh: poll };
}

View file

@ -1,27 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>hyperhive agent</title>
<link rel="icon" type="image/svg+xml" href="icon" />
<link rel="stylesheet" href="static/colors.css" />
<link rel="stylesheet" href="static/theme.css" />
<link rel="stylesheet" href="static/agent.css" />
<!-- main.css (bundled component CSS: Badge/Dropdown/MetaNav/
StatusChips/SidePanel/...) MUST load after agent.css —
`.meta-nav-popover`/etc. share class-selector
specificity with agent.css's legacy rules, so load order is what
decides which one wins the cascade (see the MetaNav.css
file comment). -->
<link rel="stylesheet" href="static/main.css" />
</head>
<body class="agent-shell">
<!-- The Preact rewrite owns everything below — header, terminal,
side panel. See main.tsx/Root.tsx for the component
tree; docs/4-implementation/web-ui/agent-page.md for the design. -->
<div id="preact-root"></div>
<script type="module" src="static/main.js" defer></script>
</body>
</html>

View file

@ -1,16 +0,0 @@
// Resolves the host dashboard's origin, ported unchanged from app.js's
// `setHeader` — pause/resume are host-side (hive-c0re) actions, not
// this agent's own `/api/*`, so they need the *dashboard's* origin, not
// a relative path. Behind the gateway this page lives at
// `/agent/<name>/` on the dashboard's own origin (`location.origin`);
// accessed directly, it's the same host on `dashboardPort`.
/** Whether this page is served through the gateway, on the dashboard's origin. */
export function isBehindGateway(): boolean {
return location.pathname.startsWith("/agent/");
}
export function resolveDashboardBase(dashboardPort: number): string {
return isBehindGateway()
? location.origin + "/"
: `${location.protocol}//${location.hostname}:${dashboardPort}/`;
}

Some files were not shown because too many files have changed in this diff Show more