Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.
Python ai-agentsaiopsdashboarddockerfastapihomelabincident-managementllmmonitoringopenaireactroot-cause-analysisself-hosteduptime-monitoring
feat(frontend): phone and tablet layouts from design/mobile
karloks2005a8e13307a470
diff --git a/ODSTUPANJA.md b/ODSTUPANJA.mdindex ee5c020..a617d32 100644--- a/ODSTUPANJA.md+++ b/ODSTUPANJA.md@@ -3,7 +3,7 @@Popis svega što se u implementaciji redizajna razlikuje od PDF-ova u `design/web/` i `design/mobile/`,s razlogom i, gdje postoji, GitHub issueom. Stanje: 14. 10. 2026.-Mobilni prikazi nisu odstupanja nego preostali posao; popisani su na kraju.+Mobilni prikazi (`design/mobile/`) napravljeni su 14. 10. 2026; njihova odstupanja su u odjeljku „Mobitel i tablet".Narančasti brojevi u krugovima, oznake „STATE 1", „LOGIN · A" i blokovi „What changed" u PDF-ovimasu anotacije dizajna i namjerno nisu ugrađeni.@@ -136,9 +136,28 @@ su anotacije dizajna i namjerno nisu ugrađeni.| Database: putanja, rast po tjednu, „Last backup", „Export", „Back up now" | Veličina baze i broj zapisa; gumbi su onemogućeni | Backup ne postoji | – || About: „built 2 Oct 2026" | Samo verzija | Datum builda se ne bilježi | #106 |-## Još nije napravljeno+## Mobitel i tablet (`design/mobile/`)-| Što | Dizajn | Issue |-| --- | --- | --- |-| Mobilni prikazi (osim prijave) | `design/mobile/` | #98 |-| Provjera na pravom stacku s pravim podacima | – | #107 |+| Dizajn | Implementacija | Razlog | Issue |+| --- | --- | --- | --- |+| Overview: ploča „Agent" s bilješkom nije na mobitelu | Kartica incidenta nema agentovu bilješku | Dizajn je na mobitelu ne prikazuje; bilješka je na ekranu incidenta | – |+| Server: graf „Disk" uz CPU, Memory i Load | Disk crta najpuniji disk iz povijesti diska (1 h ili 6 h), ne iz živih uzoraka | Živi uzorci nemaju disk | – |+| Server: tabovi Network, System i Events nisu nacrtani za mobitel | Desktopni sadržaj u jednom stupcu; tablica portova postaje kartice, tablica diskova se pomiče vodoravno | Za te tabove nema mobilnog dizajna | – |+| Kontejner u sheetu: gumbi Logs i Restart | Prikazani, ali onemogućeni, s objašnjenjem ispod | Isto kao na desktopu | #100 |+| Statistics: Timeline je zaseban ekran, ulaz nije nacrtan | Na glavnom ekranu je kartica „Timeline" s gumbom „Open timeline"; „Show on timeline" otvara ekran na tom trenutku | Dizajn ne kaže kako se dolazi do ekrana B | – |+| Statistics: „Time spent at each level" nije na mobitelu | Prikazano ispod „When it's busy" | Dizajn kaže „Same data as desktop" | – |+| Statistics: legenda „This week / Last week" | „Last 7 days / The previous 7 days" | Isti tekst kao na desktopu | – |+| Agent: „Show 5 log lines" | „Show N recorded events" | Infradeck ne čita logove kontejnera, nego bilježi događaje | #100 |+| Agent: „Push alerts are on · Critical only between 23:00 and 07:00" | Redak „Where alerts go" vodi u Account | Infradeck nema push obavijesti na mobitel (nema aplikacije ni Web Pusha) | #50 |+| Agent chat: oznake izvora ispod odgovora | Običan tekst | Model ne vraća izvore | #93 |+| More: „Owner" | Owner za admine, Member za ostale | Ne postoji uloga vlasnika | #106 |+| Security: redovi s strelicom i prekidačem za 2FA | Isti redovi kao na desktopu (gumbi „Change password", „Set up") | Postupci traže lozinku i kod, pa ostaju gumbi | – |+| Sessions: lokacija i „via WireGuard" | Adresa i vrijeme prijave | Nema geolokacije | – |+| Notifications: kanal „This iPhone · Push" | Nema | Nema push obavijesti | #50 |+| Notifications: redovi „Weekly report" i „Email digest 08:00" | Jedna rečenica da još ne postoje | Ne postoje | #33 |+| Admin: „Infradeck 0.9.3 is out" | Nema; hub prikazuje strojeve koji čekaju | Infradeck ne zove van | – |+| Admin: „Incident agent · $1.84 of $10" | „chat on/off" ili „no key" | Potrošnja se ne mjeri | #91 |+| Admin: Connect a server u tri numerirana koraka | Ista kartica kao na desktopu, uz Copy i Share ispod naredbe | Jedna implementacija | – |+| Admin: „You'll get a push when it connects" | Nema | Nema push obavijesti | #50 |+| Alert rules: „+" za novo pravilo | Nema | Vlastita pravila ne postoje | – |+| Tablet: Agent skriva chat iza gumba | Na tabletu su popis, incident i chat jedan ispod drugoga | Tri stupca ostaju od 1200 px; ispod toga slažu se okomito | – |diff --git a/src/frontend/src/App.jsx b/src/frontend/src/App.jsxindex c878c50..c28e72b 100644--- a/src/frontend/src/App.jsx+++ b/src/frontend/src/App.jsx@@ -2,6 +2,7 @@ import { BrowserRouter, Navigate, Route, Routes, useLocation } from 'react-routeimport { useEffect, useState } from 'react'import AccountPage from './account/AccountPage.jsx'import AdminPage from './admin/AdminPage.jsx'+import MorePage from './more/MorePage.jsx'import AgentPage from './agent/AgentPage.jsx'import { apiRequest } from './api.js'import { LoginPage, RegisterPage } from './auth/AuthPages.jsx'@@ -85,6 +86,7 @@ function App() {<Route path="/agent" element={page(<AgentPage user={user} onLogout={handleLogout} />)} /><Route path="/reports" element={page(<Navigate to="/agent" replace />)} /><Route path="/logs" element={page(<Navigate to="/agent" replace />)} />+ <Route path="/more" element={page(<MorePage user={user} onLogout={handleLogout} />)} /><Route path="/account" element={page(<AccountPage user={user} onLogout={handleLogout} onUserChange={(patch) => setUser((current) => (current ? { ...current, ...patch } : current))} />)} /><Route path="/admin" element={page(user?.role === 'admin' ? <AdminPage user={user} onLogout={handleLogout} /> : <Navigate to="/" replace />)} /></Routes>diff --git a/src/frontend/src/account/AccountPage.jsx b/src/frontend/src/account/AccountPage.jsxindex f65290b..37ab098 100644--- a/src/frontend/src/account/AccountPage.jsx+++ b/src/frontend/src/account/AccountPage.jsx@@ -6,7 +6,8 @@ import { MIN_PASSWORD_LENGTH } from '../auth/AuthPages.jsx'import { Icon } from '../icons.jsx'import { applyDisplay } from '../prefs.js'import { AppShell } from '../shell.jsx'-import { Check, Field, Notice, Outcome, Row, Section, SettingsLayout, ShownOnce, Switch, ago, describeBrowser, formatDate, useAction, useCopy, useLoaded } from '../ui.jsx'+import { ACCOUNT_GROUPS } from '../more/groups.js'+import { Check, Field, Notice, Outcome, Row, Section, SettingsLayout, ShownOnce, Switch, ago, describeBrowser, formatDate, useAction, useCopy, useLoaded, usePhone } from '../ui.jsx'const COLORS = ['', '#FF5A1F', '#E2B04A', '#6DBE8F', '#7FA7D9', '#B58BD6', '#D98BA4']const post = (path, body) => apiRequest(path, { method: 'POST', body: JSON.stringify(body || {}) })@@ -180,7 +181,30 @@ function Sessions({ days, onCount }) {const { data, error, reload } = useLoaded('/auth/sessions')const [state, run] = useAction()const sessions = data?.sessions+ const phone = usePhone()useEffect(() => { if (sessions) onCount(sessions.length) }, [sessions, onCount])+ const signOut = (session) => run(async () => { await apiRequest(`/auth/sessions/${session.id}`, { method: 'DELETE' }); reload() })+ const signOutOthers = () => run(async () => { const result = await post('/auth/sessions/revoke-others'); reload(); return result }, 'Signed out everywhere else.')+ if (phone) {+ return (+ <div className="space-y-3">+ <div className="divide-y divide-line overflow-hidden rounded-md border border-line bg-ink">+ {(sessions || []).map((session) => (+ <div key={session.id} className="flex items-center gap-3 px-4 py-3">+ <span className="min-w-0 flex-1">+ <span className="flex items-center gap-2"><span className="truncate text-[15px] text-paper">{describeBrowser(session.user_agent)}</span>{session.current && <span className="chip shrink-0">this device</span>}</span>+ <span className="mt-0.5 block truncate text-xs text-muted">{[session.ip || 'unknown address', session.created_at ? ago(session.created_at) : 'earlier'].join(' · ')}</span>+ </span>+ {!session.current && <button type="button" className="h-10 shrink-0 border-0 bg-transparent px-1 text-[13px] text-soft" disabled={state.busy} onClick={() => signOut(session)}>Sign out</button>}+ </div>+ ))}+ {!sessions && <p className="m-0 px-4 py-5 text-center text-xs text-muted">{error || 'Loading…'}</p>}+ </div>+ {sessions?.length > 1 && <button type="button" className="h-12 w-full rounded-md border border-signal/50 bg-transparent text-sm font-medium text-signal" disabled={state.busy} onClick={signOutOthers}>Sign out all other devices</button>}+ <p className="m-0 text-xs leading-5 text-muted">A session lasts a day, or {days} days if you ticked “Keep me signed in”. <Outcome state={state} /></p>+ </div>+ )+ }return (<div className="card overflow-hidden"><div className="custom-scroll overflow-x-auto"><table className="w-full min-w-[560px] border-collapse text-left text-[13px]">@@ -213,9 +237,17 @@ function Tokens({ account, reload }) {const canWrite = account.role === 'admin'const create = (event) => { event.preventDefault(); run(async () => { setCreated(await post('/account/tokens', { name: form.name, scope: form.scope, expires_in_days: form.expires_in_days ? Number(form.expires_in_days) : null })); setAdding(false); setForm({ name: '', scope: 'read', expires_in_days: '' }); reload() }) }const expires = (token) => { if (!token.expires_at) return 'never'; const days = Math.ceil((new Date(token.expires_at).getTime() - Date.now()) / 86400000); return days <= 0 ? 'expired' : `in ${days} ${days === 1 ? 'day' : 'days'}` }+ const phone = usePhone()+ const revoke = (token) => { if (window.confirm(`Revoke the token “${token.name}”? Whatever uses it stops working at once.`)) run(async () => { await apiRequest(`/account/tokens/${token.id}`, { method: 'DELETE' }); reload() }) }return (<div className="card overflow-hidden">- {account.tokens.length > 0 && <div className="custom-scroll overflow-x-auto"><table className="w-full min-w-[620px] border-collapse text-left text-[13px]">+ {phone && account.tokens.length > 0 && <div className="divide-y divide-line">{account.tokens.map((token) => (+ <div key={token.id} className="flex items-center gap-3 px-4 py-3">+ <span className="min-w-0 flex-1"><span className="block truncate text-[15px] text-paper">{token.name}</span><span className="mt-0.5 block truncate text-xs text-muted">{token.scope === 'write' ? 'read + acknowledge' : 'read · metrics'} · used {ago(token.last_used_at)} · expires {expires(token)}</span></span>+ <button type="button" className="h-10 shrink-0 border-0 bg-transparent px-1 text-[13px] text-soft" onClick={() => revoke(token)}>Revoke</button>+ </div>+ ))}</div>}+ {!phone && account.tokens.length > 0 && <div className="custom-scroll overflow-x-auto"><table className="w-full min-w-[620px] border-collapse text-left text-[13px]"><thead><tr className="grid-head h-10"><th className="pl-[18px] font-medium">Name</th><th className="font-medium">Scope</th><th className="font-medium">Last used</th><th className="font-medium">Expires</th><th className="pr-[18px]" /></tr></thead><tbody>{account.tokens.map((token) => (<tr key={token.id} className="h-[54px] border-t border-line">@@ -223,7 +255,7 @@ function Tokens({ account, reload }) {<td><span className={`chip ${token.scope === 'write' ? 'chip-warn' : ''}`}>{token.scope === 'write' ? 'read + acknowledge' : 'read · metrics'}</span></td><td className="text-soft">{ago(token.last_used_at)}</td><td className={expires(token) === 'expired' ? 'text-warn' : 'text-soft'}>{expires(token)}</td>- <td className="pr-[18px] text-right"><button type="button" className="link" onClick={() => { if (window.confirm(`Revoke the token “${token.name}”? Whatever uses it stops working at once.`)) run(async () => { await apiRequest(`/account/tokens/${token.id}`, { method: 'DELETE' }); reload() }) }}>Revoke</button></td>+ <td className="pr-[18px] text-right"><button type="button" className="link" onClick={() => revoke(token)}>Revoke</button></td></tr>))}</tbody></table></div>}@@ -264,6 +296,7 @@ function Notifications({ account, reload, onPreferences }) {const add = (event) => { event.preventDefault(); run(async () => { await post('/account/channels', form.kind === 'email' ? { kind: 'email' } : form); setAdding(false); setForm({ kind: 'ntfy', target: '' }); reload() }) }const status = (channel) => (channel.last_ok == null ? ['Not tested', ''] : channel.last_ok ? ['Working', 'chip-ok'] : [`Failed ${ago(channel.last_checked_at)} · ${channel.last_status}`, 'chip-warn'])const zone = prefs.display.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone+ const phone = usePhone()return <>{!account.secrets_configured && <Notice>Channels can't be saved on this server yet: it has no <span className="mono">SECRETS_KEY</span> to encrypt their addresses with (see docs/accounts.md).</Notice>}<div className="card divide-y divide-line overflow-hidden">@@ -288,7 +321,19 @@ function Notifications({ account, reload, onPreferences }) {{!adding && <button type="button" className="btn btn-sm" onClick={() => setAdding(true)}><Icon name="plus" size={13} />Add channel</button>}</div></div>- {account.channels.length > 0 && (+ {/* Phones: severity × channel doesn't fit as a grid, so each severity gets a row of on/off chips. */}+ {phone && account.channels.length > 0 && (+ <div className="card divide-y divide-line overflow-hidden">+ {EVENTS.map(([key, label, dot]) => (+ <div key={key} className="px-4 py-3">+ <div className="flex items-center gap-2 text-sm text-paper"><span className={`dot ${dot}`} style={{ width: 7, height: 7 }} />{label}</div>+ <div className="mt-2.5 flex flex-wrap gap-2">{account.channels.map((channel) => { const on = routed(key, channel); return <button key={channel.id} type="button" aria-pressed={on} disabled={state.busy} onClick={() => route(key, channel, !on)} className={`h-9 rounded-full border px-3.5 text-[13px] font-medium ${on ? 'border-paper bg-paper text-bg' : 'border-edge bg-transparent text-muted'}`}>{CHANNELS[channel.kind][1].replace(' webhook', '')}</button> })}</div>+ </div>+ ))}+ <p className="m-0 px-4 py-3 text-xs text-muted">Agent diagnosis ready, a daily digest and a weekly report are not available yet.</p>+ </div>+ )}+ {!phone && account.channels.length > 0 && (<div className="card overflow-hidden"><div className="custom-scroll overflow-x-auto"><table className="w-full border-collapse text-left text-[13px]"><thead><tr className="grid-head h-10"><th className="pl-[18px] font-medium">Send</th>{account.channels.map((channel) => <th key={channel.id} className="w-[110px] px-2 text-center font-medium">{CHANNELS[channel.kind][1].replace(' webhook', '')}</th>)}</tr></thead><tbody>@@ -367,8 +412,8 @@ export default function AccountPage({ user, onLogout, onUserChange }) {const sections = [{ id: 'profile', label: 'Profile' }, { id: 'security', label: 'Security' }, { id: 'sessions', label: 'Sessions', count: sessionCount }, { id: 'tokens', label: 'API tokens', count: account?.tokens.length || null }, { id: 'notifications', label: 'Notifications' }, { id: 'display', label: 'Display' }]return (- <AppShell user={user} onLogout={onLogout} bare>- <SettingsLayout title="Account" description="Your sign-in, where alerts reach you, and how Infradeck looks for you. Server-wide settings live in Admin." sections={sections}+ <AppShell user={user} onLogout={onLogout} bare phoneHeader>+ <SettingsLayout groups={ACCOUNT_GROUPS} title="Account" description="Your sign-in, where alerts reach you, and how Infradeck looks for you. Server-wide settings live in Admin." sections={sections}footer={<button type="button" onClick={onLogout} className="flex h-[31px] w-full items-center rounded-md border-0 bg-transparent px-2.5 text-left text-[13px] text-muted hover:bg-ink hover:text-paper">Sign out</button>}>{(error || status.error) && !account && <Notice>{error || status.error}</Notice>}{!account && !error && <p className="m-0 py-16 text-center text-[13px] text-muted">Loading your account…</p>}@@ -379,7 +424,6 @@ export default function AccountPage({ user, onLogout, onUserChange }) {<Section id="tokens" title="API tokens" description="For scripts, Home Assistant or a status page. Tokens act as you, limited to the scope you pick."><Tokens account={account} reload={reload} /></Section><Section id="notifications" title="Notifications" description="Where your alerts go and how loud they are. Critical alerts ignore quiet hours."><Notifications account={account} reload={reload} onPreferences={setPreferences} /></Section><Section id="display" title="Display" description="Only affects how you see Infradeck."><Display account={account} onPreferences={setPreferences} /></Section>- <button type="button" onClick={onLogout} className="btn lg:hidden">Sign out</button></>}</SettingsLayout></AppShell>diff --git a/src/frontend/src/admin/AdminPage.jsx b/src/frontend/src/admin/AdminPage.jsxindex 6c283b0..97fd0af 100644--- a/src/frontend/src/admin/AdminPage.jsx+++ b/src/frontend/src/admin/AdminPage.jsx@@ -1,14 +1,16 @@// Settings for this Infradeck instance and everyone who uses it: servers, users, alert rules, the incident// agent, how long data is kept, and what version this is.import { useEffect, useState } from 'react'+import { Link } from 'react-router-dom'import { apiRequest } from '../api.js'import { AnotherMachineCard, ThisMachineCard } from '../dashboard/EmptyFleet.jsx'import { INTERVALS, intervalLabel } from '../dashboard/ServerPanel.jsx'import { serverState } from '../dashboard/logic.js'import { Icon } from '../icons.jsx'import { refreshOverview, useOverview } from '../overviewStore.js'-import { AppShell } from '../shell.jsx'-import { Field, Notice, Outcome, Row, Section, SettingsLayout, ShownOnce, Switch, ago, useAction, useLoaded } from '../ui.jsx'+import { AppShell, serverLink } from '../shell.jsx'+import { ADMIN_GROUPS } from '../more/groups.js'+import { Field, Notice, Outcome, Row, Section, SettingsLayout, ShownOnce, Switch, ago, useAction, useLoaded, usePhone } from '../ui.jsx'const REPOSITORY = 'https://github.com/karloks2005/Infradeck'const STATE_DOT = { critical: 'dot-signal', warn: 'dot-warn', ok: 'dot-ok', offline: '' }@@ -179,6 +181,7 @@ function Users({ me }) {}function Rules({ onCount }) {+ const phone = usePhone()const { data, error, reload } = useLoaded('/admin/rules')const [state, run] = useAction()const [editing, setEditing] = useState(null)@@ -190,6 +193,33 @@ function Rules({ onCount }) {const open = (rule) => { setEditing(editing === rule.kind ? null : rule.kind); setValues(Object.fromEntries(rule.edit.map((key) => [key, data.thresholds[key]]))) }const save = (event) => { event.preventDefault(); run(async () => { await put({ alert_thresholds: Object.fromEntries(Object.entries(values).map(([key, value]) => [key, Number(value)])) }); setEditing(null); reload() }) }const off = data.rules.filter((rule) => !rule.enabled)+ const editor = (rule) => editing === rule.kind && <form onSubmit={save} className="my-2.5 flex flex-wrap items-end gap-2.5">+ {rule.edit.map((key) => <Field key={key} label={THRESHOLD_LABELS[key] || key}><input type="number" step="any" className="field h-9 w-28" required value={values[key] ?? ''} onChange={(event) => setValues({ ...values, [key]: event.target.value })} /></Field>)}+ <button type="submit" className="btn btn-sm h-9 btn-primary" disabled={state.busy}>Save</button>+ </form>+ // Phones: each rule as one sentence with its severity, how often it fired, and a large switch.+ if (phone) {+ return (+ <div className="space-y-3">+ <div className="divide-y divide-line overflow-hidden rounded-md border border-line bg-ink">+ {data.rules.map((rule) => (+ <div key={rule.kind} className="px-4 py-3">+ <div className="flex items-center gap-3">+ <span className="min-w-0 flex-1">+ <span className={`block text-[15px] leading-5 ${rule.enabled ? 'text-paper' : 'text-soft'}`}>{rule.when}{rule.window && rule.window !== 'n/a' ? ` · ${rule.window}` : ''}</span>+ <span className="mt-1 flex items-center gap-1.5 text-xs text-muted"><span className={`dot ${rule.enabled ? { CRITICAL: 'dot-signal', WARNING: 'dot-warn', INFO: '' }[rule.severity] : ''}`} style={{ width: 6, height: 6 }} />{rule.enabled ? SEVERITY[rule.severity][0] : 'Off'} · {rule.enabled ? `fired ${rule.fired}× in 30 d` : `would have fired ${rule.fired}×`}{rule.noisy && <span className="text-warn"> · noisy</span>}</span>+ {rule.edit.length > 0 && <button type="button" className="mt-1.5 h-7 border-0 bg-transparent p-0 text-xs text-soft underline" aria-expanded={editing === rule.kind} onClick={() => open(rule)}>{editing === rule.kind ? 'Close' : 'Change thresholds'}</button>}+ </span>+ <span className="origin-right scale-125"><Switch label={rule.when} checked={rule.enabled} disabled={state.busy} onChange={(on) => toggle(rule, on)} /></span>+ </div>+ {editor(rule)}+ </div>+ ))}+ </div>+ <p className="m-0 text-xs leading-5 text-muted">{off.length ? `${off.length} ${off.length === 1 ? 'rule is' : 'rules are'} switched off and open no incidents.` : 'Every rule is on.'} A rule that is switched off also closes the incidents it had open. Rules of your own are not built yet. <Outcome state={state} /></p>+ </div>+ )+ }return (<div className="card overflow-hidden"><div className="custom-scroll overflow-x-auto"><table className="w-full min-w-[760px] border-collapse text-left text-[13px]">@@ -200,10 +230,7 @@ function Rules({ onCount }) {<td className="h-[46px] pl-[18px]"><Switch label={rule.when} checked={rule.enabled} disabled={state.busy} onChange={(on) => toggle(rule, on)} /></td><td className={rule.enabled ? 'text-paper' : ''}>{rule.when}{rule.edit.length > 0 && <button type="button" className="link ml-3 text-xs" aria-expanded={editing === rule.kind} onClick={() => open(rule)}>{editing === rule.kind ? 'close' : 'change'}</button>}- {editing === rule.kind && <form onSubmit={save} className="my-2.5 flex flex-wrap items-end gap-2.5">- {rule.edit.map((key) => <Field key={key} label={THRESHOLD_LABELS[key] || key}><input type="number" step="any" className="field h-8 w-28" required value={values[key] ?? ''} onChange={(event) => setValues({ ...values, [key]: event.target.value })} /></Field>)}- <button type="submit" className="btn btn-sm btn-primary" disabled={state.busy}>Save</button>- </form>}+ {editor(rule)}</td><td className={rule.enabled ? 'text-soft' : ''}>{rule.window || 'n/a'}</td><td><span className={`chip ${rule.enabled ? SEVERITY[rule.severity][1] : ''}`}>{SEVERITY[rule.severity][0]}</span></td>@@ -302,6 +329,50 @@ function About({ settings, system, onSaved }) {)}+// The phone's Admin screen: servers first with their status in each subtitle, then the instance settings as rows.+function PhoneHub({ overview, settings, system }) {+ const { data: users } = useLoaded('/admin/users')+ const { data: rules } = useLoaded('/admin/rules')+ useEffect(() => { if (window.location.hash === '#instance') requestAnimationFrame(() => document.getElementById('instance')?.scrollIntoView({ block: 'start' })) }, [])+ if (!overview || !settings || !system) return <p className="m-0 py-16 text-center text-[13px] text-muted">Loading…</p>+ const row = (to, title, detail, value, dot, tone) => (+ <Link key={to + title} to={to} className="flex min-h-14 items-center gap-3 px-4 py-2.5">+ {dot !== undefined && <span className={`dot shrink-0 ${dot}`} />}+ <span className="min-w-0 flex-1"><span className="block truncate text-[15px] text-paper">{title}</span>{detail && <span className="mt-0.5 block truncate text-xs text-muted">{detail}</span>}</span>+ {value != null && <span className={`shrink-0 text-[13px] ${tone === 'warn' ? 'text-warn' : 'text-muted'}`}>{value}</span>}+ <Icon name="chevron" size={14} className="shrink-0 text-muted" />+ </Link>+ )+ const waiting = (overview.pending_collectors || []).filter((item) => item.status === 'pending').length+ const invited = users ? (users.invites || []).length : 0+ const on = rules ? rules.rules.filter((rule) => rule.enabled).length : null+ return <>+ {waiting > 0 && <Link to="/admin?section=connect" className="flex items-center gap-3 rounded-md border border-warn/40 px-4 py-3"><span className="dot dot-warn shrink-0" /><span className="min-w-0 flex-1 text-[13px] text-paper">{waiting} {waiting === 1 ? 'machine is' : 'machines are'} asking to join</span><Icon name="chevron" size={14} className="text-muted" /></Link>}+ <section aria-label="Servers">+ <div className="mb-2.5 flex items-baseline gap-2"><h2 className="m-0 text-[15px] font-semibold text-paper">Servers</h2><span className="text-xs text-muted">{overview.servers.length}</span><Link to="/admin?section=connect" className="ml-auto inline-flex h-7 items-center text-[13px] text-soft">Add</Link></div>+ <div className="divide-y divide-line overflow-hidden rounded-md border border-line bg-ink">+ {overview.servers.map((server) => {+ const version = server.system?.collector_version+ const detail = [server.ip_address, version ? `collector ${version}` : 'older collector', `every ${intervalLabel(server.check_interval_seconds)}`, server.system?.helper_installed ? null : 'no helper'].filter(Boolean).join(' · ')+ return row(serverLink(server.id, 'system'), server.hostname, detail, null, STATE_DOT[serverState(server)])+ })}+ {!overview.servers.length && <p className="m-0 px-4 py-4 text-[13px] text-muted">No servers yet.</p>}+ </div>+ <Link to="/admin?section=servers" className="mt-2 inline-flex h-9 items-center text-[13px] text-soft">Rename, interval or remove →</Link>+ </section>+ <section id="instance" aria-label="Instance" className="scroll-mt-4">+ <h2 className="m-0 mb-2.5 text-[15px] font-semibold text-paper">Instance</h2>+ <div className="divide-y divide-line overflow-hidden rounded-md border border-line bg-ink">+ {row('/admin?section=users', 'Users', null, users ? `${users.users.length}${invited ? ` · ${invited} invited` : ''}` : null)}+ {row('/admin?section=rules', 'Alert rules', null, rules ? `${on} on · ${rules.rules.length - on} off` : null)}+ {row('/admin?section=agent', 'Incident agent', null, system.agent.key_configured ? (settings.agent_chat_enabled ? 'chat on' : 'chat off') : 'no key', undefined, system.agent.key_configured ? undefined : 'warn')}+ {row('/admin?section=retention', 'Data and retention', null, megabytes(system.database.bytes))}+ {row('/admin?section=about', 'About', null, system.version)}+ </div>+ </section>+ </>+}+export default function AdminPage({ user, onLogout }) {const { data: overview } = useOverview(Boolean(user), 15, onLogout)const settings = useLoaded('/admin/settings')@@ -311,8 +382,9 @@ export default function AdminPage({ user, onLogout }) {const sections = [{ id: 'servers', label: 'Servers', count: overview?.servers.length ?? null }, { id: 'connect', label: 'Connect a server' }, { id: 'users', label: 'Users' }, { id: 'rules', label: 'Alert rules', count: ruleCount }, { id: 'agent', label: 'Incident agent' }, { id: 'retention', label: 'Data & retention' }, { id: 'about', label: 'About' }]const ready = overview && settings.data && system.datareturn (- <AppShell user={user} onLogout={onLogout} crumbs={[{ label: 'Admin' }]} bare>- <SettingsLayout title="Admin" description="Settings for this Infradeck instance and everyone who uses it." sections={sections}>+ <AppShell user={user} onLogout={onLogout} crumbs={[{ label: 'Admin' }]} bare phoneHeader>+ <SettingsLayout title="Admin" description="Settings for this Infradeck instance and everyone who uses it." sections={sections} groups={ADMIN_GROUPS}+ phoneHub={<PhoneHub overview={overview} settings={settings.data} system={system.data} />} phoneBack={{ label: 'Admin', to: '/admin' }}>{(settings.error || system.error) && !ready && <Notice>{settings.error || system.error}</Notice>}{!ready && !settings.error && !system.error && <p className="m-0 py-16 text-center text-[13px] text-muted">Loading…</p>}{ready && <>diff --git a/src/frontend/src/agent/AgentPage.jsx b/src/frontend/src/agent/AgentPage.jsxindex cb7cd62..8f1b7e8 100644--- a/src/frontend/src/agent/AgentPage.jsx+++ b/src/frontend/src/agent/AgentPage.jsx@@ -7,8 +7,8 @@ import { usePolled } from '../dashboard/data.js'import { formatAge, niceCeiling } from '../dashboard/logic.js'import { Icon } from '../icons.jsx'import { refreshOverview } from '../overviewStore.js'-import { serverLink, AppShell } from '../shell.jsx'-import { Notice, useAction, useCopy } from '../ui.jsx'+import { serverLink, AppShell, PhoneHeader, RoundButton } from '../shell.jsx'+import { Notice, Outcome, Sheet, useAction, useCopy, usePhone } from '../ui.jsx'const SEVERITY = { CRITICAL: ['Critical', 'chip-signal', 'var(--color-signal)'], WARNING: ['Warning', 'chip-warn', 'var(--color-warn)'], INFO: ['Info', '', 'var(--color-edge)'] }const TONE = { signal: 'bg-signal', warn: 'bg-warn', ok: 'bg-ok', plain: 'bg-dim' }@@ -160,7 +160,7 @@ function Incident({ incident, canAct, onChanged }) {const SUGGESTIONS = { default: ['Is anything else close to its limit?', 'What changed on this server today?', 'Explain this incident in one paragraph'], none: ['Is anything close to its limit?', 'Which server needs attention first?', 'What happened overnight?'] }-function Chat({ user, incident, enabled }) {+function Chat({ user, incident, enabled, phone = false, back }) {const conversationId = `${incident ? `incident-${incident.id}` : 'general'}-u${user.id}`const [messages, setMessages] = useState(null)const [draft, setDraft] = useState('')@@ -198,6 +198,33 @@ function Chat({ user, incident, enabled }) {exists.current = false; setMessages([]); setError('')}+ const agentMark = <span aria-hidden="true" className="inline-flex flex-col gap-[2px]"><i className="block h-[3px] w-[5px] bg-paper" /><i className="ml-[2px] block h-[3px] w-[5px] bg-signal" /><i className="block h-[3px] w-[5px] bg-paper" /></span>+ if (phone) {+ // Full screen, scoped to the incident: suggested questions sit above the input so the keyboard is rarely needed.+ return <>+ <PhoneHeader back={back} title="Ask the agent" action={incident ? <span className="chip mono shrink-0 text-paper">{incident.reference}</span> : <button type="button" className="h-11 border-0 bg-transparent px-1 text-[13px] text-muted" onClick={restart}>New chat</button>} />+ <div className="space-y-5 px-4 pb-[190px] pt-4" aria-live="polite">+ {!enabled && <Notice tone="plain">Chat with the agent has been turned off by an admin.</Notice>}+ {enabled && messages === null && <p className="m-0 text-xs text-muted">Loading…</p>}+ {enabled && messages?.length === 0 && <p className="m-0 text-[13px] leading-5 text-muted">{incident ? 'The agent is given this incident\'s facts with your question.' : 'Ask about any server.'}</p>}+ {enabled && (messages || []).map((message) => (message.role === 'user'+ ? <div key={message.id} className="ml-10 rounded-lg border border-line bg-ink px-4 py-3 text-sm leading-[21px] text-paper">{message.text}</div>+ : <div key={message.id}><div className="mb-2 flex items-center gap-2 text-xs text-muted">{agentMark}Agent</div><p className="m-0 whitespace-pre-wrap text-sm leading-[23px] text-paper">{message.text}</p></div>))}+ {busy && <p className="m-0 flex items-center gap-2.5 text-xs text-muted"><span className="spinner" />Thinking…</p>}+ {error && <Notice>{error}</Notice>}+ <div ref={end} />+ </div>+ <form className="fixed inset-x-0 bottom-0 z-30 border-t border-line bg-bg pb-[calc(10px+env(safe-area-inset-bottom))] pt-3" onSubmit={(event) => { event.preventDefault(); send(draft) }}>+ {enabled && <div className="no-scrollbar flex gap-2 overflow-x-auto px-4 pb-2.5">{(incident ? SUGGESTIONS.default : SUGGESTIONS.none).map((text) => <button key={text} type="button" disabled={busy} className="h-9 shrink-0 rounded-full border border-edge bg-transparent px-3.5 text-[13px] text-soft" onClick={() => send(text)}>{text}</button>)}</div>}+ <div className="mx-4 flex items-center gap-2 rounded-full border border-edge bg-ink py-1 pl-4 pr-1 focus-within:border-muted">+ <input className="h-10 min-w-0 flex-1 border-0 bg-transparent text-sm text-paper outline-none placeholder:text-dim" placeholder={incident ? 'Ask about this incident…' : 'Ask about any server…'} aria-label="Your question" maxLength={8000} disabled={!enabled} value={draft} onChange={(event) => setDraft(event.target.value)} />+ <button type="submit" className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full border-0 bg-paper text-bg disabled:opacity-40" aria-label="Send" disabled={!enabled || busy || !draft.trim()}><Icon name="arrow" size={15} /></button>+ </div>+ <p className="mx-4 mb-0 mt-2 text-center text-[11px] leading-4 text-muted">Reads metrics and events. Can't run commands.</p>+ </form>+ </>+ }+return (<aside className="flex min-h-[420px] flex-col xl:h-full xl:min-h-0" aria-label="Ask the agent"><div className="border-b border-line px-5 py-4">@@ -229,14 +256,144 @@ function Chat({ user, incident, enabled }) {)}+// ---------- phones ----------++const MUTE_OPTIONS = [[60, '1 hour'], [240, '4 hours'], [1440, '1 day'], [10080, '1 week']]++function PhoneIncident({ incident, canAct, onChanged, onAsk }) {+ const [state, run] = useAction()+ const [menu, setMenu] = useState(false)+ const [showLines, setShowLines] = useState(false)+ const found = incident.diagnosis+ const [label, chip] = SEVERITY[incident.severity] || SEVERITY.INFO+ const resolved = incident.status === 'resolved'+ const act = (action, body) => run(async () => { await post(`/incidents/${incident.id}/${action}`, body); setMenu(false); refreshOverview(); onChanged() })+ const denied = canAct ? undefined : 'Only owners and admins can change an incident.'+ const meta = [incident.hostname, found.container, `opened ${clock(incident.created_at)}`, incident.reference].filter(Boolean).join(' · ')+ const where = serverLink(incident.server_id, found.container ? 'containers' : found.kind?.startsWith('network') ? 'network' : 'overview')+ return <>+ <PhoneHeader back={{ label: 'Incidents', to: '/agent' }} title={incident.title} action={<RoundButton label="More actions" icon="more" onClick={() => setMenu(true)} />} />+ <article className="space-y-7 px-4 pb-32 pt-2" aria-label={`${incident.reference}: ${incident.title}`}>+ <div>+ <div className="flex flex-wrap items-center gap-2"><span className={`chip ${chip}`}>{label}</span><span className={`chip ${resolved || found.state === 'diagnosed' ? 'chip-ok' : 'chip-warn'}`}>{resolved ? 'Resolved' : incident.muted_until ? 'Muted' : found.state === 'watching' ? 'Watching' : 'Diagnosed'}</span>{incident.acknowledged_at && <span className="chip">Acknowledged</span>}</div>+ <p className="mb-0 mt-2.5 text-[13px] text-muted">{meta}</p>+ <p className="mb-0 mt-4 text-[15px] leading-6 text-paper">{found.summary}</p>+ {state.error && <p role="alert" className="mb-0 mt-2 text-xs text-warn">{state.error}</p>}+ </div>++ {found.evidence && <section aria-label="Evidence">+ <div className="mb-2.5 flex items-baseline gap-2"><h2 className="m-0 text-[15px] font-semibold text-paper">Evidence</h2><span className="truncate text-xs text-muted">{found.evidence.title}</span></div>+ <Evidence evidence={found.evidence} />+ {found.lines.length > 0 && <>+ <button type="button" className="btn mt-2.5 h-11 w-full text-sm" aria-expanded={showLines} onClick={() => setShowLines((value) => !value)}>{showLines ? 'Hide' : 'Show'} {found.lines.length} recorded {found.lines.length === 1 ? 'event' : 'events'}</button>+ {showLines && <><ul className="mono m-0 mt-2.5 list-none space-y-1.5 rounded-md border border-line bg-ink px-4 py-3 text-[12px] leading-5">+ {found.lines.map((line, index) => <li key={`${line.time}-${index}`} className={line.strong ? 'text-signal' : 'text-soft'}><span className="text-dim">{clock(line.time)}</span> <span className="text-muted">{line.source}</span> {line.text}</li>)}+ </ul><p className="mb-0 mt-2 text-xs text-muted">Events Infradeck recorded on {incident.hostname}, not the container's own log, which it can't read.</p></>}+ </>}+ </section>}++ {found.signals.length > 0 && <section aria-label="Why">+ <div className="mb-2.5 flex items-baseline gap-2"><h2 className="m-0 text-[15px] font-semibold text-paper">Why</h2><span className="text-xs text-muted">{found.agreeing} of {found.signals.length} checks hold</span></div>+ <ul className="m-0 list-none divide-y divide-line overflow-hidden rounded-md border border-line bg-ink p-0">+ {found.signals.map((signal) => <li key={signal.text} className="flex items-start gap-3 px-4 py-3 text-[13px] leading-5"><Icon name={signal.ok ? 'check' : 'close'} size={14} className={`mt-[3px] shrink-0 ${signal.ok ? 'text-ok' : 'text-muted'}`} /><span className="text-paper">{signal.text}</span></li>)}+ </ul>+ </section>}++ {found.steps.length > 0 && <section aria-label="How to fix it">+ <h2 className="m-0 mb-1 text-[15px] font-semibold text-paper">How to fix it</h2>+ <p className="mb-2.5 mt-0 text-xs text-muted">You run these yourself. Infradeck can't change your servers.</p>+ <ol className="m-0 list-none divide-y divide-line overflow-hidden rounded-md border border-line bg-ink p-0">+ {found.steps.map((step, index) => (+ <li key={step.title} className="px-4 py-4">+ <div className="mono text-xs text-signal">{String(index + 1).padStart(2, '0')}{step.recommended && ' · recommended'}</div>+ <p className="mb-0 mt-1.5 text-sm font-semibold text-paper">{step.title}</p>+ <p className="mb-0 mt-1 text-[13px] leading-5 text-muted">{step.text}</p>+ {step.command && <Command step={step} />}+ </li>+ ))}+ </ol>+ </section>}+ {!found.steps.length && !found.signals.length && <Notice tone="plain">There is no playbook for this kind of incident yet. The description above is everything the rule knows.</Notice>}++ <section aria-label="Timeline">+ <h2 className="m-0 mb-2.5 text-[15px] font-semibold text-paper">Timeline</h2>+ <ol className="m-0 list-none space-y-3 p-0">{found.timeline.map((item, index) => <li key={`${item.time}-${index}`} className="grid grid-cols-[48px_12px_minmax(0,1fr)] items-baseline text-[13px]"><time dateTime={item.time} className="mono text-muted" title={new Date(item.time).toLocaleString()}>{clock(item.time)}</time><span aria-hidden="true" className={`h-[7px] w-[7px] self-center rounded-[1px] ${TONE[item.tone] || TONE.plain}`} /><span className="text-soft">{item.text}</span></li>)}</ol>+ </section>+ </article>++ {/* Ask and acknowledge stay pinned above the home bar wherever you scroll. */}+ <div className="fixed inset-x-0 bottom-0 z-30 grid grid-cols-2 gap-2.5 border-t border-line bg-bg px-4 pb-[calc(12px+env(safe-area-inset-bottom))] pt-3">+ <button type="button" className="btn h-12 text-sm" onClick={onAsk}>Ask the agent</button>+ {resolved ? <Link to={where} className="btn btn-primary h-12 text-sm">{found.container ? 'Open container' : 'Open server'}</Link>+ : <button type="button" className="btn btn-primary h-12 text-sm" disabled={!canAct || state.busy || Boolean(incident.acknowledged_at)} title={denied} onClick={() => act('acknowledge')}>{incident.acknowledged_at ? 'Acknowledged' : 'Acknowledge'}</button>}+ </div>++ {menu && <Sheet onClose={() => setMenu(false)} open title={incident.reference}>+ <div className="overflow-hidden rounded-lg border border-line">+ <Link to={where} className="flex h-12 items-center justify-between border-b border-line px-3.5 text-sm font-medium text-paper">{found.container ? 'Open container' : 'Open server'}<Icon name="chevron" size={14} className="text-muted" /></Link>+ {!resolved && <button type="button" className="flex h-12 w-full items-center border-0 bg-transparent px-3.5 text-left text-sm font-medium text-paper disabled:text-dim" disabled={!canAct || state.busy} onClick={() => act('resolve')}>Mark resolved</button>}+ </div>+ {!resolved && <>+ <div className="mb-2 mt-5 text-xs text-muted">{incident.muted_until ? `Muted until ${clock(incident.muted_until)}` : 'Mute notifications for'}</div>+ {incident.muted_until+ ? <button type="button" className="btn h-12 w-full text-sm" disabled={!canAct || state.busy} onClick={() => act('unmute')}>Unmute</button>+ : <div className="grid grid-cols-2 gap-2">{MUTE_OPTIONS.map(([minutes, text]) => <button key={minutes} type="button" className="btn h-12 text-sm" disabled={!canAct || state.busy} onClick={() => act('mute', { minutes })}>{text}</button>)}</div>}+ {!canAct && <p className="mb-0 mt-3 text-xs text-muted">{denied}</p>}+ <p className="mb-0 mt-3 text-xs leading-5 text-muted">If the cause is still there after you mark it resolved, a new incident opens at the next check-in.</p>+ </>}+ <Outcome state={state} />+ </Sheet>}+ </>+}++function PhoneInbox({ inbox, error, tab, setTab, onSelect }) {+ const list = inbox ? inbox[tab] : []+ const weekAgo = Date.now() - 7 * 86400000+ const recent = inbox ? inbox.resolved.filter((item) => new Date(item.resolved_at).getTime() >= weekAgo).slice(0, 5) : []+ const card = (incident) => {+ const [label, chip, color] = SEVERITY[incident.severity] || SEVERITY.INFO+ const resolved = incident.status === 'resolved'+ return (+ <li key={incident.id}>+ <button type="button" onClick={() => onSelect(incident.id)} className="block w-full border-0 bg-transparent px-4 py-3.5 text-left" style={{ boxShadow: resolved ? undefined : `inset 3px 0 0 ${color}` }}>+ <span className="flex items-center gap-2 text-xs text-muted">{!resolved && <span className={`chip ${chip}`}>{label}</span>}<span className="truncate">{incident.hostname}</span><span className="ml-auto shrink-0">{resolved ? day(incident.resolved_at) : formatAge(incident.created_at)}</span></span>+ <span className={`mt-1.5 block text-[15px] font-semibold leading-5 ${resolved ? 'text-soft' : 'text-paper'}`}>{incident.title}</span>+ <span className="mt-1.5 flex items-center gap-2 text-xs text-muted">{!resolved && <span className={`dot ${incident.state === 'watching' || incident.muted_until ? 'dot-warn' : 'dot-ok'}`} style={{ width: 7, height: 7 }} />}{stateLine(incident)}</span>+ </button>+ </li>+ )+ }+ return <>+ <PhoneHeader title="Incidents" live={false} />+ <div className="flex flex-col gap-6 px-4 pt-3">+ <div className="grid grid-cols-3 gap-1 rounded-md border border-line bg-ink p-1" role="tablist" aria-label="Which incidents">+ {[['open', 'Open', inbox?.open.length], ['resolved', 'Resolved', inbox?.resolved_count], ['muted', 'Muted', inbox?.muted.length]].map(([key, label, count]) => <button key={key} type="button" role="tab" aria-selected={tab === key} onClick={() => setTab(key)} className={`h-10 rounded border-0 text-[13px] font-medium ${tab === key ? 'bg-raised text-paper' : 'bg-transparent text-soft'}`}>{label} {count ?? ''}</button>)}+ </div>+ {!inbox ? <p className="m-0 py-8 text-center text-xs text-muted">{error || 'Loading…'}</p>+ : list.length ? <ul className="m-0 list-none divide-y divide-line overflow-hidden rounded-md border border-line bg-ink p-0">{list.map(card)}</ul>+ : <p className="m-0 rounded-md border border-line bg-ink px-4 py-6 text-center text-[13px] text-muted">{tab === 'open' ? 'Nothing is open. Every drawer is in.' : tab === 'muted' ? 'Nothing is muted.' : 'Nothing has been resolved yet.'}</p>}+ {tab === 'open' && recent.length > 0 && <section aria-label="Resolved this week">+ <h2 className="m-0 mb-2.5 text-[15px] font-semibold text-paper">Resolved this week</h2>+ <ul className="m-0 list-none divide-y divide-line overflow-hidden rounded-md border border-line bg-ink p-0">{recent.map(card)}</ul>+ </section>}+ <div className="overflow-hidden rounded-md border border-line bg-ink">+ <Link to="/agent?view=chat" className="flex min-h-14 items-center gap-3 border-b border-line px-4 py-3"><Icon name="agent" className="shrink-0 text-muted" /><span className="min-w-0 flex-1"><span className="block text-sm font-medium text-paper">Ask the agent</span><span className="block text-xs text-muted">About any server, not one incident</span></span><Icon name="chevron" size={14} className="text-muted" /></Link>+ <Link to="/account" className="flex min-h-14 items-center gap-3 px-4 py-3"><Icon name="bell" className="shrink-0 text-muted" /><span className="min-w-0 flex-1"><span className="block text-sm font-medium text-paper">Where alerts go</span><span className="block text-xs text-muted">Channels and quiet hours are set in Account</span></span><Icon name="chevron" size={14} className="text-muted" /></Link>+ </div>+ </div>+ </>+}+export default function AgentPage({ user, onLogout }) {const [params, setParams] = useSearchParams()const [tab, setTab] = useState('open')const { data: inbox, error, reload } = usePolled('/incidents', 10)const { data: config } = usePolled('/agent/config', null)const all = useMemo(() => (inbox ? [...inbox.open, ...inbox.muted, ...inbox.resolved] : []), [inbox])+ const phone = usePhone()const requested = Number(params.get('incident'))- const selectedId = all.some((item) => item.id === requested) ? requested : inbox?.open[0]?.id ?? null+ // A phone shows the list, one incident and the chat as separate screens, so nothing is picked by default there.+ const selectedId = all.some((item) => item.id === requested) ? requested : phone ? null : inbox?.open[0]?.id ?? nullconst selected = all.find((item) => item.id === selectedId) || nullconst { data: detail, error: detailError, reload: reloadDetail } = usePolled(selectedId ? `/incidents/${selectedId}` : null, 20)const select = (id) => setParams({ incident: String(id) }, { replace: true })@@ -245,6 +402,18 @@ export default function AgentPage({ user, onLogout }) {const list = inbox ? inbox[tab] : []const crumbs = selected ? [{ label: 'Agent', to: '/agent' }, { label: selected.reference }] : [{ label: 'Agent' }]+ if (phone) {+ const view = params.get('view')+ const incident = detail && detail.id === selectedId ? detail : null+ const chatOpen = view === 'chat' && (!requested || incident)+ let body+ if (chatOpen) body = <Chat key={selectedId ?? 'none'} phone user={user} incident={incident} enabled={config ? config.chat_enabled : true} back={incident ? { label: incident.title, to: `/agent?incident=${incident.id}` } : { label: 'Incidents', to: '/agent' }} />+ else if (incident) body = <PhoneIncident incident={incident} canAct={Boolean(inbox?.can_act)} onChanged={() => { reload(); reloadDetail() }} onAsk={() => setParams({ incident: String(incident.id), view: 'chat' })} />+ else if (selectedId || (requested && !inbox)) body = <><PhoneHeader back={{ label: 'Incidents', to: '/agent' }} title="Incident" live={false} /><p className="m-0 px-4 py-16 text-center text-[13px] text-muted">{detailError || 'Loading the incident…'}</p></>+ else body = <PhoneInbox inbox={inbox} error={error} tab={tab} setTab={setTab} onSelect={(id) => setParams({ incident: String(id) })} />+ return <AppShell user={user} onLogout={onLogout} crumbs={crumbs} bare phoneHeader phoneTabs={!chatOpen && !incident}>{body}</AppShell>+ }+return (<AppShell user={user} onLogout={onLogout} crumbs={crumbs} bare fitViewport><div className="grid xl:h-full xl:grid-cols-[minmax(300px,380px)_minmax(0,1fr)_minmax(320px,440px)] xl:divide-x xl:divide-line">diff --git a/src/frontend/src/dashboard/Containers.jsx b/src/frontend/src/dashboard/Containers.jsxindex 1819025..30481b9 100644--- a/src/frontend/src/dashboard/Containers.jsx+++ b/src/frontend/src/dashboard/Containers.jsx@@ -9,7 +9,8 @@ import {CONTAINER_FILTERS, STANDALONE, classifyPort, collapsePaths, collapseRanges, containerUptime, formatMegabytes, formatMegabytesShort, formatPercent, formatSpan, groupContainers, niceCeiling, parsePorts, reachablePortSet,} from './logic.js'-const COLUMNS = 'grid-cols-[196px_minmax(140px,1.1fr)_128px_150px_161px_minmax(150px,1fr)_52px_72px]'+// Tablets drop the Image column; it comes back from 1200 px.+const COLUMNS = 'grid-cols-[196px_128px_150px_161px_minmax(150px,1fr)_52px_72px] xl:grid-cols-[196px_minmax(140px,1.1fr)_128px_150px_161px_minmax(150px,1fr)_52px_72px]'const READ_ONLY_NOTE = 'Infradeck only reads from Docker for now, so it cannot fetch logs or restart a container yet.'const FILTER_LABELS = { all: 'All', problems: 'Problems', exposed: 'Exposed', restarted: 'Restarted', stopped: 'Stopped' }const APP_PROJECT = /infradeck|homie/i@@ -127,7 +128,7 @@ function ContainerRow({ server, container, sparkline, scopes, expanded, onTogglereturn <><button type="button" onClick={onToggle} aria-expanded={expanded} className={`grid w-full ${COLUMNS} h-11 items-center border-0 border-t border-solid border-line px-[18px] text-left transition-colors hover:bg-raised ${expanded ? 'bg-raised' : 'bg-transparent'}`}><span className="flex min-w-0 items-center gap-2.5 pl-5 pr-3"><span className={`dot ${problem === 2 ? 'dot-ok' : container.status === 'restarting' || problem === 1 ? 'dot-signal' : 'dot-warn'}`} style={{ width: 6, height: 6 }} /><span className="truncate text-[13px] font-medium text-paper" title={container.name}>{container.name}</span></span>- <span className="mono truncate pr-4 text-soft" title={container.image || ''}>{container.image || '—'}</span>+ <span className="mono hidden truncate pr-4 text-soft xl:block" title={container.image || ''}>{container.image || '—'}</span><span className="min-w-0 pr-3"><StatusText container={container} /></span><span className="flex items-center gap-2 pr-5"><Sparkline values={sparkline} width={80} max={100} /><span className="ml-auto text-xs font-medium text-paper">{formatPercent(container.cpu_pct)}</span></span><span className="pr-5">@@ -201,9 +202,9 @@ function ContainerTable({ server, view, sparklines }) {if (!view.groups.some((group) => group.count)) return <p className="m-0 border-t border-line px-[18px] py-6 text-center text-xs text-muted">No containers match{view.query.trim() ? ` “${view.query.trim()}”` : ' this filter'}.</p>return (<div className="custom-scroll overflow-x-auto">- <div className="min-w-[1060px]">+ <div className="min-w-[900px] xl:min-w-[1060px]"><div className={`grid ${COLUMNS} grid-head h-10 items-center border-t border-line px-[18px]`}>- <span>Name</span><span>Image</span><span>Status</span><span>CPU · 15 min</span><span>Memory</span><span>Published ports</span><span className="text-right">Up</span><span className="text-right">Restarts</span>+ <span>Name</span><span className="hidden xl:block">Image</span><span>Status</span><span>CPU · 15 min</span><span>Memory</span><span>Published ports</span><span className="text-right">Up</span><span className="text-right">Restarts</span></div>{view.groups.map((group, index) => {const open = view.isOpen(group, index)diff --git a/src/frontend/src/dashboard/DashboardPage.jsx b/src/frontend/src/dashboard/DashboardPage.jsxindex d934142..6d606cb 100644--- a/src/frontend/src/dashboard/DashboardPage.jsx+++ b/src/frontend/src/dashboard/DashboardPage.jsx@@ -14,12 +14,13 @@ import { NetworkCard, NetworkTab, listeningCount } from './Network.jsx'import { ServerPanel, TABS } from './ServerPanel.jsx'import { SystemTab } from './SystemTab.jsx'import { useForecasts, usePolled } from './data.js'-import { fullestMount, serverMounts, serverState, sortServers } from './logic.js'-import { Drawer } from '../ui.jsx'+import { fullestMount, serverMounts, sortServers } from './logic.js'+import { Drawer, usePhone } from '../ui.jsx'+import { PhoneHeader } from '../shell.jsx'+import { PhoneOverview, PhoneServer, headlineParts } from './Phone.jsx'const RANGES = [15, 30, 60, 180]const RANGE_KEY = 'infradeck.overview.minutes'-const COUNT_WORDS = ['No', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']function rememberedRange() {try {@@ -30,18 +31,14 @@ function rememberedRange() {}}-function headline(servers) {- const containers = servers.reduce((sum, server) => sum + (server.containers?.length || 0), 0)- const troubled = servers.filter((server) => ['critical', 'offline'].includes(serverState(server))).length || servers.filter((server) => serverState(server) === 'warn').length- const count = `${servers.length} ${servers.length === 1 ? 'server' : 'servers'}, ${containers} ${containers === 1 ? 'container' : 'containers'}.`- if (!troubled) return `${count} All healthy.`- return `${count} ${COUNT_WORDS[troubled] || troubled} ${troubled === 1 ? 'needs' : 'need'} you now.`-}+const headline = (servers) => headlineParts(servers, ', ').join(' ')export default function DashboardPage({ user, onLogout }) {const navigate = useNavigate()const [params, setParams] = useSearchParams()const { data: overview, error } = useOverview(Boolean(user), LIVE_REFRESH_SECONDS, onLogout)+ // A phone shows the fleet and one server as separate screens; the desktop shows both, with one server picked.+ const phone = usePhone()const [minutes, setMinutes] = useState(rememberedRange)const [showConnect, setShowConnect] = useState(false)const [actionError, setActionError] = useState('')@@ -52,7 +49,7 @@ export default function DashboardPage({ user, onLogout }) {const servers = useMemo(() => sortServers(overview?.servers || []), [overview])const requested = Number(params.get('server'))- const selected = servers.find((server) => server.id === requested) || servers.find((server) => server.is_dashboard_host) || servers[0] || null+ const selected = servers.find((server) => server.id === requested) || (phone ? null : servers.find((server) => server.is_dashboard_host) || servers[0]) || nullconst tab = TABS.includes(params.get('tab')) ? params.get('tab') : 'overview'const selectedId = selected?.id ?? null@@ -107,7 +104,7 @@ export default function DashboardPage({ user, onLogout }) {}const openConnect = () => setShowConnect(true)- const crumbs = selected && tab !== 'overview' ? [{ label: 'Overview', to: `/?server=${selected.id}` }, { label: selected.hostname }] : [{ label: 'Overview' }]+ const crumbs = selected && (tab !== 'overview' || phone) ? [{ label: 'Overview', to: `/?server=${selected.id}` }, { label: selected.hostname }] : [{ label: 'Overview' }]const pending = overview?.pending_collectors || []const waiting = pending.filter((item) => item.status === 'pending')const calm = !(overview?.alerts_by_severity?.CRITICAL || overview?.alerts_by_severity?.WARNING)@@ -155,10 +152,23 @@ export default function DashboardPage({ user, onLogout }) {</>}+ if (phone && overview && servers.length) {+ const watch = calm ? nextToWatch(servers, forecasts, (server) => fullestMount(serverMounts(server))) : null+ body = selected+ ? <PhoneServer server={selected} overview={overview} tab={tab} onTab={(next) => go(selected.id, next)} isAdmin={isAdmin} onInterval={changeInterval} samples={samples} minutes={minutes} forecasts={forecasts} listening={listeningCount(selected)} error={actionError || error}>+ {tab === 'network' && <NetworkTab key={selected.id} server={selected} samples={samples} minutes={minutes} onTab={(next) => go(selected.id, next)} />}+ {tab === 'system' && <SystemTab key={selected.id} server={selected} overview={overview} forecasts={forecasts} isAdmin={isAdmin} onDelete={deleteServer} deleting={deletingId === selected.id} />}+ {tab === 'events' && <EventsTab key={selected.id} server={selected} pending={pending} isAdmin={isAdmin} onReview={openConnect} />}+ </PhoneServer>+ : <PhoneOverview overview={overview} servers={servers} isAdmin={isAdmin} waiting={waiting} sparklines={fleetLines?.servers} watch={watch} error={actionError || error} onAttention={onAttention} onConnect={openConnect} />+ } else if (phone) {+ body = <><PhoneHeader mark title="Overview" /><div className="px-4 pt-4">{body}</div></>+ }+return (- <AppShell user={user} onLogout={onLogout} crumbs={crumbs} bare>- <div className="space-y-8 px-3 pt-5 sm:px-4 lg:px-7 lg:pt-7">{body}</div>- {isAdmin && <Drawer open={showConnect && servers.length > 0} onClose={() => setShowConnect(false)} title="Connect a server" description="Run one command on the machine, then add it when it shows up here. The fleet behind this panel updates by itself.">+ <AppShell user={user} onLogout={onLogout} crumbs={crumbs} bare phoneHeader={phone}>+ {phone ? body : <div className="space-y-8 px-3 pt-5 sm:px-4 lg:px-7 lg:pt-7">{body}</div>}+ {isAdmin && <Drawer open={showConnect && (servers.length > 0 || phone)} onClose={() => setShowConnect(false)} title="Connect a server" description="Run one command on the machine, then add it when it shows up here. The fleet behind this panel updates by itself.">{pending.some((item) => item.status === 'pending' && item.details?.dashboard_host) && <ThisMachineCard pending={pending} onChanged={refreshOverview} recommended={false} />}<AnotherMachineCard pending={pending} onChanged={refreshOverview} /></Drawer>}diff --git a/src/frontend/src/dashboard/EmptyFleet.jsx b/src/frontend/src/dashboard/EmptyFleet.jsxindex 28f777a..122cd75 100644--- a/src/frontend/src/dashboard/EmptyFleet.jsx+++ b/src/frontend/src/dashboard/EmptyFleet.jsx@@ -193,6 +193,9 @@ export function AnotherMachineCard({ pending, onChanged, focusRef }) {const commands = installCommands({ url: url || '<address>', token: token || '<generated when you click the button>', name: cleanName, collectorImage: info?.collector_image || '<collector image>', proxyImage: info?.proxy_image || '<docker proxy image>' })const minutes = expiresAt ? Math.max(1, Math.round((expiresAt - Date.now()) / 60000)) : nullconst command = commands[method]+ // Nobody types a docker command on a phone: hand it to a computer through the system share sheet.+ const canShare = typeof navigator !== 'undefined' && typeof navigator.share === 'function'+ const share = () => navigator.share({ title: `Connect ${cleanName || 'a server'} to Infradeck`, text: command }).catch(() => {})return (<div className="card flex flex-col px-[18px] pb-[18px] pt-4">@@ -220,10 +223,15 @@ export function AnotherMachineCard({ pending, onChanged, focusRef }) {<div className="relative mt-3.5 rounded-md border border-line bg-bg"><pre className="custom-scroll mono m-0 max-h-[168px] overflow-auto px-3.5 py-3 pr-24 leading-[19px] text-soft">{token ? command.split(token).flatMap((part, index) => (index ? [<span key={index} className="text-signal">{token}</span>, part] : [part])) : command}</pre>- {token ? <button type="button" className="btn btn-sm absolute right-2.5 top-2.5" onClick={() => copy(command)}><Icon name={copied ? 'check' : 'copy'} size={13} />{copied ? 'Copied' : 'Copy'}</button>+ {token ? <button type="button" className="btn btn-sm absolute right-2.5 top-2.5 max-md:hidden" onClick={() => copy(command)}><Icon name={copied ? 'check' : 'copy'} size={13} />{copied ? 'Copied' : 'Copy'}</button>: <div className="absolute inset-0 flex items-center justify-center rounded-md bg-bg/85"><button type="button" className="btn btn-primary" disabled={busy || !ready || !url} onClick={generate}>{busy ? 'Generating…' : 'Generate command'}</button></div>}</div>+ {token && <div className="mt-2.5 grid grid-cols-2 gap-2 md:hidden">+ <button type="button" className="btn btn-primary h-11 text-sm" onClick={() => copy(command)}><Icon name={copied ? 'check' : 'copy'} size={14} />{copied ? 'Copied' : 'Copy'}</button>+ <button type="button" className="btn h-11 text-sm" disabled={!canShare} title={canShare ? undefined : 'This browser has no share sheet. Copy the command instead.'} onClick={share}><Icon name="share" size={14} />Share</button>+ </div>}+<div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2.5"><div className="seg" role="group" aria-label="How to run it">{Object.keys(commands).map((key) => <button key={key} type="button" aria-pressed={method === key} onClick={() => setMethod(key)}>{key}</button>)}</div>{token && <button type="button" className="link text-xs" disabled={busy} onClick={generate}>New token</button>}diff --git a/src/frontend/src/dashboard/NeedsAttention.jsx b/src/frontend/src/dashboard/NeedsAttention.jsxindex 606bada..178cf63 100644--- a/src/frontend/src/dashboard/NeedsAttention.jsx+++ b/src/frontend/src/dashboard/NeedsAttention.jsx@@ -61,7 +61,7 @@ function Fact({ label, value, detail }) {)}-function AllClear({ overview, watch }) {+export function AllClear({ overview, watch }) {const quiet = overview.quietconst servers = overview.serversconst newest = Math.max(...servers.map((server) => (server.last_seen_at ? new Date(server.last_seen_at).getTime() : 0)))diff --git a/src/frontend/src/dashboard/Network.jsx b/src/frontend/src/dashboard/Network.jsxindex d1a7341..0179ae9 100644--- a/src/frontend/src/dashboard/Network.jsx+++ b/src/frontend/src/dashboard/Network.jsx@@ -126,11 +126,26 @@ export function NetworkTab({ server, samples, minutes, onTab }) {<button type="button" aria-pressed={filter === 'local'} onClick={() => setFilter('local')}>This machine only {total.local}</button><button type="button" aria-pressed={filter === 'all'} onClick={() => setFilter('all')}>All {total.listening}</button></div>- <label className="ml-auto flex items-center gap-3 text-xs text-muted">Sort+ <label className="flex items-center gap-3 text-xs text-muted sm:ml-auto">Sort<select className="select" value={sort} onChange={(event) => setSort(event.target.value)}><option value="risk">Risk</option><option value="port">Port</option><option value="owner">Owner</option></select></label></div>- <div className="custom-scroll overflow-x-auto">+ {/* Phones: one card per port instead of a seven-column table. */}+ <ul className="m-0 list-none border-t border-line p-0 md:hidden">+ {visible.map((row) => (+ <li key={`${row.proto}-${row.label}`} className="border-b border-line px-4 py-3 last:border-b-0" style={row.risky ? { boxShadow: 'inset 2px 0 0 var(--color-warn)' } : undefined}>+ <div className="flex items-baseline gap-2.5">+ <span className="mono text-[13px] text-paper">{row.proto}/{row.label}</span>+ <span className={`min-w-0 truncate text-[13px] font-medium ${row.owner ? 'text-paper' : 'text-muted'}`}>{row.owner || 'host process'}</span>+ <span className={`ml-auto shrink-0 text-xs ${row.scope === 'any' ? 'text-warn' : 'text-soft'}`}>{reach(row)}</span>+ </div>+ <div className="mt-1 text-xs text-muted">{[row.ownerKind === 'container' ? `container${row.what ? ` · ${row.what}` : ''}` : null, `bound to ${bound(row)}`, row.rule ? RULE_NAMES[row.rule] || 'allowed' : row.reachable ? 'no firewall rule' : null].filter(Boolean).join(' · ')}</div>+ {row.reason && <div className="mt-1 text-xs text-muted">{row.reason}</div>}+ </li>+ ))}+ {!visible.length && <li className="px-4 py-6 text-center text-xs text-muted">No ports in this view.</li>}+ </ul>+ <div className="custom-scroll relative hidden overflow-x-auto md:block"><table className="w-full min-w-[720px] border-collapse text-left text-xs"><thead><tr className="grid-head h-10 border-t border-line"><th className="w-[80px] pl-[18px] font-medium">Port</th><th className="w-[60px] font-medium">Proto</th><th className="font-medium">Owner</th><th className="w-[100px] font-medium">Bound to</th><th className="w-[120px] font-medium">Reachable from</th><th className="w-[120px] font-medium">Firewall</th><th className="pr-[18px] font-medium"><span className="sr-only">Note</span></th>diff --git a/src/frontend/src/dashboard/Phone.jsx b/src/frontend/src/dashboard/Phone.jsxnew file mode 100644index 0000000..9552d22--- /dev/null+++ b/src/frontend/src/dashboard/Phone.jsx@@ -0,0 +1,475 @@+// The Overview on a phone. Same order as the desktop in one column: what needs you, then the fleet as cards with+// three numbers each. Tapping a server opens it as its own screen with tabs, one chart at a time, and container+// details in a sheet from the bottom.+import { useEffect, useMemo, useRef, useState } from 'react'+import { Link } from 'react-router-dom'+import { seriesFor } from '../chartMath.js'+import { problemRank } from '../containerLogic.js'+import { containerState, isOnline } from '../fleetLogic.js'+import { Caret, Icon } from '../icons.jsx'+import { PhoneHeader, RoundButton } from '../shell.jsx'+import { Sheet } from '../ui.jsx'+import { LineChart, Meter, Sparkline } from './charts.jsx'+import { forecastKey, usePolled } from './data.js'+import { AllClear } from './NeedsAttention.jsx'+import { INTERVALS, intervalLabel } from './ServerPanel.jsx'+import {+ CONTAINER_FILTERS, attentionAction, containerUptime, forecastPhrase, formatAge, formatMegabytes, formatPercent, formatSpan, formatUsedOfTotal, fullestMount, groupContainers, healthChecks, healthVerdict,+ mountLevel, needsAttention, niceCeiling, parsePorts, reachablePortSet, serverMounts, serverState, serverStateLabel, thresholdLevel,+} from './logic.js'++const STATE_DOT = { critical: 'dot-signal', warn: 'dot-warn', ok: 'dot-ok', offline: '' }+const TONE_DOT = { ok: 'dot-ok', warn: 'dot-warn', unknown: '' }+const LEVEL_TEXT = ['text-paper', 'text-warn', 'text-signal']+const COUNT_WORDS = ['No', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']+const READ_ONLY_NOTE = 'Infradeck only reads from Docker for now, so it cannot fetch logs or restart a container yet.'+const FILTER_LABELS = { all: 'All', problems: 'Problems', exposed: 'Exposed', restarted: 'Restarted', stopped: 'Stopped' }++const shortSystem = (server) => server.os_info?.replace(/ \((.*)\)$/, '').replace(/ LTS$/, '') || ''++// "3 servers · 63 containers." and, when something is wrong, "One needs you now."+export function headlineParts(servers, separator = ' · ') {+ const containers = servers.reduce((sum, server) => sum + (server.containers?.length || 0), 0)+ const troubled = servers.filter((server) => ['critical', 'offline'].includes(serverState(server))).length || servers.filter((server) => serverState(server) === 'warn').length+ const count = `${servers.length} ${servers.length === 1 ? 'server' : 'servers'}${separator}${containers} ${containers === 1 ? 'container' : 'containers'}.`+ return [count, troubled ? `${COUNT_WORDS[troubled] || troubled} ${troubled === 1 ? 'needs' : 'need'} you now.` : 'All healthy.']+}++function Heading({ title, detail, children }) {+ return (+ <div className="mb-2.5 flex items-baseline gap-2">+ <h2 className="m-0 text-[15px] font-semibold text-paper">{title}</h2>+ {detail != null && <span className="text-xs text-muted">{detail}</span>}+ {children && <span className="ml-auto text-[13px] text-soft">{children}</span>}+ </div>+ )+}++// ---------- the fleet screen ----------++function AttentionCard({ alert, onAction }) {+ const action = attentionAction(alert)+ const where = alert.hostname && !alert.title.includes(alert.hostname) ? `${alert.hostname} · ` : ''+ const age = formatAge(alert.created_at)+ if (alert.severity === 'CRITICAL') {+ // Still the pulled-out drawer: full orange, nudged past the rack rail, with a thumb-sized button.+ return (+ <div className="relative left-3.5 rounded-md bg-signal px-4 pb-4 pt-3.5 text-bg shadow-[0_10px_28px_rgba(0,0,0,0.4)]">+ <div className="flex items-baseline justify-between text-[11px] font-bold tracking-[0.08em]"><span>CRITICAL</span><span className="font-semibold tracking-normal">{age}</span></div>+ <div className="mt-1.5 text-[15px] font-semibold leading-5">{alert.title}</div>+ <p className="mb-0 mt-1 text-[13px] leading-5 text-bg/80">{where}{alert.description}</p>+ <button type="button" onClick={() => onAction(alert, action)} className="mt-3.5 flex h-11 w-full items-center justify-center rounded-md border-0 bg-[#160800] text-sm font-semibold text-paper">{action.label}</button>+ </div>+ )+ }+ return (+ <button type="button" onClick={() => onAction(alert, action)} className="block w-full rounded-md border border-line bg-ink px-4 pb-3.5 pt-3 text-left">+ <span className="flex items-baseline justify-between text-[11px]"><span className="font-bold tracking-[0.08em] text-warn">{alert.severity}</span><span className="text-muted">{age}</span></span>+ <span className="mt-1.5 block text-sm font-semibold text-paper">{alert.title}</span>+ <span className="mt-1 line-clamp-2 block text-[13px] leading-5 text-muted">{where}{alert.description}</span>+ </button>+ )+}++function containerNote(server) {+ const containers = server.containers || []+ const states = containers.map(containerState)+ const running = states.filter((state) => state === 'running' || state === 'unhealthy').length+ const restarting = states.filter((state) => state === 'restarting').length+ const unhealthy = states.filter((state) => state === 'unhealthy').length+ const stopped = states.filter((state) => state === 'stopped').length+ const warnings = server.alerts_by_severity?.WARNING || 0+ const note = restarting ? [`${restarting} restarting`, 'text-signal'] : unhealthy ? [`${unhealthy} unhealthy`, 'text-signal'] : stopped ? [`${stopped} stopped`, 'text-warn'] : warnings ? [`${warnings} ${warnings === 1 ? 'warning' : 'warnings'}`, ''] : null+ return { count: containers.length ? `${running}/${containers.length} containers` : null, note }+}++function Figure({ label, value, tone = 'text-paper', children }) {+ return (+ <span className="min-w-0">+ <span className="block text-xs text-muted">{label}</span>+ <span className={`mt-1 block text-[15px] font-semibold ${tone}`}>{value}</span>+ <span className="mt-1.5 block h-[18px]">{children}</span>+ </span>+ )+}++function ServerCard({ server, overview, sparkline, onOpen }) {+ const state = serverState(server)+ const host = server.host+ const disk = fullestMount(serverMounts(server))+ const thresholds = overview.alert_thresholds || {}+ const memoryLevel = thresholdLevel(host?.ram_pct, thresholds.memory_warning_pct ?? 85, thresholds.memory_critical_pct ?? 95)+ const diskLevel = disk ? mountLevel(disk, overview.disk_thresholds, overview.mount_thresholds) : 0+ const critical = state === 'critical'+ const badge = critical || state === 'offline' ? serverStateLabel(server) : null+ const { count, note } = containerNote(server)+ return (+ <Link to={`/?server=${server.id}`} onClick={onOpen} aria-label={`${server.hostname}, ${serverStateLabel(server)}`} className={`block rounded-md border bg-ink px-4 pb-3.5 pt-3.5 ${critical ? 'border-2 border-signal' : 'border-line'}`}>+ <span className="flex items-center gap-2.5">+ <span className={`dot ${STATE_DOT[state]}`} />+ <span className="truncate text-[15px] font-semibold text-paper">{server.hostname}</span>+ {badge ? <span className={`chip ${critical ? 'chip-signal' : ''}`}>{badge}</span> : server.is_dashboard_host && <span className="chip">this machine</span>}+ <Icon name="chevron" size={14} className="ml-auto shrink-0 text-muted" />+ </span>+ {host ? (+ <span className="mt-3 grid grid-cols-3 gap-x-5">+ <Figure label="CPU" value={formatPercent(host.cpu_utilization_pct)}><Sparkline values={sparkline} width={96} height={16} tone={critical ? 'signal' : 'paper'} /></Figure>+ <Figure label="Memory" value={formatPercent(host.ram_pct)} tone={LEVEL_TEXT[memoryLevel]}><Meter className="mt-1.5" percent={host.ram_pct} level={memoryLevel} label={`${server.hostname} memory`} /></Figure>+ <Figure label="Disk" value={disk ? formatPercent(disk.used_pct) : '—'} tone={LEVEL_TEXT[diskLevel]}><Meter className="mt-1.5" percent={disk?.used_pct} level={diskLevel} label={`${server.hostname} busiest disk`} /></Figure>+ </span>+ ) : <span className="mt-3 block text-[13px] text-muted">{isOnline(server) ? 'Collecting the first measurement…' : 'The collector has not sent a measurement yet.'}</span>}+ <span className="mt-2.5 block truncate text-xs text-muted">+ {[shortSystem(server), count].filter(Boolean).join(' · ')}+ {note && <> · <span className={note[1]}>{note[0]}</span></>}+ </span>+ </Link>+ )+}++export function PhoneOverview({ overview, servers, isAdmin, waiting, sparklines, watch, error, onAttention, onConnect }) {+ const alerts = (overview.alerts || []).filter(needsAttention)+ const counts = overview.alerts_by_severity || {}+ const open = (counts.CRITICAL || 0) + (counts.WARNING || 0)+ const troubled = servers.some((server) => serverState(server) !== 'ok')+ const [count, verdict] = headlineParts(servers)+ return (+ <>+ <PhoneHeader mark title="Overview" subtitle={<>{count} <span className={troubled ? 'text-paper' : ''}>{verdict}</span></>} />+ <div className="space-y-7 px-4 pt-4">+ {error && <div role="alert" className="rounded-md border border-warn/40 px-3.5 py-2.5 text-xs text-warn">{error}</div>}+ {isAdmin && waiting.length > 0 && (+ <button type="button" onClick={onConnect} className="flex w-full items-center gap-3 rounded-md border border-edge bg-ink px-3.5 py-3 text-left text-[13px] text-soft">+ <span className="dot shrink-0" style={{ background: 'var(--color-paper)' }} />+ <span className="min-w-0 flex-1"><span className="font-medium text-paper">{waiting.map((item) => item.hostname).join(', ')}</span> {waiting.length === 1 ? 'is' : 'are'} asking to join the fleet.</span>+ <span className="font-medium text-paper">Review</span>+ </button>+ )}+ <section aria-label="Needs attention">+ <Heading title="Needs attention" detail={open}><Link to="/agent" className="inline-flex h-7 items-center">All</Link></Heading>+ {open ? <>+ <div className="space-y-2.5 border-x-2 border-rail px-2.5">{alerts.map((alert) => <AttentionCard key={alert.id} alert={alert} onAction={onAttention} />)}</div>+ {open > alerts.length && <p className="mb-0 mt-2 text-xs text-muted">Showing the {alerts.length} most severe of {open}. The rest are in Agent.</p>}+ </> : <AllClear overview={overview} watch={watch} />}+ </section>+ <section aria-label="Fleet">+ <Heading title="Fleet" detail={`${servers.length} ${servers.length === 1 ? 'server' : 'servers'}`}>{troubled ? 'Problems first' : 'By name'}</Heading>+ <div className="space-y-2.5">{servers.map((server) => <ServerCard key={server.id} server={server} overview={overview} sparkline={sparklines?.[server.id]} />)}</div>+ </section>+ {isAdmin && <button type="button" onClick={onConnect} className="btn h-12 w-full text-sm"><Icon name="plus" size={15} />Connect a server</button>}+ </div>+ </>+ )+}++// ---------- one server ----------++// One full-width chart with pills to switch metric; a sideways swipe on the chart moves to the next one.+function MetricChart({ server, samples, minutes }) {+ const host = server.host+ const disk = fullestMount(serverMounts(server).filter((mount) => mount.total_gb != null))+ const metrics = [+ { key: 'cpu', label: 'CPU', value: formatPercent(host.cpu_utilization_pct) },+ { key: 'ram', label: 'Memory', value: formatPercent(host.ram_pct) },+ { key: 'load', label: 'Load', value: host.load_1m == null ? '—' : host.load_1m.toFixed(2) },+ ...(disk ? [{ key: 'disk', label: 'Disk', value: formatPercent(disk.used_pct) }] : []),+ ]+ const [metric, setMetric] = useState('cpu')+ const holding = useRef(false)+ const touch = useRef(null)+ const pills = useRef(null)+ const diskRange = minutes > 60 ? '6h' : '1h'+ const { data: diskHistory } = usePolled(metric === 'disk' && disk ? `/monitoring/servers/${server.id}/mounts/history?mount=${encodeURIComponent(disk.mount)}&range=${diskRange}&metrics=used_pct` : null, 60)++ useEffect(() => { pills.current?.querySelector('[aria-pressed="true"]')?.scrollIntoView({ block: 'nearest', inline: 'nearest' }) }, [metric])++ const cores = server.cpu_cores || 1+ let points = samples.map((sample) => ({ time: sample.time, value: sample[metric] }))+ let max = 100+ let ticks = [100, 50, 0]+ let format = (tick) => `${tick}%`+ let readout = (value) => formatPercent(value)+ let span = `last ${minutes < 60 ? `${minutes} min` : `${minutes / 60} h`}`+ if (metric === 'load') {+ const peak = Math.max(cores, ...samples.map((sample) => sample.load ?? 0))+ max = peak <= cores ? cores : niceCeiling(peak)+ ticks = [max, max / 2, 0]+ format = (tick) => String(Number(tick.toFixed(1)))+ readout = (value) => value.toFixed(2)+ } else if (metric === 'disk') {+ points = seriesFor(diskHistory?.points, 'used_pct').map((point) => ({ time: point.t, value: point.avg }))+ span = `${disk.mount} · last ${diskRange.replace('h', ' h')}`+ }+ const known = points.map((point) => point.value).filter((value) => value != null)+ const average = known.length ? known.reduce((sum, value) => sum + value, 0) / known.length : null+ const current = metrics.find((item) => item.key === metric) || metrics[0]+ const step = (direction) => {+ const index = metrics.findIndex((item) => item.key === metric)+ const next = metrics[index + direction]+ if (next) setMetric(next.key)+ }++ return (+ <div>+ <div ref={pills} className="no-scrollbar -mx-4 flex gap-2 overflow-x-auto px-4" role="group" aria-label="Chart">+ {metrics.map((item) => (+ <button key={item.key} type="button" aria-pressed={metric === item.key} onClick={() => setMetric(item.key)} className={`h-9 shrink-0 rounded-full border px-3.5 text-[13px] font-medium ${metric === item.key ? 'border-paper bg-paper text-bg' : 'border-edge bg-transparent text-soft'}`}>{item.label} {item.value}</button>+ ))}+ </div>+ <div className="mt-3 rounded-md border border-line bg-ink px-4 pb-3 pt-3.5"+ onTouchStart={(event) => { touch.current = [event.touches[0].clientX, event.touches[0].clientY] }}+ onTouchEnd={(event) => {+ const start = touch.current+ touch.current = null+ if (!start || holding.current) return+ const dx = event.changedTouches[0].clientX - start[0]+ const dy = event.changedTouches[0].clientY - start[1]+ if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(dy) * 1.5) step(dx < 0 ? 1 : -1)+ }}>+ <div className="mb-3 flex items-baseline gap-2">+ <span className="text-[28px] font-semibold leading-8 tracking-[-0.01em] text-paper">{current.value}</span>+ <span className="min-w-0 truncate text-xs text-muted">{current.label} · {span}</span>+ {average != null && <span className="ml-auto shrink-0 text-xs text-muted">avg {metric === 'load' ? average.toFixed(2) : formatPercent(average)}</span>}+ </div>+ <LineChart label={`${current.label} on ${server.hostname}`} points={points} max={max} ticks={ticks} format={format} area={metric !== 'cpu'} height={150} gutter={34} readout={readout} onHold={(value) => { holding.current = value }} />+ </div>+ <p className="mb-0 mt-2 text-center text-xs leading-5 text-muted">Swipe the chart for memory and load. Touch and hold to read a value.</p>+ </div>+ )+}++function HealthList({ server }) {+ const [help, setHelp] = useState(false)+ const checks = healthChecks(server)+ return (+ <section aria-label="Health checks">+ <Heading title="Health checks" detail={healthVerdict(checks)} />+ <ul className="m-0 list-none divide-y divide-line overflow-hidden rounded-md border border-line bg-ink p-0">+ {checks.map((check) => (+ <li key={check.key} className="grid min-h-[45px] grid-cols-[18px_96px_minmax(0,1fr)] items-center px-4 py-2 text-[13px]">+ <span className={`dot ${TONE_DOT[check.tone]}`} style={{ width: 7, height: 7 }} />+ <span className="text-muted">{check.label}</span>+ <span className={check.tone === 'warn' ? 'text-warn' : check.tone === 'unknown' ? 'text-muted' : 'text-paper'}>+ {check.text}{check.action && <> · <button type="button" className="link" aria-expanded={help} onClick={() => setHelp((value) => !value)}>{check.action}</button></>}+ </span>+ </li>+ ))}+ </ul>+ {help && <p className="mb-0 mt-2 text-xs leading-5 text-muted">The internet check is off until this machine's collector is given targets: set <span className="mono text-soft">INFRADECK_CONNECTIVITY_TARGETS</span> (for example <span className="mono text-soft">1.1.1.1:443,dns.google:443</span>) in its environment and restart it.</p>}+ </section>+ )+}++function StorageList({ server, overview, forecasts }) {+ const mounts = serverMounts(server)+ if (!mounts.length) return null+ return (+ <section aria-label="Storage">+ <Heading title="Storage" />+ <div className="divide-y divide-line overflow-hidden rounded-md border border-line bg-ink">+ {mounts.map((mount) => {+ const level = mountLevel(mount, overview.disk_thresholds, overview.mount_thresholds)+ const forecast = forecastPhrase(forecasts[forecastKey(server.id, mount.mount)])+ return (+ <div key={mount.mount} className="px-4 py-3">+ <div className="flex items-baseline justify-between gap-3 text-[13px]">+ <span className="mono min-w-0 truncate text-paper">{mount.mount}</span>+ <span className={`shrink-0 ${LEVEL_TEXT[level]}`}>{mount.total_gb != null ? formatUsedOfTotal(mount.used_gb, mount.total_gb, ' of ') : formatPercent(mount.used_pct)}</span>+ </div>+ <Meter className="mt-2.5" percent={mount.used_pct} level={level} label={`${mount.mount} usage`} />+ <div className="mt-2.5 text-xs text-muted">{forecast ? forecast.charAt(0).toUpperCase() + forecast.slice(1) : 'No clear growth trend'}</div>+ </div>+ )+ })}+ </div>+ </section>+ )+}++function containerLine(container) {+ const stopped = container.status === 'exited' || container.status === 'dead'+ const extra = stopped && container.exit_code != null ? (container.oom_killed ? 'out of memory' : `code ${container.exit_code}`) : container.healthcheck_status+ return [container.status, extra].filter(Boolean)+}++const containerDot = (container) => {+ const problem = problemRank(container)+ return problem === 2 ? 'dot-ok' : container.status === 'restarting' || problem === 1 ? 'dot-signal' : 'dot-warn'+}++function ContainerItem({ container, right, sub, onOpen }) {+ const [status, extra] = containerLine(container)+ return (+ <button type="button" onClick={onOpen} className="flex min-h-[60px] w-full items-center gap-3 border-0 border-t border-solid border-line bg-transparent px-4 py-2.5 text-left first:border-t-0">+ <span className="min-w-0 flex-1">+ <span className="flex items-center gap-2"><span className={`dot ${containerDot(container)}`} style={{ width: 7, height: 7 }} /><span className="truncate text-sm font-medium text-paper">{container.name}</span></span>+ <span className="mt-1 block truncate pl-[15px] text-xs text-muted">+ <span className={status === 'running' ? '' : 'text-warn'}>{status}</span>{extra && <span className={extra === 'unhealthy' || extra === 'out of memory' ? 'text-signal' : ''}> · {extra}</span>}{sub ? ` · ${sub}` : ''}+ </span>+ </span>+ <span className="shrink-0 text-right">{right}</span>+ </button>+ )+}++function ContainerSheet({ server, container, onClose }) {+ const { data: detail, error } = usePolled(`/monitoring/servers/${server.id}/containers/${encodeURIComponent(container.container_id)}?limit=60`, 30)+ const latest = detail?.latest+ const history = detail?.history || []+ const cpuMax = Math.max(100, niceCeiling(Math.max(0, ...history.map((sample) => sample.cpu_pct ?? 0))))+ const span = history.length > 1 ? formatSpan((new Date(history[history.length - 1].time) - new Date(history[0].time)) / 1000) : null+ const health = container.healthcheck_status+ const title = (+ <div>+ <div className="flex items-center gap-2.5">+ <span className={`dot ${containerDot(container)}`} />+ <h2 className="m-0 truncate text-[17px] font-semibold text-paper">{container.name}</h2>+ {health && <span className={`chip ${health === 'healthy' ? 'chip-ok' : health === 'unhealthy' ? 'chip-signal' : ''}`}>{health}</span>}+ </div>+ <div className="mono mt-1.5 truncate text-[11px] text-muted">{[container.image, container.container_id?.slice(0, 12)].filter(Boolean).join(' · ')}</div>+ </div>+ )+ const tile = (label, value, tone = 'text-paper') => <div className="rounded-md border border-line bg-bg px-3.5 py-3"><div className="text-xs text-muted">{label}</div><div className={`mt-1.5 text-[17px] font-semibold ${tone}`}>{value}</div></div>+ return (+ <Sheet open onClose={onClose} title={title} label={`Container ${container.name}`} footer={<>+ <div className="grid grid-cols-3 gap-2">+ <button type="button" className="btn h-12" disabled title={READ_ONLY_NOTE}><Icon name="logs" size={15} />Logs</button>+ <button type="button" className="btn h-12" disabled title={READ_ONLY_NOTE}><Icon name="restart" size={15} />Restart</button>+ <Link to="/agent" className="btn h-12"><Icon name="agent" size={15} />Ask</Link>+ </div>+ <p className="mb-0 mt-2 text-center text-[11px] text-dim">{READ_ONLY_NOTE}</p>+ </>}>+ <div className="grid grid-cols-2 gap-2">+ {tile('CPU', formatPercent(container.cpu_pct))}+ {tile('Memory', formatMegabytes(container.memory_used_mb))}+ {tile('Up', containerUptime(container.started_at) || '—')}+ {tile('Restarts', container.restart_count ?? 0, container.restart_count ? 'text-warn' : 'text-paper')}+ </div>+ <div className="mt-2 rounded-md border border-line bg-bg px-3 pb-2.5 pt-3">+ {error ? <p className="m-0 py-6 text-center text-xs text-warn">{error}</p> : !latest ? <p className="m-0 py-6 text-center text-xs text-muted">Loading the recent chart…</p> : <>+ <div className="mb-2 text-xs text-muted">CPU · {span ? `last ${span}` : 'recent'}</div>+ <LineChart label={`CPU use of ${container.name}`} points={history.map((sample) => ({ time: sample.time, value: sample.cpu_pct }))} max={cpuMax} ticks={[cpuMax, cpuMax / 2, 0]} format={(tick) => `${tick}%`} area height={96} gutter={36} readout={(value) => formatPercent(value)} />+ </>}+ </div>+ {latest && <dl className="kv m-0 mt-3 text-[13px]" style={{ '--kv-label': '96px' }}>+ <dt>Limit</dt><dd className="text-paper">{latest.memory_limit_mb && (!server.total_ram_gb || latest.memory_limit_mb < server.total_ram_gb * 1024 * 0.98) ? formatMegabytes(latest.memory_limit_mb) : 'none'}</dd>+ <dt>Processes</dt><dd className="text-paper">{latest.pids ?? '—'}</dd>+ <dt>Net in / out</dt><dd className="text-paper">{formatMegabytes(latest.net_rx_mb)} / {formatMegabytes(latest.net_tx_mb)}</dd>+ <dt>Disk r / w</dt><dd className="text-paper">{formatMegabytes(latest.block_read_mb)} / {formatMegabytes(latest.block_write_mb)}</dd>+ </dl>}+ </Sheet>+ )+}++function TopContainers({ server, onAll, onOpen }) {+ const containers = server.containers || []+ if (!containers.length) return null+ const running = containers.filter((container) => container.status === 'running').length+ const top = [...containers].sort((a, b) => problemRank(a) - problemRank(b) || (b.cpu_pct ?? -1) - (a.cpu_pct ?? -1)).slice(0, 3)+ return (+ <section aria-label="Containers">+ <Heading title="Containers" detail={`${running} running`}><button type="button" onClick={onAll} className="h-7 border-0 bg-transparent p-0 text-[13px] text-soft">See all</button></Heading>+ <div className="overflow-hidden rounded-md border border-line bg-ink">+ {top.map((container) => <ContainerItem key={container.container_id} container={container} sub={formatMegabytes(container.memory_used_mb)} onOpen={() => onOpen(container)} right={<><span className="block text-sm font-medium text-paper">{formatPercent(container.cpu_pct)}</span><span className="block text-xs text-muted">CPU</span></>} />)}+ </div>+ </section>+ )+}++function ContainerList({ server, onOpen }) {+ const [query, setQuery] = useState('')+ const [filter, setFilter] = useState('all')+ const [closed, setClosed] = useState({})+ const containers = server.containers || []+ const reachable = useMemo(() => reachablePortSet(server), [server])+ if (!containers.length) return <p className="m-0 py-10 text-center text-[13px] text-muted">{server.host?.docker_status === 'unreachable' ? 'Docker is not answering on this machine, so there is no container data right now.' : `No containers reported on ${server.hostname}.`}</p>+ const counts = Object.fromEntries(Object.keys(CONTAINER_FILTERS).map((key) => [key, containers.filter((container) => CONTAINER_FILTERS[key](container, reachable)).length]))+ const needle = query.trim().toLowerCase()+ const shown = containers.filter((container) => CONTAINER_FILTERS[filter](container, reachable) && (!needle || `${container.name} ${container.image || ''} ${parsePorts(container.ports).map((port) => port.host).join(' ')}`.toLowerCase().includes(needle)))+ const groups = groupContainers(shown, { sort: 'cpu', grouped: true })+ return (+ <div>+ <label className="relative block">+ <Icon name="search" size={15} className="pointer-events-none absolute left-3.5 top-[15px] text-muted" />+ <input type="search" className="field h-11 pl-10 text-sm" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Filter by name, image or port" aria-label={`Filter containers on ${server.hostname}`} />+ </label>+ <div className="no-scrollbar -mx-4 mt-3 flex gap-2 overflow-x-auto px-4" role="group" aria-label="Show">+ {Object.keys(FILTER_LABELS).map((key) => <button key={key} type="button" aria-pressed={filter === key} onClick={() => setFilter(key)} className={`h-9 shrink-0 rounded-full border px-3.5 text-[13px] font-medium ${filter === key ? 'border-raised bg-raised text-paper' : 'border-edge bg-transparent text-soft'}`}>{FILTER_LABELS[key]} {counts[key]}</button>)}+ </div>+ {!groups.some((group) => group.count) ? <p className="m-0 py-8 text-center text-[13px] text-muted">No containers match{needle ? ` “${query.trim()}”` : ' this filter'}.</p> : (+ <div className="mt-3 overflow-hidden rounded-md border border-line bg-ink">+ {groups.map((group) => {+ const open = !(closed[group.name] ?? false)+ return (+ <div key={group.name ?? 'all'} className="border-t border-line first:border-t-0">+ {group.name !== null && <button type="button" onClick={() => setClosed((current) => ({ ...current, [group.name]: open }))} aria-expanded={open} className="flex h-11 w-full items-center gap-2.5 border-0 bg-sunken px-4 text-left">+ <Caret open={open} className="text-muted" />+ <span className="truncate text-[13px] font-semibold text-paper">{group.name}</span>+ <span className="shrink-0 text-xs text-muted">{group.count} · {formatPercent(group.cpu)} CPU</span>+ {group.problems > 0 && <span className="chip chip-signal ml-auto">{group.problems}</span>}+ </button>}+ {open && group.containers.map((container) => <ContainerItem key={container.container_id} container={container} onOpen={() => onOpen(container)} right={<><span className="block text-sm font-medium text-paper">{formatPercent(container.cpu_pct)}</span><span className="block text-xs text-muted">{formatMegabytes(container.memory_used_mb)}</span></>} />)}+ </div>+ )+ })}+ </div>+ )}+ </div>+ )+}++function ServerActions({ server, isAdmin, onInterval, onClose }) {+ return (+ <Sheet open onClose={onClose} title={server.hostname}>+ <div className="overflow-hidden rounded-lg border border-line">+ <label className="flex min-h-12 items-center justify-between gap-3 border-b border-line px-3.5 text-sm text-paper">Check every+ {isAdmin ? <select className="select h-9" value={server.check_interval_seconds} onChange={(event) => onInterval(server, Number(event.target.value))}>+ {!INTERVALS.some(([value]) => value === server.check_interval_seconds) && <option value={server.check_interval_seconds}>{intervalLabel(server.check_interval_seconds)}</option>}+ {INTERVALS.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select> : <span className="text-soft">{intervalLabel(server.check_interval_seconds)}</span>}+ </label>+ <Link to={`/statistics?server=${server.id}`} className="flex h-12 items-center justify-between px-3.5 text-sm font-medium text-paper">Full history in Statistics<Icon name="chevron" size={14} className="text-muted" /></Link>+ </div>+ {isAdmin && <p className="mb-0 mt-3 text-xs leading-5 text-muted">Renaming and removing this server are in its System tab and in Admin.</p>}+ </Sheet>+ )+}++export function PhoneServer({ server, overview, tab, onTab, isAdmin, onInterval, samples, minutes, forecasts, listening, error, children }) {+ const [actions, setActions] = useState(false)+ const [opened, setOpened] = useState(null)+ const state = serverState(server)+ const uptime = server.host?.system_uptime_seconds+ const meta = [shortSystem(server), server.cpu_cores ? `${server.cpu_cores} cores` : null, server.total_ram_gb ? `${Math.round(server.total_ram_gb)} GB` : null, uptime != null ? `up ${formatSpan(uptime)}` : null].filter(Boolean).join(' · ')+ const tabs = [+ ['overview', 'Overview', null],+ ['containers', 'Containers', server.containers?.length || null],+ ['network', 'Network', listening || null],+ ['system', 'System', null],+ ['events', 'Events', null],+ ]+ // The container in the sheet follows the overview poll, so its numbers stay current while it is open.+ const openContainer = opened ? (server.containers || []).find((container) => container.container_id === opened) : null+ return (+ <>+ <PhoneHeader back={{ label: 'Overview', to: '/' }} title={server.hostname}+ subtitle={<span className="flex min-w-0 items-center gap-2"><span className={`dot shrink-0 ${STATE_DOT[state]}`} style={{ width: 7, height: 7 }} /><span className="truncate">{meta || serverStateLabel(server)}</span></span>}+ action={<RoundButton label={`Actions for ${server.hostname}`} icon="more" onClick={() => setActions(true)} />} />+ <div role="tablist" aria-label={`${server.hostname} sections`} className="no-scrollbar sticky top-0 z-10 mt-2 flex gap-6 overflow-x-auto border-b border-line bg-bg px-4">+ {tabs.map(([id, label, count]) => <button key={id} type="button" role="tab" aria-selected={tab === id} aria-controls="server-tabpanel" className="tab shrink-0" onClick={() => onTab(id)}>{label}{count != null && <small>{count}</small>}</button>)}+ </div>+ <div role="tabpanel" id="server-tabpanel" className="px-4 pt-4">+ {error && <div role="alert" className="mb-4 rounded-md border border-warn/40 px-3.5 py-2.5 text-xs text-warn">{error}</div>}+ {tab === 'overview' && (server.host ? <div className="space-y-7">+ <MetricChart server={server} samples={samples} minutes={minutes} />+ <HealthList server={server} />+ <StorageList server={server} overview={overview} forecasts={forecasts} />+ <TopContainers server={server} onAll={() => onTab('containers')} onOpen={(container) => setOpened(container.container_id)} />+ </div> : <p className="m-0 py-10 text-center text-[13px] text-muted">The collector on {server.hostname} has not sent a measurement yet. It shows up here on its first check-in.</p>)}+ {tab === 'containers' && <ContainerList server={server} onOpen={(container) => setOpened(container.container_id)} />}+ {tab !== 'overview' && tab !== 'containers' && <div className="-mx-4 overflow-hidden border-y border-line bg-ink">{children}</div>}+ </div>+ {actions && <ServerActions server={server} isAdmin={isAdmin} onInterval={onInterval} onClose={() => setActions(false)} />}+ {openContainer && <ContainerSheet server={server} container={openContainer} onClose={() => setOpened(null)} />}+ </>+ )+}diff --git a/src/frontend/src/dashboard/ServerPanel.jsx b/src/frontend/src/dashboard/ServerPanel.jsxindex a862073..45e1d80 100644--- a/src/frontend/src/dashboard/ServerPanel.jsx+++ b/src/frontend/src/dashboard/ServerPanel.jsx@@ -78,7 +78,7 @@ function OverviewTab({ server, overview, samples, forecasts }) {const loadMax = loadPeak <= cores ? cores : niceCeiling(loadPeak)const percentTicks = [100, 50, 0]return <>- <div className="grid divide-y divide-line lg:grid-cols-2 lg:divide-x xl:grid-cols-[1fr_1fr_1fr_331px] xl:divide-y-0">+ <div className="grid divide-y divide-line md:grid-cols-2 md:divide-x xl:grid-cols-[1fr_1fr_1fr_331px] xl:divide-y-0"><Metric label="CPU" value={formatPercent(host.cpu_utilization_pct)}><LineChart label={`CPU use on ${server.hostname}`} points={series('cpu')} max={100} ticks={percentTicks} format={(tick) => `${tick}%`} /></Metric>@@ -86,7 +86,7 @@ function OverviewTab({ server, overview, samples, forecasts }) {<LineChart label={`Memory use on ${server.hostname}`} points={series('ram')} max={100} ticks={percentTicks} format={(tick) => `${tick}%`} area /></Metric><Metric label="Load (1 min)" value={host.load_1m == null ? '—' : host.load_1m.toFixed(2)} unit={`of ${cores} ${cores === 1 ? 'core' : 'cores'}`}>- <LineChart label={`Load on ${server.hostname}`} points={series('load')} max={loadMax} ticks={[loadMax, loadMax / 2, 0]} format={(tick) => String(Number(tick.toFixed(1)))} area height={118} gutter={28} />+ <LineChart label={`Load on ${server.hostname}`} points={series('load')} max={loadMax} ticks={[loadMax, loadMax / 2, 0]} format={(tick) => String(Number(tick.toFixed(1)))} area gutter={28} /></Metric><HealthChecks server={server} /></div>diff --git a/src/frontend/src/dashboard/charts.jsx b/src/frontend/src/dashboard/charts.jsxindex 4655a55..18642db 100644--- a/src/frontend/src/dashboard/charts.jsx+++ b/src/frontend/src/dashboard/charts.jsx@@ -1,6 +1,6 @@// The Overview page's charts. All monochrome: colour is kept for status, so a chart never looks alarming just// because of its palette.-import { useId } from 'react'+import { useId, useRef, useState } from 'react'const clock = (time) => (time ? new Date(time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false }) : '')@@ -22,10 +22,49 @@ export function Sparkline({ values, max = 100, width = 76, height = 18, tone = ')}+// Touch and hold (or hover with a mouse) to read a value: the nearest point gets a line, a dot and a label above it.+// ``onHold`` tells the parent while a reading is shown, so a swipe on the same chart isn't taken as one.+function useReadout(points, onHold) {+ const [index, setIndex] = useState(null)+ const timer = useRef(null)+ const start = useRef(null)+ const nearest = (event) => {+ const box = event.currentTarget.getBoundingClientRect()+ const share = Math.min(1, Math.max(0, (event.clientX - box.left) / box.width))+ const times = points.map((point) => new Date(point.time).getTime())+ const target = times[0] + share * (times[times.length - 1] - times[0])+ let best = null+ points.forEach((point, position) => { if (point.value != null && (best === null || Math.abs(times[position] - target) < Math.abs(times[best] - target))) best = position })+ return best+ }+ const stop = () => { clearTimeout(timer.current); setIndex(null); onHold?.(false) }+ return {+ index,+ handlers: {+ onPointerDown: (event) => {+ if (event.pointerType === 'mouse') return+ const next = nearest(event)+ start.current = [event.clientX, event.clientY]+ clearTimeout(timer.current)+ timer.current = setTimeout(() => { setIndex(next); onHold?.(true) }, 250)+ },+ // A finger that moves before the hold fires is scrolling or swiping, not reading.+ onPointerMove: (event) => {+ if (event.pointerType === 'mouse' || index !== null) setIndex(nearest(event))+ else if (start.current && Math.hypot(event.clientX - start.current[0], event.clientY - start.current[1]) > 8) clearTimeout(timer.current)+ },+ onPointerUp: stop, onPointerCancel: stop, onPointerLeave: stop,+ onContextMenu: (event) => event.preventDefault(),+ },+ }+}+// A line over time with a labelled axis: ``points`` are [{ time, value }], ``max`` the top of the scale and// ``ticks`` the values to label. ``area`` shades under the line; ``second`` adds a dashed series on the same scale.-export function LineChart({ points, second, max, ticks, format = (value) => String(value), area = false, height = 150, label, gutter = 40 }) {+// ``readout`` (value -> text) turns on reading values by touch-and-hold or hover.+export function LineChart({ points, second, max, ticks, format = (value) => String(value), area = false, height = 150, label, gutter = 40, readout, onHold }) {const gradient = useId()+ const reading = useReadout(points || [], onHold)const usable = (points || []).filter((point) => point.value != null)const times = (points || []).map((point) => new Date(point.time).getTime())const start = times[0]@@ -55,6 +94,16 @@ export function LineChart({ points, second, max, ticks, format = (value) => Stri{line && <path d={line} fill="none" stroke="var(--color-paper)" strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />}</svg>{usable.length < 2 && <span className="absolute inset-0 flex items-center justify-center text-[11px] text-dim">Waiting for a few check-ins</span>}+ {readout && usable.length > 1 && <div className="absolute inset-0 select-none" style={{ touchAction: 'pan-y', WebkitTouchCallout: 'none' }} {...reading.handlers} />}+ {readout && reading.index !== null && points[reading.index] && (() => {+ const point = points[reading.index]+ const left = x(point.time)+ return <>+ <span aria-hidden="true" className="pointer-events-none absolute bottom-0 top-0 w-px bg-paper/70" style={{ left: `${left}%` }} />+ <span aria-hidden="true" className="pointer-events-none absolute h-2 w-2 -translate-x-1/2 -translate-y-1/2 rounded-full border border-paper bg-bg" style={{ left: `${left}%`, top: `${y(point.value)}%` }} />+ <span role="status" className="pointer-events-none absolute -top-9 whitespace-nowrap rounded-md border border-edge bg-raised px-2 py-1 text-[11px] font-medium text-paper" style={{ left: `${Math.min(80, Math.max(0, left - 10))}%` }}>{clock(point.time)} · {readout(point.value)}</span>+ </>+ })()}</div><div aria-hidden="true" className="mt-2 flex justify-between text-[11px] leading-none text-muted" style={{ marginLeft: gutter }}><span>{clock(points?.[0]?.time)}</span><span>{clock(points?.[points.length - 1]?.time)}</span></div></figure>diff --git a/src/frontend/src/icons.jsx b/src/frontend/src/icons.jsxindex 854e4b2..a75f84b 100644--- a/src/frontend/src/icons.jsx+++ b/src/frontend/src/icons.jsx@@ -17,6 +17,13 @@ const paths = {copy: <><rect x="5.5" y="5.5" width="8" height="8" rx="1" /><path d="M10.5 5.5v-2a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2" /></>,arrow: <path d="M3 8h10M9.5 4.5L13 8l-3.5 3.5" />,close: <path d="M4 4l8 8M12 4l-8 8" />,+ more: <path d="M3.5 8h.01M8 8h.01M12.5 8h.01" strokeWidth="2.4" />,+ bell: <><path d="M4 11V7.5a4 4 0 0 1 8 0V11l1 1.5H3z" /><path d="M6.5 14h3" /></>,+ lock: <><rect x="3.5" y="7" width="9" height="6.5" rx="1" /><path d="M5.5 7V5a2.5 2.5 0 0 1 5 0v2" /></>,+ key: <><circle cx="5.5" cy="10.5" r="2.5" /><path d="M7.3 8.7L13 3M11 5l1.5 1.5" /></>,+ eye: <><path d="M1.5 8s2.4-4.5 6.5-4.5S14.5 8 14.5 8s-2.4 4.5-6.5 4.5S1.5 8 1.5 8z" /><circle cx="8" cy="8" r="2" /></>,+ share: <><path d="M9.5 2.5h4v4M13.5 2.5L8 8" /><path d="M11.5 9.5v3a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1h3" /></>,+ chevron: <path d="M6 3.5L10.5 8 6 12.5" />,}export function Icon({ name, size = 16, className = '' }) {diff --git a/src/frontend/src/more/MorePage.jsx b/src/frontend/src/more/MorePage.jsxnew file mode 100644index 0000000..d122318--- /dev/null+++ b/src/frontend/src/more/MorePage.jsx@@ -0,0 +1,90 @@+// The More tab on a phone: your profile, the fleet, and every Account and Admin page as a plain row that shows+// its state on the right (2FA on, 1 failing, 2 waiting), so problems show without opening anything.+import { useMemo } from 'react'+import { Link, Navigate } from 'react-router-dom'+import { serverState, serverStateLabel, sortServers } from '../dashboard/logic.js'+import { Icon } from '../icons.jsx'+import { useOverview } from '../overviewStore.js'+import { AppShell, PhoneHeader, serverLink } from '../shell.jsx'+import { useLoaded, usePhone } from '../ui.jsx'+import { ACCOUNT_GROUPS } from './groups.js'++const STATE_DOT = { critical: 'dot-signal', warn: 'dot-warn', ok: 'dot-ok', offline: '' }+const initials = (name) => { const parts = (name || '?').trim().split(/\s+/); return (parts.length > 1 ? parts[0][0] + parts[parts.length - 1][0] : parts[0].slice(0, 2)).toUpperCase() }++function Group({ title, children }) {+ return (+ <section aria-label={title}>+ <h2 className="m-0 mb-2 px-1 text-xs font-medium text-muted">{title}</h2>+ <div className="divide-y divide-line overflow-hidden rounded-md border border-line bg-ink">{children}</div>+ </section>+ )+}++function Item({ to, icon, dot, title, detail, value, tone }) {+ return (+ <Link to={to} className="flex min-h-14 items-center gap-3.5 px-4 py-2.5">+ {icon && <span aria-hidden="true" className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-line bg-bg text-soft"><Icon name={icon} size={15} /></span>}+ {dot !== undefined && <span className={`dot shrink-0 ${dot}`} />}+ <span className="min-w-0 flex-1"><span className="block truncate text-[15px] text-paper">{title}</span>{detail && <span className="mt-0.5 block truncate text-xs text-muted">{detail}</span>}</span>+ {value && <span className={`shrink-0 text-[13px] ${tone === 'warn' ? 'text-warn' : 'text-muted'}`}>{value}</span>}+ <Icon name="chevron" size={14} className="shrink-0 text-muted" />+ </Link>+ )+}++export default function MorePage({ user, onLogout }) {+ const phone = usePhone()+ const { data: overview } = useOverview(Boolean(user), 30, onLogout)+ const { data: account } = useLoaded(phone ? '/account' : null)+ const { data: sessions } = useLoaded(phone ? '/auth/sessions' : null)+ const servers = useMemo(() => sortServers(overview?.servers || []), [overview])+ // There is no More page on a larger screen: the sidebar holds all of it.+ if (!phone) return <Navigate to="/account" replace />++ const isAdmin = user?.role === 'admin'+ const failing = (account?.channels || []).filter((channel) => channel.last_ok === false).length+ const display = account?.preferences?.display+ const waiting = (overview?.pending_collectors || []).filter((item) => item.status === 'pending').length+ const values = {+ security: account ? [account.two_factor.enabled ? '2FA on' : '2FA off', account.two_factor.enabled ? '' : 'warn'] : null,+ notifications: account ? (failing ? [`${failing} failing`, 'warn'] : [account.channels.length ? `${account.channels.length} ${account.channels.length === 1 ? 'channel' : 'channels'}` : 'none', '']) : null,+ sessions: account && sessions ? [`${sessions.sessions.length} · ${account.tokens.length}`, ''] : null,+ display: display ? [`${display.theme.charAt(0).toUpperCase()}${display.theme.slice(1)} · ${display.time_format === '12h' ? '12 h' : '24 h'}`, ''] : null,+ servers: overview ? (waiting ? [`${waiting} waiting`, 'warn'] : [`${servers.length}`, '']) : null,+ }+ const detail = (server) => {+ const state = serverState(server)+ const label = serverStateLabel(server)+ return server.is_dashboard_host && state !== 'critical' && state !== 'offline' ? `this machine${label === 'healthy' ? '' : ` · ${label}`}` : label+ }++ return (+ <AppShell user={user} onLogout={onLogout} crumbs={[{ label: 'More' }]} bare phoneHeader>+ <PhoneHeader title="More" live={false} action={<span />} />+ <div className="space-y-6 px-4 pt-3">+ {user && <Link to="/account?section=profile" className="flex items-center gap-3.5 rounded-md border border-line bg-ink px-4 py-3.5">+ <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-md border border-line bg-raised text-sm font-semibold text-paper" style={account?.avatar_color ? { color: account.avatar_color, borderColor: account.avatar_color } : undefined}>{initials(account?.name || user.name)}</span>+ <span className="min-w-0 flex-1"><span className="block truncate text-[15px] font-semibold text-paper">{account?.name || user.name}</span><span className="mt-0.5 block truncate text-xs text-muted">{isAdmin ? 'Owner' : 'Member'} · {user.email}</span></span>+ <Icon name="chevron" size={14} className="shrink-0 text-muted" />+ </Link>}++ {servers.length > 0 && <Group title="Fleet">+ {servers.map((server) => <Item key={server.id} to={serverLink(server.id)} dot={STATE_DOT[serverState(server)]} title={server.hostname} detail={detail(server)} />)}+ </Group>}++ <Group title="Account">+ {ACCOUNT_GROUPS.map((group) => <Item key={group.id} to={`/account?section=${group.id}`} icon={group.icon} title={group.label} value={values[group.id]?.[0]} tone={values[group.id]?.[1]} />)}+ </Group>++ {isAdmin && <Group title="Admin">+ <Item to="/admin" icon="admin" title="Servers and collectors" value={values.servers?.[0]} tone={values.servers?.[1]} />+ <Item to="/admin#instance" icon="admin" title="Users, rules, agent, data" />+ </Group>}++ <button type="button" onClick={onLogout} className="flex h-12 w-full items-center justify-center rounded-md border border-signal/50 bg-transparent text-[15px] font-medium text-signal">Sign out</button>+ <p className="m-0 pb-2 text-center text-xs text-dim">Infradeck {overview?.version || ''}{overview?.instance_name ? ` · ${overview.instance_name}` : ''}</p>+ </div>+ </AppShell>+ )+}diff --git a/src/frontend/src/more/groups.js b/src/frontend/src/more/groups.jsnew file mode 100644index 0000000..ab8c7a4--- /dev/null+++ b/src/frontend/src/more/groups.js@@ -0,0 +1,20 @@+// On a phone, Account and Admin are reached from the More tab, one screen per group of sections. ``sections`` are+// the ids of the <Section>s each screen shows.+export const ACCOUNT_GROUPS = [+ { id: 'profile', label: 'Profile', icon: 'account', sections: ['profile'] },+ { id: 'security', label: 'Security', icon: 'lock', sections: ['security'] },+ { id: 'notifications', label: 'Notifications', icon: 'bell', sections: ['notifications'] },+ { id: 'sessions', label: 'Sessions and tokens', icon: 'key', sections: ['sessions', 'tokens'] },+ { id: 'display', label: 'Display', icon: 'eye', sections: ['display'] },+]++// The Admin page on a phone starts from a list (servers, then the instance settings); each row opens one of these.+export const ADMIN_GROUPS = [+ { id: 'servers', label: 'Servers', sections: ['servers'] },+ { id: 'connect', label: 'Connect a server', sections: ['connect'] },+ { id: 'users', label: 'Users', sections: ['users'] },+ { id: 'rules', label: 'Alert rules', sections: ['rules'] },+ { id: 'agent', label: 'Incident agent', sections: ['agent'] },+ { id: 'retention', label: 'Data and retention', sections: ['retention'] },+ { id: 'about', label: 'About', sections: ['about'] },+]diff --git a/src/frontend/src/shell.jsx b/src/frontend/src/shell.jsxindex a5fc4ff..05cadb6 100644--- a/src/frontend/src/shell.jsx+++ b/src/frontend/src/shell.jsx@@ -1,6 +1,7 @@// The frame around every signed-in page: sidebar with fleet status, top bar with the live indicator and the-// jump-to palette. Phones get a top bar and a tab bar instead of the sidebar.-import { useEffect, useMemo, useRef, useState } from 'react'+// jump-to palette. Tablets get an icon rail instead of the sidebar; phones a page header and a tab bar+// (Overview, Statistics, Agent, More), with Account, Admin and the fleet under More.+import { createContext, useContext, useEffect, useMemo, useRef, useState } from 'react'import { Link, NavLink, useLocation, useNavigate } from 'react-router-dom'import { apiRequest } from './api.js'import { isOnline } from './fleetLogic.js'@@ -96,7 +97,7 @@ function Sidebar({ user, onLogout, overview, error }) {const open = (overview?.alerts_by_severity?.CRITICAL || 0) + (overview?.alerts_by_severity?.WARNING || 0)const selected = location.pathname === '/' ? new URLSearchParams(location.search).get('server') : nullreturn (- <aside className="fixed inset-y-0 left-0 z-20 hidden w-[236px] flex-col border-r border-line bg-bg px-3.5 pb-3 pt-[22px] lg:flex">+ <aside className="fixed inset-y-0 left-0 z-20 hidden w-[236px] flex-col border-r border-line bg-bg px-3.5 pb-3 pt-[22px] xl:flex"><Link to="/" className="block px-2" aria-label="Infradeck, go to Overview"><img src="/logo.svg" alt="Infradeck" className="h-5 w-auto" /></Link><div className="mt-2 truncate px-2 text-[11px] text-muted">{overview?.instance_name || instanceName(user)}{overview?.version ? ` · v${overview.version}` : ''}</div>@@ -139,6 +140,32 @@ function Sidebar({ user, onLogout, overview, error }) {)}+// 768-1199 px: the sidebar shrinks to icons. The fleet list moves out; the pages and the account stay.+function Rail({ user, onLogout, overview }) {+ const open = (overview?.alerts_by_severity?.CRITICAL || 0) + (overview?.alerts_by_severity?.WARNING || 0)+ const items = [...primaryNav, ...secondaryNav].filter((item) => !item.adminOnly || user?.role === 'admin')+ return (+ <aside className="fixed inset-y-0 left-0 z-20 hidden w-16 flex-col items-center border-r border-line bg-bg pb-3 pt-[22px] md:flex xl:hidden">+ <Link to="/" aria-label="Infradeck, go to Overview" className="flex h-8 items-center"><LogoMark /></Link>+ <nav aria-label="Main" className="mt-6 flex flex-col items-center gap-1">+ {items.map((item) => (+ <NavLink key={item.to} to={item.to} end={item.to === '/'} title={item.label} aria-label={item.label} className={({ isActive }) => `relative flex h-10 w-10 items-center justify-center rounded-md transition-colors ${isActive ? 'bg-raised text-paper' : 'text-muted hover:bg-ink hover:text-paper'}`}>+ {({ isActive }) => <>+ {isActive && <span aria-hidden="true" className="absolute -left-3 top-1 h-8 w-[3px] rounded-r-sm bg-signal" />}+ <Icon name={item.icon} size={17} />+ {item.to === '/agent' && open > 0 && <span className="absolute right-0.5 top-0.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-signal px-0.5 text-[9px] font-semibold text-bg">{open}</span>}+ </>}+ </NavLink>+ ))}+ </nav>+ {user && <div className="mt-auto flex flex-col items-center gap-2">+ <span title={`${user.name} · ${roleLabel(user.role)}`} className="flex h-8 w-8 items-center justify-center rounded-md border border-line bg-raised text-[11px] font-semibold text-paper">{initials(user.name)}</span>+ <button type="button" onClick={onLogout} aria-label="Sign out" title="Sign out" className="flex h-8 w-8 items-center justify-center rounded-md text-muted hover:bg-ink hover:text-paper"><Icon name="signout" size={15} /></button>+ </div>}+ </aside>+ )+}+// "Live · checked 4s ago", counting up between polls.function LiveStatus({ overview, loadedAt, error }) {const [, tick] = useState(0)@@ -212,7 +239,7 @@ function CommandPalette({ overview, isAdmin, onClose }) {function TopBar({ crumbs, overview, loadedAt, error, onOpenPalette }) {const mac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || '')return (- <header className="sticky top-0 z-10 hidden h-14 items-center gap-5 border-b border-line bg-bg px-7 lg:flex">+ <header className="sticky top-0 z-10 hidden h-14 items-center gap-5 border-b border-line bg-bg px-7 md:flex"><nav aria-label="Breadcrumb" className="flex min-w-0 items-center gap-3 text-sm font-semibold">{crumbs.map((crumb, position) => {const last = position === crumbs.length - 1@@ -224,7 +251,7 @@ function TopBar({ crumbs, overview, loadedAt, error, onOpenPalette }) {</nav><div className="ml-auto flex items-center gap-4"><LiveStatus overview={overview} loadedAt={loadedAt} error={error} />- <button type="button" onClick={onOpenPalette} className="flex h-8 w-[300px] items-center gap-3 rounded-md border border-line bg-bg px-3 text-left text-xs text-dim transition-colors hover:border-edge">+ <button type="button" onClick={onOpenPalette} className="flex h-8 w-[300px] items-center md:w-[220px] lg:w-[300px] gap-3 rounded-md border border-line bg-bg px-3 text-left text-xs text-dim transition-colors hover:border-edge"><Icon name="search" size={14} className="text-muted" /><span className="flex-1 truncate">Jump to server, container, port…</span><kbd className="mono rounded border border-line px-1 text-[10px] leading-4 text-dim">{mac ? '⌘K' : 'Ctrl K'}</kbd>@@ -234,52 +261,67 @@ function TopBar({ crumbs, overview, loadedAt, error, onOpenPalette }) {)}-function MobileTopBar({ user, onLogout }) {- const [menuOpen, setMenuOpen] = useState(false)+// The three blocks of the Infradeck mark, for places too small for the wordmark.+export function LogoMark({ className = 'h-[22px] w-auto' }) {+ return <svg viewBox="2.66 -32.01 8.27 32.01" className={className} aria-hidden="true"><rect x="2.66" y="-32.01" width="5.67" height="9.47" fill="var(--color-paper)" /><rect x="5.26" y="-20.74" width="5.67" height="9.47" fill="var(--color-signal)" /><rect x="2.66" y="-9.47" width="5.67" height="9.47" fill="var(--color-paper)" /></svg>+}++const ShellContext = createContext({ openPalette: () => {}, overview: null, loadedAt: 0, error: '' })+export const useShell = () => useContext(ShellContext)+// "4s ago" next to a green dot: the phone's short form of the live indicator.+function ShortLive() {+ const { overview, loadedAt, error } = useShell()+ const [, tick] = useState(0)useEffect(() => {- if (!menuOpen) return undefined- const close = (event) => { if (event.key === 'Escape') setMenuOpen(false) }- window.addEventListener('keydown', close)- return () => window.removeEventListener('keydown', close)- }, [menuOpen])+ const timer = setInterval(() => tick((value) => value + 1), 1000)+ return () => clearInterval(timer)+ }, [])+ if (!overview?.servers?.length) return null+ const seconds = Math.max(0, Math.round((Date.now() - loadedAt) / 1000))+ const stale = Boolean(error) || seconds > 30+ return <span className="flex items-center gap-1.5 whitespace-nowrap text-xs text-soft" title={error || undefined}><span className={`dot ${stale ? 'dot-warn' : 'dot-ok'}`} style={{ width: 7, height: 7 }} />{stale ? 'stale' : `${seconds}s ago`}</span>+}++export function RoundButton({ label, icon, onClick, children, ...rest }) {+ return <button type="button" onClick={onClick} aria-label={label} title={label} className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full border border-edge bg-transparent text-soft hover:text-paper" {...rest}>{children || <Icon name={icon} size={16} />}</button>+}+// A phone page's header: either the mark and the page name (top level), or a back link over the name (one level+// down). ``subtitle`` is a line under the name; ``action`` replaces the search button on the right.+export function PhoneHeader({ title, back, subtitle, action, live = !back, mark = false }) {+ const { openPalette } = useShell()return (- <header className="sticky top-0 z-30 border-b border-line bg-bg pt-[env(safe-area-inset-top)] lg:hidden">- <div className="flex h-14 items-center justify-between px-4">- <Link to="/" aria-label="Infradeck, go to Overview"><img src="/logo.svg" alt="Infradeck" className="h-[18px] w-auto" /></Link>- {user && (- <div className="relative">- <button type="button" onClick={() => setMenuOpen((open) => !open)} aria-expanded={menuOpen} aria-haspopup="menu" aria-label="Account menu" className="flex h-9 w-9 items-center justify-center rounded-md border border-line bg-raised text-[11px] font-semibold text-paper">{initials(user.name)}</button>- {menuOpen && <>- <button type="button" aria-label="Close account menu" onClick={() => setMenuOpen(false)} className="fixed inset-0 z-10 cursor-default" />- <div role="menu" className="card absolute right-0 z-20 mt-2 w-64 p-3">- <div className="px-1 text-[13px] font-medium text-paper">{user.name}</div>- <div className="truncate px-1 text-[11px] text-muted">{user.email}</div>- <button type="button" role="menuitem" onClick={() => { setMenuOpen(false); onLogout() }} className="btn mt-3 h-10 w-full">Sign out</button>- </div>- </>}- </div>- )}+ <header className="px-4 pb-1 pt-[calc(14px+env(safe-area-inset-top))] md:hidden">+ {back && <Link to={back.to} className="-ml-1 mb-0.5 inline-flex h-7 items-center gap-1 text-[13px] text-muted hover:text-paper"><svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M10 3.5L5.5 8l4.5 4.5" /></svg>{back.label}</Link>}+ <div className="flex items-center gap-3">+ {mark && !back && <LogoMark />}+ <h1 className={`m-0 min-w-0 flex-1 text-[22px] font-semibold text-paper ${back ? 'line-clamp-2 break-words leading-7' : 'truncate leading-8'}`}>{title}</h1>+ {live && <ShortLive />}+ {action || <RoundButton label="Jump to server, container or port" icon="search" onClick={openPalette} />}</div>+ {subtitle && <div className="mt-1.5 text-[13px] leading-5 text-soft">{subtitle}</div>}</header>)}-function MobileTabBar({ user, open }) {- const items = [...primaryNav, ...secondaryNav].filter((item) => !item.adminOnly || user?.role === 'admin')+function MobileTabBar({ open }) {+ const location = useLocation()+ // More holds Account and Admin, so it stays lit on their pages.+ const inMore = ['/more', '/account', '/admin'].includes(location.pathname)+ const tab = (active, icon, label, badge) => <>+ <span className="relative"><Icon name={icon} size={20} />{badge > 0 && <span className="absolute -right-2.5 -top-1.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-signal px-1 text-[10px] font-semibold text-bg">{badge}</span>}</span>+ <span className={active ? 'text-paper' : ''}>{label}</span>+ </>return (- <nav aria-label="Main" className="fixed inset-x-0 bottom-0 z-30 border-t border-line bg-bg pb-[env(safe-area-inset-bottom)] lg:hidden">- <div className="mx-auto grid max-w-md" style={{ gridTemplateColumns: `repeat(${items.length}, minmax(0, 1fr))` }}>- {items.map((item) => (- <NavLink key={item.to} to={item.to} end={item.to === '/'} className={({ isActive }) => `relative flex h-16 flex-col items-center justify-center gap-1.5 text-[11px] font-medium ${isActive ? 'text-paper' : 'text-muted'}`}>- {({ isActive }) => <>- {isActive && <span aria-hidden="true" className="absolute top-0 h-[3px] w-8 rounded-b-sm bg-signal" />}- <span className="relative"><Icon name={item.icon} size={18} />{item.to === '/agent' && open > 0 && <span className="absolute -right-2.5 -top-1.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-signal px-0.5 text-[9px] font-semibold text-bg">{open}</span>}</span>- {item.label}- </>}+ <nav aria-label="Main" className="fixed inset-x-0 bottom-0 z-30 border-t border-line bg-bg pb-[env(safe-area-inset-bottom)] md:hidden">+ <div className="mx-auto grid max-w-md grid-cols-4">+ {primaryNav.map((item) => (+ <NavLink key={item.to} to={item.to} end={item.to === '/'} className={({ isActive }) => `flex h-[60px] flex-col items-center justify-center gap-1 text-[11px] font-medium ${isActive ? 'text-paper' : 'text-muted'}`}>+ {({ isActive }) => tab(isActive, item.icon, item.label, item.to === '/agent' ? open : 0)}</NavLink>))}+ <Link to="/more" aria-current={inMore ? 'page' : undefined} className={`flex h-[60px] flex-col items-center justify-center gap-1 text-[11px] font-medium ${inMore ? 'text-paper' : 'text-muted'}`}>{tab(inMore, 'more', 'More', 0)}</Link></div></nav>)@@ -287,7 +329,9 @@ function MobileTabBar({ user, open }) {// ``crumbs``: [{ label, to? }] for the top bar; defaults to the page's own name.// ``bare``: the page lays out its own padding (the redesigned pages); otherwise the shell pads the content.-export function AppShell({ children, user, onLogout, fitViewport = false, crumbs, bare = false }) {+// ``phoneHeader``: the page draws its own <PhoneHeader>; otherwise phones get the page name from the crumbs.+// ``phoneTabs``: false hides the phone tab bar, for screens that pin their own actions to the bottom.+export function AppShell({ children, user, onLogout, fitViewport = false, crumbs, bare = false, phoneHeader = false, phoneTabs = true }) {const location = useLocation()const navigate = useNavigate()const [paletteOpen, setPaletteOpen] = useState(false)@@ -311,16 +355,23 @@ export function AppShell({ children, user, onLogout, fitViewport = false, crumbsreturn () => window.removeEventListener('keydown', onKeyDown)}, [navigate])+ const last = trail[trail.length - 1]+ const parent = trail.length > 1 ? [...trail].reverse().find((crumb) => crumb.to) : null+ const shell = useMemo(() => ({ openPalette: () => setPaletteOpen(true), overview, loadedAt, error }), [overview, loadedAt, error])+return (- <div className={`${fitViewport ? 'xl:h-screen xl:overflow-hidden' : ''} min-h-screen bg-bg text-paper`}>- <MobileTopBar user={user} onLogout={onLogout} />- <Sidebar user={user} onLogout={onLogout} overview={overview} error={error} />- <div className={`${fitViewport ? 'xl:flex xl:h-full xl:flex-col' : ''} lg:pl-[236px]`}>- <TopBar crumbs={trail} overview={overview} loadedAt={loadedAt} error={error} onOpenPalette={() => setPaletteOpen(true)} />- <main className={`${fitViewport ? 'xl:min-h-0 xl:flex-1' : ''} min-w-0 ${bare ? '' : 'px-3 pt-4 sm:px-4 lg:px-7 lg:pt-6'} pb-[calc(5.5rem+env(safe-area-inset-bottom))] lg:pb-7`}>{children}</main>+ <ShellContext.Provider value={shell}>+ <div className={`${fitViewport ? 'xl:h-screen xl:overflow-hidden' : ''} min-h-screen bg-bg text-paper`}>+ <Sidebar user={user} onLogout={onLogout} overview={overview} error={error} />+ <Rail user={user} onLogout={onLogout} overview={overview} />+ <div className={`${fitViewport ? 'xl:flex xl:h-full xl:flex-col' : ''} md:pl-16 xl:pl-[236px]`}>+ <TopBar crumbs={trail} overview={overview} loadedAt={loadedAt} error={error} onOpenPalette={() => setPaletteOpen(true)} />+ {!phoneHeader && <PhoneHeader title={last?.label || 'Infradeck'} back={parent ? { label: parent.label, to: parent.to } : null} />}+ <main className={`${fitViewport ? 'xl:min-h-0 xl:flex-1' : ''} min-w-0 ${bare ? '' : 'px-4 pt-4 md:px-7 md:pt-6'} ${phoneTabs ? 'pb-[calc(5.5rem+env(safe-area-inset-bottom))]' : ''} md:pb-7`}>{children}</main>+ </div>+ {phoneTabs && <MobileTabBar open={open} />}+ {paletteOpen && <CommandPalette overview={overview} isAdmin={user?.role === 'admin'} onClose={() => setPaletteOpen(false)} />}</div>- <MobileTabBar user={user} open={open} />- {paletteOpen && <CommandPalette overview={overview} isAdmin={user?.role === 'admin'} onClose={() => setPaletteOpen(false)} />}- </div>+ </ShellContext.Provider>)}diff --git a/src/frontend/src/statistics/ContainersTable.jsx b/src/frontend/src/statistics/ContainersTable.jsxindex 8d56659..d75aaa1 100644--- a/src/frontend/src/statistics/ContainersTable.jsx+++ b/src/frontend/src/statistics/ContainersTable.jsx@@ -57,7 +57,7 @@ function ContainerHistory({ serverId, container, range, compare }) {)}-export function ContainersTable({ server, usage, range, compare, selectedId, onSelect }) {+export function ContainersTable({ server, usage, range, compare, selectedId, onSelect, phone = false }) {const [query, setQuery] = useState('')const [sort, setSort] = useState('avg_cpu')const [all, setAll] = useState(false)@@ -77,6 +77,42 @@ export function ContainersTable({ server, usage, range, compare, selectedId, onSconst top = Math.max(100, ...rows.flatMap((row) => row.sparkline || []).filter((value) => value != null))const swapKnown = rows.some((row) => row.swap != null)+ // Phones: a ranked list with the one or two numbers that matter per row, instead of a ten-column table.+ if (phone) {+ const shown = all ? rows : rows.filter((row, index) => index < 5 || row.container_id === selectedId)+ return (+ <section aria-label="Containers">+ <div className="mb-2.5 flex items-baseline gap-2">+ <h2 className="m-0 text-[15px] font-semibold text-paper">Top containers</h2><span className="text-xs text-muted">by average CPU</span>+ {rows.length > 5 && <button type="button" onClick={() => setAll((value) => !value)} className="ml-auto h-7 border-0 bg-transparent p-0 text-[13px] text-soft">{all ? 'Top 5' : `All ${rows.length}`}</button>}+ </div>+ {!usage ? <p className="m-0 rounded-md border border-line bg-ink py-8 text-center text-xs text-muted">Loading…</p> : !rows.length ? <p className="m-0 rounded-md border border-line bg-ink px-4 py-6 text-center text-xs text-muted">No containers reported on {server.hostname} in this range.</p> : (+ <div className="divide-y divide-line overflow-hidden rounded-md border border-line bg-ink">+ {shown.map((row) => {+ const open = row.container_id === selectedId+ return (+ <div key={row.container_id}>+ <button type="button" aria-expanded={open} onClick={() => onSelect(open ? '' : row.container_id)} className={`grid w-full grid-cols-[30px_minmax(0,1fr)_auto] gap-x-2 border-0 px-4 py-3 text-left ${open ? 'bg-raised' : 'bg-transparent'}`}>+ <span className="mono pt-0.5 text-xs text-dim">{String(rank.get(row.container_id)).padStart(2, '0')}</span>+ <span className="min-w-0">+ <span className="block truncate text-sm font-medium text-paper">{row.name}</span>+ <span className="mt-1 block truncate text-xs text-muted">peak <span className={row.max_cpu >= 100 ? 'text-signal' : ''}>{formatPercent(row.max_cpu)}</span> · {megabytes(row.avg_memory_mb)}{row.swap >= 1 && <> · swap <span className="text-warn">{megabytes(row.swap)}</span></>}{row.restarts ? <> · <span className="text-warn">{row.restarts} restarts</span></> : ''}</span>+ </span>+ <span className="text-right">+ <span className="block text-sm font-medium text-paper">{formatPercent(row.avg_cpu)}</span>+ <Sparkline values={row.sparkline} width={78} height={16} max={top} className="mt-1.5" />+ </span>+ </button>+ {open && <div className="border-t border-line"><ContainerHistory serverId={server.id} container={{ ...row, image: row.now?.image, memory_limit_mb: row.now?.memory_limit_mb && row.now.memory_limit_mb < (server.total_ram_gb || 0) * 1024 * 0.98 ? row.now.memory_limit_mb : null }} range={range} compare={compare} /></div>}+ </div>+ )+ })}+ </div>+ )}+ </section>+ )+ }+return (<section className="card overflow-hidden" aria-label="Containers"><div className="flex flex-wrap items-center gap-x-3 gap-y-2.5 px-[18px] py-3">diff --git a/src/frontend/src/statistics/Insights.jsx b/src/frontend/src/statistics/Insights.jsxindex c8d254a..383eb12 100644--- a/src/frontend/src/statistics/Insights.jsx+++ b/src/frontend/src/statistics/Insights.jsx@@ -69,19 +69,19 @@ export function BusyHours({ serverId }) {{!error && !grid && <p className="m-0 py-10 text-center text-xs text-muted">Loading…</p>}{grid && !values.length && <p className="m-0 py-10 text-center text-xs text-muted">Not enough history yet. This fills in as hourly summaries are built.</p>}{grid && values.length > 0 && <>- <div className="custom-scroll overflow-x-auto"><div className="min-w-[520px]">+ <div className="custom-scroll overflow-x-auto"><div className="md:min-w-[520px]">{grid.map((row, day) => (- <div key={DAY_NAMES[day]} className="flex items-center gap-[3px] py-[1.5px]">- <span className="w-9 shrink-0 text-[11px] text-muted">{DAY_NAMES[day]}</span>+ <div key={DAY_NAMES[day]} className="flex items-center gap-[2px] py-[1px] md:gap-[3px] md:py-[1.5px]">+ <span className="w-8 shrink-0 text-[11px] text-muted md:w-9">{DAY_NAMES[day]}</span>{row.map((value, hour) => (<button key={hour} type="button" aria-label={`${DAY_NAMES[day]} ${pad(hour)}:00, ${value == null ? 'no data' : formatPercent(value)}`}onPointerEnter={() => setHover({ day, hour, value })} onFocus={() => setHover({ day, hour, value })} onPointerLeave={() => setHover(null)} onBlur={() => setHover(null)}- className="h-[22px] flex-1 cursor-default rounded-[3px] border-0 p-0"+ className="h-4 min-w-0 flex-1 cursor-default rounded-[2px] border-0 p-0 md:h-[22px] md:rounded-[3px]"style={{ background: value == null ? 'var(--color-sunken)' : `color-mix(in srgb, var(--color-paper) ${Math.round(14 + 86 * Math.min(1, value / cap))}%, var(--color-ink))` }} />))}</div>))}- <div className="flex gap-[3px] pt-1.5" aria-hidden="true"><span className="w-9 shrink-0" />{Array.from({ length: 24 }, (_, hour) => <span key={hour} className="flex-1 text-center text-[11px] text-muted">{hour % 3 === 0 ? pad(hour) : ''}</span>)}</div>+ <div className="flex gap-[3px] pt-1.5" aria-hidden="true"><span className="w-8 shrink-0 md:w-9" />{Array.from({ length: 24 }, (_, hour) => <span key={hour} className={`min-w-0 flex-1 text-center text-[11px] text-muted ${hour % 6 ? 'invisible md:visible' : ''}`}>{hour % 3 === 0 ? pad(hour) : ''}</span>)}</div></div></div><div className="mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-muted"><span className="flex items-center gap-2.5" aria-hidden="true">0%<span className="h-2 w-[140px] rounded-sm" style={{ background: 'linear-gradient(90deg, color-mix(in srgb, var(--color-paper) 14%, var(--color-ink)), var(--color-paper))' }} />{cap}%+</span>diff --git a/src/frontend/src/statistics/Phone.jsx b/src/frontend/src/statistics/Phone.jsxnew file mode 100644index 0000000..72f1287--- /dev/null+++ b/src/frontend/src/statistics/Phone.jsx@@ -0,0 +1,202 @@+// Statistics on a phone: the same data reordered for one thumb. Numbers before charts, the findings next, and the+// timeline on its own screen where touch-and-hold scrubs all four charts at once with the readout above the finger.+import { useEffect, useMemo, useRef, useState } from 'react'+import { Sparkline } from '../dashboard/charts.jsx'+import { PhoneHeader } from '../shell.jsx'+import { GUTTER, HATCH, PAD_RIGHT, Plot, axisTicks, nearest, scaleTop } from './Timeline.jsx'+import { busiestAt, formatPeriod, percentile } from './logic.js'++const TONE = { paper: 'var(--color-paper)', warn: 'var(--color-warn)' }+const CARD_PAD = 12++export function Pills({ label, items, value, onChange }) {+ const row = useRef(null)+ useEffect(() => { row.current?.querySelector('[aria-pressed="true"]')?.scrollIntoView({ block: 'nearest', inline: 'nearest' }) }, [value])+ return (+ <div ref={row} className="no-scrollbar -mx-4 flex gap-2 overflow-x-auto px-4" role="group" aria-label={label}>+ {items.map((item) => (+ <button key={item.id} type="button" aria-pressed={value === item.id} onClick={() => onChange(item.id)} className={`flex h-10 shrink-0 items-center gap-2 rounded-full border px-4 text-[13px] font-medium ${value === item.id ? 'border-paper bg-paper text-bg' : 'border-edge bg-transparent text-soft'}`}>+ {item.dot !== undefined && <span className={`dot ${item.dot}`} style={{ width: 7, height: 7 }} />}{item.label}+ </button>+ ))}+ </div>+ )+}++// The six headline numbers as a 2 × 3 grid of small cards.+export function PhoneKpis({ items }) {+ return (+ <section className="grid grid-cols-2 gap-2" aria-label="Headline figures">+ {items.map((item) => (+ <div key={item.label} className="min-w-0 rounded-md border border-line bg-ink px-3.5 pb-3 pt-3">+ <div className="truncate text-xs text-muted">{item.label}</div>+ <div className={`mt-1.5 text-[22px] font-semibold leading-7 ${item.tone === 'warn' ? 'text-warn' : 'text-paper'}`}>{item.value}</div>+ <div className={`mt-1 min-h-4 text-xs leading-4 ${item.subTone === 'warn' ? 'text-warn' : 'text-muted'}`}>{item.sub}</div>+ </div>+ ))}+ </section>+ )+}++export function PhoneFindings({ title, findings, empty, onShow }) {+ return (+ <section aria-label={title}>+ <div className="mb-2.5 flex items-baseline gap-2"><h2 className="m-0 text-[15px] font-semibold text-paper">{title}</h2><span className="text-xs text-muted">{findings.length}</span></div>+ {findings.length ? (+ <ol className="m-0 list-none divide-y divide-line overflow-hidden rounded-md border border-line bg-ink p-0">+ {findings.map((finding) => (+ <li key={finding.key} className="px-4 py-3.5">+ <div className="text-sm font-semibold text-paper">{finding.title}</div>+ <p className="mb-0 mt-1 text-[13px] leading-5 text-soft">{finding.text}</p>+ {finding.at != null && <button type="button" onClick={() => onShow(finding.at)} className="mt-2 inline-flex h-8 items-center border-0 bg-transparent p-0 text-[13px] font-medium text-paper">Show on timeline →</button>}+ </li>+ ))}+ </ol>+ ) : <p className="m-0 rounded-md border border-line bg-ink px-4 py-3.5 text-[13px] text-soft">{empty}</p>}+ </section>+ )+}++// On the main screen the timeline is a preview that opens its own screen.+export function TimelineEntry({ series, start, end, bucketSeconds, gaps, words, onOpen }) {+ return (+ <section className="rounded-md border border-line bg-ink" aria-label="Timeline">+ <div className="flex items-baseline gap-2 px-4 pt-3.5"><h2 className="m-0 text-[15px] font-semibold text-paper">Timeline</h2><span className="text-xs text-muted">CPU, memory, swap and load · last {words}</span></div>+ <div className="px-1 pt-4">{series.length ? <Plot series={series} start={start} end={end} top={100} ticks={[100, 0]} format={(tick) => `${tick}%`} bucketSeconds={bucketSeconds} gaps={gaps} height={64} /> : <p className="m-0 py-6 text-center text-xs text-muted">Nothing was recorded in this range.</p>}</div>+ <div className="p-3"><button type="button" onClick={onOpen} className="btn h-11 w-full text-sm">Open timeline</button></div>+ </section>+ )+}++// The timeline screen. ``rows`` as for the desktop Timeline, plus ``phone``: the note on the right of each chart.+export function PhoneTimeline({ rows, points, previous, start, end, bucketSeconds, gaps, marks, busiest, utc, focusT, legend, back, rangeControl }) {+ const [index, setIndex] = useState(() => (focusT && points.length ? nearest(points, focusT) : null))+ const [asTable, setAsTable] = useState(false)+ const box = useRef(null)+ const hold = useRef({ timer: null, active: false, start: null })+ const span = Math.max(1, end - start)+ const series = useMemo(() => Object.fromEntries(rows.map((row) => [row.key, points.map((point) => ({ t: point.t, avg: point[row.key]?.avg ?? null, max: point[row.key]?.max ?? null, samples: point.samples }))])), [rows, points])+ const before = useMemo(() => Object.fromEntries(rows.map((row) => [row.key, (previous || []).map((point) => ({ t: point.t, avg: point[row.key]?.avg ?? null, max: null }))])), [rows, previous])++ useEffect(() => { if (focusT && points.length) setIndex(nearest(points, focusT)) }, [focusT, points])++ const at = (event) => {+ const rect = box.current.getBoundingClientRect()+ const fraction = (event.clientX - rect.left - CARD_PAD - GUTTER) / (rect.width - 2 * CARD_PAD - GUTTER - PAD_RIGHT)+ return nearest(points, start + Math.min(1, Math.max(0, fraction)) * span)+ }+ const handlers = {+ onPointerDown: (event) => {+ if (!points.length) return+ if (event.pointerType === 'mouse') { setIndex(at(event)); return }+ const next = at(event)+ hold.current.start = [event.clientX, event.clientY]+ clearTimeout(hold.current.timer)+ hold.current.timer = setTimeout(() => { hold.current.active = true; setIndex(next) }, 200)+ },+ onPointerMove: (event) => {+ if (!points.length) return+ if (event.pointerType === 'mouse' || hold.current.active) setIndex(at(event))+ else if (hold.current.start && Math.hypot(event.clientX - hold.current.start[0], event.clientY - hold.current.start[1]) > 8) clearTimeout(hold.current.timer)+ },+ onPointerUp: () => { clearTimeout(hold.current.timer); hold.current.active = false },+ onPointerCancel: () => { clearTimeout(hold.current.timer); hold.current.active = false },+ onContextMenu: (event) => event.preventDefault(),+ }++ const point = index != null ? points[index] : points[points.length - 1] || null+ const who = point ? busiestAt(busiest, point.t) : null+ const ticks = axisTicks(start, end, utc)+ const edge = ticks.length > 2 ? [ticks[0], ticks[Math.floor(ticks.length / 2)], ticks[ticks.length - 1]] : ticks++ return (+ <>+ <PhoneHeader back={back} title="Timeline" action={rangeControl} />+ <div className="space-y-3 px-4 pt-3">+ <div role="status" className="sticky top-2 z-10 rounded-md border border-edge bg-bg px-3.5 py-3 shadow-[0_8px_24px_rgba(0,0,0,0.45)]">+ <div className="flex items-baseline justify-between gap-3 text-[13px]">+ <span className="min-w-0 truncate font-semibold text-paper">{point ? `${index == null ? 'Latest · ' : ''}${formatPeriod(point.t, bucketSeconds, utc)}` : 'No data'}</span>+ {who && <span className="shrink-0 text-xs text-soft">busiest: <span className="text-paper">{who.name}</span></span>}+ </div>+ <div className="mt-2 grid grid-cols-4 gap-2">+ {rows.map((row) => (+ <div key={row.key} className="min-w-0">+ <div className="truncate text-[11px] text-muted">{row.short || row.label}</div>+ <div className={`mt-0.5 text-[17px] font-semibold ${row.tone === 'warn' && (point?.[row.key]?.avg ?? 0) > 0 ? 'text-warn' : 'text-paper'}`}>{point?.[row.key]?.avg == null ? '–' : row.format(point[row.key].avg)}</div>+ {row.pair && point?.[row.key]?.max != null && <div className="text-[11px] text-muted">max {row.format(point[row.key].max)}</div>}+ </div>+ ))}+ </div>+ </div>++ {asTable ? (+ <div className="custom-scroll max-h-[60vh] overflow-auto rounded-md border border-line bg-ink">+ <table className="w-full border-collapse text-left text-xs">+ <thead className="sticky top-0 bg-ink"><tr className="grid-head h-9"><th className="pl-3 font-medium">Period</th>{rows.map((row) => <th key={row.key} className="pr-3 text-right font-medium">{row.short || row.label}</th>)}</tr></thead>+ <tbody>{[...points].reverse().map((item) => <tr key={item.t} className="h-9 border-t border-line text-soft"><td className="whitespace-nowrap pl-3 text-muted">{formatPeriod(item.t, bucketSeconds, utc).replace(/^[A-Z][a-z]{2} /, '')}</td>{rows.map((row) => <td key={row.key} className="pr-3 text-right">{item[row.key]?.avg == null ? '–' : row.format(item[row.key].avg)}</td>)}</tr>)}</tbody>+ </table>+ </div>+ ) : (+ <div ref={box} className="select-none overflow-hidden rounded-md border border-line bg-ink" style={{ touchAction: 'pan-y', WebkitTouchCallout: 'none' }} {...handlers} aria-label="Timeline. Touch and hold to read every metric at one moment.">+ {marks && <div className="border-b border-line pb-2.5 pt-3" style={{ paddingLeft: CARD_PAD, paddingRight: CARD_PAD }}>+ <div className="flex items-baseline justify-between text-[13px] font-medium text-paper"><span>Events</span><span className="text-xs font-normal text-muted">{marks.length}</span></div>+ <div className="relative mt-2 h-3" style={{ marginLeft: GUTTER, marginRight: PAD_RIGHT }}>+ {marks.map((mark) => <span key={`${mark.t}-${mark.kind}`} title={mark.label} className="absolute top-1/2 h-2 w-2 -translate-x-1/2 -translate-y-1/2" style={{ left: `${((mark.t - start) / span) * 100}%`, background: mark.tone === 'signal' ? 'var(--color-signal)' : mark.tone === 'warn' ? 'var(--color-warn)' : 'var(--color-dim)' }} />)}+ {point && <span aria-hidden="true" className="absolute -bottom-2.5 -top-1 w-px bg-paper/70" style={{ left: `${((point.t - start) / span) * 100}%` }} />}+ </div>+ </div>}+ {rows.map((row, position) => {+ const own = series[row.key]+ const top = scaleTop(row, own, before[row.key])+ return (+ <div key={row.key} className={`pb-2 pt-3 ${position ? 'border-t border-line' : ''}`} style={{ paddingLeft: CARD_PAD, paddingRight: CARD_PAD }}>+ <div className="mb-3 flex items-baseline justify-between text-[13px]"><span className="font-medium text-paper">{row.label}</span><span className="text-xs text-muted">{row.phone}</span></div>+ <Plot series={own} previous={before[row.key]} start={start} end={end} top={top} ticks={[top, 0]} format={row.axis || row.format} bucketSeconds={bucketSeconds} gaps={gaps} tone={row.tone} band={row.band !== false} height={78}>+ {({ x, y }) => <>+ {row.limit && row.limit.value <= top && <span aria-hidden="true" className="absolute inset-x-0 border-t border-dashed border-signal/70" style={{ top: `${y(row.limit.value)}%` }} />}+ {point && <span aria-hidden="true" className="absolute -bottom-2 -top-3 w-px bg-paper/70" style={{ left: `${x(point.t)}%` }} />}+ {point && point[row.key]?.avg != null && <span aria-hidden="true" className="absolute h-[9px] w-[9px] -translate-x-1/2 -translate-y-1/2 rounded-full border-[1.5px] bg-ink" style={{ left: `${x(point.t)}%`, top: `${y(point[row.key].avg)}%`, borderColor: TONE[row.tone] || TONE.paper }} />}+ </>}+ </Plot>+ </div>+ )+ })}+ <div className="relative mb-3 h-4 text-[11px] text-muted" style={{ marginLeft: CARD_PAD + GUTTER, marginRight: CARD_PAD + PAD_RIGHT }} aria-hidden="true">+ {edge.map((tick, position) => <span key={tick.t} className={`absolute whitespace-nowrap ${position === edge.length - 1 ? '-translate-x-full' : position ? '-translate-x-1/2' : ''}`} style={{ left: `${((tick.t - start) / span) * 100}%` }}>{tick.label}</span>)}+ </div>+ {!points.length && <p className="m-0 pb-4 text-center text-xs text-muted">Nothing was recorded in this range.</p>}+ </div>+ )}++ <div className="flex flex-wrap justify-center gap-x-5 gap-y-1 text-xs text-soft">+ <span className="flex items-center gap-2"><span className="inline-block h-0.5 w-3.5 bg-paper" />{legend.current}</span>+ {legend.previous && <span className="flex items-center gap-2"><span className="inline-block w-3.5 border-t border-dashed border-muted" />{legend.previous}</span>}+ {gaps.length > 0 && <span className="flex items-center gap-2"><span className="inline-block h-3 w-3.5" style={{ background: HATCH }} />No data</span>}+ </div>+ <button type="button" className="btn h-12 w-full text-sm" aria-pressed={asTable} onClick={() => setAsTable((value) => !value)}>{asTable ? 'View as chart' : 'View as table'}</button>+ </div>+ </>+ )+}++const milliseconds = (value) => (value == null ? '–' : value >= 10000 ? `${Number((value / 1000).toFixed(1))} s` : `${Math.round(value)} ms`)++// Response times as two rows with a small line each, instead of two full charts.+export function PhoneReliability({ docker, collect, interval }) {+ if (!docker.length && !collect.length) return null+ const row = (title, detail, series) => (+ <div className="flex items-center gap-4 px-4 py-3">+ <span className="min-w-0 flex-1"><span className="block text-sm font-medium text-paper">{title}</span><span className="mt-0.5 block text-xs text-muted">{detail}</span></span>+ <Sparkline values={series.map((point) => point.avg)} width={96} height={20} max={Math.max(1, ...series.map((point) => point.avg ?? 0))} />+ </div>+ )+ return (+ <section aria-label="Reliability">+ <h2 className="m-0 mb-2.5 text-[15px] font-semibold text-paper">Reliability</h2>+ <div className="divide-y divide-line overflow-hidden rounded-md border border-line bg-ink">+ {docker.length > 0 && row('Docker API response', `median ${milliseconds(percentile(docker.map((point) => point.avg), 50))} · p95 ${milliseconds(percentile(docker.map((point) => point.max ?? point.avg), 95))}`, docker)}+ {collect.length > 0 && row('Collector per check-in', `median ${milliseconds(percentile(collect.map((point) => point.avg), 50))} · budget ${interval >= 60 ? `${Math.round(interval / 60)} min` : `${interval} s`}`, collect)}+ </div>+ </section>+ )+}diff --git a/src/frontend/src/statistics/StatisticsPage.jsx b/src/frontend/src/statistics/StatisticsPage.jsxindex 012139a..b2772d7 100644--- a/src/frontend/src/statistics/StatisticsPage.jsx+++ b/src/frontend/src/statistics/StatisticsPage.jsx@@ -8,7 +8,9 @@ import { forecastMonth, forecastPhrase, formatPercent, fullestMount, serverMountimport FleetStatistics from '../FleetStatistics.jsx'import { Icon } from '../icons.jsx'import { useOverview } from '../overviewStore.js'-import { AppShell } from '../shell.jsx'+import { AppShell, PhoneHeader, RoundButton } from '../shell.jsx'+import { usePhone } from '../ui.jsx'+import { Pills, PhoneFindings, PhoneKpis, PhoneReliability, PhoneTimeline, TimelineEntry } from './Phone.jsx'import { apiRequest } from '../api.js'import { ContainersTable } from './ContainersTable.jsx'import { BusyHours, Disks, Reliability, TimeAtLevels } from './Insights.jsx'@@ -58,7 +60,7 @@ function Kpi({ label, value, tone, children }) {const parse = (points) => (points || []).map((point) => ({ ...point, t: new Date(point.time).getTime() }))const metric = (points, key) => points.map((point) => ({ t: point.t, avg: point[key]?.avg ?? null, max: point[key]?.max ?? null, samples: point.samples })).filter((point) => point.avg !== null || point.max !== null)-function ServerStatistics({ server, overview, range, compare, containerId, choose }) {+function ServerStatistics({ server, overview, range, compare, containerId, choose, phone = false, view, focusT, openTimeline, timelineBack, rangeControl }) {const [focus, setFocus] = useState(null)const base = `/monitoring/servers/${server.id}/history?range=${range.id}&metrics=${METRICS.join(',')}`const { data, error } = usePolled(base, LIVE.has(range.id) ? 30 : null)@@ -92,7 +94,7 @@ function ServerStatistics({ server, overview, range, compare, containerId, choos[series, bucket, gaps, eventData, busiest, server, spikeData, JSON.stringify(disks)])const marks = useMemo(() => eventMarks(eventData?.events, start, end, noticed.flatMap((finding) => finding.marks || [])), [eventData, start, end, noticed])- if (error && !data) return <div role="alert" className="rounded-md border border-warn/40 px-3.5 py-2.5 text-xs text-warn">{error}</div>+ if (error && !data) return <div role="alert" className={`rounded-md border border-warn/40 px-3.5 py-2.5 text-xs text-warn ${phone ? 'mx-4 mt-4' : ''}`}>{error}</div>if (!data) return <p className="m-0 py-20 text-center text-[13px] text-muted">Loading the history of {server.hostname}…</p>const cpu = summarize(series.cpu)@@ -107,12 +109,44 @@ function ServerStatistics({ server, overview, range, compare, containerId, choosconst versus = range.short ? `vs ${range.short}` : ''const jump = (t) => setFocus({ t, nonce: Date.now() })const rows = [- { key: 'cpu', label: 'CPU', pair: true, format: formatPercent, axis: (tick) => `${tick}%`, max: 100, sub: `avg ${formatPercent(cpu.average)} · peak ${formatPercent(cpu.peak)}` },- { key: 'ram', label: 'Memory', format: formatPercent, axis: (tick) => `${tick}%`, max: 100, sub: `avg ${formatPercent(ram.average)}${server.total_ram_gb ? ` · of ${Number(server.total_ram_gb.toFixed(1))} GB` : ''}` },- { key: 'swap', label: 'Swap', format: formatPercent, axis: (tick) => `${Number(tick.toFixed(1))}%`, floor: 20 / 1.15, tone: 'warn', sub: `now ${formatPercent(swap.last)}${server.system?.swap_total_gb ? ` · of ${Number(server.system.swap_total_gb.toFixed(1))} GB` : ''}`, note: swapFinding ? { t: swapFinding.at, text: swapFinding.note } : null },- { key: 'load', label: 'Load (1 min)', short: 'Load', format: (value) => value.toFixed(2), axis: (tick) => String(Number(tick.toFixed(1))), floor: cores * 1.3, limit: { value: cores, label: `${cores} ${cores === 1 ? 'core' : 'cores'}` }, sub: `${cores} ${cores === 1 ? 'core' : 'cores'} · avg ${load.average == null ? '–' : load.average.toFixed(2)}` },+ { key: 'cpu', label: 'CPU', pair: true, format: formatPercent, axis: (tick) => `${tick}%`, max: 100, sub: `avg ${formatPercent(cpu.average)} · peak ${formatPercent(cpu.peak)}`, phone: `avg ${formatPercent(cpu.average)}` },+ { key: 'ram', label: 'Memory', format: formatPercent, axis: (tick) => `${tick}%`, max: 100, sub: `avg ${formatPercent(ram.average)}${server.total_ram_gb ? ` · of ${Number(server.total_ram_gb.toFixed(1))} GB` : ''}`, phone: `avg ${formatPercent(ram.average)}` },+ { key: 'swap', label: 'Swap', format: formatPercent, axis: (tick) => `${Number(tick.toFixed(1))}%`, floor: 20 / 1.15, tone: 'warn', phone: `now ${formatPercent(swap.last)}`, sub: `now ${formatPercent(swap.last)}${server.system?.swap_total_gb ? ` · of ${Number(server.system.swap_total_gb.toFixed(1))} GB` : ''}`, note: swapFinding ? { t: swapFinding.at, text: swapFinding.note } : null },+ { key: 'load', label: 'Load (1 min)', short: 'Load', format: (value) => value.toFixed(2), axis: (tick) => String(Number(tick.toFixed(1))), floor: cores * 1.3, limit: { value: cores, label: `${cores} ${cores === 1 ? 'core' : 'cores'}` }, phone: `${cores} ${cores === 1 ? 'core' : 'cores'}`, sub: `${cores} ${cores === 1 ? 'core' : 'cores'} · avg ${load.average == null ? '–' : load.average.toFixed(2)}` },]+ const legend = { current: `Last ${range.words}`, previous: previous ? `The ${range.previous}` : null }+ const swapNow = server.host?.swap_pct ?? swap.last+ const swapTone = (swapNow ?? 0) >= Math.min(swapWarn, 10) && swapFinding ? 'warn' : (server.host?.swap_pct ?? 0) >= swapWarn ? 'warn' : undefined+ const rootNote = rootDays != null ? (forecastMonth(rootDays) ? `F${forecastMonth(rootDays).slice(1)}` : forecastPhrase(rootDays) || 'No clear growth trend') : 'No clear growth trend'++ if (phone && view === 'timeline') {+ return <PhoneTimeline rows={rows} points={points} previous={previous} start={start} end={end} bucketSeconds={bucket} gaps={gaps} marks={marks} busiest={busiest} utc={utc} focusT={focusT} legend={legend} back={timelineBack} rangeControl={rangeControl} />+ }+ if (phone) {+ const ramGb = server.total_ram_gb && ram.average != null ? `${Number(((ram.average / 100) * server.total_ram_gb).toFixed(1))} of ${Number(server.total_ram_gb.toFixed(1))} GB` : ''+ return (+ <div className="space-y-7 px-4 pt-4">+ <PhoneKpis items={[+ { label: 'Average CPU', value: formatPercent(cpu.average), sub: earlier ? `${deltaPoints(cpu.average, earlier.cpu.average) ?? 'no data'} ${versus}` : `over the last ${range.words}` },+ { label: 'Peak CPU', value: formatPercent(cpu.peak), sub: cpu.peakAt != null ? formatMoment(cpu.peakAt, { utc }) : '' },+ { label: 'Average memory', value: formatPercent(ram.average), sub: ramGb },+ { label: 'Peak memory', value: formatPercent(ram.peak), sub: ram.peakAt != null ? formatMoment(ram.peakAt, { utc }) : '' },+ { label: 'Swap now', value: formatPercent(swapNow), tone: swapTone, subTone: swapFinding ? 'warn' : undefined, sub: swapFinding ? `Climbing since ${formatMoment(swapFinding.at, { clock: false })}` : swap.peak != null ? `peak ${formatPercent(swap.peak)} in this range` : '' },+ { label: root?.mount === '/' || !root ? 'Root disk' : `Disk ${root.mount}`, value: formatPercent(root?.used_pct ?? server.host?.disk_usage_pct), sub: rootNote },+ ]} />+ <PhoneFindings title={range.id === '7d' ? 'Noticed this week' : `Noticed in the last ${range.words}`} findings={noticed} onShow={openTimeline}+ empty={points.length ? `Nothing stands out over the last ${range.words}: no growing swap, no repeating spikes, no gaps and no disk about to fill up.` : 'Nothing has been recorded for this server in this range.'} />+ <TimelineEntry series={series.cpu} start={start} end={end} bucketSeconds={bucket} gaps={gaps} words={range.words} onOpen={() => openTimeline(null)} />+ <BusyHours key={server.id} serverId={server.id} />+ <TimeAtLevels cpu={series.cpu} ram={series.ram} words={range.span} />+ <section aria-label="Disks" className="space-y-2.5"><h2 className="m-0 text-[15px] font-semibold text-paper">Disks</h2><Disks server={server} mounts={mounts} range={range} forecasts={forecasts} /></section>+ <ContainersTable phone key={`containers-${server.id}`} server={server} usage={usage && usage.server_id === server.id ? usage : null} range={range} compare={compare} selectedId={containerId} onSelect={(id) => choose({ container: id })} />+ <PhoneReliability docker={series.docker_ms} collect={series.collect_ms} interval={server.check_interval_seconds} />+ </div>+ )+ }+return <><section className="card grid grid-cols-2 divide-x divide-y divide-line overflow-hidden md:grid-cols-3 xl:grid-cols-6 xl:divide-y-0" aria-label="Headline figures"><Kpi label="Average CPU" value={formatPercent(cpu.average)}>{earlier ? `${deltaPoints(cpu.average, earlier.cpu.average) ?? 'no data'} ${versus}` : `over the last ${range.words}`}</Kpi>@@ -153,6 +187,7 @@ function ServerStatistics({ server, overview, range, compare, containerId, choosexport default function StatisticsPage({ user, onLogout }) {const [searchParams, setSearchParams] = useSearchParams()+ const phone = usePhone()const { data: overview, error } = useOverview(Boolean(user), 30, onLogout)const [compare, setCompare] = useState(() => remembered(COMPARE_KEY, 'on') === 'on')const servers = useMemo(() => sortServers(overview?.servers || []), [overview])@@ -177,6 +212,40 @@ export default function StatisticsPage({ user, onLogout }) {download(`${server.hostname}-${range.id}.csv`, timelineCsv(data.points, METRICS))}+ // Phones open the timeline as its own screen, so the browser's back button returns to the summary.+ const view = phone ? searchParams.get('view') : null+ const openTimeline = (time) => {+ const next = new URLSearchParams(searchParams)+ next.set('view', 'timeline')+ if (time != null) next.set('at', String(Math.round(time))); else next.delete('at')+ setSearchParams(next)+ }+ const summaryParams = new URLSearchParams(searchParams)+ summaryParams.delete('view'); summaryParams.delete('at')+ const rangeControl = <select aria-label="Time range" value={range.id} onChange={(event) => { remember(RANGE_KEY, event.target.value); choose({ range: event.target.value }) }} className="h-10 rounded-full border border-edge bg-transparent px-3.5 text-[13px] font-medium text-paper">{RANGES.map((option) => <option key={option.id} value={option.id}>{option.label}</option>)}</select>++ if (phone) {+ const serverPills = [{ id: 'all', label: 'All' }, ...servers.map((item) => ({ id: String(item.id), label: item.hostname, dot: STATE_DOT[serverState(item)] }))]+ return (+ <AppShell user={user} onLogout={onLogout} crumbs={[{ label: 'Statistics' }]} bare phoneHeader>+ {view !== 'timeline' && <>+ <PhoneHeader title="Statistics" live={false} action={server ? <RoundButton label="Export CSV" icon="download" onClick={exportCsv} /> : undefined} />+ <div className="space-y-2.5 px-4 pt-3">+ {error && !overview && <div role="alert" className="rounded-md border border-warn/40 px-3.5 py-2.5 text-xs text-warn">{error}</div>}+ {overview && !servers.length && <p className="m-0 rounded-md border border-line bg-ink px-4 py-6 text-center text-[13px] text-muted">No server is reporting yet. History appears here once a collector has checked in. <Link to="/" className="link">Connect a server</Link>.</p>}+ {servers.length > 0 && <>+ <Pills label="Server" items={serverPills} value={wantsAll ? 'all' : String(server?.id)} onChange={(id) => choose({ server: id, container: '' })} />+ <Pills label="Time range" items={RANGES} value={range.id} onChange={(id) => { remember(RANGE_KEY, id); choose({ range: id }) }} />+ </>}+ </div>+ </>}+ {servers.length > 0 && (wantsAll ? <div className="px-4 pt-5"><FleetStatistics request={apiRequest} servers={servers} range={range.id} /></div>+ : server && <ServerStatistics key={`${server.id}-${range.id}`} phone server={server} overview={overview} range={range} compare={compare} containerId={searchParams.get('container') || ''} choose={choose}+ view={view} focusT={Number(searchParams.get('at')) || null} openTimeline={openTimeline} timelineBack={{ label: 'Statistics', to: `/statistics?${summaryParams}` }} rangeControl={rangeControl} />)}+ </AppShell>+ )+ }+const crumbs = [{ label: 'Statistics', to: '/statistics' }, { label: wantsAll ? 'All servers' : server?.hostname || '…' }]return (<AppShell user={user} onLogout={onLogout} crumbs={servers.length ? crumbs : undefined} bare>diff --git a/src/frontend/src/statistics/Timeline.jsx b/src/frontend/src/statistics/Timeline.jsxindex 5ee0d43..967f1f6 100644--- a/src/frontend/src/statistics/Timeline.jsx+++ b/src/frontend/src/statistics/Timeline.jsx@@ -5,9 +5,9 @@ import { formatTime, splitRuns } from '../chartMath.js'import { niceCeiling } from '../dashboard/logic.js'import { busiestAt, formatPeriod } from './logic.js'-const GUTTER = 44-const PAD_RIGHT = 22-const HATCH = 'repeating-linear-gradient(135deg, transparent 0 5px, color-mix(in srgb, var(--color-paper) 9%, transparent) 5px 6px)'+export const GUTTER = 44+export const PAD_RIGHT = 22+export const HATCH = 'repeating-linear-gradient(135deg, transparent 0 5px, color-mix(in srgb, var(--color-paper) 9%, transparent) 5px 6px)'const TONE = { paper: 'var(--color-paper)', warn: 'var(--color-warn)' }const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']@@ -62,7 +62,7 @@ export function Plot({ series, previous, start, end, top, ticks, format, bucketS)}-function nearest(points, time) {+export function nearest(points, time) {if (!points.length) return -1let low = 0let high = points.length - 1@@ -75,7 +75,7 @@ function nearest(points, time) {}// Time labels under the timeline: midnights for ranges of days, otherwise evenly spaced clock times.-function axisTicks(start, end, utc) {+export function axisTicks(start, end, utc) {const span = end - startconst ticks = []if (span > 36 * 3600000 && span <= 40 * 86400000 && !utc) {diff --git a/src/frontend/src/ui.jsx b/src/frontend/src/ui.jsxindex 7714195..d84510e 100644--- a/src/frontend/src/ui.jsx+++ b/src/frontend/src/ui.jsx@@ -1,9 +1,29 @@// Pieces the settings-style pages (Account, Admin) share: the two-column layout with a section list, cards,// switches, notices and small helpers.-import { useEffect, useState } from 'react'+import { Children, Fragment, createContext, isValidElement, useContext, useEffect, useState } from 'react'+import { useSearchParams } from 'react-router-dom'+import { PhoneHeader } from './shell.jsx'import { apiRequest } from './api.js'import { Icon } from './icons.jsx'+// The three layouts of the redesign: phone under 768 px (tab bar, one column), tablet up to 1199 px (icon rail),+// desktop from 1200 px (full sidebar).+export const PHONE_QUERY = '(max-width: 767px)'+export function useMedia(query) {+ const read = () => typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia(query).matches+ const [matches, setMatches] = useState(read)+ useEffect(() => {+ if (typeof window.matchMedia !== 'function') return undefined+ const list = window.matchMedia(query)+ const update = () => setMatches(list.matches)+ update()+ list.addEventListener('change', update)+ return () => list.removeEventListener('change', update)+ }, [query])+ return matches+}+export const usePhone = () => useMedia(PHONE_QUERY)+export function useCopy() {const [copied, setCopied] = useState(false)const copy = async (text) => {@@ -73,11 +93,15 @@ export function Row({ icon, title, detail, children, tone }) {)}+// On a phone, a screen showing one section already has its name in the header.+const LoneSection = createContext(null)+export function Section({ id, title, description, children, aside }) {+ const lone = useContext(LoneSection) === idreturn (- <section id={id} aria-labelledby={`${id}-title`} className="scroll-mt-20 border-b border-line pb-9 last:border-b-0">+ <section id={id} aria-labelledby={`${id}-title`} className="scroll-mt-20 border-b border-line pb-9 last:border-b-0 max-md:pb-7"><div className="flex flex-wrap items-start justify-between gap-3">- <div><h2 id={`${id}-title`} className="m-0 text-base font-semibold text-paper">{title}</h2>{description && <p className="mb-0 mt-1.5 max-w-[720px] text-[13px] leading-5 text-muted">{description}</p>}</div>+ <div><h2 id={`${id}-title`} className={lone ? 'sr-only' : 'm-0 text-base font-semibold text-paper'}>{title}</h2>{description && <p className={`mb-0 max-w-[720px] text-[13px] leading-5 text-muted ${lone ? 'mt-0' : 'mt-1.5'}`}>{description}</p>}</div>{aside}</div><div className="mt-4 space-y-4">{children}</div>@@ -86,8 +110,36 @@ export function Section({ id, title, description, children, aside }) {}// The page frame: a title, the list of sections on the left (it follows you down the page), the sections on the right.-export function SettingsLayout({ title, description, aside, sections, footer, children }) {+// On a phone the page is reached from the More tab: ``?section=<group>`` shows just that group's sections+// (``groups``: [{ id, label, sections }]), under a header that leads back to More.+// ``phoneHub``: what a phone shows with no group picked (Admin's list); ``phoneBack``: where a group's screen leads back to.+export function SettingsLayout({ title, description, aside, sections, footer, children, groups = [], phoneHub, phoneBack }) {+ const phone = usePhone()+ const [params] = useSearchParams()+ const group = groups.find((item) => item.id === params.get('section'))+ if (phone) return <PhoneSettings title={group?.label || title} description={group || phoneHub ? null : description} group={group} hub={group ? null : phoneHub} back={group && phoneBack ? phoneBack : { label: 'More', to: '/more' }}>{children}</PhoneSettings>+ return <DesktopSettings title={title} description={description} aside={aside} sections={sections} footer={footer} focus={group?.sections[0]}>{children}</DesktopSettings>+}++function PhoneSettings({ title, description, group, hub, back, children }) {+ // Only <Section>s outside the group are dropped; notices and loading text stay.+ const shown = Children.toArray(children).flatMap((child) => (isValidElement(child) && child.type === Fragment ? Children.toArray(child.props.children) : [child]))+ .filter((child) => !group || !isValidElement(child) || child.type !== Section || group.sections.includes(child.props.id))+ return (+ <LoneSection.Provider value={group?.sections.length === 1 ? group.sections[0] : null}>+ <PhoneHeader title={title} back={back} action={<span />} />+ <div className="space-y-7 px-4 pt-2">+ {description && <p className="m-0 text-[13px] text-soft">{description}</p>}+ {hub || shown}+ </div>+ </LoneSection.Provider>+ )+}++function DesktopSettings({ title, description, aside, sections, footer, focus, children }) {const [active, setActive] = useState(sections[0]?.id)+ // A link to one part of the page (from a phone's More tab, say) scrolls to it.+ useEffect(() => { if (focus) requestAnimationFrame(() => document.getElementById(focus)?.scrollIntoView({ block: 'start' })) }, [focus])useEffect(() => {if (typeof IntersectionObserver === 'undefined') return undefinedconst observer = new IntersectionObserver((entries) => {@@ -166,9 +218,8 @@ export function describeBrowser(userAgent) {return `${name}${browser[1] === 'Version' && system === 'iPhone' ? '' : ` ${browser[2]}`}${system ? ` on ${system}` : ''}`}-// A panel that slides in from the right over the page, like a drawer pulled out of the rack. Escape, the close-// button and a click outside all close it; focus moves in when it opens and back when it closes.-export function Drawer({ open, title, description, onClose, children, width = 560 }) {+// Opening an overlay: focus goes in, Escape closes, the page behind stops scrolling, and focus comes back after.+function useOverlay(open, onClose) {const [shown, setShown] = useState(false)useEffect(() => {if (!open) { setShown(false); return undefined }@@ -183,9 +234,36 @@ export function Drawer({ open, title, description, onClose, children, width = 56document.body.style.overflow = ''if (previous instanceof HTMLElement) previous.focus()}- // onClose is a new function each render; the drawer only reacts to opening and closing.+ // onClose is a new function each render; the overlay only reacts to opening and closing.// eslint-disable-next-line react-hooks/exhaustive-deps}, [open])+ return shown+}++// On a phone, details open as a sheet from the bottom over the list, so you keep your place. ``title`` may be+// a node (a name with a chip); ``label`` names the dialog for screen readers.+export function Sheet({ open, onClose, title, label, children, footer }) {+ const shown = useOverlay(open, onClose)+ if (!open) return null+ return (+ <div className={`fixed inset-0 z-50 flex items-end transition-colors duration-200 ${shown ? 'bg-black/55' : 'bg-black/0'}`} onMouseDown={(event) => { if (event.target === event.currentTarget) onClose() }}>+ <div role="dialog" aria-modal="true" aria-label={label || (typeof title === 'string' ? title : undefined)} className={`flex max-h-[88vh] w-full flex-col rounded-t-2xl border-t border-edge bg-ink pb-[env(safe-area-inset-bottom)] transition-transform duration-200 ease-out motion-reduce:transition-none ${shown ? 'translate-y-0' : 'translate-y-full'}`}>+ <span aria-hidden="true" className="mx-auto mt-2 h-1 w-9 shrink-0 rounded-full bg-edge" />+ <header className="flex items-start justify-between gap-3 px-4 pb-2 pt-3">+ <div className="min-w-0 flex-1">{typeof title === 'string' ? <h2 className="m-0 text-[17px] font-semibold text-paper">{title}</h2> : title}</div>+ <button type="button" autoFocus onClick={onClose} aria-label="Close" className="-mr-1.5 flex h-11 w-11 shrink-0 items-center justify-center rounded-md text-muted hover:text-paper"><Icon name="close" size={15} /></button>+ </header>+ <div className="custom-scroll min-h-0 flex-1 overflow-y-auto px-4 pb-4">{children}</div>+ {footer && <div className="border-t border-line px-4 py-3">{footer}</div>}+ </div>+ </div>+ )+}++// A panel that slides in from the right over the page, like a drawer pulled out of the rack. Escape, the close+// button and a click outside all close it; focus moves in when it opens and back when it closes.+export function Drawer({ open, title, description, onClose, children, width = 560 }) {+ const shown = useOverlay(open, onClose)if (!open) return nullreturn (<div className={`fixed inset-0 z-40 flex justify-end transition-colors duration-200 ${shown ? 'bg-black/55' : 'bg-black/0'}`} onMouseDown={(event) => { if (event.target === event.currentTarget) onClose() }}>