agent: TodosPanel/InboxPanel flyouts + header pills

New Preact `SidePanel` drawer — deliberately not the shared
`<hive-side-panel>` shadow-DOM custom element, same rationale as
StatusChips' Badge/Dropdown. Drops that element's drag-to-resize +
localStorage width persistence for this first slice (fixed width via
CSS); reuses agent.css's existing `.agent-inbox`/`.inbox-*`/
`.side-panel-empty` content classes verbatim, only the drawer chrome
itself is new (SidePanel.css). Kept mounted regardless of open/closed
state (toggles the `open` prop) rather than conditionally rendered, so
the slide/fade CSS transitions actually fire on both open and close.

- InboxPanel: renders `state.inbox` (already polled by useAgentState)
  + a "mark all read" action — plain `fetch()` to the dashboard's
  `/api/agent/{name}/mark-all-read` (JSON response, same as app.js;
  unlike pause/resume this one doesn't need a form-submit workaround).
- TodosPanel: new `useTodos` hook (same 4s poll cadence as app.js's
  `refreshTodos`) + bulk select/mark-done via `api/todos/mark-done`.
- Both destructive-but-recoverable actions use a new `useConfirmClick`
  two-click-arm hook instead of the old shadow-DOM `themedConfirm`
  modal — lighter weight, no backdrop/dialog machinery needed for a
  "did you mean to click that" nudge.
- HeaderPill: the inbox/todos count triggers in the header's right
  cluster; Header.tsx gained a `pills` slot for them (mirrors the old
  markup's `.agent-header-pills` third column).
- types.ts: added `InboxRow`/`TodoRow`, mirroring
  `hive_sh4re::inbox::{InboxRow, LooseEnd}` (todo variant only —
  `/api/todos` never returns the others).

Screenshot-verified against a mock server exercising both panels.
This commit is contained in:
iris 2026-08-28 02:45:34 +02:00
commit 190d810762
10 changed files with 505 additions and 3 deletions

View file

@ -2,17 +2,25 @@
// to the real `/api/state` snapshot via `useAgentState`. Still a slice,
// not the whole page — see main.tsx's file comment for what's left
// (the live SSE stream, login flow, inbox/todos, term input, overflow).
import { useState } from 'preact/hooks';
import type { BadgeTone } from '@hive/shared/badge.js';
import { Header } from './components/Header.js';
import { StatusChips } from './components/StatusChips.js';
import { LiveStream } 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 { postModel, postEffort } from './lib/modelEffort.js';
import type { TokenUsage } from './types.js';
type OpenPanel = 'inbox' | 'todos' | null;
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' },
@ -41,11 +49,40 @@ function tokenTotal(u: TokenUsage | null): number | null {
export function Root() {
const { state, refresh } = useAgentState();
const { todos, refresh: refreshTodos } = useTodos();
const [openPanel, setOpenPanel] = useState<OpenPanel>(null);
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')} />
</>
);
// 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 (
<>
<Header label="…">
<Header label="…" pills={pills}>
<StatusChips
aliveLabel="… connecting"
aliveTone="neutral"
@ -64,6 +101,7 @@ export function Root() {
<main className="agent-main">
<LiveStream />
</main>
{panel}
</>
);
}
@ -81,7 +119,7 @@ export function Root() {
return (
<>
<Header label={state.label} hiveLabel={[state.swarm_name, state.hive_name].filter(Boolean).join(' / ') || null}>
<Header label={state.label} hiveLabel={[state.swarm_name, state.hive_name].filter(Boolean).join(' / ') || null} pills={pills}>
<StatusChips
aliveLabel={`${alive.glyph} ${alive.text}`}
aliveTone={alive.tone}
@ -109,6 +147,7 @@ export function Root() {
<main className="agent-main">
<LiveStream onLiveTurnBoundary={refresh} />
</main>
{panel}
</>
);
}

View file

@ -14,9 +14,13 @@ export interface HeaderProps {
label: string;
hiveLabel?: string | null;
children?: ComponentChildren;
/** Right-cluster flyout triggers (inbox/todos pills today, the
* overflow menu button lands here in a later commit) mirrors the
* old markup's `.agent-header-pills` third column. */
pills?: ComponentChildren;
}
export function Header({ label, hiveLabel, children }: HeaderProps) {
export function Header({ label, hiveLabel, children, pills }: HeaderProps) {
return (
<header class="agent-header">
<img class="agent-icon" src="icon" alt="" />
@ -27,6 +31,7 @@ export function Header({ label, hiveLabel, children }: HeaderProps) {
{hiveLabel ? <div class="agent-header-row agent-hive-row">{hiveLabel}</div> : null}
<div class="agent-header-row">{children}</div>
</div>
{pills ? <div class="agent-header-pills">{pills}</div> : null}
</header>
);
}

View file

@ -0,0 +1,26 @@
// <HeaderPill> — the inbox/todos flyout triggers in the header's right
// cluster. Reuses agent.css's existing `.hive-pill.header-pill…` rules
// (loaded globally) — same "layout is a like-for-like port, the
// component model is the change" approach as Header.tsx. Hidden
// (renders nothing) at count 0, matching the old page's `pill.hidden =
// count === 0`.
export interface HeaderPillProps {
kind: 'inbox' | 'todos';
icon: string;
label: string;
count: number;
onClick: () => void;
}
export function HeaderPill({ kind, icon, label, count, onClick }: HeaderPillProps) {
if (count === 0) return null;
return (
<button type="button" class={`hive-pill header-pill header-pill-${kind}`} onClick={onClick} title={`open ${label} flyout`}>
<span class="header-pill-icon" aria-hidden="true">
{icon}
</span>
<span class="header-pill-label">{label}</span>
<span class="header-pill-count">{count}</span>
</button>
);
}

View file

@ -0,0 +1,86 @@
// <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

@ -0,0 +1,80 @@
/* 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

@ -0,0 +1,55 @@
// <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" />
<aside
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>
</aside>
</>
);
}

View file

@ -0,0 +1,104 @@
// <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

@ -0,0 +1,48 @@
// 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

@ -0,0 +1,35 @@
// Lightweight two-click confirm for a destructive-but-recoverable button
// ("mark all read", "mark done") — deliberately NOT the old modal system
// (@hive/shared/modal.js's `themedConfirm`, itself built on the
// shadow-DOM `<hive-dialog>` custom element): a full backdrop+dialog is
// more machinery than a "did you mean to click that" nudge needs, and
// mara's ask for this rewrite was real Preact components, not a port of
// the old widget family. First click arms the button (caller renders a
// distinct "sure? click again" label off `armed`); a second click within
// `resetMs` fires `onConfirm`; anything else (timeout, blur) disarms.
import { useEffect, useRef, useState } from 'preact/hooks';
export function useConfirmClick(onConfirm: () => void, resetMs = 2500) {
const [armed, setArmed] = useState(false);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(
() => () => {
if (timerRef.current) clearTimeout(timerRef.current);
},
[],
);
function trigger() {
if (armed) {
if (timerRef.current) clearTimeout(timerRef.current);
setArmed(false);
onConfirm();
return;
}
setArmed(true);
timerRef.current = setTimeout(() => setArmed(false), resetMs);
}
return { armed, trigger };
}

View file

@ -22,6 +22,7 @@ export interface AgentState {
effort: string;
available_efforts: string[];
paused: boolean;
inbox: InboxRow[];
}
export interface TokenUsage {
@ -30,3 +31,26 @@ export interface TokenUsage {
cache_read_input_tokens?: number;
cache_creation_input_tokens?: number;
}
// Mirrors `hive_sh4re::inbox::InboxRow` — the last N messages addressed
// to this agent, newest-first.
export interface InboxRow {
id: number;
from: string;
body: string;
at: number;
in_reply_to?: number | null;
}
// Mirrors the `kind: "todo"` variant of `hive_sh4re::inbox::LooseEnd` —
// the only variant `GET /api/todos` actually returns (a dynamic,
// subsystem-pushed todo: matrix/bash/forge are the built-in producers).
export interface TodoRow {
kind: 'todo';
id: number;
subsystem: string;
subsystem_key?: string | null;
summary: string;
source?: string | null;
age_seconds: number;
}