Skip to content

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.

refact+feat: redesign of the project, majority done

karloks200577b93e94b6fc
diff --git a/.gitignore b/.gitignore
index ac38ee0..411c32a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,5 @@
+design/
+
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[codz]
diff --git a/ODSTUPANJA.md b/ODSTUPANJA.md
new file mode 100644
index 0000000..112ad91
--- /dev/null
+++ b/ODSTUPANJA.md
@@ -0,0 +1,144 @@
+# Odstupanja od dizajna
+
+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: 13. 10. 2026.
+
+Mobilni prikazi nisu odstupanja nego preostali posao; popisani su na kraju.
+
+Narančasti brojevi u krugovima, oznake „STATE 1", „LOGIN · A" i blokovi „What changed" u PDF-ovima
+su anotacije dizajna i namjerno nisu ugrađeni.
+
+## Okvir aplikacije (sidebar, top bar)
+
+| Dizajn | Implementacija | Razlog | Issue |
+| --- | --- | --- | --- |
+| „karlo's homelab" kao ime instance | Ime se izvodi iz imena prvog admina; može se promijeniti samo kroz API (`instance_name`), u Adminu nema polja | Admin stranica još nije redizajnirana | #106 |
+| „Owner" ispod imena korisnika | „Owner" se prikazuje svakom adminu, „Member" svima ostalima | Ne postoji uloga vlasnika | #106 |
+| Verzija `v0.9.2` | Konstanta u `src/backend/config.py` i druga u `src/agent/collector.py` | Nema jednog izvora verzije pri buildu | #106 |
+| Prečac `⌘K` | Na Linuxu i Windowsu piše `Ctrl K` | Prikazuje se prečac koji stvarno radi na tom sustavu | – |
+
+## Overview (`01-dashboard.pdf`, `06-dashboard-empty-states.pdf`)
+
+| Dizajn | Implementacija | Razlog | Issue |
+| --- | --- | --- | --- |
+| Agentova bilješka na svakom incidentu („Agent: limit is 4 GB…") | Stupac postoji i puni se ako backend pošalje `agent_note`; backend ga još ne šalje, pa je prazan | Agent još ne dijagnosticira incidente | #95, #93 |
+| „Open diagnosis" i „Ask the agent" otvaraju taj incident / razgovor o tom kontejneru | Vode na `/agent` bez konteksta | Agent stranica je još placeholder | #95 |
+| Zadnji incident: „Resolved 2 h ago · memory limit raised to 6 GB" | Piše samo kada je riješen i na kojem serveru | Nitko ne bilježi kako je incident riješen | #95 |
+| „You'll get a push on ntfy if that changes" | Rečenica je izostavljena | Infradeck nema ntfy obavijesti | #50 |
+| Gumbi Logs i Restart u proširenom redu kontejnera | Prikazani, ali onemogućeni, s objašnjenjem u tooltipu | Dogovoreno: aplikacija ostaje read-only dok se to sigurnosno ne pregleda | #100 |
+| „Monitor this machine": „Check every 15 s · change later in Admin" | „Checks every minute at first · change it once it reports" | Novi server počinje s intervalom od 60 s; interval se mijenja na Overviewu | #97 |
+| „Another machine": jedna `docker run` naredba | Dvije `docker run` naredbe (collector i docker-proxy) | Collector namjerno nema Docker socket; drži ga zaseban read-only proxy | – |
+| „Another machine": polje samo za ime | Dodano je i polje za adresu na koju se novi stroj javlja | Bez ispravne adrese naredba ne radi (localhost, VPN) | – |
+| Brisanje servera nije na Overviewu | „Remove this server" je u System tabu | Admin još nema pravi popis servera | #97 |
+| Kartica „What you'll get": „Kept for a year as 30-minute points" | „Kept as rolled-up points for as long as you set in Admin" | Zadržavanje je postavka, a točke nisu uvijek 30-minutne | – |
+| „The agent only sends data to your model provider when it diagnoses an incident" | „…when you ask it something" | Automatska dijagnoza ne postoji | #93 |
+
+## Tabovi servera (`08-server-tabs.pdf`)
+
+| Dizajn | Implementacija | Razlog | Issue |
+| --- | --- | --- | --- |
+| Containers: „Restarts · 24 h" | „Restarts · since created" | Postoji samo Dockerov ukupni brojač | #105 |
+| Network: imena host procesa (`sshd`, `vite dev server`) | Ime se vidi kad port objavljuje kontejner; host procesi samo uz opcionalni `port-owners` helper; bez njega `sshd` je pretpostavka po portu 22 | Čitanje tuđih procesa traži velike privilegije, pa je isključeno po defaultu | – |
+| Network: „Bound to" s pravom adresom (`10.0.0.12`) | `0.0.0.0`, `127.0.0.1` ili „one address" | Collector šalje samo opseg (svi, loopback, jedna adresa) | #103 |
+| Network: „Reachable from: LAN + VPN" | „every network", „one network" ili „this machine" | Isto kao gore | #103 |
+| Network: sučelja s opisom („WireGuard", „9 bridges") | Ime, mreža, brzina i promet | Vrsta sučelja se ne prikuplja | #39 |
+| System: „Security: 4 · openssl, libc6, sudo…" | Samo broj („4 waiting") | Imena paketa nisu ni u jednoj datoteci koju collector smije čitati | #104 |
+| System: ažuriranja za sve distribucije | Samo Debian i Ubuntu (apt) | dnf i pacman nemaju čitač | #104 |
+| System: „Failed units: 0 systemd units" | Red je izostavljen | Jedini put je D-Bus, koji može i mijenjati servise | #102 |
+| System: „Disk errors: None · SMART healthy" | Brojač I/O grešaka iz kernela; NVMe ga nema | SMART traži sirov pristup diskovima | #101 |
+| System: stupac Health po disku („SMART ok · 3% worn") | Stupac Inodes | Isto kao gore | #101 |
+| System: „Last shutdown: Clean, by reboot command" | „Clean" ili „Unclean" | Uzrok gašenja se ne bilježi | – |
+| System: „Proxy: docker-socket-proxy" | „Docker socket proxy, read-only" | Proxy je vlastiti, ne projekt tog imena | – |
+| System: `/var/lib/docker` s uređajem i tipom `overlay2` | Uređaj „—", tip „images + cache" | `/system/df` je namjerno sveden na šest brojeva | – |
+| Events: „Events are kept for 90 days, then only alerts are kept for a year" | „Events are kept for N days" (postavka zadržavanja) | Ne postoji zasebno pravilo za alerte | #58 |
+| Events: „watchtower pulled new images…", „restarted by a user through Portainer" | Generičke rečenice („now run a different image build") | Infradeck ne zna tko je pokrenuo promjenu | – |
+| Events: „alert sent to ntfy and email" | Ne piše kamo je alert poslan | Nema kanala obavijesti | #50 |
+
+## Prijava i registracija (`09-login.pdf`, `mobile/06-login.pdf`)
+
+| Dizajn | Implementacija | Razlog | Issue |
+| --- | --- | --- | --- |
+| „Forgot it?" vodi na reset lozinke | Otvara objašnjenje: pitaj admina ili napravi novog admina sa servera | Reset lozinke ne postoji; Infradeck ne šalje e-mail | #108 |
+| Stanje greške nije nacrtano | Tihi žuti okvir iznad gumba | Dizajn ga ne prikazuje | – |
+| `/register` uz zatvorenu registraciju nije nacrtan | Kratka poruka s poveznicom na prijavu | Dizajn ga ne prikazuje | – |
+| Mobitel, 2FA: sustavska tipkovnica i „From Messages" | Polja traže numeričku tipkovnicu i `one-time-code`; što se prikaže ovisi o uređaju | To crta operativni sustav, ne stranica | – |
+| 30 dana ostaje nakon promjene lozinke | Sesija se nakon promjene lozinke ili uključivanja 2FA vraća na jedan dan | Te radnje otvaraju novu sesiju bez oznake „remember" | – |
+
+## Statistics (`02-statistics.pdf`)
+
+| Dizajn | Implementacija | Razlog | Issue |
+| --- | --- | --- | --- |
+| Birač servera: samo serveri | Dodana je stavka „All" s prikazom flote | Dogovoreno, da se ne izgube incidenti i dostupnost | – |
+| Prikaz flote nije nacrtan | Stari sadržaj (incidenti, dostupnost, rang-liste) u novim bojama; krafne i stupci zadržavaju zelenu, žutu i narančastu | Za taj prikaz nema dizajna | – |
+| Events red: „nightly backup" | Oznaka „nightly <kontejner> peak" na svakom skoku koji se ponavlja | Infradeck ne zna što je backup; zna samo koji je kontejner tada najzaposleniji | – |
+| Events red: oznake uz svaki događaj | Tekst se prikazuje samo gdje ima mjesta do sljedećeg događaja; ostalo je u tooltipu | Inače se oznake preklapaju | – |
+| Events red: „apt upgrade · 41 packages" | Isto, ali tek od trenutka kad collector to počne javljati; samo Debian i Ubuntu | Događaj nastaje kad se apt-ov log promijeni između dva javljanja | #104 |
+| Nalaz: „line up with the gitlab backup job" | „gitlab is the busiest container each time" | Isto kao gore | – |
+| Nalaz: „Spikes last 8 to 14 minutes" | Isto, ali samo za raspone do 7 dana | Trajanje se čita iz pojedinačnih javljanja, a ona se čuvaju tjedan dana | #58 |
+| Tablica: Swap po kontejneru | Prosjek kroz raspon; samo cgroup v2 i tek nakon rebuilda collectora; za razdoblja prije toga prazno | Docker ne daje swap po kontejneru, čita se iz cgroupa | – |
+| Tooltip: „Busiest gitlab 94%" | Najviši CPU jednog kontejnera u tom razdoblju; za raspone od 30 dana naviše po satu, tjednu ili mjesecu | Čita se iz sažetaka | – |
+| „Not measured before collector 0.9.0" | „Not measured before <datum>" | Povijest verzija collectora se ne bilježi | – |
+| Raspon boja u heatmapu „0% – 15%+" | Gornja granica se računa iz podataka | Fiksna granica ne odgovara svakom serveru | – |
+| Export CSV | Izvozi točke Timelinea odabranog servera i raspona | Dizajn ne kaže što se izvozi | #67 |
+| Povijest kontejnera nije nacrtana | Klik na red otvara Timeline za taj kontejner (CPU, Memory, Restart count) ispod reda | Dogovoreno | – |
+
+## Agent (`03-agent.pdf`)
+
+| Dizajn | Implementacija | Razlog | Issue |
+| --- | --- | --- | --- |
+| Dijagnozu piše jezični model („watchtower updated the image to 17.4.1…") | Dijagnoza se gradi fiksnim pravilima iz spremljenih metrika i događaja; sažetak je opis pravila | Automatska LLM dijagnoza ne postoji; ovako ne košta ništa i ništa ne šalje van | #93 |
+| Evidence: retci iz loga kontejnera i `docker events` | Događaji koje je Infradeck zabilježio na tom serveru | Docker proxy ne može čitati logove | #100 |
+| „Confidence: high · 3 of 3 signals agree" | „3 of 3 checks against the data hold" | Nema modela koji bi procijenio pouzdanost | #93 |
+| Koraci s točnom putanjom (`/opt/gitlab/docker-compose.yml`) i brojkama iz povijesti verzija | Koraci iz fiksnog priručnika po vrsti pravila, s imenom kontejnera i izračunatim limitom | Infradeck ne zna gdje je compose datoteka ni koju verziju slike je kontejner imao prije | – |
+| „Notified ntfy, email" | „sent to the channels people chose" ili „nobody yet" | Ne bilježi se po kanalu | – |
+| Chat: odgovori s oznakama izvora („memory 12:30–13:55", „docker events") | Običan tekst odgovora | Model ne vraća izvore | #93 |
+| Chat: prijedlozi pitanja vezani uz incident | Tri općenita prijedloga | Isto | – |
+| „Resolved 14" po tjednima, s opisom kako je riješeno | Zadnjih 200 riješenih; opis je „Marked resolved by …" ili „Cleared on its own" | Nitko ne upisuje kako je riješeno | – |
+| „Mark resolved" trajno zatvara | Ako je uzrok još tu, na sljedećem javljanju otvara se novi incident | Pravilo i dalje vrijedi | – |
+| Viewer ne može ništa mijenjati | Isto; gumbi su onemogućeni s objašnjenjem | – | – |
+
+## Account (`04-account.pdf`)
+
+| Dizajn | Implementacija | Razlog | Issue |
+| --- | --- | --- | --- |
+| Email „Verified" | Bez oznake | Infradeck ne šalje e-mail, pa nema provjere | – |
+| Recovery codes: „Show" | Samo „Regenerate" | Kodovi su spremljeni kao hash | – |
+| Recovery codes: „8 of 10 left · generated 25 Sep" | „8 left" | Datum generiranja se ne bilježi | – |
+| Passkeys: „Add passkey" | Gumb je onemogućen | WebAuthn nije napravljen | #77 |
+| Sessions: lokacija („Zagreb, HR") i „Last active" | IP adresa i vrijeme prijave | Nema geolokacije; zadnja aktivnost se ne bilježi | – |
+| „Sessions expire after 30 days without activity" | „A session lasts a day, or 30 days…" | Sesija istječe od prijave, ne od zadnje aktivnosti | – |
+| Kanali: Telegram, Slack, Gotify, Pushover | ntfy, Discord webhook, bilo koji webhook, e-mail (ako je SMTP postavljen) | Ostali idu kroz generički webhook | #50 |
+| Kanal: „Fix" kod neuspjeha | „Send test" i „Remove" | Adresa se ne može urediti jer je spremljena šifrirano; kanal se ukloni i doda ponovno | – |
+| Matrica: „Agent diagnosis ready", „Daily digest 08:00", „Weekly report" | Redovi su prikazani, ali onemogućeni | Ne postoje | #33 |
+| Display: Time format i Sizes mijenjaju prikaz | Spremaju se, ali se još ne primjenjuju | Vremena i veličine se formatiraju na puno mjesta | – |
+| Display: Time zone za grafove | Vrijedi samo za tihe sate; grafovi prate preglednik | Isto | – |
+| „Change initials color" | Mijenja boju kroz šest ponuđenih | Dizajn ne kaže kako | – |
+
+## Admin (`05-admin.pdf`)
+
+| Dizajn | Implementacija | Razlog | Issue |
+| --- | --- | --- | --- |
+| „Update available · 0.9.3" | Nema; About ima poveznice na changelog | Infradeck ne zove van | – |
+| Connect a server kao tri numerirana koraka | Iste kartice kao na Overviewu (ime, naredba, čekanje, Add) | Jedna implementacija umjesto dvije | – |
+| „Removing a server keeps its history" | Brisanje servera briše i njegove metrike i incidente | Tako radi postojeće brisanje | – |
+| Users: „Invite pending · Resend" | Poveznica se prikaže jednom; „Cancel" i nova pozivnica | Infradeck ne šalje e-mail | – |
+| Uloge Owner / Admin / Viewer | Owner je prvi admin i ne može se mijenjati; ostalo Admin ili Viewer | Nema zasebne uloge vlasnika | #106 |
+| Alert rules: „Disk forecast full in < 30 days", „CPU > 90%" | Ne postoje; popis ima 16 stvarnih pravila | Ta pravila nisu napravljena | – |
+| Alert rules: stupac Servers s izborom servera | Uvijek „All" | Pravila vrijede za sve servere | – |
+| Alert rules: „New rule" | Gumb je onemogućen | Vlastita pravila ne postoje | – |
+| Alert rules: bilješka zašto je pravilo isključeno | Samo broj isključenih pravila | Razlog se ne upisuje | – |
+| Incident agent: „Anthropic API · key ending 4f2a", „Change" | Google Gemini, model iz `.env`; „Change" je onemogućen | Pružatelj i ključ se postavljaju u `.env` | #91 |
+| „Diagnose new incidents automatically" prekidač | Uvijek uključeno i onemogućeno | Dijagnoza je lokalna i ne može se isključiti | #93 |
+| „Read container logs" s iznimkama | Onemogućeno | Proxy ne čita logove | #100 |
+| „Redact IPs and hostnames" | Onemogućeno | Nije napravljeno | – |
+| „$1.84 estimated provider cost · cap $10" | „— · not tracked" | Potrošnja se ne mjeri | #91 |
+| Retention: tri zasebna roka | Jedan rok za sažetke; javljanja se čuvaju tjedan dana | Tako radi postojeće zadržavanje | #58 |
+| 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
+
+| Što | Dizajn | Issue |
+| --- | --- | --- |
+| Mobilni prikazi (osim prijave) | `design/mobile/` | #98 |
+| Provjera na pravom stacku s pravim podacima | – | #107 |
diff --git a/SECURITY.md b/SECURITY.md
index ed3dfe5..62e7204 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -13,6 +13,63 @@ This page says what each component can reach, so you can decide what to run.
| Collector gate (server stack) | nginx container, no capabilities | the backend; publishes one port on your VPN address | The only way to reach collector endpoints. See below. |
| Backend / frontend / database / Redis | containers | each other, over separate networks | Only the frontend port is published. Redis and PostgreSQL are on a network with no route out and are reachable only by the backend. Redis needs a password. |
+## What the sign-in page shows before anyone signs in
+
+The sign-in page says which install it belongs to, so `GET /auth/config` answers without a session.
+Anyone who can reach the dashboard can read: the install's name (by default "<first admin's first
+name>'s homelab"; change it with `instance_name` in the admin settings), how many servers it watches,
+the Infradeck version, and whether registration is open. If the dashboard faces the internet, that is
+what a stranger learns; keep it behind a VPN if that is too much.
+
+"Keep me signed in for 30 days" makes that one session, and its cookie, last 30 days instead of
+`SESSION_TTL_SECONDS` (a day by default). The choice is made at the password step and kept on the
+server, so the two-factor step cannot lengthen a session. The limited session an admin gets before
+setting up two-factor is always 30 minutes. Long sessions are listed with the rest under Account and
+end with "sign out everywhere".
+
+## API tokens, notification channels and invitations
+
+**API tokens** (Account › API tokens) let a script read what a signed-in user can read.
+
+- A token is shown once and stored only as a SHA-256 hash. It is sent as `Authorization: Bearer idk_…`.
+- A *read* token may only `GET`. A *write* token may also acknowledge, resolve, mute and unmute
+ incidents, and only an admin can create one. If the owner's role or account changes, the token follows.
+- No token, whatever its scope, reaches `/account`, `/auth`, `/admin`, the chat or anything that
+ changes servers. A leaked token can't create another token, change a password, read the pending
+ servers' pairing codes or spend the model provider's quota.
+- Tokens can expire; revoking one works at once.
+
+**Notification channels** (Account › Notifications) make the backend connect to an address a user
+typed, so that address is treated as hostile:
+
+- Only `http` and `https`, no user name or password in the address, no redirects followed, a 5 second
+ timeout, and the answer is never shown to the user, only its status code.
+- Every address the name resolves to is checked, when the channel is saved and again each time
+ something is sent. Loopback, link-local (which includes cloud metadata addresses), multicast and
+ reserved ranges are always refused.
+- Private LAN ranges are allowed **only for admins**, because a homelab's ntfy usually lives there.
+ That means an admin can make the backend send a small POST to any host on the networks the backend
+ container can reach, including the stack's own services. Admins can already do far more; other
+ users can only reach public addresses.
+- Addresses are stored encrypted with `SECRETS_KEY` and shown afterwards only as the host and the last
+ few characters. Without `SECRETS_KEY`, channels can't be saved at all.
+- Email is sent only to the account's own address, and only if `SMTP_HOST` and `SMTP_FROM` are set.
+- What is sent: the incident's title, its description, the server's name and the incident number.
+ If those must not leave your network, use a channel inside it.
+
+**Invitations** (Admin › Users) are single-use links for one email address that work while registration
+is closed. Infradeck sends no email, so the admin passes the link on; whoever holds it and knows the
+address can register, so send it over a channel you trust. It expires after 7 days and is stored hashed.
+
+**Incident actions** (acknowledge, resolve, mute) are for admins only and each is written to the audit
+log. Muting hides an incident from the Overview and stops notifications for it; it does not stop the
+rule. An admin can also switch a rule off entirely in Admin › Alert rules, which closes its incidents.
+
+**The chat about an incident** sends your question together with that incident's title, description
+and the facts Infradeck worked out (signals and recorded events, which contain container and host
+names) to the model provider. Turn Chat off in Admin › Incident agent if that must not happen. The
+diagnosis itself is built locally by fixed rules and sends nothing anywhere.
+
## The optional system helper
Reading the kernel log (`dmesg`) needs a privilege, and crash-vs-clean-shutdown detection needs
@@ -45,30 +102,62 @@ How its output is treated as untrusted:
from the current boot, and forwards only the expected fields.
- The backend validates everything again (event kinds, key format, timestamps, lengths, counts).
+## The optional port-owners helper
+
+The Network tab can name the process behind each listening port (`sshd`, `mariadbd`), but only if
+something looks into other users' processes. That is a much bigger privilege than anything else here,
+so it is a **separate container, off by default**, and enabling the kernel-log helper above never
+grants it. Enable it with `docker compose --profile port-owners up -d`.
+
+Be clear about what you are granting:
+
+- **The host's `/proc`, `CAP_SYS_PTRACE`, `CAP_DAC_READ_SEARCH` and no AppArmor confinement.** All four
+ are needed to read which sockets a process holds, and together they are enough to read any file on
+ the host (through `/proc/<pid>/root`) and the memory of any process. Treat this container as able
+ to read everything on the machine. If that is not acceptable, leave it off: ports published by
+ containers are still named, and the rest show as "not published by a container".
+- **No network, read-only filesystem, no new privileges.** It cannot send anything anywhere; its only
+ way out is the file it writes to the volume it shares with the collector.
+- **What it actually reads:** the host's socket tables, the link target of each process's file
+ descriptors (never the files behind them) and each matching process's short name. No arguments,
+ paths, users or environment.
+- **What leaves it:** protocol, port and process name, at most 512 entries. A process can name itself
+ anything, so the name is reduced to printable characters and 64 characters; the collector reads the
+ file with `O_NOFOLLOW`, a size cap and a freshness check, and the backend validates it again.
+- It is the same single file as the system helper (`src/agent/system_helper.py`), in a different mode.
+
## The Docker socket and the read-only proxy
A Docker socket mount is root on the host: the `:ro` flag only protects the socket file, not the
API behind it, and anything that can reach the API can start a privileged container. So in the
compose files the collector **does not mount the socket**. A separate `docker-proxy` container does:
-- It answers exactly four requests: `GET /containers/json?all=1`, `GET /containers/<id>/json`,
- `GET /containers/<id>/stats?stream=false` and the same stats request with `&one-shot=true` (which makes
+- It answers exactly six requests: `GET /containers/json?all=1`, `GET /containers/<id>/json`,
+ `GET /containers/<id>/stats?stream=false`, the same stats request with `&one-shot=true` (which makes
Docker answer at once instead of waiting a second for a second CPU reading; the collector works out CPU %
- from the change since its previous check-in). Everything else (other endpoints, other methods, extra
+ from the change since its previous check-in) `GET /version`, of which only the daemon's version numbers pass, and `GET /system/df`, which is cut
+ down to six numbers (how much disk images and the build cache take, and how much of that nothing
+ uses; no image, volume or container names). Everything else (other endpoints, other methods, extra
query parameters, encoded or padded paths) gets a 403 and is logged. Matching is literal against the
whole request target, with no decoding.
- It cuts the answers down to a fixed list of fields. For container inspect that is the ID, name,
restart count, image name and ID, state, health, exit code, out-of-memory flag, start and finish
- times, and published ports. Container inspect output includes each container's environment
- variables (often secrets), labels, mounts and Docker's free-text error message; none of them leave
- the proxy. Adding a field means changing the proxy and its tests on purpose.
+ times, published ports, one label and where its mounts come from. Container inspect output also
+ includes each container's environment variables (often secrets), every other label and Docker's
+ free-text error message; none of them leave the proxy. Adding a field means changing the proxy and
+ its tests on purpose.
+- The one label that passes is `com.docker.compose.project`, so the dashboard can group containers by
+ compose project. Of a mount, only its type, its source (a host path or a volume name) and its
+ destination pass: never its contents, options or driver settings. That means **host paths that
+ containers mount, and volume names, are visible to everyone who can sign in**, like container names
+ and images already are. If a path itself is sensitive, don't put it in a container's mounts.
- It runs with all capabilities dropped, a read-only filesystem and `no-new-privileges`, with no
network at all. It listens on a Unix socket (mode 0660) in a volume that only the collector shares.
- It is one standard-library file, `src/agent/docker_proxy.py`, built from this repository. Review it
before trusting it: it is the one piece that holds the socket.
A compromised collector can therefore read what it already reports (container names, states,
-stats) and nothing more through Docker.
+stats, compose project, mount sources) and nothing more through Docker.
## Protecting a fresh install
@@ -240,8 +329,17 @@ The collector's network checks are passive or opt-in, and add no privileges:
- **Firewall configuration** is read from a fixed list of files (`/etc/ufw/*.rules`, `ufw.conf`,
`nftables.conf`, `iptables/rules.v4` and `rules.v6`), never following symlinks and never reading more than
1 MB. Only a short hash and a rule count leave the host, because the rules themselves reveal your
- network layout. This sees configuration, not the live ruleset: reading that needs `CAP_NET_ADMIN`,
+ network layout, plus one more thing: for ports the host is already reported to listen on, whether one of
+ those files has a rule accepting that port (and which file), so the Network tab can say "no rule" next to
+ an exposed port. Rules about anything else are never named. This sees configuration, not the live ruleset: reading that needs `CAP_NET_ADMIN`,
which can also change the firewall, so the collector doesn't have it.
+- **Machine facts** for the System tab (kernel release, CPU model, time zone, interface names with their
+ network and traffic, temperatures from sysfs, and on Debian and Ubuntu the pending-update counts apt
+ leaves in world-readable files) are read the same passive way. Nothing is executed on the host, and the
+ backend keeps only known fields of the right type and size.
+- **Swap per container** is read from each container's cgroup file under the host's `/sys/fs/cgroup`
+ (world-readable), because Docker's stats don't report it. Only containers Docker already listed are
+ looked up, by their full ID.
- **The internet check is off by default.** When enabled it only opens a TCP connection and looks the
name up, sending nothing. Its targets come from the collector's own environment
(`HOMELAB_CONNECTIVITY_TARGETS`), never from the dashboard, so a compromised dashboard can't point
diff --git a/collector-compose.yml b/collector-compose.yml
index 8113193..a9bf6c4 100644
--- a/collector-compose.yml
+++ b/collector-compose.yml
@@ -36,7 +36,7 @@ services:
- no-new-privileges:true
# The only container that mounts the Docker socket (a mount flag can't make it read-only).
- # It answers three read requests and nothing else. It has no network at all: the collector
+ # It answers a handful of read requests and nothing else. It has no network at all: the collector
# reaches it through a Unix socket in a volume only the two of them share. See SECURITY.md.
docker-proxy:
build:
@@ -78,6 +78,34 @@ services:
- /var/log/wtmp:/host/wtmp:ro
- system_events:/out
+ # Optional and off by default: names the process behind each listening port for the Network tab.
+ # Enable with: docker compose --profile port-owners up -d
+ # This is the most privileged piece of the stack. Seeing which process holds a socket means looking into
+ # other users' processes, which needs the host's /proc, CAP_SYS_PTRACE, CAP_DAC_READ_SEARCH and no
+ # AppArmor confinement. Together those can read any file on the host, so it gets no network, a
+ # read-only filesystem, and publishes only protocol, port and process name. Read SECURITY.md first.
+ port-owners:
+ profiles: ["port-owners"]
+ build:
+ context: .
+ dockerfile: docker/system-helper.Dockerfile
+ image: homelab-system-helper:latest
+ container_name: homelab-port-owners
+ restart: unless-stopped
+ user: "0:0"
+ cap_drop: [ALL]
+ cap_add: [SYS_PTRACE, DAC_READ_SEARCH]
+ network_mode: none
+ read_only: true
+ security_opt:
+ - no-new-privileges:true
+ - apparmor=unconfined
+ environment:
+ HOMELAB_HELPER_MODE: port-owners
+ volumes:
+ - /proc:/host/proc:ro
+ - system_events:/out
+
volumes:
collector_state:
system_events:
diff --git a/compose.yml b/compose.yml
index bcd368a..ce09ce6 100644
--- a/compose.yml
+++ b/compose.yml
@@ -166,6 +166,34 @@ services:
- /var/log/wtmp:/host/wtmp:ro
- system_events:/out
+ # Optional and off by default: names the process behind each listening port for the Network tab.
+ # Enable with: docker compose --profile port-owners up -d
+ # This is the most privileged piece of the stack. Seeing which process holds a socket means looking into
+ # other users' processes, which needs the host's /proc, CAP_SYS_PTRACE, CAP_DAC_READ_SEARCH and no
+ # AppArmor confinement. Together those can read any file on the host, so it gets no network, a
+ # read-only filesystem, and publishes only protocol, port and process name. Read SECURITY.md first.
+ port-owners:
+ profiles: ["port-owners"]
+ build:
+ context: .
+ dockerfile: docker/system-helper.Dockerfile
+ image: homelab-system-helper:latest
+ container_name: homelab-port-owners
+ restart: unless-stopped
+ user: "0:0"
+ cap_drop: [ALL]
+ cap_add: [SYS_PTRACE, DAC_READ_SEARCH]
+ network_mode: none
+ read_only: true
+ security_opt:
+ - no-new-privileges:true
+ - apparmor=unconfined
+ environment:
+ HOMELAB_HELPER_MODE: port-owners
+ volumes:
+ - /proc:/host/proc:ro
+ - system_events:/out
+
frontend:
build:
context: .
diff --git a/docker-compose.server.yml b/docker-compose.server.yml
index b7497e3..099c913 100644
--- a/docker-compose.server.yml
+++ b/docker-compose.server.yml
@@ -208,6 +208,34 @@ services:
- /var/log/wtmp:/host/wtmp:ro
- system_events:/out
+ # Optional and off by default: names the process behind each listening port for the Network tab.
+ # Enable with: docker compose --profile port-owners up -d
+ # This is the most privileged piece of the stack. Seeing which process holds a socket means looking into
+ # other users' processes, which needs the host's /proc, CAP_SYS_PTRACE, CAP_DAC_READ_SEARCH and no
+ # AppArmor confinement. Together those can read any file on the host, so it gets no network, a
+ # read-only filesystem, and publishes only protocol, port and process name. Read SECURITY.md first.
+ port-owners:
+ profiles: ["port-owners"]
+ build:
+ context: .
+ dockerfile: docker/system-helper.Dockerfile
+ image: homelab-system-helper:latest
+ container_name: homelab-port-owners
+ restart: unless-stopped
+ user: "0:0"
+ cap_drop: [ALL]
+ cap_add: [SYS_PTRACE, DAC_READ_SEARCH]
+ network_mode: none
+ read_only: true
+ security_opt:
+ - no-new-privileges:true
+ - apparmor=unconfined
+ environment:
+ HOMELAB_HELPER_MODE: port-owners
+ volumes:
+ - /proc:/host/proc:ro
+ - system_events:/out
+
frontend:
build:
context: .
diff --git a/docs/images/infradeck-banner-dark.svg b/docs/images/infradeck-banner-dark.svg
index b4949bc..33bad39 100644
--- a/docs/images/infradeck-banner-dark.svg
+++ b/docs/images/infradeck-banner-dark.svg
@@ -1,6 +1,6 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 320" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest>AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYTo4MGNlN2RhMS01NjBkLTRjNmEtYTkyYi1lNzgxY2RhMzBiZjMAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaHkYg5quwgYjb4WD+PVdUCcAAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDo3Mjk0YzNmNy02NmUxLTQwMGItODVlNy1jN2U4Nzc1ODI3MGNscmVsYXRpb25zaGlwaHBhcmVudE9mAAAB4mp1bWIAAABBanVtZGNib3IAEQAQgAAAqgA4m3ETYzJwYS5hY3Rpb25zLnYyAAAAABhjMnNo6L2h8K+qUFEmnHd8qx899gAAAZljYm9yomdhY3Rpb25zgqJmYWN0aW9ua2MycGEub3BlbmVkanBhcmFtZXRlcnOha2luZ3JlZGllbnRzgaJjdXJseC1zZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmluZ3JlZGllbnQudjNkaGFzaFgg4VVPmJOvy/+I8Kna0VjmdivdPXezJIvIPi6g3PohmU2kZmFjdGlvbngdY29tLmFudGhyb3BpYy5jbGF1ZGUucHJvdmlkZWRqcGFyYW1ldGVyc6F4H2NvbS5hbnRocm9waWMub3JpZ2luLWNvbmZpZGVuY2VndW5rbm93bmtkZXNjcmlwdGlvbnhmQ2xhdWRlIHByb3ZpZGVkIHRoaXMgZmlsZSBhdCB0aGUgcmVxdWVzdCBvZiBhIHVzZXIgYW5kIG1heSBoYXZlIGNyZWF0ZWQgb3IgbW9kaWZpZWQgdGhlIGZpbGUgY29udGVudHMubXNvZnR3YXJlQWdlbnShZG5hbWVmQ2xhdWRlcmFsbEFjdGlvbnNJbmNsdWRlZPUAAADIanVtYgAAAEBqdW1kY2JvcgARABCAAACqADibcRNjMnBhLmhhc2guZGF0YQAAAAAYYzJzaMPji/V9YcGEfRqZjLx6uBEAAACAY2JvcqVjYWxnZnNoYTI1NmNwYWRNAAAAAAAAAAAAAAAAAGRoYXNoWCD/G7ktXr4ZDp5T0gKCYKJ4EKxlcDPIMwbyosAWDkS6SmRuYW1lbmp1bWJmIG1hbmlmZXN0amV4Y2x1c2lvbnOBomVzdGFydBh+Zmxlbmd0aBkeBAAAAj5qdW1iAAAAJ2p1bWRjMmNsABEAEIAAAKoAOJtxA2MycGEuY2xhaW0udjIAAAACD2Nib3KlY2FsZ2ZzaGEyNTZpc2lnbmF0dXJleE1zZWxmI2p1bWJmPS9jMnBhL3VybjpjMnBhOjgwY2U3ZGExLTU2MGQtNGM2YS1hOTJiLWU3ODFjZGEzMGJmMy9jMnBhLnNpZ25hdHVyZWppbnN0YW5jZUlEeCx4bXA6aWlkOjRmZjI2NDEwLWRlYjItNDdhZC1hYzI1LWM3NTljOTcwODhkYnJjcmVhdGVkX2Fzc2VydGlvbnODomN1cmx4LXNlbGYjanVtYmY9YzJwYS5hc3NlcnRpb25zL2MycGEuaW5ncmVkaWVudC52M2RoYXNoWCDhVU+Yk6/L/4jwqdrRWOZ2K909d7Mki8g+LqDc+iGZTaJjdXJseCpzZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmFjdGlvbnMudjJkaGFzaFgghgawfgsJye8WRPfdF/w8xNQfuhKO9QKFJWrH7Jz1+FKiY3VybHgpc2VsZiNqdW1iZj1jMnBhLmFzc2VydGlvbnMvYzJwYS5oYXNoLmRhdGFkaGFzaFggkCpr7BfNstvBAJH09fHBdmXiEW+Wbz/OyKk70shMilt0Y2xhaW1fZ2VuZXJhdG9yX2luZm+jZG5hbWVvQW50aHJvcGljIEZpbGVzZ3ZlcnNpb25lMS4wLjBrc3BlY1ZlcnNpb25lMi40LjAAABA4anVtYgAAAChqdW1kYzJjcwARABCAAACqADibcQNjMnBhLnNpZ25hdHVyZQAAABAIY2JvctKEWQISogEmGCFZAgowggIGMIIBjaADAgECAhRA5aAK7sI50L64g/oGQgU9Z1UTADAKBggqhkjOPQQDAzBJMRcwFQYDVQQKEw5BbnRocm9waWMsIFBCQzEuMCwGA1UEAxMlQW50aHJvcGljIENvbnRlbnQgQ3JlZGVudGlhbHMgUm9vdCBDQTAeFw0yNjA4MDcxODQzNTZaFw0yODA4MDYxOTQzNTZaMEQxFzAVBgNVBAoTDkFudGhyb3BpYywgUEJDMSkwJwYDVQQDEyBBbnRocm9waWMgQ2xhdWRlIENvbnRlbnQgU2lnbmluZzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJh6CmvLUBgFFNU0vUKlOVtE6djd17L5SuwX0LemFisBM3dkd/3cyjxFA3Qo5S46fX0/ihY0VZ7mfb9KF703t5OjWDBWMA4GA1UdDwEB/wQEAwIHgDAVBgNVHSUEDjAMBgorBgEEAYPoXgIBMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAUzlHiBIFOZFsj+OPEz5o+nMHXXMIwCgYIKoZIzj0EAwMDZwAwZAIwMXMdFJ4BetLLVY7ORuE9noqbbAZOZn/aArXyTwFAZfKrPzxF2vPoJNf1+UCdg1XGAjBwX1zd9WGqYkqmL5SFqw1QySjr1zJfpJM9+1rdDwSPLMOPOjKuiXjoU/pUUeG9RwmhY3BhZFkNngAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPZYQJGyudl+viefnDTA9iKbw4KDdqGKhfBMXYPg91KTSq9ZDmZZWbFXOZRHLdrK9KKd15OHqbFaxWotogRLcAaQbt8=</c2pa:manifest></metadata>
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 320" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest>AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYTplZjYzNDg3MC0zZDk4LTQyNjgtYTczMy03NjRiNTk3Zjk3MGUAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaCbBhQTUcVWRekeR93pfogUAAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDoxZTg2NGRiMC04NmU0LTQ3MjktOGNlMi1iZWQ0ODczNWE3NTRscmVsYXRpb25zaGlwaHBhcmVudE9mAAAB4mp1bWIAAABBanVtZGNib3IAEQAQgAAAqgA4m3ETYzJwYS5hY3Rpb25zLnYyAAAAABhjMnNoQ0XdVj8z6JhOuRv8AzgflwAAAZljYm9yomdhY3Rpb25zgqJmYWN0aW9ua2MycGEub3BlbmVkanBhcmFtZXRlcnOha2luZ3JlZGllbnRzgaJjdXJseC1zZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmluZ3JlZGllbnQudjNkaGFzaFggKNxY/r3FVp0Ay6izt3qWBdwaIRKqJGMv83HtVJCVoyykZmFjdGlvbngdY29tLmFudGhyb3BpYy5jbGF1ZGUucHJvdmlkZWRqcGFyYW1ldGVyc6F4H2NvbS5hbnRocm9waWMub3JpZ2luLWNvbmZpZGVuY2VndW5rbm93bmtkZXNjcmlwdGlvbnhmQ2xhdWRlIHByb3ZpZGVkIHRoaXMgZmlsZSBhdCB0aGUgcmVxdWVzdCBvZiBhIHVzZXIgYW5kIG1heSBoYXZlIGNyZWF0ZWQgb3IgbW9kaWZpZWQgdGhlIGZpbGUgY29udGVudHMubXNvZnR3YXJlQWdlbnShZG5hbWVmQ2xhdWRlcmFsbEFjdGlvbnNJbmNsdWRlZPUAAADIanVtYgAAAEBqdW1kY2JvcgARABCAAACqADibcRNjMnBhLmhhc2guZGF0YQAAAAAYYzJzaHQo+PwywXJ8/7d7O/md8/wAAACAY2JvcqVjYWxnZnNoYTI1NmNwYWRNAAAAAAAAAAAAAAAAAGRoYXNoWCA96PFofC7uJt0e/PJKHvSv3KJDRIO4YJccQkL+o0Sd6GRuYW1lbmp1bWJmIG1hbmlmZXN0amV4Y2x1c2lvbnOBomVzdGFydBh+Zmxlbmd0aBkeBAAAAj5qdW1iAAAAJ2p1bWRjMmNsABEAEIAAAKoAOJtxA2MycGEuY2xhaW0udjIAAAACD2Nib3KlY2FsZ2ZzaGEyNTZpc2lnbmF0dXJleE1zZWxmI2p1bWJmPS9jMnBhL3VybjpjMnBhOmVmNjM0ODcwLTNkOTgtNDI2OC1hNzMzLTc2NGI1OTdmOTcwZS9jMnBhLnNpZ25hdHVyZWppbnN0YW5jZUlEeCx4bXA6aWlkOjFiMGMzOTU0LTZhZGMtNDQ1ZC05ZGRlLWU4NTcwZTk5ZTQ5YnJjcmVhdGVkX2Fzc2VydGlvbnODomN1cmx4LXNlbGYjanVtYmY9YzJwYS5hc3NlcnRpb25zL2MycGEuaW5ncmVkaWVudC52M2RoYXNoWCAo3Fj+vcVWnQDLqLO3epYF3BohEqokYy/zce1UkJWjLKJjdXJseCpzZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmFjdGlvbnMudjJkaGFzaFgggbRs8+eGCxdg2CczeUQmXviVUZv/a/5qC7dVhQXlHxGiY3VybHgpc2VsZiNqdW1iZj1jMnBhLmFzc2VydGlvbnMvYzJwYS5oYXNoLmRhdGFkaGFzaFggjKFebkBmBEyV94zz+Ue3XVCZhp85JRZ2G/2G9a1Z0/90Y2xhaW1fZ2VuZXJhdG9yX2luZm+jZG5hbWVvQW50aHJvcGljIEZpbGVzZ3ZlcnNpb25lMS4wLjBrc3BlY1ZlcnNpb25lMi40LjAAABA4anVtYgAAAChqdW1kYzJjcwARABCAAACqADibcQNjMnBhLnNpZ25hdHVyZQAAABAIY2JvctKEWQISogEmGCFZAgowggIGMIIBjaADAgECAhRA5aAK7sI50L64g/oGQgU9Z1UTADAKBggqhkjOPQQDAzBJMRcwFQYDVQQKEw5BbnRocm9waWMsIFBCQzEuMCwGA1UEAxMlQW50aHJvcGljIENvbnRlbnQgQ3JlZGVudGlhbHMgUm9vdCBDQTAeFw0yNjA4MDcxODQzNTZaFw0yODA4MDYxOTQzNTZaMEQxFzAVBgNVBAoTDkFudGhyb3BpYywgUEJDMSkwJwYDVQQDEyBBbnRocm9waWMgQ2xhdWRlIENvbnRlbnQgU2lnbmluZzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJh6CmvLUBgFFNU0vUKlOVtE6djd17L5SuwX0LemFisBM3dkd/3cyjxFA3Qo5S46fX0/ihY0VZ7mfb9KF703t5OjWDBWMA4GA1UdDwEB/wQEAwIHgDAVBgNVHSUEDjAMBgorBgEEAYPoXgIBMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAUzlHiBIFOZFsj+OPEz5o+nMHXXMIwCgYIKoZIzj0EAwMDZwAwZAIwMXMdFJ4BetLLVY7ORuE9noqbbAZOZn/aArXyTwFAZfKrPzxF2vPoJNf1+UCdg1XGAjBwX1zd9WGqYkqmL5SFqw1QySjr1zJfpJM9+1rdDwSPLMOPOjKuiXjoU/pUUeG9RwmhY3BhZFkNngAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPZYQCAiv1vw0tv/9plo4t5PkXH2Ew1fVzXQ4hbnpjWOezZ7TH0HnEjcPZECZel35hUs4gEFBxAd3ZdCF0oGNKqEthY=</c2pa:manifest></metadata>
<rect width="1280" height="320" fill="#0E0E11"/>
<g transform="translate(88 170) scale(2.3)"><rect x="2.66" y="-32.01" width="5.67" height="9.47" fill="#F3F1EC"/><rect x="5.26" y="-20.74" width="5.67" height="9.47" fill="#FF5A1F"/><rect x="2.66" y="-9.47" width="5.67" height="9.47" fill="#F3F1EC"/><path transform="translate(11.48 0)" d="M7.8203125 -12.826171875C7.8203125 -16.693359375 9.947265625 -18.390625 12.783203125 -18.390625C15.68359375 -18.390625 17.359375 -16.650390625 17.359375 -13.3203125V0.0H22.794921875V-14.1796875C22.794921875 -20.001953125 19.443359375 -23.138671875 14.6953125 -23.138671875C11.580078125 -23.138671875 9.28125 -21.763671875 7.734375 -19.20703125V-22.6875H2.40625V0.0H7.8203125ZM38.383125 -22.6875H33.763984375V-25.09375C33.763984375 -26.94140625 34.451484375 -27.650390625 36.299140625 -27.650390625H38.383125V-32.01171875H35.224921875C30.7346875 -32.01171875 28.3284375 -29.90625 28.3284375 -25.99609375V-22.6875H24.24640625V-18.326171875H28.3284375V0.0H33.763984375V-18.326171875H38.383125ZM40.32875 0.0H45.7428125V-12.84765625C45.7428125 -16.392578125 47.740859375 -18.17578125 50.318984375 -18.17578125C51.393203125 -18.17578125 52.467421875 -18.068359375 52.875625 -18.00390625V-22.81640625C52.4459375 -22.859375 51.844375 -22.90234375 51.11390625 -22.90234375C48.19203125 -22.90234375 46.451796875 -21.52734375 45.61390625 -18.927734375H45.549453125V-22.6875H40.32875ZM61.588828125 0.365234375C65.28414062499999 0.365234375 67.19624999999999 -1.181640625 68.27046874999999 -3.201171875H68.35640624999999V0.0H73.68453124999999V-15.46875C73.68453124999999 -20.1953125 70.18257812499999 -23.138671875 64.27437499999999 -23.138671875C58.3446875 -23.138671875 54.649375 -20.15234375 54.3915625 -15.640625H59.612265625C59.76265625 -17.552734375 61.524375 -18.927734375 64.16695312499999 -18.927734375C66.76656249999999 -18.927734375 68.31343749999999 -17.552734375 68.31343749999999 -15.619140625V-15.447265625C68.31343749999999 -13.900390625 66.87398437499999 -13.8359375 62.663046875 -13.36328125C57.979453125 -12.869140625 53.74703125 -11.6015625 53.74703125 -6.4453125C53.74703125 -1.912109375 57.077109375 0.365234375 61.588828125 0.365234375ZM62.920859375 -3.65234375C60.557578125 -3.65234375 59.0321875 -4.705078125 59.0321875 -6.48828125C59.0321875 -8.55078125 61.00875 -9.388671875 63.3290625 -9.732421875C65.56343749999999 -10.076171875 67.66890624999999 -10.419921875 68.33492187499999 -10.849609375V-8.400390625C68.33492187499999 -5.7578125 66.46578124999999 -3.65234375 62.920859375 -3.65234375ZM85.921171875 0.451171875C88.886015625 0.451171875 91.378203125 -0.837890625 92.796171875 -3.458984375H92.839140625V0.0H98.167265625V-32.01171875H92.753203125V-19.46484375H92.710234375C91.249296875 -21.95703125 88.8215625 -23.138671875 85.878203125 -23.138671875C80.0559375 -23.138671875 76.1028125 -18.34765625 76.1028125 -11.365234375C76.1028125 -4.296875 79.991484375 0.451171875 85.921171875 0.451171875ZM87.18875 -4.08203125C83.8371875 -4.08203125 81.581328125 -6.66015625 81.581328125 -11.365234375C81.581328125 -16.048828125 83.8371875 -18.6484375 87.18875 -18.6484375C90.733671875 -18.6484375 93.053984375 -15.76953125 93.053984375 -11.365234375C93.053984375 -6.939453125 90.733671875 -4.08203125 87.18875 -4.08203125ZM111.671484375 0.515625C116.978125 0.515625 121.1890625 -2.556640625 122.0484375 -7.00390625H116.978125C116.355078125 -5.0703125 114.52890625 -3.759765625 111.800390625 -3.759765625C108.148046875 -3.759765625 106.042578125 -6.23046875 105.913671875 -9.92578125H122.327734375V-11.408203125C122.327734375 -18.369140625 117.987890625 -23.203125 111.456640625 -23.203125C105.097265625 -23.203125 100.60703125 -18.21875 100.60703125 -11.322265625C100.60703125 -4.447265625 104.8609375 0.515625 111.671484375 0.515625ZM105.956640625 -13.6640625C106.321875 -16.908203125 108.405859375 -18.90625 111.542578125 -18.90625C114.679296875 -18.90625 116.784765625 -16.908203125 117.128515625 -13.6640625ZM134.714765625 0.515625C140.45109375 0.515625 144.6190625 -3.1796875 145.00578125 -8.142578125H139.656171875C139.140546875 -5.62890625 137.61515625 -3.99609375 134.77921875 -3.99609375C131.2128125 -3.99609375 129.10734375 -6.853515625 129.10734375 -11.322265625C129.10734375 -15.8125 131.234296875 -18.69140625 134.77921875 -18.69140625C137.593671875 -18.69140625 139.2909375 -16.994140625 139.699140625 -14.56640625H145.00578125C144.533125 -19.615234375 140.408125 -23.203125 134.714765625 -23.203125C128.07609375 -23.203125 123.62882812500001 -18.326171875 123.62882812500001 -11.322265625C123.62882812500001 -4.318359375 128.07609375 0.515625 134.714765625 0.515625ZM147.31664062500002 0.0H152.73070312500002V-7.583984375L154.79320312500002 -9.7109375L162.22679687500002 0.0H168.69359375000002L158.91820312500002 -12.890625L168.13500000000002 -22.6875H161.62523437500002L152.79515625000002 -13.4921875H152.73070312500002V-32.01171875H147.31664062500002Z" fill="#F3F1EC"/></g>
- <path transform="translate(96 228)" d="M6.4453125 0.0H8.89453125V-6.3701171875L14.7705078125 -16.005859375H11.923828125L8.9482421875 -10.9033203125C8.4755859375 -10.09765625 8.0888671875 -9.3779296875 7.69140625 -8.4111328125C7.2939453125 -9.3564453125 6.9072265625 -10.0654296875 6.4130859375 -10.9033203125L3.4052734375 -16.005859375H0.5478515625L6.4453125 -6.3701171875ZM21.84703125 0.2470703125C25.2308203125 0.2470703125 27.4651953125 -2.234375 27.4651953125 -5.9404296875C27.4651953125 -9.6787109375 25.2308203125 -12.16015625 21.84703125 -12.16015625C18.4632421875 -12.16015625 16.239609375 -9.6787109375 16.239609375 -5.9404296875C16.239609375 -2.234375 18.4632421875 0.2470703125 21.84703125 0.2470703125ZM21.84703125 -1.7509765625C19.677109375 -1.7509765625 18.645859375 -3.6630859375 18.645859375 -5.9404296875C18.645859375 -8.25 19.677109375 -10.162109375 21.84703125 -10.162109375C24.0384375 -10.162109375 25.0696875 -8.2392578125 25.0696875 -5.9404296875C25.0696875 -3.6630859375 24.0384375 -1.7509765625 21.84703125 -1.7509765625ZM34.0690625 0.150390625C35.723359375 0.150390625 37.012421875 -0.5908203125 37.764375 -2.3310546875L37.7751171875 0.0H40.04171875V-12.009765625H37.6676953125V-4.8984375C37.6676953125 -2.9970703125 36.4753125 -1.912109375 34.8747265625 -1.912109375C33.3063671875 -1.912109375 32.3395703125 -2.943359375 32.3395703125 -4.6728515625V-12.009765625H29.9762890625V-4.3828125C29.9762890625 -1.41796875 31.61984375 0.150390625 34.0690625 0.150390625ZM43.1006640625 0.0H45.4639453125V-7.2939453125C45.4639453125 -8.873046875 46.6670703125 -9.990234375 48.3213671875 -9.990234375C48.8155078125 -9.990234375 49.38484375 -9.904296875 49.55671875 -9.861328125V-12.1171875C49.3096484375 -12.1494140625 48.8584765625 -12.181640625 48.5576953125 -12.181640625C47.15046875 -12.181640625 45.9580859375 -11.38671875 45.51765625 -10.076171875H45.38875V-12.009765625H43.1006640625ZM61.561328125 0.2470703125C64.4939453125 0.2470703125 66.5134765625 -1.2998046875 66.5134765625 -3.4912109375C66.5134765625 -5.15625 65.4607421875 -6.23046875 63.237109375 -6.7353515625L61.303515625 -7.1650390625C59.9822265625 -7.4658203125 59.4451171875 -7.9384765625 59.4451171875 -8.7333984375C59.4451171875 -9.6357421875 60.4333984375 -10.291015625 61.733203125 -10.291015625C63.151171875 -10.291015625 63.8279296875 -9.5390625 64.139453125 -8.701171875L66.2556640625 -9.1630859375C65.7400390625 -10.9462890625 64.311328125 -12.16015625 61.71171875 -12.16015625C58.9939453125 -12.16015625 57.0603515625 -10.7314453125 57.0603515625 -8.5830078125C57.0603515625 -6.8642578125 58.1345703125 -5.7685546875 60.3689453125 -5.263671875L62.3884765625 -4.8017578125C63.5271484375 -4.5439453125 64.075 -4.0498046875 64.075 -3.287109375C64.075 -2.3955078125 63.108203125 -1.6650390625 61.5828125 -1.6650390625C60.186328125 -1.6650390625 59.2732421875 -2.2451171875 58.940234375 -3.501953125L56.7166015625 -3.0400390625C57.1462890625 -0.9130859375 58.9509765625 0.2470703125 61.561328125 0.2470703125ZM74.170078125 0.2470703125C76.7374609375 0.2470703125 78.574375 -1.009765625 79.1437109375 -2.87890625L76.920078125 -3.4052734375C76.5011328125 -2.2880859375 75.5128515625 -1.7080078125 74.1915625 -1.7080078125C72.2257421875 -1.7080078125 70.8937109375 -2.96484375 70.8077734375 -5.28515625H79.326328125V-6.123046875C79.326328125 -10.4521484375 76.705234375 -12.16015625 73.9659765625 -12.16015625C70.603671875 -12.16015625 68.43375 -9.6142578125 68.43375 -5.9189453125C68.43375 -2.19140625 70.62515625 0.2470703125 74.170078125 0.2470703125ZM70.818515625 -7.046875C70.947421875 -8.7763671875 72.08609375 -10.205078125 73.97671875 -10.205078125C75.7921484375 -10.205078125 76.81265625 -8.9375 76.98453125 -7.046875ZM84.1684765625 -16.005859375H81.8051953125V0.0H84.1684765625ZM93.1893359375 -12.009765625H90.5037890625V-13.0625C90.5037890625 -14.115234375 90.965703125 -14.6953125 92.0936328125 -14.6953125C92.5877734375 -14.6953125 92.92078125 -14.587890625 93.1463671875 -14.5234375L93.69421875 -16.435546875C93.371953125 -16.5537109375 92.66296875 -16.7578125 91.71765625 -16.7578125C89.8162890625 -16.7578125 88.1405078125 -15.6298828125 88.1405078125 -13.384765625V-12.009765625H85.8631640625V-10.0869140625H88.1405078125V0.0H90.5037890625V-10.0869140625H93.1893359375ZM102.5324609375 -7.77734375H95.4211328125V-5.7255859375H102.5324609375ZM107.9009765625 -7.111328125C107.9009765625 -9.0126953125 109.0826171875 -10.09765625 110.6939453125 -10.09765625C112.2623046875 -10.09765625 113.2291015625 -9.06640625 113.2291015625 -7.3369140625V0.0H115.603125V-7.626953125C115.603125 -10.591796875 113.9595703125 -12.16015625 111.5103515625 -12.16015625C109.866796875 -12.16015625 108.6314453125 -11.4404296875 107.8794921875 -9.8505859375V-16.005859375H105.5376953125V0.0H107.9009765625ZM123.7108984375 0.2470703125C127.0946875 0.2470703125 129.32906250000002 -2.234375 129.32906250000002 -5.9404296875C129.32906250000002 -9.6787109375 127.0946875 -12.16015625 123.7108984375 -12.16015625C120.327109375 -12.16015625 118.1034765625 -9.6787109375 118.1034765625 -5.9404296875C118.1034765625 -2.234375 120.327109375 0.2470703125 123.7108984375 0.2470703125ZM123.7108984375 -1.7509765625C121.5409765625 -1.7509765625 120.5097265625 -3.6630859375 120.5097265625 -5.9404296875C120.5097265625 -8.25 121.5409765625 -10.162109375 123.7108984375 -10.162109375C125.9023046875 -10.162109375 126.9335546875 -8.2392578125 126.9335546875 -5.9404296875C126.9335546875 -3.6630859375 125.9023046875 -1.7509765625 123.7108984375 -1.7509765625ZM136.1477734375 0.2470703125C139.080390625 0.2470703125 141.099921875 -1.2998046875 141.099921875 -3.4912109375C141.099921875 -5.15625 140.0471875 -6.23046875 137.8235546875 -6.7353515625L135.8899609375 -7.1650390625C134.568671875 -7.4658203125 134.0315625 -7.9384765625 134.0315625 -8.7333984375C134.0315625 -9.6357421875 135.01984375 -10.291015625 136.3196484375 -10.291015625C137.7376171875 -10.291015625 138.414375 -9.5390625 138.7258984375 -8.701171875L140.842109375 -9.1630859375C140.326484375 -10.9462890625 138.8977734375 -12.16015625 136.2981640625 -12.16015625C133.580390625 -12.16015625 131.646796875 -10.7314453125 131.646796875 -8.5830078125C131.646796875 -6.8642578125 132.721015625 -5.7685546875 134.955390625 -5.263671875L136.974921875 -4.8017578125C138.11359375 -4.5439453125 138.6614453125 -4.0498046875 138.6614453125 -3.287109375C138.6614453125 -2.3955078125 137.6946484375 -1.6650390625 136.1692578125 -1.6650390625C134.7727734375 -1.6650390625 133.8596875 -2.2451171875 133.5266796875 -3.501953125L131.303046875 -3.0400390625C131.732734375 -0.9130859375 133.537421875 0.2470703125 136.1477734375 0.2470703125ZM148.7135546875 -12.009765625H146.318046875V-14.8671875H143.954765625V-12.009765625H142.2037890625V-10.0869140625H143.954765625V-3.05078125C143.954765625 -1.009765625 145.2116015625 0.1611328125 147.392265625 0.1611328125C147.9401171875 0.1611328125 148.5416796875 0.0859375 149.0465625 -0.0859375L148.6276171875 -1.9765625C148.337578125 -1.912109375 147.8756640625 -1.84765625 147.62859375 -1.84765625C146.6940234375 -1.84765625 146.318046875 -2.27734375 146.318046875 -3.244140625V-10.0869140625H148.7135546875ZM156.13382812499998 0.2470703125C158.70121093749998 0.2470703125 160.53812499999998 -1.009765625 161.10746093749998 -2.87890625L158.88382812499998 -3.4052734375C158.46488281249998 -2.2880859375 157.47660156249998 -1.7080078125 156.15531249999998 -1.7080078125C154.18949218749998 -1.7080078125 152.85746093749998 -2.96484375 152.77152343749998 -5.28515625H161.29007812499998V-6.123046875C161.29007812499998 -10.4521484375 158.66898437499998 -12.16015625 155.92972656249998 -12.16015625C152.56742187499998 -12.16015625 150.39749999999998 -9.6142578125 150.39749999999998 -5.9189453125C150.39749999999998 -2.19140625 152.58890624999998 0.2470703125 156.13382812499998 0.2470703125ZM152.78226562499998 -7.046875C152.91117187499998 -8.7763671875 154.04984374999998 -10.205078125 155.94046874999998 -10.205078125C157.75589843749998 -10.205078125 158.77640624999998 -8.9375 158.94828124999998 -7.046875ZM168.23769531249997 0.236328125C170.40761718749997 0.236328125 171.27773437499997 -1.1171875 171.69667968749997 -1.8798828125H171.89003906249997V0.0H174.18886718749997V-16.005859375H171.82558593749997V-10.0546875H171.69667968749997C171.28847656249997 -10.7958984375 170.47207031249997 -12.16015625 168.23769531249997 -12.16015625C165.34804687499997 -12.16015625 163.21035156249997 -9.8828125 163.21035156249997 -5.97265625C163.21035156249997 -2.0947265625 165.31582031249997 0.236328125 168.23769531249997 0.236328125ZM168.75332031249997 -1.7724609375C166.70156249999997 -1.7724609375 165.62734374999997 -3.609375 165.62734374999997 -5.994140625C165.62734374999997 -8.357421875 166.66933593749997 -10.1513671875 168.75332031249997 -10.1513671875C170.78359374999997 -10.1513671875 171.86855468749997 -8.486328125 171.86855468749997 -5.994140625C171.86855468749997 -3.4912109375 170.76210937499997 -1.7724609375 168.75332031249997 -1.7724609375ZM183.01378906249994 0.0H185.37707031249994V-12.009765625H183.01378906249994ZM184.20617187499994 -13.8466796875C185.02257812499994 -13.8466796875 185.69933593749994 -14.4697265625 185.69933593749994 -15.2431640625C185.69933593749994 -16.02734375 185.02257812499994 -16.650390625 184.20617187499994 -16.650390625C183.38976562499994 -16.650390625 182.71300781249994 -16.02734375 182.71300781249994 -15.2431640625C182.71300781249994 -14.4697265625 183.38976562499994 -13.8466796875 184.20617187499994 -13.8466796875ZM190.81003906249992 -7.111328125C190.81003906249992 -9.0126953125 191.99167968749992 -10.09765625 193.60300781249992 -10.09765625C195.17136718749992 -10.09765625 196.13816406249992 -9.06640625 196.13816406249992 -7.3369140625V0.0H198.50144531249992V-7.626953125C198.50144531249992 -10.591796875 196.86863281249992 -12.16015625 194.41941406249992 -12.16015625C192.72214843749992 -12.16015625 191.46531249999992 -11.3974609375 190.71335937499992 -9.7001953125L190.70261718749992 -12.009765625H188.44675781249992V0.0H190.81003906249992ZM207.5223046874999 -12.009765625H204.8367578124999V-13.0625C204.8367578124999 -14.115234375 205.2986718749999 -14.6953125 206.4266015624999 -14.6953125C206.9207421874999 -14.6953125 207.2537499999999 -14.587890625 207.4793359374999 -14.5234375L208.0271874999999 -16.435546875C207.7049218749999 -16.5537109375 206.9959374999999 -16.7578125 206.0506249999999 -16.7578125C204.1492578124999 -16.7578125 202.4734765624999 -15.6298828125 202.4734765624999 -13.384765625V-12.009765625H200.1961328124999V-10.0869140625H202.4734765624999V0.0H204.8367578124999V-10.0869140625H207.5223046874999ZM209.8078124999999 0.0H212.1710937499999V-7.2939453125C212.1710937499999 -8.873046875 213.3742187499999 -9.990234375 215.0285156249999 -9.990234375C215.5226562499999 -9.990234375 216.0919921874999 -9.904296875 216.2638671874999 -9.861328125V-12.1171875C216.0167968749999 -12.1494140625 215.5656249999999 -12.181640625 215.2648437499999 -12.181640625C213.8576171874999 -12.181640625 212.6652343749999 -11.38671875 212.2248046874999 -10.076171875H212.0958984374999V-12.009765625H209.8078124999999ZM221.56792968749988 0.2685546875C223.51226562499988 0.2685546875 224.65093749999988 -0.708984375 225.11285156249988 -1.6435546875H225.23101562499988V0.0H227.51910156249988V-7.970703125C227.51910156249988 -11.4404296875 224.75835937499988 -12.16015625 222.82476562499988 -12.16015625C220.68707031249988 -12.16015625 218.66753906249988 -11.322265625 217.85113281249988 -9.173828125L220.07476562499988 -8.59375C220.40777343749988 -9.41015625 221.28863281249988 -10.2373046875 222.85699218749988 -10.2373046875C224.36089843749988 -10.2373046875 225.15582031249988 -9.4638671875 225.15582031249988 -8.1318359375V-8.0673828125C225.15582031249988 -7.21875 224.24273437499988 -7.2294921875 222.12652343749988 -6.982421875C219.85992187499988 -6.724609375 217.50738281249988 -6.123046875 217.50738281249988 -3.39453125C217.50738281249988 -1.03125 219.27984374999988 0.2685546875 221.56792968749988 0.2685546875ZM222.09429687499988 -1.6328125C220.77300781249988 -1.6328125 219.82769531249988 -2.2236328125 219.82769531249988 -3.3623046875C219.82769531249988 -4.59765625 220.92339843749988 -5.048828125 222.25542968749988 -5.2314453125C222.98589843749988 -5.328125 224.81207031249988 -5.521484375 225.16656249999988 -5.865234375V-4.3291015625C225.16656249999988 -2.921875 224.01714843749988 -1.6328125 222.09429687499988 -1.6328125ZM234.89640624999987 0.2470703125C237.82902343749987 0.2470703125 239.84855468749987 -1.2998046875 239.84855468749987 -3.4912109375C239.84855468749987 -5.15625 238.79582031249987 -6.23046875 236.57218749999987 -6.7353515625L234.63859374999987 -7.1650390625C233.31730468749987 -7.4658203125 232.78019531249987 -7.9384765625 232.78019531249987 -8.7333984375C232.78019531249987 -9.6357421875 233.76847656249987 -10.291015625 235.06828124999987 -10.291015625C236.48624999999987 -10.291015625 237.16300781249987 -9.5390625 237.47453124999987 -8.701171875L239.59074218749987 -9.1630859375C239.07511718749987 -10.9462890625 237.64640624999987 -12.16015625 235.04679687499987 -12.16015625C232.32902343749987 -12.16015625 230.39542968749987 -10.7314453125 230.39542968749987 -8.5830078125C230.39542968749987 -6.8642578125 231.46964843749987 -5.7685546875 233.70402343749987 -5.263671875L235.72355468749987 -4.8017578125C236.86222656249987 -4.5439453125 237.41007812499987 -4.0498046875 237.41007812499987 -3.287109375C237.41007812499987 -2.3955078125 236.44328124999987 -1.6650390625 234.91789062499987 -1.6650390625C233.52140624999987 -1.6650390625 232.60832031249987 -2.2451171875 232.27531249999987 -3.501953125L230.05167968749987 -3.0400390625C230.48136718749987 -0.9130859375 232.28605468749987 0.2470703125 234.89640624999987 0.2470703125ZM247.46218749999986 -12.009765625H245.06667968749986V-14.8671875H242.70339843749986V-12.009765625H240.95242187499986V-10.0869140625H242.70339843749986V-3.05078125C242.70339843749986 -1.009765625 243.96023437499986 0.1611328125 246.14089843749986 0.1611328125C246.68874999999986 0.1611328125 247.29031249999986 0.0859375 247.79519531249986 -0.0859375L247.37624999999986 -1.9765625C247.08621093749986 -1.912109375 246.62429687499986 -1.84765625 246.37722656249986 -1.84765625C245.44265624999986 -1.84765625 245.06667968749986 -2.27734375 245.06667968749986 -3.244140625V-10.0869140625H247.46218749999986ZM249.70472656249984 0.0H252.06800781249984V-7.2939453125C252.06800781249984 -8.873046875 253.27113281249984 -9.990234375 254.92542968749984 -9.990234375C255.41957031249984 -9.990234375 255.98890624999984 -9.904296875 256.16078124999984 -9.861328125V-12.1171875C255.91371093749984 -12.1494140625 255.46253906249984 -12.181640625 255.16175781249984 -12.181640625C253.75453124999984 -12.181640625 252.56214843749984 -11.38671875 252.12171874999984 -10.076171875H251.99281249999984V-12.009765625H249.70472656249984ZM262.19531249999983 0.150390625C263.84960937499983 0.150390625 265.13867187499983 -0.5908203125 265.89062499999983 -2.3310546875L265.90136718749983 0.0H268.16796874999983V-12.009765625H265.79394531249983V-4.8984375C265.79394531249983 -2.9970703125 264.60156249999983 -1.912109375 263.00097656249983 -1.912109375C261.43261718749983 -1.912109375 260.46582031249983 -2.943359375 260.46582031249983 -4.6728515625V-12.009765625H258.10253906249983V-4.3828125C258.10253906249983 -1.41796875 259.74609374999983 0.150390625 262.19531249999983 0.150390625ZM276.2757421874998 0.2470703125C278.8001562499998 0.2470703125 280.7552343749998 -1.1171875 281.3353124999998 -3.3837890625L279.1009374999998 -3.9208984375C278.7786718749998 -2.62109375 277.7796484374998 -1.7509765625 276.2864843749998 -1.7509765625C274.1165624999998 -1.7509765625 273.0745703124998 -3.65234375 273.0745703124998 -5.9404296875C273.0745703124998 -8.2607421875 274.1165624999998 -10.162109375 276.2864843749998 -10.162109375C277.7581640624998 -10.162109375 278.7357031249998 -9.3134765625 279.0579687499998 -8.078125L281.3030859374998 -8.615234375C280.7122656249998 -10.8388671875 278.7679296874998 -12.16015625 276.2757421874998 -12.16015625C272.8919531249998 -12.16015625 270.6683203124998 -9.6787109375 270.6683203124998 -5.9404296875C270.6683203124998 -2.234375 272.8919531249998 0.2470703125 276.2757421874998 0.2470703125ZM288.9489453124998 -12.009765625H286.5534374999998V-14.8671875H284.1901562499998V-12.009765625H282.4391796874998V-10.0869140625H284.1901562499998V-3.05078125C284.1901562499998 -1.009765625 285.4469921874998 0.1611328125 287.6276562499998 0.1611328125C288.1755078124998 0.1611328125 288.7770703124998 0.0859375 289.2819531249998 -0.0859375L288.8630078124998 -1.9765625C288.5729687499998 -1.912109375 288.1110546874998 -1.84765625 287.8639843749998 -1.84765625C286.9294140624998 -1.84765625 286.5534374999998 -2.27734375 286.5534374999998 -3.244140625V-10.0869140625H288.9489453124998ZM295.2842578124998 0.150390625C296.9385546874998 0.150390625 298.2276171874998 -0.5908203125 298.9795703124998 -2.3310546875L298.9903124999998 0.0H301.2569140624998V-12.009765625H298.8828906249998V-4.8984375C298.8828906249998 -2.9970703125 297.6905078124998 -1.912109375 296.0899218749998 -1.912109375C294.5215624999998 -1.912109375 293.5547656249998 -2.943359375 293.5547656249998 -4.6728515625V-12.009765625H291.1914843749998V-4.3828125C291.1914843749998 -1.41796875 292.8350390624998 0.150390625 295.2842578124998 0.150390625ZM304.3158593749998 0.0H306.6791406249998V-7.2939453125C306.6791406249998 -8.873046875 307.8822656249998 -9.990234375 309.5365624999998 -9.990234375C310.0307031249998 -9.990234375 310.6000390624998 -9.904296875 310.7719140624998 -9.861328125V-12.1171875C310.5248437499998 -12.1494140625 310.0736718749998 -12.181640625 309.7728906249998 -12.181640625C308.3656640624998 -12.181640625 307.1732812499998 -11.38671875 306.7328515624998 -10.076171875H306.6039453124998V-12.009765625H304.3158593749998ZM317.89140624999976 0.2470703125C320.45878906249976 0.2470703125 322.29570312499976 -1.009765625 322.86503906249976 -2.87890625L320.64140624999976 -3.4052734375C320.22246093749976 -2.2880859375 319.23417968749976 -1.7080078125 317.91289062499976 -1.7080078125C315.94707031249976 -1.7080078125 314.61503906249976 -2.96484375 314.52910156249976 -5.28515625H323.04765624999976V-6.123046875C323.04765624999976 -10.4521484375 320.42656249999976 -12.16015625 317.68730468749976 -12.16015625C314.32499999999976 -12.16015625 312.15507812499976 -9.6142578125 312.15507812499976 -5.9189453125C312.15507812499976 -2.19140625 314.34648437499976 0.2470703125 317.89140624999976 0.2470703125ZM314.53984374999976 -7.046875C314.66874999999976 -8.7763671875 315.80742187499976 -10.205078125 317.69804687499976 -10.205078125C319.51347656249976 -10.205078125 320.53398437499976 -8.9375 320.70585937499976 -7.046875ZM325.27945312499975 3.9853515625H326.99820312499975L328.77066406249975 -2.298828125H326.22476562499975ZM342.8914843749997 0.2470703125C346.2752734374997 0.2470703125 348.5096484374997 -2.234375 348.5096484374997 -5.9404296875C348.5096484374997 -9.6787109375 346.2752734374997 -12.16015625 342.8914843749997 -12.16015625C339.5076953124997 -12.16015625 337.2840624999997 -9.6787109375 337.2840624999997 -5.9404296875C337.2840624999997 -2.234375 339.5076953124997 0.2470703125 342.8914843749997 0.2470703125ZM342.8914843749997 -1.7509765625C340.7215624999997 -1.7509765625 339.6903124999997 -3.6630859375 339.6903124999997 -5.9404296875C339.6903124999997 -8.25 340.7215624999997 -10.162109375 342.8914843749997 -10.162109375C345.0828906249997 -10.162109375 346.1141406249997 -8.2392578125 346.1141406249997 -5.9404296875C346.1141406249997 -3.6630859375 345.0828906249997 -1.7509765625 342.8914843749997 -1.7509765625ZM353.3840234374997 -7.111328125C353.3840234374997 -9.0126953125 354.5656640624997 -10.09765625 356.1769921874997 -10.09765625C357.7453515624997 -10.09765625 358.7121484374997 -9.06640625 358.7121484374997 -7.3369140625V0.0H361.0754296874997V-7.626953125C361.0754296874997 -10.591796875 359.4426171874997 -12.16015625 356.9933984374997 -12.16015625C355.2961328124997 -12.16015625 354.0392968749997 -11.3974609375 353.2873437499997 -9.7001953125L353.2766015624997 -12.009765625H351.0207421874997V0.0H353.3840234374997ZM374.9491796874997 0.2470703125C378.3329687499997 0.2470703125 380.5673437499997 -2.234375 380.5673437499997 -5.9404296875C380.5673437499997 -9.6787109375 378.3329687499997 -12.16015625 374.9491796874997 -12.16015625C371.5653906249997 -12.16015625 369.3417578124997 -9.6787109375 369.3417578124997 -5.9404296875C369.3417578124997 -2.234375 371.5653906249997 0.2470703125 374.9491796874997 0.2470703125ZM374.9491796874997 -1.7509765625C372.7792578124997 -1.7509765625 371.7480078124997 -3.6630859375 371.7480078124997 -5.9404296875C371.7480078124997 -8.25 372.7792578124997 -10.162109375 374.9491796874997 -10.162109375C377.1405859374997 -10.162109375 378.1718359374997 -8.2392578125 378.1718359374997 -5.9404296875C378.1718359374997 -3.6630859375 377.1405859374997 -1.7509765625 374.9491796874997 -1.7509765625ZM385.44171874999967 -7.111328125C385.44171874999967 -9.0126953125 386.62335937499967 -10.09765625 388.23468749999967 -10.09765625C389.80304687499967 -10.09765625 390.76984374999967 -9.06640625 390.76984374999967 -7.3369140625V0.0H393.13312499999967V-7.626953125C393.13312499999967 -10.591796875 391.50031249999967 -12.16015625 389.05109374999967 -12.16015625C387.35382812499967 -12.16015625 386.09699218749967 -11.3974609375 385.34503906249967 -9.7001953125L385.33429687499967 -12.009765625H383.07843749999967V0.0H385.44171874999967ZM401.38054687499965 0.2470703125C403.94792968749965 0.2470703125 405.78484374999965 -1.009765625 406.35417968749965 -2.87890625L404.13054687499965 -3.4052734375C403.71160156249965 -2.2880859375 402.72332031249965 -1.7080078125 401.40203124999965 -1.7080078125C399.43621093749965 -1.7080078125 398.10417968749965 -2.96484375 398.01824218749965 -5.28515625H406.53679687499965V-6.123046875C406.53679687499965 -10.4521484375 403.91570312499965 -12.16015625 401.17644531249965 -12.16015625C397.81414062499965 -12.16015625 395.64421874999965 -9.6142578125 395.64421874999965 -5.9189453125C395.64421874999965 -2.19140625 397.83562499999965 0.2470703125 401.38054687499965 0.2470703125ZM398.02898437499965 -7.046875C398.15789062499965 -8.7763671875 399.29656249999965 -10.205078125 401.18718749999965 -10.205078125C403.00261718749965 -10.205078125 404.02312499999965 -8.9375 404.19499999999965 -7.046875ZM419.2396484374996 0.236328125C421.4095703124996 0.236328125 422.2796874999996 -1.1171875 422.6986328124996 -1.8798828125H422.8919921874996V0.0H425.1908203124996V-16.005859375H422.8275390624996V-10.0546875H422.6986328124996C422.2904296874996 -10.7958984375 421.4740234374996 -12.16015625 419.2396484374996 -12.16015625C416.3499999999996 -12.16015625 414.2123046874996 -9.8828125 414.2123046874996 -5.97265625C414.2123046874996 -2.0947265625 416.3177734374996 0.236328125 419.2396484374996 0.236328125ZM419.7552734374996 -1.7724609375C417.7035156249996 -1.7724609375 416.6292968749996 -3.609375 416.6292968749996 -5.994140625C416.6292968749996 -8.357421875 417.6712890624996 -10.1513671875 419.7552734374996 -10.1513671875C421.7855468749996 -10.1513671875 422.8705078124996 -8.486328125 422.8705078124996 -5.994140625C422.8705078124996 -3.4912109375 421.7640624999996 -1.7724609375 419.7552734374996 -1.7724609375ZM433.4382421874996 0.2470703125C436.0056249999996 0.2470703125 437.8425390624996 -1.009765625 438.4118749999996 -2.87890625L436.1882421874996 -3.4052734375C435.7692968749996 -2.2880859375 434.7810156249996 -1.7080078125 433.4597265624996 -1.7080078125C431.4939062499996 -1.7080078125 430.1618749999996 -2.96484375 430.0759374999996 -5.28515625H438.5944921874996V-6.123046875C438.5944921874996 -10.4521484375 435.9733984374996 -12.16015625 433.2341406249996 -12.16015625C429.8718359374996 -12.16015625 427.7019140624996 -9.6142578125 427.7019140624996 -5.9189453125C427.7019140624996 -2.19140625 429.8933203124996 0.2470703125 433.4382421874996 0.2470703125ZM430.0866796874996 -7.046875C430.2155859374996 -8.7763671875 431.3542578124996 -10.205078125 433.2448828124996 -10.205078125C435.0603124999996 -10.205078125 436.0808203124996 -8.9375 436.2526953124996 -7.046875ZM446.1221874999996 0.2470703125C448.6466015624996 0.2470703125 450.6016796874996 -1.1171875 451.1817578124996 -3.3837890625L448.9473828124996 -3.9208984375C448.6251171874996 -2.62109375 447.6260937499996 -1.7509765625 446.1329296874996 -1.7509765625C443.9630078124996 -1.7509765625 442.9210156249996 -3.65234375 442.9210156249996 -5.9404296875C442.9210156249996 -8.2607421875 443.9630078124996 -10.162109375 446.1329296874996 -10.162109375C447.6046093749996 -10.162109375 448.5821484374996 -9.3134765625 448.9044140624996 -8.078125L451.1495312499996 -8.615234375C450.5587109374996 -10.8388671875 448.6143749999996 -12.16015625 446.1221874999996 -12.16015625C442.7383984374996 -12.16015625 440.5147656249996 -9.6787109375 440.5147656249996 -5.9404296875C440.5147656249996 -2.234375 442.7383984374996 0.2470703125 446.1221874999996 0.2470703125ZM453.6606249999996 0.0H456.0239062499996V-4.232421875L457.1733203124996 -5.3818359375L461.2231249999996 0.0H464.1449999999996L458.9780078124996 -6.83203125L463.8119921874996 -12.009765625H460.9760546874996L456.2387499999996 -6.939453125H456.0239062499996V-16.005859375H453.6606249999996ZM467.60140624999957 0.1611328125C468.48226562499957 0.1611328125 469.18050781249957 -0.537109375 469.18050781249957 -1.41796875C469.18050781249957 -2.3095703125 468.48226562499957 -3.0078125 467.60140624999957 -3.0078125C466.70980468749957 -3.0078125 466.01156249999957 -2.3095703125 466.01156249999957 -1.41796875C466.01156249999957 -0.537109375 466.70980468749957 0.1611328125 467.60140624999957 0.1611328125Z" fill="#9A9890"/>
+ <path transform="translate(96 228)" d="M1.7724609375 0.0H11.9130859375V-2.10546875H4.2216796875V-7.0361328125H11.3115234375V-9.130859375H4.2216796875V-13.900390625H11.8486328125V-16.005859375H1.7724609375ZM18.1839453125 0.0H20.7620703125L25.2952734375 -12.009765625H22.7601171875L20.38609375 -5.1884765625C20.020859375 -4.125 19.763046875 -3.072265625 19.4944921875 -2.01953125C19.2259375 -3.072265625 18.946640625 -4.125 18.58140625 -5.1884765625L16.2073828125 -12.009765625H13.6507421875ZM32.457734375 0.2470703125C35.0251171875 0.2470703125 36.86203125 -1.009765625 37.4313671875 -2.87890625L35.207734375 -3.4052734375C34.7887890625 -2.2880859375 33.8005078125 -1.7080078125 32.47921875 -1.7080078125C30.5133984375 -1.7080078125 29.1813671875 -2.96484375 29.0954296875 -5.28515625H37.613984375V-6.123046875C37.613984375 -10.4521484375 34.992890625 -12.16015625 32.2536328125 -12.16015625C28.891328125 -12.16015625 26.72140625 -9.6142578125 26.72140625 -5.9189453125C26.72140625 -2.19140625 28.9128125 0.2470703125 32.457734375 0.2470703125ZM29.106171875 -7.046875C29.235078125 -8.7763671875 30.37375 -10.205078125 32.264375 -10.205078125C34.0798046875 -10.205078125 35.1003125 -8.9375 35.2721875 -7.046875ZM40.0928515625 0.0H42.4561328125V-7.2939453125C42.4561328125 -8.873046875 43.6592578125 -9.990234375 45.3135546875 -9.990234375C45.8076953125 -9.990234375 46.37703125 -9.904296875 46.54890625 -9.861328125V-12.1171875C46.3018359375 -12.1494140625 45.8506640625 -12.181640625 45.5498828125 -12.181640625C44.14265625 -12.181640625 42.9502734375 -11.38671875 42.50984375 -10.076171875H42.3809375V-12.009765625H40.0928515625ZM48.32953125 4.318359375C48.6195703125 4.447265625 49.2426171875 4.576171875 49.983828125 4.576171875C51.917421875 4.576171875 53.1098046875 3.587890625 53.8402734375 1.6650390625L59.0609765625 -12.009765625H56.5258203125L54.108828125 -5.1884765625C53.7328515625 -4.146484375 53.464296875 -3.1044921875 53.1957421875 -2.0732421875C52.9379296875 -3.1044921875 52.690859375 -4.1357421875 52.325625 -5.1884765625L49.9516015625 -12.009765625H47.3949609375L51.960390625 0.0537109375L51.702578125 0.9345703125C51.2621484375 2.4814453125 50.4027734375 2.7822265625 49.1781640625 2.4599609375L48.909609375 2.3955078125ZM71.0978125 0.2470703125C74.0304296875 0.2470703125 76.0499609375 -1.2998046875 76.0499609375 -3.4912109375C76.0499609375 -5.15625 74.9972265625 -6.23046875 72.77359375 -6.7353515625L70.84 -7.1650390625C69.5187109375 -7.4658203125 68.9816015625 -7.9384765625 68.9816015625 -8.7333984375C68.9816015625 -9.6357421875 69.9698828125 -10.291015625 71.2696875 -10.291015625C72.68765625 -10.291015625 73.3644140625 -9.5390625 73.6759375 -8.701171875L75.7921484375 -9.1630859375C75.2765234375 -10.9462890625 73.8478125 -12.16015625 71.248203125 -12.16015625C68.5304296875 -12.16015625 66.5968359375 -10.7314453125 66.5968359375 -8.5830078125C66.5968359375 -6.8642578125 67.6710546875 -5.7685546875 69.9054296875 -5.263671875L71.9249609375 -4.8017578125C73.0636328125 -4.5439453125 73.611484375 -4.0498046875 73.611484375 -3.287109375C73.611484375 -2.3955078125 72.6446875 -1.6650390625 71.119296875 -1.6650390625C69.7228125 -1.6650390625 68.8097265625 -2.2451171875 68.47671875 -3.501953125L66.2530859375 -3.0400390625C66.6827734375 -0.9130859375 68.4874609375 0.2470703125 71.0978125 0.2470703125ZM83.7065625 0.2470703125C86.2739453125 0.2470703125 88.110859375 -1.009765625 88.6801953125 -2.87890625L86.4565625 -3.4052734375C86.0376171875 -2.2880859375 85.0493359375 -1.7080078125 83.728046875 -1.7080078125C81.7622265625 -1.7080078125 80.4301953125 -2.96484375 80.3442578125 -5.28515625H88.8628125V-6.123046875C88.8628125 -10.4521484375 86.24171875 -12.16015625 83.5024609375 -12.16015625C80.14015625 -12.16015625 77.970234375 -9.6142578125 77.970234375 -5.9189453125C77.970234375 -2.19140625 80.161640625 0.2470703125 83.7065625 0.2470703125ZM80.355 -7.046875C80.48390625 -8.7763671875 81.622578125 -10.205078125 83.513203125 -10.205078125C85.3286328125 -10.205078125 86.349140625 -8.9375 86.521015625 -7.046875ZM91.3416796875 0.0H93.7049609375V-7.2939453125C93.7049609375 -8.873046875 94.9080859375 -9.990234375 96.5623828125 -9.990234375C97.0565234375 -9.990234375 97.625859375 -9.904296875 97.797734375 -9.861328125V-12.1171875C97.5506640625 -12.1494140625 97.0994921875 -12.181640625 96.7987109375 -12.181640625C95.391484375 -12.181640625 94.1991015625 -11.38671875 93.758671875 -10.076171875H93.629765625V-12.009765625H91.3416796875ZM103.1769921875 0.0H105.7551171875L110.2883203125 -12.009765625H107.7531640625L105.379140625 -5.1884765625C105.01390625 -4.125 104.75609375 -3.072265625 104.4875390625 -2.01953125C104.218984375 -3.072265625 103.9396875 -4.125 103.574453125 -5.1884765625L101.2004296875 -12.009765625H98.6437890625ZM117.45078125 0.2470703125C120.0181640625 0.2470703125 121.855078125 -1.009765625 122.4244140625 -2.87890625L120.20078125 -3.4052734375C119.7818359375 -2.2880859375 118.7935546875 -1.7080078125 117.472265625 -1.7080078125C115.5064453125 -1.7080078125 114.1744140625 -2.96484375 114.0884765625 -5.28515625H122.60703125V-6.123046875C122.60703125 -10.4521484375 119.9859375 -12.16015625 117.2466796875 -12.16015625C113.884375 -12.16015625 111.714453125 -9.6142578125 111.714453125 -5.9189453125C111.714453125 -2.19140625 113.905859375 0.2470703125 117.45078125 0.2470703125ZM114.09921875 -7.046875C114.228125 -8.7763671875 115.366796875 -10.205078125 117.257421875 -10.205078125C119.0728515625 -10.205078125 120.093359375 -8.9375 120.265234375 -7.046875ZM125.0858984375 0.0H127.4491796875V-7.2939453125C127.4491796875 -8.873046875 128.65230468750002 -9.990234375 130.30660156250002 -9.990234375C130.80074218750002 -9.990234375 131.37007812500002 -9.904296875 131.54195312500002 -9.861328125V-12.1171875C131.29488281250002 -12.1494140625 130.84371093750002 -12.181640625 130.54292968750002 -12.181640625C129.13570312500002 -12.181640625 127.9433203125 -11.38671875 127.502890625 -10.076171875H127.373984375V-12.009765625H125.0858984375ZM135.2346875 0.1611328125C136.115546875 0.1611328125 136.8137890625 -0.537109375 136.8137890625 -1.41796875C136.8137890625 -2.3095703125 136.115546875 -3.0078125 135.2346875 -3.0078125C134.3430859375 -3.0078125 133.64484375 -2.3095703125 133.64484375 -1.41796875C133.64484375 -0.537109375 134.3430859375 0.1611328125 135.2346875 0.1611328125ZM145.98246093749998 0.0H156.12308593749998V-2.10546875H148.43167968749998V-7.0361328125H155.52152343749998V-9.130859375H148.43167968749998V-13.900390625H156.05863281249998V-16.005859375H145.98246093749998ZM162.39394531249997 0.0H164.97207031249997L169.50527343749997 -12.009765625H166.97011718749997L164.59609374999997 -5.1884765625C164.23085937499997 -4.125 163.97304687499997 -3.072265625 163.70449218749997 -2.01953125C163.43593749999997 -3.072265625 163.15664062499997 -4.125 162.79140624999997 -5.1884765625L160.41738281249997 -12.009765625H157.86074218749997ZM176.66773437499995 0.2470703125C179.23511718749995 0.2470703125 181.07203124999995 -1.009765625 181.64136718749995 -2.87890625L179.41773437499995 -3.4052734375C178.99878906249995 -2.2880859375 178.01050781249995 -1.7080078125 176.68921874999995 -1.7080078125C174.72339843749995 -1.7080078125 173.39136718749995 -2.96484375 173.30542968749995 -5.28515625H181.82398437499995V-6.123046875C181.82398437499995 -10.4521484375 179.20289062499995 -12.16015625 176.46363281249995 -12.16015625C173.10132812499995 -12.16015625 170.93140624999995 -9.6142578125 170.93140624999995 -5.9189453125C170.93140624999995 -2.19140625 173.12281249999995 0.2470703125 176.66773437499995 0.2470703125ZM173.31617187499995 -7.046875C173.44507812499995 -8.7763671875 174.58374999999995 -10.205078125 176.47437499999995 -10.205078125C178.28980468749995 -10.205078125 179.31031249999995 -8.9375 179.48218749999995 -7.046875ZM184.30285156249994 0.0H186.66613281249994V-7.2939453125C186.66613281249994 -8.873046875 187.86925781249994 -9.990234375 189.52355468749994 -9.990234375C190.01769531249994 -9.990234375 190.58703124999994 -9.904296875 190.75890624999994 -9.861328125V-12.1171875C190.51183593749994 -12.1494140625 190.06066406249994 -12.181640625 189.75988281249994 -12.181640625C188.35265624999994 -12.181640625 187.16027343749994 -11.38671875 186.71984374999994 -10.076171875H186.59093749999994V-12.009765625H184.30285156249994ZM192.53953124999992 4.318359375C192.82957031249992 4.447265625 193.45261718749992 4.576171875 194.19382812499992 4.576171875C196.12742187499992 4.576171875 197.31980468749992 3.587890625 198.05027343749992 1.6650390625L203.27097656249992 -12.009765625H200.73582031249992L198.31882812499992 -5.1884765625C197.94285156249992 -4.146484375 197.67429687499992 -3.1044921875 197.40574218749992 -2.0732421875C197.14792968749992 -3.1044921875 196.90085937499992 -4.1357421875 196.53562499999992 -5.1884765625L194.16160156249992 -12.009765625H191.60496093749992L196.17039062499992 0.0537109375L195.91257812499992 0.9345703125C195.47214843749992 2.4814453125 194.61277343749992 2.7822265625 193.38816406249992 2.4599609375L193.11960937499992 2.3955078125ZM216.0490234374999 0.2470703125C218.5734374999999 0.2470703125 220.5285156249999 -1.1171875 221.1085937499999 -3.3837890625L218.8742187499999 -3.9208984375C218.5519531249999 -2.62109375 217.5529296874999 -1.7509765625 216.0597656249999 -1.7509765625C213.8898437499999 -1.7509765625 212.8478515624999 -3.65234375 212.8478515624999 -5.9404296875C212.8478515624999 -8.2607421875 213.8898437499999 -10.162109375 216.0597656249999 -10.162109375C217.5314453124999 -10.162109375 218.5089843749999 -9.3134765625 218.8312499999999 -8.078125L221.0763671874999 -8.615234375C220.4855468749999 -10.8388671875 218.5412109374999 -12.16015625 216.0490234374999 -12.16015625C212.6652343749999 -12.16015625 210.4416015624999 -9.6787109375 210.4416015624999 -5.9404296875C210.4416015624999 -2.234375 212.6652343749999 0.2470703125 216.0490234374999 0.2470703125ZM228.63628906249988 0.2470703125C232.02007812499988 0.2470703125 234.25445312499988 -2.234375 234.25445312499988 -5.9404296875C234.25445312499988 -9.6787109375 232.02007812499988 -12.16015625 228.63628906249988 -12.16015625C225.25249999999988 -12.16015625 223.02886718749988 -9.6787109375 223.02886718749988 -5.9404296875C223.02886718749988 -2.234375 225.25249999999988 0.2470703125 228.63628906249988 0.2470703125ZM228.63628906249988 -1.7509765625C226.46636718749988 -1.7509765625 225.43511718749988 -3.6630859375 225.43511718749988 -5.9404296875C225.43511718749988 -8.25 226.46636718749988 -10.162109375 228.63628906249988 -10.162109375C230.82769531249988 -10.162109375 231.85894531249988 -8.2392578125 231.85894531249988 -5.9404296875C231.85894531249988 -3.6630859375 230.82769531249988 -1.7509765625 228.63628906249988 -1.7509765625ZM239.12882812499987 -7.111328125C239.12882812499987 -9.0126953125 240.31046874999987 -10.09765625 241.92179687499987 -10.09765625C243.49015624999987 -10.09765625 244.45695312499987 -9.06640625 244.45695312499987 -7.3369140625V0.0H246.82023437499987V-7.626953125C246.82023437499987 -10.591796875 245.18742187499987 -12.16015625 242.73820312499987 -12.16015625C241.04093749999987 -12.16015625 239.78410156249987 -11.3974609375 239.03214843749987 -9.7001953125L239.02140624999987 -12.009765625H236.76554687499987V0.0H239.12882812499987ZM255.02468749999986 -12.009765625H252.62917968749986V-14.8671875H250.26589843749986V-12.009765625H248.51492187499986V-10.0869140625H250.26589843749986V-3.05078125C250.26589843749986 -1.009765625 251.52273437499986 0.1611328125 253.70339843749986 0.1611328125C254.25124999999986 0.1611328125 254.85281249999986 0.0859375 255.35769531249986 -0.0859375L254.93874999999986 -1.9765625C254.64871093749986 -1.912109375 254.18679687499986 -1.84765625 253.93972656249986 -1.84765625C253.00515624999986 -1.84765625 252.62917968749986 -2.27734375 252.62917968749986 -3.244140625V-10.0869140625H255.02468749999986ZM260.62953124999984 0.2685546875C262.57386718749984 0.2685546875 263.71253906249984 -0.708984375 264.17445312499984 -1.6435546875H264.29261718749984V0.0H266.58070312499984V-7.970703125C266.58070312499984 -11.4404296875 263.81996093749984 -12.16015625 261.88636718749984 -12.16015625C259.74867187499984 -12.16015625 257.72914062499984 -11.322265625 256.91273437499984 -9.173828125L259.13636718749984 -8.59375C259.46937499999984 -9.41015625 260.35023437499984 -10.2373046875 261.91859374999984 -10.2373046875C263.42249999999984 -10.2373046875 264.21742187499984 -9.4638671875 264.21742187499984 -8.1318359375V-8.0673828125C264.21742187499984 -7.21875 263.30433593749984 -7.2294921875 261.18812499999984 -6.982421875C258.92152343749984 -6.724609375 256.56898437499984 -6.123046875 256.56898437499984 -3.39453125C256.56898437499984 -1.03125 258.34144531249984 0.2685546875 260.62953124999984 0.2685546875ZM261.15589843749984 -1.6328125C259.83460937499984 -1.6328125 258.88929687499984 -2.2236328125 258.88929687499984 -3.3623046875C258.88929687499984 -4.59765625 259.98499999999984 -5.048828125 261.31703124999984 -5.2314453125C262.04749999999984 -5.328125 263.87367187499984 -5.521484375 264.22816406249984 -5.865234375V-4.3291015625C264.22816406249984 -2.921875 263.07874999999984 -1.6328125 261.15589843749984 -1.6328125ZM269.65039062499983 0.0H272.01367187499983V-12.009765625H269.65039062499983ZM270.84277343749983 -13.8466796875C271.65917968749983 -13.8466796875 272.33593749999983 -14.4697265625 272.33593749999983 -15.2431640625C272.33593749999983 -16.02734375 271.65917968749983 -16.650390625 270.84277343749983 -16.650390625C270.02636718749983 -16.650390625 269.34960937499983 -16.02734375 269.34960937499983 -15.2431640625C269.34960937499983 -14.4697265625 270.02636718749983 -13.8466796875 270.84277343749983 -13.8466796875ZM277.4466406249998 -7.111328125C277.4466406249998 -9.0126953125 278.6282812499998 -10.09765625 280.2396093749998 -10.09765625C281.8079687499998 -10.09765625 282.7747656249998 -9.06640625 282.7747656249998 -7.3369140625V0.0H285.1380468749998V-7.626953125C285.1380468749998 -10.591796875 283.5052343749998 -12.16015625 281.0560156249998 -12.16015625C279.3587499999998 -12.16015625 278.1019140624998 -11.3974609375 277.3499609374998 -9.7001953125L277.3392187499998 -12.009765625H275.0833593749998V0.0H277.4466406249998ZM293.3854687499998 0.2470703125C295.9528515624998 0.2470703125 297.7897656249998 -1.009765625 298.3591015624998 -2.87890625L296.1354687499998 -3.4052734375C295.7165234374998 -2.2880859375 294.7282421874998 -1.7080078125 293.4069531249998 -1.7080078125C291.4411328124998 -1.7080078125 290.1091015624998 -2.96484375 290.0231640624998 -5.28515625H298.5417187499998V-6.123046875C298.5417187499998 -10.4521484375 295.9206249999998 -12.16015625 293.1813671874998 -12.16015625C289.8190624999998 -12.16015625 287.6491406249998 -9.6142578125 287.6491406249998 -5.9189453125C287.6491406249998 -2.19140625 289.8405468749998 0.2470703125 293.3854687499998 0.2470703125ZM290.0339062499998 -7.046875C290.1628124999998 -8.7763671875 291.3014843749998 -10.205078125 293.1921093749998 -10.205078125C295.0075390624998 -10.205078125 296.0280468749998 -8.9375 296.1999218749998 -7.046875ZM301.0205859374998 0.0H303.3838671874998V-7.2939453125C303.3838671874998 -8.873046875 304.5869921874998 -9.990234375 306.2412890624998 -9.990234375C306.7354296874998 -9.990234375 307.3047656249998 -9.904296875 307.4766406249998 -9.861328125V-12.1171875C307.2295703124998 -12.1494140625 306.7783984374998 -12.181640625 306.4776171874998 -12.181640625C305.0703906249998 -12.181640625 303.8780078124998 -11.38671875 303.4375781249998 -10.076171875H303.3086718749998V-12.009765625H301.0205859374998ZM311.1693749999998 0.1611328125C312.0502343749998 0.1611328125 312.7484765624998 -0.537109375 312.7484765624998 -1.41796875C312.7484765624998 -2.3095703125 312.0502343749998 -3.0078125 311.1693749999998 -3.0078125C310.2777734374998 -3.0078125 309.5795312499998 -2.3095703125 309.5795312499998 -1.41796875C309.5795312499998 -0.537109375 310.2777734374998 0.1611328125 311.1693749999998 0.1611328125ZM328.58804687499975 0.21484375C332.73453124999975 0.21484375 335.79605468749975 -2.87890625 335.79605468749975 -7.9921875C335.79605468749975 -13.126953125 332.73453124999975 -16.220703125 328.58804687499975 -16.220703125C324.43082031249975 -16.220703125 321.35855468749975 -13.126953125 321.35855468749975 -7.9921875C321.35855468749975 -2.87890625 324.43082031249975 0.21484375 328.58804687499975 0.21484375ZM328.58804687499975 -2.01953125C325.83804687499975 -2.01953125 323.78628906249975 -4.125 323.78628906249975 -7.9921875C323.78628906249975 -11.8701171875 325.83804687499975 -13.986328125 328.58804687499975 -13.986328125C331.31656249999975 -13.986328125 333.36832031249975 -11.880859375 333.36832031249975 -7.9921875C333.36832031249975 -4.125 331.31656249999975 -2.01953125 328.58804687499975 -2.01953125ZM340.85304687499973 -7.111328125C340.85304687499973 -9.0126953125 342.03468749999973 -10.09765625 343.64601562499973 -10.09765625C345.21437499999973 -10.09765625 346.18117187499973 -9.06640625 346.18117187499973 -7.3369140625V0.0H348.54445312499973V-7.626953125C348.54445312499973 -10.591796875 346.91164062499973 -12.16015625 344.46242187499973 -12.16015625C342.76515624999973 -12.16015625 341.50832031249973 -11.3974609375 340.75636718749973 -9.7001953125L340.74562499999973 -12.009765625H338.48976562499973V0.0H340.85304687499973ZM356.7918749999997 0.2470703125C359.3592578124997 0.2470703125 361.1961718749997 -1.009765625 361.7655078124997 -2.87890625L359.5418749999997 -3.4052734375C359.1229296874997 -2.2880859375 358.1346484374997 -1.7080078125 356.8133593749997 -1.7080078125C354.8475390624997 -1.7080078125 353.5155078124997 -2.96484375 353.4295703124997 -5.28515625H361.9481249999997V-6.123046875C361.9481249999997 -10.4521484375 359.3270312499997 -12.16015625 356.5877734374997 -12.16015625C353.2254687499997 -12.16015625 351.0555468749997 -9.6142578125 351.0555468749997 -5.9189453125C351.0555468749997 -2.19140625 353.2469531249997 0.2470703125 356.7918749999997 0.2470703125ZM353.4403124999997 -7.046875C353.5692187499997 -8.7763671875 354.7078906249997 -10.205078125 356.5985156249997 -10.205078125C358.4139453124997 -10.205078125 359.4344531249997 -8.9375 359.6063281249997 -7.046875ZM374.6509765624997 0.236328125C376.8208984374997 0.236328125 377.6910156249997 -1.1171875 378.1099609374997 -1.8798828125H378.3033203124997V0.0H380.6021484374997V-16.005859375H378.2388671874997V-10.0546875H378.1099609374997C377.7017578124997 -10.7958984375 376.8853515624997 -12.16015625 374.6509765624997 -12.16015625C371.7613281249997 -12.16015625 369.6236328124997 -9.8828125 369.6236328124997 -5.97265625C369.6236328124997 -2.0947265625 371.7291015624997 0.236328125 374.6509765624997 0.236328125ZM375.1666015624997 -1.7724609375C373.1148437499997 -1.7724609375 372.0406249999997 -3.609375 372.0406249999997 -5.994140625C372.0406249999997 -8.357421875 373.0826171874997 -10.1513671875 375.1666015624997 -10.1513671875C377.1968749999997 -10.1513671875 378.2818359374997 -8.486328125 378.2818359374997 -5.994140625C378.2818359374997 -3.4912109375 377.1753906249997 -1.7724609375 375.1666015624997 -1.7724609375ZM387.0341406249997 0.2685546875C388.9784765624997 0.2685546875 390.1171484374997 -0.708984375 390.5790624999997 -1.6435546875H390.6972265624997V0.0H392.9853124999997V-7.970703125C392.9853124999997 -11.4404296875 390.2245703124997 -12.16015625 388.2909765624997 -12.16015625C386.1532812499997 -12.16015625 384.1337499999997 -11.322265625 383.3173437499997 -9.173828125L385.5409765624997 -8.59375C385.8739843749997 -9.41015625 386.7548437499997 -10.2373046875 388.3232031249997 -10.2373046875C389.8271093749997 -10.2373046875 390.6220312499997 -9.4638671875 390.6220312499997 -8.1318359375V-8.0673828125C390.6220312499997 -7.21875 389.7089453124997 -7.2294921875 387.5927343749997 -6.982421875C385.3261328124997 -6.724609375 382.9735937499997 -6.123046875 382.9735937499997 -3.39453125C382.9735937499997 -1.03125 384.7460546874997 0.2685546875 387.0341406249997 0.2685546875ZM387.5605078124997 -1.6328125C386.2392187499997 -1.6328125 385.2939062499997 -2.2236328125 385.2939062499997 -3.3623046875C385.2939062499997 -4.59765625 386.3896093749997 -5.048828125 387.7216406249997 -5.2314453125C388.4521093749997 -5.328125 390.2782812499997 -5.521484375 390.6327734374997 -5.865234375V-4.3291015625C390.6327734374997 -2.921875 389.4833593749997 -1.6328125 387.5605078124997 -1.6328125ZM400.36261718749967 0.2470703125C403.29523437499967 0.2470703125 405.31476562499967 -1.2998046875 405.31476562499967 -3.4912109375C405.31476562499967 -5.15625 404.26203124999967 -6.23046875 402.03839843749967 -6.7353515625L400.10480468749967 -7.1650390625C398.78351562499967 -7.4658203125 398.24640624999967 -7.9384765625 398.24640624999967 -8.7333984375C398.24640624999967 -9.6357421875 399.23468749999967 -10.291015625 400.53449218749967 -10.291015625C401.95246093749967 -10.291015625 402.62921874999967 -9.5390625 402.94074218749967 -8.701171875L405.05695312499967 -9.1630859375C404.54132812499967 -10.9462890625 403.11261718749967 -12.16015625 400.51300781249967 -12.16015625C397.79523437499967 -12.16015625 395.86164062499967 -10.7314453125 395.86164062499967 -8.5830078125C395.86164062499967 -6.8642578125 396.93585937499967 -5.7685546875 399.17023437499967 -5.263671875L401.18976562499967 -4.8017578125C402.32843749999967 -4.5439453125 402.87628906249967 -4.0498046875 402.87628906249967 -3.287109375C402.87628906249967 -2.3955078125 401.90949218749967 -1.6650390625 400.38410156249967 -1.6650390625C398.98761718749967 -1.6650390625 398.07453124999967 -2.2451171875 397.74152343749967 -3.501953125L395.51789062499967 -3.0400390625C395.94757812499967 -0.9130859375 397.75226562499967 0.2470703125 400.36261718749967 0.2470703125ZM410.15691406249965 -7.111328125C410.15691406249965 -9.0126953125 411.33855468749965 -10.09765625 412.94988281249965 -10.09765625C414.51824218749965 -10.09765625 415.48503906249965 -9.06640625 415.48503906249965 -7.3369140625V0.0H417.85906249999965V-7.626953125C417.85906249999965 -10.591796875 416.21550781249965 -12.16015625 413.76628906249965 -12.16015625C412.12273437499965 -12.16015625 410.88738281249965 -11.4404296875 410.13542968749965 -9.8505859375V-16.005859375H407.79363281249965V0.0H410.15691406249965ZM426.87992187499964 0.236328125C429.80179687499964 0.236328125 431.89652343749964 -2.0947265625 431.89652343749964 -5.97265625C431.89652343749964 -9.8828125 429.75882812499964 -12.16015625 426.87992187499964 -12.16015625C424.63480468749964 -12.16015625 423.82914062499964 -10.7958984375 423.41019531249964 -10.0546875H423.28128906249964V-16.005859375H420.91800781249964V0.0H423.21683593749964V-1.8798828125H423.41019531249964C423.82914062499964 -1.1171875 424.69925781249964 0.236328125 426.87992187499964 0.236328125ZM426.35355468749964 -1.7724609375C424.35550781249964 -1.7724609375 423.23832031249964 -3.4912109375 423.23832031249964 -5.994140625C423.23832031249964 -8.486328125 424.32328124999964 -10.1513671875 426.35355468749964 -10.1513671875C428.43753906249964 -10.1513671875 429.47953124999964 -8.357421875 429.47953124999964 -5.994140625C429.47953124999964 -3.609375 428.40531249999964 -1.7724609375 426.35355468749964 -1.7724609375ZM439.4564453124996 0.2470703125C442.8402343749996 0.2470703125 445.0746093749996 -2.234375 445.0746093749996 -5.9404296875C445.0746093749996 -9.6787109375 442.8402343749996 -12.16015625 439.4564453124996 -12.16015625C436.0726562499996 -12.16015625 433.8490234374996 -9.6787109375 433.8490234374996 -5.9404296875C433.8490234374996 -2.234375 436.0726562499996 0.2470703125 439.4564453124996 0.2470703125ZM439.4564453124996 -1.7509765625C437.2865234374996 -1.7509765625 436.2552734374996 -3.6630859375 436.2552734374996 -5.9404296875C436.2552734374996 -8.25 437.2865234374996 -10.162109375 439.4564453124996 -10.162109375C441.6478515624996 -10.162109375 442.6791015624996 -8.2392578125 442.6791015624996 -5.9404296875C442.6791015624996 -3.6630859375 441.6478515624996 -1.7509765625 439.4564453124996 -1.7509765625ZM450.9480078124996 0.2685546875C452.8923437499996 0.2685546875 454.0310156249996 -0.708984375 454.4929296874996 -1.6435546875H454.6110937499996V0.0H456.8991796874996V-7.970703125C456.8991796874996 -11.4404296875 454.1384374999996 -12.16015625 452.2048437499996 -12.16015625C450.0671484374996 -12.16015625 448.0476171874996 -11.322265625 447.2312109374996 -9.173828125L449.4548437499996 -8.59375C449.7878515624996 -9.41015625 450.6687109374996 -10.2373046875 452.2370703124996 -10.2373046875C453.7409765624996 -10.2373046875 454.5358984374996 -9.4638671875 454.5358984374996 -8.1318359375V-8.0673828125C454.5358984374996 -7.21875 453.6228124999996 -7.2294921875 451.5066015624996 -6.982421875C449.2399999999996 -6.724609375 446.8874609374996 -6.123046875 446.8874609374996 -3.39453125C446.8874609374996 -1.03125 448.6599218749996 0.2685546875 450.9480078124996 0.2685546875ZM451.4743749999996 -1.6328125C450.1530859374996 -1.6328125 449.2077734374996 -2.2236328125 449.2077734374996 -3.3623046875C449.2077734374996 -4.59765625 450.3034765624996 -5.048828125 451.6355078124996 -5.2314453125C452.3659765624996 -5.328125 454.1921484374996 -5.521484375 454.5466406249996 -5.865234375V-4.3291015625C454.5466406249996 -2.921875 453.3972265624996 -1.6328125 451.4743749999996 -1.6328125ZM459.9688671874996 0.0H462.3321484374996V-7.2939453125C462.3321484374996 -8.873046875 463.5352734374996 -9.990234375 465.1895703124996 -9.990234375C465.6837109374996 -9.990234375 466.2530468749996 -9.904296875 466.4249218749996 -9.861328125V-12.1171875C466.1778515624996 -12.1494140625 465.7266796874996 -12.181640625 465.4258984374996 -12.181640625C464.0186718749996 -12.181640625 462.8262890624996 -11.38671875 462.3858593749996 -10.076171875H462.2569531249996V-12.009765625H459.9688671874996ZM472.8354296874996 0.236328125C475.0053515624996 0.236328125 475.8754687499996 -1.1171875 476.2944140624996 -1.8798828125H476.4877734374996V0.0H478.7866015624996V-16.005859375H476.4233203124996V-10.0546875H476.2944140624996C475.8862109374996 -10.7958984375 475.0698046874996 -12.16015625 472.8354296874996 -12.16015625C469.9457812499996 -12.16015625 467.8080859374996 -9.8828125 467.8080859374996 -5.97265625C467.8080859374996 -2.0947265625 469.9135546874996 0.236328125 472.8354296874996 0.236328125ZM473.3510546874996 -1.7724609375C471.2992968749996 -1.7724609375 470.2250781249996 -3.609375 470.2250781249996 -5.994140625C470.2250781249996 -8.357421875 471.2670703124996 -10.1513671875 473.3510546874996 -10.1513671875C475.3813281249996 -10.1513671875 476.4662890624996 -8.486328125 476.4662890624996 -5.994140625C476.4662890624996 -3.4912109375 475.3598437499996 -1.7724609375 473.3510546874996 -1.7724609375ZM483.60726562499957 0.1611328125C484.48812499999957 0.1611328125 485.18636718749957 -0.537109375 485.18636718749957 -1.41796875C485.18636718749957 -2.3095703125 484.48812499999957 -3.0078125 483.60726562499957 -3.0078125C482.71566406249957 -3.0078125 482.01742187499957 -2.3095703125 482.01742187499957 -1.41796875C482.01742187499957 -0.537109375 482.71566406249957 0.1611328125 483.60726562499957 0.1611328125Z" fill="#9A9890"/>
<path d="M886 40V280M1174 40V280" stroke="#5A5952" stroke-width="2.5"/><rect x="900" y="58" width="260" height="36" fill="none" stroke="#5A5952" stroke-width="2.5"/><circle cx="914" cy="76" r="3" fill="#5A5952"/><circle cx="1146" cy="76" r="3" fill="#5A5952"/><rect x="1050" y="71" width="3" height="10" fill="#5A5952"/><rect x="1059" y="71" width="3" height="10" fill="#5A5952"/><rect x="1068" y="71" width="3" height="10" fill="#5A5952"/><rect x="1077" y="71" width="3" height="10" fill="#5A5952"/><rect x="900" y="100" width="260" height="36" fill="none" stroke="#5A5952" stroke-width="2.5"/><circle cx="914" cy="118" r="3" fill="#5A5952"/><circle cx="1146" cy="118" r="3" fill="#5A5952"/><rect x="1050" y="113" width="3" height="10" fill="#5A5952"/><rect x="1059" y="113" width="3" height="10" fill="#5A5952"/><rect x="1068" y="113" width="3" height="10" fill="#5A5952"/><rect x="1077" y="113" width="3" height="10" fill="#5A5952"/><rect x="946" y="142" width="260" height="36" fill="#FF5A1F" stroke="#FF5A1F" stroke-width="2.5"/><circle cx="960" cy="160" r="3" fill="#0E0E11"/><circle cx="1192" cy="160" r="3" fill="#0E0E11"/><rect x="1142" y="157" width="30" height="6" fill="#0E0E11"/><rect x="900" y="184" width="260" height="36" fill="none" stroke="#5A5952" stroke-width="2.5"/><circle cx="914" cy="202" r="3" fill="#5A5952"/><circle cx="1146" cy="202" r="3" fill="#5A5952"/><rect x="1050" y="197" width="3" height="10" fill="#5A5952"/><rect x="1059" y="197" width="3" height="10" fill="#5A5952"/><rect x="1068" y="197" width="3" height="10" fill="#5A5952"/><rect x="1077" y="197" width="3" height="10" fill="#5A5952"/><rect x="900" y="226" width="260" height="36" fill="none" stroke="#5A5952" stroke-width="2.5"/><circle cx="914" cy="244" r="3" fill="#5A5952"/><circle cx="1146" cy="244" r="3" fill="#5A5952"/><rect x="1050" y="239" width="3" height="10" fill="#5A5952"/><rect x="1059" y="239" width="3" height="10" fill="#5A5952"/><rect x="1068" y="239" width="3" height="10" fill="#5A5952"/><rect x="1077" y="239" width="3" height="10" fill="#5A5952"/>
</svg>
diff --git a/src/agent/collector.py b/src/agent/collector.py
index 4af326d..c45bdc8 100644
--- a/src/agent/collector.py
+++ b/src/agent/collector.py
@@ -416,17 +416,30 @@ class _Timex(ctypes.Structure):
_TIME_ERROR = 5
+_STA_NANO = 0x2000
+
+
+def _read_clock() -> tuple[int, float] | None:
+ """(kernel clock state, offset from the time source in milliseconds) from a read-only adjtimex, or None."""
+ try:
+ libc = ctypes.CDLL(ctypes.util.find_library("c") or "libc.so.6", use_errno=True)
+ timex = _Timex()
+ state = libc.adjtimex(ctypes.byref(timex))
+ except (OSError, AttributeError):
+ return None
+ if state < 0:
+ return None
+ # The offset is in nanoseconds when the kernel says so, microseconds otherwise.
+ return state, timex.offset / (1_000_000 if timex.status & _STA_NANO else 1_000)
+
+
def _ntp_synced() -> bool | None:
"""Whether the kernel clock is disciplined by a time service; None when it can't be read."""
# A read-only adjtimex (modes=0) covers chrony, ntpd and timesyncd alike. Docker's default
# seccomp profile may refuse it, in which case timesyncd's marker file is the fallback.
- try:
- libc = ctypes.CDLL(ctypes.util.find_library("c") or "libc.so.6", use_errno=True)
- state = libc.adjtimex(ctypes.byref(_Timex()))
- if state >= 0:
- return state != _TIME_ERROR
- except (OSError, AttributeError):
- pass
+ clock = _read_clock()
+ if clock is not None:
+ return clock[0] != _TIME_ERROR
if (HOST_ROOT / "run/systemd/timesyncd/synchronized").exists():
return True
return None
@@ -489,6 +502,293 @@ def collect_system() -> dict[str, Any]:
}
+COLLECTOR_VERSION = "0.9.2"
+MAX_INTERFACES = 16
+MAX_TEMPERATURES = 8
+_KERNEL_IMAGE = re.compile(r"vmlinuz-(\d[\w.+~-]*)")
+_UPDATES_PENDING = re.compile(r"(\d+) (?:updates?|packages?) can be (?:applied|updated|installed)")
+_UPDATES_SECURITY = re.compile(r"(\d+) (?:of these updates|additional security updates?|updates?) (?:is a|are|can be applied with)[^\n]*security", re.IGNORECASE)
+# Counters from the previous check-in, per interface: (received bytes, sent bytes, monotonic time).
+_interface_previous: dict[str, tuple[int, int, float]] = {}
+
+
+def _version_key(version: str) -> list[tuple[int, Any]]:
+ """Sorts 6.8.0-9 before 6.8.0-85: digit runs compare as numbers."""
+ return [(0, int(part)) if part.isdigit() else (1, part) for part in re.split(r"(\d+)", version) if part]
+
+
+def _mtime(relative: str) -> float | None:
+ try:
+ return (HOST_ROOT / relative).stat().st_mtime
+ except OSError:
+ return None
+
+
+def _cpu_model() -> str | None:
+ for line in (_read_text(HOST_PROC / "cpuinfo") or "").splitlines():
+ if line.lower().startswith(("model name", "hardware")) and ":" in line:
+ return " ".join(line.split(":", 1)[1].split())[:128] or None
+ return None
+
+
+def _swap_total_gb() -> float | None:
+ for line in (_read_text(HOST_PROC / "meminfo") or "").splitlines():
+ if line.startswith("SwapTotal:"):
+ return round(int(line.split()[1]) * 1024 / GiB, 2)
+ return None
+
+
+def _timezone() -> str | None:
+ name = _read_text(HOST_ROOT / "etc/timezone")
+ if not name:
+ try:
+ name = os.readlink(HOST_ROOT / "etc/localtime").partition("zoneinfo/")[2]
+ except OSError:
+ name = None
+ return name[:64] if name else None
+
+
+def _time_service() -> str | None:
+ for service, marker in (("chrony", "run/chrony"), ("systemd-timesyncd", "run/systemd/timesync"), ("ntpd", "var/lib/ntp"), ("chrony", "var/lib/chrony")):
+ if (HOST_ROOT / marker).exists():
+ return service
+ return None
+
+
+def collect_updates(kernel: str | None, reboot_required: bool | None) -> dict[str, Any]:
+ """Pending package updates, from the files apt leaves behind (Debian and Ubuntu); {} elsewhere.
+
+ Nothing is run on the host, so the numbers are as old as apt's last own check.
+ """
+ if not (HOST_ROOT / "etc/debian_version").exists():
+ return {}
+ info: dict[str, Any] = {"updates_manager": "apt", "updates_checked_at": _mtime("var/lib/apt/periodic/update-success-stamp"), "updates_applied_at": _mtime("var/log/apt/history.log")}
+ summary = _read_regular_file(HOST_ROOT / "var/lib/update-notifier/updates-available", 16 * 1024)
+ if summary is not None:
+ text = summary.decode("utf-8", errors="replace")
+ pending, security = _UPDATES_PENDING.search(text), _UPDATES_SECURITY.search(text)
+ info["updates_pending"] = int(pending.group(1)) if pending else 0
+ info["updates_security"] = int(security.group(1)) if security else 0
+ settings = _read_regular_file(HOST_ROOT / "etc/apt/apt.conf.d/20auto-upgrades", 16 * 1024)
+ if settings is not None:
+ info["auto_updates"] = bool(re.search(r'Unattended-Upgrade\s+"1"', settings.decode("utf-8", errors="replace")))
+ if reboot_required and kernel:
+ try:
+ installed = [match.group(1) for entry in (HOST_ROOT / "boot").iterdir() if (match := _KERNEL_IMAGE.fullmatch(entry.name))]
+ except OSError:
+ installed = []
+ newest = max(installed, key=_version_key, default=None)
+ if newest and _version_key(newest) > _version_key(kernel):
+ info["reboot_kernel"] = newest[:64]
+ return info
+
+
+def collect_temperatures() -> list[dict[str, Any]]:
+ """Hardware temperature sensors the kernel exposes in sysfs; [] when sysfs isn't visible or has none."""
+ found: list[dict[str, Any]] = []
+ try:
+ sensors = sorted((HOST_ROOT / "sys/class/hwmon").iterdir())
+ except OSError:
+ return found
+ for sensor in sensors:
+ label, reading = _read_text(sensor / "name"), _read_text(sensor / "temp1_input")
+ if label and reading and reading.lstrip("-").isdigit() and -50_000 <= int(reading) <= 200_000:
+ found.append({"label": label[:32], "celsius": round(int(reading) / 1000, 1)})
+ return found[:MAX_TEMPERATURES]
+
+
+def _interface_networks() -> dict[str, str]:
+ """The directly connected IPv4 network of each interface, from the host's routing table."""
+ networks: dict[str, str] = {}
+ for line in (_read_net_table("route") or [])[1:]:
+ fields = line.split()
+ if len(fields) < 8 or fields[2] != "00000000" or fields[1] == "00000000":
+ continue # routes through a gateway and the default route say nothing about the interface's own network
+ try:
+ destination = socket.inet_ntoa(bytes.fromhex(fields[1])[::-1])
+ prefix = bin(int.from_bytes(bytes.fromhex(fields[7])[::-1], "big")).count("1")
+ except (ValueError, OSError):
+ continue
+ networks.setdefault(fields[0], f"{destination}/{prefix}")
+ return networks
+
+
+def collect_interfaces(now: float | None = None) -> list[dict[str, Any]]:
+ """The host's network interfaces with their current traffic; veth pairs (one per container) are left out."""
+ lines = _read_net_table("dev")
+ if lines is None:
+ return []
+ now = time.monotonic() if now is None else now
+ networks = _interface_networks()
+ interfaces, seen = [], set()
+ for line in lines[2:]:
+ name, _, raw = line.partition(":")
+ name = name.strip()
+ if not raw or name == "lo" or name.startswith("veth"):
+ continue
+ try:
+ fields = [int(value) for value in raw.split()]
+ except ValueError:
+ continue
+ if len(fields) < 9:
+ continue
+ seen.add(name)
+ received, sent = fields[0], fields[8]
+ entry: dict[str, Any] = {"name": name[:16], "network": networks.get(name)}
+ previous = _interface_previous.get(name)
+ if previous and now > previous[2] and received >= previous[0] and sent >= previous[1]:
+ elapsed = now - previous[2]
+ entry["rx_mbps"] = round((received - previous[0]) / MiB / elapsed, 3)
+ entry["tx_mbps"] = round((sent - previous[1]) / MiB / elapsed, 3)
+ speed = _read_text(HOST_ROOT / "sys/class/net" / name / "speed")
+ if speed and speed.isdigit() and int(speed) > 0:
+ entry["speed_mbit"] = int(speed)
+ _interface_previous[name] = (received, sent, now)
+ # Interfaces that carry an address or have ever moved data; idle bridges without either are noise.
+ if entry["network"] or received or sent:
+ interfaces.append(entry)
+ for stale in set(_interface_previous) - seen:
+ del _interface_previous[stale]
+ interfaces.sort(key=lambda item: (item["network"] is None, item["name"]))
+ return interfaces[:MAX_INTERFACES]
+
+
+_PORT_LIST = r"\{?\s*((?:\d{1,5}(?:\s*[-:]\s*\d{1,5})?\s*,?\s*)+)\}?"
+_NFT_ACCEPT = re.compile(rf"\b(tcp|udp)\s+dport\s+{_PORT_LIST}[^\n;]*\baccept\b")
+_IPTABLES_ACCEPT = re.compile(r"^-A \S*(?:input|INPUT)\S*\s.*-p (tcp|udp)\b.*--dports? ([\d,:]+).*-j ACCEPT", re.MULTILINE)
+
+
+def _ports_in(spec: str) -> set[int]:
+ ports: set[int] = set()
+ for part in re.split(r"[,\s]+", spec.strip()):
+ low, _, high = part.replace(":", "-").partition("-")
+ if low.isdigit() and (not high or high.isdigit()):
+ first, last = int(low), int(high or low)
+ if 1 <= first <= last <= 65535 and last - first <= 4096:
+ ports.update(range(first, last + 1))
+ return ports
+
+
+def firewall_allowed(listeners: list[dict[str, Any]] | None) -> list[dict[str, Any]]:
+ """Which of the listening ports a firewall configuration file explicitly accepts, and in which file.
+
+ Only ports the host is already reported to listen on are named, so this adds nothing about the rest of the
+ ruleset. Like the fingerprint, it reads configuration, not the live rules.
+ """
+ wanted = {(item["proto"], item["port"]) for item in listeners or []}
+ allowed: dict[tuple[str, int], str] = {}
+ for name, relative in FIREWALL_FILES:
+ data = _read_regular_file(HOST_ROOT / relative, MAX_FIREWALL_FILE_BYTES) if name != "ufw-conf" else None
+ if data is None:
+ continue
+ text = data.decode("utf-8", errors="replace")
+ for proto, spec in (_NFT_ACCEPT if name == "nftables" else _IPTABLES_ACCEPT).findall(text):
+ for port in _ports_in(spec):
+ if (proto, port) in wanted:
+ allowed.setdefault((proto, port), name)
+ return [{"proto": proto, "port": port, "file": name} for (proto, port), name in sorted(allowed.items())]
+
+
+def disk_io_errors() -> int | None:
+ """I/O errors the kernel has counted on SCSI and SATA disks since boot, or None when no disk exposes a counter
+ (NVMe drives don't)."""
+ total, found = 0, False
+ try:
+ disks = list((HOST_ROOT / "sys/block").iterdir())
+ except OSError:
+ return None
+ for disk in disks:
+ raw = _read_text(disk / "device/ioerr_cnt")
+ if raw:
+ try:
+ total += int(raw, 16)
+ found = True
+ except ValueError:
+ continue
+ return total if found else None
+
+
+PORT_OWNERS_MAX_AGE_SECONDS = 300
+MAX_PORT_OWNERS = 512
+
+
+def _port_owners_path() -> Path:
+ return Path(os.getenv("HOMELAB_PORT_OWNERS_FILE", "/helper/ports.json"))
+
+
+def collect_port_owners(path: Path | None = None, now: float | None = None) -> list[dict[str, Any]] | None:
+ """Which process listens on each port, from the optional port-owners helper; None when it isn't running.
+
+ Read like the system helper's file: no symlinks, a size cap, and nothing older than a few minutes.
+ """
+ path = path or _port_owners_path()
+ try:
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
+ except OSError:
+ return None
+ try:
+ raw = os.read(fd, HELPER_FILE_MAX_BYTES + 1)
+ except OSError:
+ return None
+ finally:
+ os.close(fd)
+ try:
+ data = json.loads(raw) if len(raw) <= HELPER_FILE_MAX_BYTES else None
+ generated = datetime.fromisoformat(data["generated_at"]).timestamp()
+ except (ValueError, KeyError, TypeError):
+ return None
+ if abs((now if now is not None else time.time()) - generated) > PORT_OWNERS_MAX_AGE_SECONDS or not isinstance(data.get("listeners"), list):
+ return None
+ owners = []
+ for item in data["listeners"][:MAX_PORT_OWNERS]:
+ if isinstance(item, dict) and item.get("proto") in ("tcp", "udp") and isinstance(item.get("port"), int) and isinstance(item.get("process"), str):
+ owners.append({"proto": item["proto"], "port": item["port"], "process": item["process"][:64]})
+ return owners
+
+
+def collect_system_info(listeners: list[dict[str, Any]] | None, reboot_required: bool | None, mounts: list[dict[str, Any]] | None = None) -> dict[str, Any]:
+ """Facts about the machine for the dashboard's System and Network tabs. Everything is read from /proc, sysfs and
+ a few world-readable files; what can't be read is simply left out."""
+ kernel = _read_text(HOST_PROC / "sys/kernel/osrelease")
+ clock = _read_clock()
+ reported = {mount["mount"] for mount in mounts or []}
+ info: dict[str, Any] = {
+ "kernel": kernel[:64] if kernel else None,
+ "arch": platform.machine()[:16] or None,
+ "cpu_model": _cpu_model(),
+ "swap_total_gb": _swap_total_gb(),
+ "timezone": _timezone(),
+ "time_service": _time_service(),
+ "clock_offset_ms": round(clock[1], 3) if clock else None,
+ "collector_version": COLLECTOR_VERSION,
+ "docker_version": _docker_version["value"],
+ "helper_installed": _helper_path().exists(),
+ "temperatures": collect_temperatures(),
+ "interfaces": collect_interfaces(),
+ "mount_devices": {mount[:255]: source.rsplit("/", 1)[-1][:64] for source, mount, _ in _mount_entries() if source.startswith("/dev/") and mount in reported},
+ "firewall_allowed": firewall_allowed(listeners),
+ "docker_disk": _docker_disk["value"],
+ "disk_io_errors": disk_io_errors(),
+ "listener_owners": collect_port_owners(),
+ **collect_updates(kernel, reboot_required),
+ }
+ return {key: value for key, value in info.items() if value is not None}
+
+
+def registration_details() -> dict[str, Any]:
+ """What a collector found on its machine, shown next to the Add button before anyone approves it."""
+ socket_path = os.getenv("HOMELAB_DOCKER_HOST") or os.getenv("DOCKER_SOCKET_PATH", "/var/run/docker.sock")
+ try:
+ containers = len(_docker_request(socket_path, "/containers/json?all=1")) if Path(socket_path).exists() else None
+ except (OSError, ValueError, TypeError, http.client.HTTPException):
+ containers = None
+ return {
+ "cpu_cores": _host_cpu_cores(), "containers": containers, "mounts": len(collect_mounts()),
+ "helper_installed": _helper_path().exists(),
+ "dashboard_host": os.getenv("HOMELAB_DASHBOARD_HOST", "").lower() in {"1", "true", "yes"},
+ }
+
+
def collect_host() -> tuple[dict[str, Any], dict[str, Any]]:
before_total, before_idle = _cpu_times()
time.sleep(0.15)
@@ -529,6 +829,7 @@ def collect_host() -> tuple[dict[str, Any], dict[str, Any]]:
"os_info": _host_os_info(),
"cpu_cores": _host_cpu_cores(),
"total_ram_gb": round(_memory_total_gb(), 3),
+ "system": collect_system_info(host["listeners"], host.get("reboot_required"), host["mounts"]),
}
# Set only on the collector in the dashboard's own compose stack; the dashboard's top charts follow it.
if os.getenv("HOMELAB_DASHBOARD_HOST", "").lower() in {"1", "true", "yes"}:
@@ -659,11 +960,14 @@ def collect_containers(socket_path: str | None = None, info: dict[str, Any] | No
"healthcheck_status": health,
"started_at": state.get("StartedAt") if status == "running" else None,
"ports": _format_ports((detail.get("NetworkSettings") or {}).get("Ports")),
+ "project": _compose_project(detail),
+ "volumes": _format_volumes(detail.get("Mounts")),
"exit_code": exit_code if stopped and isinstance(exit_code, int) and not isinstance(exit_code, bool) and -1 <= exit_code <= 65535 else None,
"oom_killed": state.get("OOMKilled") if stopped and isinstance(state.get("OOMKilled"), bool) else None,
"finished_at": _docker_time(state.get("FinishedAt")) if stopped else None,
"image_id": image_id if isinstance(image_id, str) and _IMAGE_ID.fullmatch(image_id) else None,
**usage_stats,
+ **({"swap_mb": swap} if status == "running" and (swap := container_swap_mb(container_id)) is not None else {}),
})
if containers and not result:
# Listing worked but nothing could be inspected: the daemon is failing, not empty.
@@ -671,6 +975,48 @@ def collect_containers(socket_path: str | None = None, info: dict[str, Any] | No
return result
+# The Docker daemon's version, asked for rarely: it only changes when Docker is upgraded.
+_docker_version: dict[str, Any] = {"value": None, "countdown": 0}
+DOCKER_VERSION_EVERY = 120
+
+
+def _remember_docker_version(socket_path: str) -> None:
+ if _docker_version["countdown"] > 0:
+ _docker_version["countdown"] -= 1
+ return
+ _docker_version["countdown"] = DOCKER_VERSION_EVERY
+ try:
+ version = _docker_request(socket_path, "/version").get("Version")
+ except (OSError, ValueError, AttributeError, http.client.HTTPException):
+ return # an older proxy image refuses the request; the version just stays unknown
+ _docker_version["value"] = version[:32] if isinstance(version, str) and version else None
+
+
+# What Docker's images and build cache take on disk. Asking makes the daemon walk every layer, which can take
+# seconds on a big host, so it is asked for rarely and never delays a check-in by more than its own timeout.
+_docker_disk: dict[str, Any] = {"value": None, "next": 0.0}
+DOCKER_DISK_EVERY_SECONDS = 30 * 60
+_DOCKER_DISK_KEYS = ("images_bytes", "images_unused_bytes", "build_cache_bytes", "build_cache_unused_bytes")
+
+
+def _remember_docker_disk(socket_path: str, now: float | None = None) -> None:
+ now = time.monotonic() if now is None else now
+ if now < _docker_disk["next"]:
+ return
+ _docker_disk["next"] = now + DOCKER_DISK_EVERY_SECONDS
+ try:
+ usage = _docker_request(socket_path, "/system/df")
+ except (OSError, ValueError, http.client.HTTPException):
+ return # refused by an older proxy image, too slow or too large: stays unknown
+ if not isinstance(usage, dict) or not all(isinstance(usage.get(key), int) for key in _DOCKER_DISK_KEYS):
+ return
+ _docker_disk["value"] = {
+ **{key.replace("_bytes", "_gb"): round(usage[key] / GiB, 2) for key in _DOCKER_DISK_KEYS},
+ "images": usage.get("images") if isinstance(usage.get("images"), int) else None,
+ "images_unused": usage.get("images_unused") if isinstance(usage.get("images_unused"), int) else None,
+ }
+
+
def collect_docker(socket_path: str | None = None) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""Containers plus a verdict on the Docker API: ``ok``, ``unreachable`` or ``not_configured``.
@@ -687,12 +1033,52 @@ def collect_docker(socket_path: str | None = None) -> tuple[list[dict[str, Any]]
info: dict[str, Any] = {}
try:
containers = collect_containers(target, info)
+ _remember_docker_version(target)
+ _remember_docker_disk(target)
except (OSError, ValueError, http.client.HTTPException) as error:
print(f"Docker metrics unavailable ({type(error).__name__}); sending host metrics only", flush=True)
return [], {"docker_status": "unreachable", "docker_reason": _docker_failure_reason(error), "docker_latency_ms": info.get("latency_ms")}
return containers, {"docker_status": "ok", "docker_reason": None, "docker_latency_ms": info.get("latency_ms")}
+COMPOSE_PROJECT_LABEL = "com.docker.compose.project"
+_CONTAINER_ID = re.compile(r"[0-9a-f]{64}")
+
+
+def container_swap_mb(container_id: str) -> float | None:
+ """How much of a container's memory is swapped out, from its cgroup (v2), or None when that can't be read.
+
+ Docker's stats don't report it. The cgroup files are world-readable and sit under the host's /sys, at a path
+ that depends on whether Docker uses the systemd or the cgroupfs driver.
+ """
+ if not _CONTAINER_ID.fullmatch(container_id):
+ return None
+ for relative in (f"sys/fs/cgroup/system.slice/docker-{container_id}.scope/memory.swap.current", f"sys/fs/cgroup/docker/{container_id}/memory.swap.current"):
+ raw = _read_text(HOST_ROOT / relative)
+ if raw and raw.isdigit():
+ return round(int(raw) / MiB, 2)
+ return None
+
+
+def _compose_project(detail: dict[str, Any]) -> str | None:
+ """The compose project a container belongs to, or None for one started on its own."""
+ labels = (detail.get("Config") or {}).get("Labels")
+ project = labels.get(COMPOSE_PROJECT_LABEL) if isinstance(labels, dict) else None
+ return project[:128] if isinstance(project, str) and project else None
+
+
+def _format_volumes(mounts: Any) -> str | None:
+ """Where a container's data lives on the host: bind-mount paths and volume names, never what is in them."""
+ sources = set()
+ for mount in mounts if isinstance(mounts, list) else []:
+ if not isinstance(mount, dict):
+ continue
+ source = mount.get("Name") if mount.get("Type") == "volume" else mount.get("Source")
+ if isinstance(source, str) and source:
+ sources.add(source)
+ return ", ".join(sorted(sources))[:512] or None
+
+
def _format_ports(ports: dict[str, Any] | None) -> str | None:
mappings = []
for container_port, bindings in (ports or {}).items():
@@ -871,7 +1257,7 @@ def request_approval(api_url: str) -> tuple[int, str]:
base = api_url.rstrip("/")
while True:
try:
- registration = _post_json(f"{base}/monitoring/collectors/register", {"hostname": _host_hostname(), "machine_id": _machine_id(), "os_info": _host_os_info(), "join_token": os.getenv("HOMELAB_JOIN_TOKEN", "").strip() or None})
+ registration = _post_json(f"{base}/monitoring/collectors/register", {"hostname": _host_hostname(), "machine_id": _machine_id(), "os_info": _host_os_info(), "join_token": os.getenv("HOMELAB_JOIN_TOKEN", "").strip() or None, "details": registration_details()})
except urllib.error.HTTPError as exc:
print(f"Registration refused (HTTP {exc.code}): {_error_detail(exc)}; retrying in 5 minutes", flush=True)
time.sleep(300)
diff --git a/src/agent/docker_proxy.py b/src/agent/docker_proxy.py
index 8ed7445..bf35ca1 100644
--- a/src/agent/docker_proxy.py
+++ b/src/agent/docker_proxy.py
@@ -2,14 +2,16 @@
The Docker socket is all-or-nothing: whatever can talk to it can start a privileged container,
which is root on the host. Only this proxy mounts the socket. It listens on a Unix socket in a
-volume that only the collector shares (no network port at all), and answers exactly four kinds of request:
+volume that only the collector shares (no network port at all), and answers exactly six kinds of request:
GET /containers/json?all=1
GET /containers/<id>/json
GET /containers/<id>/stats?stream=false
GET /containers/<id>/stats?stream=false&one-shot=true
+ GET /version
+ GET /system/df
-The last one returns immediately instead of waiting a second for Docker to take a second CPU reading.
+The one-shot request returns immediately instead of waiting a second for Docker to take a second CPU reading.
Everything else is refused, and the answers are cut down to the fields the collector uses: the
inspect output is where a container's environment variables (often secrets) live, and they never
@@ -40,6 +42,10 @@ _ID = r"[0-9a-f]{12,64}"
_LIST = re.compile(r"/containers/json\?all=1")
_INSPECT = re.compile(rf"/containers/{_ID}/json")
_STATS = re.compile(rf"/containers/{_ID}/stats\?stream=false(&one-shot=true)?")
+_VERSION = re.compile(r"/version")
+_DISK_USAGE = re.compile(r"/system/df")
+# The one label that passes: which compose project a container belongs to, so the dashboard can group them.
+COMPOSE_PROJECT_LABEL = "com.docker.compose.project"
def _pick(source: Any, keys: tuple[str, ...]) -> dict[str, Any]:
@@ -51,22 +57,58 @@ def project_list(data: Any) -> list[dict[str, Any]]:
def project_inspect(data: Any) -> dict[str, Any]:
- """The inspect fields the collector reads. Config.Env, mounts, labels and the rest are dropped."""
+ """The inspect fields the collector reads. Config.Env, every label but the compose project, and the rest are dropped.
+
+ Of a mount only where it comes from and where it lands passes (paths and volume names, never contents or options).
+ """
if not isinstance(data, dict):
return {}
state = data.get("State") if isinstance(data.get("State"), dict) else {}
health = state.get("Health") if isinstance(state.get("Health"), dict) else {}
network = data.get("NetworkSettings") if isinstance(data.get("NetworkSettings"), dict) else {}
config = data.get("Config") if isinstance(data.get("Config"), dict) else {}
+ labels = config.get("Labels") if isinstance(config.get("Labels"), dict) else {}
+ mounts = data.get("Mounts") if isinstance(data.get("Mounts"), list) else []
return {
# Image is the ID of the image the container runs. State.Error is free text, so it stays out.
**_pick(data, ("Id", "Name", "RestartCount", "Image")),
- "Config": _pick(config, ("Image",)),
+ "Config": {**_pick(config, ("Image",)), "Labels": _pick(labels, (COMPOSE_PROJECT_LABEL,))},
+ "Mounts": [_pick(mount, ("Type", "Name", "Source", "Destination")) for mount in mounts if isinstance(mount, dict)],
"State": {**_pick(state, ("Status", "StartedAt", "ExitCode", "OOMKilled", "FinishedAt")), "Health": _pick(health, ("Status",))},
"NetworkSettings": _pick(network, ("Ports",)),
}
+def project_version(data: Any) -> dict[str, Any]:
+ """Only the daemon's version numbers; the rest of /version describes the host."""
+ return _pick(data, ("Version", "ApiVersion"))
+
+
+def _size(value: Any) -> int:
+ return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) and 0 <= value < 2**62 else 0
+
+
+def project_disk_usage(data: Any) -> dict[str, int]:
+ """How much disk Docker's images and build cache take and how much of it nothing uses: six numbers.
+
+ /system/df lists every image, container, volume and build step by name; none of those leave the proxy.
+ """
+ if not isinstance(data, dict):
+ return {}
+ images = [item for item in data.get("Images") or [] if isinstance(item, dict)] if isinstance(data.get("Images"), list) else []
+ cache = [item for item in data.get("BuildCache") or [] if isinstance(item, dict)] if isinstance(data.get("BuildCache"), list) else []
+ unused = [item for item in images if item.get("Containers") == 0]
+ return {
+ "images_bytes": _size(data.get("LayersSize")),
+ # What only that image holds: layers it shares with an image still in use stay after a prune.
+ "images_unused_bytes": sum(max(0, _size(item.get("Size")) - _size(item.get("SharedSize"))) for item in unused),
+ "images_unused": len(unused),
+ "images": len(images),
+ "build_cache_bytes": sum(_size(item.get("Size")) for item in cache if not item.get("Shared")),
+ "build_cache_unused_bytes": sum(_size(item.get("Size")) for item in cache if not item.get("Shared") and not item.get("InUse")),
+ }
+
+
def project_stats(data: Any) -> dict[str, Any]:
if not isinstance(data, dict):
return {}
@@ -77,7 +119,7 @@ def route(method: str, target: str) -> tuple[str, Callable[[Any], Any]] | None:
"""The upstream request and response filter for an allowed request, or None to refuse it."""
if method != "GET" or not target.isascii() or not target.isprintable():
return None
- for pattern, project in ((_LIST, project_list), (_INSPECT, project_inspect), (_STATS, project_stats)):
+ for pattern, project in ((_LIST, project_list), (_INSPECT, project_inspect), (_STATS, project_stats), (_VERSION, project_version), (_DISK_USAGE, project_disk_usage)):
if pattern.fullmatch(target):
return target, project
return None
diff --git a/src/agent/system_helper.py b/src/agent/system_helper.py
index b9f53fd..2d3dff6 100644
--- a/src/agent/system_helper.py
+++ b/src/agent/system_helper.py
@@ -10,6 +10,12 @@ with fixed patterns, strings are reduced to printable text and truncated, and th
fixed schema. The helper is stateless; each run re-reads the kernel ring buffer and publishes
a snapshot, and the backend de-duplicates events by their key.
+A second, separate mode (``HOMELAB_HELPER_MODE=port-owners``, the ``port-owners`` compose profile) names the
+process behind each listening port. That needs far more than the kernel log does: the host's /proc and the
+right to look at other users' processes (CAP_SYS_PTRACE and CAP_DAC_READ_SEARCH), which together can read
+any file on the host. It therefore runs as its own container, so enabling the kernel-log helper never grants
+it, and it publishes nothing but protocol, port and process name.
+
Standard library only. Run with ``python -m src.agent.system_helper`` or as a standalone script.
"""
from __future__ import annotations
@@ -136,6 +142,90 @@ def classify_last_shutdown(records: list[tuple[int, str, int]], boot_time: float
return "unclean" if any(is_shutdown(record) for record in records[:latest]) else "unknown"
+PORTS_OUTPUT_PATH = Path(os.getenv("HOMELAB_PORT_OWNERS_OUTPUT", "/out/ports.json"))
+# Where the host's /proc is mounted for the port-owners mode (its own /proc only shows this container).
+PORTS_HOST_PROC = Path(os.getenv("HOMELAB_PORT_OWNERS_PROC", "/host/proc"))
+MAX_SOCKET_LINES = 200_000
+MAX_PROCESSES = 20_000
+MAX_FDS_PER_PROCESS = 4096
+MAX_PORT_OWNERS = 512
+PORT_SCAN_BUDGET_SECONDS = 8.0
+_SOCKET_LINK = re.compile(r"socket:\[(\d{1,20})\]")
+_ZERO_V6 = "0" * 32
+
+
+def listening_sockets(proc: Path = PORTS_HOST_PROC) -> dict[int, tuple[str, int]]:
+ """{socket inode: (protocol, port)} for every listening TCP socket and bound UDP socket on the host."""
+ sockets: dict[int, tuple[str, int]] = {}
+ for table, proto in (("tcp", "tcp"), ("tcp6", "tcp"), ("udp", "udp"), ("udp6", "udp")):
+ try:
+ handle = open(proc / "1/net" / table, "r", encoding="utf-8", errors="replace")
+ except OSError:
+ continue
+ with handle:
+ for number, line in enumerate(handle):
+ if number > MAX_SOCKET_LINES:
+ break
+ fields = line.split()
+ if not number or len(fields) < 10:
+ continue
+ listening = fields[3] == "0A" if proto == "tcp" else fields[3] == "07" and fields[2].startswith(("00000000:0000", _ZERO_V6 + ":0000"))
+ if not listening:
+ continue
+ try:
+ port, inode = int(fields[1].rpartition(":")[2], 16), int(fields[9])
+ except ValueError:
+ continue
+ if inode and 1 <= port <= 65535:
+ sockets[inode] = (proto, port)
+ return sockets
+
+
+def port_owners(proc: Path = PORTS_HOST_PROC, deadline: float | None = None) -> list[dict[str, Any]]:
+ """[{proto, port, process}] for the listening ports whose process could be found, lowest port first.
+
+ Only the link target of each file descriptor is read (never the file behind it), and only the process's
+ short name is kept: no arguments, no paths, no user.
+ """
+ wanted = listening_sockets(proc)
+ if not wanted:
+ return []
+ deadline = time.monotonic() + PORT_SCAN_BUDGET_SECONDS if deadline is None else deadline
+ found: dict[tuple[str, int], str] = {}
+ try:
+ pids = sorted((entry for entry in os.listdir(proc) if entry.isdigit()), key=int)[:MAX_PROCESSES]
+ except OSError:
+ return []
+ for pid in pids:
+ if len(found) == len(set(wanted.values())) or time.monotonic() > deadline:
+ break
+ try:
+ descriptors = os.listdir(proc / pid / "fd")[:MAX_FDS_PER_PROCESS]
+ except OSError:
+ continue # the process ended, or this container lacks the capabilities
+ name = None
+ for descriptor in descriptors:
+ try:
+ match = _SOCKET_LINK.fullmatch(os.readlink(proc / pid / "fd" / descriptor))
+ except OSError:
+ continue
+ key = wanted.get(int(match.group(1))) if match else None
+ if key is None or key in found:
+ continue
+ if name is None:
+ try:
+ name = sanitize((proc / pid / "comm").read_text().strip(), MAX_PROCESS_NAME)
+ except OSError:
+ name = ""
+ if name:
+ found[key] = name
+ return [{"proto": proto, "port": port, "process": name} for (proto, port), name in sorted(found.items(), key=lambda item: (item[0][1], item[0][0]))][:MAX_PORT_OWNERS]
+
+
+def build_port_snapshot() -> dict[str, Any]:
+ return {"version": 1, "generated_at": datetime.fromtimestamp(time.time(), timezone.utc).isoformat(timespec="seconds"), "listeners": port_owners()}
+
+
def build_snapshot() -> dict[str, Any]:
boot_id = (HOST_PROC / "sys/kernel/random/boot_id").read_text().strip()[:64]
wall_now, monotonic_now = time.time(), time.monotonic()
@@ -165,11 +255,13 @@ def write_snapshot(snapshot: dict[str, Any], path: Path = OUTPUT_PATH) -> None:
def run() -> None:
interval = max(10, int(os.getenv("HOMELAB_HELPER_INTERVAL_SECONDS", "30")))
- print(f"System helper started; writing {OUTPUT_PATH} every {interval}s", flush=True)
+ ports_mode = os.getenv("HOMELAB_HELPER_MODE", "").strip().lower() == "port-owners"
+ output = PORTS_OUTPUT_PATH if ports_mode else OUTPUT_PATH
+ print(f"{'Port-owners' if ports_mode else 'System'} helper started; writing {output} every {interval}s", flush=True)
while True:
started = time.monotonic()
try:
- write_snapshot(build_snapshot())
+ write_snapshot(build_port_snapshot() if ports_mode else build_snapshot(), output)
except (OSError, ValueError) as error:
print(f"Snapshot failed ({type(error).__name__}): {error}", flush=True)
time.sleep(max(1, interval - (time.monotonic() - started)))
diff --git a/src/backend/auth.py b/src/backend/auth.py
index a957d39..0e72aac 100644
--- a/src/backend/auth.py
+++ b/src/backend/auth.py
@@ -18,6 +18,8 @@ STAGE_ENROLLMENT = "enrollment"
PENDING_TWO_FACTOR_TTL_SECONDS = 300
# A limited session exists only to set up two-factor, so it doesn't need to last a day; a stolen one is worth less.
ENROLLMENT_SESSION_TTL_SECONDS = 30 * 60
+# "Keep me signed in for 30 days" on the sign-in page. Never shorter than the ordinary session.
+REMEMBER_SESSION_TTL_SECONDS = max(30 * 24 * 3600, SESSION_TTL_SECONDS)
MAX_PENDING_ATTEMPTS = 5
_PUBLIC_ID = re.compile(r"[0-9a-f]{16}")
# Checked against when the account doesn't exist, so that unknown emails cost the same time as wrong passwords.
@@ -51,9 +53,15 @@ def _key_for_digest(digest: str) -> str:
return f"homelab:session:{digest}"
+def session_lifetime(stage: str, remember: bool) -> int:
+ """How long a session lasts, in seconds. A limited (enrollment) session is always short, whatever was ticked."""
+ if stage == STAGE_ENROLLMENT:
+ return ENROLLMENT_SESSION_TTL_SECONDS
+ return REMEMBER_SESSION_TTL_SECONDS if remember else SESSION_TTL_SECONDS
+
+
def _store_session(redis_client, session_id: str, payload: dict):
- lifetime = ENROLLMENT_SESSION_TTL_SECONDS if payload.get("stage") == STAGE_ENROLLMENT else SESSION_TTL_SECONDS
- redis_client.set(_session_key(session_id), json.dumps(payload), ex=lifetime)
+ redis_client.set(_session_key(session_id), json.dumps(payload), ex=session_lifetime(payload.get("stage"), payload.get("remember") is True))
def _read_session(redis_client, session_id: str):
@@ -81,7 +89,7 @@ def _printable(text: str | None, limit: int) -> str | None:
return cleaned or None
-def create_session(redis_client, user: User, *, stage: str = STAGE_FULL, ip: str | None = None, user_agent: str | None = None) -> tuple[str, str]:
+def create_session(redis_client, user: User, *, stage: str = STAGE_FULL, ip: str | None = None, user_agent: str | None = None, remember: bool = False) -> tuple[str, str]:
"""Open a session and index it under its user. Returns (session_id, public_id).
The session ID is the secret in the cookie and is never shown to a client. The public ID is a separate
@@ -89,12 +97,14 @@ def create_session(redis_client, user: User, *, stage: str = STAGE_FULL, ip: str
"""
session_id, public_id = secrets.token_urlsafe(32), secrets.token_hex(8)
_store_session(redis_client, session_id, {
- "user_id": user.id, "email": user.email, "name": user.name, "role": user.role, "stage": stage, "public_id": public_id,
+ "user_id": user.id, "email": user.email, "name": user.name, "role": user.role, "stage": stage, "public_id": public_id, "remember": bool(remember),
"created_at": datetime.now(timezone.utc).isoformat(), "ip": _printable(ip, 64), "user_agent": _printable(user_agent, 120),
})
index = _user_sessions_key(user.id)
redis_client.hset(index, public_id, _digest(session_id))
- redis_client.expire(index, SESSION_TTL_SECONDS)
+ # The index must outlive the longest session it can list, or a 30-day session would vanish from the list (and
+ # from "sign out everywhere") after a day. Entries for sessions that have ended are dropped when it is read.
+ redis_client.expire(index, REMEMBER_SESSION_TTL_SECONDS)
return session_id, public_id
@@ -178,13 +188,24 @@ def revoke_other_sessions(redis_client, user_id: int, keep_public_id: str | None
return revoked
-def create_pending_two_factor(redis_client, user_id: int) -> str:
+def create_pending_two_factor(redis_client, user_id: int, remember: bool = False) -> str:
"""The short-lived token that carries a login between the password step and the code step."""
token = secrets.token_urlsafe(32)
- redis_client.set(_pending_key(token), json.dumps({"user_id": user_id}), ex=PENDING_TWO_FACTOR_TTL_SECONDS)
+ redis_client.set(_pending_key(token), json.dumps({"user_id": user_id, "remember": bool(remember)}), ex=PENDING_TWO_FACTOR_TTL_SECONDS)
return token
+def pending_two_factor_remember(redis_client, token) -> bool:
+ """Whether the login waiting behind this token asked to stay signed in. The choice is made at the password step
+ and kept on the server, so the code step can't be used to lengthen someone's session."""
+ if not isinstance(token, str) or not 20 <= len(token) <= 100:
+ return False
+ try:
+ return json.loads(redis_client.get(_pending_key(token)) or "{}").get("remember") is True
+ except (TypeError, ValueError, AttributeError):
+ return False
+
+
def read_pending_two_factor(redis_client, token) -> int | None:
if not isinstance(token, str) or not 20 <= len(token) <= 100:
return None
@@ -323,7 +344,7 @@ def validate_password(password: str) -> None:
def register_user(db, redis_client, *, name: str, email: str, password: str, admin_requires_two_factor: bool = False,
- ip: str | None = None, user_agent: str | None = None):
+ everyone_requires_two_factor: bool = False, role: str | None = None, ip: str | None = None, user_agent: str | None = None):
normalized_name = name.strip()
normalized_email = email.strip().lower()
@@ -344,7 +365,7 @@ def register_user(db, redis_client, *, name: str, email: str, password: str, adm
name=normalized_name,
email=normalized_email,
password_hash=password_hash,
- role="admin" if is_first_user else "user",
+ role="admin" if is_first_user else role if role in ("admin", "user") else "user",
is_active=True,
)
db.add(user)
@@ -353,7 +374,7 @@ def register_user(db, redis_client, *, name: str, email: str, password: str, adm
record_audit_log(db, user_id=user.id, level="INFO", message="New account registered", source="auth")
- stage = STAGE_ENROLLMENT if user.role == "admin" and admin_requires_two_factor else STAGE_FULL
+ stage = STAGE_ENROLLMENT if everyone_requires_two_factor or (user.role == "admin" and admin_requires_two_factor) else STAGE_FULL
session_id, _public_id = create_session(redis_client, user, stage=stage, ip=ip, user_agent=user_agent)
return {"session_id": session_id, "user": _serialize_user(user), "setup_required": stage == STAGE_ENROLLMENT}
diff --git a/src/backend/config.py b/src/backend/config.py
index 8319c61..22d72d1 100644
--- a/src/backend/config.py
+++ b/src/backend/config.py
@@ -6,6 +6,9 @@ from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parents[2]
load_dotenv(BASE_DIR / ".env")
+# Shown in the sidebar and compared with what each collector reports.
+APP_VERSION = "0.9.2"
+
DATABASE_URL = os.getenv(
"DATABASE_URL",
"postgresql+psycopg://homelab:homelab_dev@localhost:5432/homelab",
diff --git a/src/backend/dashboard.py b/src/backend/dashboard.py
new file mode 100644
index 0000000..a8ba13c
--- /dev/null
+++ b/src/backend/dashboard.py
@@ -0,0 +1,110 @@
+"""Read models for the Overview page: sparklines, the all-clear summary and a server's event timeline."""
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+
+from .alerts import INFO, SERVER_OFFLINE_RULE
+from .models import ContainerMetric, HostMetric, IncidentAlert, Server, SystemEvent
+from .rules import CONTAINER_EVENT_KINDS, NETWORK_EVENT_KINDS
+
+SPARKLINE_POINTS = 40
+MAX_EVENTS = 2000
+
+
+def _utc(moment: datetime) -> datetime:
+ return moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
+
+
+def downsample(values: list[float | None], limit: int = SPARKLINE_POINTS) -> list[float | None]:
+ """At most ``limit`` points, each the average of its share of ``values``; gaps stay gaps."""
+ if len(values) <= limit:
+ return [None if value is None else round(value, 2) for value in values]
+ result = []
+ for index in range(limit):
+ chunk = [value for value in values[index * len(values) // limit:(index + 1) * len(values) // limit] if value is not None]
+ result.append(round(sum(chunk) / len(chunk), 2) if chunk else None)
+ return result
+
+
+def fleet_sparklines(db, minutes: int, now: datetime | None = None) -> dict[int, list[float | None]]:
+ """Recent CPU use of every server, oldest first, for the fleet rack."""
+ since = (now or datetime.now(timezone.utc)) - timedelta(minutes=minutes)
+ series: dict[int, list[float | None]] = {}
+ for server_id, cpu in db.query(HostMetric.server_id, HostMetric.cpu_utilization_pct).filter(HostMetric.time >= since).order_by(HostMetric.time):
+ series.setdefault(server_id, []).append(cpu)
+ return {server_id: downsample(values) for server_id, values in series.items()}
+
+
+def container_sparklines(db, server_id: int, minutes: int, now: datetime | None = None) -> dict[str, list[float | None]]:
+ """Recent CPU use of every container on one server, oldest first, for the container table."""
+ since = (now or datetime.now(timezone.utc)) - timedelta(minutes=minutes)
+ series: dict[str, list[float | None]] = {}
+ rows = db.query(ContainerMetric.container_id, ContainerMetric.cpu_pct).filter(ContainerMetric.server_id == server_id, ContainerMetric.time >= since).order_by(ContainerMetric.time)
+ for container_id, cpu in rows:
+ series.setdefault(container_id, []).append(cpu)
+ return {container_id: downsample(values) for container_id, values in series.items()}
+
+
+def longest_quiet_seconds(spans: list[tuple[datetime, datetime]], start: datetime, end: datetime) -> float:
+ """The longest stretch between ``start`` and ``end`` that none of the (opened, closed) ``spans`` covers."""
+ longest, cursor = 0.0, start
+ for opened, closed in sorted(spans):
+ if opened > cursor:
+ longest = max(longest, (min(opened, end) - cursor).total_seconds())
+ cursor = max(cursor, closed)
+ if cursor >= end:
+ break
+ return max(longest, (end - cursor).total_seconds(), 0.0)
+
+
+def quiet_summary(db, now: datetime | None = None) -> dict:
+ """What the Overview says when nothing needs attention: the last incident and how long it has been quiet.
+
+ Notices (INFO) don't count: they never asked for attention in the first place.
+ """
+ now = _utc(now or datetime.now(timezone.utc))
+ serious = IncidentAlert.severity != INFO
+ last = db.query(IncidentAlert).filter(serious, IncidentAlert.status == "resolved", IncidentAlert.resolved_at.isnot(None)).order_by(IncidentAlert.resolved_at.desc()).first()
+ month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+ first_server = db.query(Server.created_at).order_by(Server.created_at).first()
+ # A month the install only partly existed in is measured from when it started watching.
+ window_start = max(month_start, _utc(first_server[0])) if first_server else now
+ spans = [
+ (_utc(alert.created_at), _utc(alert.resolved_at) if alert.resolved_at else now)
+ for alert in db.query(IncidentAlert).filter(serious, (IncidentAlert.resolved_at.is_(None)) | (IncidentAlert.resolved_at >= window_start))
+ ]
+ hostname = db.query(Server.hostname).filter(Server.id == last.server_id).scalar() if last else None
+ return {
+ "last_incident": {"title": last.title, "hostname": hostname, "severity": last.severity, "created_at": _utc(last.created_at).isoformat(), "resolved_at": _utc(last.resolved_at).isoformat()} if last else None,
+ "quiet_since": (_utc(last.resolved_at) if last else _utc(first_server[0]) if first_server else now).isoformat(),
+ "longest_quiet_seconds_this_month": round(longest_quiet_seconds(spans, window_start, now)),
+ }
+
+
+def _event_source(kind: str) -> str:
+ return "container" if kind in CONTAINER_EVENT_KINDS else "network" if kind in NETWORK_EVENT_KINDS else "system"
+
+
+def server_events(db, server: Server, days: int, now: datetime | None = None) -> list[dict]:
+ """Everything that happened on one server, newest first: its recorded events plus alerts opening and clearing.
+
+ A server going offline and coming back is told as the collector's story rather than as an alert.
+ """
+ now = _utc(now or datetime.now(timezone.utc))
+ since = now - timedelta(days=days)
+ events: list[dict] = []
+ for event in db.query(SystemEvent).filter(SystemEvent.server_id == server.id, SystemEvent.time >= since).order_by(SystemEvent.time.desc()).limit(MAX_EVENTS):
+ events.append({"time": _utc(event.time).isoformat(), "source": _event_source(event.kind), "kind": event.kind, "detail": event.detail})
+ alerts = db.query(IncidentAlert).filter(IncidentAlert.server_id == server.id, (IncidentAlert.created_at >= since) | (IncidentAlert.resolved_at >= since)).order_by(IncidentAlert.created_at.desc()).limit(MAX_EVENTS)
+ for alert in alerts:
+ offline = alert.rule_key == SERVER_OFFLINE_RULE
+ created, resolved = _utc(alert.created_at), _utc(alert.resolved_at) if alert.resolved_at else None
+ common = {"alert_id": alert.id, "rule_key": alert.rule_key, "severity": alert.severity, "title": alert.title}
+ if created >= since:
+ events.append({**common, "time": created.isoformat(), "source": "collector" if offline else "alert", "kind": "collector_stopped" if offline else "alert_opened",
+ "detail": alert.description, "resolved": resolved is not None})
+ if resolved and resolved >= since:
+ events.append({**common, "time": resolved.isoformat(), "source": "collector" if offline else "alert", "kind": "collector_resumed" if offline else "alert_resolved",
+ "detail": alert.description, "duration_seconds": round((resolved - created).total_seconds())})
+ events.sort(key=lambda event: event["time"], reverse=True)
+ return events[:MAX_EVENTS]
diff --git a/src/backend/history.py b/src/backend/history.py
index 4ca05e3..b9b524e 100644
--- a/src/backend/history.py
+++ b/src/backend/history.py
@@ -60,7 +60,7 @@ MOUNT_METRICS = {
}
CONTAINER_METRICS = {
"cpu": _m("cpu_pct", "cpu"), "memory_mb": _m("memory_used_mb", "memory_mb"), "memory_pct": _m("memory_pct", "memory_pct"),
- "memory_limit_mb": _m("memory_limit_mb", "memory_limit_mb", avg=False), "restarts": _m("restart_count", "restarts", avg=False),
+ "swap_mb": _m("swap_mb", "swap_mb"), "memory_limit_mb": _m("memory_limit_mb", "memory_limit_mb", avg=False), "restarts": _m("restart_count", "restarts", avg=False),
}
DEFAULT_HOST_METRICS = ("cpu", "ram", "swap", "load", "disk")
@@ -217,8 +217,15 @@ def _tiered_items(db, spec, wanted, server_id, key, tier: str, window_start: dat
return sorted(grouped.items()), NATURAL_SECONDS[tier]
+def previous_end(range_name: str, now: datetime | None = None) -> datetime | None:
+ """Where the period before ``range_name`` ends (which is where the range itself starts), for "compare with the
+ previous 7 days". None for "all", which has nothing before it."""
+ length = RANGES[range_name]
+ return rollups._utc(now or datetime.now(timezone.utc)) - length if length else None
+
+
def history(db, spec: Series, server_id: int, key: str | None, range_name: str, wanted, interval_seconds: int, now: datetime | None = None) -> dict:
- """The chart series for one server (and mount or container) over ``range_name``."""
+ """The chart series for one server (and mount or container) over ``range_name``, ending at ``now``."""
now = rollups._utc(now or datetime.now(timezone.utc))
since = data_since(db, spec, server_id, key)
length = RANGES[range_name]
diff --git a/src/backend/incidents.py b/src/backend/incidents.py
new file mode 100644
index 0000000..d50e3cc
--- /dev/null
+++ b/src/backend/incidents.py
@@ -0,0 +1,273 @@
+"""Incidents as the Agent page shows them: an inbox, and for each incident a diagnosis built from the data.
+
+Nothing here is guessed or written by a language model. The summary is the rule's own description, the evidence is
+the metric the rule looks at, the signals are checks against stored samples, and the fixes come from a fixed
+playbook per kind of rule, with the container or mount name filled in.
+"""
+from __future__ import annotations
+
+import math
+import re
+from datetime import datetime, timedelta, timezone
+
+from .alerts import CRITICAL, INFO, SERVER_OFFLINE_RULE, WARNING
+from .dashboard import _event_source
+from .models import ContainerMetric, HostMetric, IncidentAlert, MountMetric, Server, SystemEvent, User
+
+MAX_LISTED = 200
+EVIDENCE_POINTS = 120
+EVIDENCE_LEAD = timedelta(minutes=60)
+MAX_LINES = 14
+MAX_TIMELINE = 12
+_SAFE_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+
+
+def _utc(moment: datetime | None) -> datetime | None:
+ return None if moment is None else moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
+
+
+def rule_kind(rule_key: str | None) -> str:
+ """The kind of rule behind an alert, without the container, mount or port it is about:
+ ``container:gitlab:restart_loop`` -> ``container:restart_loop``, ``host:disk:/mnt/x`` -> ``host:disk``."""
+ if not rule_key:
+ return "other"
+ parts = rule_key.split(":")
+ if parts[0] == "container" and len(parts) >= 3:
+ return f"container:{parts[-1]}"
+ if parts[0] == "trend":
+ return "trend:memory"
+ if parts[0] in ("host", "system", "network") and len(parts) >= 2:
+ return f"{parts[0]}:{parts[1]}"
+ return rule_key
+
+
+def subject(rule_key: str | None) -> str | None:
+ """The container, mount or port a rule is about, when it names one."""
+ parts = (rule_key or "").split(":")
+ if parts[0] in ("container", "trend") and len(parts) >= 3:
+ return ":".join(parts[1:-1])
+ if parts[0] in ("host", "network") and len(parts) >= 3:
+ return ":".join(parts[2:])
+ return None
+
+
+def reference(alert_id: int) -> str:
+ return f"INC-{alert_id:04d}"
+
+
+def is_muted(alert: IncidentAlert, now: datetime) -> bool:
+ return alert.muted_until is not None and _utc(alert.muted_until) > now
+
+
+def state_of(alert: IncidentAlert) -> str:
+ """What the inbox says under the title: diagnosed (there are steps to take) or watching (nothing to do yet)."""
+ return "watching" if alert.severity == INFO or rule_kind(alert.rule_key) in ("trend:memory", "host:swap") else "diagnosed"
+
+
+def _command_name(name: str | None) -> str:
+ """A container name that is safe to show inside a command to copy; anything unusual becomes a placeholder."""
+ return name if name and _SAFE_NAME.fullmatch(name) else "<container>"
+
+
+def _gb(megabytes: float) -> str:
+ return f"{megabytes / 1024:.1f} GB" if megabytes >= 1024 else f"{megabytes:.0f} MB"
+
+
+def _step(title: str, text: str, command: str | None = None, label: str | None = None, recommended: bool = False) -> dict:
+ return {"title": title, "text": text, "command": command, "label": label, "recommended": recommended}
+
+
+def _downsample(rows: list[tuple[datetime, float | None]], limit: int = EVIDENCE_POINTS) -> list[dict]:
+ if len(rows) > limit:
+ size = math.ceil(len(rows) / limit)
+ grouped = []
+ for start in range(0, len(rows), size):
+ chunk = [value for _, value in rows[start:start + size] if value is not None]
+ # The highest value in each group: an incident is about peaks, and an average would hide them.
+ grouped.append((rows[start][0], max(chunk) if chunk else None))
+ rows = grouped
+ return [{"time": _utc(moment).isoformat(), "value": None if value is None else round(value, 2)} for moment, value in rows]
+
+
+def _container_samples(db, server_id: int, name: str, since: datetime, until: datetime) -> list[ContainerMetric]:
+ return db.query(ContainerMetric).filter(ContainerMetric.server_id == server_id, ContainerMetric.name == name, ContainerMetric.time >= since, ContainerMetric.time <= until).order_by(ContainerMetric.time).limit(5000).all()
+
+
+def _container_diagnosis(db, alert: IncidentAlert, server: Server, kind: str, since: datetime, until: datetime) -> dict:
+ name = subject(alert.rule_key) or ""
+ samples = _container_samples(db, server.id, name, since, until)
+ shown = _command_name(name)
+ latest = samples[-1] if samples else None
+ host_mb = (server.total_ram_gb or 0) * 1024
+ limit = latest.memory_limit_mb if latest and latest.memory_limit_mb and (not host_mb or latest.memory_limit_mb < host_mb * 0.98) else None
+ restarts = [(sample.time, sample.restart_count) for sample in samples]
+ marks = [{"time": _utc(moment).isoformat(), "label": "restart"} for (_, before), (moment, after) in zip(restarts, restarts[1:]) if after > before]
+ peak = max((sample.memory_used_mb for sample in samples if sample.memory_used_mb is not None), default=None)
+ oom = any(sample.oom_killed for sample in samples)
+ codes = sorted({sample.exit_code for sample in samples if sample.exit_code is not None})
+ signals = []
+ if restarts:
+ rose = restarts[-1][1] - restarts[0][1]
+ signals.append({"text": f"The restart count rose by {rose} in this window.", "source": f"{len(marks)} of {len(samples)} check-ins", "ok": rose > 0})
+ if limit and peak is not None:
+ signals.append({"text": f"Memory reached {_gb(peak)} of its {_gb(limit)} limit.", "source": "container memory", "ok": peak >= limit * 0.9})
+ if oom:
+ signals.append({"text": "Docker reports the last exit as an out-of-memory kill.", "source": "container state", "ok": True})
+ elif codes:
+ signals.append({"text": f"Exit code{'s' if len(codes) > 1 else ''} seen: {', '.join(map(str, codes))}{' (137 means it was killed)' if 137 in codes else ''}.", "source": "container state", "ok": True})
+ if latest and latest.healthcheck_status:
+ signals.append({"text": f"Its healthcheck reports {latest.healthcheck_status}.", "source": "docker healthcheck", "ok": latest.healthcheck_status == "unhealthy"})
+ memory_bound = oom or (limit is not None and peak is not None and peak >= limit * 0.9)
+ steps = []
+ if memory_bound and limit:
+ bigger = max(1, math.ceil(limit * 1.5 / 1024))
+ steps.append(_step(f"Raise the memory limit to {bigger} GB", f"{name} runs into its {_gb(limit)} limit. In its compose file, raise the limit and recreate the container:", f"mem_limit: {bigger}g", "compose", True))
+ elif memory_bound:
+ steps.append(_step("Find what is using the memory", f"{name} has no memory limit of its own, so the host ran out. See which containers hold the most:", "docker stats --no-stream --format 'table {{.Name}}\\t{{.MemUsage}}' | sort -k2 -h", "shell", True))
+ steps.append(_step("Read why it exits" if kind != "container:unhealthy" else "Read what the healthcheck says", "The container's own log usually names the reason in its last lines before each exit." if kind != "container:unhealthy" else "The last healthcheck output is kept by Docker.",
+ f"docker logs --since 30m --tail 200 {shown}" if kind != "container:unhealthy" else f"docker inspect -f '{{{{json .State.Health}}}}' {shown}", "shell", not steps))
+ steps.append(_step("Confirm it's fixed", "Infradeck resolves this incident on its own once the container stays up with no new restarts.", f"docker inspect -f '{{{{.RestartCount}}}} {{{{.State.Status}}}}' {shown}", "shell"))
+ series = _downsample([(sample.time, sample.memory_used_mb) for sample in samples])
+ return {
+ "evidence": {"title": "container memory", "unit": "MB", "series": series, "limit": limit, "limit_label": "Container limit", "marks": marks[-40:], "mark_label": "Restart"} if series else None,
+ "signals": signals, "steps": steps, "container": name,
+ "note": (f"limit is {_gb(limit)}, peak {_gb(peak)}" if limit and peak is not None and memory_bound else f"{len(marks)} restarts in this window" if marks else None),
+ }
+
+
+def _host_series(db, server: Server, column, since: datetime, until: datetime) -> list[tuple[datetime, float | None]]:
+ return [(moment, value) for moment, value in db.query(HostMetric.time, column).filter(HostMetric.server_id == server.id, HostMetric.time >= since, HostMetric.time <= until).order_by(HostMetric.time).limit(20000)]
+
+
+def _top_containers(db, server: Server, column, count: int = 3) -> list[tuple[str, float]]:
+ latest = db.query(HostMetric.time).filter(HostMetric.server_id == server.id).order_by(HostMetric.time.desc()).limit(1).scalar()
+ if latest is None:
+ return []
+ rows = db.query(ContainerMetric.name, column).filter(ContainerMetric.server_id == server.id, ContainerMetric.time == latest, column.isnot(None)).order_by(column.desc()).limit(count).all()
+ return [(name, value) for name, value in rows if value]
+
+
+def _host_diagnosis(db, alert: IncidentAlert, server: Server, kind: str, since: datetime, until: datetime) -> dict:
+ confirm = _step("Confirm it's fixed", "Infradeck resolves this incident on its own once the value stays under the threshold for a few check-ins.")
+ if kind in ("host:memory", "host:swap"):
+ swap = kind == "host:swap"
+ rows = _host_series(db, server, HostMetric.swap_pct if swap else HostMetric.ram_pct, since, until)
+ top = _top_containers(db, server, ContainerMetric.swap_mb if swap else ContainerMetric.memory_used_mb)
+ values = [value for _, value in rows if value is not None]
+ signals = [{"text": f"{'Swap' if swap else 'Memory'} use peaked at {max(values):.0f}% in this window.", "source": "host metrics", "ok": True}] if values else []
+ if top:
+ signals.append({"text": f"{top[0][0]} holds the most {'swap' if swap else 'memory'}: {_gb(top[0][1])}." + (f" Then {', '.join(f'{name} ({_gb(value)})' for name, value in top[1:])}." if len(top) > 1 else ""), "source": "container metrics", "ok": True})
+ steps = [_step("See what holds the memory", "The biggest containers right now are listed above. To see it on the machine:", "docker stats --no-stream --format 'table {{.Name}}\\t{{.MemUsage}}\\t{{.MemPerc}}'", "shell", True)]
+ if top:
+ steps.append(_step(f"Give {top[0][0]} a memory limit", "A limit stops one container from pushing the rest of the machine into swap. In its compose file:", f"mem_limit: {max(1, math.ceil(top[0][1] * 1.3 / 1024))}g", "compose"))
+ return {"evidence": {"title": "swap in use" if swap else "memory in use", "unit": "%", "series": _downsample(rows), "limit": None, "marks": []}, "signals": signals, "steps": [*steps, confirm],
+ "note": f"top {'swap' if swap else 'memory'} user is {top[0][0]} ({_gb(top[0][1])})" if top else None}
+ if kind == "host:load":
+ rows = _host_series(db, server, HostMetric.load_1m, since, until)
+ top = _top_containers(db, server, ContainerMetric.cpu_pct)
+ signals = [{"text": f"The machine has {server.cpu_cores} cores; load above that means work is waiting.", "source": "host metrics", "ok": True}] if server.cpu_cores else []
+ if top:
+ signals.append({"text": f"{top[0][0]} uses the most CPU right now: {top[0][1]:.0f}%.", "source": "container metrics", "ok": True})
+ return {"evidence": {"title": "load (1 min)", "unit": "", "series": _downsample(rows), "limit": server.cpu_cores, "limit_label": f"{server.cpu_cores} cores", "marks": []}, "signals": signals,
+ "steps": [_step("See what is using the CPU", "Load counts processes that are running or waiting for the CPU or the disk.", "docker stats --no-stream --format 'table {{.Name}}\\t{{.CPUPerc}}' | sort -k2 -rh | head", "shell", True), confirm],
+ "note": f"busiest container is {top[0][0]} ({top[0][1]:.0f}% CPU)" if top else None}
+ if kind in ("host:disk", "host:inodes"):
+ mount = subject(alert.rule_key) or "/"
+ column = MountMetric.used_pct if kind == "host:disk" else MountMetric.inodes_pct
+ rows = [(moment, value) for moment, value in db.query(MountMetric.time, column).filter(MountMetric.server_id == server.id, MountMetric.mount == mount, MountMetric.time >= since, MountMetric.time <= until).order_by(MountMetric.time).limit(20000)]
+ values = [value for _, value in rows if value is not None]
+ signals = [{"text": f"{mount} went from {values[0]:.1f}% to {values[-1]:.1f}% in this window.", "source": "mount metrics", "ok": values[-1] >= values[0]}] if len(values) > 1 else []
+ docker = mount in ("/", "/var", "/var/lib", "/var/lib/docker")
+ steps = [_step("See what Docker can give back", "Unused images and build cache are the usual cause on a Docker host.", "docker system df", "shell", True),
+ _step("Remove what nothing uses", "This deletes every image no container uses and the unused build cache. Images you keep for later will be pulled again.", "docker image prune -a && docker builder prune", "shell")] if docker else []
+ steps.append(_step("Find the biggest folders", "Shows the largest directories on that filesystem.", f"sudo du -xh --max-depth=2 {mount if mount.startswith('/') else '/'} | sort -rh | head -20", "shell", not docker))
+ return {"evidence": {"title": f"{mount} used" if kind == "host:disk" else f"{mount} inodes used", "unit": "%", "series": _downsample(rows), "limit": None, "marks": []}, "signals": signals, "steps": [*steps, confirm], "note": None}
+ return {}
+
+
+PLAYBOOKS: dict[str, list[dict]] = {
+ SERVER_OFFLINE_RULE: [
+ _step("Check that the machine is up", "If it answers a ping, the machine is fine and the collector or the network path is the problem.", None, None, True),
+ _step("Look at the collector on that machine", "It logs why it could not send.", "docker compose -p homelab-collector logs --tail 50 collector", "shell"),
+ _step("Confirm it's back", "This incident resolves on the collector's next check-in."),
+ ],
+ "network:port": [
+ _step("Decide whether it should be reachable", "If the service is only used on this machine or behind a reverse proxy, bind it to localhost in its compose file:", 'ports: ["127.0.0.1:8080:8080"]', "compose", True),
+ _step("Or allow it on purpose", "If other machines need it, add a firewall rule for it so the choice is written down. Note that ports published by Docker bypass ufw.", "sudo ufw allow from 10.0.0.0/24 to any port <port>", "shell"),
+ ],
+ "network:firewall": [
+ _step("Turn the firewall back on", "If it was switched off by accident:", "sudo ufw enable && sudo ufw status verbose", "shell", True),
+ _step("Check what changed", "The Network tab lists which ports are reachable from other machines now."),
+ ],
+ "network:internet": [_step("Check the uplink", "The collector could not open a connection to its targets.", "ping -c 3 1.1.1.1", "shell", True)],
+ "network:dns": [_step("Check name resolution", "Connections by address work but names don't resolve.", "resolvectl status | head -20", "shell", True)],
+ "system:reboot_required": [_step("Reboot when it suits you", "Installed updates, usually a new kernel, only take effect after a restart.", "sudo systemctl reboot", "shell", True)],
+ "system:ntp": [_step("Check the time service", "One of chrony, systemd-timesyncd or ntpd should be running.", "timedatectl status", "shell", True)],
+ "system:oom": [_step("See what the kernel killed", "The kernel log names the process and how much memory it held.", "sudo dmesg -T | grep -i 'out of memory' | tail", "shell", True)],
+ "system:kernel": [_step("Read the kernel log", "The fault flag clears after a reboot; the log says what raised it.", "sudo dmesg -T --level=err,crit,alert,emerg | tail -30", "shell", True)],
+ "system:docker_unreachable": [_step("Check the Docker daemon and the proxy", "Container data stops while either is down.", "sudo systemctl status docker --no-pager && docker ps --filter name=docker-proxy", "shell", True)],
+ "system:docker_slow": [_step("See what keeps Docker busy", "A daemon that takes seconds to list containers is usually starved of CPU or disk.", "docker stats --no-stream | head -15", "shell", True)],
+ "system:collect_slow": [_step("Give the collector more time", "Raise this server's check interval in Admin, or reduce the number of containers on the machine.", None, None, True)],
+ "system:reboot": [_step("Find out why it restarted", "The previous boot's last log lines usually say.", "journalctl -b -1 -n 50 --no-pager", "shell", True)],
+ "system:credentials": [_step("Make sure it was you", "The enrollment key gave this server new credentials. If you did not re-install its collector, rotate the enrollment key and remove the server.", None, None, True)],
+ "container:removed": [_step("Bring it back if it should exist", "The container is no longer on the machine.", "docker compose up -d", "shell", True)],
+ "container:image": [_step("Check what changed", "The container now runs a different image build than before.", "docker image history --no-trunc <image> | head", "shell", True)],
+ "trend:memory": [_step("Watch it, then restart it", "Memory has climbed steadily. Restarting the container frees it; a limit keeps a leak from taking the host down.", "mem_limit: 2g", "compose", True)],
+}
+
+
+def diagnose(db, alert: IncidentAlert, server: Server, now: datetime | None = None) -> dict:
+ """Everything the incident page shows under the title, worked out from stored data."""
+ now = _utc(now or datetime.now(timezone.utc))
+ created, resolved = _utc(alert.created_at), _utc(alert.resolved_at)
+ since, until = created - EVIDENCE_LEAD, resolved or now
+ kind = rule_kind(alert.rule_key)
+ found: dict = {}
+ if kind.startswith("container:") and kind not in ("container:removed", "container:image"):
+ found = _container_diagnosis(db, alert, server, kind, since, until)
+ elif kind.startswith("host:"):
+ found = _host_diagnosis(db, alert, server, kind, since, until)
+ steps = found.get("steps") or PLAYBOOKS.get(kind) or []
+ events = db.query(SystemEvent).filter(SystemEvent.server_id == server.id, SystemEvent.time >= since - timedelta(hours=1), SystemEvent.time <= until).order_by(SystemEvent.time.desc()).limit(200).all()
+ lines = [{"time": _utc(event.time).isoformat(), "source": _event_source(event.kind), "text": event.detail, "strong": event.kind in ("oom_kill", "kernel_error", "kernel_fault", "firewall_weakened")} for event in reversed(events[:MAX_LINES])]
+ timeline = [{"time": _utc(event.time).isoformat(), "text": event.detail, "tone": "plain"} for event in events[:MAX_TIMELINE - 2]]
+ timeline.append({"time": created.isoformat(), "text": f"Incident opened · {alert.title}", "tone": "signal" if alert.severity == CRITICAL else "warn" if alert.severity == WARNING else "plain"})
+ if alert.acknowledged_at:
+ timeline.append({"time": _utc(alert.acknowledged_at).isoformat(), "text": "Acknowledged", "tone": "plain"})
+ if resolved:
+ timeline.append({"time": resolved.isoformat(), "text": f"Resolved · {alert.resolution or 'the condition cleared'}", "tone": "ok"})
+ timeline.sort(key=lambda item: item["time"])
+ signals = found.get("signals") or []
+ return {
+ "summary": alert.description, "state": state_of(alert), "kind": kind, "container": found.get("container"), "note": found.get("note"),
+ "evidence": found.get("evidence"), "lines": lines, "signals": signals, "agreeing": sum(1 for signal in signals if signal["ok"]),
+ "steps": steps, "timeline": timeline[-MAX_TIMELINE:], "window": {"start": since.isoformat(), "end": until.isoformat()},
+ }
+
+
+def summary(alert: IncidentAlert, hostname: str | None, now: datetime, users: dict[int, str] | None = None) -> dict:
+ return {
+ "id": alert.id, "reference": reference(alert.id), "server_id": alert.server_id, "hostname": hostname, "severity": alert.severity, "title": alert.title, "description": alert.description,
+ "rule_key": alert.rule_key, "kind": rule_kind(alert.rule_key), "status": alert.status, "state": state_of(alert), "created_at": _utc(alert.created_at).isoformat(),
+ "resolved_at": _utc(alert.resolved_at).isoformat() if alert.resolved_at else None, "resolution": alert.resolution,
+ "acknowledged_at": _utc(alert.acknowledged_at).isoformat() if alert.acknowledged_at else None, "acknowledged_by": (users or {}).get(alert.acknowledged_by),
+ "muted_until": _utc(alert.muted_until).isoformat() if is_muted(alert, now) else None, "notified": bool(alert.notified_at),
+ }
+
+
+def inbox(db, now: datetime | None = None) -> dict:
+ """Open incidents (most severe first), the ones resolved lately, and the muted ones, each as a summary."""
+ now = _utc(now or datetime.now(timezone.utc))
+ hostnames = dict(db.query(Server.id, Server.hostname).all())
+ users = dict(db.query(User.id, User.name).all())
+ rank = {CRITICAL: 0, WARNING: 1, INFO: 2}
+ active = db.query(IncidentAlert).filter(IncidentAlert.status == "active").order_by(IncidentAlert.created_at.desc()).limit(MAX_LISTED).all()
+ active.sort(key=lambda alert: (rank.get(alert.severity, 3), -_utc(alert.created_at).timestamp()))
+ recent = db.query(IncidentAlert).filter(IncidentAlert.status == "resolved", IncidentAlert.resolved_at.isnot(None)).order_by(IncidentAlert.resolved_at.desc()).limit(MAX_LISTED).all()
+ row = lambda alert: summary(alert, hostnames.get(alert.server_id), now, users) # noqa: E731
+ return {
+ "open": [row(alert) for alert in active if not is_muted(alert, now)],
+ "muted": [row(alert) for alert in active if is_muted(alert, now)],
+ "resolved": [row(alert) for alert in recent],
+ "resolved_count": db.query(IncidentAlert).filter(IncidentAlert.status == "resolved").count(),
+ }
diff --git a/src/backend/main.py b/src/backend/main.py
index b8c8994..b79691d 100644
--- a/src/backend/main.py
+++ b/src/backend/main.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import ipaddress
+import os
import json
import math
import unicodedata
@@ -24,17 +25,21 @@ from pydantic import BaseModel, EmailStr, Field, field_validator
from sqlalchemy import case, func, inspect, text
from .alerts import CONTAINER_RULE_PREFIX, CRITICAL, SERVER_OFFLINE_RULE, SEVERITIES, active_rule_keys, raise_alert, resolve_alerts, sync_alerts
-from . import auth, history as history_service, rollups, secrets_box, stats, totp
+import contextvars
+
+from . import auth, dashboard, history as history_service, incidents, notify, rollups, secrets_box, stats, totp
from .auth import (
STAGE_ENROLLMENT, STAGE_FULL, count_pending_attempt, create_pending_two_factor, create_session, delete_pending_two_factor, delete_session, get_recent_logs,
- get_session, get_user_from_session, hash_password, issue_recovery_codes, list_user_sessions, read_pending_two_factor, recovery_codes_left, record_audit_log,
+ get_session, get_user_from_session, hash_password, issue_recovery_codes, list_user_sessions, pending_two_factor_remember, read_pending_two_factor, session_lifetime, recovery_codes_left, record_audit_log,
register_user, revoke_other_sessions, revoke_user_session, validate_password, verify_credentials, verify_password, verify_second_factor,
)
from .db import SessionLocal, check_database, get_db
-from .models import AppSetting, AuditLog, Base, ChatMessage, ContainerMetric, ContainerRollup, Conversation, EnrollmentKey, FirewallState, HostMetric, HostRollup, IncidentAlert, JoinToken, ListenerState, MountMetric, MountRollup, PendingCollector, RecoveryCode, Server, SystemEvent, User
+from .models import ApiToken, Invite, NotificationChannel, AppSetting, AuditLog, Base, ChatMessage, ContainerMetric, ContainerRollup, Conversation, EnrollmentKey, FirewallState, HostMetric, HostRollup, IncidentAlert, JoinToken, ListenerState, MountMetric, MountRollup, PendingCollector, RecoveryCode, Server, SystemEvent, User
from .db import engine
from .config import (
+ AGENT_MODEL,
+ APP_VERSION,
LOGIN_RATE_LIMIT,
LOGIN_RATE_WINDOW_SECONDS,
REDIS_URL,
@@ -57,7 +62,7 @@ from .config import (
SESSION_COOKIE_SECURE,
SESSION_TTL_SECONDS,
)
-from .rules import HELPER_EVENT_KINDS, DEFAULT_THRESHOLDS, HOST_RULE_PREFIX, container_rules, host_rules, validate_thresholds, detect_system_events, system_rules, SYSTEM_RULE_PREFIX, validate_mount_thresholds, validate_helper_events, REBOOT_DETAILS, REBOOT_KEY_PREFIX, detect_container_events, memory_trend_rules, CONTAINER_EVENT_KINDS, MAX_CONTAINER_EVENTS_PER_CHECKIN, MAX_CONTAINER_EVENTS_PER_HOUR, TREND_RULE_PREFIX, NETWORK_EVENT_KINDS, NETWORK_RULE_PREFIX, MAX_NETWORK_EVENTS_PER_CHECKIN, MAX_NETWORK_EVENTS_PER_HOUR, INTERNET_STATUSES, LISTENER_SCOPES, FIREWALL_LABELS, detect_listener_changes, detect_firewall_changes, network_rules, validate_listeners, validate_firewall
+from .rules import HELPER_EVENT_KINDS, DEFAULT_THRESHOLDS, HOST_RULE_PREFIX, container_rules, host_rules, validate_thresholds, detect_system_events, system_rules, SYSTEM_RULE_PREFIX, validate_mount_thresholds, validate_helper_events, REBOOT_DETAILS, REBOOT_KEY_PREFIX, detect_container_events, memory_trend_rules, CONTAINER_EVENT_KINDS, MAX_CONTAINER_EVENTS_PER_CHECKIN, MAX_CONTAINER_EVENTS_PER_HOUR, TREND_RULE_PREFIX, NETWORK_EVENT_KINDS, NETWORK_RULE_PREFIX, MAX_NETWORK_EVENTS_PER_CHECKIN, MAX_NETWORK_EVENTS_PER_HOUR, INTERNET_STATUSES, LISTENER_SCOPES, LISTENER_PROTOCOLS, MAX_LISTENERS, FIREWALL_LABELS, detect_listener_changes, detect_firewall_changes, network_rules, validate_listeners, validate_firewall
from .rate_limit import enforce_ip_limit, enforce_limit, enforce_login_limit, enforce_register_limit, refund_attempt, reset_limits
from ..agent.service import delete_agent_conversation, send_agent_message
@@ -68,11 +73,15 @@ class RegisterRequest(BaseModel):
password: str = Field(max_length=1024)
# Only needed for the very first account; see ensure_bootstrap_token.
bootstrap_token: str | None = Field(default=None, max_length=200)
+ # From an admin's invitation link; lets one person register while registration is closed.
+ invite_token: str | None = Field(default=None, max_length=200)
class LoginRequest(BaseModel):
email: EmailStr
password: str = Field(max_length=1024)
+ # "Keep me signed in for 30 days"; without it the session lasts SESSION_TTL_SECONDS.
+ remember: bool = False
class TwoFactorLoginRequest(BaseModel):
@@ -101,6 +110,8 @@ class PasswordChangeRequest(BaseModel):
class AgentChatRequest(BaseModel):
conversation_id: str = Field(max_length=64)
message: str = Field(max_length=8000)
+ # The incident the question is about; the backend adds what it knows about it for the assistant.
+ incident_id: int | None = Field(default=None, ge=1, le=2**31 - 1)
class ConversationRequest(BaseModel):
@@ -152,12 +163,15 @@ class CollectorRegisterRequest(BaseModel):
hostname: str = Field(max_length=255)
machine_id: str | None = Field(default=None, max_length=64)
os_info: str | None = Field(default=None, max_length=255)
+ details: dict | None = None
join_token: str | None = Field(default=None, max_length=200)
class ApproveRequest(BaseModel):
# Required to approve a request whose machine matches a server that already exists.
replace: bool = False
+ # A name chosen on the dashboard; it then stays, whatever hostname the collector reports.
+ hostname: str | None = Field(default=None, max_length=255)
class AdminSettingsRequest(BaseModel):
@@ -168,6 +182,11 @@ class AdminSettingsRequest(BaseModel):
alert_thresholds: dict | None = None
# Replaces all per-mount disk overrides: {mount: {disk_warning_pct, disk_critical_pct}}.
mount_thresholds: dict | None = None
+ require_2fa_for_everyone: bool | None = None
+ # Kinds of rule that should not open incidents (see incidents.rule_kind), replacing the whole list.
+ disabled_rules: list[str] | None = Field(default=None, max_length=100)
+ # What this install calls itself on the sign-in page and in the sidebar; an empty string goes back to the default.
+ instance_name: str | None = Field(default=None, max_length=200)
class MetricsIngestRequest(BaseModel):
@@ -227,6 +246,22 @@ def cross_site_request(method: str, headers, allowed_origins: list[str]) -> bool
return headers.get("sec-fetch-site") not in (None, "same-origin", "none")
+API_TOKEN_PREFIX = "idk_"
+# The API token a request carried, if any, with its method and path. Checked in _current_user.
+_request_token: contextvars.ContextVar[tuple[str, str, str] | None] = contextvars.ContextVar("request_token", default=None)
+
+
+async def note_api_token(request: Request, call_next):
+ header = request.headers.get("authorization", "")
+ token = header[7:].strip() if header.startswith("Bearer ") else ""
+ marker = _request_token.set((token, request.method, request.url.path) if token.startswith(API_TOKEN_PREFIX) and len(token) <= 100 else None)
+ try:
+ return await call_next(request)
+ finally:
+ _request_token.reset(marker)
+
+
@app.middleware("http")
async def refuse_cross_site_requests(request: Request, call_next):
if cross_site_request(request.method, request.headers, CORS_ORIGINS):
@@ -273,10 +308,13 @@ def startup_event():
("internet_status", "VARCHAR(16)"), ("internet_latency_ms", "INTEGER"), ("collect_duration_ms", "INTEGER"),
):
connection.execute(text(f"ALTER TABLE host_metrics ADD COLUMN IF NOT EXISTS {column} {column_type}"))
- for column, column_type in (("exit_code", "INTEGER"), ("oom_killed", "BOOLEAN"), ("finished_at", "TIMESTAMP WITH TIME ZONE"), ("image_id", "VARCHAR(80)")):
+ for column, column_type in (("exit_code", "INTEGER"), ("oom_killed", "BOOLEAN"), ("finished_at", "TIMESTAMP WITH TIME ZONE"), ("image_id", "VARCHAR(80)"), ("project", "VARCHAR(128)"), ("volumes", "VARCHAR(512)"), ("swap_mb", "DOUBLE PRECISION")):
connection.execute(text(f"ALTER TABLE container_metrics ADD COLUMN IF NOT EXISTS {column} {column_type}"))
connection.execute(text("ALTER TABLE system_events ADD COLUMN IF NOT EXISTS event_key VARCHAR(128)"))
connection.execute(text("ALTER TABLE pending_collectors ADD COLUMN IF NOT EXISTS join_token_id INTEGER REFERENCES join_tokens(id) ON DELETE SET NULL"))
+ connection.execute(text("ALTER TABLE pending_collectors ADD COLUMN IF NOT EXISTS details TEXT"))
+ for column, column_type in (("avg_swap_mb", "DOUBLE PRECISION"), ("n_swap_mb", "INTEGER NOT NULL DEFAULT 0"), ("max_swap_mb", "DOUBLE PRECISION")):
+ connection.execute(text(f"ALTER TABLE container_rollups ADD COLUMN IF NOT EXISTS {column} {column_type}"))
connection.execute(text("CREATE INDEX IF NOT EXISTS ix_system_events_event_key ON system_events (event_key)"))
# Composite indexes that match how the metrics tables are read, then the single-column ones they make
# redundant (and the pointless indexes on each table's own primary key). Safe to repeat. Creating an index
@@ -298,6 +336,11 @@ def startup_event():
connection.execute(text(f"ALTER TABLE users ADD COLUMN IF NOT EXISTS {column} {column_type}"))
connection.execute(text("ALTER TABLE incident_alerts ADD COLUMN IF NOT EXISTS rule_key VARCHAR(255)"))
connection.execute(text("ALTER TABLE incident_alerts ADD COLUMN IF NOT EXISTS resolved_at TIMESTAMP WITH TIME ZONE"))
+ for column, column_type in (("resolution", "VARCHAR(255)"), ("acknowledged_at", "TIMESTAMP WITH TIME ZONE"), ("acknowledged_by", "INTEGER"), ("muted_until", "TIMESTAMP WITH TIME ZONE"),
+ ("notified_at", "TIMESTAMP WITH TIME ZONE"), ("resolve_notified_at", "TIMESTAMP WITH TIME ZONE")):
+ connection.execute(text(f"ALTER TABLE incident_alerts ADD COLUMN IF NOT EXISTS {column} {column_type}"))
+ for column, column_type in (("username", "VARCHAR(64)"), ("avatar_color", "VARCHAR(16)"), ("preferences", "TEXT"), ("last_seen_at", "TIMESTAMP WITH TIME ZONE")):
+ connection.execute(text(f"ALTER TABLE users ADD COLUMN IF NOT EXISTS {column} {column_type}"))
connection.execute(text("CREATE INDEX IF NOT EXISTS ix_incident_alerts_rule_key ON incident_alerts (rule_key)"))
# Alerts from before the alert engine: offline alerts keep going under their rule, the rest were
# duplicated on every check-in with no way to resolve, so close them; the engine re-raises live ones.
@@ -316,6 +359,12 @@ def startup_event():
if "is_dashboard_host" not in columns:
with engine.begin() as connection:
connection.execute(text("ALTER TABLE servers ADD COLUMN is_dashboard_host BOOLEAN NOT NULL DEFAULT FALSE"))
+ if "system_info" not in columns:
+ with engine.begin() as connection:
+ connection.execute(text("ALTER TABLE servers ADD COLUMN system_info TEXT"))
+ if "name_locked" not in columns:
+ with engine.begin() as connection:
+ connection.execute(text("ALTER TABLE servers ADD COLUMN name_locked BOOLEAN NOT NULL DEFAULT FALSE"))
db = SessionLocal()
try:
ensure_admin_exists(db)
@@ -332,6 +381,7 @@ def startup_event():
finally:
db.close()
threading.Thread(target=_offline_watch_loop, name="offline-watch", daemon=True).start()
+ threading.Thread(target=_notify_loop, name="notify", daemon=True).start()
try:
redis_client.ping()
except Exception:
@@ -385,14 +435,55 @@ def _bootstrap_token_valid(db, token: str | None) -> bool:
return bool(setting and token and hmac.compare_digest(setting.value, _hash_secret(token.strip())))
+INSTANCE_NAME_KEY = "instance_name"
+MAX_INSTANCE_NAME = 60
+
+
+def get_instance_name(db) -> str | None:
+ """What this install calls itself: the name set in the admin settings, else "<first admin>'s homelab".
+ None on a new install, which has nobody to name it after."""
+ setting = db.get(AppSetting, INSTANCE_NAME_KEY)
+ if setting and setting.value.strip():
+ return setting.value.strip()
+ owner = db.query(User).filter(User.role == "admin").order_by(User.id).first()
+ first = _printable(owner.name, 40).split()[0].lower() if owner and _printable(owner.name, 40) else ""
+ return f"{first}'s homelab" if first else None
+
+
@app.get("/auth/config")
def auth_config(db=Depends(get_db)):
- return {"registration_enabled": registration_open(db), "bootstrap_required": db.query(User).count() == 0}
+ """What the sign-in pages show before anyone has signed in. Everything here is public by design: keep it to
+ what a visitor may know (see SECURITY.md)."""
+ return {
+ "registration_enabled": registration_open(db), "bootstrap_required": db.query(User).count() == 0,
+ "instance_name": get_instance_name(db), "server_count": db.query(Server).count(), "version": APP_VERSION,
+ }
+
+
+def _valid_invite(db, token: str | None) -> Invite | None:
+ if not token or not 20 <= len(token) <= 200:
+ return None
+ return db.query(Invite).filter(Invite.token_hash == _hash_secret(token.strip()), Invite.used_at.is_(None), Invite.expires_at > datetime.now(timezone.utc)).first()
+
+
[email protected]("/auth/invite")
+def auth_invite(token: Annotated[str, Query(min_length=20, max_length=200)], request: Request, db=Depends(get_db)):
+ """Whether an invitation link still works and who it is for, so the register page can say so."""
+ enforce_ip_limit(redis_client, scope="invite-check", ip_address=_client_ip(request), limit=30, window_seconds=3600)
+ invite = _valid_invite(db, token)
+ if not invite:
+ raise HTTPException(status_code=404, detail="This invitation is no longer valid.")
+ return {"email": invite.email, "role": invite.role}
@app.post("/auth/register")
def auth_register(payload: RegisterRequest, request: Request, response: Response, db=Depends(get_db)):
- if not registration_open(db):
+ invite = _valid_invite(db, payload.invite_token)
+ if payload.invite_token and not invite:
+ raise HTTPException(status_code=403, detail="This invitation is no longer valid. Ask for a new one.")
+ if invite and invite.email != str(payload.email).strip().lower():
+ raise HTTPException(status_code=403, detail="This invitation was made for a different email address.")
+ if not invite and not registration_open(db):
raise HTTPException(status_code=403, detail="Registration is disabled on this server.")
enforce_register_limit(
redis_client,
@@ -411,23 +502,28 @@ def auth_register(payload: RegisterRequest, request: Request, response: Response
email=str(payload.email),
password=payload.password,
admin_requires_two_factor=two_factor_enforced(db),
+ everyone_requires_two_factor=two_factor_required_for(db, "user"),
+ role=invite.role if invite and not first_account else None,
ip=_client_ip(request),
user_agent=request.headers.get("user-agent"),
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+ if invite:
+ invite.used_at = datetime.now(timezone.utc)
+ db.commit()
if first_account:
ensure_bootstrap_token(db) # an account exists now: this removes the token
_set_session_cookie(response, result.pop("session_id"))
return result
-def _set_session_cookie(response: Response, session_id: str) -> None:
+def _set_session_cookie(response: Response, session_id: str, lifetime: int = SESSION_TTL_SECONDS) -> None:
response.set_cookie(
key=SESSION_COOKIE_NAME,
value=session_id,
- max_age=SESSION_TTL_SECONDS,
+ max_age=lifetime,
httponly=True,
secure=SESSION_COOKIE_SECURE,
samesite="lax",
@@ -439,16 +535,18 @@ def _user_payload(user: User, **extra) -> dict:
return {"id": user.id, "name": user.name, "email": user.email, "role": user.role, "is_active": user.is_active, **extra}
-def _complete_login(db, request: Request, response: Response, user: User, how: str = "") -> dict:
+def _complete_login(db, request: Request, response: Response, user: User, how: str = "", remember: bool = False) -> dict:
"""Open the session after every required step has passed.
An administrator without two-factor, while it is required, gets an enrollment session: it can reach
the two-factor setup and nothing else until setup is done.
"""
- stage = STAGE_ENROLLMENT if user.role == "admin" and not user.totp_enabled and two_factor_enforced(db) else STAGE_FULL
- session_id, _public_id = create_session(redis_client, user, stage=stage, ip=_client_ip(request), user_agent=request.headers.get("user-agent"))
- _set_session_cookie(response, session_id)
- record_audit_log(db, user_id=user.id, level="INFO", message=f"User signed in{how}", source="auth")
+ stage = STAGE_ENROLLMENT if not user.totp_enabled and two_factor_required_for(db, user.role) else STAGE_FULL
+ user.last_seen_at = datetime.now(timezone.utc)
+ session_id, _public_id = create_session(redis_client, user, stage=stage, ip=_client_ip(request), user_agent=request.headers.get("user-agent"), remember=remember)
+ # The cookie lasts exactly as long as the session behind it.
+ _set_session_cookie(response, session_id, session_lifetime(stage, remember))
+ record_audit_log(db, user_id=user.id, level="INFO", message=f"User signed in{how}{' (staying signed in for 30 days)' if remember and stage == STAGE_FULL else ''}", source="auth")
return {"user": _user_payload(user), "setup_required": stage == STAGE_ENROLLMENT}
@@ -472,8 +570,8 @@ def auth_login(payload: LoginRequest, request: Request, response: Response, db=D
refund_attempt(redis_client, limit_keys[0])
if user.totp_enabled:
# No session exists until the second step passes; this token only carries the login between the steps.
- return {"status": "two_factor_required", "pending_token": create_pending_two_factor(redis_client, user.id)}
- return _complete_login(db, request, response, user)
+ return {"status": "two_factor_required", "pending_token": create_pending_two_factor(redis_client, user.id, payload.remember)}
+ return _complete_login(db, request, response, user, remember=payload.remember)
def _second_factor_or_error(db, user: User, code: str) -> str:
@@ -504,10 +602,11 @@ def auth_login_two_factor(payload: TwoFactorLoginRequest, request: Request, resp
raise expired
method = _second_factor_or_error(db, user, payload.code)
db.commit() # the code that was just accepted is now spent
+ remember = pending_two_factor_remember(redis_client, payload.pending_token)
delete_pending_two_factor(redis_client, payload.pending_token)
if method == "recovery":
record_audit_log(db, user_id=user.id, level="WARNING", message="A two-factor recovery code was used to sign in", source="auth")
- result = _complete_login(db, request, response, user, " with two-factor")
+ result = _complete_login(db, request, response, user, " with two-factor", remember=remember)
result["recovery_codes_left"] = recovery_codes_left(db, user)
return result
@@ -552,7 +651,7 @@ def two_factor_status(session_id: Annotated[str | None, Cookie(alias=SESSION_COO
session, user = _account_session(session_id, db, allow_limited=True)
return {
"enabled": user.totp_enabled, "available": secrets_box.available(),
- "required": user.role == "admin" and two_factor_enforced(db),
+ "required": two_factor_required_for(db, user.role),
"recovery_codes_left": recovery_codes_left(db, user) if user.totp_enabled else 0,
"setup_required": session["stage"] != STAGE_FULL,
}
@@ -634,7 +733,7 @@ def two_factor_disable(payload: ReauthRequest, request: Request, response: Respo
session, user = _account_session(session_id, db)
if not user.totp_enabled:
raise HTTPException(status_code=409, detail="Two-factor is not turned on.")
- if user.role == "admin" and two_factor_enforced(db):
+ if two_factor_required_for(db, user.role):
raise HTTPException(status_code=403, detail="Two-factor is required for administrators on this server.")
_reauthenticate(db, user, payload.password, payload.code)
user.totp_enabled, user.totp_secret_enc, user.totp_last_step = False, None, None
@@ -709,11 +808,47 @@ def auth_revoke_session(public_id: str, response: Response, session_id: Annotate
return {"status": "ok"}
+_TOKEN_WRITE_PATH = re.compile(r"/incidents/\d{1,10}/(acknowledge|resolve|mute|unmute)")
+_TOKEN_FORBIDDEN = ("/admin", "/auth", "/account", "/agent", "/conversations", "/logs")
+
+
+def _token_user(db) -> dict | None:
+ """The account behind the API token this request carried, if the token is valid for this method and path.
+
+ A read token may only GET; a write token may also acknowledge, resolve and mute incidents. No token reaches
+ the account, admin or chat endpoints, whatever its scope: a leaked token must not be able to mint another
+ one, change a password or spend the provider's quota."""
+ noted = _request_token.get()
+ if not noted:
+ return None
+ token, method, path = noted
+ if path.startswith("/api"):
+ path = path[4:]
+ row = db.query(ApiToken).filter(ApiToken.token_hash == _hash_secret(token)).first()
+ now = datetime.now(timezone.utc)
+ if not row or (row.expires_at and (row.expires_at if row.expires_at.tzinfo else row.expires_at.replace(tzinfo=timezone.utc)) <= now):
+ raise HTTPException(status_code=401, detail="The API token is invalid or has expired.")
+ owner = db.get(User, row.user_id)
+ if not owner or not owner.is_active:
+ raise HTTPException(status_code=401, detail="The API token is invalid or has expired.")
+ allowed = method == "GET" or (row.scope == "write" and method == "POST" and _TOKEN_WRITE_PATH.fullmatch(path))
+ if not allowed or path.startswith(_TOKEN_FORBIDDEN):
+ raise HTTPException(status_code=403, detail="This API token is not allowed to do that.")
+ # Noting each use would be a write on every poll; once a minute is enough to show that it is alive.
+ last = row.last_used_at if row.last_used_at is None or row.last_used_at.tzinfo else row.last_used_at.replace(tzinfo=timezone.utc)
+ if last is None or now - last > timedelta(seconds=60):
+ row.last_used_at = now
+ db.commit()
+ return {"id": owner.id, "name": owner.name, "email": owner.email, "role": owner.role, "stage": STAGE_FULL, "token": row.scope}
+
+
def _current_user(session_id, db):
session = get_session(redis_client, session_id)
if session and session["stage"] != STAGE_FULL:
raise HTTPException(status_code=403, detail="Finish setting up two-factor first.")
user = get_user_from_session(redis_client, session_id)
+ if not user:
+ user = _token_user(db)
if not user:
raise HTTPException(status_code=401, detail="Session is invalid or expired.")
return user
@@ -727,11 +862,19 @@ def _is_admin(db, user_id: int) -> bool:
def _require_admin(session_id, db):
"""Like _current_user, but checks the role in the database rather than the session."""
user = _current_user(session_id, db)
- if not _is_admin(db, user["id"]):
+ if user.get("token") or not _is_admin(db, user["id"]):
raise HTTPException(status_code=403, detail="Admin access required.")
return user
+def _require_operator(session_id, db):
+ """Who may acknowledge, resolve and mute incidents: an admin in the browser, or an admin's write token."""
+ user = _current_user(session_id, db)
+ if not _is_admin(db, user["id"]):
+ raise HTTPException(status_code=403, detail="Only owners and admins can change an incident.")
+ return user
+
+
def ensure_admin_exists(db) -> None:
"""Installs from before roles were enforced have no admin: promote the oldest account."""
if db.query(User).filter(User.role == "admin").first():
@@ -783,6 +926,39 @@ def two_factor_enforced(db) -> bool:
return require_admin_two_factor(db) and secrets_box.available()
+REQUIRE_2FA_EVERYONE_KEY = "require_2fa_for_everyone"
+
+
+def require_two_factor_for_everyone(db) -> bool:
+ setting = db.get(AppSetting, REQUIRE_2FA_EVERYONE_KEY)
+ return setting is not None and setting.value == "true"
+
+
+def two_factor_required_for(db, role: str) -> bool:
+ """Whether an account with this role must have two-factor: admins by default, everyone when the admin says so.
+ Never when enrolment is impossible (no SECRETS_KEY), or nobody could sign in at all."""
+ if not secrets_box.available():
+ return False
+ return require_two_factor_for_everyone(db) or (role == "admin" and require_admin_two_factor(db))
+
+
+DISABLED_RULES_KEY = "disabled_rules"
+
+
+def get_disabled_rules(db) -> set[str]:
+ setting = db.get(AppSetting, DISABLED_RULES_KEY)
+ try:
+ return {kind for kind in json.loads(setting.value) if isinstance(kind, str)} if setting else set()
+ except ValueError:
+ return set()
+
+
+def _enabled_rules(db, firing: dict) -> dict:
+ """``firing`` without the rules an admin switched off; what is left out resolves like a rule that cleared."""
+ disabled = get_disabled_rules(db)
+ return {key: value for key, value in firing.items() if incidents.rule_kind(key) not in disabled} if disabled else firing
+
+
def is_agent_chat_enabled(db) -> bool:
setting = db.get(AppSetting, AGENT_CHAT_ENABLED_KEY)
return setting is None or setting.value == "true"
@@ -808,7 +984,8 @@ def get_mount_thresholds(db) -> dict:
def _admin_settings(db) -> dict:
- return {"metrics_retention_days": get_metrics_retention_days(db), "agent_chat_enabled": is_agent_chat_enabled(db), "alert_thresholds": get_alert_thresholds(db), "mount_thresholds": get_mount_thresholds(db), "require_2fa_for_admins": require_admin_two_factor(db), "secrets_configured": secrets_box.available()}
+ return {"instance_name": get_instance_name(db), "metrics_retention_days": get_metrics_retention_days(db), "agent_chat_enabled": is_agent_chat_enabled(db), "alert_thresholds": get_alert_thresholds(db), "mount_thresholds": get_mount_thresholds(db), "require_2fa_for_admins": require_admin_two_factor(db), "secrets_configured": secrets_box.available(),
+ "require_2fa_for_everyone": require_two_factor_for_everyone(db), "disabled_rules": sorted(get_disabled_rules(db))}
def purge_old_metrics(db, now: datetime | None = None) -> int:
@@ -845,6 +1022,22 @@ def update_admin_settings(payload: AdminSettingsRequest, session_id: Annotated[s
if payload.require_2fa_for_admins is not None and payload.require_2fa_for_admins != require_admin_two_factor(db):
_set_setting(db, REQUIRE_ADMIN_2FA_KEY, "true" if payload.require_2fa_for_admins else "false")
changes.append(f"{'Required' if payload.require_2fa_for_admins else 'Stopped requiring'} two-factor for administrators")
+ if payload.instance_name is not None:
+ name = _printable(payload.instance_name, MAX_INSTANCE_NAME)
+ if payload.instance_name.strip() and (not name or len(payload.instance_name.strip()) > MAX_INSTANCE_NAME):
+ raise HTTPException(status_code=400, detail=f"The name must be printable text of at most {MAX_INSTANCE_NAME} characters.")
+ if name != (get_instance_name(db) or ""):
+ _set_setting(db, INSTANCE_NAME_KEY, name)
+ changes.append(f"Renamed this install to {name}" if name else "Reset this install's name to the default")
+ if payload.require_2fa_for_everyone is not None and payload.require_2fa_for_everyone != require_two_factor_for_everyone(db):
+ _set_setting(db, REQUIRE_2FA_EVERYONE_KEY, "true" if payload.require_2fa_for_everyone else "false")
+ changes.append(f"{'Required' if payload.require_2fa_for_everyone else 'Stopped requiring'} two-factor for everyone")
+ if payload.disabled_rules is not None:
+ known = {row["kind"] for row in RULE_ROWS}
+ wanted = sorted({kind for kind in payload.disabled_rules if kind in known})
+ if set(wanted) != get_disabled_rules(db):
+ _set_setting(db, DISABLED_RULES_KEY, json.dumps(wanted))
+ changes.append("Switched off alert rules: " + (", ".join(wanted) or "none"))
if payload.agent_chat_enabled is not None:
_set_setting(db, AGENT_CHAT_ENABLED_KEY, "true" if payload.agent_chat_enabled else "false")
changes.append(f"{'Enabled' if payload.agent_chat_enabled else 'Disabled'} chat with the agent")
@@ -976,7 +1169,11 @@ def monitoring_overview(session_id: Annotated[str | None, Cookie(alias=SESSION_C
user = _current_user(session_id, db)
# The dashboard's own machine first, then the newest servers.
servers = db.query(Server).order_by(Server.is_dashboard_host.desc(), Server.created_at.desc()).all()
- alert_counts = dict(db.query(IncidentAlert.server_id, func.count()).filter(IncidentAlert.status == "active").group_by(IncidentAlert.server_id).all())
+ unmuted = (IncidentAlert.status == "active", (IncidentAlert.muted_until.is_(None)) | (IncidentAlert.muted_until <= datetime.now(timezone.utc)))
+ alert_counts = dict(db.query(IncidentAlert.server_id, func.count()).filter(*unmuted).group_by(IncidentAlert.server_id).all())
+ severity_counts: dict[int, dict[str, int]] = {}
+ for server_id, severity, count in db.query(IncidentAlert.server_id, IncidentAlert.severity, func.count()).filter(*unmuted).group_by(IncidentAlert.server_id, IncidentAlert.severity):
+ severity_counts.setdefault(server_id, {})[severity] = count
since = datetime.now(timezone.utc) - timedelta(days=7)
events = recent_system_events(db, since)
container_events = recent_container_events(db, since)
@@ -997,28 +1194,40 @@ def monitoring_overview(session_id: Annotated[str | None, Cookie(alias=SESSION_C
"id": server.id, "hostname": server.hostname, "ip_address": server.ip_address, "os_info": server.os_info,
"cpu_cores": server.cpu_cores, "total_ram_gb": server.total_ram_gb,
"check_interval_seconds": server.check_interval_seconds, "is_dashboard_host": server.is_dashboard_host,
- "active_alert_count": alert_counts.get(server.id, 0),
+ "active_alert_count": alert_counts.get(server.id, 0), "alerts_by_severity": severity_counts.get(server.id, {}),
+ "system": _load_json(server.system_info), "created_at": server.created_at.isoformat(),
"last_seen_at": server.last_seen_at.isoformat() if server.last_seen_at else None,
"host": ({key: getattr(metric, key) for key in ("time", "cpu_utilization_pct", "load_1m", "load_5m", "load_15m", "ram_used_gb", "ram_available_gb", "ram_pct", "swap_pct", "disk_usage_pct", "disk_inodes_pct", "net_bytes_sent_mb", "net_bytes_recv_mb", "system_uptime_seconds", "oom_kill_total", "kernel_tainted", "ntp_synced", "reboot_required", "last_shutdown", "docker_status", "docker_reason", "docker_latency_ms", "internet_status", "internet_latency_ms")} if metric else None),
"network": {"listeners": listeners.get(server.id, []), "firewall": firewalls.get(server.id, []), "events": network_events.get(server.id, [])},
"container_events": container_events.get(server.id, []),
"system_events": events.get(server.id, []),
"mounts": [{key: getattr(m, key) for key in ("mount", "fs_type", "total_gb", "used_gb", "used_pct", "inodes_pct")} for m in mounts],
- "containers": [{"container_id": c.container_id, "name": c.name, "image": c.image, "status": c.status, "restart_count": c.restart_count, "cpu_pct": c.cpu_pct, "memory_used_mb": c.memory_used_mb, "memory_pct": c.memory_pct, "healthcheck_status": c.healthcheck_status, "exit_code": c.exit_code, "oom_killed": c.oom_killed, "finished_at": c.finished_at.isoformat() if c.finished_at else None, "time": c.time.isoformat()} for c in latest.values()],
+ "containers": [{"container_id": c.container_id, "name": c.name, "image": c.image, "status": c.status, "restart_count": c.restart_count, "cpu_pct": c.cpu_pct, "memory_used_mb": c.memory_used_mb, "memory_pct": c.memory_pct, "memory_limit_mb": c.memory_limit_mb, "swap_mb": c.swap_mb, "ports": c.ports, "project": c.project, "started_at": c.started_at, "healthcheck_status": c.healthcheck_status, "exit_code": c.exit_code, "oom_killed": c.oom_killed, "finished_at": c.finished_at.isoformat() if c.finished_at else None, "time": c.time.isoformat()} for c in latest.values()],
})
- active_alerts = db.query(IncidentAlert).filter(IncidentAlert.status == "active")
+ active_alerts = db.query(IncidentAlert).filter(*unmuted)
# Most severe first, then newest.
severity_rank = case({severity: rank for rank, severity in enumerate(reversed(SEVERITIES))}, value=IncidentAlert.severity, else_=len(SEVERITIES))
alerts = _spread_alerts(active_alerts.order_by(severity_rank, IncidentAlert.created_at.desc()).limit(OVERVIEW_ALERT_SCAN).all())
hostnames = {server.id: server.hostname for server in servers}
+ servers_by_id = {server.id: server for server in servers}
thresholds = get_alert_thresholds(db)
- pending = visible_pending_collectors(db) if _is_admin(db, user["id"]) else []
+ pending = visible_pending_collectors(db) if _is_admin(db, user["id"]) and not user.get("token") else []
+ totals: dict[str, int] = {}
+ for counts in severity_counts.values():
+ for severity, count in counts.items():
+ totals[severity] = totals.get(severity, 0) + count
return {
- "servers": result, "pending_collectors": pending, "alert_count": active_alerts.count(),
+ "servers": result, "pending_collectors": pending, "alert_count": active_alerts.count(), "alerts_by_severity": totals,
+ "version": APP_VERSION, "instance_name": get_instance_name(db), "server_time": datetime.now(timezone.utc).isoformat(),
+ # Only worked out when nothing needs attention, which is the only time the page shows it.
+ "quiet": dashboard.quiet_summary(db) if not (totals.get(CRITICAL) or totals.get("WARNING")) else None,
# Lets the dashboard color disk bars the same way the alert rules judge them.
"mount_thresholds": get_mount_thresholds(db),
+ # The same limits the alert rules use, so the page's amber and orange mean what an alert would.
+ "alert_thresholds": {key: thresholds[key] for key in ("memory_warning_pct", "memory_critical_pct", "swap_warning_pct")},
"disk_thresholds": {key: thresholds[key] for key in ("disk_warning_pct", "disk_critical_pct", "inodes_warning_pct", "inodes_critical_pct")},
- "alerts": [{"id": a.id, "server_id": a.server_id, "hostname": hostnames.get(a.server_id), "severity": a.severity, "title": a.title, "description": a.description, "created_at": a.created_at.isoformat()} for a in alerts],
+ "alerts": [{"id": a.id, "server_id": a.server_id, "hostname": hostnames.get(a.server_id), "severity": a.severity, "title": a.title, "description": a.description, "rule_key": a.rule_key, "created_at": a.created_at.isoformat(), "reference": incidents.reference(a.id), "acknowledged": a.acknowledged_at is not None,
+ "agent_note": _agent_note(db, a, servers_by_id.get(a.server_id))} for a in alerts],
}
@@ -1050,14 +1259,18 @@ def _wanted_metrics(raw: str | None, allowed: dict, default: tuple[str, ...]) ->
return names
-def _history_response(db, spec, server: Server, key: str | None, range_name: str, wanted: tuple[str, ...]) -> dict:
- result = history_service.history(db, spec, server.id, key, range_name, wanted, server.check_interval_seconds)
- return {"server_id": server.id, **result}
+def _history_response(db, spec, server: Server, key: str | None, range_name: str, wanted: tuple[str, ...], previous: bool = False) -> dict:
+ """``previous`` answers for the period just before the range (the 7 days before the last 7), for comparing."""
+ end = history_service.previous_end(range_name) if previous else None
+ if previous and end is None:
+ raise HTTPException(status_code=422, detail="There is nothing before \"all\" to compare with.")
+ result = history_service.history(db, spec, server.id, key, range_name, wanted, server.check_interval_seconds, now=end)
+ return {"server_id": server.id, "previous": previous, **result}
@app.get("/monitoring/servers/{server_id}/history")
def server_history(
- server_id: PathId, minutes: int = 30, range_name: Annotated[RangeName | None, Query(alias="range")] = None, metrics: str | None = None,
+ server_id: PathId, minutes: int = 30, range_name: Annotated[RangeName | None, Query(alias="range")] = None, metrics: str | None = None, previous: bool = False,
session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db),
):
"""A server's metrics over time.
@@ -1071,12 +1284,55 @@ def server_history(
if not server:
raise HTTPException(status_code=404, detail="Server not found.")
if range_name is not None:
- return _history_response(db, history_service.HOST, server, None, range_name, _wanted_metrics(metrics, history_service.HOST_METRICS, history_service.DEFAULT_HOST_METRICS))
+ return _history_response(db, history_service.HOST, server, None, range_name, _wanted_metrics(metrics, history_service.HOST_METRICS, history_service.DEFAULT_HOST_METRICS), previous)
since = datetime.now(timezone.utc) - timedelta(minutes=max(1, min(minutes, HISTORY_MAX_MINUTES)))
rows = db.query(HostMetric.time, HostMetric.cpu_utilization_pct, HostMetric.ram_pct, HostMetric.disk_usage_pct).filter(HostMetric.server_id == server_id, HostMetric.time >= since).order_by(HostMetric.time).all()
return {"server_id": server_id, "samples": [{"time": row.time.isoformat(), "cpu": row.cpu_utilization_pct, "ram": row.ram_pct, "disk": row.disk_usage_pct} for row in rows]}
[email protected]("/monitoring/servers/{server_id}/live")
+def server_live(server_id: PathId, minutes: int = 30, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """Every check-in of the last ``minutes`` for the server panel's live charts, oldest first. Network figures are
+ running totals; the page turns them into a rate."""
+ _current_user(session_id, db)
+ if not db.query(Server.id).filter(Server.id == server_id).first():
+ raise HTTPException(status_code=404, detail="Server not found.")
+ since = datetime.now(timezone.utc) - timedelta(minutes=max(1, min(minutes, HISTORY_MAX_MINUTES)))
+ rows = db.query(HostMetric.time, HostMetric.cpu_utilization_pct, HostMetric.ram_pct, HostMetric.load_1m, HostMetric.swap_pct, HostMetric.net_bytes_sent_mb, HostMetric.net_bytes_recv_mb).filter(HostMetric.server_id == server_id, HostMetric.time >= since).order_by(HostMetric.time).all()
+ return {"server_id": server_id, "samples": [{"time": row.time.isoformat(), "cpu": row.cpu_utilization_pct, "ram": row.ram_pct, "load": row.load_1m, "swap": row.swap_pct, "net_sent_mb": row.net_bytes_sent_mb, "net_recv_mb": row.net_bytes_recv_mb} for row in rows]}
+
+
+SPARKLINE_MAX_MINUTES = 24 * 60
+EVENTS_MAX_DAYS = 366
+
+
[email protected]("/monitoring/sparklines")
+def monitoring_sparklines(minutes: int = 30, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """Recent CPU use of every server, for the small charts in the fleet rack."""
+ _current_user(session_id, db)
+ return {"minutes": minutes, "servers": dashboard.fleet_sparklines(db, max(1, min(minutes, SPARKLINE_MAX_MINUTES)))}
+
+
[email protected]("/monitoring/servers/{server_id}/containers/sparklines")
+def monitoring_container_sparklines(server_id: PathId, minutes: int = 15, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """Recent CPU use of every container on one server, for the small charts in the container table."""
+ _current_user(session_id, db)
+ if not db.query(Server.id).filter(Server.id == server_id).first():
+ raise HTTPException(status_code=404, detail="Server not found.")
+ return {"minutes": minutes, "containers": dashboard.container_sparklines(db, server_id, max(1, min(minutes, SPARKLINE_MAX_MINUTES)))}
+
+
[email protected]("/monitoring/servers/{server_id}/events")
+def monitoring_server_events(server_id: PathId, days: int = 7, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """One server's timeline: recorded events and alerts opening and clearing, newest first."""
+ _current_user(session_id, db)
+ server = db.query(Server).filter(Server.id == server_id).first()
+ if not server:
+ raise HTTPException(status_code=404, detail="Server not found.")
+ days = max(1, min(days, EVENTS_MAX_DAYS))
+ return {"server_id": server.id, "days": days, "retention_days": get_metrics_retention_days(db), "events": dashboard.server_events(db, server, days)}
+
+
STATS_CACHE_SECONDS = 60
@@ -1100,6 +1356,48 @@ def fleet_statistics(range_name: Annotated[RangeName, Query(alias="range")] = "2
return result
+def _cached_server_stats(db, server_id: int, name: str, range_name: str, build) -> dict:
+ """A per-server statistic, remembered for a minute. Only existing servers and known ranges get this far, so the
+ cache can't grow without limit; a cache problem never breaks the page."""
+ server = db.query(Server).filter(Server.id == server_id).first()
+ if not server:
+ raise HTTPException(status_code=404, detail="Server not found.")
+ cache_key = f"homelab:stats:{name}:{server.id}:{range_name}"
+ try:
+ cached = redis_client.get(cache_key)
+ if cached:
+ return json.loads(cached)
+ except Exception:
+ pass
+ result = build(db, server, range_name)
+ try:
+ redis_client.set(cache_key, json.dumps(result), ex=STATS_CACHE_SECONDS)
+ except Exception:
+ pass
+ return result
+
+
[email protected]("/stats/servers/{server_id}/containers")
+def server_container_usage(server_id: PathId, range_name: Annotated[RangeName, Query(alias="range")] = "24h", session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """Every container of a server over a range, busiest first, for the Statistics page's ranked table."""
+ _current_user(session_id, db)
+ return _cached_server_stats(db, server_id, "containers", range_name, stats.container_usage)
+
+
[email protected]("/stats/servers/{server_id}/busiest")
+def server_busiest_containers(server_id: PathId, range_name: Annotated[RangeName, Query(alias="range")] = "24h", session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """The container using the most CPU in each period of a range, for the timeline's tooltip."""
+ _current_user(session_id, db)
+ return _cached_server_stats(db, server_id, "busiest", range_name, stats.busiest_containers)
+
+
[email protected]("/stats/servers/{server_id}/spikes")
+def server_cpu_spikes(server_id: PathId, range_name: Annotated[RangeName, Query(alias="range")] = "24h", session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """When the server's CPU was at or above 90% and for how long, for the Statistics page's findings."""
+ _current_user(session_id, db)
+ return _cached_server_stats(db, server_id, "spikes", range_name, stats.cpu_spikes)
+
+
@app.get("/stats/servers/{server_id}/heatmap")
def server_heatmap(
server_id: PathId, metric: Literal["cpu", "ram"] = "cpu", offset: Annotated[int, Query(ge=-stats.MAX_OFFSET_MINUTES, le=stats.MAX_OFFSET_MINUTES)] = 0,
@@ -1145,7 +1443,7 @@ def mount_history(
@app.get("/monitoring/servers/{server_id}/containers/{container_id}/history")
def container_history(
- server_id: PathId, container_id: Annotated[str, PathParam(min_length=1, max_length=128)], range_name: Annotated[RangeName, Query(alias="range")] = "24h", metrics: str | None = None,
+ server_id: PathId, container_id: Annotated[str, PathParam(min_length=1, max_length=128)], range_name: Annotated[RangeName, Query(alias="range")] = "24h", metrics: str | None = None, previous: bool = False,
session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db),
):
"""One container's CPU and memory over time."""
@@ -1154,7 +1452,7 @@ def container_history(
if not server:
raise HTTPException(status_code=404, detail="Server or container not found.")
wanted = _wanted_metrics(metrics, history_service.CONTAINER_METRICS, ("cpu", "memory_mb", "memory_pct", "memory_limit_mb"))
- result = _history_response(db, history_service.CONTAINER, server, container_id, range_name, wanted)
+ result = _history_response(db, history_service.CONTAINER, server, container_id, range_name, wanted, previous)
if result["data_since"] is None:
raise HTTPException(status_code=404, detail="Server or container not found.")
name = db.query(ContainerMetric.name).filter(ContainerMetric.server_id == server.id, ContainerMetric.container_id == container_id).order_by(ContainerMetric.time.desc()).limit(1).scalar()
@@ -1193,6 +1491,8 @@ def container_detail(server_id: PathId, container_id: str, limit: int = 60, sess
"image": latest.image,
"started_at": latest.started_at,
"ports": latest.ports,
+ "volumes": latest.volumes,
+ "project": latest.project,
"latest": {"time": latest.time.isoformat(), **{field: getattr(latest, field) for field in CONTAINER_DETAIL_FIELDS}},
"history": [{"time": s.time.isoformat(), **{field: getattr(s, field) for field in CONTAINER_DETAIL_FIELDS}} for s in reversed(samples)],
}
@@ -1352,10 +1652,13 @@ def register_collector(payload: CollectorRegisterRequest, request: Request, db=D
raise HTTPException(status_code=503, detail="Too many servers are waiting for approval.")
secret = secrets.token_urlsafe(32)
code = "".join(secrets.choice(PAIRING_ALPHABET) for _ in range(6))
+ details = _clean_registration_details(payload.details)
+ # Only the stack's own collector, coming in through the internal listener, can be "this machine" (see ingest_metrics).
+ details["dashboard_host"] = details.get("dashboard_host") is True and via in ("internal", "")
pending = PendingCollector(
poll_secret_hash=_hash_secret(secret), pairing_code=f"{code[:3]}-{code[3:]}", hostname=hostname,
machine_id=machine_id, ip_address=ip_address[:64], os_info=(payload.os_info or "")[:255] or None,
- join_token_id=join_token.id if join_token else None,
+ join_token_id=join_token.id if join_token else None, details=json.dumps(details),
)
db.add(pending)
db.commit()
@@ -1403,11 +1706,17 @@ def approve_pending_collector(pending_id: PathId, payload: ApproveRequest | None
if server and not (payload and payload.replace):
# Approving mints new credentials for that server and locks out its current collector, so never do it silently.
raise HTTPException(status_code=409, detail=f"This machine matches the existing server {server.hostname}. Approving replaces that server's credentials and signs its current collector out. Confirm to continue.")
+ chosen = _hostname_or_error(payload.hostname) if payload and payload.hostname and payload.hostname.strip() else None
+ if chosen and _hostname_in_use(db, chosen, excluding=server.id if server else None):
+ raise HTTPException(status_code=409, detail=f"Another server is already called {chosen}. Pick a different name.")
if not server:
_ensure_server_capacity(db)
- server = Server(owner_id=user["id"], hostname=_unique_hostname(db, _clean_hostname(pending.hostname) or "unnamed server"), machine_id=pending.machine_id, ip_address=pending.ip_address, os_info=pending.os_info)
+ server = Server(owner_id=user["id"], hostname=chosen or _unique_hostname(db, _clean_hostname(pending.hostname) or "unnamed server"), machine_id=pending.machine_id, ip_address=pending.ip_address, os_info=pending.os_info)
db.add(server)
db.flush()
+ # A name that differs from what the machine calls itself was chosen on purpose, so it is kept.
+ if chosen and _name_key(chosen) != _name_key(_clean_hostname(pending.hostname) or ""):
+ server.hostname, server.name_locked = chosen, True
pending.status = "approved"
pending.approved_server_id = server.id
if pending.join_token_id:
@@ -1436,7 +1745,7 @@ def visible_pending_collectors(db, now: datetime | None = None) -> list[dict]:
existing = _server_for_machine(db, row.machine_id)
visible.append({
"id": row.id, "hostname": row.hostname, "pairing_code": row.pairing_code, "ip_address": row.ip_address, "os_info": row.os_info, "status": row.status, "created_at": row.created_at.isoformat(),
- "verified": row.join_token_id is not None,
+ "verified": row.join_token_id is not None, "details": _load_json(row.details),
"replaces": {"id": existing.id, "hostname": existing.hostname} if existing else None,
})
return visible
@@ -1461,6 +1770,8 @@ def mark_offline_servers(db, now: datetime | None = None) -> int:
"""Raise one active alert per server that has missed several check-ins."""
now = now or datetime.now(timezone.utc)
raised = 0
+ if SERVER_OFFLINE_RULE in get_disabled_rules(db):
+ return 0
for server in db.query(Server).filter(Server.last_seen_at.isnot(None)).all():
last_seen = server.last_seen_at if server.last_seen_at.tzinfo else server.last_seen_at.replace(tzinfo=timezone.utc)
if now - last_seen < timedelta(seconds=server.check_interval_seconds * OFFLINE_AFTER_MISSED_CHECKS):
@@ -1604,8 +1915,8 @@ MAX_CONTAINERS_PER_CHECKIN = 500
# Names end up inside incident keys (255 characters, with a prefix and suffix), so they are kept well under that.
MAX_CONTAINER_NAME = 128
_IMAGE_ID = re.compile(r"sha256:[0-9a-f]{64}")
-_CONTAINER_FLOATS = ("cpu_pct", "memory_used_mb", "memory_pct", "memory_limit_mb", "net_rx_mb", "net_tx_mb", "block_read_mb", "block_write_mb")
-_CONTAINER_TEXT = {"image": 255, "started_at": 64, "ports": 512, "healthcheck_status": 64}
+_CONTAINER_FLOATS = ("cpu_pct", "memory_used_mb", "memory_pct", "memory_limit_mb", "net_rx_mb", "net_tx_mb", "block_read_mb", "block_write_mb", "swap_mb")
+_CONTAINER_TEXT = {"image": 255, "started_at": 64, "ports": 512, "healthcheck_status": 64, "project": 128, "volumes": 512}
def _printable(text: str, limit: int) -> str:
@@ -1735,7 +2046,7 @@ def _apply_server_fields(db, server: Server, reported: dict) -> None:
alert titles.
"""
hostname = reported.get("hostname")
- if isinstance(hostname, str) and (name := _clean_hostname(hostname)):
+ if not server.name_locked and isinstance(hostname, str) and (name := _clean_hostname(hostname)):
if not _hostname_in_use(db, name, excluding=server.id):
server.hostname = name
address = reported.get("ip_address")
@@ -1751,6 +2062,122 @@ def _apply_server_fields(db, server: Server, reported: dict) -> None:
server.cpu_cores = cores
if (ram := _finite_number(reported.get("total_ram_gb"), 0, 1e6)) is not None:
server.total_ram_gb = ram
+ if isinstance(reported.get("system"), dict):
+ server.system_info = json.dumps(_clean_system_info(reported["system"]), separators=(",", ":"))
+
+
+_SYSTEM_TEXT = {"kernel": 64, "arch": 16, "cpu_model": 128, "timezone": 64, "time_service": 32, "collector_version": 16, "docker_version": 32, "reboot_kernel": 64, "updates_manager": 16}
+_SYSTEM_NUMBERS = {"swap_total_gb": (0, 1e6), "clock_offset_ms": (-1e9, 1e9), "updates_checked_at": (0, 1e11), "updates_applied_at": (0, 1e11)}
+_SYSTEM_COUNTS = {"updates_pending": 100_000, "updates_security": 100_000, "disk_io_errors": INT_MAX}
+_DOCKER_DISK_SIZES = ("images_gb", "images_unused_gb", "build_cache_gb", "build_cache_unused_gb")
+_SYSTEM_FLAGS = ("auto_updates", "helper_installed")
+MAX_INTERFACES = 16
+MAX_TEMPERATURES = 8
+
+
+def _clean_system_info(raw: dict) -> dict:
+ """The machine facts a collector reported, reduced to known keys of the right type and size.
+
+ Like everything else from a collector this is untrusted: it is stored as JSON and sent to every browser, so
+ unknown keys are dropped, text is made printable and bounded, and numbers are range-checked.
+ """
+ clean: dict = {}
+ for key, limit in _SYSTEM_TEXT.items():
+ if isinstance(raw.get(key), str) and (value := _printable(raw[key], limit)):
+ clean[key] = value
+ for key, (low, high) in _SYSTEM_NUMBERS.items():
+ if (number := _finite_number(raw.get(key), low, high)) is not None:
+ clean[key] = number
+ for key, high in _SYSTEM_COUNTS.items():
+ if (count := _whole_number(raw.get(key), 0, high)) is not None:
+ clean[key] = count
+ for key in _SYSTEM_FLAGS:
+ if isinstance(raw.get(key), bool):
+ clean[key] = raw[key]
+ temperatures = []
+ for item in raw["temperatures"][:MAX_TEMPERATURES] if isinstance(raw.get("temperatures"), list) else []:
+ if isinstance(item, dict) and isinstance(item.get("label"), str) and (label := _printable(item["label"], 32)) and (celsius := _finite_number(item.get("celsius"), -50, 200)) is not None:
+ temperatures.append({"label": label, "celsius": celsius})
+ clean["temperatures"] = temperatures
+ interfaces = []
+ for item in raw["interfaces"][:MAX_INTERFACES] if isinstance(raw.get("interfaces"), list) else []:
+ if not isinstance(item, dict) or not isinstance(item.get("name"), str) or not (name := _printable(item["name"], 16)):
+ continue
+ entry: dict = {"name": name}
+ if isinstance(item.get("network"), str):
+ try:
+ entry["network"] = str(ipaddress.ip_network(item["network"].strip(), strict=False))
+ except ValueError:
+ pass
+ for key in ("rx_mbps", "tx_mbps"):
+ if (rate := _finite_number(item.get(key), 0, 1e6)) is not None:
+ entry[key] = rate
+ if (speed := _whole_number(item.get("speed_mbit"), 1, 10_000_000)) is not None:
+ entry["speed_mbit"] = speed
+ interfaces.append(entry)
+ clean["interfaces"] = interfaces
+ devices = {}
+ for mount, device in list(raw["mount_devices"].items())[:MAX_MOUNTS_PER_CHECKIN] if isinstance(raw.get("mount_devices"), dict) else []:
+ if isinstance(mount, str) and isinstance(device, str) and (mount_name := _printable(mount, MAX_MOUNT_NAME)) and (device_name := _printable(device, 64)):
+ devices[mount_name] = device_name
+ clean["mount_devices"] = devices
+ allowed = []
+ for item in raw["firewall_allowed"][:MAX_LISTENERS] if isinstance(raw.get("firewall_allowed"), list) else []:
+ if isinstance(item, dict) and item.get("proto") in LISTENER_PROTOCOLS and item.get("file") in FIREWALL_LABELS and (port := _whole_number(item.get("port"), 1, 65535)) is not None:
+ allowed.append({"proto": item["proto"], "port": port, "file": item["file"]})
+ clean["firewall_allowed"] = allowed
+ if isinstance(raw.get("docker_disk"), dict):
+ disk = {key: size for key in _DOCKER_DISK_SIZES if (size := _finite_number(raw["docker_disk"].get(key), 0, 1e9)) is not None}
+ for key in ("images", "images_unused"):
+ if (count := _whole_number(raw["docker_disk"].get(key), 0, 10_000_000)) is not None:
+ disk[key] = count
+ if disk:
+ clean["docker_disk"] = disk
+ # None means the port-owners helper isn't running there; a list (even an empty one) means it is.
+ if isinstance(raw.get("listener_owners"), list):
+ owners = []
+ for item in raw["listener_owners"][:MAX_LISTENERS]:
+ if isinstance(item, dict) and item.get("proto") in LISTENER_PROTOCOLS and (port := _whole_number(item.get("port"), 1, 65535)) is not None and isinstance(item.get("process"), str) and (process := _printable(item["process"], 64)):
+ owners.append({"proto": item["proto"], "port": port, "process": process})
+ clean["listener_owners"] = owners
+ return clean
+
+
+def _clean_registration_details(raw: dict | None) -> dict:
+ """What a collector asking to join says it found on its machine; shown to an admin, so checked like the rest."""
+ if not isinstance(raw, dict):
+ return {}
+ clean: dict = {}
+ for key, high in (("cpu_cores", 4096), ("containers", 100_000), ("mounts", 1000)):
+ if (count := _whole_number(raw.get(key), 0, high)) is not None:
+ clean[key] = count
+ for key in ("helper_installed", "dashboard_host"):
+ if isinstance(raw.get(key), bool):
+ clean[key] = raw[key]
+ return clean
+
+
+PACKAGES_UPDATED_KIND = "packages_updated"
+
+
+def packages_updated_detail(before: dict, after: dict) -> str | None:
+ """A sentence for the event log when a machine's package manager has installed updates since the last check-in
+ (its log file is newer), or None. The count is how far the pending number fell, when both are known."""
+ was, now = before.get("updates_applied_at"), after.get("updates_applied_at")
+ if not isinstance(was, (int, float)) or not isinstance(now, (int, float)) or now <= was + 1:
+ return None
+ manager = after.get("updates_manager") or "the package manager"
+ fell = (before.get("updates_pending") or 0) - (after.get("updates_pending") or 0) if isinstance(before.get("updates_pending"), int) and isinstance(after.get("updates_pending"), int) else 0
+ what = f"{fell} {'package' if fell == 1 else 'packages'} updated by {manager}" if fell > 0 else f"Packages installed or updated by {manager}"
+ return what + (f", kernel {after['reboot_kernel']} waiting for reboot" if after.get("reboot_kernel") and after.get("reboot_kernel") != before.get("reboot_kernel") else "")
+
+
+def _load_json(text_value: str | None) -> dict:
+ try:
+ loaded = json.loads(text_value) if text_value else {}
+ except ValueError:
+ return {}
+ return loaded if isinstance(loaded, dict) else {}
ENROLL_RATE_WINDOW_SECONDS = 3600
@@ -1920,7 +2347,10 @@ def ingest_metrics(payload: MetricsIngestRequest, authorization: Annotated[str |
else:
_require_admin(session_id, db)
_enforce_ingest_spacing(server)
+ updates_before = _load_json(server.system_info)
_apply_server_fields(db, server, payload.server)
+ if detail := packages_updated_detail(updates_before, _load_json(server.system_info)):
+ db.add(SystemEvent(server_id=server.id, time=datetime.now(timezone.utc), kind=PACKAGES_UPDATED_KIND, detail=detail))
# Only the stack's own collector, which reaches the backend through the gate's internal listener, may claim to
# be the dashboard's machine; a collector coming in over the VPN can't take that place. (With a single
# listener, in the development stack, there is no way to tell, so the claim is accepted.)
@@ -1958,12 +2388,12 @@ def ingest_metrics(payload: MetricsIngestRequest, authorization: Annotated[str |
record_capped_events(db, server.id, network_events, NETWORK_EVENT_KINDS, "network_notice", "network changes", now, MAX_NETWORK_EVENTS_PER_CHECKIN, MAX_NETWORK_EVENTS_PER_HOUR)
db.flush() # the rules read this check-in back from the history tables
thresholds = get_alert_thresholds(db)
- sync_alerts(db, server.id, HOST_RULE_PREFIX, host_rules(db, server, thresholds, active_rule_keys(db, server.id, HOST_RULE_PREFIX), get_mount_thresholds(db)))
- sync_alerts(db, server.id, SYSTEM_RULE_PREFIX, system_rules(db, server, thresholds, now, active_rule_keys(db, server.id, SYSTEM_RULE_PREFIX)))
- sync_alerts(db, server.id, NETWORK_RULE_PREFIX, network_rules(db, server, thresholds, now))
+ sync_alerts(db, server.id, HOST_RULE_PREFIX, _enabled_rules(db, host_rules(db, server, thresholds, active_rule_keys(db, server.id, HOST_RULE_PREFIX), get_mount_thresholds(db))))
+ sync_alerts(db, server.id, SYSTEM_RULE_PREFIX, _enabled_rules(db, system_rules(db, server, thresholds, now, active_rule_keys(db, server.id, SYSTEM_RULE_PREFIX))))
+ sync_alerts(db, server.id, NETWORK_RULE_PREFIX, _enabled_rules(db, network_rules(db, server, thresholds, now)))
# The collector sends no containers when Docker is unreachable; keep container alerts as they are rather than resolving them all.
if containers:
- sync_alerts(db, server.id, CONTAINER_RULE_PREFIX, container_rules(db, server.id, containers, thresholds, now))
+ sync_alerts(db, server.id, CONTAINER_RULE_PREFIX, _enabled_rules(db, container_rules(db, server.id, containers, thresholds, now)))
server.last_seen_at = now
resolve_alerts(db, server.id, [SERVER_OFFLINE_RULE])
db.commit()
@@ -2111,7 +2541,7 @@ def agent_chat(payload: AgentChatRequest, session_id: Annotated[str | None, Cook
response_text = send_agent_message(
user["id"],
payload.conversation_id,
- message,
+ _incident_context(db, payload.incident_id) + message,
command_logger=lambda event: record_audit_log(
db,
user_id=user["id"],
@@ -2158,6 +2588,577 @@ def agent_chat(payload: AgentChatRequest, session_id: Annotated[str | None, Cook
return {"message": response_text}
+# ---------------------------------------------------------------------------------------------------------
+# Incidents (the Agent page)
+
+def _agent_note(db, alert: IncidentAlert, server: Server | None) -> str | None:
+ """The one line the Overview shows next to an incident, from its diagnosis. Remembered for a minute: the
+ Overview is polled every few seconds and working it out reads samples."""
+ if server is None:
+ return None
+ key = f"homelab:incident-note:{alert.id}"
+ try:
+ cached = redis_client.get(key)
+ if cached is not None:
+ return (cached.decode() if isinstance(cached, bytes) else cached) or None
+ except Exception:
+ pass
+ note = incidents.diagnose(db, alert, server).get("note")
+ try:
+ redis_client.set(key, note or "", ex=60)
+ except Exception:
+ pass
+ return note
+
+
+def _incident_context(db, incident_id: int | None) -> str:
+ """What Infradeck knows about an incident, put in front of a chat question about it. Built here from stored
+ data, never from what the browser sent."""
+ alert = db.get(IncidentAlert, incident_id) if incident_id else None
+ server = db.get(Server, alert.server_id) if alert else None
+ if not alert or not server:
+ return ""
+ found = incidents.diagnose(db, alert, server)
+ facts = [f"- {signal['text']}" for signal in found["signals"]] + [f"- {line['text']}" for line in found["lines"][-6:]]
+ return (f"[INCIDENT {incidents.reference(alert.id)} on {server.hostname}, {alert.severity.lower()}, {alert.status}]\n{alert.title}\n{alert.description}\n"
+ + ("\n".join(facts) + "\n" if facts else "") + "[QUESTION]\n")
+
+
+class MuteRequest(BaseModel):
+ minutes: int = Field(default=60, ge=5, le=7 * 24 * 60)
+
+
+def _incident_or_404(db, incident_id: int) -> tuple[IncidentAlert, Server]:
+ alert = db.get(IncidentAlert, incident_id)
+ server = db.get(Server, alert.server_id) if alert else None
+ if not alert or not server:
+ raise HTTPException(status_code=404, detail="Incident not found.")
+ return alert, server
+
+
[email protected]("/incidents")
+def list_incidents(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ user = _current_user(session_id, db)
+ return {**incidents.inbox(db), "can_act": _is_admin(db, user["id"])}
+
+
[email protected]("/incidents/{incident_id}")
+def get_incident(incident_id: PathId, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ _current_user(session_id, db)
+ alert, server = _incident_or_404(db, incident_id)
+ users = dict(db.query(User.id, User.name).all())
+ return {**incidents.summary(alert, server.hostname, datetime.now(timezone.utc), users), "diagnosis": incidents.diagnose(db, alert, server), "cpu_cores": server.cpu_cores}
+
+
+def _incident_action(db, incident_id: int, session_id, change, message: str) -> dict:
+ user = _require_operator(session_id, db)
+ alert, server = _incident_or_404(db, incident_id)
+ change(alert, user)
+ db.commit()
+ record_audit_log(db, user_id=user["id"], level="INFO", message=f"{message} {incidents.reference(alert.id)} ({alert.title})"[:255], source="incidents")
+ return incidents.summary(alert, server.hostname, datetime.now(timezone.utc), dict(db.query(User.id, User.name).all()))
+
+
[email protected]("/incidents/{incident_id}/acknowledge")
+def acknowledge_incident(incident_id: PathId, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ def change(alert, user):
+ alert.acknowledged_at, alert.acknowledged_by = datetime.now(timezone.utc), user["id"]
+ return _incident_action(db, incident_id, session_id, change, "Acknowledged")
+
+
[email protected]("/incidents/{incident_id}/resolve")
+def resolve_incident(incident_id: PathId, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """Close an incident by hand. If the rule behind it is still firing at the next check-in, a new one opens."""
+ def change(alert, user):
+ if alert.status != "active":
+ raise HTTPException(status_code=409, detail="This incident is already resolved.")
+ alert.status, alert.resolved_at, alert.resolution = "resolved", datetime.now(timezone.utc), f"Marked resolved by {user['name']}"[:255]
+ return _incident_action(db, incident_id, session_id, change, "Marked resolved")
+
+
[email protected]("/incidents/{incident_id}/mute")
+def mute_incident(incident_id: PathId, payload: MuteRequest | None = None, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ minutes = (payload or MuteRequest()).minutes
+
+ def change(alert, user):
+ alert.muted_until = datetime.now(timezone.utc) + timedelta(minutes=minutes)
+ return _incident_action(db, incident_id, session_id, change, f"Muted for {minutes} min")
+
+
[email protected]("/incidents/{incident_id}/unmute")
+def unmute_incident(incident_id: PathId, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ def change(alert, user):
+ alert.muted_until = None
+ return _incident_action(db, incident_id, session_id, change, "Unmuted")
+
+
+# ---------------------------------------------------------------------------------------------------------
+# The account page: profile, preferences, API tokens, notification channels
+
+_USERNAME = re.compile(r"[a-z0-9][a-z0-9._-]{1,31}")
+_COLOR = re.compile(r"#[0-9a-fA-F]{6}")
+_CLOCK = re.compile(r"([01]\d|2[0-3]):[0-5]\d")
+DISPLAY_CHOICES = {"time_format": ("24h", "12h"), "sizes": ("GB", "GiB"), "theme": ("dark", "light", "system"), "density": ("comfortable", "compact"), "open_on": ("overview", "statistics", "agent")}
+DISPLAY_DEFAULTS = {"time_format": "24h", "sizes": "GB", "theme": "dark", "density": "comfortable", "open_on": "overview", "timezone": ""}
+
+
+class ProfileRequest(BaseModel):
+ name: str | None = Field(default=None, max_length=255)
+ username: str | None = Field(default=None, max_length=64)
+ avatar_color: str | None = Field(default=None, max_length=16)
+
+
+class PreferencesRequest(BaseModel):
+ display: dict | None = None
+ routing: dict | None = None
+ quiet: dict | None = None
+
+
+class TokenRequest(BaseModel):
+ name: str = Field(min_length=1, max_length=64)
+ scope: Literal["read", "write"] = "read"
+ expires_in_days: int | None = Field(default=None, ge=1, le=3650)
+
+
+class ChannelRequest(BaseModel):
+ kind: Literal["ntfy", "discord", "webhook", "email"]
+ target: str | None = Field(default=None, max_length=500)
+
+
+def _preferences(user: User) -> dict:
+ stored = _load_json(user.preferences)
+ display = {**DISPLAY_DEFAULTS, **{key: value for key, value in (stored.get("display") or {}).items() if key in DISPLAY_DEFAULTS}}
+ quiet = {"enabled": False, "start": "23:00", "end": "07:00", **(stored.get("quiet") if isinstance(stored.get("quiet"), dict) else {})}
+ return {"display": display, "routing": stored.get("routing") if isinstance(stored.get("routing"), dict) else {}, "quiet": quiet}
+
+
+def _owner_id(db) -> int | None:
+ return db.query(func.min(User.id)).filter(User.role == "admin").scalar()
+
+
+def _role_name(db, user: User) -> str:
+ return "Owner" if user.id == _owner_id(db) else "Admin" if user.role == "admin" else "Viewer"
+
+
+def _channel_payload(channel: NotificationChannel) -> dict:
+ return {"id": channel.id, "kind": channel.kind, "display": channel.display, "last_ok": channel.last_ok, "last_status": channel.last_status,
+ "last_checked_at": channel.last_checked_at.isoformat() if channel.last_checked_at else None}
+
+
+def _token_payload(token: ApiToken) -> dict:
+ return {"id": token.id, "name": token.name, "scope": token.scope, "hint": token.hint, "created_at": token.created_at.isoformat(),
+ "last_used_at": token.last_used_at.isoformat() if token.last_used_at else None, "expires_at": token.expires_at.isoformat() if token.expires_at else None}
+
+
[email protected]("/account")
+def get_account(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db)
+ return {
+ "id": user.id, "name": user.name, "username": user.username, "email": user.email, "role": user.role, "role_name": _role_name(db, user), "avatar_color": user.avatar_color,
+ "created_at": user.created_at.isoformat(), "password_changed_at": user.password_changed_at.isoformat() if user.password_changed_at else None,
+ "two_factor": {"enabled": user.totp_enabled, "available": secrets_box.available(), "required": two_factor_required_for(db, user.role), "recovery_codes_left": recovery_codes_left(db, user) if user.totp_enabled else 0},
+ "preferences": _preferences(user), "session_days": round(auth.REMEMBER_SESSION_TTL_SECONDS / 86400),
+ "tokens": [_token_payload(token) for token in db.query(ApiToken).filter(ApiToken.user_id == user.id).order_by(ApiToken.created_at)],
+ "channels": [_channel_payload(channel) for channel in db.query(NotificationChannel).filter(NotificationChannel.user_id == user.id).order_by(NotificationChannel.id)],
+ "smtp_configured": notify.smtp_configured(), "secrets_configured": secrets_box.available(),
+ }
+
+
[email protected]("/account/profile")
+def update_profile(payload: ProfileRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db)
+ if payload.name is not None:
+ name = _printable(payload.name, 255)
+ if not name:
+ raise HTTPException(status_code=400, detail="The display name can't be empty.")
+ user.name = name
+ if payload.username is not None:
+ username = payload.username.strip().lower()
+ if username and not _USERNAME.fullmatch(username):
+ raise HTTPException(status_code=400, detail="A username is 2 to 32 lowercase letters, digits, dots, dashes or underscores.")
+ if username and db.query(User.id).filter(User.username == username, User.id != user.id).first():
+ raise HTTPException(status_code=409, detail="That username is taken.")
+ user.username = username or None
+ if payload.avatar_color is not None:
+ if payload.avatar_color and not _COLOR.fullmatch(payload.avatar_color):
+ raise HTTPException(status_code=400, detail="The color must look like #A1B2C3.")
+ user.avatar_color = payload.avatar_color or None
+ db.commit()
+ return get_account(session_id, db)
+
+
[email protected]("/account/preferences")
+def update_preferences(payload: PreferencesRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """Display and notification choices. Everything is checked against a fixed list; unknown keys are dropped."""
+ session, user = _account_session(session_id, db)
+ current = _preferences(user)
+ if payload.display is not None:
+ for key, choices in DISPLAY_CHOICES.items():
+ if payload.display.get(key) in choices:
+ current["display"][key] = payload.display[key]
+ zone = payload.display.get("timezone")
+ if isinstance(zone, str) and len(zone) <= 64:
+ try:
+ notify.ZoneInfo(zone) if zone else None
+ current["display"]["timezone"] = zone
+ except (notify.ZoneInfoNotFoundError, ValueError):
+ raise HTTPException(status_code=400, detail="That time zone is not known.")
+ if payload.routing is not None:
+ own = {str(channel_id) for (channel_id,) in db.query(NotificationChannel.id).filter(NotificationChannel.user_id == user.id)}
+ current["routing"] = {event: {channel: bool(on) for channel, on in (payload.routing.get(event) or {}).items() if channel in own} for event in notify.EVENTS if isinstance(payload.routing.get(event), dict)}
+ if payload.quiet is not None:
+ start, end = payload.quiet.get("start"), payload.quiet.get("end")
+ if not (isinstance(start, str) and isinstance(end, str) and _CLOCK.fullmatch(start) and _CLOCK.fullmatch(end)):
+ raise HTTPException(status_code=400, detail="Quiet hours need a start and an end like 23:00.")
+ current["quiet"] = {"enabled": payload.quiet.get("enabled") is True, "start": start, "end": end}
+ user.preferences = json.dumps(current, separators=(",", ":"))
+ db.commit()
+ return current
+
+
+MAX_TOKENS_PER_USER = 20
+
+
[email protected]("/account/tokens")
+def create_api_token(payload: TokenRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db)
+ name = _printable(payload.name, 64)
+ if not name:
+ raise HTTPException(status_code=400, detail="Give the token a name.")
+ if payload.scope == "write" and user.role != "admin":
+ raise HTTPException(status_code=403, detail="Only owners and admins can create a token that acknowledges incidents.")
+ if db.query(ApiToken).filter(ApiToken.user_id == user.id).count() >= MAX_TOKENS_PER_USER:
+ raise HTTPException(status_code=400, detail="Revoke a token you no longer use first.")
+ secret = f"{API_TOKEN_PREFIX}{'w' if payload.scope == 'write' else 'r'}_{secrets.token_urlsafe(32)}"
+ token = ApiToken(user_id=user.id, name=name, scope=payload.scope, token_hash=_hash_secret(secret), hint=secret[-4:],
+ expires_at=datetime.now(timezone.utc) + timedelta(days=payload.expires_in_days) if payload.expires_in_days else None)
+ db.add(token)
+ db.commit()
+ record_audit_log(db, user_id=user.id, level="INFO", message=f"Created API token {name} ({payload.scope})", source="auth")
+ return {**_token_payload(token), "token": secret}
+
+
[email protected]("/account/tokens/{token_id}")
+def revoke_api_token(token_id: PathId, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db)
+ token = db.query(ApiToken).filter(ApiToken.id == token_id, ApiToken.user_id == user.id).first()
+ if not token:
+ raise HTTPException(status_code=404, detail="Token not found.")
+ name = token.name
+ db.delete(token)
+ db.commit()
+ record_audit_log(db, user_id=user.id, level="INFO", message=f"Revoked API token {name}", source="auth")
+ return {"status": "ok"}
+
+
[email protected]("/account/channels")
+def add_channel(payload: ChannelRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db)
+ if not secrets_box.available():
+ raise HTTPException(status_code=503, detail="Channels can't be saved on this server yet: it has no SECRETS_KEY to encrypt their addresses with.")
+ if db.query(NotificationChannel).filter(NotificationChannel.user_id == user.id).count() >= notify.MAX_CHANNELS_PER_USER:
+ raise HTTPException(status_code=400, detail="Remove a channel you no longer use first.")
+ if payload.kind == "email":
+ if not notify.smtp_configured():
+ raise HTTPException(status_code=400, detail="Email isn't set up on this server. An admin needs to set SMTP_HOST and SMTP_FROM in .env.")
+ if db.query(NotificationChannel).filter(NotificationChannel.user_id == user.id, NotificationChannel.kind == "email").first():
+ raise HTTPException(status_code=409, detail="Email is already one of your channels.")
+ target, display = user.email, user.email # only ever the account's own address
+ else:
+ try:
+ target, display = notify.check_url(payload.target or "", allow_private=user.role == "admin")
+ except notify.ChannelError as error:
+ raise HTTPException(status_code=400, detail=str(error)) from error
+ channel = NotificationChannel(user_id=user.id, kind=payload.kind, target_enc=secrets_box.encrypt(target), display=display)
+ db.add(channel)
+ db.commit()
+ return _channel_payload(channel)
+
+
+def _own_channel(db, user: User, channel_id: int) -> NotificationChannel:
+ channel = db.query(NotificationChannel).filter(NotificationChannel.id == channel_id, NotificationChannel.user_id == user.id).first()
+ if not channel:
+ raise HTTPException(status_code=404, detail="Channel not found.")
+ return channel
+
+
+def _deliver(db, channel: NotificationChannel, owner: User, title: str, body: str, severity: str) -> bool:
+ try:
+ ok, status_text = notify.send(channel.kind, secrets_box.decrypt(channel.target_enc), title, body, severity, allow_private=owner.role == "admin")
+ except secrets_box.SecretsUnavailable:
+ ok, status_text = False, "SECRETS_KEY problem"
+ channel.last_ok, channel.last_status, channel.last_checked_at = ok, status_text[:64], datetime.now(timezone.utc)
+ db.commit()
+ return ok
+
+
[email protected]("/account/channels/{channel_id}/test")
+def test_channel(channel_id: PathId, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db)
+ enforce_limit(redis_client, scope="channel-test", subject=user.id, limit=10, window_seconds=600)
+ channel = _own_channel(db, user, channel_id)
+ _deliver(db, channel, user, "Infradeck test", f"This is a test from {get_instance_name(db) or 'Infradeck'}. Alerts for {user.name} will arrive here.", "INFO")
+ return _channel_payload(channel)
+
+
[email protected]("/account/channels/{channel_id}")
+def remove_channel(channel_id: PathId, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db)
+ db.delete(_own_channel(db, user, channel_id))
+ db.commit()
+ return {"status": "ok"}
+
+
+NOTIFY_WINDOW = timedelta(hours=24)
+NOTIFY_MARK_SECONDS = 7 * 24 * 3600
+
+
+def dispatch_notifications(db, now: datetime | None = None) -> int:
+ """Send what hasn't been sent: incidents that opened or resolved in the last day, to every user with channels,
+ following each user's routing and quiet hours. Returns how many messages went out.
+
+ A warning that opens during someone's quiet hours waits and is sent when they end, if it is still open.
+ Critical incidents are never held back. Muted incidents notify nobody."""
+ now = now or datetime.now(timezone.utc)
+ owners = {user.id: user for user in db.query(User).filter(User.is_active.is_(True))}
+ by_user: dict[int, list[NotificationChannel]] = {}
+ for channel in db.query(NotificationChannel).order_by(NotificationChannel.id):
+ if channel.user_id in owners:
+ by_user.setdefault(channel.user_id, []).append(channel)
+ if not by_user:
+ return 0
+ recent = db.query(IncidentAlert).filter((IncidentAlert.created_at >= now - NOTIFY_WINDOW) | (IncidentAlert.resolved_at >= now - NOTIFY_WINDOW), IncidentAlert.severity != "INFO").order_by(IncidentAlert.created_at).limit(200).all()
+ hostnames = dict(db.query(Server.id, Server.hostname).all())
+ sent = 0
+ for alert in recent:
+ if incidents.is_muted(alert, now):
+ continue
+ event = "resolved" if alert.status == "resolved" else alert.severity.lower()
+ if event not in notify.EVENTS:
+ continue
+ for user_id, channels in by_user.items():
+ preferences = _preferences(owners[user_id])
+ routing = preferences["routing"].get(event, {})
+ wanted = [channel for channel in channels if routing.get(str(channel.id), notify.DEFAULT_ROUTING[event])]
+ if not wanted or (event != "critical" and notify.in_quiet_hours(preferences["quiet"], preferences["display"]["timezone"], now)):
+ continue
+ marker = f"homelab:notified:{alert.id}:{user_id}:{event}"
+ try:
+ if not redis_client.set(marker, "1", nx=True, ex=NOTIFY_MARK_SECONDS):
+ continue
+ except Exception: # without the marker everyone would be told again every few seconds
+ return sent
+ title = f"{'Resolved: ' if event == 'resolved' else ''}{alert.title}"
+ body = f"{hostnames.get(alert.server_id, 'server')} · {alert.severity.lower()} · {incidents.reference(alert.id)}\n{alert.resolution or 'The condition cleared.' if event == 'resolved' else alert.description}"
+ for channel in wanted:
+ sent += 1 if _deliver(db, channel, owners[user_id], title, body, "INFO" if event == "resolved" else alert.severity) else 0
+ if event == "resolved":
+ alert.resolve_notified_at = alert.resolve_notified_at or now
+ else:
+ alert.notified_at = alert.notified_at or now
+ db.commit()
+ return sent
+
+
+def _notify_loop() -> None:
+ while True:
+ time.sleep(15)
+ db = SessionLocal()
+ try:
+ dispatch_notifications(db)
+ except Exception as exc: # a broken channel or a database hiccup must not end the loop
+ print(f"Notifications failed: {type(exc).__name__}: {exc}", flush=True)
+ finally:
+ db.close()
+
+
+# ---------------------------------------------------------------------------------------------------------
+# Admin: users, invitations, alert rules, servers, the install itself
+
+INVITE_TTL = timedelta(days=7)
+
+
+class UserUpdateRequest(BaseModel):
+ role: Literal["admin", "user"] | None = None
+ is_active: bool | None = None
+
+
+class InviteRequest(BaseModel):
+ email: EmailStr
+ role: Literal["admin", "user"] = "user"
+
+
+class ServerUpdateRequest(BaseModel):
+ hostname: str | None = Field(default=None, max_length=255)
+ check_interval_seconds: int | None = None
+
+
+def _admin_users(db) -> dict:
+ owner = _owner_id(db)
+ now = datetime.now(timezone.utc)
+ users = []
+ for account in db.query(User).order_by(User.id):
+ users.append({"id": account.id, "name": account.name, "email": account.email, "role": account.role, "role_name": "Owner" if account.id == owner else "Admin" if account.role == "admin" else "Viewer",
+ "is_active": account.is_active, "two_factor": account.totp_enabled, "avatar_color": account.avatar_color, "sessions": len(list_user_sessions(redis_client, account.id, None)),
+ "last_seen_at": account.last_seen_at.isoformat() if account.last_seen_at else None, "created_at": account.created_at.isoformat()})
+ invites = [{"id": invite.id, "email": invite.email, "role": invite.role, "created_at": invite.created_at.isoformat(), "expires_at": invite.expires_at.isoformat()}
+ for invite in db.query(Invite).filter(Invite.used_at.is_(None), Invite.expires_at > now).order_by(Invite.created_at)]
+ return {"users": users, "invites": invites, "require_2fa_for_everyone": require_two_factor_for_everyone(db), "require_2fa_for_admins": require_admin_two_factor(db), "secrets_configured": secrets_box.available()}
+
+
[email protected]("/admin/users")
+def admin_users(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ _require_admin(session_id, db)
+ return _admin_users(db)
+
+
[email protected]("/admin/users/{user_id}")
+def admin_update_user(user_id: PathId, payload: UserUpdateRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """Change someone's role or switch their account off. The owner can't be changed, and nobody changes themselves
+ here, so an install can't be left without an admin."""
+ admin = _require_admin(session_id, db)
+ account = db.get(User, user_id)
+ if not account:
+ raise HTTPException(status_code=404, detail="User not found.")
+ if account.id == _owner_id(db):
+ raise HTTPException(status_code=403, detail="The owner's account can't be changed here.")
+ if account.id == admin["id"]:
+ raise HTTPException(status_code=403, detail="You can't change your own role or switch yourself off.")
+ changes = []
+ if payload.role is not None and payload.role != account.role:
+ account.role = payload.role
+ changes.append(f"role to {payload.role}")
+ if payload.is_active is not None and payload.is_active != account.is_active:
+ account.is_active = payload.is_active
+ changes.append("enabled" if payload.is_active else "disabled")
+ db.commit()
+ if changes:
+ # A role in a live session would outlast the change, and a disabled account must be out at once.
+ revoke_other_sessions(redis_client, account.id, None)
+ record_audit_log(db, user_id=admin["id"], level="WARNING", message=f"Changed {account.email}: {', '.join(changes)}", source="admin")
+ return _admin_users(db)
+
+
[email protected]("/admin/users/{user_id}/sign-out")
+def admin_sign_out_user(user_id: PathId, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ admin = _require_admin(session_id, db)
+ account = db.get(User, user_id)
+ if not account:
+ raise HTTPException(status_code=404, detail="User not found.")
+ session = get_session(redis_client, session_id)
+ signed_out = revoke_other_sessions(redis_client, account.id, session["public_id"] if account.id == admin["id"] and session else None)
+ record_audit_log(db, user_id=admin["id"], level="WARNING", message=f"Signed {account.email} out everywhere", source="admin")
+ return {"signed_out": signed_out}
+
+
[email protected]("/admin/invites")
+def admin_create_invite(payload: InviteRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """An invitation link for one email address. Infradeck sends no email, so the admin passes the link on; it is
+ shown once, works once and expires in a week."""
+ admin = _require_admin(session_id, db)
+ email = str(payload.email).strip().lower()
+ if db.query(User.id).filter(User.email == email).first():
+ raise HTTPException(status_code=409, detail="An account with that email already exists.")
+ db.query(Invite).filter(Invite.email == email, Invite.used_at.is_(None)).delete(synchronize_session=False)
+ if db.query(Invite).filter(Invite.used_at.is_(None)).count() >= 50:
+ raise HTTPException(status_code=400, detail="Too many invitations are waiting. Cancel some first.")
+ token = secrets.token_urlsafe(32)
+ invite = Invite(email=email, role=payload.role, token_hash=_hash_secret(token), created_by=admin["id"], expires_at=datetime.now(timezone.utc) + INVITE_TTL)
+ db.add(invite)
+ db.commit()
+ record_audit_log(db, user_id=admin["id"], level="INFO", message=f"Invited {email} as {payload.role}", source="admin")
+ return {"id": invite.id, "email": email, "role": payload.role, "token": token, "expires_at": invite.expires_at.isoformat()}
+
+
[email protected]("/admin/invites/{invite_id}")
+def admin_cancel_invite(invite_id: PathId, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ _require_admin(session_id, db)
+ db.query(Invite).filter(Invite.id == invite_id).delete(synchronize_session=False)
+ db.commit()
+ return _admin_users(db)
+
+
+# The rules that open incidents, as the Admin page lists them. ``when`` is a sentence with threshold names in braces;
+# ``edit`` names the thresholds an admin can change on that row.
+RULE_ROWS = [
+ {"kind": "container:restart_loop", "when": "Container restarts ≥ {restart_loop_count}", "window": "{restart_loop_window_minutes} min", "severity": "CRITICAL", "edit": ["restart_loop_count", "restart_loop_window_minutes"]},
+ {"kind": SERVER_OFFLINE_RULE, "when": f"Server misses {OFFLINE_AFTER_MISSED_CHECKS} check-ins in a row", "window": None, "severity": "CRITICAL", "edit": []},
+ {"kind": "host:disk", "when": "Disk used > {disk_critical_pct}% (warning from {disk_warning_pct}%)", "window": "{sustained_checks} check-ins", "severity": "CRITICAL", "edit": ["disk_warning_pct", "disk_critical_pct"]},
+ {"kind": "host:inodes", "when": "Inodes used > {inodes_critical_pct}% (warning from {inodes_warning_pct}%)", "window": "{sustained_checks} check-ins", "severity": "CRITICAL", "edit": ["inodes_warning_pct", "inodes_critical_pct"]},
+ {"kind": "host:memory", "when": "Memory used > {memory_warning_pct}% (critical from {memory_critical_pct}%)", "window": "{sustained_checks} check-ins", "severity": "WARNING", "edit": ["memory_warning_pct", "memory_critical_pct"]},
+ {"kind": "host:swap", "when": "Swap used > {swap_warning_pct}%", "window": "{sustained_checks} check-ins", "severity": "WARNING", "edit": ["swap_warning_pct"]},
+ {"kind": "host:load", "when": "Load > {load_warning_per_core}× the cores (critical from {load_critical_per_core}×)", "window": "{sustained_checks} check-ins", "severity": "WARNING", "edit": ["load_warning_per_core", "load_critical_per_core"]},
+ {"kind": "trend:memory", "when": "A container's memory climbs steadily", "window": None, "severity": "WARNING", "edit": []},
+ {"kind": "container:unhealthy", "when": "A container's healthcheck fails", "window": None, "severity": "WARNING", "edit": []},
+ {"kind": "container:exit", "when": "A container exits with an error or is killed for memory", "window": "{event_window_minutes} min", "severity": "WARNING", "edit": ["event_window_minutes"]},
+ {"kind": "network:port", "when": "New port reachable from other machines", "window": None, "severity": "WARNING", "edit": []},
+ {"kind": "network:firewall", "when": "The firewall configuration is weakened", "window": None, "severity": "WARNING", "edit": []},
+ {"kind": "system:oom", "when": "The kernel kills a process to free memory", "window": "{event_window_minutes} min", "severity": "WARNING", "edit": []},
+ {"kind": "system:docker_unreachable", "when": "Docker stops answering", "window": None, "severity": "CRITICAL", "edit": []},
+ {"kind": "system:ntp", "when": "The clock is not synchronized", "window": None, "severity": "WARNING", "edit": []},
+ {"kind": "system:reboot_required", "when": "Reboot required for updates", "window": None, "severity": "INFO", "edit": []},
+]
+NOISY_FIRED = 20
+
+
[email protected]("/admin/rules")
+def admin_rules(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """Every rule as a sentence, whether it is on, and how often it opened an incident in the last 30 days."""
+ _require_admin(session_id, db)
+ thresholds = get_alert_thresholds(db)
+ disabled = get_disabled_rules(db)
+ fired: dict[str, int] = {}
+ for (rule_key,) in db.query(IncidentAlert.rule_key).filter(IncidentAlert.created_at >= datetime.now(timezone.utc) - timedelta(days=30)).limit(50_000):
+ kind = incidents.rule_kind(rule_key)
+ fired[kind] = fired.get(kind, 0) + 1
+ fill = lambda text_value: text_value.format(**{key: f"{value:g}" for key, value in thresholds.items()}) if text_value else None # noqa: E731
+ return {"rules": [{"kind": row["kind"], "when": fill(row["when"]), "window": fill(row["window"]), "severity": row["severity"], "edit": row["edit"], "enabled": row["kind"] not in disabled,
+ "fired": fired.get(row["kind"], 0), "noisy": fired.get(row["kind"], 0) >= NOISY_FIRED} for row in RULE_ROWS],
+ "thresholds": thresholds}
+
+
[email protected]("/monitoring/servers/{server_id}")
+def update_server(server_id: PathId, payload: ServerUpdateRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """Rename a server or change how often it checks in. A name given here stays, whatever the machine calls itself."""
+ admin = _require_admin(session_id, db)
+ server = db.query(Server).filter(Server.id == server_id).first()
+ if not server:
+ raise HTTPException(status_code=404, detail="Server not found.")
+ if payload.hostname is not None and payload.hostname.strip() and _name_key(payload.hostname) != _name_key(server.hostname):
+ name = _hostname_or_error(payload.hostname)
+ if _hostname_in_use(db, name, excluding=server.id):
+ raise HTTPException(status_code=409, detail=f"Another server is already called {name}.")
+ record_audit_log(db, user_id=admin["id"], level="INFO", message=f"Renamed server {server.hostname} to {name}", source="admin")
+ server.hostname, server.name_locked = name, True
+ if payload.check_interval_seconds is not None:
+ if payload.check_interval_seconds not in (15, 30, 60, 300, 900):
+ raise HTTPException(status_code=400, detail="The check interval must be 15, 30, 60, 300 or 900 seconds.")
+ server.check_interval_seconds = payload.check_interval_seconds
+ db.commit()
+ return {"id": server.id, "hostname": server.hostname, "check_interval_seconds": server.check_interval_seconds}
+
+
[email protected]("/admin/system")
+def admin_system(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ """Read-only facts about this install for the Admin page: version, database size, what the agent was used for."""
+ _require_admin(session_id, db)
+ now = datetime.now(timezone.utc)
+ month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+ size = None
+ if engine.dialect.name == "postgresql":
+ size = db.execute(text("SELECT pg_database_size(current_database())")).scalar()
+ week = now - timedelta(days=7)
+ return {
+ "version": APP_VERSION, "database": {"engine": engine.dialect.name, "bytes": size,
+ "host_rows": db.query(func.count(HostMetric.id)).scalar(), "host_rows_week": db.query(func.count(HostMetric.id)).filter(HostMetric.time >= week).scalar()},
+ "retention_days": get_metrics_retention_days(db),
+ "agent": {"model": AGENT_MODEL, "key_configured": bool(os.getenv("GEMINI_API_KEY", "").strip()), "chat_enabled": is_agent_chat_enabled(db),
+ "incidents_this_month": db.query(IncidentAlert).filter(IncidentAlert.created_at >= month).count(),
+ "chat_messages_this_month": db.query(ChatMessage).filter(ChatMessage.role == "user", ChatMessage.created_at >= month).count()},
+ "smtp_configured": notify.smtp_configured(), "secrets_configured": secrets_box.available(),
+ }
+
+
@app.get("/")
def root():
return {"message": "Infradeck API"}
diff --git a/src/backend/models.py b/src/backend/models.py
index 50a44b0..e247ad3 100644
--- a/src/backend/models.py
+++ b/src/backend/models.py
@@ -24,6 +24,11 @@ class User(Base):
# The newest time step already accepted, so an intercepted code can't be replayed.
totp_last_step: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
password_changed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
+ username: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ avatar_color: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
+ # Display and notification choices, as checked JSON.
+ preferences: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+ last_seen_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(timezone.utc),
@@ -121,6 +126,10 @@ class Server(Base):
machine_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
# The machine running the dashboard itself, as reported by the collector in its compose stack.
is_dashboard_host: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
+ # Facts the collector reports about the machine (kernel, CPU model, interfaces, pending updates), as checked JSON.
+ system_info: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+ # Set when someone named the server on the dashboard, so the collector's own hostname no longer replaces it.
+ name_locked: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
last_seen_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
@@ -139,6 +148,8 @@ class PendingCollector(Base):
ip_address: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
os_info: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
status: Mapped[str] = mapped_column(String(16), default="pending", nullable=False) # pending | dismissed | approved
+ # What the collector found on its machine (cores, containers, mounts), as checked JSON, shown before approval.
+ details: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
approved_server_id: Mapped[Optional[int]] = mapped_column(ForeignKey("servers.id", ondelete="CASCADE"), nullable=True)
# The join token this request presented, if any (shown as "verified" on the dashboard).
join_token_id: Mapped[Optional[int]] = mapped_column(ForeignKey("join_tokens.id", ondelete="SET NULL"), nullable=True)
@@ -300,6 +311,11 @@ class ContainerMetric(Base):
pids: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
started_at: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
ports: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
+ # The compose project the container belongs to, and the host paths or volume names it mounts.
+ project: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
+ # Memory swapped out, from the container's cgroup; Docker's own stats don't include it.
+ swap_mb: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
+ volumes: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
healthcheck_status: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# How a stopped container ended, and the ID of the image it runs (to notice it changing).
exit_code: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
@@ -322,6 +338,15 @@ class IncidentAlert(Base):
rule_key: Mapped[Optional[str]] = mapped_column(String(255), index=True, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), index=True, nullable=False)
resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
+ # How it ended, in a few words ("Marked resolved by Ana"); empty when the condition simply cleared.
+ resolution: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
+ acknowledged_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
+ acknowledged_by: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
+ # While this is in the future the incident is out of the inbox and nobody is notified about it.
+ muted_until: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
+ # When the notifier handled its opening and its resolving, so each is sent once.
+ notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
+ resolve_notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
class HostRollup(Base):
@@ -415,4 +440,55 @@ class ContainerRollup(Base):
n_memory_pct: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
max_memory_pct: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
max_memory_limit_mb: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
+ avg_swap_mb: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
+ n_swap_mb: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
+ max_swap_mb: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
max_restarts: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
+
+
+class ApiToken(Base):
+ """A personal access token for scripts. Only its hash is stored; the token is shown once, when created."""
+
+ __tablename__ = "api_tokens"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
+ user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False)
+ name: Mapped[str] = mapped_column(String(64), nullable=False)
+ scope: Mapped[str] = mapped_column(String(16), nullable=False) # read | write
+ token_hash: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
+ hint: Mapped[str] = mapped_column(String(8), nullable=False)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
+ last_used_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
+ expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
+
+
+class NotificationChannel(Base):
+ """Where one user's alerts go. The address (a URL or an email) is stored encrypted."""
+
+ __tablename__ = "notification_channels"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
+ user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False)
+ kind: Mapped[str] = mapped_column(String(16), nullable=False) # ntfy | discord | webhook | email
+ target_enc: Mapped[str] = mapped_column(Text, nullable=False)
+ # A shortened form that is safe to show (the host and the end of the path).
+ display: Mapped[str] = mapped_column(String(120), nullable=False)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
+ last_status: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ last_ok: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
+ last_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
+
+
+class Invite(Base):
+ """An invitation an admin hands to someone: a single-use link that lets them register while registration is closed."""
+
+ __tablename__ = "invites"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
+ email: Mapped[str] = mapped_column(String(255), nullable=False)
+ role: Mapped[str] = mapped_column(String(50), default="user", nullable=False)
+ token_hash: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
+ created_by: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
+ expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
+ used_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
diff --git a/src/backend/notify.py b/src/backend/notify.py
new file mode 100644
index 0000000..32229ad
--- /dev/null
+++ b/src/backend/notify.py
@@ -0,0 +1,143 @@
+"""Sending alerts to the places a user chose: ntfy, a Discord webhook, any other webhook, or email.
+
+The address of a channel is something a signed-in user typed, and the backend then connects to it, so it is treated
+as hostile: only http and https, no credentials in the address, no redirects, a short timeout, a small answer that
+is never shown to the user (only its status), and every address the name resolves to must be one a channel may
+reach. Loopback, link-local (which includes cloud metadata) and other special ranges are always refused; private
+LAN ranges are allowed only for admins, because a homelab's ntfy usually lives there.
+"""
+from __future__ import annotations
+
+import ipaddress
+import json
+import os
+import smtplib
+import socket
+import urllib.error
+import urllib.parse
+import urllib.request
+from datetime import datetime
+from email.message import EmailMessage
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+
+WEB_KINDS = ("ntfy", "discord", "webhook")
+KINDS = (*WEB_KINDS, "email")
+TIMEOUT_SECONDS = 5
+MAX_URL = 500
+MAX_CHANNELS_PER_USER = 8
+EVENTS = ("critical", "warning", "resolved")
+DEFAULT_ROUTING = {"critical": True, "warning": True, "resolved": False}
+
+
+class ChannelError(ValueError):
+ """The address can't be used; the message is safe to show."""
+
+
+def _allowed(address: str, allow_private: bool) -> bool:
+ ip = ipaddress.ip_address(address)
+ if ip.version == 6 and ip.ipv4_mapped:
+ ip = ip.ipv4_mapped
+ if ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_unspecified or ip.is_reserved:
+ return False
+ return allow_private or ip.is_global
+
+
+def resolve(host: str, port: int) -> list[str]:
+ try:
+ return sorted({info[4][0] for info in socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)})
+ except (socket.gaierror, UnicodeError) as error:
+ raise ChannelError("That address does not resolve.") from error
+
+
+def check_url(url: str, allow_private: bool) -> tuple[str, str]:
+ """The cleaned address and a short form safe to display, or ChannelError."""
+ url = (url or "").strip()
+ if not url or len(url) > MAX_URL or not url.isprintable():
+ raise ChannelError("Enter the channel's address.")
+ parts = urllib.parse.urlsplit(url)
+ if parts.scheme not in ("http", "https") or not parts.hostname:
+ raise ChannelError("The address must start with http:// or https://.")
+ if parts.username or parts.password:
+ raise ChannelError("Put no user name or password in the address.")
+ try:
+ port = parts.port or (443 if parts.scheme == "https" else 80)
+ except ValueError as error:
+ raise ChannelError("The port in that address is not valid.") from error
+ addresses = resolve(parts.hostname, port)
+ if not addresses or not all(_allowed(address, allow_private) for address in addresses):
+ raise ChannelError("That address points at this machine or a private network." + ("" if allow_private else " Only an admin can add a channel on the local network."))
+ tail = parts.path.rstrip("/").rsplit("/", 1)[-1]
+ return url, f"{parts.hostname}{'/…' + tail[-6:] if tail else ''}"[:120]
+
+
+class _NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, *args, **kwargs): # a redirect could lead anywhere, including inside
+ return None
+
+
+_opener = urllib.request.build_opener(_NoRedirect)
+
+
+def _post(url: str, data: bytes, headers: dict[str, str]) -> tuple[bool, str]:
+ request = urllib.request.Request(url, data=data, headers={"User-Agent": "Infradeck", **headers}, method="POST")
+ try:
+ with _opener.open(request, timeout=TIMEOUT_SECONDS) as response:
+ response.read(1024)
+ return True, f"{response.status}"
+ except urllib.error.HTTPError as error:
+ return False, f"{error.code}"
+ except (urllib.error.URLError, OSError, ValueError) as error:
+ return False, type(getattr(error, "reason", error)).__name__[:40]
+
+
+def smtp_configured() -> bool:
+ return bool(os.getenv("SMTP_HOST", "").strip() and os.getenv("SMTP_FROM", "").strip())
+
+
+def _send_email(address: str, title: str, body: str) -> tuple[bool, str]:
+ if not smtp_configured():
+ return False, "SMTP is not configured"
+ message = EmailMessage()
+ message["From"], message["To"], message["Subject"] = os.environ["SMTP_FROM"], address, title[:200]
+ message.set_content(body)
+ try:
+ with smtplib.SMTP(os.environ["SMTP_HOST"], int(os.getenv("SMTP_PORT", "587")), timeout=TIMEOUT_SECONDS * 2) as server:
+ if os.getenv("SMTP_STARTTLS", "true").lower() != "false":
+ server.starttls()
+ if os.getenv("SMTP_USER"):
+ server.login(os.environ["SMTP_USER"], os.getenv("SMTP_PASSWORD", ""))
+ server.send_message(message)
+ return True, "sent"
+ except (smtplib.SMTPException, OSError, ValueError) as error:
+ return False, type(error).__name__[:40]
+
+
+def send(kind: str, target: str, title: str, body: str, severity: str = "INFO", allow_private: bool = False) -> tuple[bool, str]:
+ """Deliver one message. Returns (worked, a short status). The address is checked again at send time, because
+ what a name resolves to can change after the channel was saved."""
+ if kind == "email":
+ return _send_email(target, title, body)
+ try:
+ url, _display = check_url(target, allow_private)
+ except ChannelError:
+ return False, "address refused"
+ if kind == "ntfy":
+ # Header values must be Latin-1; anything else in a title goes into the body instead.
+ safe = title.encode("latin-1", "ignore").decode("latin-1")[:200]
+ return _post(url, body.encode(), {"Title": safe, "Priority": "5" if severity == "CRITICAL" else "3", "Tags": "rotating_light" if severity == "CRITICAL" else "warning" if severity == "WARNING" else "white_check_mark"})
+ if kind == "discord":
+ return _post(url, json.dumps({"content": f"**{title}**\n{body}"[:1900], "allowed_mentions": {"parse": []}}).encode(), {"Content-Type": "application/json"})
+ return _post(url, json.dumps({"title": title, "body": body, "severity": severity}).encode(), {"Content-Type": "application/json"})
+
+
+def in_quiet_hours(quiet: dict | None, timezone_name: str | None, now: datetime) -> bool:
+ """Whether ``now`` falls in the user's quiet hours ("23:00" to "07:00" may wrap past midnight)."""
+ if not quiet or not quiet.get("enabled"):
+ return False
+ try:
+ local = now.astimezone(ZoneInfo(timezone_name or "UTC"))
+ start, end = (int(part[:2]) * 60 + int(part[3:5]) for part in (quiet["start"], quiet["end"]))
+ except (ZoneInfoNotFoundError, KeyError, ValueError, TypeError):
+ return False
+ minute = local.hour * 60 + local.minute
+ return start <= minute < end if start < end else minute >= start or minute < end if start != end else False
diff --git a/src/backend/rollups.py b/src/backend/rollups.py
index f09e534..7741881 100644
--- a/src/backend/rollups.py
+++ b/src/backend/rollups.py
@@ -61,6 +61,7 @@ CONTAINER_COLUMNS = (
("avg_memory_mb", "avg", "memory_used_mb"), ("max_memory_mb", "max", "memory_used_mb"),
("avg_memory_pct", "avg", "memory_pct"), ("max_memory_pct", "max", "memory_pct"),
("max_memory_limit_mb", "max", "memory_limit_mb"), ("max_restarts", "max", "restart_count"),
+ ("avg_swap_mb", "avg", "swap_mb"), ("max_swap_mb", "max", "swap_mb"),
)
# What each kind of rollup groups by and builds from.
KINDS = (
diff --git a/src/backend/stats.py b/src/backend/stats.py
index 6b17eca..b0eedfc 100644
--- a/src/backend/stats.py
+++ b/src/backend/stats.py
@@ -8,11 +8,11 @@ from __future__ import annotations
from datetime import datetime, timedelta, timezone
-from sqlalchemy import func, select
+from sqlalchemy import Integer, case, cast, extract, func, select
from . import history, rollups
from .alerts import CRITICAL, INFO, SEVERITIES, WARNING
-from .models import HostMetric, IncidentAlert, Server
+from .models import ContainerMetric, ContainerRollup, HostMetric, IncidentAlert, Server
MAX_INCIDENTS_READ = 20000
# The bucket an incident count is grouped into, by range.
@@ -131,3 +131,185 @@ def hour_weekday_heatmap(db, server: Server, metric: str, offset_minutes: int =
def fleet_stats(db, range_name: str, now: datetime | None = None) -> dict:
return {"incidents": incident_stats(db, range_name, now), "availability": availability(db, range_name, now)}
+
+
+# --- containers over a range ------------------------------------------------------------------------------
+
+SPARKLINE_POINTS = 40
+MAX_ROLLUP_ROWS = 200_000
+# Which summaries answer a range for every container of a server at once. A week is read from the hourly ones
+# rather than from check-ins: a week of check-ins for a few dozen containers is over a million rows.
+CONTAINER_TIER = {"7d": rollups.HOUR, "30d": rollups.HOUR, "90d": rollups.DAY, "1y": rollups.DAY, "all": rollups.DAY}
+BUSIEST_TIER = {"7d": rollups.HOUR, "30d": rollups.HOUR, "90d": rollups.WEEK, "1y": rollups.WEEK, "all": rollups.MONTH}
+
+
+def _epoch_bucket(column, step: int, origin: int = 0):
+ """The whole number of ``step``-second periods a timestamp is past ``origin``, worked out by the database."""
+ return (cast(extract("epoch", column), Integer) - origin) // step
+
+
+class _Usage:
+ """What one container did over a range, added up from samples or summaries."""
+
+ __slots__ = ("name", "cpu", "cpu_n", "cpu_max", "memory", "memory_n", "memory_max", "restarts_high", "restarts_low", "samples", "down", "spark", "swap", "swap_n", "swap_max")
+
+ def __init__(self):
+ self.name, self.cpu, self.cpu_n, self.cpu_max, self.memory, self.memory_n, self.memory_max = "", 0.0, 0, None, 0.0, 0, None
+ self.restarts_high, self.restarts_low, self.samples, self.down, self.spark = None, None, 0, 0, {}
+ self.swap, self.swap_n, self.swap_max = 0.0, 0, None
+
+ def add_swap(self, total, count, maximum):
+ if total is not None and count:
+ self.swap, self.swap_n = self.swap + total, self.swap_n + count
+ self.swap_max = maximum if maximum is not None and (self.swap_max is None or maximum > self.swap_max) else self.swap_max
+
+ def add(self, name, cpu_total, cpu_n, cpu_max, memory_total, memory_n, memory_max, restarts_high, restarts_low, samples, down, slot):
+ self.name = name or self.name
+ if cpu_total is not None and cpu_n:
+ self.cpu, self.cpu_n = self.cpu + cpu_total, self.cpu_n + cpu_n
+ cell = self.spark.setdefault(slot, [0.0, 0])
+ cell[0], cell[1] = cell[0] + cpu_total, cell[1] + cpu_n
+ if memory_total is not None and memory_n:
+ self.memory, self.memory_n = self.memory + memory_total, self.memory_n + memory_n
+ self.cpu_max = cpu_max if cpu_max is not None and (self.cpu_max is None or cpu_max > self.cpu_max) else self.cpu_max
+ self.memory_max = memory_max if memory_max is not None and (self.memory_max is None or memory_max > self.memory_max) else self.memory_max
+ for value in (restarts_high, restarts_low):
+ if value is not None:
+ self.restarts_high = value if self.restarts_high is None else max(self.restarts_high, value)
+ self.restarts_low = value if self.restarts_low is None else min(self.restarts_low, value)
+ self.samples, self.down = self.samples + (samples or 0), self.down + (down or 0)
+
+
+def _raw_usage(db, usage: dict, server_id: int, since: datetime, until: datetime, origin: int, slot_seconds: int) -> None:
+ table = ContainerMetric
+ slot = _epoch_bucket(table.time, slot_seconds, origin).label("slot")
+ query = select(
+ table.container_id, func.max(table.name), slot, func.sum(table.cpu_pct), func.count(table.cpu_pct), func.max(table.cpu_pct),
+ func.sum(table.memory_used_mb), func.count(table.memory_used_mb), func.max(table.memory_used_mb), func.max(table.restart_count), func.min(table.restart_count),
+ func.count(), func.sum(case((table.status != "running", 1), else_=0)),
+ func.sum(table.swap_mb), func.count(table.swap_mb), func.max(table.swap_mb),
+ ).where(table.server_id == server_id, table.time >= since, table.time < until).group_by(table.container_id, slot)
+ for container_id, name, index, *figures in db.execute(query):
+ item = usage.setdefault(container_id, _Usage())
+ item.add(name, *figures[:-3], max(0, min(SPARKLINE_POINTS - 1, int(index))))
+ item.add_swap(*figures[-3:])
+
+
+def container_usage(db, server: Server, range_name: str, now: datetime | None = None) -> dict:
+ """Every container of a server over a range: average and peak CPU and memory, restarts in the range, the share of
+ check-ins it was down, and a small CPU series. The busiest comes first."""
+ now = _utc(now or datetime.now(timezone.utc))
+ length = history.RANGES[range_name]
+ tier = CONTAINER_TIER.get(range_name)
+ first = db.execute(select(func.min(ContainerMetric.time)).where(ContainerMetric.server_id == server.id)).scalar()
+ oldest = db.execute(select(func.min(ContainerRollup.bucket_start)).where(ContainerRollup.server_id == server.id)).scalar()
+ known = [_utc(moment) for moment in (first, oldest) if moment]
+ since = min(known) if known else now
+ start = max(now - length, since) if length else since
+ origin = int(start.timestamp())
+ slot_seconds = max(1, -(-int((now - start).total_seconds() + 1) // SPARKLINE_POINTS))
+ usage: dict[str, _Usage] = {}
+ raw_from = start
+ if tier:
+ done = rollups._read_watermark(db, rollups.HOUR if tier == rollups.HOUR else tier)
+ closed = min(done, now) if done and done > start else start
+ table = ContainerRollup
+ query = select(
+ table.container_id, table.name, table.bucket_start, table.avg_cpu, table.n_cpu, table.max_cpu, table.avg_memory_mb, table.n_memory_mb, table.max_memory_mb,
+ table.max_restarts, table.samples, table.down_samples, table.avg_swap_mb, table.n_swap_mb, table.max_swap_mb,
+ ).where(table.server_id == server.id, table.tier == tier, table.bucket_start >= rollups.floor(tier, start), table.bucket_start < closed).limit(MAX_ROLLUP_ROWS)
+ for container_id, name, bucket, avg_cpu, n_cpu, max_cpu, avg_memory, n_memory, max_memory, restarts, samples, down, avg_swap, n_swap, max_swap in db.execute(query):
+ slot = max(0, min(SPARKLINE_POINTS - 1, (int(_utc(bucket).timestamp()) - origin) // slot_seconds))
+ usage.setdefault(container_id, _Usage()).add(
+ name, avg_cpu * n_cpu if avg_cpu is not None else None, n_cpu, max_cpu, avg_memory * n_memory if avg_memory is not None else None, n_memory, max_memory,
+ restarts, restarts, samples, down, slot)
+ usage[container_id].add_swap(avg_swap * n_swap if avg_swap is not None and n_swap else None, n_swap or 0, max_swap)
+ # What the summaries haven't reached yet comes from the check-ins themselves, when those are still recent.
+ raw_from = max(closed, now - timedelta(days=2)) if closed > start else start if now - start <= timedelta(days=2) else closed
+ _raw_usage(db, usage, server.id, raw_from, now + timedelta(seconds=1), origin, slot_seconds)
+ containers = []
+ for container_id, item in usage.items():
+ containers.append({
+ "container_id": container_id, "name": item.name,
+ "avg_cpu": item.cpu / item.cpu_n if item.cpu_n else None, "max_cpu": item.cpu_max,
+ "avg_memory_mb": item.memory / item.memory_n if item.memory_n else None, "max_memory_mb": item.memory_max,
+ "avg_swap_mb": item.swap / item.swap_n if item.swap_n else None, "max_swap_mb": item.swap_max,
+ "restarts": item.restarts_high - item.restarts_low if item.restarts_high is not None else None,
+ "samples": item.samples, "down_samples": item.down,
+ "sparkline": [round(item.spark[slot][0] / item.spark[slot][1], 2) if slot in item.spark else None for slot in range(SPARKLINE_POINTS)],
+ })
+ containers.sort(key=lambda item: (-(item["avg_cpu"] if item["avg_cpu"] is not None else -1), item["name"]))
+ return {"server_id": server.id, "range": range_name, "start": start.isoformat(), "end": now.isoformat(), "containers": containers}
+
+
+def busiest_containers(db, server: Server, range_name: str, now: datetime | None = None) -> dict:
+ """Per period of the range, the container that used the most CPU and how much, so a spike on the server's
+ chart can name what caused it. Periods in which no container reported are left out."""
+ now = _utc(now or datetime.now(timezone.utc))
+ length = history.RANGES[range_name]
+ tier = BUSIEST_TIER.get(range_name)
+ best: dict[int, tuple[float, str]] = {}
+
+ def offer(moment: int, name: str, cpu: float | None) -> None:
+ if cpu is not None and (moment not in best or cpu > best[moment][0]):
+ best[moment] = (cpu, name)
+
+ if tier:
+ step = history.NATURAL_SECONDS[tier]
+ table = ContainerRollup
+ query = select(table.bucket_start, table.name, table.max_cpu).where(table.server_id == server.id, table.tier == tier, table.max_cpu.isnot(None))
+ if length:
+ query = query.where(table.bucket_start >= rollups.floor(tier, now - length))
+ for bucket, name, cpu in db.execute(query.limit(MAX_ROLLUP_ROWS)):
+ offer(int(_utc(bucket).timestamp()), name, cpu)
+ done = rollups._read_watermark(db, tier)
+ raw_from = max(done, now - timedelta(days=2)) if done else now - min(length or timedelta(days=2), timedelta(days=2))
+ else:
+ step = history.nice_step(max(length.total_seconds() / history.MAX_POINTS, server.check_interval_seconds))
+ raw_from = now - length
+ # Check-ins the summaries haven't reached (or, for the short ranges, all of them), grouped by the database.
+ raw_step = step if not tier else history.NATURAL_SECONDS[rollups.HOUR] if tier == rollups.HOUR else None
+ if raw_step:
+ table = ContainerMetric
+ bucket = _epoch_bucket(table.time, raw_step).label("bucket")
+ query = select(bucket, table.container_id, func.max(table.name), func.max(table.cpu_pct)).where(table.server_id == server.id, table.time >= raw_from, table.time <= now).group_by(bucket, table.container_id)
+ for index, _container_id, name, cpu in db.execute(query):
+ offer(int(index) * raw_step, name, cpu)
+ return {"server_id": server.id, "range": range_name, "bucket_seconds": step,
+ "points": [{"time": datetime.fromtimestamp(moment, timezone.utc).isoformat(), "name": name, "cpu": round(cpu, 2)} for moment, (cpu, name) in sorted(best.items())]}
+
+
+SPIKE_PERCENT = 90.0
+MAX_SPIKES = 500
+MAX_SPIKE_ROWS = 150_000
+
+
+def cpu_spikes(db, server: Server, range_name: str, now: datetime | None = None) -> dict:
+ """Every stretch in which the server's CPU stayed at or above 90%, with how long it lasted, read from the
+ check-ins themselves so a spike shorter than a chart point still has a length. Only ranges that still have
+ check-ins (up to a week) can be answered; longer ones give no spikes and say so."""
+ now = _utc(now or datetime.now(timezone.utc))
+ length = history.RANGES[range_name]
+ if history.SOURCE[range_name] != history.DETAILED or length is None:
+ return {"server_id": server.id, "range": range_name, "available": False, "threshold": SPIKE_PERCENT, "spikes": []}
+ rows = db.execute(select(HostMetric.time, HostMetric.cpu_utilization_pct).where(HostMetric.server_id == server.id, HostMetric.time >= now - length, HostMetric.time <= now).order_by(HostMetric.time).limit(MAX_SPIKE_ROWS))
+ spikes, current, previous = [], None, None
+ # A check-in that is late by more than a few intervals ends a spike: nobody knows what happened in between.
+ patience = timedelta(seconds=server.check_interval_seconds * 3)
+ for moment, cpu in rows:
+ moment = _utc(moment)
+ high = cpu is not None and cpu >= SPIKE_PERCENT
+ if current and (not high or moment - previous > patience):
+ spikes.append(current)
+ current = None
+ if high:
+ if current is None:
+ current = {"start": moment, "end": moment, "peak": cpu}
+ current["end"], current["peak"] = moment, max(current["peak"], cpu)
+ previous = moment
+ if current:
+ spikes.append(current)
+ return {"server_id": server.id, "range": range_name, "available": True, "threshold": SPIKE_PERCENT, "spikes": [
+ # One check-in at 90% stands for about one interval, not for no time at all.
+ {"time": spike["start"].isoformat(), "seconds": round((spike["end"] - spike["start"]).total_seconds()) + server.check_interval_seconds, "peak": round(spike["peak"], 1)}
+ for spike in spikes[-MAX_SPIKES:]]}
diff --git a/src/frontend/index.html b/src/frontend/index.html
index 6ad885b..2cb943e 100644
--- a/src/frontend/index.html
+++ b/src/frontend/index.html
@@ -4,8 +4,8 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
- <meta name="theme-color" content="#0d1013" />
- <title>frontend</title>
+ <meta name="theme-color" content="#0E0E11" />
+ <title>Infradeck</title>
</head>
<body>
<div id="root"></div>
diff --git a/src/frontend/package-lock.json b/src/frontend/package-lock.json
index a2802c1..30dfbb3 100644
--- a/src/frontend/package-lock.json
+++ b/src/frontend/package-lock.json
@@ -8,6 +8,8 @@
"name": "frontend",
"version": "0.0.0",
"dependencies": {
+ "@fontsource-variable/inter": "^5.3.0",
+ "@fontsource-variable/jetbrains-mono": "^5.3.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-router-dom": "^7.18.3"
@@ -22,6 +24,24 @@
"vite": "^8.2.2"
}
},
+ "node_modules/@fontsource-variable/inter": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
+ "integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",
+ "license": "OFL-1.1",
+ "funding": {
+ "url": "https://github.com/sponsors/ayuhito"
+ }
+ },
+ "node_modules/@fontsource-variable/jetbrains-mono": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/@fontsource-variable/jetbrains-mono/-/jetbrains-mono-5.3.0.tgz",
+ "integrity": "sha512-F32xpS2NsGYoQi2ADSkKTgpJj7ozajsGgDJ8woTnqjmIB+dxDIqImjl4pXZVEExu8UFZ2ndhmX18EBS/hdz3Lw==",
+ "license": "OFL-1.1",
+ "funding": {
+ "url": "https://github.com/sponsors/ayuhito"
+ }
+ },
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@@ -1151,6 +1171,72 @@
"node": ">=14.0.0"
}
},
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
+ "version": "1.11.1",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "1.2.2",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
+ "version": "1.11.1",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
+ "version": "1.2.2",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
+ "version": "1.1.4",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@tybys/wasm-util": "^0.10.1"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "peerDependencies": {
+ "@emnapi/core": "^1.7.1",
+ "@emnapi/runtime": "^1.7.1"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {
+ "version": "0.10.2",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {
+ "version": "2.8.1",
+ "dev": true,
+ "inBundle": true,
+ "license": "0BSD",
+ "optional": true
+ },
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz",
diff --git a/src/frontend/package.json b/src/frontend/package.json
index 300f8fc..b235598 100644
--- a/src/frontend/package.json
+++ b/src/frontend/package.json
@@ -10,6 +10,8 @@
"preview": "vite preview"
},
"dependencies": {
+ "@fontsource-variable/inter": "^5.3.0",
+ "@fontsource-variable/jetbrains-mono": "^5.3.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-router-dom": "^7.18.3"
diff --git a/src/frontend/public/favicon.svg b/src/frontend/public/favicon.svg
index 6893eb1..e1d212b 100644
--- a/src/frontend/public/favicon.svg
+++ b/src/frontend/public/favicon.svg
@@ -1 +1,3 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-49.64" y="2.03" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-45.045" y="20.029" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-43.513" y="21.178" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="g" width="74.749" height="58.852" x="15.756" y="-17.901" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="h" width="61.377" height="25.362" x="23.548" y="2.284" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="i" width="61.377" height="25.362" x="23.548" y="2.284" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="j" width="56.045" height="63.649" x="-27.636" y="-22.853" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="k" width="54.814" height="64.646" x="20.116" y="-38.415" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="l" width="33.541" height="35.313" x="24.641" y="-11.323" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="m" width="54.814" height="64.646" x="-29.286" y="6.009" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="n" width="54.814" height="64.646" x="-29.286" y="6.009" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="o" width="54.814" height="64.646" x="8.244" y="-2.416" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="p" width="39.409" height="43.623" x="18.713" y="10.588" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter></defs></svg>
\ No newline at end of file
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
+ <rect width="64" height="64" rx="10" fill="#0E0E11"/><rect x="20" y="8" width="16" height="12" fill="#F3F1EC"/><rect x="28" y="26" width="16" height="12" fill="#FF5A1F"/><rect x="20" y="44" width="16" height="12" fill="#F3F1EC"/>
+</svg>
diff --git a/src/frontend/public/icons.svg b/src/frontend/public/icons.svg
deleted file mode 100644
index c607ebe..0000000
--- a/src/frontend/public/icons.svg
+++ /dev/null
@@ -1,24 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg">
- <symbol id="brand-icon" viewBox="0 0 16 17">
- <g clip-path="url(#brand-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
- <defs><clipPath id="brand-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
- </symbol>
- <symbol id="discord-icon" viewBox="0 0 20 19">
- <path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
- </symbol>
- <symbol id="documentation-icon" viewBox="0 0 21 20">
- <path fill="none" stroke="#cfcfcf" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
- <path fill="none" stroke="#cfcfcf" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
- <path fill="none" stroke="#cfcfcf" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
- </symbol>
- <symbol id="github-icon" viewBox="0 0 19 19">
- <path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
- </symbol>
- <symbol id="social-icon" viewBox="0 0 20 20">
- <path fill="none" stroke="#cfcfcf" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
- <path fill="none" stroke="#cfcfcf" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
- </symbol>
- <symbol id="x-icon" viewBox="0 0 19 19">
- <path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
- </symbol>
-</svg>
diff --git a/src/frontend/public/logo.svg b/src/frontend/public/logo.svg
new file mode 100644
index 0000000..77cd176
--- /dev/null
+++ b/src/frontend/public/logo.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="2.66 -32.01 177.32 32.01">
+ <rect x="2.66" y="-32.01" width="5.67" height="9.47" fill="#F3F1EC"/><rect x="5.26" y="-20.74" width="5.67" height="9.47" fill="#FF5A1F"/><rect x="2.66" y="-9.47" width="5.67" height="9.47" fill="#F3F1EC"/><path transform="translate(11.48 0)" d="M7.8203125 -12.826171875C7.8203125 -16.693359375 9.947265625 -18.390625 12.783203125 -18.390625C15.68359375 -18.390625 17.359375 -16.650390625 17.359375 -13.3203125V0.0H22.794921875V-14.1796875C22.794921875 -20.001953125 19.443359375 -23.138671875 14.6953125 -23.138671875C11.580078125 -23.138671875 9.28125 -21.763671875 7.734375 -19.20703125V-22.6875H2.40625V0.0H7.8203125ZM38.383125 -22.6875H33.763984375V-25.09375C33.763984375 -26.94140625 34.451484375 -27.650390625 36.299140625 -27.650390625H38.383125V-32.01171875H35.224921875C30.7346875 -32.01171875 28.3284375 -29.90625 28.3284375 -25.99609375V-22.6875H24.24640625V-18.326171875H28.3284375V0.0H33.763984375V-18.326171875H38.383125ZM40.32875 0.0H45.7428125V-12.84765625C45.7428125 -16.392578125 47.740859375 -18.17578125 50.318984375 -18.17578125C51.393203125 -18.17578125 52.467421875 -18.068359375 52.875625 -18.00390625V-22.81640625C52.4459375 -22.859375 51.844375 -22.90234375 51.11390625 -22.90234375C48.19203125 -22.90234375 46.451796875 -21.52734375 45.61390625 -18.927734375H45.549453125V-22.6875H40.32875ZM61.588828125 0.365234375C65.28414062499999 0.365234375 67.19624999999999 -1.181640625 68.27046874999999 -3.201171875H68.35640624999999V0.0H73.68453124999999V-15.46875C73.68453124999999 -20.1953125 70.18257812499999 -23.138671875 64.27437499999999 -23.138671875C58.3446875 -23.138671875 54.649375 -20.15234375 54.3915625 -15.640625H59.612265625C59.76265625 -17.552734375 61.524375 -18.927734375 64.16695312499999 -18.927734375C66.76656249999999 -18.927734375 68.31343749999999 -17.552734375 68.31343749999999 -15.619140625V-15.447265625C68.31343749999999 -13.900390625 66.87398437499999 -13.8359375 62.663046875 -13.36328125C57.979453125 -12.869140625 53.74703125 -11.6015625 53.74703125 -6.4453125C53.74703125 -1.912109375 57.077109375 0.365234375 61.588828125 0.365234375ZM62.920859375 -3.65234375C60.557578125 -3.65234375 59.0321875 -4.705078125 59.0321875 -6.48828125C59.0321875 -8.55078125 61.00875 -9.388671875 63.3290625 -9.732421875C65.56343749999999 -10.076171875 67.66890624999999 -10.419921875 68.33492187499999 -10.849609375V-8.400390625C68.33492187499999 -5.7578125 66.46578124999999 -3.65234375 62.920859375 -3.65234375ZM85.921171875 0.451171875C88.886015625 0.451171875 91.378203125 -0.837890625 92.796171875 -3.458984375H92.839140625V0.0H98.167265625V-32.01171875H92.753203125V-19.46484375H92.710234375C91.249296875 -21.95703125 88.8215625 -23.138671875 85.878203125 -23.138671875C80.0559375 -23.138671875 76.1028125 -18.34765625 76.1028125 -11.365234375C76.1028125 -4.296875 79.991484375 0.451171875 85.921171875 0.451171875ZM87.18875 -4.08203125C83.8371875 -4.08203125 81.581328125 -6.66015625 81.581328125 -11.365234375C81.581328125 -16.048828125 83.8371875 -18.6484375 87.18875 -18.6484375C90.733671875 -18.6484375 93.053984375 -15.76953125 93.053984375 -11.365234375C93.053984375 -6.939453125 90.733671875 -4.08203125 87.18875 -4.08203125ZM111.671484375 0.515625C116.978125 0.515625 121.1890625 -2.556640625 122.0484375 -7.00390625H116.978125C116.355078125 -5.0703125 114.52890625 -3.759765625 111.800390625 -3.759765625C108.148046875 -3.759765625 106.042578125 -6.23046875 105.913671875 -9.92578125H122.327734375V-11.408203125C122.327734375 -18.369140625 117.987890625 -23.203125 111.456640625 -23.203125C105.097265625 -23.203125 100.60703125 -18.21875 100.60703125 -11.322265625C100.60703125 -4.447265625 104.8609375 0.515625 111.671484375 0.515625ZM105.956640625 -13.6640625C106.321875 -16.908203125 108.405859375 -18.90625 111.542578125 -18.90625C114.679296875 -18.90625 116.784765625 -16.908203125 117.128515625 -13.6640625ZM134.714765625 0.515625C140.45109375 0.515625 144.6190625 -3.1796875 145.00578125 -8.142578125H139.656171875C139.140546875 -5.62890625 137.61515625 -3.99609375 134.77921875 -3.99609375C131.2128125 -3.99609375 129.10734375 -6.853515625 129.10734375 -11.322265625C129.10734375 -15.8125 131.234296875 -18.69140625 134.77921875 -18.69140625C137.593671875 -18.69140625 139.2909375 -16.994140625 139.699140625 -14.56640625H145.00578125C144.533125 -19.615234375 140.408125 -23.203125 134.714765625 -23.203125C128.07609375 -23.203125 123.62882812500001 -18.326171875 123.62882812500001 -11.322265625C123.62882812500001 -4.318359375 128.07609375 0.515625 134.714765625 0.515625ZM147.31664062500002 0.0H152.73070312500002V-7.583984375L154.79320312500002 -9.7109375L162.22679687500002 0.0H168.69359375000002L158.91820312500002 -12.890625L168.13500000000002 -22.6875H161.62523437500002L152.79515625000002 -13.4921875H152.73070312500002V-32.01171875H147.31664062500002Z" fill="#F3F1EC"/>
+
+</svg>
diff --git a/src/frontend/src/App.css b/src/frontend/src/App.css
deleted file mode 100644
index f90339d..0000000
--- a/src/frontend/src/App.css
+++ /dev/null
@@ -1,184 +0,0 @@
-.counter {
- font-size: 16px;
- padding: 5px 10px;
- border-radius: 5px;
- color: var(--accent);
- background: var(--accent-bg);
- border: 2px solid transparent;
- transition: border-color 0.3s;
- margin-bottom: 24px;
-
- &:hover {
- border-color: var(--accent-border);
- }
- &:focus-visible {
- outline: 2px solid var(--accent);
- outline-offset: 2px;
- }
-}
-
-.hero {
- position: relative;
-
- .base,
- .framework,
- .vite {
- inset-inline: 0;
- margin: 0 auto;
- }
-
- .base {
- width: 170px;
- position: relative;
- z-index: 0;
- }
-
- .framework,
- .vite {
- position: absolute;
- }
-
- .framework {
- z-index: 1;
- top: 34px;
- height: 28px;
- transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
- scale(1.4);
- }
-
- .vite {
- z-index: 0;
- top: 107px;
- height: 26px;
- width: auto;
- transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
- scale(0.8);
- }
-}
-
-#center {
- display: flex;
- flex-direction: column;
- gap: 25px;
- place-content: center;
- place-items: center;
- flex-grow: 1;
-
- @media (max-width: 1024px) {
- padding: 32px 20px 24px;
- gap: 18px;
- }
-}
-
-#next-steps {
- display: flex;
- border-top: 1px solid var(--border);
- text-align: left;
-
- & > div {
- flex: 1 1 0;
- padding: 32px;
- @media (max-width: 1024px) {
- padding: 24px 20px;
- }
- }
-
- .icon {
- margin-bottom: 16px;
- width: 22px;
- height: 22px;
- }
-
- @media (max-width: 1024px) {
- flex-direction: column;
- text-align: center;
- }
-}
-
-#docs {
- border-right: 1px solid var(--border);
-
- @media (max-width: 1024px) {
- border-right: none;
- border-bottom: 1px solid var(--border);
- }
-}
-
-#next-steps ul {
- list-style: none;
- padding: 0;
- display: flex;
- gap: 8px;
- margin: 32px 0 0;
-
- .logo {
- height: 18px;
- }
-
- a {
- color: var(--text-h);
- font-size: 16px;
- border-radius: 6px;
- background: var(--social-bg);
- display: flex;
- padding: 6px 12px;
- align-items: center;
- gap: 8px;
- text-decoration: none;
- transition: box-shadow 0.3s;
-
- &:hover {
- box-shadow: var(--shadow);
- }
- .button-icon {
- height: 18px;
- width: 18px;
- }
- }
-
- @media (max-width: 1024px) {
- margin-top: 20px;
- flex-wrap: wrap;
- justify-content: center;
-
- li {
- flex: 1 1 calc(50% - 8px);
- }
-
- a {
- width: 100%;
- justify-content: center;
- box-sizing: border-box;
- }
- }
-}
-
-#spacer {
- height: 88px;
- border-top: 1px solid var(--border);
- @media (max-width: 1024px) {
- height: 48px;
- }
-}
-
-.ticks {
- position: relative;
- width: 100%;
-
- &::before,
- &::after {
- content: '';
- position: absolute;
- top: -4.5px;
- border: 5px solid transparent;
- }
-
- &::before {
- left: 0;
- border-left-color: var(--border);
- }
- &::after {
- right: 0;
- border-right-color: var(--border);
- }
-}
diff --git a/src/frontend/src/App.jsx b/src/frontend/src/App.jsx
index fb798b1..c878c50 100644
--- a/src/frontend/src/App.jsx
+++ b/src/frontend/src/App.jsx
@@ -1,84 +1,18 @@
-import { BrowserRouter, Link, NavLink, Navigate, Route, Routes, useLocation, useNavigate } from 'react-router-dom'
-import { useEffect, useRef, useState } from 'react'
-import StatisticsContent from './StatisticsPage.jsx'
+import { BrowserRouter, Navigate, Route, Routes, useLocation } from 'react-router-dom'
+import { useEffect, useState } from 'react'
+import AccountPage from './account/AccountPage.jsx'
+import AdminPage from './admin/AdminPage.jsx'
+import AgentPage from './agent/AgentPage.jsx'
+import { apiRequest } from './api.js'
+import { LoginPage, RegisterPage } from './auth/AuthPages.jsx'
+import DashboardPage from './dashboard/DashboardPage.jsx'
+import { resetOverview } from './overviewStore.js'
+import { applyDisplay } from './prefs.js'
+import StatisticsPage from './statistics/StatisticsPage.jsx'
const AUTH_KEY = 'homie-auth-user'
-const USERS_KEY = 'homie-auth-users'
-const API_BASE = import.meta.env.VITE_API_BASE_URL || '/api'
-// Vite only exposes VITE_-prefixed env vars; clamp so a bad value can't flood the API.
-const LIVE_GRAPH_REFRESH_INTERVAL_SECONDS = Math.max(Number(import.meta.env.VITE_LIVE_GRAPH_REFRESH_INTERVAL_SECONDS) || 3, 1)
-
-function createChatThread() {
- return {
- id: typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : `chat-${Date.now()}`,
- title: 'New chat',
- preview: 'Start a task with Homie',
- time: 'now',
- unread: 0,
- persisted: false,
- messages: [],
- }
-}
-
-async function apiRequest(path, options = {}) {
- const response = await fetch(`${API_BASE}${path}`, {
- ...options,
- credentials: 'include',
- headers: {
- 'Content-Type': 'application/json',
- ...(options.headers || {}),
- },
- })
-
- if (!response.ok) {
- const errorBody = await response.json().catch(() => ({}))
- const detail = errorBody.detail
- const error = new Error(typeof detail === 'string' ? detail : detail?.message || 'Request failed.')
- error.status = response.status
- throw error
- }
-
- return response.json()
-}
-
-function parseAgentMessage(text) {
- return { text, risk: 'neutral' }
-}
-
-const navigation = [
- { label: 'Dashboard', to: '/', icon: '▣' },
- { label: 'Statistics', to: '/statistics', icon: '▤' },
- { label: 'Agent', to: '/agent', icon: '◷' },
- { label: 'Account', to: '/account', icon: '◉' },
- { label: 'Admin', to: '/admin', icon: '⚙', adminOnly: true },
-]
-
-const conversationThreads = []
-
-const stats = [
- { label: 'Health checks', value: '0', delta: 'Monitoring-only', accent: 'emerald' },
- { label: 'Avg. response', value: '3.8s', delta: '-0.6s', accent: 'silver' },
- { label: 'Uptime', value: '99.97%', delta: '+0.3%', accent: 'violet' },
- { label: 'Alerts', value: '0', delta: 'No critical findings', accent: 'amber' },
-]
-
-const logEntries = [
- { id: 'health-monitor', type: 'COMPLETED', taskTitle: 'Monitoring-only mode enabled', message: 'The agent can run only predefined health checks.', time: 'now', actor: 'homie', steps: ['Shell command execution is disabled.', 'Server, container, and daily health checks are available.'] },
-]
-
-const adminSettings = {
- systemPrompt: 'Homie is a monitoring-only health assistant. It can request only predefined read-only checks and cannot execute commands or change the system.',
- safetyRules: [
- 'No shell execution',
- 'Closed allow-list of health checks',
- 'No configuration or service changes',
- 'Alerts only for critical findings',
- ],
-}
function getStoredUser() {
- if (typeof window === 'undefined') return null
-
try {
const raw = window.localStorage.getItem(AUTH_KEY)
return raw ? JSON.parse(raw) : null
@@ -87,2156 +21,13 @@ function getStoredUser() {
}
}
-function getStoredUsers() {
- if (typeof window === 'undefined') return []
-
- try {
- const raw = window.localStorage.getItem(USERS_KEY)
- return raw ? JSON.parse(raw) : []
- } catch {
- return []
- }
-}
-
-function getAccentClasses(accent) {
- const map = {
- emerald: 'from-emerald-500/25 to-emerald-400/10 text-emerald-300 ring-emerald-400/20',
- silver: 'from-[#e6e7ea]/25 to-[#f5f5f6]/10 text-[#cfcfcf] ring-[#cfcfcf]/20',
- violet: 'from-violet-500/25 to-violet-400/10 text-violet-300 ring-violet-400/20',
- amber: 'from-amber-500/25 to-amber-400/10 text-amber-300 ring-amber-400/20',
- }
- return map[accent] || map.emerald
-}
-
-function getRiskStyles(risk, role) {
- if (role === 'user') {
- return {
- card: 'border-white/20 bg-white/5',
- badge: 'bg-white/10 text-slate-200 border-white/20',
- dot: 'bg-white',
- }
- }
-
- const map = {
- low: {
- card: 'border-emerald-400/40 bg-emerald-500/5',
- badge: 'bg-emerald-500/10 text-emerald-300 border-emerald-400/30',
- dot: 'bg-emerald-400',
- },
- medium: {
- card: 'border-amber-400/45 bg-amber-500/5',
- badge: 'bg-amber-500/10 text-amber-300 border-amber-400/30',
- dot: 'bg-amber-400',
- },
- high: {
- card: 'border-red-400/45 bg-red-500/5',
- badge: 'bg-red-500/10 text-red-300 border-red-400/30',
- dot: 'bg-red-400',
- },
- neutral: {
- card: 'border-[#1f2326]/80 bg-[#0d1013]/60',
- badge: 'bg-[#111417]/70 text-[#bcbcbc] border-[#1f2326]',
- dot: 'bg-[#cfcfcf]',
- },
- }
-
- return map[risk] || map.neutral
-}
-
-function MobileTopBar({ user, onLogout }) {
- const [menuOpen, setMenuOpen] = useState(false)
-
- useEffect(() => {
- if (!menuOpen) return
- const close = (event) => { if (event.key === 'Escape') setMenuOpen(false) }
- window.addEventListener('keydown', close)
- return () => window.removeEventListener('keydown', close)
- }, [menuOpen])
-
- return (
- <header className="sticky top-0 z-30 border-b border-white/5 bg-[#0d1013]/85 pt-[env(safe-area-inset-top)] backdrop-blur-xl lg:hidden">
- <div className="flex h-14 items-center justify-between px-4">
- <div className="flex items-center gap-2.5">
- <div className="flex h-8 w-8 items-center justify-center rounded-xl bg-linear-to-br from-white to-[#cfcfcf] text-xs font-bold text-slate-950">H</div>
- <span className="text-sm font-medium text-[#cfcfcf]">Homie</span>
- </div>
- {user && (
- <div className="relative">
- <button type="button" onClick={() => setMenuOpen((open) => !open)} aria-expanded={menuOpen} aria-haspopup="menu" aria-label="Account menu" className="flex h-10 w-10 items-center justify-center rounded-full border border-white/10 bg-white/5 text-sm font-medium text-white transition active:bg-white/10">
- {(user.name || user.email || '?').trim().charAt(0).toUpperCase()}
- </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="glass-panel absolute right-0 z-20 mt-2 w-64 rounded-2xl p-3">
- <div className="px-1 text-sm font-medium text-white">{user.name}</div>
- <div className="truncate px-1 text-xs text-[#9aa0a6]">{user.email}</div>
- <button type="button" role="menuitem" onClick={() => { setMenuOpen(false); onLogout() }} className="mt-3 flex h-11 w-full items-center justify-center rounded-xl border border-red-400/30 bg-red-500/10 text-sm text-red-300 transition active:bg-red-500/20">Logout</button>
- </div>
- </>}
- </div>
- )}
- </div>
- </header>
- )
-}
-
-function MobileTabBar({ user }) {
- const items = navigation.filter((item) => !item.adminOnly || user?.role === 'admin')
- return (
- <nav aria-label="Main" className="fixed inset-x-0 bottom-0 z-30 border-t border-white/5 bg-[#0d1013]/90 pb-[env(safe-area-inset-bottom)] backdrop-blur-xl 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 }) => `flex h-16 flex-col items-center justify-center gap-1 text-[11px] font-medium transition ${isActive ? 'text-white' : 'text-[#7f8589] active:text-[#cfcfcf]'}`}
- >
- {({ isActive }) => <>
- <span className={`flex h-7 w-12 items-center justify-center rounded-full text-base transition ${isActive ? 'bg-white/10' : ''}`}>{item.icon}</span>
- {item.label}
- </>}
- </NavLink>
- ))}
- </div>
- </nav>
- )
-}
-
-function AppShell({ children, user, onLogout, fitViewport = false }) {
- return (
- <div className={`${fitViewport ? 'min-h-screen xl:h-screen xl:overflow-hidden' : 'min-h-screen'} bg-[#0d1013] text-[#e6e7ea]`}>
- <MobileTopBar user={user} onLogout={onLogout} />
- <div className={`${fitViewport ? 'xl:h-full xl:min-h-0' : ''} mx-auto flex max-w-[1700px] gap-6 px-3 pt-4 pb-[calc(5.5rem+env(safe-area-inset-bottom))] sm:px-4 lg:px-6 lg:py-5`}>
- <aside className="glass-panel hidden w-72 shrink-0 rounded-3xl p-4 lg:block">
- <div className="mb-6 flex items-center gap-3 px-2">
- <div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-linear-to-br from-white to-[#cfcfcf] text-sm font-bold text-slate-950">H</div>
- <div>
- <div className="text-sm font-medium text-[#cfcfcf]">Homie</div>
- <div className="text-xs text-[#9aa0a6]">Sysadmin agent</div>
- </div>
- </div>
-
- <nav className="space-y-2">
- {navigation.filter((item) => !item.adminOnly || user?.role === 'admin').map((item) => (
- <NavLink
- key={item.to}
- to={item.to}
- end={item.to === '/'}
- className={({ isActive }) =>
- `flex items-center gap-3 rounded-2xl px-3 py-2.5 text-sm transition ${
- isActive
- ? 'bg-[#171b1f] text-white ring-1 ring-white/10'
- : 'text-[#bcbcbc] hover:bg-[#111417] hover:text-white'
- }`
- }
- >
- <span className="text-base">{item.icon}</span>
- {item.label}
- </NavLink>
- ))}
- </nav>
-
- {user && (
- <div className="mt-8 rounded-2xl border border-neutral-800 bg-[#111417] p-3">
- <div className="text-xs uppercase tracking-[0.2em] text-[#9aa0a6]">Signed in</div>
- <div className="mt-2 text-sm font-medium text-white">{user.name}</div>
- <div className="text-xs text-[#9aa0a6]">{user.email}</div>
- <button
- onClick={onLogout}
- className="mt-4 w-full rounded-xl border border-red-400/30 bg-red-500/10 px-3 py-2 text-sm text-red-300 transition hover:bg-red-500/15"
- >
- Logout
- </button>
- </div>
- )}
-
- <div className="mt-8 rounded-2xl border border-emerald-400/20 bg-emerald-500/5 p-3">
- <div className="flex items-center justify-between text-xs text-[#bcbcbc]">
- <span>Agent status</span>
- <span className="inline-flex items-center gap-1.5">
- <span className="h-2 w-2 rounded-full bg-emerald-400" />
- Online
- </span>
- </div>
- <div className="mt-3 text-2xl font-semibold text-white">99.97%</div>
- <div className="mt-1 text-xs text-[#9aa0a6]">uptime this week</div>
- </div>
- </aside>
-
- <main className={`${fitViewport ? 'xl:min-h-0' : ''} min-w-0 flex-1`}>{children}</main>
- </div>
- <MobileTabBar user={user} />
- </div>
- )
-}
-
-function AuthCard({ title, subtitle, children, footerText, footerLink, footerLinkText }) {
- return (
- <div className="flex min-h-screen items-center justify-center bg-[radial-gradient(circle_at_top,rgba(255,255,255,0.08),transparent_22%),radial-gradient(circle_at_bottom_right,rgba(255,255,255,0.04),transparent_28%),linear-gradient(180deg,#12171b_0%,#090b0d_100%)] px-4">
- <div className="glass-panel w-full max-w-md rounded-[28px] p-7">
- <div className="mb-8 flex items-center gap-3">
- <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-linear-to-br from-white to-[#cfcfcf] text-lg font-bold text-slate-950">H</div>
- <div>
- <div className="text-lg font-semibold text-white">Homie</div>
- <div className="text-sm text-[#9aa0a6]">{subtitle}</div>
- </div>
- </div>
-
- <div className="mb-6">
- <div className="text-sm uppercase tracking-[0.2em] text-emerald-300">{title}</div>
- <h1 className="mt-2 text-3xl font-semibold text-white">{title === 'Login' ? 'Welcome back' : 'Create account'}</h1>
- </div>
-
- {children}
-
- {footerText && (
- <div className="mt-5 text-center text-sm text-[#9aa0a6]">
- {footerText}{' '}
- <Link to={footerLink} className="font-medium text-emerald-300">{footerLinkText}</Link>
- </div>
- )}
- </div>
- </div>
- )
-}
-
-// null while loading; the backend decides (ALLOW_REGISTRATION, or no accounts exist yet).
-const MIN_PASSWORD_LENGTH = 16
-
-function useRegistrationEnabled() {
- const [config, setConfig] = useState({ enabled: null, bootstrapRequired: false })
- useEffect(() => {
- let active = true
- apiRequest('/auth/config', { method: 'GET' })
- .then((data) => { if (active) setConfig({ enabled: Boolean(data.registration_enabled), bootstrapRequired: Boolean(data.bootstrap_required) }) })
- .catch(() => { if (active) setConfig({ enabled: true, bootstrapRequired: false }) })
- return () => { active = false }
- }, [])
- return config
-}
-
-function LoginPage({ onLogin }) {
- const navigate = useNavigate()
- const { enabled: registrationEnabled } = useRegistrationEnabled()
- const [email, setEmail] = useState('')
- const [password, setPassword] = useState('')
- const [pendingToken, setPendingToken] = useState(null)
- const [code, setCode] = useState('')
- const [error, setError] = useState('')
-
- const finish = (data) => {
- const setupRequired = Boolean(data.setup_required)
- onLogin({ id: data.user.id, name: data.user.name, email: data.user.email, role: data.user.role, setup_required: setupRequired })
- navigate(setupRequired ? '/account' : '/')
- }
-
- const handleSubmit = async (event) => {
- event.preventDefault()
- setError('')
-
- try {
- const data = await apiRequest('/auth/login', {
- method: 'POST',
- body: JSON.stringify({ email, password }),
- })
- if (data.status === 'two_factor_required') {
- setPassword('')
- setPendingToken(data.pending_token)
- return
- }
- finish(data)
- } catch (requestError) {
- setError(requestError.message || 'Invalid email or password.')
- }
- }
-
- const handleCode = async (event) => {
- event.preventDefault()
- setError('')
- try {
- finish(await apiRequest('/auth/login/2fa', { method: 'POST', body: JSON.stringify({ pending_token: pendingToken, code: code.trim() }) }))
- } catch (requestError) {
- setError(requestError.message || 'Invalid code.')
- // An expired or used-up sign-in can't be retried; start again from the password.
- if (requestError.status === 401 && /sign in again|expired/i.test(requestError.message || '')) { setPendingToken(null); setCode('') }
- }
- }
-
- if (pendingToken) {
- return (
- <AuthCard title="Two-factor" subtitle="Second step">
- <form onSubmit={handleCode} className="space-y-4">
- <p className="text-sm text-[#bcbcbc]">Enter the 6-digit code from your authenticator app, or one of your recovery codes.</p>
- <label className="block">
- <span className="mb-2 block text-sm text-[#bcbcbc]">Code</span>
- <input
- type="text"
- inputMode="text"
- autoComplete="one-time-code"
- autoFocus
- maxLength={32}
- value={code}
- onChange={(event) => setCode(event.target.value)}
- className="w-full rounded-2xl border border-neutral-700 bg-neutral-900/70 px-4 py-3 font-mono text-lg tracking-widest text-white outline-none transition focus:border-emerald-400"
- placeholder="123456"
- required
- />
- </label>
- {error && <div className="rounded-xl border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300">{error}</div>}
- <button type="submit" className="flex w-full items-center justify-center rounded-2xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-3 font-medium text-slate-950 transition hover:brightness-110">Verify</button>
- <button type="button" onClick={() => { setPendingToken(null); setCode(''); setError('') }} className="w-full py-2 text-sm text-[#9aa0a6] hover:text-white">Back to sign in</button>
- </form>
- </AuthCard>
- )
- }
-
- return (
- <AuthCard title="Login" subtitle="Secure access" footerText={registrationEnabled ? 'Need an account?' : null} footerLink="/register" footerLinkText="Register here">
- <form onSubmit={handleSubmit} className="space-y-4">
- <label className="block">
- <span className="mb-2 block text-sm text-[#bcbcbc]">Email</span>
- <input
- type="email"
- value={email}
- onChange={(event) => setEmail(event.target.value)}
- className="w-full rounded-2xl border border-neutral-700 bg-neutral-900/70 px-4 py-3 text-white outline-none ring-0 transition focus:border-emerald-400"
- required
- />
- </label>
-
- <label className="block">
- <span className="mb-2 block text-sm text-[#bcbcbc]">Password</span>
- <input
- type="password"
- value={password}
- onChange={(event) => setPassword(event.target.value)}
- className="w-full rounded-2xl border border-neutral-700 bg-neutral-900/70 px-4 py-3 text-white outline-none transition focus:border-emerald-400"
- required
- />
- </label>
-
- {error && <div className="rounded-xl border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300">{error}</div>}
-
- <div className="flex items-center justify-between text-sm text-[#9aa0a6]">
- <label className="inline-flex items-center gap-2 py-2">
- <input type="checkbox" defaultChecked className="h-4 w-4 rounded border-neutral-600 bg-neutral-800" />
- Remember me
- </label>
- <a href="#" className="py-2 text-emerald-300">Forgot password?</a>
- </div>
-
- <button
- type="submit"
- className="mt-2 flex w-full items-center justify-center rounded-2xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-3 font-medium text-slate-950 transition hover:brightness-110"
- >
- Sign in
- </button>
- </form>
- </AuthCard>
- )
-}
-
-function RegisterPage({ onRegister }) {
- const navigate = useNavigate()
- const { enabled: registrationEnabled, bootstrapRequired } = useRegistrationEnabled()
- const [form, setForm] = useState({ name: '', email: '', password: '', bootstrapToken: '' })
- const [error, setError] = useState('')
-
- const handleChange = (event) => {
- setForm((current) => ({
- ...current,
- [event.target.name]: event.target.value,
- }))
- }
-
- const handleSubmit = async (event) => {
- event.preventDefault()
- const trimmedName = form.name.trim()
- const trimmedEmail = form.email.trim()
-
- if (!trimmedName || !trimmedEmail || form.password.length < MIN_PASSWORD_LENGTH) {
- setError(`Please provide a name, an email, and a password of at least ${MIN_PASSWORD_LENGTH} characters.`)
- return
- }
-
- try {
- const data = await apiRequest('/auth/register', {
- method: 'POST',
- body: JSON.stringify({
- name: trimmedName,
- email: trimmedEmail,
- password: form.password,
- bootstrap_token: bootstrapRequired ? form.bootstrapToken.trim() : undefined,
- }),
- })
-
- onRegister({
- id: data.user.id,
- name: data.user.name,
- email: data.user.email,
- role: data.user.role,
- setup_required: Boolean(data.setup_required),
- })
- navigate(data.setup_required ? '/account' : '/')
- } catch (requestError) {
- setError(requestError.message || 'Unable to create account right now.')
- }
- }
-
- return (
- <AuthCard title="Register" subtitle="Create account" footerText="Already have an account?" footerLink="/login" footerLinkText="Log in">
- {registrationEnabled === false ? (
- <p className="rounded-2xl border border-neutral-700 bg-[#111417] p-4 text-sm text-[#bcbcbc]">Registration is disabled on this server. Ask the administrator for an account.</p>
- ) : (
- <form onSubmit={handleSubmit} className="space-y-4">
- <label className="block">
- <span className="mb-2 block text-sm text-[#bcbcbc]">Full name</span>
- <input
- type="text"
- name="name"
- value={form.name}
- onChange={handleChange}
- className="w-full rounded-2xl border border-neutral-700 bg-neutral-900/70 px-4 py-3 text-white outline-none transition focus:border-emerald-400"
- placeholder="Jane Doe"
- required
- />
- </label>
-
- <label className="block">
- <span className="mb-2 block text-sm text-[#bcbcbc]">Email</span>
- <input
- type="email"
- name="email"
- value={form.email}
- onChange={handleChange}
- className="w-full rounded-2xl border border-neutral-700 bg-neutral-900/70 px-4 py-3 text-white outline-none transition focus:border-emerald-400"
- placeholder="[email protected]"
- required
- />
- </label>
-
- <label className="block">
- <span className="mb-2 block text-sm text-[#bcbcbc]">Password</span>
- <input
- type="password"
- name="password"
- value={form.password}
- onChange={handleChange}
- className="w-full rounded-2xl border border-neutral-700 bg-neutral-900/70 px-4 py-3 text-white outline-none transition focus:border-emerald-400"
- placeholder={`At least ${MIN_PASSWORD_LENGTH} characters`}
- minLength={MIN_PASSWORD_LENGTH}
- autoComplete="new-password"
- required
- />
- <span className="mt-2 block text-xs text-[#7f8589]">A few random words make a good passphrase, for example “correct horse battery staple”. Up to 72 bytes.</span>
- </label>
-
- {bootstrapRequired && (
- <label className="block">
- <span className="mb-2 block text-sm text-[#bcbcbc]">Setup token</span>
- <input
- type="password"
- name="bootstrapToken"
- value={form.bootstrapToken}
- onChange={handleChange}
- autoComplete="off"
- className="w-full rounded-2xl border border-neutral-700 bg-neutral-900/70 px-4 py-3 font-mono text-sm text-white outline-none transition focus:border-emerald-400"
- placeholder="hlb_…"
- required
- />
- <span className="mt-2 block text-xs text-[#7f8589]">This install has no accounts yet, so the first one needs its setup token. Find it in the backend log: <code>docker compose logs backend | grep "setup token"</code>, or use the value of <code>ADMIN_BOOTSTRAP_TOKEN</code> if you set one. The first account becomes the admin.</span>
- </label>
- )}
-
- {error && <div className="rounded-xl border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300">{error}</div>}
-
- <button
- type="submit"
- className="mt-2 flex w-full items-center justify-center rounded-2xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-3 font-medium text-slate-950 transition hover:brightness-110"
- >
- Create account
- </button>
- </form>
- )}
- </AuthCard>
- )
-}
-
-// Izvan ili na vrhu komponente postavi guard za izbjegavanje paralelnih poziva
-let isFetchingOverview = false
-
-// Collectors from before per-mount reporting only send the root filesystem's usage.
-function serverMounts(server) {
- if (server.mounts?.length) return server.mounts
- const host = server.host
- return host?.disk_usage_pct != null ? [{ mount: '/', used_pct: host.disk_usage_pct, inodes_pct: host.disk_inodes_pct }] : []
-}
-
-function fullestMount(mounts) {
- return mounts.reduce((fullest, mount) => (mount.used_pct != null && (!fullest || mount.used_pct > fullest.used_pct) ? mount : fullest), null)
-}
-
-const HOST_HISTORY_MINUTES = 30
-
-// Adds the latest check-in unless it's already there (the dashboard polls faster than collectors report).
-function appendHostSample(samples, sample) {
- const last = samples.at(-1)
- if (!sample.time || (last && new Date(sample.time) <= new Date(last.time))) return samples
- const cutoff = new Date(sample.time).getTime() - HOST_HISTORY_MINUTES * 60 * 1000
- return [...samples, sample].filter((item) => new Date(item.time).getTime() >= cutoff)
-}
-
-function formatGigabytes(value) {
- if (value == null) return '?'
- return value >= 1024 ? `${(value / 1024).toFixed(1)} TB` : `${value >= 10 ? value.toFixed(0) : value.toFixed(1)} GB`
-}
-
-const DISK_LEVEL_STYLES = [
- { bar: 'bg-emerald-400/70', text: 'text-[#cfcfcf]' },
- { bar: 'bg-amber-400/80', text: 'text-amber-200' },
- { bar: 'bg-red-400/80', text: 'text-red-300' },
-]
-
-function thresholdLevel(value, warning, critical) {
- if (value == null) return 0
- return value >= critical ? 2 : value >= warning ? 1 : 0
-}
-
-function StorageBars({ mounts, thresholds, mountThresholds }) {
- if (!mounts.length) return null
- const t = { disk_warning_pct: 85, disk_critical_pct: 95, inodes_warning_pct: 85, inodes_critical_pct: 95, ...thresholds }
- return (
- <div className="mt-4">
- <div className="mb-2 text-xs uppercase tracking-[0.2em] text-[#7f8589]">Storage</div>
- <div className="space-y-2">
- {mounts.map((mount) => {
- const own = mountThresholds?.[mount.mount]
- const style = DISK_LEVEL_STYLES[thresholdLevel(mount.used_pct, own?.disk_warning_pct ?? t.disk_warning_pct, own?.disk_critical_pct ?? t.disk_critical_pct)]
- const inodeLevel = thresholdLevel(mount.inodes_pct, t.inodes_warning_pct, t.inodes_critical_pct)
- const used = Math.min(100, Math.max(0, mount.used_pct ?? 0))
- return (
- <div key={mount.mount} className="grid grid-cols-[minmax(0,9rem)_1fr_auto] items-center gap-3 text-sm sm:grid-cols-[minmax(0,12rem)_1fr_auto]">
- <span className="truncate font-mono text-xs text-[#bcbcbc]" title={mount.fs_type ? `${mount.mount} (${mount.fs_type})` : mount.mount}>{mount.mount}</span>
- <div className="h-2 overflow-hidden rounded-full bg-white/5" role="meter" aria-label={`${mount.mount} usage`} aria-valuemin={0} aria-valuemax={100} aria-valuenow={used}>
- <div className={`h-full rounded-full ${style.bar}`} style={{ width: `${used}%` }} />
- </div>
- <span className="whitespace-nowrap text-right text-xs text-[#9aa0a6]">
- {mount.total_gb != null && <span className="hidden sm:inline">{formatGigabytes(mount.used_gb)} / {formatGigabytes(mount.total_gb)} · </span>}
- <span className={`font-medium ${style.text}`}>{mount.used_pct == null ? '—' : `${Math.round(mount.used_pct)}%`}</span>
- {inodeLevel > 0 && <span className={`ml-2 ${DISK_LEVEL_STYLES[inodeLevel].text}`}>inodes {Math.round(mount.inodes_pct)}%</span>}
- </span>
- </div>
- )
- })}
- </div>
- </div>
- )
-}
-
-function readStoredIds(storageKey) {
- try {
- const stored = JSON.parse(window.localStorage.getItem(storageKey))
- return new Set(Array.isArray(stored) ? stored : [])
- } catch {
- return new Set()
- }
-}
-
-// A set of ids kept in localStorage; falls back to in-memory state when storage is unavailable.
-function useStoredIdSet(storageKey) {
- const [ids, setIds] = useState(() => readStoredIds(storageKey))
- useEffect(() => {
- try {
- window.localStorage.setItem(storageKey, JSON.stringify([...ids]))
- } catch {
- // Private windows and blocked storage: keep the state for this visit only.
- }
- }, [storageKey, ids])
- const toggle = (id) => setIds((current) => {
- const next = new Set(current)
- if (next.has(id)) next.delete(id)
- else next.add(id)
- return next
- })
- return [ids, toggle, (list) => setIds(new Set(list))]
-}
-
-// Like useStoredIdSet but forgotten on reload, so these sections always start collapsed.
-function useIdSet() {
- const [ids, setIds] = useState(() => new Set())
- const toggle = (id) => setIds((current) => {
- const next = new Set(current)
- if (next.has(id)) next.delete(id)
- else next.add(id)
- return next
- })
- return [ids, toggle]
-}
-
-function Chevron({ open, className = '' }) {
- return <span aria-hidden="true" className={`inline-block text-[10px] text-[#7f8589] transition-transform ${open ? 'rotate-90' : ''} ${className}`}>▶</span>
-}
-
-const CONTAINER_SEARCH_MIN = 10
-const byName = (a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base', numeric: true })
-
-const CONTAINER_EVENT_LABELS = { container_added: 'Added', container_removed: 'Removed', image_changed: 'Image change', container_notice: 'Notice' }
-const CONTAINER_EVENT_CLASSES = { container_added: 'text-emerald-300', container_removed: 'text-amber-300', image_changed: 'text-sky-300', container_notice: 'text-[#9aa0a6]' }
-
-function DockerNotice({ host }) {
- const reasons = { timeout: 'it did not answer in time', refused: 'the connection was refused', missing: 'its socket is missing', denied: 'access was denied', error: 'it returned an error' }
- return <div className="mt-4 rounded-xl border border-amber-400/30 bg-amber-400/5 px-3 py-2.5 text-sm text-amber-200">Docker is unreachable{host.docker_reason ? `: ${reasons[host.docker_reason] || reasons.error}` : ''}. Container data is not updating until it is back.</div>
-}
-
-function ContainerSection({ server, open, onToggle }) {
- const [query, setQuery] = useState('')
- const containers = [...server.containers].sort(byName)
- const count = (predicate) => containers.filter(predicate).length
- const running = count((c) => c.status === 'running')
- const unhealthy = count((c) => c.healthcheck_status === 'unhealthy')
- const restarting = count((c) => c.status === 'restarting')
- const stopped = count((c) => c.status === 'exited' || c.status === 'dead')
- const needle = query.trim().toLowerCase()
- const shown = needle ? containers.filter((c) => `${c.name} ${c.image || ''}`.toLowerCase().includes(needle)) : containers
-
- return (
- <div className="mt-4 rounded-xl border border-neutral-800">
- <button type="button" onClick={onToggle} aria-expanded={open} className="flex w-full flex-wrap items-center gap-x-3 gap-y-1 rounded-xl px-3 py-2.5 text-left text-sm transition hover:bg-white/3">
- <Chevron open={open} />
- <span className="text-white">Containers <span className="text-[#7f8589]">({containers.length})</span></span>
- <span className="text-[#9aa0a6]">{running} running</span>
- {unhealthy > 0 && <span className="text-red-300">{unhealthy} unhealthy</span>}
- {restarting > 0 && <span className="text-red-300">{restarting} restarting</span>}
- {stopped > 0 && <span className="text-amber-300">{stopped} stopped</span>}
- </button>
- {open && (
- <div className="border-t border-neutral-800 px-3 pb-2">
- {containers.length > CONTAINER_SEARCH_MIN && <input type="search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Filter by name or image" aria-label={`Filter containers on ${server.hostname}`} className="mt-3 w-full rounded-lg border border-neutral-800 bg-[#0d1013] px-3 py-1.5 text-sm text-[#cfcfcf] outline-none focus:border-white/30" />}
- {shown.length ? <ContainerTable serverId={server.id} containers={shown} /> : <p className="py-3 text-sm text-[#9aa0a6]">No containers match “{query.trim()}”.</p>}
- {server.container_events?.length > 0 && (
- <div className="mt-2 border-t border-neutral-800 pt-3">
- <div className="mb-2 text-xs uppercase tracking-[0.2em] text-[#7f8589]">Recent changes · 7 days</div>
- <ul className="space-y-1.5 pb-1 text-sm">{server.container_events.map((event, index) => (
- <li key={`${event.time}-${event.kind}-${index}`} className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5">
- <span className="w-24 shrink-0 text-xs text-[#7f8589]" title={new Date(event.time).toLocaleString()}>{formatAgo(event.time)}</span>
- <span className={`w-24 shrink-0 text-xs font-medium ${CONTAINER_EVENT_CLASSES[event.kind] || 'text-[#cfcfcf]'}`}>{CONTAINER_EVENT_LABELS[event.kind] || event.kind}</span>
- <span className="min-w-0 flex-1 basis-60 break-words text-[#bcbcbc]">{event.detail}</span>
- </li>
- ))}</ul>
- </div>
- )}
- </div>
- )}
- </div>
- )
-}
-
-const TAINT_FAULT_BITS = [4, 5, 7, 9, 14]
-const SYSTEM_EVENT_LABELS = { reboot: 'Reboot', oom_kill: 'OOM kill', kernel_fault: 'Kernel fault', kernel_error: 'Kernel error', credentials_replaced: 'Credentials replaced' }
-const SYSTEM_EVENT_CLASSES = { reboot: 'text-sky-300', oom_kill: 'text-amber-300', kernel_fault: 'text-red-300', kernel_error: 'text-amber-300', credentials_replaced: 'text-amber-300' }
-const CHIP_CLASSES = { ok: 'text-emerald-300', warn: 'text-amber-300', info: 'text-sky-300', unknown: 'text-[#7f8589]' }
-
-function formatAgo(value) {
- const seconds = Math.max(0, Math.floor((Date.now() - new Date(value).getTime()) / 1000))
- if (seconds < 90) return 'just now'
- if (seconds < 5400) return `${Math.round(seconds / 60)}m ago`
- if (seconds < 172800) return `${Math.round(seconds / 3600)}h ago`
- return `${Math.round(seconds / 86400)}d ago`
-}
-
-function systemChips(host, events) {
- const oomRecently = events.some((event) => event.kind === 'oom_kill' && Date.now() - new Date(event.time).getTime() < 24 * 3600 * 1000)
- const faulty = host.kernel_tainted != null && TAINT_FAULT_BITS.some((bit) => (host.kernel_tainted >> bit) & 1)
- return [
- ['Booted', host.system_uptime_seconds == null ? 'unknown' : formatAgo(Date.now() - host.system_uptime_seconds * 1000), host.system_uptime_seconds == null ? 'unknown' : events.some((event) => event.kind === 'reboot' && Date.now() - new Date(event.time).getTime() < 3600 * 1000) ? 'info' : 'ok'],
- ['Last shutdown', host.last_shutdown == null || host.last_shutdown === 'unknown' ? 'unknown' : host.last_shutdown, host.last_shutdown === 'clean' ? 'ok' : host.last_shutdown === 'unclean' ? 'warn' : 'unknown'],
- ['Clock', host.ntp_synced == null ? 'unknown' : host.ntp_synced ? 'synced' : 'not synced', host.ntp_synced == null ? 'unknown' : host.ntp_synced ? 'ok' : 'warn'],
- ['OOM kills (24h)', host.oom_kill_total == null ? 'unknown' : oomRecently ? 'yes' : 'none', host.oom_kill_total == null ? 'unknown' : oomRecently ? 'warn' : 'ok'],
- ['Kernel', host.kernel_tainted == null ? 'unknown' : faulty ? 'faults reported' : 'clean', host.kernel_tainted == null ? 'unknown' : faulty ? 'warn' : 'ok'],
- ['Updates', host.reboot_required == null ? 'unknown' : host.reboot_required ? 'reboot needed' : 'applied', host.reboot_required == null ? 'unknown' : host.reboot_required ? 'info' : 'ok'],
- ]
-}
-
-function SystemSection({ server, open, onToggle }) {
- const host = server.host
- const events = server.system_events || []
- const chips = systemChips(host, events)
- return (
- <div className="mt-4 rounded-xl border border-neutral-800">
- <button type="button" onClick={onToggle} aria-expanded={open} className="flex w-full flex-wrap items-center gap-x-4 gap-y-1 rounded-xl px-3 py-2.5 text-left text-sm transition hover:bg-white/3">
- <Chevron open={open} />
- <span className="text-white">System</span>
- {chips.map(([label, value, tone]) => <span key={label} className="whitespace-nowrap text-xs text-[#7f8589]">{label} <span className={`font-medium ${CHIP_CLASSES[tone]}`}>{value}</span></span>)}
- </button>
- {open && (
- <div className="border-t border-neutral-800 px-3 py-3">
- <div className="mb-2 text-xs uppercase tracking-[0.2em] text-[#7f8589]">Recent events · 7 days</div>
- {events.length ? <ul className="space-y-1.5 text-sm">{events.map((event, index) => (
- <li key={`${event.time}-${event.kind}-${index}`} className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5">
- <span className="w-24 shrink-0 text-xs text-[#7f8589]" title={event.count > 1 ? `Last seen ${new Date(event.time).toLocaleString()}` : new Date(event.time).toLocaleString()}>{formatAgo(event.time)}</span>
- <span className={`w-24 shrink-0 text-xs font-medium ${SYSTEM_EVENT_CLASSES[event.kind] || 'text-[#cfcfcf]'}`}>{SYSTEM_EVENT_LABELS[event.kind] || event.kind}</span>
- <span className="min-w-0 flex-1 basis-60 break-words text-[#bcbcbc]">{event.detail}{event.count > 1 && <span className="ml-2 whitespace-nowrap rounded-full bg-white/10 px-2 py-0.5 text-[10px] font-medium text-[#cfcfcf]" title={`Seen ${event.count} times · first ${formatAgo(event.first_time)}, last ${formatAgo(event.time)}`}>×{event.count}</span>}</span>
- </li>
- ))}</ul> : <p className="text-sm text-[#9aa0a6]">No reboots, OOM kills or kernel faults in the last 7 days.</p>}
- {events.some((event) => event.count > 1) && <p className="mt-2 text-xs text-[#7f8589]">Repeated kernel messages are shown once with a count; the time is when each was last seen.</p>}
- {host.last_shutdown == null && <p className="mt-3 text-xs text-[#7f8589]">“Unknown” means the collector couldn't read that value on this host, not that anything is wrong. Last shutdown, OOM process names and kernel errors need the optional system helper (see SECURITY.md).</p>}
- </div>
- )}
- </div>
- )
-}
-
-const NETWORK_EVENT_LABELS = { port_opened: 'Port opened', port_closed: 'Port closed', firewall_changed: 'Firewall', firewall_weakened: 'Firewall', network_notice: 'Notice' }
-const NETWORK_EVENT_CLASSES = { port_opened: 'text-amber-300', port_closed: 'text-[#9aa0a6]', firewall_changed: 'text-sky-300', firewall_weakened: 'text-red-300', network_notice: 'text-[#9aa0a6]' }
-const LISTENER_SCOPE_LABELS = { loopback: 'loopback only', any: 'all interfaces', specific: 'one address' }
-const INTERNET_LABELS = { ok: ['reachable', 'ok'], degraded: ['partly reachable', 'warn'], dns_failed: ['DNS failing', 'warn'], down: ['down', 'warn'] }
-
-function networkChips(server) {
- const host = server.host
- const network = server.network || { listeners: [], firewall: [], events: [] }
- const internet = INTERNET_LABELS[host.internet_status]
- const exposed = network.listeners.filter((listener) => listener.scope !== 'loopback').length
- const ufw = network.firewall.find((file) => file.name === 'ufw-conf')
- const ruleFiles = network.firewall.filter((file) => file.name !== 'ufw-conf' && file.rules > 0)
- const firewall = [ufw ? (ufw.enabled === true ? 'ufw enabled' : ufw.enabled === false ? 'ufw disabled' : null) : null, ...ruleFiles.map((file) => `${file.label.split(' ')[0]} ${file.rules} rules`)].filter(Boolean)
- return [
- ['Internet', internet ? internet[0] : 'not checked', internet ? internet[1] : 'unknown'],
- ['Listening', network.listeners.length ? `${network.listeners.length} ports · ${exposed} exposed` : 'unknown', network.listeners.length ? 'ok' : 'unknown'],
- ['Firewall', firewall.length ? firewall.join(' · ') : 'no config found', ufw?.enabled === false ? 'warn' : firewall.length ? 'ok' : 'unknown'],
- ]
-}
-
-function NetworkSection({ server, open, onToggle }) {
- const network = server.network || { listeners: [], firewall: [], events: [] }
- const chips = networkChips(server)
- const exposed = network.listeners.filter((listener) => listener.scope !== 'loopback')
- const local = network.listeners.filter((listener) => listener.scope === 'loopback')
- const listenerLine = (listener) => <li key={`${listener.proto}-${listener.port}-${listener.scope}`} className="whitespace-nowrap rounded-md bg-white/5 px-2 py-1 font-mono text-xs text-[#cfcfcf]" title={LISTENER_SCOPE_LABELS[listener.scope]}>{listener.proto}/{listener.port}</li>
- return (
- <div className="mt-4 rounded-xl border border-neutral-800">
- <button type="button" onClick={onToggle} aria-expanded={open} className="flex w-full flex-wrap items-center gap-x-4 gap-y-1 rounded-xl px-3 py-2.5 text-left text-sm transition hover:bg-white/3">
- <Chevron open={open} />
- <span className="text-white">Network</span>
- {chips.map(([label, value, tone]) => <span key={label} className="whitespace-nowrap text-xs text-[#7f8589]">{label} <span className={`font-medium ${CHIP_CLASSES[tone]}`}>{value}</span></span>)}
- </button>
- {open && (
- <div className="space-y-4 border-t border-neutral-800 px-3 py-3">
- {network.listeners.length > 0 && <div>
- <div className="mb-2 text-xs uppercase tracking-[0.2em] text-[#7f8589]">Listening ports</div>
- {exposed.length > 0 && <div className="mb-2"><div className="mb-1 text-xs text-amber-300">Reachable from other machines ({exposed.length})</div><ul className="flex flex-wrap gap-1.5">{exposed.map(listenerLine)}</ul></div>}
- {local.length > 0 && <div><div className="mb-1 text-xs text-[#7f8589]">This machine only ({local.length})</div><ul className="flex flex-wrap gap-1.5">{local.map(listenerLine)}</ul></div>}
- </div>}
- <div>
- <div className="mb-2 text-xs uppercase tracking-[0.2em] text-[#7f8589]">Recent changes · 7 days</div>
- {network.events.length ? <ul className="space-y-1.5 text-sm">{network.events.map((event, index) => (
- <li key={`${event.time}-${event.kind}-${index}`} className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5">
- <span className="w-24 shrink-0 text-xs text-[#7f8589]" title={new Date(event.time).toLocaleString()}>{formatAgo(event.time)}</span>
- <span className={`w-24 shrink-0 text-xs font-medium ${NETWORK_EVENT_CLASSES[event.kind] || 'text-[#cfcfcf]'}`}>{NETWORK_EVENT_LABELS[event.kind] || event.kind}</span>
- <span className="min-w-0 flex-1 basis-60 break-words text-[#bcbcbc]">{event.detail}</span>
- </li>
- ))}</ul> : <p className="text-sm text-[#9aa0a6]">No new listeners or firewall changes in the last 7 days.</p>}
- </div>
- <p className="text-xs text-[#7f8589]">The firewall chip reads configuration files, not the live ruleset. The internet check is off unless <code>HOMELAB_CONNECTIVITY_TARGETS</code> is set on that machine's collector.</p>
- </div>
- )}
- </div>
- )
-}
-
-const HEALTH_CLASSES = { healthy: 'text-[#7f8589]', unhealthy: 'text-red-300', starting: 'text-amber-300' }
-
-const ALERT_STYLES = {
- CRITICAL: { box: 'border-red-400/25 bg-red-500/5', badge: 'bg-red-500/15 text-red-300', title: 'text-red-200' },
- WARNING: { box: 'border-amber-400/20 bg-amber-400/5', badge: 'bg-amber-400/15 text-amber-300', title: 'text-amber-200' },
- INFO: { box: 'border-sky-400/20 bg-sky-400/5', badge: 'bg-sky-400/15 text-sky-300', title: 'text-sky-200' },
-}
-
-function DashboardPage({ user, onLogout }) {
- const [overview, setOverview] = useState({ servers: [], alerts: [] })
- const [error, setError] = useState('')
- const [showConnect, setShowConnect] = useState(false)
- const [deletingServerId, setDeletingServerId] = useState(null)
- // Recent samples of the machine running the dashboard: loaded from the backend, then extended live.
- const [history, setHistory] = useState({ serverId: null, samples: [] })
-
-const refresh = async () => {
- // Ako je zahtjev već u tijeku, preskoči ovaj poziv
- if (isFetchingOverview) return
- isFetchingOverview = true
-
- try {
- const data = await apiRequest('/monitoring/overview', { method: 'GET' })
- setOverview(data)
- setError('')
-
- const host = (data.servers || []).find((server) => server.is_dashboard_host)
- if (host?.host) {
- const sample = { time: host.host.time, cpu: host.host.cpu_utilization_pct, ram: host.host.ram_pct, disk: host.host.disk_usage_pct }
- setHistory((current) => current.serverId === host.id ? { ...current, samples: appendHostSample(current.samples, sample) } : current)
- }
- } catch (requestError) {
- // Ako backend vrati 401 (neautoriziran/odjavljen korisnik), odjavi ga i prekini petlju
- if (requestError.status === 401 || requestError.message?.includes('401')) {
- if (typeof onLogout === 'function') {
- onLogout()
- }
- return
- }
- setError(requestError.message || 'Could not load monitoring data.')
- } finally {
- // Oslobodi guard za sljedeći interval
- isFetchingOverview = false
- }
-}
-
- // ✅ ISPRAVAK: Koristimo primitive `user?.id` umjesto cijelog `user` objekta
- useEffect(() => {
- if (!user) return
-
- // Inicijalno učitavanje
- refresh()
-
- // No polling while the tab is hidden; refresh straight away when it comes back.
- let timer = null
- const start = () => { if (timer === null) timer = setInterval(refresh, LIVE_GRAPH_REFRESH_INTERVAL_SECONDS * 1000) }
- const stop = () => { if (timer !== null) { clearInterval(timer); timer = null } }
- const onVisibilityChange = () => {
- if (document.hidden) { stop(); return }
- refresh()
- start()
- }
- if (!document.hidden) start()
- document.addEventListener('visibilitychange', onVisibilityChange)
-
- // Obavezno čišćenje timera pri unmountu
- return () => {
- stop()
- document.removeEventListener('visibilitychange', onVisibilityChange)
- }
- }, [user?.id]) // <-- Stabilna instanca, okida se samo pri promjeni ID-a
-
- const servers = overview.servers || []
- // Remembered per browser: which server cards are collapsed and which container lists are open.
- const [collapsedServers, toggleServer, setCollapsedServers] = useStoredIdSet('homelab.collapsedServers')
- const [openContainerLists, toggleContainerList] = useIdSet()
- const [openSystemLists, toggleSystemList] = useIdSet()
- const [openNetworkLists, toggleNetworkList] = useIdSet()
- const allCollapsed = servers.length > 0 && servers.every((server) => collapsedServers.has(server.id))
- const dashboardHost = servers.find((server) => server.is_dashboard_host)
- const dashboardHostId = dashboardHost?.id
-
- useEffect(() => {
- if (!dashboardHostId) return
- let cancelled = false
- apiRequest(`/monitoring/servers/${dashboardHostId}/history?minutes=${HOST_HISTORY_MINUTES}`, { method: 'GET' })
- .then((data) => { if (!cancelled) setHistory({ serverId: dashboardHostId, samples: data.samples }) })
- .catch(() => { if (!cancelled) setHistory({ serverId: dashboardHostId, samples: [] }) })
- return () => { cancelled = true }
- }, [dashboardHostId])
-
- const changeInterval = async (server, value) => {
- try {
- await apiRequest(`/monitoring/servers/${server.id}/interval`, { method: 'PATCH', body: JSON.stringify({ check_interval_seconds: Number(value) }) })
- await refresh()
- } catch (requestError) { setError(requestError.message || 'Could not update interval.') }
- }
- const deleteServer = async (server) => {
- if (!window.confirm(`Delete ${server.hostname} and all its stored metrics and incidents? This cannot be undone.`)) return
- setDeletingServerId(server.id)
- try {
- await apiRequest(`/monitoring/servers/${server.id}`, { method: 'DELETE' })
- await refresh()
- } catch (requestError) {
- setError(requestError.message || 'Could not delete server.')
- } finally {
- setDeletingServerId(null)
- }
- }
- const online = servers.filter((server) => server.last_seen_at && Date.now() - new Date(server.last_seen_at).getTime() < server.check_interval_seconds * 3000).length
- const hostSamples = history.serverId === dashboardHostId ? history.samples : []
- const hostMetric = dashboardHost?.host
- const runningContainers = servers.reduce((sum, server) => sum + server.containers.filter((container) => container.status === 'running').length, 0)
-
- // Regular users get a read-only view; the backend enforces the same rules.
- const isAdmin = user?.role === 'admin'
-
- return (
- <AppShell user={user} onLogout={onLogout}>
- <div className="flex flex-col gap-5">
- <header className="glass-panel rounded-[28px] p-5 md:p-6">
- <div className="flex flex-wrap items-end justify-between gap-4">
- <div><div className="text-xs uppercase tracking-[0.22em] text-[#9aa0a6]">Infrastructure overview</div><h1 className="mt-1 text-3xl font-semibold text-white">Dashboard</h1><p className="mt-2 text-sm text-[#9aa0a6]">Live host and container health · updated every {LIVE_GRAPH_REFRESH_INTERVAL_SECONDS} seconds.</p></div>
- {isAdmin && <button type="button" onClick={() => setShowConnect((current) => !current)} aria-expanded={showConnect} className="rounded-xl bg-white px-4 py-2 text-sm font-medium text-slate-950">{showConnect ? 'Close' : 'Connect a server'}</button>}
- </div>
- {error && <div className="mt-4 rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-sm text-amber-200">{error}</div>}
- {isAdmin && showConnect && <ConnectServerPanel />}
- </header>
-
- <section className="grid grid-cols-3 gap-2 sm:gap-4">
- {[
- ['Servers online', `${online} / ${servers.length}`, 'Based on last check-in'],
- ['Containers running', String(runningContainers), 'Across monitored servers'],
- ['Active incidents', String(overview.alert_count ?? overview.alerts?.length ?? 0), 'Needs attention'],
- ].map(([label, value, detail]) => <div key={label} className="glass-panel rounded-2xl p-3 sm:rounded-[24px] sm:p-5"><div className="text-xs leading-4 text-[#9aa0a6] sm:text-sm">{label}</div><div className="mt-2 text-2xl font-semibold text-white sm:mt-3 sm:text-3xl">{value}</div><div className="mt-2 hidden text-xs text-[#7f8589] sm:block">{detail}</div></div>)}
- </section>
-
- <section>
- <div className="mb-3 flex flex-wrap items-baseline justify-between gap-2 px-1">
- <div className="text-xs uppercase tracking-[0.2em] text-[#9aa0a6]">This machine{dashboardHost && <span className="ml-2 normal-case tracking-normal text-[#cfcfcf]">{dashboardHost.hostname}</span>}</div>
- <span className="text-xs text-[#7f8589]">Last {HOST_HISTORY_MINUTES} minutes</span>
- </div>
- {dashboardHost ? <div className="grid gap-4 xl:grid-cols-3">
- {[
- { key: 'cpu', title: 'CPU utilization', color: '#34d399', latest: hostMetric?.cpu_utilization_pct },
- { key: 'ram', title: 'Memory utilization', color: '#60a5fa', latest: hostMetric?.ram_pct },
- { key: 'disk', title: 'Disk usage (/)', color: '#c084fc', latest: hostMetric?.disk_usage_pct },
- ].map((chart) => <MetricTrend key={chart.key} title={chart.title} color={chart.color} value={chart.latest == null ? '—' : Number(chart.latest).toFixed(1)} points={hostSamples.map((sample) => sample[chart.key])} times={hostSamples.map((sample) => sample.time)} />)}
- </div> : <div className="glass-panel rounded-[24px] p-5 text-sm text-[#9aa0a6]">The machine running the dashboard isn't reporting yet. Its collector starts with the dashboard's compose stack and shows up here once it's added under <span className="text-white">New servers detected</span>.</div>}
- </section>
-
- <section className="glass-panel rounded-[28px] p-5 md:p-6">
- <div className="mb-4 flex items-center justify-between"><div><div className="text-xs uppercase tracking-[0.2em] text-[#9aa0a6]">Fleet</div><h2 className="mt-1 text-xl font-semibold text-white">Monitored servers</h2></div><div className="flex items-center gap-3"><span className="text-sm text-[#9aa0a6]">{servers.length} configured</span>{servers.length > 1 && <button type="button" onClick={() => setCollapsedServers(allCollapsed ? [] : servers.map((server) => server.id))} className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-[#cfcfcf] transition hover:bg-white/10">{allCollapsed ? 'Expand all' : 'Collapse all'}</button>}</div></div>
- {isAdmin && <PendingServers pending={overview.pending_collectors || []} onChanged={refresh} />}
- {!servers.length ? <div className="rounded-2xl border border-dashed border-neutral-700 p-8 text-center"><div className="text-lg font-medium text-white">No servers registered</div><p className="mt-2 text-sm text-[#9aa0a6]">{isAdmin ? <>Click <span className="text-white">Connect a server</span> above and run the command on each machine you want to monitor.</> : 'An admin needs to connect a server before it shows up here.'}</p></div> : <div className="space-y-3">{servers.map((server) => {
- const metric = server.host
- const mounts = serverMounts(server)
- const fullest = fullestMount(mounts)
- const fresh = server.last_seen_at && Date.now() - new Date(server.last_seen_at).getTime() < server.check_interval_seconds * 3000
- const collapsed = collapsedServers.has(server.id)
- const alertBadge = server.active_alert_count > 0 && <span className="rounded-full bg-amber-400/15 px-2 py-0.5 text-[10px] font-semibold tracking-wider text-amber-300">{server.active_alert_count} {server.active_alert_count === 1 ? 'incident' : 'incidents'}</span>
- return <article key={server.id} className={`rounded-2xl border border-neutral-800 bg-[#0d1013]/70 ${collapsed ? 'px-4 py-3 md:px-5' : 'p-4 md:p-5'}`}>
- <div className={`flex flex-wrap justify-between gap-3 ${collapsed ? 'items-center' : 'items-start'}`}>
- <button type="button" onClick={() => toggleServer(server.id)} aria-expanded={!collapsed} className="flex min-w-0 max-w-full items-start gap-2 py-1 text-left">
- <Chevron open={!collapsed} className="mt-2" />
- <span className="min-w-0">
- <span className="flex min-w-0 items-center gap-2"><span aria-label={fresh ? 'Online' : 'Offline'} className={`h-2.5 w-2.5 shrink-0 rounded-full ${fresh ? 'bg-emerald-400' : 'bg-neutral-600'}`} /><span className="truncate text-lg font-medium text-white" title={server.hostname}>{server.hostname}</span></span>
- {(server.is_dashboard_host || alertBadge) && <span className="mt-1.5 flex flex-wrap items-center gap-2">{server.is_dashboard_host && <span className="rounded-full border border-white/10 bg-white/5 px-2 py-0.5 text-[10px] uppercase tracking-wider text-[#cfcfcf]">This machine</span>}{alertBadge}</span>}
- {!collapsed && <span className="mt-1 block text-sm text-[#9aa0a6]">{server.os_info || server.ip_address || 'Waiting for first collector check-in'}{server.cpu_cores ? ` · ${server.cpu_cores} cores` : ''}</span>}
- </span>
- </button>
- {collapsed ? (metric ? <div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-[#9aa0a6]">{[['CPU', metric.cpu_utilization_pct], ['RAM', metric.ram_pct], [fullest ? `Disk ${fullest.mount}` : 'Disk', fullest?.used_pct]].map(([label, value]) => <span key={label} className="whitespace-nowrap">{label} <span className="font-medium text-white">{value == null ? '—' : `${Math.round(value)}%`}</span></span>)}</div> : <span className="text-sm text-[#7f8589]">No measurement yet</span>)
- : isAdmin ? <div className="flex flex-wrap items-center gap-2"><label className="flex items-center gap-2 text-xs text-[#9aa0a6]">Check interval<select value={server.check_interval_seconds} onChange={(e) => changeInterval(server, e.target.value)} className="min-h-10 sm:min-h-0 rounded-lg border border-neutral-700 bg-[#111417] px-2 py-1.5 text-sm text-white"><option value="15">15 sec</option><option value="30">30 sec</option><option value="60">1 min</option><option value="300">5 min</option><option value="900">15 min</option></select></label><button type="button" onClick={() => deleteServer(server)} disabled={deletingServerId === server.id} className="min-h-10 sm:min-h-0 rounded-lg border border-red-400/30 bg-red-500/5 px-3 py-1.5 text-xs text-red-300 transition hover:bg-red-500/10 disabled:opacity-50">{deletingServerId === server.id ? 'Deleting…' : 'Delete server'}</button></div> : <span className="text-xs text-[#9aa0a6]">Checks every {server.check_interval_seconds < 60 ? `${server.check_interval_seconds} sec` : `${Math.round(server.check_interval_seconds / 60)} min`}</span>}
- </div>
- {!collapsed && <>
- {metric ? <div className="mt-5 grid grid-cols-2 gap-3 lg:grid-cols-4">{[['CPU', metric.cpu_utilization_pct, '%'], ['RAM', metric.ram_pct, '%'], [fullest ? `Disk · ${fullest.mount}` : 'Disk', fullest?.used_pct, '%'], ['Load (1m)', metric.load_1m, '']].map(([label, value, unit]) => <div key={label} className="rounded-xl bg-[#171b1f] p-3"><div className="truncate text-xs text-[#9aa0a6]" title={label}>{label}</div><div className="mt-1 text-xl font-semibold text-white">{value == null ? '—' : `${Number(value).toFixed(1)}${unit}`}</div></div>)}</div> : <div className="mt-4 rounded-xl bg-[#171b1f] p-4 text-sm text-[#9aa0a6]">Collector has not sent a measurement yet.</div>}
- {metric && <StorageBars mounts={mounts} thresholds={overview.disk_thresholds} mountThresholds={overview.mount_thresholds} />}
- {metric?.docker_status === 'unreachable' && <DockerNotice host={metric} />}
- {metric && <SystemSection server={server} open={openSystemLists.has(server.id)} onToggle={() => toggleSystemList(server.id)} />}
- {metric && <NetworkSection server={server} open={openNetworkLists.has(server.id)} onToggle={() => toggleNetworkList(server.id)} />}
- {server.containers.length > 0 && <ContainerSection server={server} open={openContainerLists.has(server.id)} onToggle={() => toggleContainerList(server.id)} />}
- <div className="mt-3 text-xs text-[#7f8589]">Last check: {server.last_seen_at ? new Date(server.last_seen_at).toLocaleString() : 'Never'}</div>
- </>}
- </article>
- })}</div>}
- </section>
- <section className="glass-panel rounded-[28px] p-5 md:p-6"><div className="mb-4"><div className="text-xs uppercase tracking-[0.2em] text-[#9aa0a6]">Alerts</div><h2 className="mt-1 text-xl font-semibold text-white">Active incidents</h2></div>{overview.alerts?.length ? <div className="space-y-2">{overview.alerts.map((alert) => { const style = ALERT_STYLES[alert.severity] || ALERT_STYLES.WARNING; return <div key={alert.id} className={`rounded-xl border p-3 ${style.box}`}><div className="flex items-center gap-2"><span className={`rounded-full px-2 py-0.5 text-[10px] font-semibold tracking-wider ${style.badge}`}>{alert.severity}</span><div className={`font-medium ${style.title}`}>{alert.title}</div></div><div className="mt-1 text-xs text-[#9aa0a6]">{alert.hostname || `Server ${alert.server_id}`} · since {new Date(alert.created_at).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' })}</div><div className="mt-1 text-sm text-[#bcbcbc]">{alert.description}</div></div> })}{overview.alert_count > overview.alerts.length ? <p className="text-xs text-[#9aa0a6]">Showing the {overview.alerts.length} most severe of {overview.alert_count} incidents.</p> : null}</div> : <p className="text-sm text-[#9aa0a6]">No active incidents recorded.</p>}</section>
- </div>
- </AppShell>
- )
-}
-
-function CopyableCommand({ label, text }) {
- const [copied, setCopied] = useState(false)
- const copy = async () => {
- try {
- await navigator.clipboard.writeText(text)
- setCopied(true)
- setTimeout(() => setCopied(false), 1500)
- } catch {
- setCopied(false)
- }
- }
- return (
- <div className="mt-3">
- <div className="flex items-center justify-between gap-2 text-xs text-[#9aa0a6]"><span>{label}</span><button type="button" onClick={copy} className="rounded-lg border border-neutral-700 px-2 py-1 text-[11px] text-[#cfcfcf] hover:bg-white/5">{copied ? 'Copied' : 'Copy'}</button></div>
- <pre className="custom-scroll mt-1 overflow-x-auto rounded-xl bg-[#090b0d] p-3 text-xs text-[#cfcfcf]">{text}</pre>
- </div>
- )
-}
-
-function EnrollmentKeySettings() {
- const [keyInfo, setKeyInfo] = useState(null)
- const [enrollKey, setEnrollKey] = useState('')
- const [busy, setBusy] = useState(false)
- const [confirmRevoke, setConfirmRevoke] = useState(false)
- const [error, setError] = useState('')
-
- useEffect(() => {
- apiRequest('/monitoring/enrollment-key', { method: 'GET' })
- .then(setKeyInfo)
- .catch((requestError) => setError(requestError.message || 'Could not load enrollment key.'))
- }, [])
-
- const generateKey = async () => {
- setBusy(true); setError('')
- try {
- const data = await apiRequest('/monitoring/enrollment-key', { method: 'POST' })
- setEnrollKey(data.enroll_key)
- setKeyInfo({ exists: true, created_at: data.created_at })
- } catch (requestError) { setError(requestError.message || 'Could not create enrollment key.') }
- finally { setBusy(false) }
- }
-
- const revokeKey = async () => {
- setBusy(true); setError('')
- try {
- await apiRequest('/monitoring/enrollment-key', { method: 'DELETE' })
- setEnrollKey(''); setKeyInfo({ exists: false, created_at: null }); setConfirmRevoke(false)
- } catch (requestError) { setError(requestError.message || 'Could not revoke enrollment key.') }
- finally { setBusy(false) }
- }
-
- return (
- <div className="mt-3">
- <p className="text-xs text-[#9aa0a6]">For scripted installs where nobody clicks Add: collectors started with <code>-e HOMELAB_ENROLL_KEY=…</code> join immediately. Servers already connected are unaffected by rotating or revoking.</p>
- {error && <div className="mt-3 rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-sm text-amber-200">{error}</div>}
- {!keyInfo ? <p className="mt-3 text-sm text-[#9aa0a6]">Loading…</p> : enrollKey ? (
- <>
- <p className="mt-3 text-xs text-amber-100">Copy this key now. It is shown only once.</p>
- <CopyableCommand label="Enrollment key" text={enrollKey} />
- <CopyableCommand label="Add to the command above" text={`-e HOMELAB_ENROLL_KEY=${enrollKey}`} />
- </>
- ) : keyInfo.exists ? (
- <p className="mt-3 text-sm text-[#bcbcbc]">A key was created {new Date(keyInfo.created_at).toLocaleString()}. Rotate it to see a new one.</p>
- ) : null}
- {keyInfo && (
- <div className="mt-3 flex flex-wrap gap-2">
- <button type="button" onClick={generateKey} disabled={busy} className="rounded-lg border border-neutral-700 px-3 py-1.5 text-xs text-[#cfcfcf] disabled:opacity-50">{keyInfo.exists ? 'Rotate key' : 'Generate key'}</button>
- {keyInfo.exists && (confirmRevoke ? (
- <>
- <button type="button" onClick={revokeKey} disabled={busy} className="rounded-lg border border-red-400/30 bg-red-500/10 px-3 py-1.5 text-xs text-red-300 disabled:opacity-50">Yes, revoke</button>
- <button type="button" onClick={() => setConfirmRevoke(false)} className="rounded-lg border border-neutral-700 px-3 py-1.5 text-xs text-[#cfcfcf]">Cancel</button>
- </>
- ) : <button type="button" onClick={() => setConfirmRevoke(true)} disabled={busy} className="rounded-lg border border-red-400/30 bg-red-500/5 px-3 py-1.5 text-xs text-red-300 disabled:opacity-50">Revoke key</button>)}
- </div>
- )}
- </div>
- )
-}
-
-function buildJoinCommand({ url, token, collectorImage, proxyImage }) {
- return `docker compose -p homelab-collector -f - up -d <<'EOF'
-services:
- collector:
- image: ${collectorImage}
- container_name: homelab-collector
- restart: unless-stopped
- environment:
- HOMELAB_API_URL: ${url}
- HOMELAB_JOIN_TOKEN: ${token}
- HOMELAB_DOCKER_HOST: /run/docker-proxy/docker.sock
- volumes:
- - /proc:/host/proc:ro
- - /:/hostfs:ro
- - collector_state:/var/lib/homelab-collector
- - docker_proxy_socket:/run/docker-proxy:ro
- cap_drop: [ALL]
- read_only: true
- security_opt: [no-new-privileges:true]
- docker-proxy:
- image: ${proxyImage}
- container_name: homelab-docker-proxy
- restart: unless-stopped
- user: "0:0"
- network_mode: none
- cap_drop: [ALL]
- read_only: true
- security_opt: [no-new-privileges:true]
- volumes:
- - /var/run/docker.sock:/var/run/docker.sock
- - docker_proxy_socket:/run/docker-proxy
-volumes:
- collector_state:
- docker_proxy_socket:
-EOF`
-}
-
-function ConnectServerPanel() {
- const [info, setInfo] = useState(null)
- const [apiUrl, setApiUrl] = useState('')
- const [token, setToken] = useState(null)
- const [expiresAt, setExpiresAt] = useState(null)
- const [busy, setBusy] = useState(false)
- const [error, setError] = useState('')
-
- useEffect(() => {
- apiRequest('/monitoring/install-info', { method: 'GET' })
- .then((data) => {
- setInfo(data)
- // API_BASE is usually relative ('/api'); a collector needs an absolute address. The VPN address wins when one is configured.
- setApiUrl(data.collector_url || new URL(API_BASE, window.location.origin).href.replace(/\/$/, ''))
- })
- .catch((requestError) => setError(requestError.message || 'Could not load the install settings.'))
- }, [])
-
- const generate = async () => {
- setBusy(true); setError('')
- try {
- const data = await apiRequest('/monitoring/join-tokens', { method: 'POST' })
- setToken(data.join_token)
- setExpiresAt(Date.now() + data.expires_in_seconds * 1000)
- } catch (requestError) { setError(requestError.message || 'Could not create a join token.') }
- finally { setBusy(false) }
- }
-
- const url = apiUrl.trim().replace(/\/$/, '')
- const isLocalhost = /\/\/(localhost|127\.0\.0\.1)(:|\/|$)/.test(url)
- const ready = info?.collector_image && info?.proxy_image
- const minutes = expiresAt ? Math.max(1, Math.round((expiresAt - Date.now()) / 60000)) : null
- const command = token && ready ? buildJoinCommand({ url, token, collectorImage: info.collector_image, proxyImage: info.proxy_image }) : null
-
- return (
- <div className="mt-4 rounded-2xl border border-cyan-300/20 bg-cyan-300/5 p-4">
- <div className="font-medium text-cyan-100">Connect a server</div>
- <p className="mt-1 text-sm text-[#bcbcbc]">Generate a command, run it once on the machine you want to monitor, then click <span className="text-white">Add</span> when it appears below under <span className="text-white">New servers detected</span>. The command carries a single-use token that expires, so only you can add servers.</p>
-
- <label className="mt-4 block text-xs text-[#9aa0a6]">Address the new machine will use to reach the dashboard
- <input value={apiUrl} onChange={(e) => { setApiUrl(e.target.value); setToken(null) }} className="mt-1 w-full rounded-xl border border-neutral-700 bg-[#0d1013] px-3 py-2 text-sm text-white" aria-describedby="api-url-hint" />
- </label>
- {info?.collector_url
- ? <p id="api-url-hint" className="mt-1 text-[11px] text-[#7f8589]">Your configured collector (VPN) address.</p>
- : info?.strict
- ? <p id="api-url-hint" className="mt-1 text-[11px] text-amber-200">Collectors can't use the public address. Set <code>COLLECTOR_PUBLIC_URL</code> to the collector listener on your VPN (for example <code>http://10.8.0.1:8081/api</code>).</p>
- : isLocalhost
- ? <p id="api-url-hint" className="mt-1 text-[11px] text-amber-200">Other machines can't reach <code>localhost</code>. Use this machine's LAN IP, VPN address or domain (e.g. <code>http://192.168.1.10:5173/api</code>).</p>
- : <p id="api-url-hint" className="mt-1 text-[11px] text-[#7f8589]">Prefilled with the address you opened this dashboard at. Over plain HTTP, use it only on a trusted LAN or VPN.</p>}
-
- {info && !ready && <div className="mt-4 rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-sm text-amber-200">No collector images are configured, so there is nothing safe to install from. Set <code>COLLECTOR_IMAGE</code> and <code>DOCKER_PROXY_IMAGE</code> in <code>.env</code> to your published, digest-pinned images (see SECURITY.md). The dashboard never serves collector code itself.</div>}
-
- <div className="mt-4 flex flex-wrap items-center gap-3">
- <button type="button" onClick={generate} disabled={busy || !ready || !url} className="rounded-xl bg-white px-4 py-2 text-sm font-medium text-slate-950 disabled:cursor-not-allowed disabled:opacity-40">{busy ? 'Generating…' : token ? 'Generate a new command' : 'Generate command'}</button>
- {token && <span className="text-xs text-[#9aa0a6]">Single use · expires in about {minutes} min. A new command makes this one's token stop working once it is used.</span>}
- </div>
- {error && <div className="mt-3 rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-sm text-amber-200">{error}</div>}
-
- {command && <>
- <CopyableCommand label="Run on the new machine (needs Docker with the compose plugin)" text={command} />
- <p className="mt-2 text-[11px] text-[#7f8589]">Installs the collector with no Docker socket and no capabilities; a separate read-only proxy is the only container that touches the socket. The machine running this dashboard is detected automatically.</p>
- </>}
-
- <details className="mt-4 rounded-xl border border-neutral-800 p-3">
- <summary className="cursor-pointer text-xs text-[#9aa0a6]">Advanced: skip approval with an enrollment key</summary>
- <EnrollmentKeySettings />
- </details>
- </div>
- )
-}
-
-function PendingServers({ pending, onChanged }) {
- const [busyId, setBusyId] = useState(null)
- const [error, setError] = useState('')
- const waiting = pending.filter((item) => item.status === 'pending')
- const dismissed = pending.filter((item) => item.status === 'dismissed')
- if (!pending.length) return null
-
- const act = async (item, action) => {
- // Approving a machine that matches an existing server replaces that server's credentials and signs out its collector.
- if (action === 'approve' && item.replaces && !window.confirm(`This machine matches the existing server "${item.replaces.hostname}". Adding it replaces that server's credentials and signs its current collector out. Only continue if you are re-installing that machine.`)) return
- setBusyId(item.id); setError('')
- try {
- await apiRequest(`/monitoring/pending-collectors/${item.id}/${action}`, { method: 'POST', body: JSON.stringify({ replace: Boolean(item.replaces) }) })
- await onChanged()
- } catch (requestError) { setError(requestError.message || 'Could not update the server.') }
- finally { setBusyId(null) }
- }
-
- const row = (item) => (
- <div key={item.id} className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-neutral-800 bg-[#0d1013]/70 p-3">
- <div>
- <div className="flex flex-wrap items-center gap-2"><span className="font-medium text-white">{item.hostname}</span>{item.verified ? <span className="rounded-full bg-emerald-400/15 px-2 py-0.5 text-[10px] font-semibold tracking-wider text-emerald-300">JOIN TOKEN</span> : <span className="rounded-full bg-amber-400/15 px-2 py-0.5 text-[10px] font-semibold tracking-wider text-amber-300">NO TOKEN</span>}</div>
- {item.replaces && <div className="mt-1 text-xs text-amber-200">Replaces the existing server “{item.replaces.hostname}”: its current collector will be signed out.</div>}
- <div className="mt-0.5 text-xs text-[#9aa0a6]">{[item.ip_address, item.os_info].filter(Boolean).join(' · ')} · code <span className="font-mono text-[#cfcfcf]">{item.pairing_code}</span></div>
- </div>
- <div className="flex w-full gap-2 sm:w-auto">
- <button type="button" onClick={() => act(item, 'approve')} disabled={busyId === item.id} className="min-h-10 flex-1 rounded-lg bg-white px-3 py-1.5 text-xs sm:min-h-0 sm:flex-none font-medium text-slate-950 disabled:opacity-50">{busyId === item.id ? 'Adding…' : 'Add'}</button>
- {item.status === 'pending' && <button type="button" onClick={() => act(item, 'dismiss')} disabled={busyId === item.id} className="min-h-10 flex-1 rounded-lg border border-neutral-700 px-3 py-1.5 text-xs sm:min-h-0 sm:flex-none text-[#cfcfcf] disabled:opacity-50">Dismiss</button>}
- </div>
- </div>
- )
-
- return (
- <div className="mb-4">
- {waiting.length > 0 && (
- <div className="rounded-2xl border border-cyan-300/20 bg-cyan-300/5 p-4">
- <div className="text-sm font-medium text-cyan-100">New servers detected</div>
- <p className="mt-1 text-xs text-[#9aa0a6]">These machines are running the collector and asking to join. The pairing code is also printed in the collector's log if you want to double-check.</p>
- <div className="mt-3 space-y-2">{waiting.map(row)}</div>
- </div>
- )}
- {dismissed.length > 0 && (
- <details className="mt-3 text-sm">
- <summary className="cursor-pointer text-xs text-[#7f8589]">Dismissed ({dismissed.length})</summary>
- <div className="mt-2 space-y-2">{dismissed.map(row)}</div>
- </details>
- )}
- {error && <div className="mt-3 rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-sm text-amber-200">{error}</div>}
- </div>
- )
-}
-
-function formatMegabytes(value) {
- if (value == null) return '—'
- return value >= 1024 ? `${(value / 1024).toFixed(2)} GB` : `${Number(value).toFixed(1)} MB`
-}
-
-function formatUptime(startedAt) {
- const started = startedAt ? new Date(startedAt).getTime() : NaN
- if (Number.isNaN(started) || started <= 0) return '—'
- const seconds = Math.max(0, Math.floor((Date.now() - started) / 1000))
- const days = Math.floor(seconds / 86400)
- const hours = Math.floor((seconds % 86400) / 3600)
- const minutes = Math.floor((seconds % 3600) / 60)
- return days ? `${days}d ${hours}h` : hours ? `${hours}h ${minutes}m` : `${minutes}m`
-}
-
-function ContainerStatus({ container }) {
- const stopped = container.status === 'exited' || container.status === 'dead'
- return <span className="whitespace-nowrap"><span className={container.status === 'running' ? 'text-emerald-300' : container.status === 'restarting' ? 'text-red-300' : 'text-amber-300'}>{container.status}</span>{stopped && container.exit_code != null && <span className={container.oom_killed ? 'text-red-300' : container.exit_code === 0 ? 'text-[#7f8589]' : 'text-amber-300'}> · {container.oom_killed ? 'out of memory' : `code ${container.exit_code}`}</span>}{container.healthcheck_status && <span className={HEALTH_CLASSES[container.healthcheck_status] || 'text-[#7f8589]'}> · {container.healthcheck_status}</span>}</span>
-}
-
-const formatContainerCpu = (c) => (c.cpu_pct == null ? '—' : `${c.cpu_pct}%`)
-const formatContainerMemory = (c) => (c.memory_used_mb == null ? '—' : c.memory_used_mb >= 1024 ? `${(c.memory_used_mb / 1024).toFixed(1)} GB` : `${Math.round(c.memory_used_mb)} MB`)
-
-function ContainerTable({ serverId, containers }) {
- const [expandedId, setExpandedId] = useState(null)
- const toggle = (containerId) => setExpandedId((current) => (current === containerId ? null : containerId))
-
- return <>
- {/* Phones: one tappable two-line row per container. */}
- <ul className="divide-y divide-neutral-800 md:hidden">
- {containers.map((c) => {
- const expanded = expandedId === c.container_id
- return (
- <li key={c.container_id}>
- <button type="button" onClick={() => toggle(c.container_id)} aria-expanded={expanded} className="flex w-full flex-col gap-1 py-3 text-left">
- <span className="flex w-full items-center justify-between gap-3">
- <span className="flex min-w-0 items-center gap-2"><Chevron open={expanded} /><span className="truncate text-sm text-white">{c.name}</span></span>
- <span className="text-xs"><ContainerStatus container={c} /></span>
- </span>
- <span className="flex gap-4 pl-[18px] text-xs text-[#7f8589]">
- <span>CPU <span className="text-[#cfcfcf]">{formatContainerCpu(c)}</span></span>
- <span>Mem <span className="text-[#cfcfcf]">{formatContainerMemory(c)}</span></span>
- <span>Restarts <span className={c.restart_count ? 'text-amber-300' : 'text-[#cfcfcf]'}>{c.restart_count}</span></span>
- </span>
- </button>
- {expanded && <div className="pb-4"><ContainerDetails serverId={serverId} container={c} /></div>}
- </li>
- )
- })}
- </ul>
-
- <div className="hidden overflow-x-auto md:block">
- <table className="w-full text-left text-sm">
- <thead className="text-xs uppercase text-[#7f8589]"><tr><th className="py-2">Container</th><th>Status</th><th>CPU</th><th>Memory</th><th>Restarts</th></tr></thead>
- <tbody>
- {containers.map((c) => {
- const expanded = expandedId === c.container_id
- return [
- <tr
- key={c.container_id}
- onClick={() => toggle(c.container_id)}
- onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggle(c.container_id) } }}
- tabIndex={0}
- aria-expanded={expanded}
- className={`cursor-pointer border-t border-neutral-800 text-[#cfcfcf] transition hover:bg-white/3 focus:outline-none focus-visible:bg-white/5 ${expanded ? 'bg-white/3' : ''}`}
- >
- <td className="py-2"><Chevron open={expanded} className="mr-2" />{c.name}</td>
- <td><ContainerStatus container={c} /></td>
- <td>{formatContainerCpu(c)}</td>
- <td>{formatContainerMemory(c)}</td>
- <td>{c.restart_count}</td>
- </tr>,
- expanded && (
- <tr key={`${c.container_id}-details`}>
- <td colSpan={5} className="pb-4"><ContainerDetails serverId={serverId} container={c} /></td>
- </tr>
- ),
- ]
- })}
- </tbody>
- </table>
- </div>
- </>
-}
-
-function ContainerDetails({ serverId, container }) {
- const [detail, setDetail] = useState(null)
- const [error, setError] = useState('')
- // Re-fetch whenever the overview poll brings in a newer sample for this container.
- const sampleTime = container.time
-
- useEffect(() => {
- let active = true
- apiRequest(`/monitoring/servers/${serverId}/containers/${encodeURIComponent(container.container_id)}?limit=60`, { method: 'GET' })
- .then((data) => { if (active) { setDetail(data); setError('') } })
- .catch((requestError) => { if (active) setError(requestError.message || 'Could not load container details.') })
- return () => { active = false }
- }, [serverId, container.container_id, sampleTime])
-
- if (error) return <div className="rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-sm text-amber-200">{error}</div>
- if (!detail) return <div className="rounded-xl bg-[#171b1f] p-4 text-sm text-[#9aa0a6]">Loading container details…</div>
-
- const latest = detail.latest
- const history = detail.history
- const times = history.map((sample) => sample.time)
- const stats = [
- ['CPU', latest.cpu_pct == null ? '—' : `${latest.cpu_pct}%`],
- ['Memory', latest.memory_limit_mb ? `${formatMegabytes(latest.memory_used_mb)} / ${formatMegabytes(latest.memory_limit_mb)}` : formatMegabytes(latest.memory_used_mb)],
- ['Memory %', latest.memory_pct == null ? '—' : `${latest.memory_pct}%`],
- ['Processes', latest.pids ?? '—'],
- ['Network in', formatMegabytes(latest.net_rx_mb)],
- ['Network out', formatMegabytes(latest.net_tx_mb)],
- ['Disk read', formatMegabytes(latest.block_read_mb)],
- ['Disk write', formatMegabytes(latest.block_write_mb)],
- ]
-
- return (
- <div className="rounded-2xl border border-neutral-800 bg-[#090b0d]/80 p-4">
- <div className="grid gap-x-6 gap-y-1 text-xs text-[#9aa0a6] sm:grid-cols-2">
- <div><span className="text-[#7f8589]">Image:</span> <span className="break-all text-[#cfcfcf]">{detail.image || '—'}</span></div>
- <div><span className="text-[#7f8589]">ID:</span> <span className="font-mono text-[#cfcfcf]">{detail.container_id.slice(0, 12)}</span></div>
- <div><span className="text-[#7f8589]">Uptime:</span> <span className="text-[#cfcfcf]">{formatUptime(detail.started_at)}</span></div>
- <div><span className="text-[#7f8589]">Health:</span> <span className="text-[#cfcfcf]">{latest.healthcheck_status || 'no healthcheck'}</span></div>
- <div className="sm:col-span-2"><span className="text-[#7f8589]">Ports:</span> <span className="break-all text-[#cfcfcf]">{detail.ports || 'none published'}</span></div>
- </div>
- <div className="mt-4 grid grid-cols-2 gap-3 lg:grid-cols-4">
- {stats.map(([label, value]) => <div key={label} className="rounded-xl bg-[#171b1f] p-3"><div className="text-xs text-[#9aa0a6]">{label}</div><div className="mt-1 text-base font-semibold text-white">{value}</div></div>)}
- </div>
- <div className="mt-4 grid gap-4 lg:grid-cols-2">
- <MetricTrend title="Container CPU" color="#34d399" value={latest.cpu_pct == null ? '—' : latest.cpu_pct} points={history.map((s) => s.cpu_pct)} times={times} />
- <MetricTrend title="Container memory" color="#60a5fa" value={latest.memory_pct == null ? '—' : latest.memory_pct} points={history.map((s) => s.memory_pct)} times={times} />
- </div>
- <p className="mt-3 text-[10px] text-[#7f8589]">Network and disk figures are totals since the container started. CPU can exceed 100% when a container uses more than one core.</p>
- </div>
- )
-}
-
-// Plot area spans y=3..97 of the 0..100 viewBox so the line isn't clipped at 0% or 100%.
-const TREND_Y_TICKS = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0]
-const trendY = (percent) => 3 + (100 - Math.max(0, Math.min(100, Number(percent) || 0))) * 0.94
-
-function MetricTrend({ title, color, value, points, times }) {
- // Used in url(#…), so keep only characters that are safe there (titles like "Disk usage (/)" aren't).
- const fillId = `fill-${title.replace(/[^a-zA-Z0-9]+/g, '-')}`
- const chartPoints = points.map((point, index) => `${points.length > 1 ? (index / (points.length - 1)) * 320 : 320},${trendY(point)}`).join(' ')
- const areaPoints = points.length ? `0,${trendY(0)} ${chartPoints} 320,${trendY(0)}` : ''
- return (
- <article className="glass-panel rounded-[24px] p-5">
- <div className="flex items-start justify-between gap-3"><div><div className="text-sm text-[#9aa0a6]">{title}</div><div className="mt-2 text-2xl font-semibold text-white">{value === '—' ? '—' : `${value}%`}</div></div><span className="rounded-full px-2.5 py-1 text-[10px] uppercase tracking-wider" style={{ color, backgroundColor: `${color}18` }}>Live</span></div>
- <div className="mt-4 flex h-28 w-full gap-2">
- <div className="relative w-8 shrink-0 text-right text-[10px] tabular-nums text-[#7f8589]" aria-hidden="true">
- {TREND_Y_TICKS.filter((tick) => tick % 20 === 0).map((tick) => <span key={tick} className="absolute right-0 -translate-y-1/2 leading-none" style={{ top: `${trendY(tick)}%` }}>{tick}%</span>)}
- </div>
- <div className="min-w-0 flex-1">
- {points.length > 1 ? <svg viewBox="0 0 320 100" preserveAspectRatio="none" className="h-full w-full" role="img" aria-label={`${title} recent trend`}><defs><linearGradient id={fillId} x1="0" x2="0" y1="0" y2="1"><stop offset="0%" stopColor={color} stopOpacity="0.28"/><stop offset="100%" stopColor={color} stopOpacity="0"/></linearGradient></defs>{TREND_Y_TICKS.map((tick) => <line key={tick} x1="0" x2="320" y1={trendY(tick)} y2={trendY(tick)} stroke="#ffffff" strokeOpacity={tick % 20 === 0 ? 0.12 : 0.05} strokeWidth="1" vectorEffect="non-scaling-stroke" />)}<polygon points={areaPoints} fill={`url(#${fillId})`}/><polyline points={chartPoints} fill="none" stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke"/></svg> : <div className="flex h-full items-center justify-center rounded-xl border border-dashed border-neutral-800 text-xs text-[#7f8589]">Trend appears as live samples arrive</div>}
- </div>
- </div>
- <div className="mt-2 flex justify-between pl-10 text-[10px] text-[#7f8589]"><span>{times[0] ? new Date(times[0]).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : 'Waiting for data'}</span><span>{times.at(-1) ? new Date(times.at(-1)).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '—'}</span></div>
- </article>
- )
-}
-
-// Placeholder data until the agent diagnoses incidents on the backend.
-const placeholderIncidents = [
- {
- id: 'inc-1',
- severity: 'CRITICAL',
- server: 'homelab-01',
- detectedAt: '2026-09-25T01:42:00',
- status: 'diagnosed',
- summary: 'GitLab container keeps restarting',
- details: 'The gitlab container restarted 6 times in the last 30 minutes. Each restart follows an out-of-memory kill while Puma workers are starting, so the service never becomes healthy.',
- actions: [
- 'Raise the container memory limit to at least 6 GB, or lower puma[\'worker_processes\'] in gitlab.rb.',
- 'Run docker logs gitlab --since 30m and confirm the OOM kill in dmesg.',
- 'After restarting, confirm the healthcheck turns healthy and the restart count stops increasing.',
- ],
- },
- {
- id: 'inc-2',
- severity: 'WARNING',
- server: 'homelab-01',
- detectedAt: '2026-09-25T00:15:00',
- status: 'diagnosed',
- summary: 'Root disk is 94% full',
- details: 'Disk usage on / grew from 81% to 94% over the last 3 days. Most of the growth is in /var/lib/docker, from unused images and build cache.',
- actions: [
- 'Run docker system df to see how much space images, containers and build cache use.',
- 'Remove unused images and build cache with docker image prune -a and docker builder prune.',
- 'Set up log rotation for container logs so they cannot fill the disk again.',
- ],
- },
- {
- id: 'inc-3',
- severity: 'WARNING',
- server: 'media-server',
- detectedAt: '2026-09-24T22:03:00',
- status: 'analyzing',
- summary: 'High CPU usage on jellyfin',
- details: 'The jellyfin container has used over 350% CPU for 20 minutes, which matches software video transcoding.',
- actions: [],
- },
-]
-
-const placeholderChat = [
- { id: 'm1', role: 'agent', text: 'Hi! I review new incidents automatically and suggest how to fix them. Ask me about any report on the left, or about your servers.' },
- { id: 'm2', role: 'user', text: 'Why does GitLab keep restarting?' },
- { id: 'm3', role: 'agent', text: 'It runs out of memory while its Puma workers start, so the kernel kills it and Docker restarts it. Raising the memory limit or running fewer workers should fix it. The full steps are in the report.' },
-]
-
-function IncidentCard({ incident, expanded, onToggle }) {
- const critical = incident.severity === 'CRITICAL'
-
- return (
- <article className={`message-card rounded-[20px] transition ${expanded ? 'border-white/15' : 'hover:border-white/15'}`}>
- <button type="button" onClick={onToggle} aria-expanded={expanded} className="flex w-full items-start gap-3 p-4 text-left">
- <span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${critical ? 'bg-red-400' : 'bg-amber-400'}`} />
- <div className="min-w-0 flex-1">
- <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-[#9aa0a6]">
- <time dateTime={incident.detectedAt}>{new Date(incident.detectedAt).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' })}</time>
- <span>·</span>
- <span>{incident.server}</span>
- <span className={`rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider ${critical ? 'bg-red-400/10 text-red-300' : 'bg-amber-400/10 text-amber-200'}`}>
- {incident.severity}
- </span>
- </div>
- <h3 className="mt-1.5 font-medium text-white">{incident.summary}</h3>
- </div>
- <span className={`mt-1 text-[#9aa0a6] transition-transform ${expanded ? 'rotate-180' : ''}`} aria-hidden="true">⌄</span>
- </button>
-
- {expanded && (
- <div className="px-4 pb-4 pl-9">
- <p className="text-sm leading-6 break-words text-[#bcbcbc]">{incident.details}</p>
- <div className="mt-4 rounded-2xl border border-cyan-300/15 bg-cyan-300/5 p-4">
- <div className="text-xs uppercase tracking-[0.18em] text-cyan-200">Recommended actions</div>
- {incident.status === 'analyzing' ? (
- <p className="mt-3 flex items-center gap-2 text-sm text-[#9aa0a6]">
- <span className="h-2 w-2 animate-pulse rounded-full bg-cyan-300" />
- The agent is still diagnosing this incident.
- </p>
- ) : (
- <ol className="mt-3 space-y-2 text-sm leading-6 text-[#d1d5db]">
- {incident.actions.map((action, index) => (
- <li key={action} className="flex gap-3">
- <span className="font-mono text-cyan-300">0{index + 1}</span>
- <span className="min-w-0 break-words">{action}</span>
- </li>
- ))}
- </ol>
- )}
- </div>
- </div>
- )}
- </article>
- )
-}
-
-function AgentPage({ user, onLogout }) {
- const [expandedId, setExpandedId] = useState(placeholderIncidents[0]?.id)
- const [chatEnabled, setChatEnabled] = useState(true)
-
- useEffect(() => {
- apiRequest('/agent/config', { method: 'GET' })
- .then((data) => setChatEnabled(data.chat_enabled))
- .catch(() => {})
- }, [])
-
- return (
- <AppShell user={user} onLogout={onLogout} fitViewport>
- <div className="flex flex-col gap-5 xl:h-full">
- <header className="glass-panel rounded-[28px] p-5 md:p-6">
- <div className="text-xs uppercase tracking-[0.22em] text-[#9aa0a6]">Diagnostics</div>
- <h1 className="mt-1 text-3xl font-semibold text-white">Agent</h1>
- <p className="mt-2 max-w-3xl text-sm leading-6 text-[#9aa0a6]">
- The agent reviews each incident, diagnoses the cause and recommends how to fix it. Showing placeholder data for now.
- </p>
- </header>
-
- <div className="grid grid-cols-1 gap-5 xl:min-h-0 xl:flex-1 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)] xl:grid-rows-[minmax(0,1fr)]">
- <section className="glass-panel flex flex-col rounded-[28px] p-5 md:p-6 xl:min-h-0">
- <div className="mb-4 flex items-end justify-between gap-3">
- <div>
- <div className="text-xs uppercase tracking-[0.2em] text-[#9aa0a6]">Incident reports</div>
- <h2 className="mt-1 text-xl font-semibold text-white">Recent problems</h2>
- </div>
- <span className="text-xs text-[#9aa0a6]">{placeholderIncidents.length} reports</span>
- </div>
- <div className="custom-scroll -mr-2 space-y-3 pr-2 xl:min-h-0 xl:flex-1 xl:overflow-y-auto">
- {placeholderIncidents.map((incident) => (
- <IncidentCard
- key={incident.id}
- incident={incident}
- expanded={expandedId === incident.id}
- onToggle={() => setExpandedId((current) => (current === incident.id ? null : incident.id))}
- />
- ))}
- </div>
- </section>
-
- <section className="glass-panel flex h-150 flex-col rounded-[28px] p-5 md:p-6 xl:h-auto xl:min-h-0">
- <div className="mb-4 flex items-end justify-between gap-3">
- <div>
- <div className="text-xs uppercase tracking-[0.2em] text-[#9aa0a6]">Chat</div>
- <h2 className="mt-1 text-xl font-semibold text-white">Ask the agent</h2>
- </div>
- {chatEnabled
- ? <span className="rounded-full border border-white/10 bg-white/5 px-2.5 py-1 text-[10px] uppercase tracking-[0.2em] text-[#9aa0a6]">Preview</span>
- : <span className="rounded-full border border-amber-400/30 bg-amber-400/10 px-2.5 py-1 text-[10px] uppercase tracking-[0.2em] text-amber-200">Off</span>}
- </div>
- {!chatEnabled && (
- <div className="mb-4 rounded-2xl border border-amber-400/20 bg-amber-400/5 px-4 py-3 text-sm text-amber-200">
- Chat with the agent has been turned off by an admin. Incident reports still work.
- </div>
- )}
- <div className="custom-scroll -mr-2 min-h-0 flex-1 space-y-3 overflow-y-auto pr-2">
- {placeholderChat.map((message) => (
- <div key={message.id} className={`flex ${message.role === 'user' ? 'justify-end' : 'justify-start'}`}>
- <div className={`max-w-[85%] rounded-2xl px-4 py-3 text-sm leading-6 ${message.role === 'user' ? 'bg-white/10 text-white' : 'message-card text-[#d1d5db]'}`}>
- {message.text}
- </div>
- </div>
- ))}
- </div>
- <form className="mt-4 flex gap-2" onSubmit={(event) => event.preventDefault()}>
- <input
- disabled
- placeholder={chatEnabled ? 'Chat is not connected yet' : 'Chat is turned off'}
- className="min-w-0 flex-1 rounded-2xl border border-[#1f2326] bg-[#0d1013]/80 px-4 py-3 text-sm text-[#cfcfcf] outline-none placeholder:text-[#6b7075] disabled:cursor-not-allowed"
- />
- <button type="submit" disabled className="rounded-2xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-3 text-sm font-medium text-[#0b0b0b] disabled:cursor-not-allowed disabled:opacity-40">
- Send
- </button>
- </form>
- </section>
- </div>
- </div>
- </AppShell>
- )
-}
-
-// Placeholder data for the admin page until its backend endpoints exist.
-const placeholderAdmin = {
- users: [
- { id: 1, name: 'Admin', email: '[email protected]', role: 'admin', lastLogin: '2026-09-25T01:58:00', active: true, sessions: 2 },
- { id: 2, name: 'Ana', email: '[email protected]', role: 'user', lastLogin: '2026-09-23T18:12:00', active: true, sessions: 1 },
- { id: 3, name: 'Old account', email: '[email protected]', role: 'user', lastLogin: '2026-06-02T09:40:00', active: false, sessions: 0 },
- ],
- servers: [
- { id: 1, name: 'homelab-01', online: true, lastSeen: '2026-09-25T02:10:00', interval: 60, collectorVersion: '0.4.0' },
- { id: 2, name: 'media-server', online: true, lastSeen: '2026-09-25T02:09:30', interval: 60, collectorVersion: '0.4.0' },
- { id: 3, name: 'backup-nas', online: false, lastSeen: '2026-09-24T14:22:00', interval: 300, collectorVersion: '0.3.2' },
- ],
- pending: [{ id: 7, hostname: 'raspberrypi', ip: '192.168.1.44', requestedAt: '2026-09-25T01:30:00' }],
- services: [
- { name: 'Backend API', status: 'ok', detail: 'Responding' },
- { name: 'PostgreSQL', status: 'ok', detail: '412 MB' },
- { name: 'Redis', status: 'ok', detail: '3 active sessions' },
- ],
- audit: [
- { id: 1, time: '2026-09-25T01:58:00', actor: 'Admin', event: 'Signed in' },
- { id: 2, time: '2026-09-25T01:31:00', actor: 'system', event: 'New server requested to join: raspberrypi' },
- { id: 3, time: '2026-09-24T20:05:00', actor: 'Admin', event: 'Changed check interval of backup-nas to 300 s' },
- { id: 4, time: '2026-09-24T19:47:00', actor: 'Admin', event: 'Approved server media-server' },
- ],
-}
-
-const adminTabs = [
- { id: 'users', label: 'Users' },
- { id: 'servers', label: 'Servers' },
- { id: 'agent', label: 'Agent' },
- { id: 'alerts', label: 'Alerts' },
- { id: 'system', label: 'System' },
-]
-
-const formatDateTime = (value) => new Date(value).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' })
-
-const inputClass = 'w-full rounded-2xl border border-[#1f2326] bg-[#0d1013]/80 px-4 py-2.5 text-sm text-[#cfcfcf] outline-none transition focus:border-white/30'
-const secondaryButtonClass = 'min-h-10 sm:min-h-0 rounded-xl border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-[#cfcfcf] transition hover:bg-white/10'
-const dangerButtonClass = 'min-h-10 sm:min-h-0 rounded-xl border border-red-400/30 bg-red-500/10 px-3 py-1.5 text-xs text-red-300 transition hover:bg-red-500/15'
-
-function AdminSection({ title, description, action, children }) {
- return (
- <section className="glass-panel rounded-[28px] p-5 md:p-6">
- <div className="mb-4 flex flex-wrap items-start justify-between gap-3">
- <div>
- <h2 className="text-lg font-semibold text-white">{title}</h2>
- {description && <p className="mt-1 max-w-2xl text-sm text-[#9aa0a6]">{description}</p>}
- </div>
- {action}
- </div>
- {children}
- </section>
- )
-}
-
-function Toggle({ label, description, defaultOn = false, checked, onChange, disabled = false }) {
- const [localOn, setLocalOn] = useState(defaultOn)
- const controlled = checked !== undefined
- const on = controlled ? checked : localOn
- const setOn = controlled ? (update) => onChange(update(on)) : setLocalOn
-
- return (
- <div className="flex items-center justify-between gap-4 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3">
- <div>
- <div className="text-sm text-white">{label}</div>
- {description && <div className="mt-0.5 text-xs text-[#9aa0a6]">{description}</div>}
- </div>
- <button
- type="button"
- role="switch"
- aria-checked={on}
- aria-label={label}
- disabled={disabled}
- onClick={() => setOn((value) => !value)}
- className={`relative h-6 w-11 shrink-0 rounded-full transition before:absolute before:-inset-2.5 before:content-[''] disabled:cursor-not-allowed disabled:opacity-50 ${on ? 'bg-emerald-500/70' : 'bg-white/10'}`}
- >
- <span className={`absolute top-1 h-4 w-4 rounded-full bg-white transition-all ${on ? 'left-6' : 'left-1'}`} />
- </button>
- </div>
- )
-}
-
-function StatusDot({ ok }) {
- return <span className={`inline-block h-2 w-2 rounded-full ${ok ? 'bg-emerald-400' : 'bg-red-400'}`} />
-}
-
-function SaveButton() {
- return (
- <button type="button" disabled title="Not connected yet" className="rounded-2xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-2.5 text-sm font-medium text-[#0b0b0b] disabled:cursor-not-allowed disabled:opacity-40">
- Save changes
- </button>
- )
-}
-
-function TwoFactorPolicySetting() {
- const [state, setState] = useState(null)
- const [saving, setSaving] = useState(false)
- const [message, setMessage] = useState(null)
-
- useEffect(() => {
- apiRequest('/admin/settings', { method: 'GET' })
- .then((data) => setState({ required: data.require_2fa_for_admins, configured: data.secrets_configured }))
- .catch((error) => setMessage({ ok: false, text: error.message || 'Could not load the setting.' }))
- }, [])
-
- const change = async (next) => {
- setSaving(true)
- setMessage(null)
- try {
- const data = await apiRequest('/admin/settings', { method: 'PUT', body: JSON.stringify({ require_2fa_for_admins: next }) })
- setState({ required: data.require_2fa_for_admins, configured: data.secrets_configured })
- setMessage({ ok: true, text: data.require_2fa_for_admins ? 'Administrators must now use two-factor. Those without it are asked to set it up at their next sign-in.' : 'Two-factor is optional for administrators.' })
- } catch (error) {
- setMessage({ ok: false, text: error.message || 'Could not save the setting.' })
- } finally {
- setSaving(false)
- }
- }
-
- return (
- <AdminSection title="Two-factor" description="Protects sign-in with a code from an authenticator app, on top of the password.">
- <Toggle label="Require two-factor for administrators" description="An administrator without it can only reach the two-factor setup until it is done." checked={state?.required ?? false} onChange={change} disabled={state === null || saving} />
- {state && !state.configured && <p className="mt-3 rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-xs text-amber-200">SECRETS_KEY is not set on the server, so two-factor can't be set up and this is <strong>not being enforced</strong> yet. Set it in <code>.env</code> (see docs/accounts.md, Two-factor sign-in) and restart.</p>}
- {message && <p className={`mt-3 text-xs ${message.ok ? 'text-emerald-300' : 'text-amber-200'}`}>{message.text}</p>}
- </AdminSection>
- )
-}
-
-function AdminUsersTab() {
- return (
- <div className="space-y-5">
- <TwoFactorPolicySetting />
-
- <AdminSection title="Users" description="Change roles, disable accounts or sign someone out everywhere.">
- <ul className="space-y-2 md:hidden">
- {placeholderAdmin.users.map((account) => (
- <li key={account.id} className={`rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 p-4 ${account.active ? '' : 'opacity-60'}`}>
- <div className="flex items-start justify-between gap-3">
- <div className="min-w-0"><div className="truncate text-white">{account.name}</div><div className="truncate text-xs text-[#9aa0a6]">{account.email}</div></div>
- <span className="inline-flex shrink-0 items-center gap-2 text-xs text-[#bcbcbc]"><StatusDot ok={account.active} />{account.active ? 'Active' : 'Disabled'}</span>
- </div>
- <div className="mt-1 text-xs text-[#7f8589]">Last login {formatDateTime(account.lastLogin)}</div>
- <div className="mt-3 grid grid-cols-3 gap-2">
- <select defaultValue={account.role} aria-label={`Role of ${account.name}`} className="h-10 min-w-0 rounded-xl border border-[#1f2326] bg-[#0d1013] px-3 text-sm text-[#cfcfcf]">
- <option value="admin">Admin</option>
- <option value="user">User</option>
- </select>
- <button type="button" className={`${secondaryButtonClass} h-10`} disabled={!account.sessions}>Sign out ({account.sessions})</button>
- <button type="button" className={`${account.active ? dangerButtonClass : secondaryButtonClass} h-10`}>{account.active ? 'Disable' : 'Enable'}</button>
- </div>
- </li>
- ))}
- </ul>
- <div className="hidden overflow-x-auto md:block">
- <table className="w-full min-w-160 text-left text-sm">
- <thead className="text-xs uppercase tracking-wider text-[#7f8589]">
- <tr><th className="pb-3 font-medium">User</th><th className="pb-3 font-medium">Role</th><th className="pb-3 font-medium">Last login</th><th className="pb-3 font-medium">Status</th><th className="pb-3 text-right font-medium">Actions</th></tr>
- </thead>
- <tbody className="divide-y divide-white/5">
- {placeholderAdmin.users.map((account) => (
- <tr key={account.id} className={account.active ? '' : 'opacity-60'}>
- <td className="py-3"><div className="text-white">{account.name}</div><div className="text-xs text-[#9aa0a6]">{account.email}</div></td>
- <td className="py-3">
- <select defaultValue={account.role} aria-label={`Role of ${account.name}`} className="rounded-xl border border-[#1f2326] bg-[#0d1013] px-2 py-1 text-xs text-[#cfcfcf]">
- <option value="admin">Admin</option>
- <option value="user">User</option>
- </select>
- </td>
- <td className="py-3 text-[#bcbcbc]">{formatDateTime(account.lastLogin)}</td>
- <td className="py-3"><span className="inline-flex items-center gap-2 text-[#bcbcbc]"><StatusDot ok={account.active} />{account.active ? 'Active' : 'Disabled'}</span></td>
- <td className="py-3">
- <div className="flex justify-end gap-2">
- <button type="button" className={secondaryButtonClass} disabled={!account.sessions}>Sign out ({account.sessions})</button>
- <button type="button" className={account.active ? dangerButtonClass : secondaryButtonClass}>{account.active ? 'Disable' : 'Enable'}</button>
- </div>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- </AdminSection>
- </div>
- )
-}
-
-function AdminServersTab() {
- return (
- <div className="space-y-5">
- <div className="grid gap-5 xl:grid-cols-2">
- <AdminSection title="Enrollment key" description="Servers that connect with this key are approved automatically.">
- <div className="flex flex-col gap-2 sm:flex-row">
- <input readOnly value="hlk_••••••••••••••••3f9a" aria-label="Enrollment key" className={`${inputClass} font-mono`} />
- <div className="flex gap-2">
- <button type="button" className={`${secondaryButtonClass} h-10 flex-1 sm:h-auto sm:flex-none`}>Regenerate</button>
- <button type="button" className={`${dangerButtonClass} h-10 flex-1 sm:h-auto sm:flex-none`}>Revoke</button>
- </div>
- </div>
- </AdminSection>
-
- <AdminSection title="Waiting for approval" description="Collectors that asked to join without a key.">
- <div className="space-y-2">
- {placeholderAdmin.pending.map((request) => (
- <div key={request.id} className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-amber-400/20 bg-amber-400/5 px-4 py-3">
- <div><div className="text-sm text-white">{request.hostname}</div><div className="text-xs text-[#9aa0a6]">{request.ip} · {formatDateTime(request.requestedAt)}</div></div>
- <div className="flex w-full gap-2 sm:w-auto"><button type="button" className={`${secondaryButtonClass} h-10 flex-1 sm:h-auto`}>Approve</button><button type="button" className={`${dangerButtonClass} h-10 flex-1 sm:h-auto`}>Dismiss</button></div>
- </div>
- ))}
- </div>
- </AdminSection>
- </div>
-
- <AdminSection title="Servers" description="Every monitored machine, its collector and how often it reports.">
- <ul className="space-y-2 md:hidden">
- {placeholderAdmin.servers.map((server) => (
- <li key={server.id} className="rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 p-4">
- <div className="flex items-center justify-between gap-3">
- <span className="inline-flex min-w-0 items-center gap-2 text-white"><StatusDot ok={server.online} /><span className="truncate">{server.name}</span></span>
- <span className="shrink-0 font-mono text-xs text-[#9aa0a6]">v{server.collectorVersion}</span>
- </div>
- <div className="mt-1 text-xs text-[#7f8589]">Last seen {formatDateTime(server.lastSeen)}</div>
- <div className="mt-3 flex items-center gap-2">
- <select defaultValue={server.interval} aria-label={`Check interval of ${server.name}`} className="h-10 flex-1 rounded-xl border border-[#1f2326] bg-[#0d1013] px-3 text-sm text-[#cfcfcf]">
- {[15, 30, 60, 120, 300].map((seconds) => <option key={seconds} value={seconds}>Every {seconds} s</option>)}
- </select>
- <button type="button" className={`${dangerButtonClass} h-10`}>Remove</button>
- </div>
- </li>
- ))}
- </ul>
- <div className="hidden overflow-x-auto md:block">
- <table className="w-full min-w-160 text-left text-sm">
- <thead className="text-xs uppercase tracking-wider text-[#7f8589]">
- <tr><th className="pb-3 font-medium">Server</th><th className="pb-3 font-medium">Last seen</th><th className="pb-3 font-medium">Collector</th><th className="pb-3 font-medium">Interval</th><th className="pb-3 text-right font-medium">Actions</th></tr>
- </thead>
- <tbody className="divide-y divide-white/5">
- {placeholderAdmin.servers.map((server) => (
- <tr key={server.id}>
- <td className="py-3"><span className="inline-flex items-center gap-2 text-white"><StatusDot ok={server.online} />{server.name}</span></td>
- <td className="py-3 text-[#bcbcbc]">{formatDateTime(server.lastSeen)}</td>
- <td className="py-3 font-mono text-xs text-[#bcbcbc]">v{server.collectorVersion}</td>
- <td className="py-3">
- <select defaultValue={server.interval} aria-label={`Check interval of ${server.name}`} className="rounded-xl border border-[#1f2326] bg-[#0d1013] px-2 py-1 text-xs text-[#cfcfcf]">
- {[15, 30, 60, 120, 300].map((seconds) => <option key={seconds} value={seconds}>{seconds} s</option>)}
- </select>
- </td>
- <td className="py-3"><div className="flex justify-end"><button type="button" className={dangerButtonClass}>Remove</button></div></td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- </AdminSection>
- </div>
- )
-}
-
-function AgentChatSetting() {
- const [enabled, setEnabled] = useState(null)
- const [saving, setSaving] = useState(false)
- const [message, setMessage] = useState(null)
-
- useEffect(() => {
- apiRequest('/admin/settings', { method: 'GET' })
- .then((data) => setEnabled(data.agent_chat_enabled))
- .catch((error) => setMessage({ ok: false, text: error.message || 'Could not load the setting.' }))
- }, [])
-
- // Saves straight away, like a light switch.
- const change = async (next) => {
- setSaving(true)
- setMessage(null)
- try {
- const data = await apiRequest('/admin/settings', { method: 'PUT', body: JSON.stringify({ agent_chat_enabled: next }) })
- setEnabled(data.agent_chat_enabled)
- setMessage({ ok: true, text: data.agent_chat_enabled ? 'Chat is on for everyone.' : 'Chat is off. Nobody can send messages to the agent.' })
- } catch (error) {
- setMessage({ ok: false, text: error.message || 'Could not save the setting.' })
- } finally {
- setSaving(false)
- }
- }
-
- return (
- <AdminSection title="Chat" description="Lets users talk to the agent on the Agent page. Automatic incident diagnosis is not affected.">
- <Toggle label="Allow chat with the agent" description="Applies to every user, including admins." checked={enabled ?? false} onChange={change} disabled={enabled === null || saving} />
- {message && <p className={`mt-3 text-xs ${message.ok ? 'text-emerald-300' : 'text-amber-200'}`}>{message.text}</p>}
- </AdminSection>
- )
-}
-
-function AdminAgentTab() {
- return (
- <div className="space-y-5">
- <AgentChatSetting />
- <div className="grid gap-5 xl:grid-cols-2">
- <AdminSection title="Model" description="Which Gemini model the agent uses.">
- <div className="space-y-3">
- <select defaultValue="models/gemini-3.5-flash" aria-label="Agent model" className={inputClass}>
- <option value="models/gemini-3.5-flash">gemini-3.5-flash</option>
- <option value="models/gemini-3.5-pro">gemini-3.5-pro</option>
- </select>
- <div className="flex items-center justify-between rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm">
- <span className="text-[#bcbcbc]">API key</span>
- <span className="inline-flex items-center gap-2 text-white"><StatusDot ok />Set in .env</span>
- </div>
- </div>
- </AdminSection>
-
- <AdminSection title="Automatic diagnosis" description="Send new incidents to the agent for review without asking.">
- <div className="space-y-3">
- <Toggle label="Diagnose new incidents automatically" defaultOn />
- <label className="block">
- <span className="mb-2 block text-sm text-[#bcbcbc]">Minimum severity</span>
- <select defaultValue="WARNING" className={inputClass}>
- <option value="CRITICAL">Critical only</option>
- <option value="WARNING">Warning and critical</option>
- </select>
- </label>
- </div>
- </AdminSection>
- </div>
-
- <AdminSection title="System prompt" description="Instructions the agent follows in every diagnosis and chat." action={<SaveButton />}>
- <textarea rows={8} defaultValue={adminSettings.systemPrompt} aria-label="System prompt" className={`${inputClass} resize-y leading-6`} />
- </AdminSection>
-
- <AdminSection title="Safety rules" description="Built into the agent and always on. They can't be changed from the dashboard.">
- <div className="grid gap-2 md:grid-cols-2">
- {adminSettings.safetyRules.map((rule) => (
- <div key={rule} className="flex items-center justify-between gap-3 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm text-slate-200">
- {rule}
- <span className="rounded-full border border-emerald-400/30 bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-[0.2em] text-emerald-300">Enforced</span>
- </div>
- ))}
- </div>
- </AdminSection>
- </div>
- )
-}
-
-// [label, hint, warning key, critical key (null when the rule only warns), unit, step]
-const thresholdRows = [
- ['Disk usage', 'Default for every mount', 'disk_warning_pct', 'disk_critical_pct', '%', 1],
- ['Inode usage', 'Root filesystem', 'inodes_warning_pct', 'inodes_critical_pct', '%', 1],
- ['Memory usage', null, 'memory_warning_pct', 'memory_critical_pct', '%', 1],
- ['Swap usage', 'Warning only', 'swap_warning_pct', null, '%', 1],
- ['Load per CPU core', '5-minute average', 'load_warning_per_core', 'load_critical_per_core', '×', 0.1],
-]
-
-const thresholdInputClass = 'h-10 sm:h-8 w-20 rounded-xl border border-[#1f2326] bg-[#0d1013] px-2 py-1 text-right text-white outline-none focus:border-white/30 disabled:opacity-50'
-
-function ThresholdInput({ label, value, step, onChange, disabled, caption }) {
- const input = <input type="number" inputMode="decimal" aria-label={label} value={value ?? ''} step={step} min={0} disabled={disabled} onChange={(event) => onChange(event.target.value === '' ? '' : Number(event.target.value))} className={thresholdInputClass} />
- if (!caption) return input
- // On phones the Warning/Critical column headings are hidden, so each field carries its own.
- return <span className="flex flex-col gap-1"><span className={`text-[10px] uppercase tracking-wider sm:hidden ${caption === 'Warning' ? 'text-amber-300/80' : 'text-red-300/80'}`}>{caption}</span>{input}</span>
-}
-
-function IncidentThresholdsSection() {
- const [saved, setSaved] = useState(null)
- const [values, setValues] = useState(null)
- const [savedMounts, setSavedMounts] = useState([])
- const [mountRows, setMountRows] = useState([])
- const [saving, setSaving] = useState(false)
- const [message, setMessage] = useState(null)
-
- // The API keys overrides by mount; the form edits them as rows so a path can be typed freely.
- const toRows = (mountThresholds) => Object.entries(mountThresholds || {}).map(([mount, limits]) => ({ mount, warning: limits.disk_warning_pct, critical: limits.disk_critical_pct }))
- const toMountThresholds = (rows) => Object.fromEntries(rows.map((row) => [row.mount.trim(), { disk_warning_pct: row.warning, disk_critical_pct: row.critical }]))
-
- useEffect(() => {
- apiRequest('/admin/settings', { method: 'GET' })
- .then((data) => {
- setSaved(data.alert_thresholds)
- setValues(data.alert_thresholds)
- setSavedMounts(toRows(data.mount_thresholds))
- setMountRows(toRows(data.mount_thresholds))
- })
- .catch((error) => setMessage({ ok: false, text: error.message || 'Could not load the thresholds.' }))
- }, [])
-
- const set = (key) => (value) => setValues((current) => ({ ...current, [key]: value }))
- const setMountRow = (index, field) => (value) => setMountRows((rows) => rows.map((row, i) => (i === index ? { ...row, [field]: value } : row)))
-
- const save = async () => {
- setSaving(true)
- setMessage(null)
- try {
- const data = await apiRequest('/admin/settings', { method: 'PUT', body: JSON.stringify({ alert_thresholds: values, mount_thresholds: toMountThresholds(mountRows) }) })
- setSaved(data.alert_thresholds)
- setValues(data.alert_thresholds)
- setSavedMounts(toRows(data.mount_thresholds))
- setMountRows(toRows(data.mount_thresholds))
- setMessage({ ok: true, text: 'Saved. New thresholds apply from each server\'s next check-in.' })
- } catch (error) {
- setMessage({ ok: false, text: error.message || 'Could not save the thresholds.' })
- } finally {
- setSaving(false)
- }
- }
-
- const loading = values === null
- const unchanged = loading || (JSON.stringify(values) === JSON.stringify(saved) && JSON.stringify(mountRows) === JSON.stringify(savedMounts))
- const mountPaths = mountRows.map((row) => row.mount.trim())
- const incomplete = !loading && (Object.values(values).some((value) => value === '') || mountRows.some((row) => !row.mount.trim() || row.warning === '' || row.critical === '') || new Set(mountPaths).size !== mountPaths.length)
-
- return (
- <AdminSection
- title="Incident thresholds"
- description="When monitoring opens an incident. Applies to every server."
- action={
- <button type="button" onClick={save} disabled={unchanged || incomplete || saving} className="rounded-2xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-2.5 text-sm font-medium text-[#0b0b0b] disabled:cursor-not-allowed disabled:opacity-40">
- {saving ? 'Saving…' : 'Save changes'}
- </button>
- }
- >
- <div className="space-y-2">
- <div className="hidden justify-end gap-2 px-4 text-[10px] uppercase tracking-wider text-[#7f8589] sm:flex"><span className="w-20 text-right text-amber-300/80">Warning</span><span className="w-20 text-right text-red-300/80">Critical</span><span className="w-4" /></div>
- {thresholdRows.map(([label, hint, warningKey, criticalKey, unit, step]) => (
- <div key={label} className="flex flex-col gap-3 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:py-2.5">
- <span><span className="text-[#bcbcbc]">{label}</span>{hint && <span className="block text-xs text-[#7f8589]">{hint}</span>}</span>
- <span className="flex items-end gap-2 sm:items-center">
- <ThresholdInput label={`${label} warning`} caption="Warning" value={values?.[warningKey]} step={step} onChange={set(warningKey)} disabled={loading} />
- {criticalKey ? <ThresholdInput label={`${label} critical`} caption="Critical" value={values?.[criticalKey]} step={step} onChange={set(criticalKey)} disabled={loading} /> : <span className="hidden w-20 text-right text-[#7f8589] sm:inline">—</span>}
- <span className="w-4 pb-2 text-xs text-[#9aa0a6] sm:pb-0">{unit}</span>
- </span>
- </div>
- ))}
- <label className="flex flex-col gap-3 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:py-2.5">
- <span><span className="text-[#bcbcbc]">Check-ins in a row</span><span className="block text-xs text-[#7f8589]">How long a host metric must stay over before an incident opens</span></span>
- <ThresholdInput label="Check-ins in a row" value={values?.sustained_checks} step={1} onChange={set('sustained_checks')} disabled={loading} />
- </label>
- <div className="flex flex-col gap-3 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:py-2.5">
- <span className="shrink-0"><span className="text-[#bcbcbc]">Container restart loop</span><span className="block text-xs text-[#7f8589]">Critical incident</span></span>
- <span className="flex flex-wrap items-center gap-2 text-xs text-[#9aa0a6]">
- <ThresholdInput label="Restarts" value={values?.restart_loop_count} step={1} onChange={set('restart_loop_count')} disabled={loading} />restarts in
- <ThresholdInput label="Restart window in minutes" value={values?.restart_loop_window_minutes} step={1} onChange={set('restart_loop_window_minutes')} disabled={loading} />min
- </span>
- </div>
- <label className="flex flex-col gap-3 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:py-2.5">
- <span><span className="text-[#bcbcbc]">Event incidents</span><span className="block text-xs text-[#7f8589]">Minutes an incident stays open after a reboot, OOM kill, container exit, removal or image change</span></span>
- <ThresholdInput label="Event incident window in minutes" value={values?.event_window_minutes} step={1} onChange={set('event_window_minutes')} disabled={loading} />
- </label>
- <label className="flex flex-col gap-3 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:py-2.5">
- <span><span className="text-[#bcbcbc]">Slow Docker</span><span className="block text-xs text-[#7f8589]">Milliseconds to list containers before Docker counts as slow (sustained)</span></span>
- <ThresholdInput label="Slow Docker threshold in milliseconds" value={values?.docker_slow_ms} step={100} onChange={set('docker_slow_ms')} disabled={loading} />
- </label>
- <label className="flex flex-col gap-3 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:py-2.5">
- <span><span className="text-[#bcbcbc]">Slow collection</span><span className="block text-xs text-[#7f8589]">Warning when gathering data takes more than this percent of the check interval (sustained)</span></span>
- <ThresholdInput label="Slow collection threshold in percent of the check interval" value={values?.collect_slow_pct} step={5} onChange={set('collect_slow_pct')} disabled={loading} />
- </label>
- <div className="flex flex-col gap-3 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:py-2.5">
- <span className="shrink-0"><span className="text-[#bcbcbc]">Possible memory leak</span><span className="block text-xs text-[#7f8589]">Warning when a container's memory climbs steadily</span></span>
- <span className="flex flex-wrap items-center gap-2 text-xs text-[#9aa0a6]">
- <ThresholdInput label="Leak window in hours" value={values?.leak_window_hours} step={1} onChange={set('leak_window_hours')} disabled={loading} />h, at least
- <ThresholdInput label="Leak minimum MB per hour" value={values?.leak_min_mb_per_hour} step={1} onChange={set('leak_min_mb_per_hour')} disabled={loading} />MB/h and
- <ThresholdInput label="Leak minimum growth percent" value={values?.leak_min_growth_pct} step={1} onChange={set('leak_min_growth_pct')} disabled={loading} />%
- </span>
- </div>
- <div className="rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm">
- <div className="flex flex-wrap items-center justify-between gap-2">
- <span><span className="text-[#bcbcbc]">Disk usage per mount</span><span className="block text-xs text-[#7f8589]">Replaces the default disk thresholds for that mount, on every server</span></span>
- <button type="button" disabled={loading} onClick={() => setMountRows((rows) => [...rows, { mount: '', warning: values?.disk_warning_pct ?? 85, critical: values?.disk_critical_pct ?? 95 }])} className={secondaryButtonClass}>Add override</button>
- </div>
- {mountRows.length > 0 && <div className="mt-3 space-y-2">{mountRows.map((row, index) => (
- <div key={index} className="flex flex-wrap items-end gap-2 sm:items-center">
- <input type="text" aria-label="Mount path" placeholder="/mnt/data" value={row.mount} onChange={(event) => setMountRow(index, 'mount')(event.target.value)} className="h-10 min-w-0 flex-1 basis-40 rounded-xl border border-[#1f2326] bg-[#0d1013] px-3 font-mono text-xs text-white outline-none focus:border-white/30 sm:h-8" />
- <ThresholdInput label={`${row.mount || 'Mount'} warning`} caption="Warning" value={row.warning} step={1} onChange={setMountRow(index, 'warning')} />
- <ThresholdInput label={`${row.mount || 'Mount'} critical`} caption="Critical" value={row.critical} step={1} onChange={setMountRow(index, 'critical')} />
- <span className="pb-2 text-xs text-[#9aa0a6] sm:pb-0">%</span>
- <button type="button" aria-label={`Remove override for ${row.mount || 'mount'}`} onClick={() => setMountRows((rows) => rows.filter((_, i) => i !== index))} className="pb-2 text-lg leading-none text-[#9aa0a6] hover:text-red-300 sm:pb-0">×</button>
- </div>
- ))}</div>}
- </div>
- </div>
- {message && <p className={`mt-3 text-xs ${message.ok ? 'text-emerald-300' : 'text-amber-200'}`}>{message.text}</p>}
- </AdminSection>
- )
-}
-
-function AdminAlertsTab() {
- return (
- <IncidentThresholdsSection />
- )
-}
-
-const retentionOptions = [7, 30, 90, 365]
-
-function DataRetentionSection() {
- const [savedDays, setSavedDays] = useState(null)
- const [days, setDays] = useState(null)
- const [saving, setSaving] = useState(false)
- const [message, setMessage] = useState(null)
-
- useEffect(() => {
- apiRequest('/admin/settings', { method: 'GET' })
- .then((data) => {
- setSavedDays(data.metrics_retention_days)
- setDays(data.metrics_retention_days)
- })
- .catch((error) => setMessage({ ok: false, text: error.message || 'Could not load the setting.' }))
- }, [])
-
- const save = async () => {
- setSaving(true)
- setMessage(null)
- try {
- const data = await apiRequest('/admin/settings', { method: 'PUT', body: JSON.stringify({ metrics_retention_days: days }) })
- setSavedDays(data.metrics_retention_days)
- setMessage({ ok: true, text: 'Saved. Older metrics are removed within the hour.' })
- } catch (error) {
- setMessage({ ok: false, text: error.message || 'Could not save the setting.' })
- } finally {
- setSaving(false)
- }
- }
-
- const options = days && !retentionOptions.includes(days) ? [...retentionOptions, days].sort((a, b) => a - b) : retentionOptions
- const unchanged = days === null || days === savedDays
-
- return (
- <AdminSection
- title="Data retention"
- description="Older metrics are deleted automatically to keep the database small."
- action={
- <button type="button" onClick={save} disabled={unchanged || saving} className="rounded-2xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-2.5 text-sm font-medium text-[#0b0b0b] disabled:cursor-not-allowed disabled:opacity-40">
- {saving ? 'Saving…' : 'Save changes'}
- </button>
- }
- >
- <select value={days ?? ''} disabled={days === null} onChange={(event) => setDays(Number(event.target.value))} aria-label="Keep metrics for" className={inputClass}>
- {days === null && <option value="">Loading…</option>}
- {options.map((value) => <option key={value} value={value}>Keep metrics for {value === 365 ? '1 year' : `${value} days`}</option>)}
- </select>
- {message && <p className={`mt-3 text-xs ${message.ok ? 'text-emerald-300' : 'text-amber-200'}`}>{message.text}</p>}
- </AdminSection>
- )
-}
-
-function AdminSystemTab() {
- return (
- <div className="space-y-5">
- <div className="grid gap-5 xl:grid-cols-2">
- <AdminSection title="Services">
- <div className="space-y-2">
- {placeholderAdmin.services.map((service) => (
- <div key={service.name} className="flex items-center justify-between rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm">
- <span className="inline-flex items-center gap-2 text-white"><StatusDot ok={service.status === 'ok'} />{service.name}</span>
- <span className="text-xs text-[#9aa0a6]">{service.detail}</span>
- </div>
- ))}
- </div>
- </AdminSection>
-
- <DataRetentionSection />
- </div>
-
- <AdminSection title="Audit log" description="Who did what, and when.">
- <ul className="divide-y divide-white/5">
- {placeholderAdmin.audit.map((entry) => (
- <li key={entry.id} className="flex flex-wrap items-baseline gap-x-4 gap-y-1 py-2.5 text-sm">
- <time className="w-40 shrink-0 text-xs text-[#7f8589]">{formatDateTime(entry.time)}</time>
- <span className="w-20 shrink-0 text-[#9aa0a6]">{entry.actor}</span>
- <span className="text-[#d1d5db]">{entry.event}</span>
- </li>
- ))}
- </ul>
- </AdminSection>
- </div>
- )
-}
-
-const adminTabContent = {
- users: AdminUsersTab,
- servers: AdminServersTab,
- agent: AdminAgentTab,
- alerts: AdminAlertsTab,
- system: AdminSystemTab,
-}
-
-function AdminPage({ user, onLogout }) {
- const [activeTab, setActiveTab] = useState('users')
- const TabContent = adminTabContent[activeTab]
-
- return (
- <AppShell user={user} onLogout={onLogout}>
- <div className="flex flex-col gap-5">
- <header className="glass-panel rounded-[28px] p-5 md:p-6">
- <div className="text-xs uppercase tracking-[0.22em] text-[#9aa0a6]">Configuration</div>
- <h1 className="mt-1 text-3xl font-semibold text-white">Admin</h1>
- <p className="mt-2 max-w-3xl text-sm leading-6 text-[#9aa0a6]">Manage users, servers, the agent and system settings. Showing placeholder data for now; changes are not saved.</p>
- <div role="tablist" aria-label="Admin sections" className="no-scrollbar -mx-5 mt-5 flex gap-2 overflow-x-auto px-5 md:mx-0 md:flex-wrap md:px-0">
- {adminTabs.map((tab) => (
- <button
- key={tab.id}
- type="button"
- role="tab"
- aria-selected={activeTab === tab.id}
- onClick={() => setActiveTab(tab.id)}
- className={`shrink-0 rounded-2xl px-4 py-2.5 text-sm transition ${activeTab === tab.id ? 'bg-[#171b1f] text-white ring-1 ring-white/10' : 'text-[#bcbcbc] hover:bg-[#111417] hover:text-white'}`}
- >
- {tab.label}
- </button>
- ))}
- </div>
- </header>
-
- <TabContent />
- </div>
- </AppShell>
- )
-}
-
function RequireAuth({ user, children }) {
const location = useLocation()
if (!user) {
return <Navigate to="/login" replace state={{ from: location.pathname }} />
}
- // An administrator who still has to set up two-factor can only use the account page.
+ // Someone who still has to set up two-factor can only use the account page.
if (user.setup_required && location.pathname !== '/account') {
return <Navigate to="/account" replace />
}
@@ -2244,265 +35,33 @@ function RequireAuth({ user, children }) {
return children
}
-function SecretsBox({ children }) {
- return <div className="rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 p-4">{children}</div>
-}
-
-function PasswordSection() {
- const [form, setForm] = useState({ current: '', next: '', repeat: '' })
- const [message, setMessage] = useState(null)
- const [busy, setBusy] = useState(false)
- const set = (key) => (event) => setForm((current) => ({ ...current, [key]: event.target.value }))
-
- const submit = async (event) => {
- event.preventDefault()
- setMessage(null)
- if (form.next.length < MIN_PASSWORD_LENGTH) return setMessage({ ok: false, text: `The new password must be at least ${MIN_PASSWORD_LENGTH} characters.` })
- if (form.next !== form.repeat) return setMessage({ ok: false, text: 'The two new passwords do not match.' })
- setBusy(true)
- try {
- const data = await apiRequest('/auth/password', { method: 'POST', body: JSON.stringify({ current_password: form.current, new_password: form.next }) })
- setForm({ current: '', next: '', repeat: '' })
- setMessage({ ok: true, text: `Password changed. ${data.other_sessions_signed_out} other ${data.other_sessions_signed_out === 1 ? 'session was' : 'sessions were'} signed out.` })
- } catch (error) {
- setMessage({ ok: false, text: error.message || 'Could not change the password.' })
- } finally {
- setBusy(false)
- }
- }
-
- return (
- <AdminSection title="Password" description={`At least ${MIN_PASSWORD_LENGTH} characters; a few random words make a good passphrase. Changing it signs you out everywhere else.`}>
- <form onSubmit={submit} className="max-w-md space-y-3">
- <input type="password" autoComplete="current-password" aria-label="Current password" placeholder="Current password" value={form.current} onChange={set('current')} className={inputClass} required />
- <input type="password" autoComplete="new-password" aria-label="New password" placeholder={`New password (${MIN_PASSWORD_LENGTH}+ characters)`} value={form.next} onChange={set('next')} className={inputClass} required />
- <input type="password" autoComplete="new-password" aria-label="Repeat the new password" placeholder="Repeat the new password" value={form.repeat} onChange={set('repeat')} className={inputClass} required />
- <button type="submit" disabled={busy} className="rounded-2xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-2.5 text-sm font-medium text-[#0b0b0b] disabled:opacity-50">{busy ? 'Changing…' : 'Change password'}</button>
- {message && <p className={`text-xs ${message.ok ? 'text-emerald-300' : 'text-amber-200'}`}>{message.text}</p>}
- </form>
- </AdminSection>
- )
-}
-
-function RecoveryCodesPanel({ codes, onDone, doneLabel }) {
- const [saved, setSaved] = useState(false)
- const [copied, setCopied] = useState(false)
- const copy = async () => {
- try { await navigator.clipboard.writeText(codes.join('\n')); setCopied(true); setTimeout(() => setCopied(false), 1500) } catch { setCopied(false) }
- }
- return (
- <SecretsBox>
- <div className="text-sm font-medium text-white">Save your recovery codes</div>
- <p className="mt-1 text-xs text-[#9aa0a6]">Each code works once if you lose your authenticator. They are shown only now; store them somewhere safe, such as a password manager.</p>
- <ul className="mt-3 grid grid-cols-1 gap-1.5 font-mono text-sm text-[#cfcfcf] sm:grid-cols-2">{codes.map((code) => <li key={code} className="rounded-lg bg-white/5 px-3 py-1.5">{code}</li>)}</ul>
- <div className="mt-3 flex flex-wrap items-center gap-3">
- <button type="button" onClick={copy} className={secondaryButtonClass}>{copied ? 'Copied' : 'Copy codes'}</button>
- <label className="inline-flex items-center gap-2 text-xs text-[#bcbcbc]"><input type="checkbox" checked={saved} onChange={(event) => setSaved(event.target.checked)} className="h-4 w-4" />I have saved these codes</label>
- <button type="button" disabled={!saved} onClick={onDone} className="rounded-xl bg-white px-3 py-1.5 text-xs font-medium text-slate-950 disabled:opacity-40">{doneLabel}</button>
- </div>
- </SecretsBox>
- )
-}
-
-function TwoFactorSection({ status, reload, onEnrolled }) {
- const [setup, setSetup] = useState(null)
- const [code, setCode] = useState('')
- const [codes, setCodes] = useState(null)
- const [form, setForm] = useState({ password: '', code: '' })
- const [action, setAction] = useState(null)
- const [message, setMessage] = useState(null)
- const [busy, setBusy] = useState(false)
-
- const run = async (work) => {
- setBusy(true)
- setMessage(null)
- try { await work() } catch (error) { setMessage({ ok: false, text: error.message || 'Something went wrong.' }) } finally { setBusy(false) }
- }
- const [askPassword, setAskPassword] = useState(false)
- const [setupPassword, setSetupPassword] = useState('')
- // A session that has just signed in (the forced first enrolment) needs no password; a normal one must give it again.
- const start = () => {
- if (!status.setup_required && !askPassword) { setAskPassword(true); return }
- return run(async () => {
- setSetup(await apiRequest('/auth/2fa/setup', { method: 'POST', body: JSON.stringify(status.setup_required ? {} : { password: setupPassword }) }))
- setSetupPassword(''); setAskPassword(false)
- })
- }
- const enable = (event) => { event.preventDefault(); run(async () => {
- const data = await apiRequest('/auth/2fa/enable', { method: 'POST', body: JSON.stringify({ code: code.trim() }) })
- setCodes(data.recovery_codes); setSetup(null); setCode('')
- await reload()
- }) }
- const reauth = (path, onData) => (event) => { event.preventDefault(); run(async () => {
- const data = await apiRequest(path, { method: 'POST', body: JSON.stringify({ password: form.password, code: form.code.trim() }) })
- setForm({ password: '', code: '' }); setAction(null); onData(data)
- await reload()
- }) }
- const secretText = setup ? setup.secret.match(/.{1,4}/g).join(' ') : ''
-
- return (
- <AdminSection title="Two-factor sign-in" description="A 6-digit code from an authenticator app (such as Aegis, Authy or Google Authenticator) is asked for after your password.">
- {!status.available && <p className="rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-sm text-amber-200">Two-factor can't be set up because the server has no <code>SECRETS_KEY</code>. An administrator needs to set one in <code>.env</code> (see docs/accounts.md, Two-factor sign-in).</p>}
-
- {status.available && codes && <RecoveryCodesPanel codes={codes} doneLabel={status.setup_required || onEnrolled ? 'Continue' : 'Done'} onDone={() => { setCodes(null); if (onEnrolled) onEnrolled() }} />}
-
- {status.available && !codes && !status.enabled && (
- <div className="space-y-3">
- {status.required && <p className="text-sm text-amber-200">Two-factor is required for administrators on this server.</p>}
- {!setup && askPassword && (
- <form onSubmit={(event) => { event.preventDefault(); start() }} className="flex flex-wrap items-center gap-2">
- <input type="password" autoComplete="current-password" autoFocus aria-label="Your current password" placeholder="Your current password" value={setupPassword} onChange={(event) => setSetupPassword(event.target.value)} className="min-h-10 w-64 max-w-full rounded-xl border border-white/10 bg-[#111417] px-3 text-sm text-white" />
- <button type="submit" disabled={busy || !setupPassword} className="rounded-xl bg-white px-4 py-2 text-sm font-medium text-slate-950 disabled:opacity-50">Continue</button>
- <button type="button" onClick={() => { setAskPassword(false); setSetupPassword('') }} className="text-xs text-[#9aa0a6] hover:text-white">Cancel</button>
- <span className="w-full text-xs text-[#7f8589]">Asked again because turning on two-factor is a sensitive change.</span>
- </form>
- )}
- {!setup && !askPassword && <button type="button" onClick={start} disabled={busy} className="rounded-2xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-2.5 text-sm font-medium text-[#0b0b0b] disabled:opacity-50">Set up two-factor</button>}
- {setup && (
- <SecretsBox>
- <ol className="list-decimal space-y-3 pl-5 text-sm text-[#bcbcbc]">
- <li>In your authenticator app, add an account and enter this key (time-based, 6 digits):
- <div className="mt-2 break-all rounded-lg bg-white/5 px-3 py-2 font-mono text-base tracking-wider text-white select-all">{secretText}</div>
- <a href={setup.otpauth_uri} className="mt-1 inline-block text-xs text-emerald-300 underline">or open it in an authenticator app on this device</a>
- </li>
- <li>Enter the code the app shows now to confirm:
- <form onSubmit={enable} className="mt-2 flex flex-wrap items-center gap-2">
- <input type="text" inputMode="numeric" autoComplete="one-time-code" maxLength={8} aria-label="Code from the authenticator app" placeholder="123456" value={code} onChange={(event) => setCode(event.target.value)} className={`${inputClass} w-40 font-mono tracking-widest`} required />
- <button type="submit" disabled={busy} className="rounded-xl bg-white px-4 py-2 text-sm font-medium text-slate-950 disabled:opacity-50">Turn on</button>
- </form>
- </li>
- </ol>
- </SecretsBox>
- )}
- </div>
- )}
-
- {status.available && !codes && status.enabled && (
- <div className="space-y-3">
- <p className="text-sm text-emerald-300">Two-factor is on. <span className="text-[#9aa0a6]">{status.recovery_codes_left} recovery {status.recovery_codes_left === 1 ? 'code' : 'codes'} left.</span></p>
- <div className="flex flex-wrap gap-2">
- <button type="button" onClick={() => setAction(action === 'codes' ? null : 'codes')} className={secondaryButtonClass}>New recovery codes</button>
- {!status.required && <button type="button" onClick={() => setAction(action === 'off' ? null : 'off')} className="min-h-10 sm:min-h-0 rounded-xl border border-red-400/30 bg-red-500/5 px-3 py-1.5 text-xs text-red-300 hover:bg-red-500/10">Turn off</button>}
- </div>
- {status.required && <p className="text-xs text-[#7f8589]">It can't be turned off while it is required for administrators.</p>}
- {action && (
- <form onSubmit={action === 'off' ? reauth('/auth/2fa/disable', () => setMessage({ ok: true, text: 'Two-factor is off. Your other sessions were signed out.' })) : reauth('/auth/2fa/recovery-codes', (data) => setCodes(data.recovery_codes))} className="max-w-md space-y-2">
- <p className="text-xs text-[#9aa0a6]">Confirm with your password and a current code (or a recovery code).</p>
- <input type="password" autoComplete="current-password" aria-label="Password" placeholder="Password" value={form.password} onChange={(event) => setForm((current) => ({ ...current, password: event.target.value }))} className={inputClass} required />
- <input type="text" autoComplete="one-time-code" aria-label="Code" placeholder="Code" maxLength={32} value={form.code} onChange={(event) => setForm((current) => ({ ...current, code: event.target.value }))} className={`${inputClass} font-mono`} required />
- <button type="submit" disabled={busy} className="rounded-xl bg-white px-4 py-2 text-sm font-medium text-slate-950 disabled:opacity-50">{action === 'off' ? 'Turn off two-factor' : 'Generate new codes'}</button>
- </form>
- )}
- </div>
- )}
- {message && <p className={`mt-3 text-xs ${message.ok ? 'text-emerald-300' : 'text-amber-200'}`}>{message.text}</p>}
- </AdminSection>
- )
-}
-
-function SessionsSection() {
- const [sessions, setSessions] = useState(null)
- const [message, setMessage] = useState(null)
- const load = () => apiRequest('/auth/sessions', { method: 'GET' }).then((data) => setSessions(data.sessions)).catch((error) => setMessage({ ok: false, text: error.message || 'Could not load the sessions.' }))
- // eslint-disable-next-line react-hooks/exhaustive-deps
- useEffect(() => { load() }, [])
-
- const end = async (id) => {
- setMessage(null)
- try { await apiRequest(`/auth/sessions/${id}`, { method: 'DELETE' }); await load() } catch (error) { setMessage({ ok: false, text: error.message || 'Could not sign that session out.' }) }
- }
- const endOthers = async () => {
- setMessage(null)
- try {
- const data = await apiRequest('/auth/sessions/revoke-others', { method: 'POST' })
- setMessage({ ok: true, text: `Signed out ${data.signed_out} other ${data.signed_out === 1 ? 'session' : 'sessions'}.` })
- await load()
- } catch (error) { setMessage({ ok: false, text: error.message || 'Could not sign the other sessions out.' }) }
- }
-
- return (
- <AdminSection title="Where you're signed in" description="Sign out any session you don't recognise." action={sessions?.length > 1 ? <button type="button" onClick={endOthers} className={secondaryButtonClass}>Sign out all others</button> : null}>
- {sessions === null ? <p className="text-sm text-[#9aa0a6]">Loading…</p> : (
- <ul className="space-y-2">{sessions.map((session) => (
- <li key={session.id} className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm">
- <div className="min-w-0">
- <div className="truncate text-white">{session.user_agent || 'Unknown browser'}{session.current && <span className="ml-2 rounded-full bg-emerald-400/15 px-2 py-0.5 text-[10px] font-semibold tracking-wider text-emerald-300">THIS SESSION</span>}</div>
- <div className="text-xs text-[#9aa0a6]">{session.ip || 'unknown address'} · signed in {session.created_at ? formatDateTime(session.created_at) : 'earlier'}</div>
- </div>
- {!session.current && <button type="button" onClick={() => end(session.id)} className={secondaryButtonClass}>Sign out</button>}
- </li>
- ))}</ul>
- )}
- <p className="mt-3 text-xs text-[#7f8589]">Sessions that started before this feature was added don't appear here and expire on their own within a day.</p>
- {message && <p className={`mt-3 text-xs ${message.ok ? 'text-emerald-300' : 'text-amber-200'}`}>{message.text}</p>}
- </AdminSection>
- )
-}
-
-function AccountPage({ user, onLogout, onUserChange }) {
- const navigate = useNavigate()
- const [status, setStatus] = useState(null)
- const [error, setError] = useState('')
- // Remember that this visit began as a required setup, so Continue leads on to the dashboard once it is done.
- const wasRequired = useRef(false)
- if (status?.setup_required) wasRequired.current = true
- const reload = () => apiRequest('/auth/2fa/status', { method: 'GET' }).then((data) => { setStatus(data); onUserChange({ setup_required: data.setup_required, two_factor_enabled: data.enabled }) }).catch((requestError) => setError(requestError.message || 'Could not load your account.'))
- // eslint-disable-next-line react-hooks/exhaustive-deps
- useEffect(() => { reload() }, [])
-
- return (
- <AppShell user={user} onLogout={onLogout}>
- <div className="flex flex-col gap-5">
- <header className="glass-panel rounded-[28px] p-5 md:p-6">
- <div className="text-xs uppercase tracking-[0.22em] text-[#9aa0a6]">Your account</div>
- <h1 className="mt-1 text-3xl font-semibold text-white">Account</h1>
- <p className="mt-2 text-sm text-[#9aa0a6]">{user.name} · {user.email} · {user.role}</p>
- {status?.setup_required && <div className="mt-4 rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-sm text-amber-200">Two-factor is required for administrators. Set it up below to continue to the dashboard.</div>}
- {error && <div className="mt-4 rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-sm text-amber-200">{error}</div>}
- </header>
- {status && <TwoFactorSection status={status} reload={reload} onEnrolled={wasRequired.current ? () => navigate('/') : null} />}
- {status && !status.setup_required && <PasswordSection />}
- {status && !status.setup_required && <SessionsSection />}
- </div>
- </AppShell>
- )
-}
-
function App() {
const [user, setUser] = useState(() => getStoredUser())
- const [users, setUsers] = useState(() => getStoredUsers())
useEffect(() => {
- if (user) {
- window.localStorage.setItem(AUTH_KEY, JSON.stringify(user))
- } else {
- window.localStorage.removeItem(AUTH_KEY)
+ try {
+ if (user) window.localStorage.setItem(AUTH_KEY, JSON.stringify(user))
+ else window.localStorage.removeItem(AUTH_KEY)
+ } catch {
+ // Private windows: the sign-in just isn't remembered across reloads.
}
}, [user])
useEffect(() => {
if (!user) return
-
- apiRequest('/auth/me', {
- method: 'GET',
- }).then((data) => {
- setUser((currentUser) => ({ ...(currentUser || {}), ...data.user }))
- }).catch(() => {
- setUser(null)
- })
+ apiRequest('/auth/me', { method: 'GET' })
+ .then((data) => setUser((current) => ({ ...(current || {}), ...data.user })))
+ .catch(() => setUser(null))
+ // Only on load: this checks that the remembered sign-in is still valid.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
+ // Theme and density from this browser at once, then from the account once it has loaded.
+ useEffect(() => { applyDisplay() }, [])
useEffect(() => {
- window.localStorage.setItem(USERS_KEY, JSON.stringify(users))
- }, [users])
-
- const handleLogin = (nextUser) => {
- setUser(nextUser)
- }
-
- const handleRegister = (nextUser) => {
- setUser(nextUser)
- }
+ if (!user?.id || user.setup_required) return
+ apiRequest('/account', { method: 'GET' }).then((account) => applyDisplay(account.preferences.display)).catch(() => {})
+ }, [user?.id, user?.setup_required])
const handleLogout = async () => {
try {
@@ -2510,60 +69,24 @@ function App() {
} catch {
// Clear local state even if the session has already expired.
}
+ resetOverview()
setUser(null)
}
+ const page = (element) => <RequireAuth user={user}>{element}</RequireAuth>
return (
<BrowserRouter>
<Routes>
- <Route path="/login" element={user ? <Navigate to="/" replace /> : <LoginPage onLogin={handleLogin} />} />
- <Route path="/register" element={user ? <Navigate to="/" replace /> : <RegisterPage onRegister={handleRegister} />} />
-
- <Route
- path="/"
- element={
- <RequireAuth user={user}>
- <DashboardPage user={user} onLogout={handleLogout} />
- </RequireAuth>
- }
- />
- <Route path="/dashboard" element={<RequireAuth user={user}><Navigate to="/" replace /></RequireAuth>} />
- <Route
- path="/agent"
- element={
- <RequireAuth user={user}>
- <AgentPage user={user} onLogout={handleLogout} />
- </RequireAuth>
- }
- />
- <Route
- path="/statistics"
- element={
- <RequireAuth user={user}>
- <AppShell user={user} onLogout={handleLogout}>
- <StatisticsContent request={apiRequest} />
- </AppShell>
- </RequireAuth>
- }
- />
- <Route
- path="/account"
- element={
- <RequireAuth user={user}>
- <AccountPage user={user} onLogout={handleLogout} onUserChange={(patch) => setUser((current) => (current ? { ...current, ...patch } : current))} />
- </RequireAuth>
- }
- />
- <Route path="/reports" element={<RequireAuth user={user}><Navigate to="/agent" replace /></RequireAuth>} />
- <Route path="/logs" element={<RequireAuth user={user}><Navigate to="/agent" replace /></RequireAuth>} />
- <Route
- path="/admin"
- element={
- <RequireAuth user={user}>
- {user?.role === 'admin' ? <AdminPage user={user} onLogout={handleLogout} /> : <Navigate to="/" replace />}
- </RequireAuth>
- }
- />
+ <Route path="/login" element={user ? <Navigate to="/" replace /> : <LoginPage onLogin={setUser} />} />
+ <Route path="/register" element={user ? <Navigate to="/" replace /> : <RegisterPage onRegister={setUser} />} />
+ <Route path="/" element={page(<DashboardPage user={user} onLogout={handleLogout} />)} />
+ <Route path="/dashboard" element={page(<Navigate to="/" replace />)} />
+ <Route path="/statistics" element={page(<StatisticsPage user={user} onLogout={handleLogout} />)} />
+ <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="/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>
</BrowserRouter>
)
diff --git a/src/frontend/src/ContainerStatistics.jsx b/src/frontend/src/ContainerStatistics.jsx
deleted file mode 100644
index e4fa5e7..0000000
--- a/src/frontend/src/ContainerStatistics.jsx
+++ /dev/null
@@ -1,148 +0,0 @@
-// The containers of one server as small cards; selecting one shows its statistics over the chosen range.
-import { useEffect, useMemo, useState } from 'react'
-import { TimeSeriesChart } from './charts.jsx'
-import { describeBucket, seriesFor, summarise } from './chartMath.js'
-import { problemRank, sortContainers } from './containerLogic.js'
-
-const LIVE_RANGES = new Set(['1h', '6h', '24h'])
-const REFRESH_SECONDS = 30
-const METRICS = 'cpu,memory_mb,memory_limit_mb,restarts'
-const SORTS = [
- { id: 'problems', label: 'Problems first' },
- { id: 'name', label: 'Name' },
- { id: 'memory', label: 'Memory' },
- { id: 'cpu', label: 'CPU' },
-]
-
-function statusColour(container) {
- const rank = problemRank(container)
- if (rank === 0) return container.status === 'restarting' ? 'bg-red-400' : 'bg-amber-400'
- return rank === 1 ? 'bg-red-400' : 'bg-emerald-400'
-}
-
-function ContainerCard({ container, selected, onSelect }) {
- const memoryPct = container.memory_pct
- return (
- <button
- type="button"
- aria-pressed={selected}
- onClick={onSelect}
- className={`min-w-0 rounded-2xl border p-3 text-left transition ${selected ? 'border-white/40 bg-white/10' : 'border-[#1f2326] bg-[#0d1013]/60 hover:border-white/20'}`}
- >
- <div className="flex items-center gap-2">
- <span aria-hidden="true" className={`h-2.5 w-2.5 shrink-0 rounded-full ${statusColour(container)}`} />
- <span className="truncate text-sm font-medium text-white">{container.name}</span>
- </div>
- <div className="mt-1 truncate text-xs text-[#7f8589]">
- {container.status}{container.healthcheck_status ? ` · ${container.healthcheck_status}` : ''}{container.restart_count > 0 ? ` · ${container.restart_count} restarts` : ''}
- </div>
- <div className="mt-2 flex items-baseline justify-between text-xs text-[#9aa0a6]">
- <span>CPU <span className="text-sm text-white">{container.cpu_pct == null ? '–' : `${container.cpu_pct}%`}</span></span>
- <span>Memory <span className="text-sm text-white">{container.memory_used_mb == null ? '–' : `${Math.round(container.memory_used_mb)} MB`}</span></span>
- </div>
- <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-white/10" title={memoryPct == null ? 'No memory limit' : `${memoryPct}% of its memory limit`}>
- {memoryPct != null && <div className={`h-full rounded-full ${memoryPct >= 90 ? 'bg-red-400' : memoryPct >= 75 ? 'bg-amber-400' : 'bg-emerald-400'}`} style={{ width: `${Math.min(Math.max(memoryPct, 0), 100)}%` }} />}
- </div>
- </button>
- )
-}
-
-function Figure({ label, value }) {
- return (
- <div className="rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3">
- <div className="text-xs uppercase tracking-[0.18em] text-[#9aa0a6]">{label}</div>
- <div className="mt-1 text-xl font-semibold text-white">{value}</div>
- </div>
- )
-}
-
-function ContainerDetail({ request, serverId, container, range, onClose }) {
- const [data, setData] = useState(null)
- const [error, setError] = useState('')
-
- useEffect(() => {
- const controller = new AbortController()
- const load = () => request(`/monitoring/servers/${serverId}/containers/${encodeURIComponent(container.container_id)}/history?range=${range}&metrics=${METRICS}`, { method: 'GET', signal: controller.signal })
- .then((result) => { setData(result); setError('') })
- .catch((requestError) => { if (requestError.name !== 'AbortError') setError(requestError.message || 'Could not load this container.') })
- load()
- if (!LIVE_RANGES.has(range)) return () => controller.abort()
- const timer = setInterval(() => { if (!document.hidden) load() }, REFRESH_SECONDS * 1000)
- return () => { controller.abort(); clearInterval(timer) }
- }, [request, serverId, container.container_id, range])
-
- const current = data && data.container_id === container.container_id ? data : null
- const series = useMemo(() => ({ cpu: seriesFor(current?.points, 'cpu'), memory: seriesFor(current?.points, 'memory_mb') }), [current])
- const limit = useMemo(() => Math.max(0, ...(current?.points || []).map((point) => point.memory_limit_mb?.max ?? 0)) || null, [current])
- const figures = useMemo(() => {
- const points = current?.points || []
- const samples = points.reduce((total, point) => total + point.samples, 0)
- const down = points.reduce((total, point) => total + (point.down || 0), 0)
- const restarts = points.map((point) => point.restarts?.max).filter((value) => value != null)
- return { samples, notRunning: samples ? (100 * down) / samples : null, restarts: restarts.length ? restarts[restarts.length - 1] - restarts[0] : null }
- }, [current])
- const cpu = summarise(series.cpu)
- const memory = summarise(series.memory)
- const common = { bucketSeconds: current?.bucket_seconds ?? 60, start: current ? new Date(current.start).getTime() : undefined, end: current ? new Date(current.end).getTime() : undefined, utc: current ? ['day', 'week', 'month'].includes(current.source) : false }
-
- return (
- <section aria-label={`Statistics for ${container.name}`} className="space-y-4 rounded-3xl border border-white/10 bg-[#0d1013]/40 p-4">
- <div className="flex items-start justify-between gap-3">
- <div className="min-w-0">
- <h3 className="truncate text-lg font-semibold text-white">{container.name}</h3>
- <div className="truncate text-xs text-[#7f8589]">{container.image || 'unknown image'}</div>
- </div>
- <button type="button" onClick={onClose} className="shrink-0 rounded-xl border border-white/10 px-3 py-1.5 text-xs text-[#9aa0a6] hover:text-white">Close</button>
- </div>
- {error && <div role="alert" className="rounded-2xl border border-red-400/30 bg-red-500/10 px-4 py-3 text-sm text-red-200">{error}</div>}
- {current && (
- <>
- <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
- <Figure label="Average CPU" value={cpu.average == null ? '–' : `${cpu.average.toFixed(1)}%`} />
- <Figure label="Peak memory" value={memory.maximum == null ? '–' : `${Math.round(memory.maximum)} MB`} />
- <Figure label="Not running" value={figures.notRunning == null ? '–' : `${figures.notRunning.toFixed(1)}% of the time`} />
- <Figure label="Restarts in range" value={figures.restarts == null ? '–' : figures.restarts} />
- </div>
- <p className="text-xs text-[#7f8589]">{current.points.length ? `One point per ${describeBucket(current.bucket_seconds)}. A container only reports CPU and memory while it is running.` : 'Nothing recorded for this container in this range.'}</p>
- <div className="grid gap-4 xl:grid-cols-2">
- <TimeSeriesChart {...common} title="CPU usage" series={series.cpu} color="#34d399" />
- <TimeSeriesChart {...common} title="Memory used" series={series.memory} color="#a78bfa" unit="MB" decimals={0} limit={limit} />
- </div>
- </>
- )}
- </section>
- )
-}
-
-export default function ContainerStatistics({ request, serverId, containers, range, selectedId, onSelect }) {
- const [query, setQuery] = useState('')
- const [sort, setSort] = useState('problems')
- const shown = useMemo(() => sortContainers(containers.filter((container) => container.name.toLowerCase().includes(query.trim().toLowerCase())), sort), [containers, query, sort])
- const selected = containers.find((container) => container.container_id === selectedId) || null
- const problems = containers.filter((container) => problemRank(container) < 2).length
-
- return (
- <section aria-label="Containers" className="space-y-4">
- <div className="flex flex-wrap items-end justify-between gap-3">
- <div>
- <h2 className="text-xl font-semibold text-white">Containers</h2>
- <p className="text-xs text-[#7f8589]">{containers.length} on this server{problems ? ` · ${problems} need attention` : ''}. Select one for its statistics.</p>
- </div>
- {containers.length > 0 && (
- <div className="flex flex-wrap gap-2">
- <input type="search" aria-label="Search containers" placeholder="Search" value={query} onChange={(event) => setQuery(event.target.value)} className="min-h-11 w-40 rounded-xl border border-white/10 bg-[#111417] px-3 text-sm text-white sm:min-h-0 sm:py-2" />
- <select aria-label="Sort containers" value={sort} onChange={(event) => setSort(event.target.value)} className="min-h-11 rounded-xl border border-white/10 bg-[#111417] px-3 text-sm text-white sm:min-h-0 sm:py-2">
- {SORTS.map((option) => <option key={option.id} value={option.id}>{option.label}</option>)}
- </select>
- </div>
- )}
- </div>
- {containers.length === 0 && <div className="rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-6 text-sm text-[#9aa0a6]">This server has no containers (or its collector has no Docker access).</div>}
- {containers.length > 0 && shown.length === 0 && <div className="text-sm text-[#7f8589]">No container matches “{query}”.</div>}
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">
- {shown.map((container) => <ContainerCard key={container.container_id} container={container} selected={container.container_id === selectedId} onSelect={() => onSelect(container.container_id === selectedId ? '' : container.container_id)} />)}
- </div>
- {selected && <ContainerDetail request={request} serverId={serverId} container={selected} range={range} onClose={() => onSelect('')} />}
- </section>
- )
-}
diff --git a/src/frontend/src/FleetStatistics.jsx b/src/frontend/src/FleetStatistics.jsx
index 283060f..b3718a3 100644
--- a/src/frontend/src/FleetStatistics.jsx
+++ b/src/frontend/src/FleetStatistics.jsx
@@ -6,17 +6,17 @@ import { availabilityRows, bucketLabel, containerStateSlices, formatDuration, in
const LIVE_RANGES = new Set(['1h', '6h', '24h'])
const REFRESH_SECONDS = 30
const SEVERITIES = [
- { key: 'critical', label: 'Critical', color: '#f87171' },
- { key: 'warning', label: 'Warning', color: '#fbbf24' },
- { key: 'info', label: 'Info', color: '#7dd3fc' },
+ { key: 'critical', label: 'Critical', color: '#FF5A1F' },
+ { key: 'warning', label: 'Warning', color: '#E2B04A' },
+ { key: 'info', label: 'Info', color: '#6F6D69' },
]
function Figure({ label, value, detail }) {
return (
- <div className="rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3">
- <div className="text-xs uppercase tracking-[0.18em] text-[#9aa0a6]">{label}</div>
- <div className="mt-1 text-2xl font-semibold text-white">{value}</div>
- {detail && <div className="text-xs text-[#7f8589]">{detail}</div>}
+ <div className="card px-4 py-3">
+ <div className="text-xs text-soft">{label}</div>
+ <div className="mt-1 text-2xl font-semibold leading-none text-paper">{value}</div>
+ {detail && <div className="text-xs text-muted">{detail}</div>}
</div>
)
}
@@ -48,7 +48,7 @@ export default function FleetStatistics({ request, servers, range }) {
return (
<div className="space-y-5">
- {error && <div role="alert" className="rounded-2xl border border-red-400/30 bg-red-500/10 px-4 py-3 text-sm text-red-200">{error}</div>}
+ {error && <div role="alert" className="rounded-md border border-warn/40 px-3.5 py-2.5 text-xs text-warn">{error}</div>}
<div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
<Figure label="Servers online" value={`${online} of ${servers.length}`} />
<Figure label="Containers running" value={`${running} of ${containerTotal}`} />
@@ -73,10 +73,10 @@ export default function FleetStatistics({ request, servers, range }) {
)}
<div className="grid gap-4 lg:grid-cols-2">
- {current && <BarList title="What the incidents were about" subtitle="Opened in this range" rows={current.incidents.by_kind.slice(0, 10).map((item) => ({ label: item.kind, value: item.count }))} color="#a78bfa" empty="No incidents opened in this range." />}
+ {current && <BarList title="What the incidents were about" subtitle="Opened in this range" rows={current.incidents.by_kind.slice(0, 10).map((item) => ({ label: item.kind, value: item.count }))} color="#D0CEC8" empty="No incidents opened in this range." />}
<BarList title="Servers by disk usage" subtitle="Root disk, right now" rows={serversByDisk(servers)} max={100} unit="%" decimals={0} />
- <BarList title="Containers using the most memory" subtitle="Right now" rows={topContainers(servers, 'memory_used_mb')} unit=" MB" color="#a78bfa" />
- <BarList title="Containers using the most CPU" subtitle="Right now" rows={topContainers(servers, 'cpu_pct')} unit="%" decimals={1} color="#34d399" />
+ <BarList title="Containers using the most memory" subtitle="Right now" rows={topContainers(servers, 'memory_used_mb')} unit=" MB" color="#D0CEC8" />
+ <BarList title="Containers using the most CPU" subtitle="Right now" rows={topContainers(servers, 'cpu_pct')} unit="%" decimals={1} color="#D0CEC8" />
</div>
{current && (
diff --git a/src/frontend/src/ServerInsights.jsx b/src/frontend/src/ServerInsights.jsx
deleted file mode 100644
index 2fe9230..0000000
--- a/src/frontend/src/ServerInsights.jsx
+++ /dev/null
@@ -1,100 +0,0 @@
-// The extra views of one server: how its load is distributed, when it is busy, how its disks are filling up.
-import { useEffect, useMemo, useState } from 'react'
-import { TimeSeriesChart } from './charts.jsx'
-import { daysUntilFull, formatForecast, histogramBins, seriesFor } from './chartMath.js'
-import { ColumnChart, Heatmap } from './distributions.jsx'
-
-const LIVE_RANGES = new Set(['1h', '6h', '24h'])
-const REFRESH_SECONDS = 30
-
-// How much of the time a metric spent in each 10% band: weighted by the check-ins behind every point.
-function shareOfTime(series) {
- const bins = histogramBins(series.filter((point) => point.avg !== null).map((point) => ({ value: point.avg, weight: point.samples })))
- const total = bins.reduce((sum, bin) => sum + bin.count, 0)
- return bins.map((bin) => ({ label: `${bin.from}–${bin.to}`, values: { share: total ? Math.round((1000 * bin.count) / total) / 10 : 0 } }))
-}
-
-export function Distributions({ cpu, memory }) {
- const share = [{ key: 'share', label: 'Share of the time', color: '#7dd3fc' }]
- const memoryShare = [{ key: 'share', label: 'Share of the time', color: '#a78bfa' }]
- return (
- <div className="grid gap-4 xl:grid-cols-2">
- <ColumnChart title="CPU usage distribution" subtitle="Share of the time the average CPU was in each band (%)" categories={shareOfTime(cpu)} series={share} unit="%" empty="Not enough data for this range." />
- <ColumnChart title="Memory usage distribution" subtitle="Share of the time the memory in use was in each band (%)" categories={shareOfTime(memory)} series={memoryShare} unit="%" empty="Not enough data for this range." />
- </div>
- )
-}
-
-export function BusyHours({ request, serverId }) {
- const [data, setData] = useState(null)
- const [metric, setMetric] = useState('cpu')
- const [error, setError] = useState('')
- const offset = -new Date().getTimezoneOffset()
-
- useEffect(() => {
- const controller = new AbortController()
- request(`/stats/servers/${serverId}/heatmap?metric=${metric}&offset=${offset}`, { method: 'GET', signal: controller.signal })
- .then((result) => { setData(result); setError('') })
- .catch((requestError) => { if (requestError.name !== 'AbortError') setError(requestError.message || 'Could not load the busy hours.') })
- return () => controller.abort()
- }, [request, serverId, metric, offset])
-
- const current = data && data.server_id === serverId && data.metric === metric ? data : null
- return (
- <div className="space-y-2">
- <div className="flex items-center justify-between gap-3">
- <h2 className="text-xl font-semibold text-white">When it is busy</h2>
- <div role="group" aria-label="Metric" className="flex gap-1.5">
- {[['cpu', 'CPU'], ['ram', 'Memory']].map(([id, label]) => (
- <button key={id} type="button" aria-pressed={metric === id} onClick={() => setMetric(id)} className={`min-h-9 rounded-xl border px-3 text-sm ${metric === id ? 'border-white/30 bg-white/10 text-white' : 'border-white/10 text-[#9aa0a6] hover:text-white'}`}>{label}</button>
- ))}
- </div>
- </div>
- {error && <div role="alert" className="rounded-2xl border border-red-400/30 bg-red-500/10 px-4 py-3 text-sm text-red-200">{error}</div>}
- {current && <Heatmap title={`Average ${metric === 'cpu' ? 'CPU' : 'memory'} by hour of the day`} subtitle="The last 30 days, in your time zone, whatever range is selected above." grid={current.cells} color={metric === 'cpu' ? '#7dd3fc' : '#a78bfa'} empty="Not enough history yet. This fills in as days pass." />}
- </div>
- )
-}
-
-function MountChart({ request, serverId, mount, range }) {
- const [data, setData] = useState(null)
- const [error, setError] = useState('')
-
- useEffect(() => {
- const controller = new AbortController()
- const load = () => request(`/monitoring/servers/${serverId}/mounts/history?mount=${encodeURIComponent(mount.mount)}&range=${range}&metrics=used_pct,used_gb,total_gb`, { method: 'GET', signal: controller.signal })
- .then((result) => { setData(result); setError('') })
- .catch((requestError) => { if (requestError.name !== 'AbortError') setError(requestError.message || 'Could not load this filesystem.') })
- load()
- if (!LIVE_RANGES.has(range)) return () => controller.abort()
- const timer = setInterval(() => { if (!document.hidden) load() }, REFRESH_SECONDS * 1000)
- return () => { controller.abort(); clearInterval(timer) }
- }, [request, serverId, mount.mount, range])
-
- const current = data && data.mount === mount.mount ? data : null
- const series = useMemo(() => seriesFor(current?.points, 'used_pct'), [current])
- const forecast = useMemo(() => daysUntilFull(series.filter((point) => point.avg !== null).map((point) => ({ t: point.t, value: point.avg }))), [series])
- const common = { bucketSeconds: current?.bucket_seconds ?? 60, start: current ? new Date(current.start).getTime() : undefined, end: current ? new Date(current.end).getTime() : undefined, utc: current ? ['day', 'week', 'month'].includes(current.source) : false }
- return (
- <div className="min-w-0 space-y-2">
- {error && <div role="alert" className="rounded-2xl border border-red-400/30 bg-red-500/10 px-4 py-3 text-sm text-red-200">{error}</div>}
- <TimeSeriesChart {...common} title={`Disk usage · ${mount.mount}`} series={series} color="#f472b6" domain={[0, 100]} />
- <p className="px-1 text-xs text-[#9aa0a6]">
- {mount.used_gb != null && mount.total_gb != null ? `${mount.used_gb.toFixed(1)} of ${mount.total_gb.toFixed(1)} GB used now. ` : ''}
- {current ? formatForecast(forecast) : ''}
- </p>
- </div>
- )
-}
-
-export function Storage({ request, serverId, mounts, range }) {
- if (!mounts.length) return null
- return (
- <div className="space-y-3">
- <h2 className="text-xl font-semibold text-white">Storage</h2>
- <div className="grid gap-4 xl:grid-cols-2">
- {mounts.map((mount) => <MountChart key={mount.mount} request={request} serverId={serverId} mount={mount} range={range} />)}
- </div>
- </div>
- )
-}
diff --git a/src/frontend/src/StatisticsPage.jsx b/src/frontend/src/StatisticsPage.jsx
deleted file mode 100644
index 531c669..0000000
--- a/src/frontend/src/StatisticsPage.jsx
+++ /dev/null
@@ -1,211 +0,0 @@
-// The Statistics page: pick a server and a time range and see how it behaved, from the last hour to all time.
-// It only needs a way to call the API, so it has no import from App.jsx.
-import { useCallback, useEffect, useMemo, useState } from 'react'
-import { useSearchParams } from 'react-router-dom'
-import { TimeSeriesChart } from './charts.jsx'
-import ContainerStatistics from './ContainerStatistics.jsx'
-import FleetStatistics from './FleetStatistics.jsx'
-import { BusyHours, Distributions, Storage } from './ServerInsights.jsx'
-import { describeBucket, formatDateTime, seriesFor, summarise } from './chartMath.js'
-
-const RANGES = [
- { id: '1h', label: '1 hour' },
- { id: '6h', label: '6 hours' },
- { id: '24h', label: '24 hours' },
- { id: '7d', label: '7 days' },
- { id: '30d', label: '30 days' },
- { id: '90d', label: '90 days' },
- { id: '1y', label: '1 year' },
- { id: 'all', label: 'All time' },
-]
-const RANGE_IDS = new Set(RANGES.map((range) => range.id))
-const DEFAULT_RANGE = '24h'
-const RANGE_STORAGE_KEY = 'homelab.statisticsRange'
-// Only short ranges change from one minute to the next.
-const LIVE_RANGES = new Set(['1h', '6h', '24h'])
-const REFRESH_SECONDS = 30
-const METRICS = 'cpu,ram,swap,load,disk,docker_ms,collect_ms'
-const SOURCES = {
- detailed: 'check-ins grouped together',
- hour: 'hourly summaries',
- day: 'daily summaries',
- week: 'weekly summaries (Monday to Sunday, UTC)',
- month: 'monthly summaries (UTC)',
-}
-
-function rememberedRange() {
- try {
- const stored = window.localStorage.getItem(RANGE_STORAGE_KEY)
- return RANGE_IDS.has(stored) ? stored : DEFAULT_RANGE
- } catch {
- return DEFAULT_RANGE
- }
-}
-
-function SummaryCard({ label, value, detail }) {
- return (
- <div className="rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3">
- <div className="text-xs uppercase tracking-[0.18em] text-[#9aa0a6]">{label}</div>
- <div className="mt-1 text-2xl font-semibold text-white">{value}</div>
- {detail && <div className="text-xs text-[#7f8589]">{detail}</div>}
- </div>
- )
-}
-
-const percent = (value) => (value === null || value === undefined ? '–' : `${value.toFixed(1)}%`)
-
-export default function StatisticsContent({ request }) {
- const [searchParams, setSearchParams] = useSearchParams()
- const [servers, setServers] = useState(null)
- const [data, setData] = useState(null)
- const [error, setError] = useState('')
- const [loading, setLoading] = useState(false)
-
- const range = RANGE_IDS.has(searchParams.get('range')) ? searchParams.get('range') : rememberedRange()
- const requestedServer = Number(searchParams.get('server'))
- const wantsAll = searchParams.get('server') === 'all'
- const serverId = useMemo(() => {
- if (!servers?.length || wantsAll) return null
- return servers.find((server) => server.id === requestedServer)?.id ?? (servers.find((server) => server.is_dashboard_host) || servers[0]).id
- }, [servers, requestedServer, wantsAll])
-
- const choose = useCallback((changes) => {
- const next = new URLSearchParams(searchParams)
- for (const [key, value] of Object.entries(changes)) {
- if (value === '' || value === null) next.delete(key)
- else next.set(key, String(value))
- }
- setSearchParams(next, { replace: true })
- }, [searchParams, setSearchParams])
-
- useEffect(() => {
- let cancelled = false
- const load = () => request('/monitoring/overview', { method: 'GET' })
- .then((overview) => { if (!cancelled) setServers((overview.servers || []).map((server) => ({ ...server, is_dashboard_host: Boolean(server.is_dashboard_host), containers: server.containers || [] }))) })
- .catch((requestError) => { if (!cancelled) { setServers((current) => current || []); setError(requestError.message || 'Could not load the servers.') } })
- load()
- // The containers on the cards change, so keep them current, but not while the tab is hidden.
- const timer = setInterval(() => { if (!document.hidden) load() }, REFRESH_SECONDS * 1000)
- return () => { cancelled = true; clearInterval(timer) }
- }, [request])
-
- useEffect(() => {
- if (serverId === null) return undefined
- const controller = new AbortController()
- const load = (showSpinner) => {
- if (showSpinner) setLoading(true)
- request(`/monitoring/servers/${serverId}/history?range=${range}&metrics=${METRICS}`, { method: 'GET', signal: controller.signal })
- .then((result) => { setData(result); setError('') })
- .catch((requestError) => { if (requestError.name !== 'AbortError') setError(requestError.message || 'Could not load the statistics.') })
- .finally(() => { if (!controller.signal.aborted) setLoading(false) })
- }
- load(true)
- if (!LIVE_RANGES.has(range)) return () => controller.abort()
- // Refresh the short ranges, but not while the tab is hidden.
- const timer = setInterval(() => { if (!document.hidden) load(false) }, REFRESH_SECONDS * 1000)
- return () => { controller.abort(); clearInterval(timer) }
- }, [request, serverId, range])
-
- const series = useMemo(() => Object.fromEntries(['cpu', 'ram', 'swap', 'load', 'disk', 'docker_ms', 'collect_ms'].map((metric) => [metric, seriesFor(data?.points, metric)])), [data])
- const cpu = summarise(series.cpu)
- const memory = summarise(series.ram)
- const start = data ? new Date(data.start).getTime() : undefined
- const end = data ? new Date(data.end).getTime() : undefined
- const utc = data ? ['day', 'week', 'month'].includes(data.source) : false
- const common = { bucketSeconds: data?.bucket_seconds ?? 60, start, end, utc }
- const ready = data && data.server_id === serverId
-
- return (
- <div className="space-y-5">
- <div>
- <div className="text-xs uppercase tracking-[0.22em] text-[#9aa0a6]">History</div>
- <h1 className="mt-1 text-3xl font-semibold text-white">Statistics</h1>
- <p className="mt-2 text-sm text-[#9aa0a6]">How a server behaved over time, from the last hour to everything that has been recorded.</p>
- </div>
-
- <div className="flex flex-wrap items-end gap-4">
- <label className="flex flex-col gap-1 text-xs text-[#9aa0a6]">
- Server
- <select
- value={wantsAll ? 'all' : serverId ?? ''}
- onChange={(event) => choose({ server: event.target.value, container: '' })}
- disabled={!servers?.length}
- className="min-h-11 rounded-xl border border-white/10 bg-[#111417] px-3 py-2 text-sm text-white sm:min-h-0"
- >
- {servers?.length > 0 && <option value="all">All servers</option>}
- {(servers || []).map((server) => <option key={server.id} value={server.id}>{server.hostname}{server.is_dashboard_host ? ' (this machine)' : ''}</option>)}
- </select>
- </label>
- <div role="group" aria-label="Time range" className="flex flex-wrap gap-1.5">
- {RANGES.map((option) => (
- <button
- key={option.id}
- type="button"
- aria-pressed={range === option.id}
- onClick={() => {
- try { window.localStorage.setItem(RANGE_STORAGE_KEY, option.id) } catch { /* the choice just isn't remembered */ }
- choose({ range: option.id })
- }}
- className={`min-h-11 rounded-xl border px-3 text-sm transition sm:min-h-9 ${range === option.id ? 'border-white/30 bg-white/10 text-white' : 'border-white/10 text-[#9aa0a6] hover:text-white'}`}
- >
- {option.label}
- </button>
- ))}
- </div>
- </div>
-
- {error && <div role="alert" className="rounded-2xl border border-red-400/30 bg-red-500/10 px-4 py-3 text-sm text-red-200">{error}</div>}
- {servers !== null && servers.length === 0 && !error && <div className="rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-6 text-sm text-[#9aa0a6]">No servers are reporting yet. Add one from the dashboard and its history will appear here.</div>}
-
- {servers?.length > 0 && wantsAll && <FleetStatistics request={request} servers={servers} range={range} />}
-
- {ready && (
- <div className={loading ? 'space-y-5 opacity-60 transition-opacity' : 'space-y-5 transition-opacity'}>
- <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
- <SummaryCard label="Average CPU" value={percent(cpu.average)} />
- <SummaryCard label="Peak CPU" value={percent(cpu.maximum)} />
- <SummaryCard label="Average memory" value={percent(memory.average)} />
- <SummaryCard label="Peak memory" value={percent(memory.maximum)} />
- </div>
- <p className="text-xs text-[#7f8589]">
- {data.points.length
- ? `${data.points.length} ${data.points.length === 1 ? 'point' : 'points'}, one per ${describeBucket(data.bucket_seconds)} (${SOURCES[data.source] || data.source}). The line is the average and the lighter band reaches up to the highest value. `
- : 'Nothing has been recorded for this server in this range. '}
- {data.data_since && `History starts ${formatDateTime(new Date(data.data_since).getTime(), utc)}. `}
- {utc ? 'Dates are UTC.' : 'Times are in your time zone.'}
- </p>
- <div className="grid gap-4 xl:grid-cols-2">
- <TimeSeriesChart {...common} title="CPU usage" series={series.cpu} color="#7dd3fc" domain={[0, 100]} />
- <TimeSeriesChart {...common} title="Memory used" series={series.ram} color="#a78bfa" domain={[0, 100]} />
- <TimeSeriesChart {...common} title="Swap used" series={series.swap} color="#fbbf24" domain={[0, 100]} />
- <TimeSeriesChart {...common} title="Load (1 minute average)" series={series.load} color="#34d399" unit="" decimals={2} />
- <TimeSeriesChart {...common} title="Root disk used" series={series.disk} color="#f472b6" domain={[0, 100]} />
- </div>
- <Distributions cpu={series.cpu} memory={series.ram} />
- <BusyHours request={request} serverId={serverId} />
- <Storage request={request} serverId={serverId} mounts={servers.find((server) => server.id === serverId)?.mounts || []} range={range} />
- {(series.docker_ms.length > 0 || series.collect_ms.length > 0) && (
- <div className="space-y-3">
- <h2 className="text-xl font-semibold text-white">Reliability</h2>
- <div className="grid gap-4 xl:grid-cols-2">
- <TimeSeriesChart {...common} title="Docker response time (listing containers)" series={series.docker_ms} color="#fb923c" unit="ms" decimals={0} />
- <TimeSeriesChart {...common} title="Time the collector takes per check-in" series={series.collect_ms} color="#94a3b8" unit="ms" decimals={0} />
- </div>
- </div>
- )}
- </div>
- )}
- {servers?.length > 0 && serverId !== null && !wantsAll && (
- <ContainerStatistics
- request={request}
- serverId={serverId}
- containers={servers.find((server) => server.id === serverId)?.containers || []}
- range={range}
- selectedId={searchParams.get('container') || ''}
- onSelect={(containerId) => choose({ container: containerId })}
- />
- )}
- {servers === null && !error && <div className="text-sm text-[#7f8589]">Loading…</div>}
- </div>
- )
-}
diff --git a/src/frontend/src/account/AccountPage.jsx b/src/frontend/src/account/AccountPage.jsx
new file mode 100644
index 0000000..f65290b
--- /dev/null
+++ b/src/frontend/src/account/AccountPage.jsx
@@ -0,0 +1,387 @@
+// Your account: who you are, how you sign in, where alerts reach you and how Infradeck looks for you.
+import { useEffect, useRef, useState } from 'react'
+import { useNavigate } from 'react-router-dom'
+import { apiRequest } from '../api.js'
+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'
+
+const COLORS = ['', '#FF5A1F', '#E2B04A', '#6DBE8F', '#7FA7D9', '#B58BD6', '#D98BA4']
+const post = (path, body) => apiRequest(path, { method: 'POST', body: JSON.stringify(body || {}) })
+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 Avatar({ name, color, size = 44 }) {
+ return <span className="flex shrink-0 items-center justify-center rounded-md border border-line bg-raised font-semibold" style={{ width: size, height: size, fontSize: size * 0.34, color: color || 'var(--color-paper)', borderColor: color || undefined }}>{initials(name)}</span>
+}
+
+function Profile({ account, onSaved }) {
+ const [form, setForm] = useState({ name: account.name, username: account.username || '', avatar_color: account.avatar_color || '' })
+ const [state, run] = useAction()
+ const dirty = form.name !== account.name || form.username !== (account.username || '') || form.avatar_color !== (account.avatar_color || '')
+ const nextColor = () => setForm((current) => ({ ...current, avatar_color: COLORS[(COLORS.indexOf(current.avatar_color) + 1) % COLORS.length] }))
+ const save = (event) => { event.preventDefault(); run(async () => onSaved(await apiRequest('/account/profile', { method: 'PATCH', body: JSON.stringify(form) })), 'Saved.') }
+ return (
+ <form onSubmit={save} className="card px-[18px] py-[18px]">
+ <div className="flex flex-wrap items-center gap-3.5">
+ <Avatar name={form.name} color={form.avatar_color} />
+ <span className="min-w-0 flex-1"><span className="block truncate text-[15px] font-semibold text-paper">{form.name || account.name}</span><span className="block text-xs text-muted">{account.role_name} · member since {formatDate(account.created_at)}</span></span>
+ <button type="button" className="btn btn-sm" onClick={nextColor}>Change initials color</button>
+ </div>
+ <div className="mt-5 grid gap-x-5 gap-y-4 sm:grid-cols-2">
+ <Field label="Display name"><input className="field h-9" value={form.name} maxLength={255} required onChange={(event) => setForm({ ...form, name: event.target.value })} /></Field>
+ <Field label="Username" hint="Optional. Shown next to your name; you still sign in with your email."><input className="field mono h-9" value={form.username} maxLength={32} autoCapitalize="none" spellCheck={false} onChange={(event) => setForm({ ...form, username: event.target.value })} /></Field>
+ <Field label="Email" hint="Used for sign-in and, if email is set up on this server, alert emails."><input className="field h-9 text-soft" value={account.email} readOnly /></Field>
+ <Field label="Role" hint="Roles are changed in Admin › Users"><input className="field h-9 text-soft" value={account.role_name} readOnly /></Field>
+ </div>
+ <div className="mt-5 flex items-center justify-end gap-3">
+ <Outcome state={state} />
+ <button type="button" className="btn btn-ghost" disabled={!dirty} onClick={() => setForm({ name: account.name, username: account.username || '', avatar_color: account.avatar_color || '' })}>Discard</button>
+ <button type="submit" className="btn btn-primary" disabled={!dirty || state.busy}>{state.busy ? 'Saving…' : 'Save profile'}</button>
+ </div>
+ </form>
+ )
+}
+
+function RecoveryCodes({ codes, onDone, doneLabel = 'Done' }) {
+ const [saved, setSaved] = useState(false)
+ const [copied, copy] = useCopy()
+ return (
+ <div className="border-t border-line px-[18px] py-4">
+ <p className="m-0 text-[13px] font-medium text-paper">Save your recovery codes</p>
+ <p className="mb-0 mt-1 text-xs text-muted">Each works once if you lose your authenticator. They are shown only now; keep them somewhere safe, such as a password manager.</p>
+ <ul className="m-0 mt-3 grid list-none grid-cols-2 gap-1.5 p-0 sm:grid-cols-5">{codes.map((code) => <li key={code} className="mono rounded border border-line bg-bg px-2 py-1.5 text-center text-paper">{code}</li>)}</ul>
+ <div className="mt-3 flex flex-wrap items-center gap-3">
+ <button type="button" className="btn btn-sm" onClick={() => copy(codes.join('\n'))}><Icon name={copied ? 'check' : 'copy'} size={13} />{copied ? 'Copied' : 'Copy codes'}</button>
+ <label className="flex items-center gap-2 text-xs text-soft"><Check checked={saved} onChange={setSaved} />I have saved these codes</label>
+ <button type="button" className="btn btn-sm btn-primary" disabled={!saved} onClick={onDone}>{doneLabel}</button>
+ </div>
+ </div>
+ )
+}
+
+// Confirm a sensitive change with the password and a current code.
+function Reauth({ label, path, onDone, onCancel }) {
+ const [form, setForm] = useState({ password: '', code: '' })
+ const [state, run] = useAction()
+ return (
+ <form className="border-t border-line px-[18px] py-4" onSubmit={(event) => { event.preventDefault(); run(async () => onDone(await post(path, { password: form.password, code: form.code.trim() }))) }}>
+ <p className="m-0 text-xs text-muted">Confirm with your password and a current code from your authenticator (or a recovery code).</p>
+ <div className="mt-3 flex flex-wrap items-center gap-2.5">
+ <input type="password" className="field h-9 w-56" autoComplete="current-password" autoFocus placeholder="Password" aria-label="Password" required value={form.password} onChange={(event) => setForm({ ...form, password: event.target.value })} />
+ <input className="field mono h-9 w-40" autoComplete="one-time-code" placeholder="Code" aria-label="Code" maxLength={32} required value={form.code} onChange={(event) => setForm({ ...form, code: event.target.value })} />
+ <button type="submit" className="btn btn-primary" disabled={state.busy}>{label}</button>
+ <button type="button" className="btn btn-ghost" onClick={onCancel}>Cancel</button>
+ </div>
+ <div className="mt-2"><Outcome state={state} /></div>
+ </form>
+ )
+}
+
+function ChangePassword({ onDone }) {
+ const [form, setForm] = useState({ current: '', next: '', repeat: '' })
+ const [state, run] = useAction()
+ const [problem, setProblem] = useState('')
+ const set = (key) => (event) => setForm((current) => ({ ...current, [key]: event.target.value }))
+ const submit = (event) => {
+ event.preventDefault()
+ if (form.next.length < MIN_PASSWORD_LENGTH) return setProblem(`The new password must be at least ${MIN_PASSWORD_LENGTH} characters.`)
+ if (form.next !== form.repeat) return setProblem('The two new passwords do not match.')
+ setProblem('')
+ return run(async () => { const data = await post('/auth/password', { current_password: form.current, new_password: form.next }); onDone(`Password changed. ${data.other_sessions_signed_out} other ${data.other_sessions_signed_out === 1 ? 'session was' : 'sessions were'} signed out.`) })
+ }
+ return (
+ <form onSubmit={submit} className="border-t border-line px-[18px] py-4">
+ <div className="grid max-w-[720px] gap-2.5 sm:grid-cols-3">
+ <input type="password" className="field h-9" autoComplete="current-password" autoFocus placeholder="Current password" aria-label="Current password" required value={form.current} onChange={set('current')} />
+ <input type="password" className="field h-9" autoComplete="new-password" placeholder={`New password (${MIN_PASSWORD_LENGTH}+ characters)`} aria-label="New password" required value={form.next} onChange={set('next')} />
+ <input type="password" className="field h-9" autoComplete="new-password" placeholder="Repeat the new password" aria-label="Repeat the new password" required value={form.repeat} onChange={set('repeat')} />
+ </div>
+ <div className="mt-3 flex flex-wrap items-center gap-3"><button type="submit" className="btn btn-primary" disabled={state.busy}>{state.busy ? 'Changing…' : 'Change password'}</button><span className="text-xs text-muted">A few random words make a good passphrase. Changing it signs you out everywhere else.</span></div>
+ <div className="mt-2">{problem ? <p role="alert" className="m-0 text-xs text-warn">{problem}</p> : <Outcome state={state} />}</div>
+ </form>
+ )
+}
+
+// Turning two-factor on: ask for the password (unless this is the forced first set-up), show the key, confirm a code.
+function TwoFactorSetup({ forced, onEnabled, onCancel }) {
+ const [setup, setSetup] = useState(null)
+ const [password, setPassword] = useState('')
+ const [code, setCode] = useState('')
+ const [state, run] = useAction()
+ const begin = () => run(async () => setSetup(await post('/auth/2fa/setup', forced ? {} : { password })))
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ useEffect(() => { if (forced) begin() }, [])
+ return (
+ <div className="border-t border-line px-[18px] py-4">
+ {!setup && !forced && (
+ <form className="flex flex-wrap items-center gap-2.5" onSubmit={(event) => { event.preventDefault(); begin() }}>
+ <input type="password" className="field h-9 w-64" autoComplete="current-password" autoFocus placeholder="Your current password" aria-label="Your current password" required value={password} onChange={(event) => setPassword(event.target.value)} />
+ <button type="submit" className="btn btn-primary" disabled={state.busy}>Continue</button>
+ {onCancel && <button type="button" className="btn btn-ghost" onClick={onCancel}>Cancel</button>}
+ </form>
+ )}
+ {setup && (
+ <ol className="m-0 max-w-[640px] space-y-4 pl-5 text-[13px] text-soft">
+ <li>In your authenticator app (Aegis, Authy, Google Authenticator), add an account and enter this key (time-based, 6 digits):
+ <div className="mono mt-2 select-all break-all rounded-md border border-line bg-bg px-3 py-2 text-sm tracking-wider text-paper">{setup.secret.match(/.{1,4}/g).join(' ')}</div>
+ <a href={setup.otpauth_uri} className="link mt-1.5 inline-block text-xs">or open it in an authenticator app on this device</a>
+ </li>
+ <li>Enter the code the app shows now:
+ <form className="mt-2 flex flex-wrap items-center gap-2.5" onSubmit={(event) => { event.preventDefault(); run(async () => onEnabled((await post('/auth/2fa/enable', { code: code.trim() })).recovery_codes)) }}>
+ <input className="field mono h-9 w-36 tracking-widest" inputMode="numeric" autoComplete="one-time-code" maxLength={8} placeholder="123456" aria-label="Code from the authenticator app" required value={code} onChange={(event) => setCode(event.target.value)} />
+ <button type="submit" className="btn btn-primary" disabled={state.busy}>Turn on</button>
+ </form>
+ </li>
+ </ol>
+ )}
+ <div className="mt-2"><Outcome state={state} /></div>
+ </div>
+ )
+}
+
+function Security({ account, reload, forced = false, onEnrolled }) {
+ const [open, setOpen] = useState(forced ? 'setup' : null)
+ const [codes, setCodes] = useState(null)
+ const [message, setMessage] = useState('')
+ const two = account.two_factor
+ const days = account.password_changed_at ? Math.floor((Date.now() - new Date(account.password_changed_at).getTime()) / 86400000) : null
+ const toggle = (name) => { setMessage(''); setOpen((current) => (current === name ? null : name)) }
+ const done = (text) => { setOpen(null); setMessage(text || ''); reload() }
+ return (
+ <div className="card divide-y divide-line overflow-hidden">
+ {!forced && <div>
+ <Row icon="***" title="Password" detail={days == null ? 'Never changed since the account was created' : days === 0 ? 'Changed today' : `Last changed ${days} ${days === 1 ? 'day' : 'days'} ago`}><button type="button" className="btn btn-sm" aria-expanded={open === 'password'} onClick={() => toggle('password')}>Change password</button></Row>
+ {open === 'password' && <ChangePassword onDone={done} />}
+ </div>}
+ <div>
+ <Row icon="2FA" title="Two-factor authentication" detail={!two.available ? 'Not possible on this server yet: it has no SECRETS_KEY (see docs/accounts.md)' : two.enabled ? 'Authenticator app · asked for at every new sign-in' : two.required ? 'Required for your account. Set it up to continue.' : 'A 6-digit code from an authenticator app, asked for after your password'} tone={!two.enabled && two.required ? 'warn' : undefined}>
+ <span className={`chip ${two.enabled ? 'chip-ok' : ''}`}>{two.enabled ? 'On' : 'Off'}</span>
+ {two.available && !forced && <button type="button" className="btn btn-sm" aria-expanded={open === 'setup' || open === 'off'} onClick={() => toggle(two.enabled ? 'off' : 'setup')}>{two.enabled ? 'Manage' : 'Set up'}</button>}
+ </Row>
+ {open === 'setup' && !two.enabled && !codes && <TwoFactorSetup forced={forced} onCancel={forced ? null : () => setOpen(null)} onEnabled={(list) => { setCodes(list); reload() }} />}
+ {open === 'off' && two.enabled && (two.required
+ ? <p className="m-0 border-t border-line px-[18px] py-4 text-xs text-muted">Two-factor is required for your account, so it can't be turned off. An admin sets that in Admin › Users.</p>
+ : <Reauth label="Turn off two-factor" path="/auth/2fa/disable" onCancel={() => setOpen(null)} onDone={() => done('Two-factor is off. Your other sessions were signed out.')} />)}
+ {codes && <RecoveryCodes codes={codes} doneLabel={onEnrolled ? 'Continue' : 'Done'} onDone={() => { setCodes(null); setOpen(null); if (onEnrolled) onEnrolled() }} />}
+ </div>
+ {two.enabled && !forced && <div>
+ <Row icon="#" title="Recovery codes" detail={`${two.recovery_codes_left} left. Stored only as hashes, so they can't be shown again, only replaced.`} tone={two.recovery_codes_left <= 2 ? 'warn' : undefined}><button type="button" className="btn btn-sm" aria-expanded={open === 'codes'} onClick={() => toggle('codes')}>Regenerate</button></Row>
+ {open === 'codes' && !codes && <Reauth label="Generate new codes" path="/auth/2fa/recovery-codes" onCancel={() => setOpen(null)} onDone={(data) => { setCodes(data.recovery_codes); reload() }} />}
+ </div>}
+ {!forced && <Row icon="key" title="Passkeys" detail="Sign in with a fingerprint or security key instead of a password. Not available yet."><button type="button" className="btn btn-sm" disabled title="Passkeys are not built yet"><Icon name="plus" size={13} />Add passkey</button></Row>}
+ {message && <p role="status" className="m-0 px-[18px] py-3 text-xs text-ok">{message}</p>}
+ </div>
+ )
+}
+
+function Sessions({ days, onCount }) {
+ const { data, error, reload } = useLoaded('/auth/sessions')
+ const [state, run] = useAction()
+ const sessions = data?.sessions
+ useEffect(() => { if (sessions) onCount(sessions.length) }, [sessions, onCount])
+ 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]">
+ <thead><tr className="grid-head h-10"><th className="pl-[18px] font-medium">Device</th><th className="font-medium">Address</th><th className="font-medium">Signed in</th><th className="pr-[18px]" /></tr></thead>
+ <tbody>
+ {(sessions || []).map((session) => (
+ <tr key={session.id} className="h-[46px] border-t border-line">
+ <td className="pl-[18px] font-medium text-paper">{describeBrowser(session.user_agent)}{session.current && <span className="chip chip-ok ml-2.5 font-normal">this session</span>}</td>
+ <td className="mono text-soft">{session.ip || 'unknown'}</td>
+ <td className="text-soft">{session.created_at ? ago(session.created_at) : 'earlier'}</td>
+ <td className="pr-[18px] text-right">{!session.current && <button type="button" className="link" disabled={state.busy} onClick={() => run(async () => { await apiRequest(`/auth/sessions/${session.id}`, { method: 'DELETE' }); reload() })}>Sign out</button>}</td>
+ </tr>
+ ))}
+ {!sessions && <tr className="border-t border-line"><td colSpan={4} className="px-[18px] py-5 text-center text-xs text-muted">{error || 'Loading…'}</td></tr>}
+ </tbody>
+ </table></div>
+ <div className="flex flex-wrap items-center justify-between gap-3 border-t border-line px-[18px] py-3 text-xs text-muted">
+ <span>A session lasts a day, or {days} days if you ticked “Keep me signed in”. <Outcome state={state} /></span>
+ {sessions?.length > 1 && <button type="button" className="btn btn-sm" disabled={state.busy} onClick={() => run(async () => { const result = await post('/auth/sessions/revoke-others'); reload(); return result }, 'Signed out everywhere else.')}>Sign out all other sessions</button>}
+ </div>
+ </div>
+ )
+}
+
+function Tokens({ account, reload }) {
+ const [adding, setAdding] = useState(false)
+ const [form, setForm] = useState({ name: '', scope: 'read', expires_in_days: '' })
+ const [created, setCreated] = useState(null)
+ const [state, run] = useAction()
+ 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'}` }
+ 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]">
+ <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">
+ <td className="pl-[18px]"><span className="block font-medium text-paper">{token.name}</span><span className="mono block text-[11px] text-dim">idk_{token.scope === 'write' ? 'w' : 'r'}_••••••••{token.hint}</span></td>
+ <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>
+ </tr>
+ ))}</tbody>
+ </table></div>}
+ {created && <div className="border-t border-line px-[18px] py-3.5 first:border-t-0"><ShownOnce value={created.token}>Copy “{created.name}” now. It is shown only once. Send it as <span className="mono">Authorization: Bearer …</span></ShownOnce></div>}
+ {adding && (
+ <form onSubmit={create} className="flex flex-wrap items-end gap-3 border-t border-line px-[18px] py-3.5 first:border-t-0">
+ <Field label="Name"><input className="field h-9 w-52" autoFocus required maxLength={64} placeholder="home-assistant" value={form.name} onChange={(event) => setForm({ ...form, name: event.target.value })} /></Field>
+ <Field label="Scope"><select className="select h-9" value={form.scope} onChange={(event) => setForm({ ...form, scope: event.target.value })}><option value="read">read · metrics</option><option value="write" disabled={!canWrite}>read + acknowledge{canWrite ? '' : ' (admins only)'}</option></select></Field>
+ <Field label="Expires"><select className="select h-9" value={form.expires_in_days} onChange={(event) => setForm({ ...form, expires_in_days: event.target.value })}><option value="">never</option><option value="30">in 30 days</option><option value="90">in 90 days</option><option value="365">in a year</option></select></Field>
+ <button type="submit" className="btn btn-primary h-9" disabled={state.busy}>Create token</button>
+ <button type="button" className="btn btn-ghost h-9" onClick={() => setAdding(false)}>Cancel</button>
+ </form>
+ )}
+ <div className="flex flex-wrap items-center justify-between gap-3 border-t border-line px-[18px] py-3 text-xs text-muted first:border-t-0">
+ <span>{account.tokens.length ? 'A token is shown once, when it\'s created.' : 'No tokens yet. A token is shown once, when it\'s created.'} A read token can only read; no token can change your account or the servers. <Outcome state={state} /></span>
+ {!adding && <button type="button" className="btn btn-sm" onClick={() => { setCreated(null); setAdding(true) }}><Icon name="plus" size={13} />New token</button>}
+ </div>
+ </div>
+ )
+}
+
+const CHANNELS = { email: ['@', 'Email'], ntfy: ['ntfy', 'ntfy'], discord: ['#', 'Discord webhook'], webhook: ['{ }', 'Webhook'] }
+const EVENTS = [['critical', 'Critical incidents', 'dot-signal'], ['warning', 'Warnings', 'dot-warn'], ['resolved', 'Resolved', 'dot-ok']]
+const DEFAULT_ROUTING = { critical: true, warning: true, resolved: false }
+
+function Notifications({ account, reload, onPreferences }) {
+ const [adding, setAdding] = useState(false)
+ const [form, setForm] = useState({ kind: 'ntfy', target: '' })
+ const [state, run] = useAction()
+ const prefs = account.preferences
+ const routed = (event, channel) => prefs.routing?.[event]?.[String(channel.id)] ?? DEFAULT_ROUTING[event]
+ const save = (changes, done) => run(async () => onPreferences(await apiRequest('/account/preferences', { method: 'PUT', body: JSON.stringify(changes) })), done)
+ const route = (event, channel, on) => {
+ const routing = Object.fromEntries(EVENTS.map(([key]) => [key, Object.fromEntries(account.channels.map((item) => [String(item.id), routed(key, item)]))]))
+ routing[event][String(channel.id)] = on
+ save({ routing })
+ }
+ 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
+ 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">
+ {account.channels.map((channel) => { const [text, tone] = status(channel); return (
+ <Row key={channel.id} icon={CHANNELS[channel.kind][0]} title={CHANNELS[channel.kind][1]} detail={<span className={channel.kind === 'email' ? '' : 'mono'}>{channel.display}</span>}>
+ <span className={`chip ${tone}`}>{text}</span>
+ <button type="button" className="btn btn-sm btn-ghost" disabled={state.busy} onClick={() => run(async () => { await post(`/account/channels/${channel.id}/test`); reload() })}>Send test</button>
+ <button type="button" className="link text-xs" onClick={() => { if (window.confirm(`Remove this ${CHANNELS[channel.kind][1]} channel?`)) run(async () => { await apiRequest(`/account/channels/${channel.id}`, { method: 'DELETE' }); reload() }) }}>Remove</button>
+ </Row>
+ ) })}
+ {adding && (
+ <form onSubmit={add} className="flex flex-wrap items-end gap-3 px-[18px] py-3.5">
+ <Field label="Kind"><select className="select h-9" value={form.kind} onChange={(event) => setForm({ ...form, kind: event.target.value })}><option value="ntfy">ntfy</option><option value="discord">Discord webhook</option><option value="webhook">Any webhook (Slack, Gotify, Telegram bridge…)</option><option value="email" disabled={!account.smtp_configured}>Email{account.smtp_configured ? '' : ' (not set up on this server)'}</option></select></Field>
+ {form.kind === 'email' ? <span className="pb-2 text-xs text-muted">Alerts go to {account.email}.</span>
+ : <Field label="Address" className="min-w-0 flex-1 basis-72"><input className="field mono h-9" autoFocus required maxLength={500} placeholder={form.kind === 'ntfy' ? 'https://ntfy.sh/your-topic' : 'https://…'} value={form.target} onChange={(event) => setForm({ ...form, target: event.target.value })} /></Field>}
+ <button type="submit" className="btn btn-primary h-9" disabled={state.busy || !account.secrets_configured}>Add</button>
+ <button type="button" className="btn btn-ghost h-9" onClick={() => setAdding(false)}>Cancel</button>
+ </form>
+ )}
+ <div className="flex flex-wrap items-center justify-between gap-3 px-[18px] py-3 text-xs text-muted">
+ <span>{account.channels.length ? 'ntfy, Discord, or any webhook (Slack, Gotify, a Telegram bridge).' : 'No channels yet, so alerts only show up here. Add ntfy, Discord or any webhook.'} The address is stored encrypted and never shown in full again. <Outcome state={state} /></span>
+ {!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 && (
+ <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>
+ {EVENTS.map(([key, label, dot]) => (
+ <tr key={key} className="h-11 border-t border-line">
+ <td className="pl-[18px] text-paper"><span className={`dot ${dot} mr-2.5`} style={{ width: 6, height: 6 }} />{label}</td>
+ {account.channels.map((channel) => <td key={channel.id} className="px-2 text-center"><Check checked={routed(key, channel)} label={`${label} to ${CHANNELS[channel.kind][1]}`} onChange={(on) => route(key, channel, on)} /></td>)}
+ </tr>
+ ))}
+ {['Agent diagnosis ready', 'Daily digest', 'Weekly report (Monday)'].map((label) => (
+ <tr key={label} className="h-11 border-t border-line text-dim"><td className="pl-[18px]"><span className="dot mr-2.5" style={{ width: 6, height: 6 }} />{label} <span className="ml-1.5 text-[11px]">not available yet</span></td>{account.channels.map((channel) => <td key={channel.id} className="px-2 text-center"><Check checked={false} disabled onChange={() => {}} label={`${label} (not available yet)`} /></td>)}</tr>
+ ))}
+ </tbody>
+ </table></div></div>
+ )}
+ <div className="card">
+ <Row title="Quiet hours" detail={`Warnings wait until the end of quiet hours. Critical still comes through. Times are in ${zone}.`}>
+ <input type="time" className="field h-8 w-[104px]" aria-label="Quiet hours start" value={prefs.quiet.start} onChange={(event) => save({ quiet: { ...prefs.quiet, start: event.target.value } })} />
+ <span className="text-xs text-muted">to</span>
+ <input type="time" className="field h-8 w-[104px]" aria-label="Quiet hours end" value={prefs.quiet.end} onChange={(event) => save({ quiet: { ...prefs.quiet, end: event.target.value } })} />
+ <Switch checked={prefs.quiet.enabled} label="Quiet hours" onChange={(enabled) => save({ quiet: { ...prefs.quiet, enabled } })} />
+ </Row>
+ </div>
+ </>
+}
+
+function Choice({ value, options, onChange, label }) {
+ return <div className="seg" role="group" aria-label={label}>{options.map(([key, text]) => <button key={key} type="button" aria-pressed={value === key} onClick={() => onChange(key)}>{text}</button>)}</div>
+}
+
+function Display({ account, onPreferences }) {
+ const [state, run] = useAction()
+ const display = account.preferences.display
+ const set = (key, value) => run(async () => { const saved = await apiRequest('/account/preferences', { method: 'PUT', body: JSON.stringify({ display: { [key]: value } }) }); applyDisplay(saved.display); onPreferences(saved) })
+ const zones = typeof Intl.supportedValuesOf === 'function' ? Intl.supportedValuesOf('timeZone') : []
+ const browserZone = Intl.DateTimeFormat().resolvedOptions().timeZone
+ return (
+ <div className="card divide-y divide-line">
+ <Row title="Theme" detail="Dark is what Infradeck was designed in."><Choice label="Theme" value={display.theme} options={[['dark', 'Dark'], ['light', 'Light'], ['system', 'System']]} onChange={(value) => set('theme', value)} /></Row>
+ <Row title="Density" detail="Compact fits more rows on a screen."><Choice label="Density" value={display.density} options={[['comfortable', 'Comfortable'], ['compact', 'Compact']]} onChange={(value) => set('density', value)} /></Row>
+ <Row title="Open on" detail="The page you land on after signing in."><select className="select" aria-label="Open on" value={display.open_on} onChange={(event) => set('open_on', event.target.value)}><option value="overview">Overview</option><option value="statistics">Statistics</option><option value="agent">Agent</option></select></Row>
+ <Row title="Time zone" detail={`Used for your quiet hours. Charts and incident times follow this browser (${browserZone}).`}><select className="select max-w-[240px]" aria-label="Time zone" value={display.timezone} onChange={(event) => set('timezone', event.target.value)}><option value="">This browser ({browserZone})</option>{zones.map((zone) => <option key={zone} value={zone}>{zone}</option>)}</select></Row>
+ <Row title="Time format" detail="Saved with your account. Times are shown in 24 h everywhere for now."><Choice label="Time format" value={display.time_format} options={[['24h', '24 h'], ['12h', '12 h']]} onChange={(value) => set('time_format', value)} /></Row>
+ <Row title="Sizes" detail="Saved with your account. Sizes are shown as 1 GB = 1024 MB everywhere for now."><Choice label="Sizes" value={display.sizes} options={[['GB', 'GB'], ['GiB', 'GiB']]} onChange={(value) => set('sizes', value)} /></Row>
+ {(state.error || state.ok) && <div className="px-[18px] py-2.5"><Outcome state={state} /></div>}
+ </div>
+ )
+}
+
+export default function AccountPage({ user, onLogout, onUserChange }) {
+ const navigate = useNavigate()
+ const status = useLoaded('/auth/2fa/status')
+ // Remember that this visit began as a required set-up, so Continue leads on to the dashboard once it is done.
+ const wasRequired = useRef(false)
+ const forced = Boolean(status.data?.setup_required)
+ if (forced) wasRequired.current = true
+ const { data: account, error, reload, setData } = useLoaded(status.data && !forced ? '/account' : null)
+ const [sessionCount, setSessionCount] = useState(null)
+ useEffect(() => { if (status.data) onUserChange({ setup_required: status.data.setup_required, two_factor_enabled: status.data.enabled }) }, [status.data]) // eslint-disable-line react-hooks/exhaustive-deps
+ useEffect(() => { if (account) { applyDisplay(account.preferences.display); onUserChange({ name: account.name }) } }, [account]) // eslint-disable-line react-hooks/exhaustive-deps
+ const refresh = () => { status.reload(); reload() }
+ const setPreferences = (preferences) => setData({ ...account, preferences })
+
+ if (forced) {
+ const two = { enabled: status.data.enabled, available: status.data.available, required: true, recovery_codes_left: status.data.recovery_codes_left }
+ return (
+ <AppShell user={user} onLogout={onLogout} bare>
+ <div className="mx-auto max-w-[760px] space-y-4 px-3 pt-7 sm:px-4 lg:px-7">
+ <h1 className="m-0 text-[21px] font-semibold text-paper">Set up two-factor to continue</h1>
+ <p className="m-0 text-[13px] text-soft">Infradeck can see inside every server you connect, so your account needs a second step at sign-in before you can use it.</p>
+ <Security account={{ two_factor: two }} reload={status.reload} forced onEnrolled={() => { status.reload(); navigate('/') }} />
+ </div>
+ </AppShell>
+ )
+ }
+
+ 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}
+ 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>}
+ {account && <>
+ <Section id="profile" title="Profile" description="Shown in the sidebar and on incidents you acknowledge."><Profile key={`${account.name}-${account.username}-${account.avatar_color}`} account={account} onSaved={setData} /></Section>
+ <Section id="security" title="Security" description="Infradeck can see inside every server you connect. Protect it like an SSH key."><Security account={account} reload={refresh} onEnrolled={wasRequired.current ? () => navigate('/') : null} /></Section>
+ <Section id="sessions" title="Sessions" description="Every browser and device signed in as you. Sign out anything you don't recognize."><Sessions days={account.session_days} onCount={setSessionCount} /></Section>
+ <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.jsx
new file mode 100644
index 0000000..b6c591d
--- /dev/null
+++ b/src/frontend/src/admin/AdminPage.jsx
@@ -0,0 +1,295 @@
+// 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 { 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'
+
+const REPOSITORY = 'https://github.com/karloks2005/Infradeck'
+const STATE_DOT = { critical: 'dot-signal', warn: 'dot-warn', ok: 'dot-ok', offline: '' }
+const SEVERITY = { CRITICAL: ['Critical', 'chip-signal'], WARNING: ['Warning', 'chip-warn'], INFO: ['Info', ''] }
+const THRESHOLD_LABELS = {
+ restart_loop_count: 'Restarts', restart_loop_window_minutes: 'Within (min)', disk_warning_pct: 'Warning from %', disk_critical_pct: 'Critical from %', inodes_warning_pct: 'Warning from %', inodes_critical_pct: 'Critical from %',
+ memory_warning_pct: 'Warning from %', memory_critical_pct: 'Critical from %', swap_warning_pct: 'Warning from %', load_warning_per_core: 'Warning × cores', load_critical_per_core: 'Critical × cores', event_window_minutes: 'Stays open (min)',
+}
+const put = (body) => apiRequest('/admin/settings', { method: 'PUT', body: JSON.stringify(body) })
+const post = (path, body) => apiRequest(path, { method: 'POST', body: JSON.stringify(body || {}) })
+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 Servers({ overview }) {
+ const [editing, setEditing] = useState(null)
+ const [menu, setMenu] = useState(null)
+ const [state, run] = useAction()
+ const servers = overview.servers
+ const save = (server, body) => run(async () => { await apiRequest(`/monitoring/servers/${server.id}`, { method: 'PATCH', body: JSON.stringify(body) }); await refreshOverview() })
+ const remove = (server) => {
+ setMenu(null)
+ if (!window.confirm(`Remove ${server.hostname} and all its stored metrics and incidents? This cannot be undone.`)) return
+ run(async () => { await apiRequest(`/monitoring/servers/${server.id}`, { method: 'DELETE' }); await refreshOverview() })
+ }
+ return (
+ <div className="card overflow-hidden">
+ <div className="custom-scroll overflow-x-auto"><table className="w-full min-w-[820px] border-collapse text-left text-[13px]">
+ <thead><tr className="grid-head h-10"><th className="pl-[18px] font-medium">Server</th><th className="font-medium">Address</th><th className="font-medium">Collector</th><th className="font-medium">Check every</th><th className="font-medium">Last check-in</th><th className="font-medium">System helper</th><th className="pr-[18px]" /></tr></thead>
+ <tbody>
+ {servers.map((server) => {
+ const version = server.system?.collector_version
+ const outdated = !version || version !== overview.version
+ return (
+ <tr key={server.id} className="h-[50px] border-t border-line">
+ <td className="pl-[18px]">
+ {editing?.id === server.id
+ ? <form className="flex items-center gap-2" onSubmit={(event) => { event.preventDefault(); save(server, { hostname: editing.name }).then(() => setEditing(null)) }}>
+ <input className="field h-8 w-44" autoFocus maxLength={253} aria-label={`New name for ${server.hostname}`} value={editing.name} onChange={(event) => setEditing({ id: server.id, name: event.target.value })} />
+ <button type="submit" className="btn btn-sm btn-primary" disabled={state.busy}>Save</button>
+ </form>
+ : <span className="flex items-center gap-2.5"><span className={`dot ${STATE_DOT[serverState(server)]}`} /><span className="text-sm font-semibold text-paper">{server.hostname}</span>{server.is_dashboard_host && <span className="chip">this machine</span>}</span>}
+ </td>
+ <td className="mono text-soft">{server.ip_address || '—'}</td>
+ <td className="mono text-paper">{version || 'older'}{outdated && <span className="ml-2 font-sans text-xs text-warn">update</span>}</td>
+ <td><select className="select h-8" aria-label={`Check interval of ${server.hostname}`} value={server.check_interval_seconds} onChange={(event) => save(server, { check_interval_seconds: 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></td>
+ <td className="text-soft">{ago(server.last_seen_at)}</td>
+ <td><span className={`chip ${server.system?.helper_installed ? 'chip-ok' : ''}`}>{server.system?.helper_installed ? 'installed' : 'not installed'}</span></td>
+ <td className="relative whitespace-nowrap pr-[18px] text-right">
+ <button type="button" className="link" onClick={() => setEditing(editing?.id === server.id ? null : { id: server.id, name: server.hostname })}>{editing?.id === server.id ? 'Cancel' : 'Edit'}</button>
+ <button type="button" className="ml-3 rounded border-0 bg-transparent px-1.5 text-base leading-none text-muted hover:text-paper" aria-label={`More for ${server.hostname}`} aria-expanded={menu === server.id} onClick={() => setMenu(menu === server.id ? null : server.id)}>⋯</button>
+ {menu === server.id && <div role="menu" className="absolute right-[18px] top-10 z-10 rounded-md border border-edge bg-bg p-1 text-left"><button type="button" role="menuitem" className="block rounded border-0 bg-transparent px-3 py-1.5 text-xs text-signal hover:bg-raised" onClick={() => remove(server)}>Remove this server…</button></div>}
+ </td>
+ </tr>
+ )
+ })}
+ {!servers.length && <tr className="border-t border-line"><td colSpan={7} className="px-[18px] py-6 text-center text-xs text-muted">No servers yet. Connect one below.</td></tr>}
+ </tbody>
+ </table></div>
+ <p className="m-0 border-t border-line px-[18px] py-3 text-xs text-muted">The system helper lets the collector read shutdown history, OOM process names and kernel errors. See SECURITY.md before installing. <Outcome state={state} /></p>
+ </div>
+ )
+}
+
+function Users({ me }) {
+ const { data, error, setData, reload } = useLoaded('/admin/users')
+ const [state, run] = useAction()
+ const [inviting, setInviting] = useState(false)
+ const [form, setForm] = useState({ email: '', role: 'user' })
+ const [link, setLink] = useState(null)
+ if (!data) return <Notice tone="plain">{error || 'Loading users…'}</Notice>
+ const change = (user, body) => run(async () => setData(await apiRequest(`/admin/users/${user.id}`, { method: 'PATCH', body: JSON.stringify(body) })))
+ const invite = (event) => { event.preventDefault(); run(async () => { const created = await post('/admin/invites', form); setLink({ email: created.email, url: `${window.location.origin}/register?invite=${created.token}` }); setInviting(false); setForm({ email: '', role: 'user' }); reload() }) }
+ const setting = (body) => run(async () => { await put(body); reload() })
+ return (
+ <div className="card overflow-hidden">
+ <div className="custom-scroll overflow-x-auto"><table className="w-full min-w-[680px] border-collapse text-left text-[13px]">
+ <thead><tr className="grid-head h-10"><th className="pl-[18px] font-medium">User</th><th className="font-medium">Role</th><th className="font-medium">Two-factor</th><th className="font-medium">Last seen</th><th className="pr-[18px]" /></tr></thead>
+ <tbody>
+ {data.users.map((user) => {
+ const fixed = user.role_name === 'Owner' || user.id === me.id
+ return (
+ <tr key={user.id} className={`h-[54px] border-t border-line ${user.is_active ? '' : 'opacity-60'}`}>
+ <td className="pl-[18px]"><span className="flex items-center gap-3"><span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-line bg-raised text-[11px] font-semibold" style={{ color: user.avatar_color || undefined }}>{initials(user.name)}</span><span className="min-w-0"><span className="block truncate font-medium text-paper">{user.name}{user.id === me.id && <span className="ml-2 text-xs font-normal text-muted">you</span>}</span><span className="block truncate text-xs text-muted">{user.email}</span></span></span></td>
+ <td>{fixed ? <span className="text-paper">{user.role_name}</span> : <select className="select h-8" aria-label={`Role of ${user.name}`} value={user.role} onChange={(event) => change(user, { role: event.target.value })}><option value="admin">Admin</option><option value="user">Viewer</option></select>}</td>
+ <td><span className={`chip ${user.two_factor ? 'chip-ok' : ''}`}>{user.two_factor ? 'On' : 'Off'}</span></td>
+ <td className="text-soft">{!user.is_active ? 'disabled' : user.sessions > 0 && user.id === me.id ? 'now' : ago(user.last_seen_at)}</td>
+ <td className="whitespace-nowrap pr-[18px] text-right">{!fixed && <>
+ {user.sessions > 0 && <button type="button" className="link" onClick={() => run(async () => { await post(`/admin/users/${user.id}/sign-out`); reload() })}>Sign out</button>}
+ <button type="button" className="link ml-3" onClick={() => change(user, { is_active: !user.is_active })}>{user.is_active ? 'Disable' : 'Enable'}</button>
+ </>}</td>
+ </tr>
+ )
+ })}
+ {data.invites.map((invite) => (
+ <tr key={`invite-${invite.id}`} className="h-[54px] border-t border-line">
+ <td className="pl-[18px]"><span className="flex items-center gap-3"><span className="flex h-7 w-7 items-center justify-center rounded-md border border-dashed border-edge text-[11px] text-muted">?</span><span><span className="block font-medium text-paper">Invite pending</span><span className="block text-xs text-muted">{invite.email} · made {ago(invite.created_at)}</span></span></span></td>
+ <td className="text-soft">{invite.role === 'admin' ? 'Admin' : 'Viewer'}</td><td className="text-muted">n/a</td><td className="text-muted">never</td>
+ <td className="pr-[18px] text-right"><button type="button" className="link" onClick={() => run(async () => setData(await apiRequest(`/admin/invites/${invite.id}`, { method: 'DELETE' })))}>Cancel</button></td>
+ </tr>
+ ))}
+ </tbody>
+ </table></div>
+ {link && <div className="border-t border-line px-[18px] py-3.5"><ShownOnce value={link.url}>Send this link to {link.email}. Infradeck sends no email itself. It works once, only for that address, and expires in 7 days.</ShownOnce></div>}
+ {inviting && (
+ <form onSubmit={invite} className="flex flex-wrap items-end gap-3 border-t border-line px-[18px] py-3.5">
+ <Field label="Email"><input type="email" className="field h-9 w-64" autoFocus required value={form.email} onChange={(event) => setForm({ ...form, email: event.target.value })} /></Field>
+ <Field label="Role"><select className="select h-9" value={form.role} onChange={(event) => setForm({ ...form, role: event.target.value })}><option value="user">Viewer</option><option value="admin">Admin</option></select></Field>
+ <button type="submit" className="btn btn-primary h-9" disabled={state.busy}>Create invitation link</button>
+ <button type="button" className="btn btn-ghost h-9" onClick={() => setInviting(false)}>Cancel</button>
+ </form>
+ )}
+ <div className="divide-y divide-line border-t border-line">
+ <Row title="Require two-factor for everyone" detail={data.secrets_configured ? 'New and existing users set it up at their next sign-in' : 'Not possible yet: this server has no SECRETS_KEY (see docs/accounts.md)'}>
+ <Switch label="Require two-factor for everyone" checked={data.require_2fa_for_everyone} disabled={!data.secrets_configured || state.busy} onChange={(on) => setting({ require_2fa_for_everyone: on })} />
+ </Row>
+ <Row title="Require two-factor for owners and admins" detail="On unless you turn it off. Applies even when the switch above is off.">
+ <Switch label="Require two-factor for admins" checked={data.require_2fa_for_admins} disabled={!data.secrets_configured || state.busy || data.require_2fa_for_everyone} onChange={(on) => setting({ require_2fa_for_admins: on })} />
+ </Row>
+ </div>
+ <div className="flex flex-wrap items-center justify-between gap-3 border-t border-line px-[18px] py-3 text-xs text-muted">
+ <span>Owners and admins change settings. Viewers see everything but can't acknowledge, resolve or change anything. <Outcome state={state} /></span>
+ {!inviting && <button type="button" className="btn btn-sm" onClick={() => { setLink(null); setInviting(true) }}><Icon name="plus" size={13} />Invite user</button>}
+ </div>
+ </div>
+ )
+}
+
+function Rules({ onCount }) {
+ const { data, error, reload } = useLoaded('/admin/rules')
+ const [state, run] = useAction()
+ const [editing, setEditing] = useState(null)
+ const [values, setValues] = useState({})
+ const count = data?.rules.length
+ useEffect(() => { if (count != null) onCount(count) }, [count, onCount])
+ if (!data) return <Notice tone="plain">{error || 'Loading rules…'}</Notice>
+ const toggle = (rule, on) => run(async () => { await put({ disabled_rules: data.rules.filter((item) => (item.kind === rule.kind ? !on : !item.enabled)).map((item) => item.kind) }); reload() })
+ 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)
+ 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]">
+ <thead><tr className="grid-head h-10"><th className="w-[70px] pl-[18px] font-medium">On</th><th className="font-medium">When</th><th className="font-medium">For</th><th className="font-medium">Severity</th><th className="font-medium">Servers</th><th className="pr-[18px] text-right font-medium">Fired · 30 d</th></tr></thead>
+ <tbody>
+ {data.rules.map((rule) => (
+ <tr key={rule.kind} className={`border-t border-line ${rule.enabled ? '' : 'text-dim'}`}>
+ <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>}
+ </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>
+ <td className={rule.enabled ? 'text-soft' : ''}>All</td>
+ <td className="pr-[18px] text-right">{rule.fired}{rule.noisy && <span className="ml-2 text-xs text-warn">noisy</span>}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table></div>
+ <div className="flex flex-wrap items-center justify-between gap-3 border-t border-line px-[18px] py-3 text-xs text-muted">
+ <span>{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. <Outcome state={state} /></span>
+ <button type="button" className="btn btn-sm" disabled title="Rules of your own are not built yet; the built-in ones can be tuned and switched off."><Icon name="plus" size={13} />New rule</button>
+ </div>
+ </div>
+ )
+}
+
+function MountOverrides({ settings, onSaved }) {
+ const [rows, setRows] = useState(() => Object.entries(settings.mount_thresholds || {}).map(([mount, limits]) => ({ mount, warning: limits.disk_warning_pct, critical: limits.disk_critical_pct })))
+ const [state, run] = useAction()
+ const set = (index, key, value) => setRows(rows.map((row, position) => (position === index ? { ...row, [key]: value } : row)))
+ const save = () => run(async () => onSaved(await put({ mount_thresholds: Object.fromEntries(rows.filter((row) => row.mount.trim()).map((row) => [row.mount.trim(), { disk_warning_pct: Number(row.warning), disk_critical_pct: Number(row.critical) }])) })), 'Saved.')
+ return (
+ <div className="card px-[18px] py-4">
+ <p className="m-0 text-[13px] font-medium text-paper">Disk limits for single filesystems</p>
+ <p className="mb-0 mt-1 text-xs text-muted">A backup disk that is meant to be nearly full can get its own limits instead of the ones in the Disk rule above.</p>
+ <div className="mt-3 space-y-2">
+ {rows.map((row, index) => (
+ <div key={index} className="flex flex-wrap items-center gap-2.5">
+ <input className="field mono h-8 w-56" placeholder="/mnt/backup" aria-label="Mount" value={row.mount} onChange={(event) => set(index, 'mount', event.target.value)} />
+ <input type="number" className="field h-8 w-24" aria-label="Warning from %" placeholder="warn %" value={row.warning} onChange={(event) => set(index, 'warning', event.target.value)} />
+ <input type="number" className="field h-8 w-24" aria-label="Critical from %" placeholder="crit %" value={row.critical} onChange={(event) => set(index, 'critical', event.target.value)} />
+ <button type="button" className="link text-xs" onClick={() => setRows(rows.filter((_, position) => position !== index))}>Remove</button>
+ </div>
+ ))}
+ </div>
+ <div className="mt-3 flex flex-wrap items-center gap-3"><button type="button" className="btn btn-sm" onClick={() => setRows([...rows, { mount: '', warning: 95, critical: 99 }])}><Icon name="plus" size={13} />Add a filesystem</button><button type="button" className="btn btn-sm btn-primary" disabled={state.busy} onClick={save}>Save limits</button><Outcome state={state} /></div>
+ </div>
+ )
+}
+
+function Agent({ settings, system, onSaved }) {
+ const [state, run] = useAction()
+ const agent = system.agent
+ return <>
+ <div className="card divide-y divide-line">
+ <Row icon="AI" title="Model provider" detail={agent.key_configured ? `Google Gemini · ${agent.model.replace('models/', '')} · key configured` : 'No API key configured. Set GEMINI_API_KEY in .env to turn the chat on.'} tone={agent.key_configured ? undefined : 'warn'}><button type="button" className="btn btn-sm" disabled title="The provider and key are set in .env (AGENT_MODEL, GEMINI_API_KEY) and need a restart.">Change</button></Row>
+ <Row title="Diagnose new incidents automatically" detail="Always on. The diagnosis is built from stored metrics and events by fixed rules, so it costs nothing and sends nothing to the provider."><Switch label="Diagnose automatically" checked disabled onChange={() => {}} /></Row>
+ <Row title="Read container logs" detail="Not available: Infradeck's Docker proxy can't read logs. See SECURITY.md."><Switch label="Read container logs" checked={false} disabled onChange={() => {}} /></Row>
+ <Row title="Chat" detail="Available to every signed-in user while it is on. Questions and the incident's facts are sent to the provider."><Switch label="Chat with the agent" checked={settings.agent_chat_enabled} disabled={state.busy} onChange={(on) => run(async () => onSaved(await put({ agent_chat_enabled: on })))} /></Row>
+ <Row title="Redact IPs and hostnames before sending" detail="Not available yet. Until then, turn Chat off if names must not leave this machine."><Switch label="Redact before sending" checked={false} disabled onChange={() => {}} /></Row>
+ </div>
+ <div className="card grid divide-y divide-line sm:grid-cols-3 sm:divide-x sm:divide-y-0">
+ {[[agent.incidents_this_month, 'incidents diagnosed this month'], [agent.chat_messages_this_month, 'chat messages this month'], ['—', 'provider cost · not tracked']].map(([value, label]) => <div key={label} className="px-[18px] py-4"><div className="text-2xl font-semibold leading-none text-paper">{value}</div><div className="mt-2 text-xs text-muted">{label}</div></div>)}
+ </div>
+ <Outcome state={state} />
+ </>
+}
+
+const megabytes = (bytes) => (bytes == null ? '—' : bytes >= 1024 ** 3 ? `${(bytes / 1024 ** 3).toFixed(1)} GB` : `${Math.round(bytes / 1024 ** 2)} MB`)
+
+function Retention({ settings, system, onSaved }) {
+ const [state, run] = useAction()
+ const database = system.database
+ return (
+ <div className="card divide-y divide-line">
+ <Row title="Check-ins and their summaries" detail="Every check-in is kept for a week; hourly, daily, weekly and monthly summaries for as long as this says. Statistics reads the summaries for ranges past 7 days.">
+ <select className="select" aria-label="Retention" value={settings.metrics_retention_days} disabled={state.busy} onChange={(event) => run(async () => onSaved(await put({ metrics_retention_days: Number(event.target.value) })), 'Saved.')}>
+ {[...new Set([7, 30, 90, 365, settings.metrics_retention_days])].sort((a, b) => a - b).map((days) => <option key={days} value={days}>{days === 365 ? '1 year' : `${days} days`}</option>)}
+ </select>
+ </Row>
+ <Row title="Incidents" detail="Kept until their server is removed."><span className="text-[13px] text-soft">Forever</span></Row>
+ <Row icon="db" title="Database" detail={`${database.engine}${database.host_rows != null ? ` · ${database.host_rows.toLocaleString()} check-ins stored, ${database.host_rows_week.toLocaleString()} from the last 7 days` : ''}`}>
+ <span className="mr-2 text-lg font-semibold text-paper">{megabytes(database.bytes)}</span>
+ <button type="button" className="btn btn-sm" disabled title="Not built yet. Back up the postgres volume with pg_dump for now (see SETUP_DATABASES.md).">Export</button>
+ <button type="button" className="btn btn-sm" disabled title="Not built yet. Back up the postgres volume with pg_dump for now (see SETUP_DATABASES.md).">Back up now</button>
+ </Row>
+ {(state.error || state.ok) && <div className="px-[18px] py-2.5"><Outcome state={state} /></div>}
+ </div>
+ )
+}
+
+function About({ settings, system, onSaved }) {
+ const [name, setName] = useState(settings.instance_name || '')
+ const [state, run] = useAction()
+ return (
+ <div className="card divide-y divide-line">
+ <Row title={`Infradeck ${system.version}`} detail="Open source, MIT licensed. Infradeck doesn't call home, so it can't tell you about new versions; the changelog can."><a className="btn btn-sm" href={`${REPOSITORY}/releases`} target="_blank" rel="noreferrer">Changelog</a><a className="btn btn-sm" href={`${REPOSITORY}#readme`} target="_blank" rel="noreferrer">How to update</a></Row>
+ <Row title="Source" detail="github.com/karloks2005/Infradeck"><a className="btn btn-sm" href={REPOSITORY} target="_blank" rel="noreferrer">Open</a></Row>
+ <form className="flex flex-wrap items-end gap-3 px-[18px] py-3.5" onSubmit={(event) => { event.preventDefault(); run(async () => { const saved = await put({ instance_name: name }); setName(saved.instance_name || ''); onSaved(saved); refreshOverview() }, 'Saved.') }}>
+ <Field label="Name of this install" hint="Shown in the sidebar and on the sign-in page, where anyone who can reach it can read it. Leave empty for the default." className="min-w-0 flex-1 basis-72"><input className="field h-9" maxLength={60} value={name} onChange={(event) => setName(event.target.value)} /></Field>
+ <button type="submit" className="btn btn-primary h-9" disabled={state.busy || name === (settings.instance_name || '')}>Save name</button>
+ <Outcome state={state} />
+ </form>
+ </div>
+ )
+}
+
+export default function AdminPage({ user, onLogout }) {
+ const { data: overview } = useOverview(Boolean(user), 15, onLogout)
+ const settings = useLoaded('/admin/settings')
+ const system = useLoaded('/admin/system')
+ const [ruleCount, setRuleCount] = useState(null)
+ const pending = overview?.pending_collectors || []
+ 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.data
+ return (
+ <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}>
+ {(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 && <>
+ <Section id="servers" title="Servers" description="Each server runs a small collector container that reports every few seconds. Removing a server deletes its stored metrics and incidents."><Servers overview={overview} /></Section>
+ <Section id="connect" title="Connect a server" description="Name it, run one command on that machine, then add it when it shows up. The token works once and expires.">
+ <div className="grid items-start gap-4 2xl:grid-cols-2 [&>*]:min-w-0">
+ {pending.some((item) => item.status === 'pending' && item.details?.dashboard_host) && <ThisMachineCard pending={pending} onChanged={refreshOverview} />}
+ <AnotherMachineCard pending={pending} onChanged={refreshOverview} />
+ </div>
+ </Section>
+ <Section id="users" title="Users" description="Who can sign in, what they may do, and whether they must use two-factor."><Users me={user} /></Section>
+ <Section id="rules" title="Alert rules" description="What opens an incident. Rules apply to every server. The “Fired” column shows how noisy each rule has been."><Rules onCount={setRuleCount} /><MountOverrides settings={settings.data} onSaved={settings.setData} /></Section>
+ <Section id="agent" title="Incident agent" description="Diagnoses incidents and answers questions using the data Infradeck already has. It is read-only: it can't run commands, restart containers or change files on your servers."><Agent settings={settings.data} system={system.data} onSaved={settings.setData} /></Section>
+ <Section id="retention" title="Data & retention" description="How long history is kept and how big it is."><Retention settings={settings.data} system={system.data} onSaved={settings.setData} /></Section>
+ <Section id="about" title="About"><About settings={settings.data} system={system.data} onSaved={settings.setData} /></Section>
+ </>}
+ </SettingsLayout>
+ </AppShell>
+ )
+}
diff --git a/src/frontend/src/agent/AgentPage.jsx b/src/frontend/src/agent/AgentPage.jsx
new file mode 100644
index 0000000..cb7cd62
--- /dev/null
+++ b/src/frontend/src/agent/AgentPage.jsx
@@ -0,0 +1,273 @@
+// The Agent page: an inbox of incidents, one incident with its diagnosis and the proof behind it, and a chat
+// about that incident. The diagnosis is built by the backend from stored data; the chat is the language model.
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { Link, useSearchParams } from 'react-router-dom'
+import { apiRequest } from '../api.js'
+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'
+
+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' }
+const clock = (time) => new Date(time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
+const day = (time) => new Date(time).toLocaleDateString([], { weekday: 'short', day: 'numeric', month: 'short' })
+const post = (path, body) => apiRequest(path, { method: 'POST', body: JSON.stringify(body || {}) })
+
+function stateLine(incident) {
+ if (incident.status === 'resolved') return incident.resolution || 'Cleared on its own'
+ if (incident.muted_until) return `Muted until ${clock(incident.muted_until)}`
+ return `${incident.state === 'watching' ? 'Watching' : 'Diagnosed'}${incident.acknowledged_at ? ` · acknowledged${incident.acknowledged_by ? ` by ${incident.acknowledged_by}` : ''}` : ''}`
+}
+
+function InboxRow({ incident, selected, onSelect }) {
+ const [label, chip, color] = SEVERITY[incident.severity] || SEVERITY.INFO
+ const resolved = incident.status === 'resolved'
+ return (
+ <li>
+ <button type="button" aria-current={selected ? 'true' : undefined} onClick={() => onSelect(incident.id)} className={`block w-full border-0 border-b border-solid border-line px-[18px] py-3.5 text-left transition-colors hover:bg-ink ${selected ? 'bg-ink' : 'bg-transparent'}`} style={{ boxShadow: resolved ? undefined : `inset 2px 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-[13px] font-semibold leading-[18px] ${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: 6, height: 6 }} />}{stateLine(incident)}</span>
+ </button>
+ </li>
+ )
+}
+
+// The metric the rule looks at, with its limit as a dashed line and a mark wherever something happened.
+function Evidence({ evidence }) {
+ const points = evidence.series.filter((point) => point.value != null)
+ if (points.length < 2) return <p className="m-0 rounded-md border border-line px-[18px] py-8 text-center text-xs text-muted">Not enough samples in this window to draw.</p>
+ const start = new Date(evidence.series[0].time).getTime()
+ const span = Math.max(1, new Date(evidence.series[evidence.series.length - 1].time).getTime() - start)
+ const percent = evidence.unit === '%'
+ const inGb = evidence.unit === 'MB' && Math.max(evidence.limit || 0, ...points.map((point) => point.value)) >= 1024
+ const scale = inGb ? 1024 : 1
+ const top = percent ? 100 : niceCeiling(Math.max(evidence.limit || 0, ...points.map((point) => point.value)) / scale * 1.15)
+ const x = (time) => ((new Date(time).getTime() - start) / span) * 100
+ const y = (value) => (1 - Math.min(Math.max(value / scale, 0), top) / top) * 100
+ const unit = percent ? '%' : inGb ? ' GB' : evidence.unit ? ` ${evidence.unit}` : ''
+ let drawing = false
+ const line = evidence.series.map((point) => { if (point.value == null) { drawing = false; return '' } const command = `${drawing ? 'L' : 'M'}${x(point.time).toFixed(2)},${y(point.value).toFixed(2)}`; drawing = true; return command }).join(' ')
+ return (
+ <figure className="m-0 rounded-md border border-line bg-ink px-[18px] pb-3 pt-5" role="img" aria-label={`${evidence.title} around the incident`}>
+ <div className="relative ml-12 h-[150px]">
+ {[top, top / 2, 0].map((tick) => <span key={tick} aria-hidden="true" className="absolute right-full -translate-y-1/2 whitespace-nowrap pr-2.5 text-[11px] text-muted" style={{ top: `${(1 - tick / top) * 100}%` }}>{Number(tick.toFixed(1))}{unit}</span>)}
+ <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="absolute inset-0 h-full w-full overflow-visible" aria-hidden="true">
+ {[top, top / 2, 0].map((tick) => <line key={tick} x1="0" x2="100" y1={(1 - tick / top) * 100} y2={(1 - tick / top) * 100} stroke="var(--color-line)" strokeWidth="1" vectorEffect="non-scaling-stroke" />)}
+ {(evidence.marks || []).map((mark) => <line key={mark.time} x1={x(mark.time)} x2={x(mark.time)} y1="0" y2="100" stroke="var(--color-signal)" strokeWidth="1" vectorEffect="non-scaling-stroke" />)}
+ {evidence.limit != null && evidence.limit / scale <= top && <line x1="0" x2="100" y1={y(evidence.limit)} y2={y(evidence.limit)} stroke="var(--color-signal)" strokeWidth="1" strokeDasharray="4 3" vectorEffect="non-scaling-stroke" />}
+ <path d={line} fill="none" stroke="var(--color-paper)" strokeWidth="1.4" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
+ </svg>
+ {(evidence.marks || []).map((mark) => <span key={mark.time} aria-hidden="true" className="absolute -top-[3px] h-[6px] w-[6px] -translate-x-1/2 bg-signal" style={{ left: `${x(mark.time)}%` }} />)}
+ </div>
+ <div aria-hidden="true" className="ml-12 mt-2 flex justify-between text-[11px] text-muted"><span>{clock(evidence.series[0].time)}</span><span>{clock(evidence.series[evidence.series.length - 1].time)}</span></div>
+ <figcaption className="ml-12 mt-2.5 flex flex-wrap gap-x-5 gap-y-1 text-xs text-soft">
+ {(evidence.marks || []).length > 0 && <span><span className="mr-2 inline-block h-[6px] w-[6px] bg-signal align-middle" />{evidence.mark_label || 'Event'}</span>}
+ {evidence.limit != null && <span><span className="mr-2 inline-block w-4 border-t border-dashed border-signal align-middle" />{evidence.limit_label || 'Limit'}</span>}
+ </figcaption>
+ </figure>
+ )
+}
+
+function Command({ step }) {
+ const [copied, copy] = useCopy()
+ return (
+ <div className="mt-2.5 flex items-center gap-3 rounded-md border border-line bg-bg py-1.5 pl-3 pr-1.5">
+ {step.label && <span className="mono shrink-0 text-dim">{step.label}</span>}
+ <code className="mono custom-scroll min-w-0 flex-1 overflow-x-auto whitespace-nowrap text-paper">{step.command}</code>
+ <button type="button" className="btn btn-sm btn-ghost shrink-0" onClick={() => copy(step.command)}><Icon name={copied ? 'check' : 'copy'} size={13} />{copied ? 'Copied' : 'Copy'}</button>
+ </div>
+ )
+}
+
+function Incident({ incident, canAct, onChanged }) {
+ const [state, run] = useAction()
+ const [muteFor, setMuteFor] = useState(60)
+ 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); refreshOverview(); onChanged() })
+ const denied = canAct ? undefined : 'Only owners and admins can change an incident.'
+ const section = 'mt-7'
+ return (
+ <article className="px-5 pb-10 pt-6 lg:px-7" aria-label={`${incident.reference}: ${incident.title}`}>
+ <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><span className="mono text-xs text-muted">{incident.reference}</span></div>
+ <h1 className="m-0 mt-3 text-[21px] font-semibold leading-7 text-paper">{incident.title}</h1>
+ <dl className="m-0 mt-3 flex flex-wrap gap-x-5 gap-y-1 text-[13px] text-muted">
+ <div>Server <span className="font-medium text-paper">{incident.hostname}</span></div>
+ {found.container && <div>Container <span className="mono text-paper">{found.container}</span></div>}
+ <div>Opened <span className="font-medium text-paper">{clock(incident.created_at)}</span> · {formatAge(incident.created_at)} ago</div>
+ {resolved && <div>Resolved <span className="font-medium text-paper">{day(incident.resolved_at)} {clock(incident.resolved_at)}</span></div>}
+ <div>Notified <span className="font-medium text-paper">{incident.notified ? 'sent to the channels people chose' : 'nobody yet'}</span></div>
+ {incident.acknowledged_at && <div>Acknowledged <span className="font-medium text-paper">{incident.acknowledged_by ? `by ${incident.acknowledged_by}` : formatAge(incident.acknowledged_at)}</span></div>}
+ </dl>
+ <div className="mt-4 flex flex-wrap items-center gap-2.5">
+ {!resolved && <>
+ <button type="button" className={`btn ${incident.acknowledged_at ? '' : 'btn-primary'}`} disabled={!canAct || state.busy || Boolean(incident.acknowledged_at)} title={denied} onClick={() => act('acknowledge')}><Icon name="check" size={14} />{incident.acknowledged_at ? 'Acknowledged' : 'Acknowledge'}</button>
+ <button type="button" className="btn" disabled={!canAct || state.busy} title={denied || 'If the cause is still there, a new incident opens at the next check-in.'} onClick={() => act('resolve')}>Mark resolved</button>
+ {incident.muted_until
+ ? <button type="button" className="btn" disabled={!canAct || state.busy} title={denied} onClick={() => act('unmute')}>Unmute</button>
+ : <span className="inline-flex"><button type="button" className="btn rounded-r-none" disabled={!canAct || state.busy} title={denied} onClick={() => act('mute', { minutes: muteFor })}>Mute</button><select className="select -ml-px rounded-l-none" aria-label="Mute for how long" value={muteFor} disabled={!canAct} onChange={(event) => setMuteFor(Number(event.target.value))}><option value={60}>1 h</option><option value={240}>4 h</option><option value={1440}>1 day</option><option value={10080}>1 week</option></select></span>}
+ </>}
+ <Link to={serverLink(incident.server_id, found.container ? 'containers' : found.kind?.startsWith('network') ? 'network' : 'overview')} className="btn btn-ghost">{found.container ? 'Open container' : 'Open server'}<Icon name="arrow" size={13} /></Link>
+ </div>
+ {state.error && <p role="alert" className="mb-0 mt-2 text-xs text-warn">{state.error}</p>}
+
+ <p className="mb-0 mt-6 max-w-[760px] text-[15px] leading-[25px] text-paper">{found.summary}</p>
+
+ {found.evidence && <section className={section} aria-label="Evidence">
+ <div className="mb-2.5 flex flex-wrap items-baseline justify-between gap-2"><h2 className="m-0 text-sm font-semibold text-paper">Evidence</h2><span className="text-xs text-muted">{found.evidence.title} · {clock(found.window.start)} to {resolved ? clock(found.window.end) : 'now'}{found.evidence.limit != null ? ` · ${found.evidence.limit_label?.toLowerCase() || 'limit'} drawn dashed` : ''}</span></div>
+ <Evidence evidence={found.evidence} />
+ </section>}
+
+ {found.lines.length > 0 && <section className="mt-3" aria-label="What was recorded">
+ <ul className="mono custom-scroll m-0 max-h-[240px] list-none space-y-1 overflow-auto rounded-md border border-line bg-ink px-[18px] py-3.5 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">These are the events Infradeck recorded on {incident.hostname}, not the container's own log, which it can't read.</p>
+ </section>}
+
+ {found.signals.length > 0 && <section className={section} aria-label="Why the agent thinks so">
+ <div className="mb-2.5 flex flex-wrap items-baseline justify-between gap-2"><h2 className="m-0 text-sm font-semibold text-paper">Why the agent thinks so</h2><span className="text-xs text-soft">{found.agreeing} of {found.signals.length} checks against the data hold</span></div>
+ <ul className="card m-0 list-none divide-y divide-line p-0">
+ {found.signals.map((signal) => <li key={signal.text} className="flex items-center gap-3.5 px-[18px] py-3 text-[13px]"><Icon name={signal.ok ? 'check' : 'close'} size={14} className={signal.ok ? 'shrink-0 text-ok' : 'shrink-0 text-muted'} /><span className="min-w-0 flex-1 text-paper">{signal.text}</span><span className="shrink-0 text-xs text-muted">{signal.source}</span></li>)}
+ </ul>
+ </section>}
+
+ {found.steps.length > 0 && <section className={section} aria-label="How to fix it">
+ <div className="mb-2.5 flex flex-wrap items-baseline justify-between gap-2"><h2 className="m-0 text-sm font-semibold text-paper">How to fix it</h2><span className="text-xs text-muted">You run these yourself. Infradeck can't change your servers.</span></div>
+ <ol className="card m-0 list-none divide-y divide-line p-0">
+ {found.steps.map((step, index) => (
+ <li key={step.title} className="grid grid-cols-[34px_minmax(0,1fr)] px-[18px] py-4">
+ <span className="mono pt-0.5 text-signal">{String(index + 1).padStart(2, '0')}</span>
+ <div className="min-w-0"><p className="m-0 text-sm font-semibold text-paper">{step.title}{step.recommended && <span className="chip ml-2.5 align-middle font-normal">recommended</span>}</p><p className="mb-0 mt-1 text-[13px] leading-5 text-muted">{step.text}</p>{step.command && <Command step={step} />}</div>
+ </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 className={section} aria-label="Timeline">
+ <h2 className="m-0 mb-2.5 text-sm font-semibold text-paper">Timeline</h2>
+ <ol className="m-0 list-none space-y-2.5 p-0">{found.timeline.map((item, index) => <li key={`${item.time}-${index}`} className="grid grid-cols-[96px_14px_minmax(0,1fr)] items-baseline text-[13px]"><time dateTime={item.time} className="mono text-muted" title={new Date(item.time).toLocaleString()}>{day(item.time).split(',')[0]} {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>
+ )
+}
+
+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 }) {
+ const conversationId = `${incident ? `incident-${incident.id}` : 'general'}-u${user.id}`
+ const [messages, setMessages] = useState(null)
+ const [draft, setDraft] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const exists = useRef(false)
+ const end = useRef(null)
+
+ useEffect(() => {
+ let active = true
+ setMessages(null); setError(''); exists.current = false
+ apiRequest('/conversations', { method: 'GET' }).then((data) => {
+ if (!active) return
+ const found = data.conversations.find((item) => item.id === conversationId)
+ exists.current = Boolean(found)
+ setMessages(found ? found.messages : [])
+ }).catch((requestError) => { if (active) { setMessages([]); setError(requestError.message || 'Could not load the chat.') } })
+ return () => { active = false }
+ }, [conversationId])
+ useEffect(() => { end.current?.scrollIntoView({ block: 'nearest' }) }, [messages, busy])
+
+ const send = async (text) => {
+ const message = text.trim()
+ if (!message || busy) return
+ setBusy(true); setError(''); setDraft('')
+ setMessages((current) => [...(current || []), { id: `local-${Date.now()}`, role: 'user', text: message }])
+ try {
+ if (!exists.current) { await post('/conversations', { conversation_id: conversationId, title: incident ? `${incident.reference} · ${incident.title}`.slice(0, 250) : 'New chat' }); exists.current = true }
+ const reply = await post('/agent/chat', { conversation_id: conversationId, message, incident_id: incident?.id })
+ setMessages((current) => [...current, { id: `reply-${Date.now()}`, role: 'agent', text: reply.message }])
+ } catch (requestError) { setError(requestError.message || 'The agent could not answer.') } finally { setBusy(false) }
+ }
+ const restart = async () => {
+ if (exists.current) { try { await apiRequest(`/conversations/${conversationId}`, { method: 'DELETE' }) } catch { /* it is gone either way for this page */ } }
+ exists.current = false; setMessages([]); setError('')
+ }
+
+ 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">
+ <div className="flex items-baseline justify-between"><h2 className="m-0 text-[15px] font-semibold text-paper">Ask the agent</h2><button type="button" className="border-0 bg-transparent p-0 text-xs text-muted hover:text-paper" onClick={restart}>New chat</button></div>
+ <div className="mt-2 flex items-center gap-2 text-xs text-muted">About <span className="chip max-w-full truncate text-paper">{incident ? `${incident.reference} · ${incident.hostname}` : 'any server'}</span></div>
+ </div>
+ <div className="custom-scroll min-h-0 flex-1 space-y-4 overflow-y-auto px-5 py-4">
+ {!enabled && <Notice tone="plain">Chat with the agent has been turned off by an admin. The diagnosis on the left doesn't need it.</Notice>}
+ {enabled && messages === null && <p className="m-0 text-xs text-muted">Loading…</p>}
+ {enabled && messages?.length === 0 && <div className="space-y-2">
+ <p className="m-0 text-xs text-muted">{incident ? 'The agent is given this incident\'s facts with your question.' : 'Ask about any server.'} Suggestions:</p>
+ {(incident ? SUGGESTIONS.default : SUGGESTIONS.none).map((text) => <button key={text} type="button" className="block w-full rounded-md border border-line bg-transparent px-3 py-2 text-left text-[13px] text-soft hover:border-edge hover:text-paper" onClick={() => send(text)}>{text}</button>)}
+ </div>}
+ {enabled && (messages || []).map((message) => (message.role === 'user'
+ ? <div key={message.id} className="ml-8 rounded-md border border-line bg-ink px-3.5 py-2.5 text-[13px] leading-5 text-paper">{message.text}</div>
+ : <div key={message.id}><div className="mb-1.5 flex items-center gap-2 text-xs text-muted"><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>Agent</div><p className="m-0 whitespace-pre-wrap text-[13px] leading-[21px] 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="border-t border-line p-4" onSubmit={(event) => { event.preventDefault(); send(draft) }}>
+ <div className="flex items-end gap-2 rounded-md border border-edge bg-ink p-1.5 focus-within:border-muted">
+ <textarea rows={2} className="min-h-[40px] flex-1 resize-none border-0 bg-transparent px-2 py-1.5 text-[13px] text-paper outline-none placeholder:text-dim" placeholder={incident ? 'Ask about this incident or any server…' : 'Ask about any server…'} aria-label="Your question" maxLength={8000} disabled={!enabled} value={draft} onChange={(event) => setDraft(event.target.value)} onKeyDown={(event) => { if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); send(draft) } }} />
+ <button type="submit" className="btn btn-primary h-8 w-8 shrink-0 p-0" aria-label="Send" disabled={!enabled || busy || !draft.trim()}><Icon name="arrow" size={14} /></button>
+ </div>
+ <p className="mb-0 mt-2 text-[11px] leading-4 text-muted">Reads metrics and events. Can't run commands on your servers. Your question and the incident's facts are sent to the model provider.</p>
+ </form>
+ </aside>
+ )
+}
+
+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 requested = Number(params.get('incident'))
+ const selectedId = all.some((item) => item.id === requested) ? requested : inbox?.open[0]?.id ?? null
+ const selected = all.find((item) => item.id === selectedId) || null
+ const { data: detail, error: detailError, reload: reloadDetail } = usePolled(selectedId ? `/incidents/${selectedId}` : null, 20)
+ const select = (id) => setParams({ incident: String(id) }, { replace: true })
+ // Following a link to a resolved or muted incident opens the tab it lives in.
+ useEffect(() => { if (selected) setTab(selected.status === 'resolved' ? 'resolved' : selected.muted_until ? 'muted' : 'open') }, [selected?.id]) // eslint-disable-line react-hooks/exhaustive-deps
+ const list = inbox ? inbox[tab] : []
+ const crumbs = selected ? [{ label: 'Agent', to: '/agent' }, { label: selected.reference }] : [{ label: 'Agent' }]
+
+ 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">
+ <section className="flex min-h-0 flex-col border-b border-line xl:border-b-0" aria-label="Incidents">
+ <div className="px-[18px] pb-3 pt-5">
+ <div className="flex items-baseline gap-2.5"><h2 className="m-0 text-[15px] font-semibold text-paper">Incidents</h2><span className="text-xs text-muted">{inbox ? `${inbox.open.length} open` : ''}</span></div>
+ <div className="seg mt-3" 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)}>{label} {count ?? ''}</button>)}
+ </div>
+ </div>
+ <ul className="custom-scroll m-0 max-h-[320px] min-h-0 flex-1 list-none overflow-y-auto border-t border-line p-0 xl:max-h-none">
+ {list.map((incident) => <InboxRow key={incident.id} incident={incident} selected={incident.id === selectedId} onSelect={select} />)}
+ {inbox && !list.length && <li className="px-[18px] py-8 text-center text-xs text-muted">{tab === 'open' ? 'Nothing is open. Every drawer is in.' : tab === 'muted' ? 'Nothing is muted.' : 'Nothing has been resolved yet.'}</li>}
+ {!inbox && <li className="px-[18px] py-8 text-center text-xs text-muted">{error || 'Loading…'}</li>}
+ </ul>
+ </section>
+ <div className="custom-scroll min-h-0 xl:overflow-y-auto">
+ {detail && detail.id === selectedId ? <Incident incident={detail} canAct={Boolean(inbox?.can_act)} onChanged={() => { reload(); reloadDetail() }} />
+ : selectedId ? <p className="m-0 px-7 py-16 text-center text-[13px] text-muted">{detailError || 'Loading the incident…'}</p>
+ : <div className="px-7 py-16 text-center"><p className="m-0 text-sm font-medium text-paper">{inbox && !all.length ? 'No incidents yet.' : 'Nothing needs you right now.'}</p><p className="mb-0 mt-2 text-[13px] text-muted">{inbox && !all.length ? 'When a rule fires on one of your servers, the incident shows up here with what was found and how to fix it.' : 'Pick a resolved incident on the left to see how it went.'}</p></div>}
+ </div>
+ <div className="min-h-0 border-t border-line xl:border-t-0"><Chat key={selectedId ?? 'none'} user={user} incident={detail && detail.id === selectedId ? detail : null} enabled={config ? config.chat_enabled : true} /></div>
+ </div>
+ </AppShell>
+ )
+}
diff --git a/src/frontend/src/api.js b/src/frontend/src/api.js
new file mode 100644
index 0000000..3855833
--- /dev/null
+++ b/src/frontend/src/api.js
@@ -0,0 +1,25 @@
+// The one way the pages talk to the backend.
+export const API_BASE = import.meta.env.VITE_API_BASE_URL || '/api'
+// Vite only exposes VITE_-prefixed env vars; clamp so a bad value can't flood the API.
+export const LIVE_REFRESH_SECONDS = Math.max(Number(import.meta.env.VITE_LIVE_GRAPH_REFRESH_INTERVAL_SECONDS) || 3, 1)
+
+export async function apiRequest(path, options = {}) {
+ const response = await fetch(`${API_BASE}${path}`, {
+ ...options,
+ credentials: 'include',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(options.headers || {}),
+ },
+ })
+
+ if (!response.ok) {
+ const errorBody = await response.json().catch(() => ({}))
+ const detail = errorBody.detail
+ const error = new Error(typeof detail === 'string' ? detail : detail?.message || 'Request failed.')
+ error.status = response.status
+ throw error
+ }
+
+ return response.json()
+}
diff --git a/src/frontend/src/assets/hero.png b/src/frontend/src/assets/hero.png
deleted file mode 100644
index 02251f4..0000000
Binary files a/src/frontend/src/assets/hero.png and /dev/null differ
diff --git a/src/frontend/src/assets/react.svg b/src/frontend/src/assets/react.svg
deleted file mode 100644
index 6c87de9..0000000
--- a/src/frontend/src/assets/react.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
\ No newline at end of file
diff --git a/src/frontend/src/assets/vite.svg b/src/frontend/src/assets/vite.svg
deleted file mode 100644
index 5101b67..0000000
--- a/src/frontend/src/assets/vite.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="77" height="47" fill="none" aria-labelledby="vite-logo-title" viewBox="0 0 77 47"><title id="vite-logo-title">Vite</title><style>.parenthesis{fill:#000}@media (prefers-color-scheme:dark){.parenthesis{fill:#fff}}</style><path fill="#9135ff" d="M40.151 45.71c-.663.844-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.493c-.92 0-1.457-1.04-.92-1.788l7.479-10.471c1.07-1.498 0-3.578-1.842-3.578H15.443c-.92 0-1.456-1.04-.92-1.788l9.696-13.576c.213-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.472c-1.07 1.497 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.087.89 1.83L40.153 45.712z"/><mask id="a" width="48" height="47" x="14" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M40.047 45.71c-.663.843-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.389c-.92 0-1.457-1.04-.92-1.788l7.479-10.472c1.07-1.497 0-3.578-1.842-3.578H15.34c-.92 0-1.456-1.04-.92-1.788l9.696-13.575c.213-.297.556-.474.92-.474H53.93c.92 0 1.456 1.04.92 1.788L47.37 13.03c-1.07 1.498 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.088.89 1.831L40.049 45.712z"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#eee6ff" rx="5.508" ry="14.704" transform="rotate(269.814 20.96 11.29)scale(-1 1)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#eee6ff" rx="10.399" ry="29.851" transform="rotate(89.814 -16.902 -8.275)scale(1 -1)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#8900ff" rx="5.508" ry="30.487" transform="rotate(89.814 -19.197 -7.127)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.928 4.177)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.738 5.52)scale(1 -1)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#eee6ff" rx="14.072" ry="22.078" transform="rotate(93.35 31.245 55.578)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx="14.592" cy="9.743" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(39.51 14.592 9.743)"/></g><g filter="url(#k)"><ellipse cx="61.728" cy="-5.321" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 61.728 -5.32)"/></g><g filter="url(#l)"><ellipse cx="55.618" cy="7.104" fill="#00c2ff" rx="5.971" ry="9.665" transform="rotate(37.892 55.618 7.104)"/></g><g filter="url(#m)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#n)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#o)"><ellipse cx="49.857" cy="30.678" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 49.857 30.678)"/></g><g filter="url(#p)"><ellipse cx="52.623" cy="33.171" fill="#00c2ff" rx="5.971" ry="15.297" transform="rotate(37.892 52.623 33.17)"/></g></g><path d="M6.919 0c-9.198 13.166-9.252 33.575 0 46.789h6.215c-9.25-13.214-9.196-33.623 0-46.789zm62.424 0h-6.215c9.198 13.166 9.252 33.575 0 46.789h6.215c9.25-13.214 9.196-33.623 0-46.789" class="parenthesis"/><defs><filter id="b" width="60.045" height="41.654" x="-5.564" y="16.92" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-40.407" y="-6.762" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-35.435" y="2.801" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-30.84" y="20.8" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-29.307" y="21.949" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="g" width="74.749" height="58.852" x="29.961" y="-17.13" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="h" width="61.377" height="25.362" x="37.754" y="3.055" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="i" width="61.377" height="25.362" x="37.754" y="3.055" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="j" width="56.045" height="63.649" x="-13.43" y="-22.082" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="k" width="54.814" height="64.646" x="34.321" y="-37.644" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="l" width="33.541" height="35.313" x="38.847" y="-10.552" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="m" width="54.814" height="64.646" x="-15.081" y="6.78" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="n" width="54.814" height="64.646" x="-15.081" y="6.78" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="o" width="54.814" height="64.646" x="22.45" y="-1.645" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="p" width="39.409" height="43.623" x="32.919" y="11.36" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter></defs></svg>
diff --git a/src/frontend/src/auth/AuthPages.jsx b/src/frontend/src/auth/AuthPages.jsx
new file mode 100644
index 0000000..ed0ceb9
--- /dev/null
+++ b/src/frontend/src/auth/AuthPages.jsx
@@ -0,0 +1,390 @@
+// Signing in, the two-factor step, registering and the first account on a new install. One frame for all of
+// them: the brand panel on the left (a band on top on a phone), the form on the right.
+import { useEffect, useRef, useState } from 'react'
+import { Link, useNavigate, useSearchParams } from 'react-router-dom'
+import { apiRequest } from '../api.js'
+import { Icon } from '../icons.jsx'
+import { landingPath } from '../prefs.js'
+
+export const MIN_PASSWORD_LENGTH = 16
+const MAX_PASSWORD_BYTES = 72
+const CODE_LENGTH = 6
+const DOCS_URL = 'https://github.com/karloks2005/Infradeck#readme'
+const REPOSITORY_URL = 'https://github.com/karloks2005/Infradeck'
+const SETUP_TOKEN_COMMAND = 'docker compose logs backend | grep "setup token"'
+
+// What the backend lets a visitor know before signing in. ``enabled`` is null while loading; the backend decides
+// (ALLOW_REGISTRATION, or no accounts exist yet).
+function useInstance() {
+ const [instance, setInstance] = useState({ enabled: null, bootstrapRequired: false, name: null, servers: null, version: null })
+ useEffect(() => {
+ let active = true
+ apiRequest('/auth/config', { method: 'GET' })
+ .then((data) => { if (active) setInstance({ enabled: Boolean(data.registration_enabled), bootstrapRequired: Boolean(data.bootstrap_required), name: data.instance_name || null, servers: data.server_count ?? null, version: data.version || null }) })
+ .catch(() => { if (active) setInstance((current) => ({ ...current, enabled: true })) })
+ return () => { active = false }
+ }, [])
+ return instance
+}
+
+// The README banner's rack: four units in line and the orange one pulled out.
+function Rack({ className = '' }) {
+ const unit = (y) => (
+ <g key={y}>
+ <rect x="27.5" y={y + 1.5} width="357" height="59" rx="3" fill="none" stroke="var(--color-paper)" strokeWidth="3" />
+ <circle cx="51" cy={y + 31} r="5.5" fill="var(--color-paper)" /><circle cx="359" cy={y + 31} r="5.5" fill="var(--color-paper)" />
+ {[276, 290, 304, 318].map((x) => <rect key={x} x={x} y={y + 22} width="3.5" height="18" fill="var(--color-paper)" />)}
+ </g>
+ )
+ return (
+ <svg viewBox="0 0 494 432" className={className} role="img" aria-label="A server rack with one unit pulled out">
+ <rect x="2" y="0" width="3.5" height="432" fill="var(--color-paper)" /><rect x="404" y="0" width="3.5" height="432" fill="var(--color-paper)" />
+ {[19, 100, 261, 341].map(unit)}
+ <rect x="88" y="181" width="403" height="61" fill="var(--color-signal)" />
+ <circle cx="112.5" cy="211.5" r="5.5" fill="var(--color-ink)" /><circle cx="465.5" cy="211.5" r="5.5" fill="var(--color-ink)" />
+ <rect x="374" y="208" width="53" height="7" fill="var(--color-ink)" />
+ </svg>
+ )
+}
+
+function instanceLine(instance) {
+ if (instance.bootstrapRequired) return 'new install'
+ if (instance.servers == null) return ''
+ return `${instance.servers} ${instance.servers === 1 ? 'server' : 'servers'}`
+}
+
+// ``banner``: on a phone, show the tall band with the tagline and rack (sign-in); otherwise one compact row.
+function AuthFrame({ instance, banner = false, children }) {
+ const where = instanceLine(instance)
+ return (
+ <div className="flex min-h-screen flex-col bg-bg text-paper lg:flex-row">
+ <aside className="hidden w-[41.6%] min-w-[420px] max-w-[640px] flex-col border-r border-line bg-ink px-[52px] pb-6 pt-[49px] lg:flex">
+ <img src="/logo.svg" alt="Infradeck" className="h-6 w-auto self-start" />
+ <div className="flex flex-1 items-center justify-center py-10"><Rack className="w-[356px] max-w-[72%]" /></div>
+ <p className="m-0 text-[21px] font-medium leading-7 text-paper">Every server. Every container.<br /><span className="text-signal">One dashboard.</span></p>
+ <div className="mt-7 flex items-center justify-between gap-4 border-t border-line pt-[18px] text-xs text-muted">
+ <span className="min-w-0 truncate">{instance.name && <span className="font-medium text-paper">{instance.name}</span>}{instance.name && where ? ' · ' : ''}{where}</span>
+ <span className="shrink-0">Infradeck{instance.version ? ` v${instance.version}` : ''}</span>
+ </div>
+ </aside>
+
+ {banner ? (
+ <header className="border-b border-line bg-ink px-5 pb-5 pt-[calc(1.25rem+env(safe-area-inset-top))] lg:hidden">
+ <img src="/logo.svg" alt="Infradeck" className="h-[19px] w-auto" />
+ <div className="mt-5 flex items-end justify-between gap-4">
+ <p className="m-0 text-sm font-medium leading-[19px] text-paper">Every server.<br />Every container.<br /><span className="text-signal">One dashboard.</span></p>
+ <Rack className="w-[92px] shrink-0" />
+ </div>
+ </header>
+ ) : (
+ <header className="flex items-center justify-between gap-4 border-b border-line bg-ink px-5 pb-4 pt-[calc(1rem+env(safe-area-inset-top))] lg:hidden">
+ <img src="/logo.svg" alt="Infradeck" className="h-[17px] w-auto" />
+ <span className="truncate text-[11px] text-muted">{instance.bootstrapRequired ? 'new install' : instance.name}</span>
+ </header>
+ )}
+
+ <main className="flex min-w-0 flex-1 flex-col px-5 lg:px-10">
+ <div className="flex flex-1 flex-col pb-8 pt-8 lg:items-center lg:justify-center lg:py-12">
+ <div className="w-full lg:w-[380px]">{children}</div>
+ </div>
+ <footer className="flex flex-wrap items-center justify-center gap-x-6 gap-y-1 pb-[calc(1.25rem+env(safe-area-inset-bottom))] text-xs text-dim lg:pb-6">
+ <span>Self-hosted · your data stays on this machine</span>
+ <a href={DOCS_URL} target="_blank" rel="noreferrer" className="hidden hover:text-soft lg:inline">Docs</a>
+ <a href={REPOSITORY_URL} target="_blank" rel="noreferrer" className="hidden hover:text-soft lg:inline">GitHub</a>
+ </footer>
+ </main>
+ </div>
+ )
+}
+
+function Heading({ title, children }) {
+ return <>
+ <h1 className="m-0 text-2xl font-semibold leading-8 text-paper">{title}</h1>
+ {children && <p className="mb-0 mt-2 text-sm leading-[21px] text-muted">{children}</p>}
+ </>
+}
+
+const strong = 'font-medium text-paper'
+const inputClass = 'auth-input'
+
+function Field({ label, aside, children }) {
+ return (
+ <label className="mt-[22px] block first:mt-0">
+ <span className="mb-2 flex items-baseline justify-between gap-3 text-[13px] text-soft"><span>{label}</span>{aside}</span>
+ {children}
+ </label>
+ )
+}
+
+function PasswordInput({ value, onChange, ...props }) {
+ const [shown, setShown] = useState(false)
+ return (
+ <span className="relative block">
+ <input {...props} type={shown ? 'text' : 'password'} value={value} onChange={onChange} className={`${inputClass} pr-16`} />
+ <button type="button" onClick={() => setShown((visible) => !visible)} aria-pressed={shown} aria-label={shown ? 'Hide password' : 'Show password'} className="absolute right-1 top-1 flex h-[34px] items-center rounded px-3 text-xs text-muted hover:text-paper">{shown ? 'Hide' : 'Show'}</button>
+ </span>
+ )
+}
+
+function Submit({ children, busy, disabled }) {
+ return <button type="submit" disabled={busy || disabled} className="auth-submit">{children}<Icon name="arrow" size={15} /></button>
+}
+
+function Problem({ children }) {
+ if (!children) return null
+ return <div role="alert" className="mt-4 rounded-md border border-warn/40 px-3.5 py-2.5 text-[13px] leading-5 text-warn">{children}</div>
+}
+
+function Quiet({ children }) {
+ return <p className="mb-0 mt-5 text-center text-[13px] leading-5 text-muted">{children}</p>
+}
+
+const quietLink = 'font-medium text-paper underline decoration-muted underline-offset-4 hover:decoration-paper'
+
+// Six boxes, one digit each. Typing moves on, backspace moves back, pasting a code fills them all, and the
+// form sends itself after the sixth digit.
+function CodeBoxes({ value, onChange, onComplete, disabled }) {
+ const refs = useRef([])
+ const digits = Array.from({ length: CODE_LENGTH }, (_, index) => value[index] || '')
+ const focus = (index) => refs.current[Math.max(0, Math.min(CODE_LENGTH - 1, index))]?.focus()
+ const apply = (next, from) => {
+ const clean = next.replace(/\D/g, '').slice(0, CODE_LENGTH)
+ onChange(clean)
+ focus(Math.min(clean.length, from))
+ if (clean.length === CODE_LENGTH) onComplete(clean)
+ }
+ const onInput = (index, typed) => {
+ const added = typed.replace(/\D/g, '')
+ if (!added) return
+ // More than one character means a paste or an autofilled one-time code: it replaces from this box on.
+ apply(value.slice(0, index) + added + (added.length > 1 ? '' : value.slice(index + 1)), index + added.length)
+ }
+ const onKeyDown = (index, event) => {
+ if (event.key === 'Backspace') {
+ event.preventDefault()
+ const target = digits[index] ? index : index - 1
+ if (target >= 0) { onChange(value.slice(0, target) + value.slice(target + 1)); focus(target) }
+ } else if (event.key === 'ArrowLeft') { event.preventDefault(); focus(index - 1) } else if (event.key === 'ArrowRight') { event.preventDefault(); focus(index + 1) }
+ }
+ return (
+ <div className="flex justify-between gap-2" role="group" aria-label="6-digit code">
+ {digits.map((digit, index) => (
+ <input key={index} ref={(element) => { refs.current[index] = element }} value={digit} disabled={disabled} autoFocus={index === 0}
+ inputMode="numeric" pattern="[0-9]*" autoComplete={index === 0 ? 'one-time-code' : 'off'} aria-label={`Digit ${index + 1}`}
+ onChange={(event) => onInput(index, event.target.value)} onKeyDown={(event) => onKeyDown(index, event)}
+ onPaste={(event) => { event.preventDefault(); apply(value.slice(0, index) + event.clipboardData.getData('text'), CODE_LENGTH) }}
+ onFocus={(event) => event.target.select()} className="auth-digit" />
+ ))}
+ </div>
+ )
+}
+
+function TwoFactorStep({ instance, email, pendingToken, onDone, onBack }) {
+ const [code, setCode] = useState('')
+ const [recovery, setRecovery] = useState(false)
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+
+ const verify = async (value) => {
+ if (busy) return
+ setBusy(true); setError('')
+ try {
+ onDone(await apiRequest('/auth/login/2fa', { method: 'POST', body: JSON.stringify({ pending_token: pendingToken, code: value.trim() }) }))
+ } catch (requestError) {
+ // An expired or used-up sign-in can't be retried; start again from the password.
+ if (requestError.status === 401 && /sign in again|expired/i.test(requestError.message || '')) { onBack(requestError.message); return }
+ setError(requestError.message || 'That code is not valid.')
+ setCode('')
+ setBusy(false)
+ }
+ }
+
+ return (
+ <AuthFrame instance={instance}>
+ <form onSubmit={(event) => { event.preventDefault(); if (!recovery && code.length < CODE_LENGTH) setError('Type all six digits of the code.'); else if (code.trim()) verify(code) }}>
+ <Heading title="Enter your code">Signed in as <span className={strong}>{email}</span>. {recovery ? 'Type one of the recovery codes you saved when you turned two-factor on.' : 'Open your authenticator app and type the 6-digit code.'}</Heading>
+ <div className="mt-6">
+ {recovery
+ ? <input key="recovery" autoFocus value={code} onChange={(event) => setCode(event.target.value)} maxLength={32} autoComplete="off" autoCapitalize="none" spellCheck={false} aria-label="Recovery code" placeholder="xxxx-xxxx-xxxx" className={`${inputClass} mono tracking-wider`} />
+ : <CodeBoxes key="digits" value={code} onChange={setCode} onComplete={verify} disabled={busy} />}
+ </div>
+ <Problem>{error}</Problem>
+ <div className="mt-[22px]"><Submit busy={busy}>{busy ? 'Checking…' : 'Verify'}</Submit></div>
+ <Quiet>{recovery ? 'Have your phone after all? ' : 'Lost your phone? '}<button type="button" className={quietLink} onClick={() => { setRecovery((mode) => !mode); setCode(''); setError('') }}>{recovery ? 'Use the 6-digit code' : 'Use a recovery code'}</button></Quiet>
+ <p className="mb-0 mt-3 text-center text-[13px]"><button type="button" className="text-muted underline decoration-edge underline-offset-4 hover:text-paper" onClick={() => onBack('')}>Back to sign in</button></p>
+ </form>
+ </AuthFrame>
+ )
+}
+
+export function LoginPage({ onLogin }) {
+ const navigate = useNavigate()
+ const instance = useInstance()
+ const [email, setEmail] = useState('')
+ const [password, setPassword] = useState('')
+ const [remember, setRemember] = useState(true)
+ const [pendingToken, setPendingToken] = useState(null)
+ const [forgot, setForgot] = useState(false)
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+
+ const finish = (data) => {
+ const setupRequired = Boolean(data.setup_required)
+ onLogin({ id: data.user.id, name: data.user.name, email: data.user.email, role: data.user.role, setup_required: setupRequired })
+ navigate(setupRequired ? '/account' : landingPath())
+ }
+
+ const handleSubmit = async (event) => {
+ event.preventDefault()
+ setBusy(true); setError('')
+ try {
+ const data = await apiRequest('/auth/login', { method: 'POST', body: JSON.stringify({ email, password, remember }) })
+ if (data.status === 'two_factor_required') {
+ setPassword('')
+ setPendingToken(data.pending_token)
+ return
+ }
+ finish(data)
+ } catch (requestError) {
+ setError(requestError.message || 'Invalid email or password.')
+ } finally { setBusy(false) }
+ }
+
+ if (pendingToken) return <TwoFactorStep instance={instance} email={email} pendingToken={pendingToken} onDone={finish} onBack={(message) => { setPendingToken(null); setError(message || '') }} />
+
+ const host = typeof window !== 'undefined' ? window.location.host : ''
+ return (
+ <AuthFrame instance={instance} banner>
+ <form onSubmit={handleSubmit}>
+ <Heading title="Sign in">to <span className={strong}>{instance.name || 'Infradeck'}</span>{host ? ` on ${host}` : ''}</Heading>
+ <div className="mt-6">
+ <Field label="Email"><input type="email" autoComplete="username" autoFocus required value={email} onChange={(event) => setEmail(event.target.value)} className={inputClass} /></Field>
+ <Field label="Password" aside={<button type="button" aria-expanded={forgot} onClick={(event) => { event.preventDefault(); setForgot((open) => !open) }} className="text-[13px] text-soft underline decoration-edge underline-offset-4 hover:text-paper">Forgot it?</button>}>
+ <PasswordInput autoComplete="current-password" required value={password} onChange={(event) => setPassword(event.target.value)} />
+ </Field>
+ {forgot && <p className="mb-0 mt-3 rounded-md border border-line bg-ink px-3.5 py-3 text-[13px] leading-5 text-muted">Infradeck doesn't send email, so it can't mail you a reset link. Ask an admin of this install to help you back in. If you are the only admin, you can create a new admin account from the server: <span className="mono text-soft">docker compose exec -it backend python src/backend/seed_user.py</span></p>}
+ <label className="mt-[22px] flex cursor-pointer items-center gap-2.5 text-[13px] text-soft">
+ <input type="checkbox" checked={remember} onChange={(event) => setRemember(event.target.checked)} className="auth-check" />
+ Keep me signed in for 30 days
+ </label>
+ </div>
+ <Problem>{error}</Problem>
+ <div className="mt-[22px]"><Submit busy={busy}>{busy ? 'Signing in…' : 'Sign in'}</Submit></div>
+ {instance.enabled === true && <Quiet>New to this Infradeck? <Link to="/register" className={quietLink}>{instance.bootstrapRequired ? 'Set it up' : 'Register'}</Link></Quiet>}
+ {instance.enabled === false && <Quiet>Accounts are created by an admin.<span className="lg:hidden"><br /></span> Ask the owner for an invite.</Quiet>}
+ </form>
+ </AuthFrame>
+ )
+}
+
+const byteLength = (text) => new TextEncoder().encode(text).length
+
+// Whether the password is long enough, checked as it is typed. On a phone a four-part bar fills up to the rule.
+function PasswordRule({ password, extra }) {
+ const met = password.length >= MIN_PASSWORD_LENGTH
+ const tooLong = byteLength(password) > MAX_PASSWORD_BYTES
+ const filled = Math.min(4, Math.floor((password.length / MIN_PASSWORD_LENGTH) * 4))
+ return <>
+ <span aria-hidden="true" className="mt-2 flex gap-1 lg:hidden">{[0, 1, 2, 3].map((part) => <span key={part} className={`h-[3px] flex-1 rounded-sm ${part < filled ? 'bg-paper' : 'bg-edge'}`} />)}</span>
+ <span className={`mt-2.5 flex items-center gap-1.5 text-xs ${tooLong ? 'text-warn' : met ? 'text-ok' : 'text-muted'}`}>
+ {met && !tooLong && <Icon name="check" size={12} />}
+ {tooLong ? `Too long: at most ${MAX_PASSWORD_BYTES} bytes` : `At least ${MIN_PASSWORD_LENGTH} characters${met ? '' : ` · ${password.length} so far`}`}{extra && !tooLong ? ` · ${extra}` : ''}
+ </span>
+ </>
+}
+
+function SetupTokenHelp() {
+ const [copied, setCopied] = useState(false)
+ const copy = async () => {
+ try { await navigator.clipboard.writeText(SETUP_TOKEN_COMMAND); setCopied(true); setTimeout(() => setCopied(false), 1500) } catch { setCopied(false) }
+ }
+ return (
+ <div className="mt-2.5 rounded-md border border-line bg-ink px-3 py-3 text-xs text-muted">
+ Find it in the backend log:
+ <div className="mt-2.5 flex items-center gap-1.5 rounded border border-line bg-bg py-1.5 pl-2 pr-1.5">
+ <code className="no-scrollbar min-w-0 flex-1 overflow-x-auto whitespace-nowrap font-mono text-[10.5px] text-paper">{SETUP_TOKEN_COMMAND}</code>
+ <button type="button" onClick={copy} aria-label={copied ? 'Copied' : 'Copy the command'} title={copied ? 'Copied' : 'Copy'} className="flex h-6 w-6 shrink-0 items-center justify-center rounded border border-line text-soft hover:text-paper"><Icon name={copied ? 'check' : 'copy'} size={12} /></button>
+ </div>
+ <p className="mb-0 mt-2.5">Or use <span className="mono text-soft">ADMIN_BOOTSTRAP_TOKEN</span> from your .env if you set one.</p>
+ </div>
+ )
+}
+
+export function RegisterPage({ onRegister }) {
+ const navigate = useNavigate()
+ const instance = useInstance()
+ const [form, setForm] = useState({ name: '', email: '', password: '', bootstrapToken: '' })
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ // An invitation link from an admin: it names the email it is for and works while registration is closed.
+ const [params] = useSearchParams()
+ const inviteToken = params.get('invite') || ''
+ const [invite, setInvite] = useState(inviteToken ? undefined : null)
+ useEffect(() => {
+ if (!inviteToken) return undefined
+ let active = true
+ apiRequest(`/auth/invite?token=${encodeURIComponent(inviteToken)}`, { method: 'GET' })
+ .then((data) => { if (active) { setInvite(data); setForm((current) => ({ ...current, email: data.email })) } })
+ .catch(() => { if (active) setInvite(null) })
+ return () => { active = false }
+ }, [inviteToken])
+ const setup = instance.bootstrapRequired
+ const change = (event) => setForm((current) => ({ ...current, [event.target.name]: event.target.value }))
+
+ const handleSubmit = async (event) => {
+ event.preventDefault()
+ const name = form.name.trim()
+ const email = form.email.trim()
+ if (!name || !email || form.password.length < MIN_PASSWORD_LENGTH) {
+ setError(`Please provide a name, an email, and a password of at least ${MIN_PASSWORD_LENGTH} characters.`)
+ return
+ }
+ setBusy(true); setError('')
+ try {
+ const data = await apiRequest('/auth/register', { method: 'POST', body: JSON.stringify({ name, email, password: form.password, bootstrap_token: setup ? form.bootstrapToken.trim() : undefined, invite_token: invite ? inviteToken : undefined }) })
+ onRegister({ id: data.user.id, name: data.user.name, email: data.user.email, role: data.user.role, setup_required: Boolean(data.setup_required) })
+ navigate(data.setup_required ? '/account' : '/')
+ } catch (requestError) {
+ setError(requestError.message || 'Unable to create the account right now.')
+ } finally { setBusy(false) }
+ }
+
+ if (inviteToken && invite === undefined) return <AuthFrame instance={instance}><Heading title="Checking your invitation…" /></AuthFrame>
+ if (instance.enabled === false && !invite) {
+ return (
+ <AuthFrame instance={instance}>
+ <Heading title={inviteToken ? 'This invitation is no longer valid' : 'Registration is closed'}>{inviteToken ? 'It may have been used or have expired. ' : ''}Accounts on <span className={strong}>{instance.name || 'this Infradeck'}</span> are created by an admin. Ask the owner for an invite.</Heading>
+ <Quiet>Already have an account? <Link to="/login" className={quietLink}>Sign in</Link></Quiet>
+ </AuthFrame>
+ )
+ }
+
+ return (
+ <AuthFrame instance={instance}>
+ <form onSubmit={handleSubmit}>
+ {setup
+ ? <Heading title="Set up Infradeck"><span className="lg:hidden">No accounts yet. This one becomes the <span className={strong}>admin</span>.</span><span className="hidden lg:inline">This install has no accounts yet. The account you create now becomes the <span className={strong}>admin</span>.</span></Heading>
+ : <Heading title="Create your account">on <span className={strong}>{instance.name || 'this Infradeck'}</span></Heading>}
+ <div className="mt-6">
+ <Field label="Full name"><input type="text" name="name" autoComplete="name" autoFocus required value={form.name} onChange={change} className={inputClass} /></Field>
+ <Field label="Email" aside={invite ? <span className="text-xs text-muted">from your invitation</span> : null}><input type="email" name="email" autoComplete="username" required readOnly={Boolean(invite)} value={form.email} onChange={change} className={inputClass} /></Field>
+ <Field label="Password">
+ <PasswordInput name="password" autoComplete="new-password" required minLength={MIN_PASSWORD_LENGTH} value={form.password} onChange={change} />
+ <PasswordRule password={form.password} extra={setup ? `up to ${MAX_PASSWORD_BYTES} bytes` : ''} />
+ {!setup && <span className="mt-2 block text-xs leading-[18px] text-muted">A few random words make a good passphrase, like “correct horse battery staple”. Up to {MAX_PASSWORD_BYTES} bytes.</span>}
+ </Field>
+ {setup && <>
+ <Field label={<span className="font-medium text-paper">Setup token</span>} aside={<span className="hidden text-[13px] text-muted lg:inline">proves you run this server</span>}>
+ <input type="text" name="bootstrapToken" autoComplete="off" autoCapitalize="none" spellCheck={false} required value={form.bootstrapToken} onChange={change} placeholder="hlb_…" className={`${inputClass} mono`} />
+ </Field>
+ <div className="hidden lg:block"><SetupTokenHelp /></div>
+ <p className="mb-0 mt-2.5 text-xs leading-[19px] text-muted lg:hidden">From the backend log: <span className="mono rounded border border-line bg-ink px-1 py-px text-soft">{SETUP_TOKEN_COMMAND}</span>, or <span className="mono rounded border border-line bg-ink px-1 py-px text-soft">ADMIN_BOOTSTRAP_TOKEN</span> in .env.</p>
+ </>}
+ </div>
+ <Problem>{error}</Problem>
+ <div className="mt-[22px]"><Submit busy={busy}>{busy ? 'Creating…' : setup ? 'Create admin account' : 'Create account'}</Submit></div>
+ {!setup && <Quiet>Already have an account? <Link to="/login" className={quietLink}>Sign in</Link></Quiet>}
+ </form>
+ </AuthFrame>
+ )
+}
diff --git a/src/frontend/src/charts.jsx b/src/frontend/src/charts.jsx
deleted file mode 100644
index b395353..0000000
--- a/src/frontend/src/charts.jsx
+++ /dev/null
@@ -1,143 +0,0 @@
-// Chart components drawn with plain SVG: no charting library, so there is nothing extra to trust or update, and
-// every label from the server is rendered as text by React, never as HTML.
-import { useEffect, useMemo, useRef, useState } from 'react'
-import { formatDateTime, formatTime, niceTicks, splitRuns, summarise } from './chartMath.js'
-
-const MARGIN = { top: 10, right: 12, bottom: 24, left: 40 }
-
-// The width of an element in pixels, kept up to date, so SVG text stays crisp at any screen size.
-function useElementWidth(ref, fallback = 640) {
- const [width, setWidth] = useState(fallback)
- useEffect(() => {
- const element = ref.current
- if (!element) return undefined
- const update = () => setWidth(Math.max(Math.round(element.getBoundingClientRect().width), 200))
- update()
- if (typeof ResizeObserver === 'undefined') return undefined
- const observer = new ResizeObserver(update)
- observer.observe(element)
- return () => observer.disconnect()
- }, [ref])
- return width
-}
-
-const FIXED_DOMAIN_FALLBACK = [0, 1]
-
-// An average line with a lighter band up to the maximum, over time. Hover or touch shows the exact figures; the
-// whole chart is also available as a table.
-export function TimeSeriesChart({ title, series, bucketSeconds, start, end, unit = '%', color = '#7dd3fc', domain = null, height = 200, utc = false, decimals = 1, limit = null }) {
- const wrapper = useRef(null)
- const width = useElementWidth(wrapper)
- const [hover, setHover] = useState(null)
- const [asTable, setAsTable] = useState(false)
-
- const layout = useMemo(() => {
- const tStart = start ?? (series[0]?.t ?? 0)
- const tEnd = Math.max(end ?? (series[series.length - 1]?.t ?? 1), tStart + 1)
- const values = series.flatMap((point) => [point.avg, point.max]).filter((value) => value !== null)
- if (limit !== null && !domain) values.push(limit / 1.1) // keep the limit line inside the chart
- const [fixedLow, fixedHigh] = domain || FIXED_DOMAIN_FALLBACK
- const yTicks = domain
- ? niceTicks(fixedLow, fixedHigh, 4)
- : niceTicks(0, values.length ? Math.max(...values) * 1.1 : 1, 4)
- const yMax = yTicks[yTicks.length - 1] || fixedHigh
- const plotWidth = Math.max(width - MARGIN.left - MARGIN.right, 50)
- const plotHeight = height - MARGIN.top - MARGIN.bottom
- const x = (t) => MARGIN.left + ((t - tStart) / (tEnd - tStart)) * plotWidth
- const y = (value) => MARGIN.top + plotHeight - (Math.min(Math.max(value, 0), yMax) / yMax) * plotHeight
- const spanSeconds = (tEnd - tStart) / 1000
- const tickCount = Math.max(2, Math.min(7, Math.floor(plotWidth / 110)))
- const xTicks = Array.from({ length: tickCount }, (_, index) => tStart + ((tEnd - tStart) * index) / (tickCount - 1))
- return { tStart, tEnd, yTicks, yMax, plotWidth, plotHeight, x, y, spanSeconds, xTicks }
- }, [series, start, end, width, height, domain, limit])
-
- const runs = useMemo(() => splitRuns(series, bucketSeconds), [series, bucketSeconds])
- const format = (value) => (value === null || value === undefined ? '–' : `${value.toFixed(decimals)}${unit === '%' ? '%' : ` ${unit}`.trimEnd()}`)
-
- if (!series.length) {
- return (
- <figure className="min-w-0 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 p-4">
- <figcaption className="text-sm font-medium text-white">{title}</figcaption>
- <div className="mt-3 flex items-center justify-center rounded-xl border border-dashed border-neutral-800 text-xs text-[#7f8589]" style={{ height }}>No data for this range yet</div>
- </figure>
- )
- }
-
- const move = (event) => {
- const box = wrapper.current?.getBoundingClientRect()
- if (!box) return
- const px = event.clientX - box.left
- let best = null
- for (const point of series) {
- const distance = Math.abs(layout.x(point.t) - px)
- if (best === null || distance < best.distance) best = { point, distance }
- }
- setHover(best && best.distance < 60 ? best.point : null)
- }
- const label = `${title}: average ${format(summarise(series).average)}, highest ${format(summarise(series).maximum)}`
-
- return (
- <figure className="min-w-0 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 p-4">
- <div className="flex items-center justify-between gap-3">
- <figcaption className="text-sm font-medium text-white">{title}</figcaption>
- <button type="button" onClick={() => setAsTable((value) => !value)} className="rounded-lg border border-white/10 px-2 py-1 text-[11px] text-[#9aa0a6] hover:text-white">{asTable ? 'View as chart' : 'View as table'}</button>
- </div>
- {asTable ? (
- <div className="mt-3 max-h-64 overflow-auto rounded-xl border border-[#1f2326]">
- <table className="w-full text-left text-xs text-[#bcbcbc]">
- <thead className="sticky top-0 bg-[#111417] text-[#9aa0a6]"><tr><th className="px-3 py-2 font-medium">Time</th><th className="px-3 py-2 font-medium">Average</th><th className="px-3 py-2 font-medium">Highest</th><th className="px-3 py-2 font-medium">Check-ins</th></tr></thead>
- <tbody>{series.map((point) => <tr key={point.t} className="border-t border-[#1f2326]"><td className="px-3 py-1.5">{formatDateTime(point.t, utc)}</td><td className="px-3 py-1.5">{format(point.avg)}</td><td className="px-3 py-1.5">{format(point.max)}</td><td className="px-3 py-1.5">{point.samples}</td></tr>)}</tbody>
- </table>
- </div>
- ) : (
- <div ref={wrapper} className="relative mt-2 w-full min-w-0 touch-pan-y select-none overflow-hidden" onPointerMove={move} onPointerLeave={() => setHover(null)} onPointerDown={move}>
- <svg width={width} height={height} role="img" aria-label={label} className="block">
- {layout.yTicks.map((tick) => (
- <g key={tick}>
- <line x1={MARGIN.left} x2={width - MARGIN.right} y1={layout.y(tick)} y2={layout.y(tick)} stroke="#ffffff" strokeOpacity="0.07" />
- <text x={MARGIN.left - 6} y={layout.y(tick) + 4} textAnchor="end" fontSize="10" fill="#7f8589">{tick}</text>
- </g>
- ))}
- {layout.xTicks.map((tick, index) => (
- <text key={tick} x={layout.x(tick)} y={height - 6} textAnchor={index === 0 ? 'start' : index === layout.xTicks.length - 1 ? 'end' : 'middle'} fontSize="10" fill="#7f8589">{formatTime(tick, layout.spanSeconds, utc)}</text>
- ))}
- {runs.map((run) => {
- const withMax = run.filter((point) => point.max !== null && point.avg !== null)
- const band = withMax.length > 1
- ? `${withMax.map((point) => `${layout.x(point.t)},${layout.y(point.max)}`).join(' ')} ${[...withMax].reverse().map((point) => `${layout.x(point.t)},${layout.y(point.avg)}`).join(' ')}`
- : null
- const line = run.filter((point) => point.avg !== null)
- return (
- <g key={run[0].t}>
- {band && <polygon points={band} fill={color} fillOpacity="0.22" />}
- {line.length > 1 && <polyline points={line.map((point) => `${layout.x(point.t)},${layout.y(point.avg)}`).join(' ')} fill="none" stroke={color} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />}
- {line.length === 1 && <circle cx={layout.x(line[0].t)} cy={layout.y(line[0].avg)} r="3" fill={color} />}
- </g>
- )
- })}
- {limit !== null && (
- <g pointerEvents="none">
- <line x1={MARGIN.left} x2={width - MARGIN.right} y1={layout.y(limit)} y2={layout.y(limit)} stroke="#f87171" strokeOpacity="0.8" strokeDasharray="5 4" />
- <text x={width - MARGIN.right - 2} y={layout.y(limit) < MARGIN.top + 14 ? layout.y(limit) + 12 : layout.y(limit) - 4} textAnchor="end" fontSize="10" fill="#f87171">limit {limit.toFixed(0)} {unit}</text>
- </g>
- )}
- {hover && (
- <g pointerEvents="none">
- <line x1={layout.x(hover.t)} x2={layout.x(hover.t)} y1={MARGIN.top} y2={height - MARGIN.bottom} stroke="#ffffff" strokeOpacity="0.35" />
- {hover.avg !== null && <circle cx={layout.x(hover.t)} cy={layout.y(hover.avg)} r="4" fill={color} stroke="#0d1013" strokeWidth="2" />}
- </g>
- )}
- </svg>
- {hover && (
- <div role="status" className="pointer-events-none absolute z-10 rounded-xl border border-white/10 bg-[#111417]/95 px-3 py-2 text-xs text-[#e6e7ea] shadow-lg" style={{ top: 0, left: Math.min(Math.max(layout.x(hover.t) - 70, 0), Math.max(width - 150, 0)) }}>
- <div className="text-[#9aa0a6]">{formatDateTime(hover.t, utc)}</div>
- <div>Average <span className="font-medium text-white">{format(hover.avg)}</span></div>
- <div>Highest <span className="font-medium text-white">{format(hover.max)}</span></div>
- <div className="text-[#7f8589]">{hover.samples} check-ins</div>
- </div>
- )}
- </div>
- )}
- </figure>
- )
-}
diff --git a/src/frontend/src/dashboard/Containers.jsx b/src/frontend/src/dashboard/Containers.jsx
new file mode 100644
index 0000000..4f62671
--- /dev/null
+++ b/src/frontend/src/dashboard/Containers.jsx
@@ -0,0 +1,300 @@
+// Containers grouped by compose project: the summary card under a server's Overview and the full Containers tab.
+import { useEffect, useMemo, useState } from 'react'
+import { Link } from 'react-router-dom'
+import { apiRequest } from '../api.js'
+import { problemRank } from '../containerLogic.js'
+import { Caret, Icon } from '../icons.jsx'
+import { LineChart, Meter, Sparkline } from './charts.jsx'
+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]'
+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|homelab|homie/i
+
+function statusTone(container) {
+ if (container.status === 'running') return container.healthcheck_status === 'unhealthy' ? 'text-signal' : 'text-ok'
+ return container.status === 'restarting' ? 'text-signal' : 'text-warn'
+}
+
+function StatusText({ 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 <span className="block truncate text-xs" title={[container.status, extra].filter(Boolean).join(' · ')}><span className={statusTone(container)}>{container.status}</span>{extra && <span className={extra === 'unhealthy' || extra === 'out of memory' ? 'text-signal' : 'text-muted'}> · {extra}</span>}</span>
+}
+
+// Published ports as chips; databases and admin panels that other machines can reach are amber.
+function PortChips({ container, scopes }) {
+ const ports = parsePorts(container.ports)
+ if (!ports.length) return <span className="text-xs text-muted">none</span>
+ const byHost = new Map()
+ for (const port of ports) {
+ const entry = byHost.get(port.host) || { host: port.host, protos: [] }
+ entry.protos.push(port.proto)
+ byHost.set(port.host, entry)
+ }
+ const chips = []
+ for (const entry of byHost.values()) {
+ const scope = entry.protos.map((proto) => scopes.get(`${proto}/${entry.host}`)).find(Boolean)
+ const risky = scope !== 'loopback' && entry.protos.some((proto) => classifyPort(proto, entry.host, container).risky)
+ const proto = entry.protos.length > 1 ? 'tcp+udp' : entry.protos[0] === 'udp' ? 'udp' : ''
+ const last = chips[chips.length - 1]
+ if (last && !risky && !last.risky && last.proto === proto && last.hosts[last.hosts.length - 1] === entry.host - 1) last.hosts.push(entry.host)
+ else chips.push({ hosts: [entry.host], proto, risky, note: risky && scope === 'any' ? 'all interfaces' : '' })
+ }
+ const shown = chips.slice(0, 3)
+ return (
+ <span className="flex min-w-0 items-center gap-1 overflow-hidden">
+ {shown.map((chip) => <span key={chip.hosts[0]} className={`port ${chip.risky ? 'port-risky' : ''}`} title={chip.risky ? 'A database or admin panel that other machines can reach' : undefined}>{collapseRanges(chip.hosts).join(', ')}{(chip.proto || chip.note) && <span>{[chip.proto, chip.note].filter(Boolean).join(' ')}</span>}</span>)}
+ {chips.length > shown.length && <span className="text-[11px] text-muted">+{chips.length - shown.length}</span>}
+ </span>
+ )
+}
+
+function Facts({ items }) {
+ return <dl className="kv m-0" style={{ '--kv-label': '72px' }}>{items.map(([label, value, mono]) => <div key={label} className="contents"><dt>{label}</dt><dd className={`break-words text-paper ${mono ? 'mono break-all' : ''}`} title={typeof value === 'string' ? value : undefined}>{value}</dd></div>)}</dl>
+}
+
+function ContainerDetails({ server, container }) {
+ const [detail, setDetail] = useState(null)
+ const [error, setError] = useState('')
+ // Re-fetch whenever the overview poll brings in a newer sample for this container.
+ const sampleTime = container.time
+
+ useEffect(() => {
+ let active = true
+ apiRequest(`/monitoring/servers/${server.id}/containers/${encodeURIComponent(container.container_id)}?limit=60`, { method: 'GET' })
+ .then((data) => { if (active) { setDetail(data); setError('') } })
+ .catch((requestError) => { if (active) setError(requestError.message || 'Could not load container details.') })
+ return () => { active = false }
+ }, [server.id, container.container_id, sampleTime])
+
+ if (error) return <div className="border-l-2 border-warn bg-bg px-[18px] py-4 text-xs text-warn">{error}</div>
+ if (!detail) return <div className="border-l-2 border-paper bg-bg px-[18px] py-4 text-xs text-muted">Loading container details…</div>
+
+ const latest = detail.latest
+ const history = detail.history
+ const hostMb = (server.total_ram_gb || 0) * 1024
+ const limited = latest.memory_limit_mb && (!hostMb || latest.memory_limit_mb < hostMb * 0.98)
+ const span = history.length > 1 ? (new Date(history[history.length - 1].time) - new Date(history[0].time)) / 1000 : 0
+ const window = span ? `last ${formatSpan(span)}` : 'recent'
+ const cpuMax = Math.max(100, niceCeiling(Math.max(0, ...history.map((sample) => sample.cpu_pct ?? 0))))
+ const memoryPeak = Math.max(1, ...history.map((sample) => sample.memory_used_mb ?? 0))
+ const inGb = memoryPeak >= 1024
+ const memoryMax = niceCeiling((inGb ? memoryPeak / 1024 : memoryPeak) * 1.3)
+ const volumes = collapsePaths(detail.volumes)
+ const checked = formatSpan((Date.now() - new Date(latest.time).getTime()) / 1000)
+ return (
+ <div className="grid border-l-2 border-paper bg-bg lg:grid-cols-[312px_minmax(0,1fr)_minmax(0,1fr)] lg:divide-x lg:divide-line">
+ <div className="min-w-0 px-[18px] py-4">
+ <Facts items={[
+ ['ID', detail.container_id.slice(0, 12), true],
+ ['Health', latest.healthcheck_status ? `${latest.healthcheck_status} · checked ${checked} ago` : `no healthcheck · seen ${checked} ago`],
+ ['Limit', limited ? formatMegabytes(latest.memory_limit_mb) : `none${hostMb ? ` (can use ${Number(server.total_ram_gb.toFixed(1))} GB)` : ''}`],
+ ['Processes', latest.pids ?? '—'],
+ ['Volumes', volumes.length ? volumes.join(', ') : 'none', true],
+ ]} />
+ <div className="mt-4 grid grid-cols-2 gap-x-4">
+ <div><div className="text-[11px] text-muted">Network in / out</div><div className="mt-1 whitespace-nowrap text-[13px] font-semibold text-paper">{formatMegabytes(latest.net_rx_mb)} / {formatMegabytes(latest.net_tx_mb)}</div></div>
+ <div><div className="text-[11px] text-muted">Disk read / write</div><div className="mt-1 whitespace-nowrap text-[13px] font-semibold text-paper">{formatMegabytes(latest.block_read_mb)} / {formatMegabytes(latest.block_write_mb)}</div></div>
+ </div>
+ <div className="mt-4 flex flex-wrap gap-1.5">
+ <button type="button" className="btn btn-sm" disabled title={READ_ONLY_NOTE}><Icon name="logs" size={13} />Logs</button>
+ <button type="button" className="btn btn-sm" disabled title={READ_ONLY_NOTE}><Icon name="restart" size={13} />Restart</button>
+ <Link to="/agent" className="btn btn-sm"><Icon name="agent" size={13} />Ask the agent</Link>
+ </div>
+ </div>
+ <div className="min-w-0 px-[18px] py-4">
+ <div className="mb-3 flex items-baseline justify-between"><span className="text-xs font-medium text-soft">CPU · {window}</span><span className="text-[15px] font-semibold text-paper">{formatPercent(latest.cpu_pct)}</span></div>
+ <LineChart label={`CPU use of ${detail.name}`} points={history.map((sample) => ({ time: sample.time, value: sample.cpu_pct }))} max={cpuMax} ticks={[cpuMax, cpuMax / 2, 0]} format={(tick) => `${tick}%`} area height={92} />
+ <p className="mb-0 mt-3 text-[11px] text-muted">Can pass 100% when the container uses more than one core.</p>
+ </div>
+ <div className="min-w-0 px-[18px] py-4">
+ <div className="mb-3 flex items-baseline justify-between"><span className="text-xs font-medium text-soft">Memory · {window}</span><span className="text-[15px] font-semibold text-paper">{formatMegabytes(latest.memory_used_mb)}</span></div>
+ <LineChart label={`Memory use of ${detail.name}`} points={history.map((sample) => ({ time: sample.time, value: sample.memory_used_mb == null ? null : inGb ? sample.memory_used_mb / 1024 : sample.memory_used_mb }))} max={memoryMax} ticks={[memoryMax, memoryMax / 2, 0]} format={(tick) => `${Number(tick.toFixed(1))} ${inGb ? 'GB' : 'MB'}`} area height={92} gutter={46} />
+ <p className="mb-0 mt-3 text-[11px] text-muted">Totals for network and disk count from container start.</p>
+ </div>
+ </div>
+ )
+}
+
+function ContainerRow({ server, container, sparkline, scopes, expanded, onToggle }) {
+ const hostMb = (server.total_ram_gb || 0) * 1024
+ const share = hostMb && container.memory_used_mb != null ? (container.memory_used_mb / hostMb) * 100 : null
+ const problem = problemRank(container)
+ return <>
+ <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="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">
+ <span className="flex items-baseline justify-between gap-2"><span className="text-xs font-medium text-paper">{formatMegabytes(container.memory_used_mb)}</span>{share != null && share >= 10 && <span className="truncate text-[11px] text-muted">{Math.round(share)}% of host</span>}</span>
+ <Meter className="mt-1" percent={share} label={`${container.name} memory share of the host`} />
+ </span>
+ <PortChips container={container} scopes={scopes} />
+ <span className="truncate text-right text-xs text-soft">{containerUptime(container.started_at) || '—'}</span>
+ <span className={`text-right text-xs ${container.restart_count ? 'text-warn' : 'text-paper'}`}>{container.restart_count}</span>
+ </button>
+ {expanded && <div className="border-t border-line"><ContainerDetails server={server} container={container} /></div>}
+ </>
+}
+
+function summary(containers) {
+ const count = (test) => containers.filter(test).length
+ const restarting = count((container) => container.status === 'restarting')
+ const unhealthy = count((container) => container.healthcheck_status === 'unhealthy' && container.status === 'running')
+ const stopped = count(CONTAINER_FILTERS.stopped)
+ const parts = [restarting ? `${restarting} restarting` : null, unhealthy ? `${unhealthy} unhealthy` : null, stopped ? `${stopped} stopped` : null].filter(Boolean)
+ return parts.length ? parts.join(' · ') : 'all running'
+}
+
+// Filter, sort and grouping state shared by the card and the tab, plus which groups and rows are open.
+function useContainerView(server, { rowLimit, openFirst }) {
+ const [query, setQuery] = useState('')
+ const [filter, setFilter] = useState('all')
+ const [sort, setSort] = useState('cpu')
+ const [grouped, setGrouped] = useState(true)
+ const [toggled, setToggled] = useState({})
+ const [unfolded, setUnfolded] = useState(() => new Set())
+ const [expandedId, setExpandedId] = useState(null)
+ const containers = server.containers || []
+ const reachable = useMemo(() => reachablePortSet(server), [server])
+ const scopes = useMemo(() => new Map((server.network?.listeners || []).map((listener) => [`${listener.proto}/${listener.port}`, listener.scope])), [server])
+ 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 narrowed = needle !== '' || filter !== 'all'
+ 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, grouped })
+ const isOpen = (group, index) => toggled[group.name] ?? (narrowed || group.problems > 0 || (openFirst && (index === 0 || group.name === STANDALONE)) || !grouped)
+ return {
+ query, setQuery, filter, setFilter, sort, setSort, grouped, setGrouped, counts, groups, scopes, narrowed, expandedId,
+ toggleRow: (id) => setExpandedId((current) => (current === id ? null : id)),
+ isOpen, toggleGroup: (group, index) => setToggled((current) => ({ ...current, [group.name]: !isOpen(group, index) })),
+ openGroup: (name) => setToggled((current) => ({ ...current, [name]: true })),
+ limitFor: (group) => (narrowed || unfolded.has(group.name) || !grouped ? Infinity : rowLimit),
+ unfold: (name) => setUnfolded((current) => new Set(current).add(name)),
+ }
+}
+
+function Toolbar({ view, filters, server, showSort }) {
+ return <>
+ <label className="relative block w-full max-w-[262px]">
+ <Icon name="search" size={14} className="pointer-events-none absolute left-3 top-[9px] text-muted" />
+ <input type="search" className="field pl-9" value={view.query} onChange={(event) => view.setQuery(event.target.value)} placeholder="Filter by name, image or port" aria-label={`Filter containers on ${server.hostname}`} />
+ </label>
+ <div className="seg" role="group" aria-label="Show">
+ {filters.map((key) => <button key={key} type="button" aria-pressed={view.filter === key} onClick={() => view.setFilter(key)}>{FILTER_LABELS[key]} {view.counts[key]}</button>)}
+ </div>
+ <span className="ml-auto flex items-center gap-3">
+ {showSort && <label className="flex items-center gap-3 text-xs text-muted">Sort
+ <select className="select" value={view.sort} onChange={(event) => view.setSort(event.target.value)}><option value="cpu">CPU</option><option value="memory">Memory</option><option value="name">Name</option></select>
+ </label>}
+ <select className="select" aria-label="Grouping" value={view.grouped ? 'project' : 'none'} onChange={(event) => view.setGrouped(event.target.value === 'project')}><option value="project">Group: project</option><option value="none">Group: none</option></select>
+ </span>
+ </>
+}
+
+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={`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>
+ </div>
+ {view.groups.map((group, index) => {
+ const open = view.isOpen(group, index)
+ const limit = view.limitFor(group)
+ const visible = group.containers.slice(0, limit)
+ const hidden = group.containers.slice(limit)
+ const appGroup = server.is_dashboard_host && group.name !== null && APP_PROJECT.test(group.name)
+ const totals = `${group.count} ${group.count === 1 ? 'container' : 'containers'} · ${formatPercent(group.cpu)} CPU · ${formatMegabytesShort(group.memoryMb)}`
+ return (
+ <div key={group.name ?? 'all'}>
+ {group.name !== null && (
+ <button type="button" onClick={() => view.toggleGroup(group, index)} aria-expanded={open} className="flex h-[38px] w-full items-center gap-2.5 border-0 border-t border-solid border-line bg-sunken px-[18px] text-left hover:bg-raised">
+ <Caret open={open} className="text-muted" />
+ <span className="text-[13px] font-semibold text-paper">{group.name}</span>
+ {appGroup && <span className="chip">this app</span>}
+ <span className="min-w-0 truncate text-xs text-muted">{totals}{!open && appGroup ? ` · ${group.containers.map((container) => container.name).sort().join(', ')}` : ''}</span>
+ {group.problems > 0 && <span className="chip chip-signal ml-1">{group.problems} {group.problems === 1 ? 'problem' : 'problems'}</span>}
+ </button>
+ )}
+ {open && <>
+ {visible.map((container) => <ContainerRow key={container.container_id} server={server} container={container} sparkline={sparklines?.[container.container_id]} scopes={view.scopes} expanded={view.expandedId === container.container_id} onToggle={() => view.toggleRow(container.container_id)} />)}
+ {hidden.length > 0 && <button type="button" onClick={() => view.unfold(group.name)} className="block h-10 w-full truncate border-0 border-t border-solid border-line bg-transparent pl-[58px] pr-[18px] text-left text-xs text-muted hover:bg-raised hover:text-soft">{hidden.length} more · {hidden.map((container) => container.name).sort().join(', ')}</button>}
+ </>}
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ )
+}
+
+// Under a server's Overview: the same table in short, or just the group names when nothing is wrong anywhere.
+export function ContainersCard({ server, sparklines, calm }) {
+ const view = useContainerView(server, { rowLimit: 5, openFirst: true })
+ const [showTable, setShowTable] = useState(false)
+ const containers = server.containers || []
+ if (!containers.length) return null
+ const collapsed = calm && !showTable && !view.narrowed && !view.groups.some((group) => group.problems)
+ return (
+ <section className="card overflow-hidden" aria-label={`Containers on ${server.hostname}`}>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2.5 px-[18px] py-3">
+ <h2 className="m-0 text-sm font-semibold text-paper">Containers</h2>
+ <span className="mr-auto text-xs text-muted">{containers.length} on {server.hostname} · {summary(containers)}</span>
+ <Toolbar view={view} filters={['all', 'problems', 'exposed', 'restarted']} server={server} />
+ </div>
+ {collapsed ? <>
+ <div className="flex flex-wrap gap-2.5 border-t border-line px-[18px] py-3.5">
+ {view.groups.map((group) => <button key={group.name ?? 'all'} type="button" className="chip h-[22px] cursor-pointer text-paper hover:border-muted" onClick={() => { view.openGroup(group.name); setShowTable(true) }}>{(group.name ?? 'all').toLowerCase()} · {group.count}</button>)}
+ </div>
+ <p className="m-0 border-t border-line px-[18px] py-3 text-xs text-muted">All groups collapsed because nothing is wrong. A group opens by itself when one of its containers has a problem.</p>
+ </> : <ContainerTable server={server} view={view} sparklines={sparklines} />}
+ </section>
+ )
+}
+
+function Stat({ label, value, unit, tone }) {
+ return (
+ <div className="min-w-0 px-[18px] py-3">
+ <div className="truncate text-[11px] text-muted">{label}</div>
+ <div className="mt-1.5 whitespace-nowrap"><span className={`text-[17px] font-semibold ${tone === 'warn' ? 'text-warn' : tone === 'signal' ? 'text-signal' : 'text-paper'}`}>{value}</span>{unit && <span className="ml-1.5 text-[11px] text-muted">{unit}</span>}</div>
+ </div>
+ )
+}
+
+export function StatStrip({ children, columns }) {
+ return <div className={`grid grid-cols-2 divide-x divide-line border-b border-line ${columns}`}>{children}</div>
+}
+
+export function ContainersTab({ server, sparklines }) {
+ const view = useContainerView(server, { rowLimit: 4, openFirst: true })
+ const containers = server.containers || []
+ if (!containers.length) {
+ return <p className="m-0 px-[18px] 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 running = containers.filter((container) => container.status === 'running').length
+ const unhealthy = containers.filter((container) => container.healthcheck_status === 'unhealthy').length
+ const restarts = containers.reduce((sum, container) => sum + (container.restart_count || 0), 0)
+ const cpu = containers.reduce((sum, container) => sum + (container.cpu_pct ?? 0), 0)
+ const memory = containers.reduce((sum, container) => sum + (container.memory_used_mb ?? 0), 0)
+ const hostMb = (server.total_ram_gb || 0) * 1024
+ return <>
+ <StatStrip columns="md:grid-cols-3 xl:grid-cols-6">
+ <Stat label="Running" value={running} unit={`of ${containers.length}`} tone={running < containers.length ? 'warn' : undefined} />
+ <Stat label="Unhealthy" value={unhealthy} tone={unhealthy ? 'signal' : undefined} />
+ <Stat label="Restarts · since created" value={restarts} tone={restarts ? 'warn' : undefined} />
+ <Stat label="Exposed to network" value={view.counts.exposed} tone={view.counts.exposed ? 'warn' : undefined} />
+ <Stat label="CPU, all containers" value={formatPercent(cpu)} unit={server.cpu_cores ? `of ${server.cpu_cores * 100}%` : undefined} />
+ <Stat label="Memory, all containers" value={formatMegabytesShort(memory)} unit={hostMb ? `${Math.round((memory / hostMb) * 100)}% of host` : undefined} />
+ </StatStrip>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2.5 px-[18px] py-3"><Toolbar view={view} filters={['all', 'problems', 'exposed', 'restarted', 'stopped']} server={server} showSort /></div>
+ <ContainerTable server={server} view={view} sparklines={sparklines} />
+ <p className="m-0 border-t border-line px-[18px] py-3 text-xs text-muted">Click a row for its details and a recent chart. Amber ports are admin panels or databases that other machines can reach.</p>
+ </>
+}
diff --git a/src/frontend/src/dashboard/DashboardPage.jsx b/src/frontend/src/dashboard/DashboardPage.jsx
new file mode 100644
index 0000000..d934142
--- /dev/null
+++ b/src/frontend/src/dashboard/DashboardPage.jsx
@@ -0,0 +1,167 @@
+// The Overview page: what needs you first, then the fleet as a rack, then one server in depth.
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { useNavigate, useSearchParams } from 'react-router-dom'
+import { LIVE_REFRESH_SECONDS, apiRequest } from '../api.js'
+import { Icon } from '../icons.jsx'
+import { refreshOverview, useOverview } from '../overviewStore.js'
+import { AppShell } from '../shell.jsx'
+import { ContainersCard, ContainersTab } from './Containers.jsx'
+import { AnotherMachineCard, EmptyFleet, ThisMachineCard } from './EmptyFleet.jsx'
+import { EventsTab } from './EventsTab.jsx'
+import { FleetRack, rangeLabel } from './FleetRack.jsx'
+import { NeedsAttention, nextToWatch } from './NeedsAttention.jsx'
+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'
+
+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 {
+ const stored = Number(window.localStorage.getItem(RANGE_KEY))
+ return RANGES.includes(stored) ? stored : 30
+ } catch {
+ return 30
+ }
+}
+
+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.`
+}
+
+export default function DashboardPage({ user, onLogout }) {
+ const navigate = useNavigate()
+ const [params, setParams] = useSearchParams()
+ const { data: overview, error } = useOverview(Boolean(user), LIVE_REFRESH_SECONDS, onLogout)
+ const [minutes, setMinutes] = useState(rememberedRange)
+ const [showConnect, setShowConnect] = useState(false)
+ const [actionError, setActionError] = useState('')
+ const [deletingId, setDeletingId] = useState(null)
+ const panelRef = useRef(null)
+ // Regular users get a read-only view; the backend enforces the same rules.
+ const isAdmin = user?.role === 'admin'
+
+ 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 tab = TABS.includes(params.get('tab')) ? params.get('tab') : 'overview'
+ const selectedId = selected?.id ?? null
+
+ const go = (serverId, nextTab, scroll = false) => {
+ const next = new URLSearchParams()
+ next.set('server', String(serverId))
+ if (nextTab && nextTab !== 'overview') next.set('tab', nextTab)
+ setParams(next, { replace: serverId === selectedId })
+ if (scroll) requestAnimationFrame(() => panelRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }))
+ }
+
+ useEffect(() => {
+ try { window.localStorage.setItem(RANGE_KEY, String(minutes)) } catch { /* private windows: keep it for this visit only */ }
+ }, [minutes])
+
+ const pace = Math.max(5, Math.min(selected?.check_interval_seconds || 15, 30))
+ const { data: fleetLines } = usePolled(servers.length ? `/monitoring/sparklines?minutes=${minutes}` : null, 15)
+ const { data: live } = usePolled(selectedId ? `/monitoring/servers/${selectedId}/live?minutes=${minutes}` : null, pace)
+ const showsContainers = selected?.containers?.length > 0 && (tab === 'overview' || tab === 'containers')
+ const { data: containerLines } = usePolled(selectedId && showsContainers ? `/monitoring/servers/${selectedId}/containers/sparklines?minutes=15` : null, 15)
+ const wanted = useMemo(() => {
+ const list = []
+ for (const server of servers) {
+ const mounts = serverMounts(server).filter((mount) => mount.total_gb != null)
+ const fullest = fullestMount(mounts)
+ for (const mount of server.id === selectedId ? mounts : fullest ? [fullest] : []) list.push({ serverId: server.id, mount: mount.mount })
+ }
+ return list
+ }, [servers, selectedId])
+ const forecasts = useForecasts(wanted)
+
+ const changeInterval = async (server, seconds) => {
+ setActionError('')
+ try {
+ await apiRequest(`/monitoring/servers/${server.id}/interval`, { method: 'PATCH', body: JSON.stringify({ check_interval_seconds: seconds }) })
+ await refreshOverview()
+ } catch (requestError) { setActionError(requestError.message || 'Could not update the check interval.') }
+ }
+ const deleteServer = async (server) => {
+ if (!window.confirm(`Remove ${server.hostname} and all its stored metrics and incidents? This cannot be undone.`)) return
+ setDeletingId(server.id); setActionError('')
+ try {
+ await apiRequest(`/monitoring/servers/${server.id}`, { method: 'DELETE' })
+ setParams(new URLSearchParams(), { replace: true })
+ await refreshOverview()
+ } catch (requestError) { setActionError(requestError.message || 'Could not remove the server.') } finally { setDeletingId(null) }
+ }
+ const onAttention = (alert, action) => {
+ if (action.kind === 'network' || action.kind === 'containers') go(alert.server_id, action.kind, true)
+ else if (action.kind === 'trend') navigate(`/statistics?server=${alert.server_id}`)
+ else navigate(`/agent?incident=${alert.id}`)
+ }
+ const openConnect = () => setShowConnect(true)
+
+ const crumbs = selected && tab !== 'overview' ? [{ 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)
+ const samples = live?.samples || []
+
+ let body
+ if (!overview) {
+ body = <p className="m-0 py-24 text-center text-[13px] text-muted">{error || 'Loading the fleet…'}</p>
+ } else if (!servers.length) {
+ body = <EmptyFleet overview={overview} isAdmin={isAdmin} onChanged={refreshOverview} />
+ } else {
+ body = <>
+ <header className="flex flex-wrap items-end justify-between gap-4">
+ <div>
+ <h1 className="m-0 text-[21px] font-semibold leading-7 text-paper">Overview</h1>
+ <p className="mb-0 mt-1.5 text-[13px] text-soft">{headline(servers)}</p>
+ </div>
+ <div className="flex items-center gap-4">
+ <select className="select" aria-label="Chart range" value={minutes} onChange={(event) => setMinutes(Number(event.target.value))}>{RANGES.map((value) => <option key={value} value={value}>Last {rangeLabel(value)}</option>)}</select>
+ {isAdmin && <button type="button" className="btn btn-primary" aria-haspopup="dialog" aria-expanded={showConnect} onClick={openConnect}><Icon name="plus" size={14} />Connect server</button>}
+ </div>
+ </header>
+
+ {(error || actionError) && <div role="alert" className="rounded-md border border-warn/40 px-3.5 py-2.5 text-xs text-warn">{actionError || error}</div>}
+ {isAdmin && waiting.length > 0 && (
+ <div className="flex flex-wrap items-center gap-3 rounded-md border border-edge bg-ink px-3.5 py-2.5 text-xs text-soft">
+ <span className="dot" style={{ background: 'var(--color-paper)' }} />
+ <span><span className="font-medium text-paper">{waiting.map((item) => item.hostname).join(', ')}</span> {waiting.length === 1 ? 'is' : 'are'} asking to join the fleet.</span>
+ <button type="button" className="btn btn-sm ml-auto" onClick={openConnect}>Review</button>
+ </div>
+ )}
+ <NeedsAttention overview={overview} watch={calm ? nextToWatch(servers, forecasts, (server) => fullestMount(serverMounts(server))) : null} onAction={onAttention} />
+ <FleetRack overview={overview} servers={servers} selectedId={selectedId} sparklines={fleetLines?.servers} forecasts={forecasts} minutes={minutes} onSelect={(id) => go(id, tab)} />
+
+ {selected && <div ref={panelRef} className="scroll-mt-20 space-y-7">
+ <ServerPanel server={selected} overview={overview} tab={tab} onTab={(next) => go(selected.id, next)} isAdmin={isAdmin} onInterval={changeInterval} samples={samples} forecasts={forecasts} listening={listeningCount(selected)}>
+ {tab === 'containers' && <ContainersTab key={selected.id} server={selected} sparklines={containerLines?.containers} />}
+ {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} />}
+ </ServerPanel>
+ {tab === 'overview' && <ContainersCard key={`containers-${selected.id}`} server={selected} sparklines={containerLines?.containers} calm={calm} />}
+ {tab === 'overview' && <NetworkCard key={`network-${selected.id}`} server={selected} />}
+ </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.">
+ {pending.some((item) => item.status === 'pending' && item.details?.dashboard_host) && <ThisMachineCard pending={pending} onChanged={refreshOverview} recommended={false} />}
+ <AnotherMachineCard pending={pending} onChanged={refreshOverview} />
+ </Drawer>}
+ </AppShell>
+ )
+}
diff --git a/src/frontend/src/dashboard/EmptyFleet.jsx b/src/frontend/src/dashboard/EmptyFleet.jsx
new file mode 100644
index 0000000..401fe73
--- /dev/null
+++ b/src/frontend/src/dashboard/EmptyFleet.jsx
@@ -0,0 +1,313 @@
+// The first run: an empty rack and the shortest way to fill it. Also the Connect server panel a running fleet opens.
+import { useEffect, useState } from 'react'
+import { API_BASE, apiRequest } from '../api.js'
+import { Icon } from '../icons.jsx'
+import { FLEET_COLUMNS, FleetHeader } from './FleetRack.jsx'
+import { SectionHeading } from './NeedsAttention.jsx'
+import { installCommands } from './logic.js'
+
+const DOCS_URL = 'https://github.com/karloks2005/Infradeck#readme'
+
+function useCopy() {
+ const [copied, setCopied] = useState(false)
+ const copy = async (text) => {
+ try { await navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 1500) } catch { setCopied(false) }
+ }
+ return [copied, copy]
+}
+
+function Notice({ children, tone = 'warn' }) {
+ return <div role="alert" className={`rounded-md border px-3.5 py-2.5 text-xs ${tone === 'warn' ? 'border-warn/40 text-warn' : 'border-line text-soft'}`}>{children}</div>
+}
+
+function Found({ ok, label, value, note }) {
+ return <li className="flex items-center gap-2.5 text-xs"><span className={`dot ${ok ? 'dot-ok' : ''}`} style={{ width: 6, height: 6 }} /><span className="text-muted">{label}</span><span className={`font-medium ${ok ? 'text-paper' : 'text-muted'}`}>{value}</span>{note && <span className="text-muted">{note}</span>}</li>
+}
+
+// The machine Infradeck itself runs on: its collector ships with the stack and is already asking to join.
+export function ThisMachineCard({ pending, onChanged, recommended = true }) {
+ const local = pending.find((item) => item.status === 'pending' && item.details?.dashboard_host) || null
+ const [name, setName] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const details = local?.details || {}
+ const chosen = name.trim() || local?.hostname || ''
+
+ const start = async () => {
+ if (local.replaces && !window.confirm(`This machine matches the existing server "${local.replaces.hostname}". Adding it replaces that server's credentials and signs its current collector out. Only continue if you are re-installing that machine.`)) return
+ setBusy(true); setError('')
+ try {
+ await apiRequest(`/monitoring/pending-collectors/${local.id}/approve`, { method: 'POST', body: JSON.stringify({ replace: Boolean(local.replaces), hostname: chosen }) })
+ await onChanged()
+ } catch (requestError) { setError(requestError.message || 'Could not start monitoring this machine.') } finally { setBusy(false) }
+ }
+
+ return (
+ <div className={`card flex flex-col px-[18px] pb-[18px] pt-4 ${recommended ? 'border-edge' : ''}`}>
+ <div className="flex items-center gap-2.5 text-[11px] text-muted">{recommended && <span className="chip text-paper">Recommended</span>}1 click</div>
+ <h3 className="m-0 mt-2.5 text-[15px] font-semibold text-paper">Monitor this machine</h3>
+ <p className="mb-0 mt-1.5 text-[13px] text-soft">The collector already ships with Infradeck's compose file. Turning it on starts reporting within 15 seconds.</p>
+ {local ? <>
+ <ul className="m-0 mt-3.5 grid list-none gap-x-6 gap-y-2 rounded-md border border-line bg-bg px-3.5 py-3 sm:grid-cols-2">
+ <Found ok label="Host" value={local.hostname} />
+ <Found ok={Boolean(local.os_info)} label="" value={local.os_info || 'Unknown system'} note={details.cpu_cores ? `· ${details.cpu_cores} cores` : ''} />
+ <Found ok={details.containers != null} label="Docker socket" value={details.containers != null ? 'readable' : 'not reachable'} />
+ <Found ok={details.containers > 0} label="" value={details.containers != null ? `${details.containers} containers` : 'No containers'} note={details.containers != null ? 'found' : ''} />
+ <Found ok={Boolean(details.helper_installed)} label="System helper" value={details.helper_installed ? 'installed' : 'not installed'} />
+ <Found ok={details.mounts > 0} label="Disk" value={details.mounts != null ? `${details.mounts} ${details.mounts === 1 ? 'mount' : 'mounts'}` : 'unknown'} />
+ </ul>
+ <label className="mt-3.5 block text-xs text-soft">Name
+ <input className="field mt-1.5 h-[34px]" value={name} placeholder={local.hostname} maxLength={253} onChange={(event) => setName(event.target.value)} />
+ </label>
+ {error && <div className="mt-3"><Notice>{error}</Notice></div>}
+ <div className="mt-3.5 flex flex-wrap items-center gap-3">
+ <button type="button" className="btn btn-primary" disabled={busy} onClick={start}><Icon name="check" size={14} />{busy ? 'Starting…' : `Start monitoring ${chosen}`}</button>
+ <span className="text-xs text-muted">Checks every minute at first · change it once it reports</span>
+ </div>
+ </> : <div className="mt-3.5 flex items-center gap-3 rounded-md border border-line bg-bg px-3.5 py-3 text-xs text-muted"><span className="spinner shrink-0" />Waiting for this machine's collector. It starts with Infradeck's own compose stack and shows up here within a few seconds; if it doesn't, check that the <span className="mono text-soft">collector</span> service is running.</div>}
+ </div>
+ )
+}
+
+function Waiting({ pending, onChanged }) {
+ const [busyId, setBusyId] = useState(null)
+ const [error, setError] = useState('')
+ const waiting = pending.filter((item) => item.status === 'pending' && !item.details?.dashboard_host)
+ const dismissed = pending.filter((item) => item.status === 'dismissed')
+
+ const act = async (item, action) => {
+ // Approving a machine that matches an existing server replaces that server's credentials and signs out its collector.
+ if (action === 'approve' && item.replaces && !window.confirm(`This machine matches the existing server "${item.replaces.hostname}". Adding it replaces that server's credentials and signs its current collector out. Only continue if you are re-installing that machine.`)) return
+ setBusyId(item.id); setError('')
+ try {
+ await apiRequest(`/monitoring/pending-collectors/${item.id}/${action}`, { method: 'POST', body: JSON.stringify({ replace: Boolean(item.replaces) }) })
+ await onChanged()
+ } catch (requestError) { setError(requestError.message || 'Could not update the server.') } finally { setBusyId(null) }
+ }
+
+ const row = (item) => (
+ <li key={item.id} className="flex flex-wrap items-center gap-x-3 gap-y-2 rounded-md border border-line bg-bg px-3.5 py-2.5">
+ <span className="min-w-0 flex-1">
+ <span className="flex flex-wrap items-center gap-2"><span className="text-[13px] font-medium text-paper">{item.hostname}</span><span className={`chip ${item.verified ? 'chip-ok' : 'chip-warn'}`}>{item.verified ? 'join token' : 'no token'}</span></span>
+ <span className="mt-0.5 block text-[11px] text-muted">{[item.ip_address, item.os_info, item.details?.containers != null ? `${item.details.containers} containers` : null].filter(Boolean).join(' · ')} · code <span className="mono text-soft">{item.pairing_code}</span></span>
+ {item.replaces && <span className="mt-0.5 block text-[11px] text-warn">Replaces the existing server “{item.replaces.hostname}”: its current collector will be signed out.</span>}
+ </span>
+ <button type="button" className="btn btn-sm btn-primary" disabled={busyId === item.id} onClick={() => act(item, 'approve')}>{busyId === item.id ? 'Adding…' : 'Add'}</button>
+ {item.status === 'pending' && <button type="button" className="btn btn-sm" disabled={busyId === item.id} onClick={() => act(item, 'dismiss')}>Dismiss</button>}
+ </li>
+ )
+
+ if (!waiting.length && !dismissed.length) return null
+ return (
+ <div className="mt-3.5">
+ {waiting.length > 0 && <>
+ <div className="mb-2 text-xs text-soft">Asking to join. The pairing code is also printed in that collector's log.</div>
+ <ul className="m-0 list-none space-y-2 p-0">{waiting.map(row)}</ul>
+ </>}
+ {dismissed.length > 0 && <details className="mt-2.5"><summary className="cursor-pointer text-[11px] text-muted">Dismissed ({dismissed.length})</summary><ul className="m-0 mt-2 list-none space-y-2 p-0">{dismissed.map(row)}</ul></details>}
+ {error && <div className="mt-2.5"><Notice>{error}</Notice></div>}
+ </div>
+ )
+}
+
+function EnrollmentKey() {
+ const [keyInfo, setKeyInfo] = useState(null)
+ const [enrollKey, setEnrollKey] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [confirmRevoke, setConfirmRevoke] = useState(false)
+ const [error, setError] = useState('')
+ const [copied, copy] = useCopy()
+
+ useEffect(() => {
+ apiRequest('/monitoring/enrollment-key', { method: 'GET' }).then(setKeyInfo).catch((requestError) => setError(requestError.message || 'Could not load the enrollment key.'))
+ }, [])
+
+ const generate = async () => {
+ setBusy(true); setError('')
+ try {
+ const data = await apiRequest('/monitoring/enrollment-key', { method: 'POST' })
+ setEnrollKey(data.enroll_key); setKeyInfo({ exists: true, created_at: data.created_at })
+ } catch (requestError) { setError(requestError.message || 'Could not create an enrollment key.') } finally { setBusy(false) }
+ }
+ const revoke = async () => {
+ setBusy(true); setError('')
+ try {
+ await apiRequest('/monitoring/enrollment-key', { method: 'DELETE' })
+ setEnrollKey(''); setKeyInfo({ exists: false, created_at: null }); setConfirmRevoke(false)
+ } catch (requestError) { setError(requestError.message || 'Could not revoke the enrollment key.') } finally { setBusy(false) }
+ }
+
+ return (
+ <div className="mt-2.5 text-xs">
+ <p className="m-0 text-muted">For scripted installs where nobody clicks Add: collectors started with <span className="mono text-soft">HOMELAB_ENROLL_KEY</span> join immediately. Servers already connected are unaffected by rotating or revoking it.</p>
+ {error && <div className="mt-2.5"><Notice>{error}</Notice></div>}
+ {!keyInfo ? <p className="mb-0 mt-2.5 text-muted">Loading…</p> : enrollKey ? <>
+ <p className="mb-0 mt-2.5 text-warn">Copy this key now. It is shown only once.</p>
+ <div className="mt-1.5 flex items-center gap-3 rounded-md border border-line bg-bg py-1.5 pl-3.5 pr-1.5"><code className="mono min-w-0 flex-1 truncate text-paper">{enrollKey}</code><button type="button" className="btn btn-sm" onClick={() => copy(enrollKey)}><Icon name={copied ? 'check' : 'copy'} size={13} />{copied ? 'Copied' : 'Copy'}</button></div>
+ </> : keyInfo.exists && <p className="mb-0 mt-2.5 text-soft">A key was created {new Date(keyInfo.created_at).toLocaleString()}. Rotate it to see a new one.</p>}
+ {keyInfo && <div className="mt-2.5 flex flex-wrap gap-2">
+ <button type="button" className="btn btn-sm" disabled={busy} onClick={generate}>{keyInfo.exists ? 'Rotate key' : 'Generate key'}</button>
+ {keyInfo.exists && (confirmRevoke ? <>
+ <button type="button" className="btn btn-sm border-signal/50 text-signal" disabled={busy} onClick={revoke}>Yes, revoke</button>
+ <button type="button" className="btn btn-sm" onClick={() => setConfirmRevoke(false)}>Cancel</button>
+ </> : <button type="button" className="btn btn-sm" disabled={busy} onClick={() => setConfirmRevoke(true)}>Revoke key</button>)}
+ </div>}
+ </div>
+ )
+}
+
+// Any other machine: one command, three ways to run it, and a live wait for its first check-in.
+export function AnotherMachineCard({ pending, onChanged, focusRef }) {
+ const [info, setInfo] = useState(null)
+ const [apiUrl, setApiUrl] = useState('')
+ const [name, setName] = useState('')
+ const [token, setToken] = useState(null)
+ const [expiresAt, setExpiresAt] = useState(null)
+ const [method, setMethod] = useState('docker run')
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const [copied, copy] = useCopy()
+
+ useEffect(() => {
+ apiRequest('/monitoring/install-info', { method: 'GET' })
+ .then((data) => {
+ setInfo(data)
+ // API_BASE is usually relative ('/api'); a collector needs an absolute address. The VPN address wins when one is configured.
+ setApiUrl(data.collector_url || new URL(API_BASE, window.location.origin).href.replace(/\/$/, ''))
+ })
+ .catch((requestError) => setError(requestError.message || 'Could not load the install settings.'))
+ }, [])
+
+ const generate = async () => {
+ setBusy(true); setError('')
+ try {
+ const data = await apiRequest('/monitoring/join-tokens', { method: 'POST' })
+ setToken(data.join_token); setExpiresAt(Date.now() + data.expires_in_seconds * 1000)
+ } catch (requestError) { setError(requestError.message || 'Could not create a join token.') } finally { setBusy(false) }
+ }
+
+ const url = apiUrl.trim().replace(/\/$/, '')
+ const isLocalhost = /\/\/(localhost|127\.0\.0\.1)(:|\/|$)/.test(url)
+ const ready = Boolean(info?.collector_image && info?.proxy_image)
+ const cleanName = name.trim().replace(/[^A-Za-z0-9.-]/g, '')
+ 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)) : null
+ const command = commands[method]
+
+ return (
+ <div className="card flex flex-col px-[18px] pb-[18px] pt-4">
+ <div className="text-[11px] text-muted">About 2 minutes</div>
+ <h3 className="m-0 mt-2.5 text-[15px] font-semibold text-paper">Another machine</h3>
+ <p className="mb-0 mt-1.5 text-[13px] text-soft">Run one command on any Linux machine with Docker. It connects back to this Infradeck and shows up here to be added.</p>
+
+ <div className="mt-3.5 grid gap-3 @container sm:grid-cols-[minmax(0,1fr)_minmax(0,1.3fr)]">
+ <label className="block text-xs text-soft">Name
+ <input ref={focusRef} className="field mt-1.5 h-[34px]" value={name} placeholder="e.g. homelab-01" maxLength={253} onChange={(event) => setName(event.target.value)} />
+ </label>
+ <label className="block text-xs text-soft">Address it will use to reach Infradeck
+ <input className="field mono mt-1.5 h-[34px]" value={apiUrl} onChange={(event) => { setApiUrl(event.target.value); setToken(null) }} aria-describedby="api-url-hint" />
+ </label>
+ </div>
+ <p id="api-url-hint" className={`mb-0 mt-1.5 text-[11px] ${info?.strict && !info?.collector_url ? 'text-warn' : isLocalhost ? 'text-warn' : 'text-muted'}`}>
+ {info?.collector_url ? 'Your configured collector (VPN) address.'
+ : info?.strict ? <>Collectors can't use the public address. Set <span className="mono">COLLECTOR_PUBLIC_URL</span> to the collector listener on your VPN (for example <span className="mono">http://10.8.0.1:8081/api</span>).</>
+ : isLocalhost ? <>Other machines can't reach <span className="mono">localhost</span>. Use this machine's LAN IP, VPN address or domain.</>
+ : 'Prefilled with the address you opened this page at. Over plain HTTP, use it only on a trusted LAN or VPN.'}
+ </p>
+
+ {info && !ready && <div className="mt-3"><Notice>No collector images are configured, so there is nothing safe to install from. Set <span className="mono">COLLECTOR_IMAGE</span> and <span className="mono">DOCKER_PROXY_IMAGE</span> in <span className="mono">.env</span> to your published, digest-pinned images (see SECURITY.md).</Notice></div>}
+ {error && <div className="mt-3"><Notice>{error}</Notice></div>}
+
+ <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>
+ : <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>
+
+ <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>}
+ <span className="ml-auto flex items-center gap-2.5 text-xs text-muted">{token ? <><span className="spinner" />Waiting for a check-in…</> : 'The token is single use and expires.'}</span>
+ </div>
+ {token && <p className="mb-0 mt-2 text-[11px] text-muted">Single use · expires in about {minutes} min. Both containers run with no capabilities; only the read-only proxy touches the Docker socket.</p>}
+
+ <Waiting pending={pending} onChanged={onChanged} />
+
+ <details className="mt-3.5 border-t border-line pt-3"><summary className="cursor-pointer text-xs text-muted">Advanced: skip approval with an enrollment key</summary><EnrollmentKey /></details>
+ </div>
+ )
+}
+
+// An empty rack with dashed slots and one orange drawer sliding in.
+function EmptyRack({ name }) {
+ return (
+ <svg viewBox="0 0 360 252" className="h-[252px] w-[360px] max-w-full" role="img" aria-label="An empty rack with one server sliding in">
+ <path d="M1 0v252M359 0v252" stroke="var(--color-rail)" strokeWidth="2" />
+ {[24, 124, 167, 210].map((y) => <rect key={y} x="24.5" y={y + 0.5} width="311" height="33" rx="2" fill="none" stroke="var(--color-edge)" strokeDasharray="3 3" />)}
+ <rect x="58" y="66" width="278" height="34" rx="2" fill="var(--color-signal)" />
+ <path d="M76 83h10M81 78v10" stroke="var(--color-bg)" strokeWidth="1.8" />
+ <text x="96" y="88" fill="var(--color-bg)" fontSize="13.5" fontWeight="600" fontFamily="var(--font-sans)">{name}</text>
+ <circle cx="320" cy="83" r="2.4" fill="var(--color-bg)" />
+ </svg>
+ )
+}
+
+const PROMISES = [
+ ['Needs attention', 'Problems float to the top as pulled-out drawers, so the page opens on what needs you.'],
+ ['Live health', 'CPU, memory, load and disks at every check-in, plus checks for firewall, updates, clock and OOM kills.'],
+ ['Containers and ports', 'Every container grouped by compose project, and which ports are reachable from other machines.'],
+ ['History', 'Kept as rolled-up points for as long as you set in Admin, with forecasts like “disk full around April”.'],
+]
+
+export function EmptyFleet({ overview, isAdmin, onChanged }) {
+ const pending = overview.pending_collectors || []
+ const local = pending.find((item) => item.status === 'pending' && item.details?.dashboard_host)
+ const scrollTo = (id) => document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'center' })
+ return (
+ <div className="space-y-9">
+ <section className="flex flex-wrap items-center justify-between gap-x-10 gap-y-8 pt-6">
+ <div className="max-w-[560px]">
+ <h1 className="m-0 text-[28px] font-semibold leading-[1.12] tracking-[-0.01em] text-paper">Your deck is empty.<br />Slide in your first server.</h1>
+ <p className="mb-0 mt-5 text-sm leading-[23px] text-soft">Infradeck watches servers through a small collector container. Start with the machine Infradeck runs on; it takes one click. Other machines need one command each.</p>
+ {isAdmin ? <div className="mt-6 flex flex-wrap items-center gap-2.5">
+ <button type="button" className="btn btn-primary" onClick={() => scrollTo('add-this-machine')}><Icon name="plus" size={14} />Monitor this machine</button>
+ <button type="button" className="btn" onClick={() => scrollTo('add-another-machine')}>Add another machine</button>
+ <a className="btn btn-ghost" href={DOCS_URL} target="_blank" rel="noreferrer">Read the docs</a>
+ </div> : <p className="mb-0 mt-5 text-[13px] text-muted">An admin needs to connect a server before anything shows up here.</p>}
+ </div>
+ <EmptyRack name={`${local?.hostname || 'server'} · this machine`} />
+ </section>
+
+ {isAdmin && <section aria-label="Add a server">
+ <SectionHeading title="Add a server" detail="pick one to start, you can add the rest later" />
+ <div className="grid items-start gap-4 xl:grid-cols-2">
+ <div id="add-this-machine"><ThisMachineCard pending={pending} onChanged={onChanged} /></div>
+ <div id="add-another-machine"><AnotherMachineCard pending={pending} onChanged={onChanged} /></div>
+ </div>
+ </section>}
+
+ <section aria-label="Fleet">
+ <SectionHeading title="Fleet" detail="0 servers · this is where they'll line up" />
+ <div className="custom-scroll overflow-x-auto"><div className="min-w-[1080px]">
+ <FleetHeader minutes={30} />
+ <div className="rack" aria-hidden="true">
+ {[[150, 205], [124, 178]].map(([first, second]) => (
+ <div key={first} className={`drawer drawer-ghost ${FLEET_COLUMNS}`} style={{ minHeight: 58 }}>
+ <span className="flex items-center gap-2.5"><span className="dot" style={{ background: 'var(--color-edge)' }} /><span className="ghost-bar" style={{ width: first }} /></span>
+ <span className="ghost-bar" style={{ width: second }} /><span className="ghost-bar w-[120px]" /><span className="ghost-bar w-[120px]" /><span className="ghost-bar w-[140px]" /><span className="ghost-bar w-9" /><span className="ghost-bar w-20" />
+ </div>
+ ))}
+ </div>
+ </div></div>
+ </section>
+
+ <section aria-label="What you'll get once a server reports">
+ <SectionHeading title="What you'll get once a server reports" />
+ <div className="card grid divide-y divide-line sm:grid-cols-2 sm:divide-x xl:grid-cols-4 xl:divide-y-0">
+ {PROMISES.map(([title, text]) => <div key={title} className="px-[18px] py-4"><h3 className="m-0 text-[13px] font-semibold text-paper">{title}</h3><p className="mb-0 mt-2 text-xs leading-[19px] text-muted">{text}</p></div>)}
+ </div>
+ <p className="mb-0 mt-3.5 text-xs text-muted">Everything stays on this machine. The agent only sends data to your model provider when you ask it something, and you can turn that off in Admin.</p>
+ </section>
+ </div>
+ )
+}
diff --git a/src/frontend/src/dashboard/EventsTab.jsx b/src/frontend/src/dashboard/EventsTab.jsx
new file mode 100644
index 0000000..a0bf9be
--- /dev/null
+++ b/src/frontend/src/dashboard/EventsTab.jsx
@@ -0,0 +1,131 @@
+// A server's week on one strip and in readable lines: alerts, containers, network and system events together.
+import { useMemo, useState } from 'react'
+import { Link } from 'react-router-dom'
+import { Icon } from '../icons.jsx'
+import { usePolled } from './data.js'
+import { EVENT_SOURCES, dayHeading, describeEvent, describeGroup, eventCategory, eventStrip, eventsToCsv, groupRepeats } from './logic.js'
+
+const DAYS = 7
+const PAGE = 40
+const MARK = { signal: 'bg-signal', warn: 'bg-warn', ok: 'bg-ok', paper: 'bg-paper', plain: 'bg-dim' }
+const BAR = { signal: 'var(--color-signal)', warn: 'var(--color-warn)', plain: 'var(--color-rail)' }
+const TAG = { signal: 'chip-signal', warn: 'chip-warn', ok: 'chip-ok' }
+const clock = (time) => new Date(time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
+
+function download(name, text) {
+ const url = URL.createObjectURL(new Blob([text], { type: 'text/csv' }))
+ const link = document.createElement('a')
+ link.href = url
+ link.download = name
+ link.click()
+ URL.revokeObjectURL(url)
+}
+
+function Strip({ events }) {
+ const strip = useMemo(() => eventStrip(events, DAYS), [events])
+ return (
+ <div className="grid gap-x-2.5 border-b border-line px-[18px] pb-4 pt-4" style={{ gridTemplateColumns: `repeat(${strip.length}, minmax(0, 1fr))` }} role="img" aria-label={`Events per day over the last ${DAYS} days: ${strip.map((day) => `${day.label} ${day.count}`).join(', ')}`}>
+ {strip.map((day) => (
+ <div key={day.key} className="min-w-0">
+ <div className={`flex h-10 items-end gap-0.5 border-b ${day.today ? 'border-paper' : 'border-transparent'}`}>
+ {day.bars.map((bar, index) => <span key={index} className="flex-1 rounded-t-[1px]" style={{ height: bar.count ? `${Math.round(bar.height * 100)}%` : 3, background: bar.count ? BAR[bar.tone] : 'var(--color-edge)' }} />)}
+ </div>
+ <div className={`mt-2.5 flex justify-between text-[11px] ${day.today ? 'font-medium text-paper' : 'text-muted'}`}><span>{day.label}</span><span>{day.count}</span></div>
+ </div>
+ ))}
+ </div>
+ )
+}
+
+function Row({ group, serverId, grouped }) {
+ const [open, setOpen] = useState(false)
+ const line = grouped ? describeGroup(group) : { ...describeEvent(group.events[0]), count: 1 }
+ const first = group.events[0]
+ const many = line.count > 1
+ let action = null
+ if (many) action = <button type="button" className="link" aria-expanded={open} onClick={() => setOpen((value) => !value)}>{open ? 'Hide' : `Show ${line.count}`}</button>
+ else if (first.kind === 'alert_resolved') action = <Link to={`/statistics?server=${serverId}`} className="link">See chart</Link>
+ else if (line.tag) action = <span className={`chip ${TAG[line.tag.tone] || ''}`}>{line.tag.text}</span>
+ return <>
+ <li className="grid min-h-[44px] grid-cols-[52px_14px_minmax(0,1fr)_auto] items-center gap-x-3 border-t border-line px-[18px] py-2.5 text-xs md:grid-cols-[58px_14px_150px_minmax(0,1fr)_auto]">
+ <time dateTime={first.time} className="mono text-muted" title={new Date(first.time).toLocaleString()}>{clock(first.time)}</time>
+ <span aria-hidden="true" className={`h-2 w-2 rounded-[2px] ${MARK[line.tone] || MARK.plain}`} />
+ <span className="hidden truncate text-soft md:block">{line.source}</span>
+ <span className="min-w-0 text-soft"><span className="mr-1.5 text-soft md:hidden">{line.source}:</span>{line.lead && <span className="font-medium text-paper">{line.lead} </span>}{line.text}</span>
+ <span className="justify-self-end whitespace-nowrap">{action}</span>
+ </li>
+ {open && group.events.map((event, index) => {
+ const child = describeEvent(event)
+ return <li key={`${event.time}-${index}`} className="grid grid-cols-[52px_14px_minmax(0,1fr)] gap-x-3 bg-sunken px-[18px] py-1.5 text-[11px] text-muted md:grid-cols-[58px_14px_150px_minmax(0,1fr)]"><time dateTime={event.time} className="mono">{clock(event.time)}</time><span /><span className="hidden md:block" /><span className="min-w-0">{child.lead && <span className="text-soft">{child.lead} </span>}{child.text}</span></li>
+ })}
+ </>
+}
+
+export function EventsTab({ server, pending, isAdmin, onReview }) {
+ const { data, error } = usePolled(`/monitoring/servers/${server.id}/events?days=${DAYS}`, 30)
+ const [query, setQuery] = useState('')
+ const [category, setCategory] = useState('all')
+ const [grouped, setGrouped] = useState(true)
+ const [limit, setLimit] = useState(PAGE)
+
+ // Machines asking to join are the fleet's news, told on the machine that runs the dashboard.
+ const events = useMemo(() => {
+ const joined = server.is_dashboard_host && isAdmin ? (pending || []).filter((item) => item.status === 'pending').map((item) => ({ time: item.created_at, source: 'infradeck', kind: 'pending_collector', title: item.hostname, detail: `asked to join the fleet${item.ip_address ? ` from ${item.ip_address}` : ''}` })) : []
+ return [...joined, ...(data?.events || [])].sort((a, b) => (a.time < b.time ? 1 : -1))
+ }, [data, pending, server.is_dashboard_host, isAdmin])
+
+ if (!data) return <p className="m-0 px-[18px] py-10 text-center text-[13px] text-muted">{error || 'Loading events…'}</p>
+
+ const counts = { all: events.length }
+ for (const key of Object.keys(EVENT_SOURCES)) counts[key] = events.filter((event) => eventCategory(event) === key).length
+ const needle = query.trim().toLowerCase()
+ const matching = events.filter((event) => (category === 'all' || eventCategory(event) === category) && (!needle || `${event.title || ''} ${event.detail || ''} ${event.kind} ${event.source}`.toLowerCase().includes(needle)))
+ const groups = grouped ? groupRepeats(matching) : matching.map((event) => ({ source: event.source, kind: event.kind, events: [event] }))
+ const visible = groups.slice(0, limit)
+ const days = []
+ for (const group of visible) {
+ const heading = dayHeading(group.events[0].time)
+ if (!days.length || days[days.length - 1].heading !== heading) days.push({ heading, groups: [] })
+ days[days.length - 1].groups.push(group)
+ }
+
+ return <>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2.5 border-b border-line px-[18px] py-3">
+ <label className="relative block w-full max-w-[262px]">
+ <Icon name="search" size={14} className="pointer-events-none absolute left-3 top-[9px] text-muted" />
+ <input type="search" className="field pl-9" value={query} onChange={(event) => { setQuery(event.target.value); setLimit(PAGE) }} placeholder="Search events" aria-label={`Search events on ${server.hostname}`} />
+ </label>
+ <div className="seg" role="group" aria-label="Show">
+ <button type="button" aria-pressed={category === 'all'} onClick={() => { setCategory('all'); setLimit(PAGE) }}>All {counts.all}</button>
+ {Object.entries(EVENT_SOURCES).map(([key, label]) => <button key={key} type="button" aria-pressed={category === key} onClick={() => { setCategory(key); setLimit(PAGE) }}>{label} {counts[key]}</button>)}
+ </div>
+ <span className="ml-auto flex items-center gap-3.5">
+ <label className="flex cursor-pointer items-center gap-2.5 text-xs text-soft">
+ <input type="checkbox" role="switch" className="peer sr-only" checked={grouped} onChange={(event) => setGrouped(event.target.checked)} />
+ <span aria-hidden="true" className="relative h-[18px] w-8 rounded-full border border-edge bg-raised transition-colors after:absolute after:left-[2px] after:top-[2px] after:h-3 after:w-3 after:rounded-full after:bg-muted after:transition-all peer-checked:border-paper peer-checked:bg-paper peer-checked:after:left-[16px] peer-checked:after:bg-bg peer-focus-visible:outline peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-paper" />
+ Group repeats
+ </label>
+ <button type="button" className="btn" disabled={!matching.length} onClick={() => download(`${server.hostname}-events.csv`, eventsToCsv(matching))}><Icon name="download" size={14} />Export</button>
+ </span>
+ </div>
+ <Strip events={matching} />
+ {days.length ? days.map((day) => (
+ <div key={day.heading}>
+ <div className="bg-sunken px-[18px] py-2.5 text-[11px] font-semibold tracking-[0.1em] text-muted">{day.heading}</div>
+ <ul className="m-0 list-none p-0">
+ {day.groups.map((group, index) => group.kind === 'pending_collector'
+ ? <li key={`${group.events[0].time}-${index}`} className="grid min-h-[44px] grid-cols-[52px_14px_minmax(0,1fr)_auto] items-center gap-x-3 border-t border-line px-[18px] py-2 text-xs md:grid-cols-[58px_14px_150px_minmax(0,1fr)_auto]">
+ <time dateTime={group.events[0].time} className="mono text-muted">{clock(group.events[0].time)}</time><span aria-hidden="true" className="h-2 w-2 rounded-[2px] bg-paper" /><span className="hidden text-soft md:block">Infradeck</span>
+ <span className="min-w-0 text-soft"><span className="font-medium text-paper">{group.events[0].title} </span>{group.events[0].detail}</span>
+ <button type="button" className="btn btn-sm" onClick={onReview}>Review</button>
+ </li>
+ : <Row key={`${group.events[0].time}-${group.kind}-${index}`} group={group} serverId={server.id} grouped={grouped} />)}
+ </ul>
+ </div>
+ )) : <p className="m-0 px-[18px] py-10 text-center text-[13px] text-muted">{events.length ? 'No events match this search.' : `Nothing happened on ${server.hostname} in the last ${DAYS} days.`}</p>}
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 border-t border-line px-[18px] py-3 text-xs text-muted">
+ <span>Showing {visible.length} of {groups.length} {grouped ? 'grouped ' : ''}events from the last {DAYS} days. Events are kept for {data.retention_days} days.</span>
+ {groups.length > visible.length && <button type="button" className="link" onClick={() => setLimit((value) => value + PAGE)}>Show {Math.min(PAGE, groups.length - visible.length)} more</button>}
+ </div>
+ </>
+}
diff --git a/src/frontend/src/dashboard/FleetRack.jsx b/src/frontend/src/dashboard/FleetRack.jsx
new file mode 100644
index 0000000..a7596aa
--- /dev/null
+++ b/src/frontend/src/dashboard/FleetRack.jsx
@@ -0,0 +1,95 @@
+// The fleet as a rack: one row per server with the same columns, so three or thirty machines compare at a glance.
+import { containerState } from '../fleetLogic.js'
+import { Meter, Sparkline } from './charts.jsx'
+import { SectionHeading } from './NeedsAttention.jsx'
+import { forecastKey } from './data.js'
+import { forecastPhrase, formatPercent, formatUsedOfTotal, fullestMount, mountLevel, serverMounts, serverState, serverStateLabel, systemLines, thresholdLevel } from './logic.js'
+import { isOnline } from '../fleetLogic.js'
+
+export const FLEET_COLUMNS = 'grid-cols-[196px_minmax(150px,1fr)_144px_144px_166px_56px_116px]'
+const STATE_DOT = { critical: 'dot-signal', warn: 'dot-warn', ok: 'dot-ok', offline: '' }
+const LEVEL_TEXT = ['text-paper', 'text-warn', 'text-signal']
+
+export function rangeLabel(minutes) {
+ return minutes < 60 ? `${minutes} min` : `${minutes / 60} h`
+}
+
+function ContainersCell({ server }) {
+ const containers = server.containers || []
+ if (!containers.length) return <span className="text-xs text-dim">{server.host?.docker_status === 'unreachable' ? 'Docker unreachable' : 'none'}</span>
+ 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 note = restarting ? [`${restarting} restarting`, 'text-signal'] : unhealthy ? [`${unhealthy} unhealthy`, 'text-signal'] : stopped ? [`${stopped} stopped`, 'text-warn'] : ['running', 'text-muted']
+ return <span className="whitespace-nowrap"><span className="text-[13px] font-medium text-paper">{running}/{containers.length}</span> <span className={`text-[11px] ${note[1]}`}>{note[0]}</span></span>
+}
+
+function ServerRow({ server, selected, sparkline, forecasts, overview, onSelect }) {
+ const state = serverState(server)
+ const host = server.host
+ const mounts = serverMounts(server)
+ const disk = fullestMount(mounts)
+ const [system, address] = systemLines(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 forecast = disk ? forecastPhrase(forecasts[forecastKey(server.id, disk.mount)], { short: true }) : null
+ const diskNote = !disk ? '' : forecast ? `${disk.mount} · ${forecast}` : disk.total_gb != null && disk.mount.length < 9 ? `${disk.mount} · ${formatUsedOfTotal(disk.used_gb, disk.total_gb)}` : disk.mount
+ const critical = state === 'critical'
+ const badge = critical || state === 'offline' ? serverStateLabel(server) : null
+ return (
+ <button type="button" onClick={() => onSelect(server.id)} aria-pressed={selected} aria-label={`${server.hostname}, ${serverStateLabel(server)}${selected ? ', selected' : ''}`}
+ className={`drawer w-full ${FLEET_COLUMNS} ${critical ? 'drawer-alert drawer-out' : ''} ${selected ? 'drawer-selected' : ''}`} style={{ minHeight: 58, width: critical ? 'calc(100% - 24px)' : undefined }}>
+ <span className="flex min-w-0 items-center gap-2.5 pr-3">
+ <span className={`dot ${STATE_DOT[state]}`} />
+ <span className="truncate text-sm 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>}
+ </span>
+ <span className="min-w-0 pr-4">
+ <span className="block truncate text-xs text-soft">{system || 'Waiting for the first check-in'}</span>
+ <span className="block truncate text-[11px] text-muted">{address}</span>
+ </span>
+ {host ? <>
+ <span className="flex items-center gap-2.5 pr-4"><Sparkline values={sparkline} tone={critical ? 'signal' : 'paper'} /><span className="ml-auto text-[13px] font-medium text-paper">{formatPercent(host.cpu_utilization_pct)}</span></span>
+ <span className="pr-4">
+ <span className="flex items-baseline justify-between gap-2"><span className={`text-[13px] font-medium ${LEVEL_TEXT[memoryLevel]}`}>{formatPercent(host.ram_pct)}</span><span className="truncate text-[11px] text-muted">{server.total_ram_gb ? formatUsedOfTotal(host.ram_used_gb, server.total_ram_gb) : ''}</span></span>
+ <Meter className="mt-1.5" percent={host.ram_pct} level={memoryLevel} label={`${server.hostname} memory`} />
+ </span>
+ <span className="pr-4">
+ <span className="flex items-baseline justify-between gap-2"><span className={`text-[13px] font-medium ${LEVEL_TEXT[diskLevel]}`}>{disk ? formatPercent(disk.used_pct) : '—'}</span><span className="truncate text-[11px] text-muted" title={diskNote}>{diskNote}</span></span>
+ <Meter className="mt-1.5" percent={disk?.used_pct} level={diskLevel} label={`${server.hostname} busiest disk`} />
+ </span>
+ <span className="text-[13px] font-medium text-paper">{host.load_1m == null ? '—' : host.load_1m.toFixed(2)}</span>
+ <ContainersCell server={server} />
+ </> : <span className="col-span-5 text-xs text-muted">{isOnline(server) ? 'Collecting the first measurement…' : 'The collector has not sent a measurement yet.'}</span>}
+ </button>
+ )
+}
+
+export function FleetHeader({ minutes }) {
+ return (
+ <div className={`grid ${FLEET_COLUMNS} grid-head px-[43px] pb-1`}>
+ <span>Server</span><span>System</span><span>CPU · {rangeLabel(minutes)}</span><span>Memory</span><span>Busiest disk</span><span>Load</span><span>Containers</span>
+ </div>
+ )
+}
+
+export function FleetRack({ overview, servers, selectedId, sparklines, forecasts, minutes, onSelect }) {
+ const reporting = servers.filter((server) => isOnline(server)).length
+ const troubled = servers.some((server) => serverState(server) !== 'ok')
+ return (
+ <section aria-label="Fleet">
+ <SectionHeading title="Fleet" detail={`${servers.length} ${servers.length === 1 ? 'server' : 'servers'} · ${troubled ? `${reporting} ${reporting === 1 ? 'collector' : 'collectors'} reporting` : 'all healthy'}`}>Sort: {troubled ? 'problems first' : 'name'}</SectionHeading>
+ <div className="custom-scroll overflow-x-auto">
+ <div className="min-w-[1080px]">
+ <FleetHeader minutes={minutes} />
+ <div className="rack">
+ {servers.map((server) => <ServerRow key={server.id} server={server} selected={server.id === selectedId} sparkline={sparklines?.[server.id]} forecasts={forecasts} overview={overview} onSelect={onSelect} />)}
+ </div>
+ </div>
+ </div>
+ </section>
+ )
+}
diff --git a/src/frontend/src/dashboard/NeedsAttention.jsx b/src/frontend/src/dashboard/NeedsAttention.jsx
new file mode 100644
index 0000000..606bada
--- /dev/null
+++ b/src/frontend/src/dashboard/NeedsAttention.jsx
@@ -0,0 +1,123 @@
+// What needs you now, as pulled-out drawers; or one calm panel saying that nothing does.
+import { Link } from 'react-router-dom'
+import { Icon } from '../icons.jsx'
+import { attentionAction, forecastMonth, formatAge, formatPercent, formatQuiet, needsAttention } from './logic.js'
+
+export function SectionHeading({ title, detail, children }) {
+ return (
+ <div className="mb-2.5 flex flex-wrap items-baseline gap-x-2.5 gap-y-1">
+ <h2 className="m-0 text-sm font-semibold text-paper">{title}</h2>
+ {detail && <span className="text-xs text-muted">{detail}</span>}
+ {children && <span className="ml-auto text-xs text-soft">{children}</span>}
+ </div>
+ )
+}
+
+function Drawer({ alert, onAction }) {
+ const critical = alert.severity === 'CRITICAL'
+ const action = attentionAction(alert)
+ // Rule titles name the container or the metric; the server goes in front of the explanation when the title lacks it.
+ const where = alert.hostname && !alert.title.includes(alert.hostname) ? `${alert.hostname} · ` : ''
+ return (
+ <div className={`drawer ${critical ? 'drawer-critical drawer-out' : ''} grid-cols-[minmax(0,1fr)_auto] gap-x-4 py-2 md:grid-cols-[96px_minmax(0,1fr)_minmax(0,auto)_56px_auto]`}>
+ <span className={`col-span-2 text-[11px] font-bold tracking-[0.08em] md:col-span-1 ${critical ? 'text-bg' : 'text-warn'}`}>{alert.severity}</span>
+ <span className="min-w-0">
+ <span className={`block truncate text-[13px] font-semibold ${critical ? 'text-bg' : 'text-paper'}`}>{alert.title}</span>
+ <span className={`block truncate text-xs ${critical ? 'text-bg/80' : 'text-muted'}`} title={alert.description}>{where}{alert.description}</span>
+ </span>
+ <span className={`hidden min-w-0 max-w-[400px] items-center gap-2.5 text-xs md:flex ${critical ? 'text-bg/85' : 'text-soft'}`}>
+ {alert.agent_note && <><Icon name="agent" size={14} className="shrink-0" /><span className="truncate" title={alert.agent_note}>Agent: {alert.agent_note}</span></>}
+ </span>
+ <span className={`hidden text-center text-xs md:block ${critical ? 'text-bg/85' : 'text-muted'}`} title={`Since ${new Date(alert.created_at).toLocaleString()}`}>{formatAge(alert.created_at)}</span>
+ <button type="button" onClick={() => onAction(alert, action)} className={`btn btn-sm ${critical ? 'border-[#160800] bg-[#160800] text-paper hover:!border-black hover:!bg-black' : ''}`}>{action.label}</button>
+ </div>
+ )
+}
+
+// A rack with every drawer pushed in.
+function RackIllustration({ units = 5 }) {
+ return (
+ <svg viewBox="0 0 232 164" className="h-[164px] w-[232px]" role="img" aria-label="A rack with every drawer pushed in">
+ <path d="M1 0v164M231 0v164" stroke="var(--color-rail)" strokeWidth="2" />
+ {Array.from({ length: units }, (_, index) => {
+ const y = 18 + index * 27
+ return <g key={index}>
+ <rect x="18.5" y={y + 0.5} width="194" height="19" rx="2" fill="none" stroke="var(--color-edge)" />
+ <circle cx="27" cy={y + 10} r="1.4" fill="var(--color-dim)" /><circle cx="43" cy={y + 10} r="2.4" fill="var(--color-ok)" />
+ <path d={`M184 ${y + 6}v8M188 ${y + 6}v8M192 ${y + 6}v8`} stroke="var(--color-dim)" strokeWidth="1.2" /><circle cx="204" cy={y + 10} r="1.4" fill="var(--color-dim)" />
+ </g>
+ })}
+ </svg>
+ )
+}
+
+function Fact({ label, value, detail }) {
+ return (
+ <div className="min-w-0 px-5 py-4">
+ <div className="text-xs text-muted">{label}</div>
+ <div className="mt-2 truncate text-[13px] font-medium text-paper" title={typeof value === 'string' ? value : undefined}>{value}</div>
+ <div className="mt-2 text-xs leading-[18px] text-muted">{detail}</div>
+ </div>
+ )
+}
+
+function AllClear({ overview, watch }) {
+ const quiet = overview.quiet
+ const servers = overview.servers
+ const newest = Math.max(...servers.map((server) => (server.last_seen_at ? new Date(server.last_seen_at).getTime() : 0)))
+ const slowest = Math.max(...servers.map((server) => server.check_interval_seconds || 60))
+ const reporting = servers.filter((server) => server.last_seen_at && Date.now() - new Date(server.last_seen_at).getTime() < (server.check_interval_seconds || 60) * 3000).length
+ const last = quiet?.last_incident
+ return (
+ <div className="card grid overflow-hidden md:grid-cols-[300px_minmax(0,1fr)]">
+ <div className="hidden items-center justify-center border-r border-line py-4 md:flex"><RackIllustration /></div>
+ <div className="px-6 py-6">
+ <h3 className="m-0 text-[17px] font-semibold text-paper">Every drawer is in. Nothing needs you right now.</h3>
+ <p className="mb-0 mt-2.5 text-[13px] text-soft">
+ {reporting === servers.length ? `${servers.length === 1 ? 'The collector' : `All ${servers.length} collectors`} reported in the last ${formatQuiet(Math.max(slowest, (Date.now() - newest) / 1000 + slowest)).replace(/^1 min$/, 'minute')} and nothing is open.` : `${reporting} of ${servers.length} collectors are reporting and nothing is open.`}
+ </p>
+ <div className="mt-5 grid divide-y divide-line rounded-md border border-line md:grid-cols-3 md:divide-x md:divide-y-0">
+ <Fact label="Last incident" value={last ? last.title : 'None yet'} detail={last ? `Resolved ${formatAge(last.resolved_at)} ago${last.hostname ? ` · ${last.hostname}` : ''}` : 'Nothing has needed attention since this install started.'} />
+ <Fact label="Next thing to watch" value={watch ? watch.title : 'Nothing in sight'} detail={watch ? watch.detail : 'No disk is on course to fill up.'} />
+ <Fact label="Quiet for" value={quiet ? formatQuiet((Date.now() - new Date(quiet.quiet_since).getTime()) / 1000) : '—'} detail={quiet ? `Longest this month: ${formatQuiet(quiet.longest_quiet_seconds_this_month)}` : ''} />
+ </div>
+ </div>
+ </div>
+ )
+}
+
+// The filesystem most likely to need attention next: the one that fills soonest, else the fullest.
+export function nextToWatch(servers, forecasts, fullest) {
+ let best = null
+ for (const server of servers) {
+ const mount = fullest(server)
+ if (!mount) continue
+ const days = forecasts[`${server.id}:${mount.mount}`]
+ const candidate = { server, mount, days, rank: days != null ? days : 1e9 - (mount.used_pct || 0) }
+ if (!best || candidate.rank < best.rank) best = candidate
+ }
+ if (!best || (best.days == null && (best.mount.used_pct || 0) < 50)) return null
+ const name = best.mount.mount === '/' ? 'Root disk' : best.mount.mount
+ const when = forecastMonth(best.days)
+ return { title: `${name} on ${best.server.hostname}`, detail: `${formatPercent(best.mount.used_pct)} now${when ? ` · ${when}` : ' · no clear growth'}` }
+}
+
+export function NeedsAttention({ overview, watch, onAction }) {
+ const alerts = (overview.alerts || []).filter(needsAttention)
+ const counts = overview.alerts_by_severity || {}
+ const critical = counts.CRITICAL || 0
+ const warnings = counts.WARNING || 0
+ const open = critical + warnings
+ const detail = open ? [`${open} open`, critical ? `${critical} critical` : null, warnings ? `${warnings} ${warnings === 1 ? 'warning' : 'warnings'}` : null].filter(Boolean).join(' · ') : '0 open'
+ return (
+ <section aria-label="Needs attention">
+ <SectionHeading title="Needs attention" detail={detail}>
+ <Link to="/agent" className="hover:text-paper">{open ? 'All incidents in Agent' : 'Incident history in Agent'} →</Link>
+ </SectionHeading>
+ {open ? <>
+ <div className="rack">{alerts.map((alert) => <Drawer key={alert.id} alert={alert} onAction={onAction} />)}</div>
+ {open > alerts.length && <p className="mb-0 mt-2 text-[11px] text-muted">Showing the {alerts.length} most severe of {open}. The rest are in Agent.</p>}
+ </> : <AllClear overview={overview} watch={watch} />}
+ </section>
+ )
+}
diff --git a/src/frontend/src/dashboard/Network.jsx b/src/frontend/src/dashboard/Network.jsx
new file mode 100644
index 0000000..d1a7341
--- /dev/null
+++ b/src/frontend/src/dashboard/Network.jsx
@@ -0,0 +1,179 @@
+// Who is listening and who can reach it: the summary card under a server's Overview and the full Network tab.
+import { useMemo, useState } from 'react'
+import { LineChart } from './charts.jsx'
+import { StatStrip } from './Containers.jsx'
+import { rangeLabel } from './FleetRack.jsx'
+import { firewallLine, firewallSummary, formatAge, groupNetworkEvents, listenerRows, niceCeiling, sortListeners, trafficRates } from './logic.js'
+
+const RULE_NAMES = { ufw: 'ufw allow', ufw6: 'ufw allow', nftables: 'nftables allow', iptables: 'iptables allow', ip6tables: 'ip6tables allow' }
+const rate = (value) => (value == null ? '—' : value >= 10 ? value.toFixed(0) : value.toFixed(1))
+
+function PortChip({ row }) {
+ return <li className={`port ${row.risky ? 'port-risky' : ''}`} title={row.risky ? row.reason : undefined}>{row.proto}/{row.label}{(row.owner || row.what) && <span>{[row.owner, row.risky && row.what !== 'database' ? row.what.replace(' UI', '') : null].filter(Boolean).join(' ') || row.what}</span>}</li>
+}
+
+function Changes({ events, limit = 4, compact = false }) {
+ const [all, setAll] = useState(false)
+ const groups = useMemo(() => groupNetworkEvents(events), [events])
+ const [open, setOpen] = useState(null)
+ if (!groups.length) return <p className="m-0 text-xs text-muted">No new listeners or firewall changes in the last 7 days.</p>
+ const shown = all ? groups : groups.slice(0, limit)
+ return <>
+ <ul className="m-0 list-none divide-y divide-line p-0">
+ {shown.map((group, index) => (
+ <li key={`${group.time}-${group.port}-${index}`} className={`grid ${compact ? 'grid-cols-[52px_96px_minmax(0,1fr)]' : 'grid-cols-[86px_124px_minmax(0,1fr)]'} gap-x-2 py-2.5 text-xs`}>
+ <span className="text-muted" title={new Date(group.time).toLocaleString()}>{group.age}{compact ? '' : ' ago'}</span>
+ <span className={group.tone === 'warn' ? 'text-warn' : 'text-soft'}>{compact ? group.label.replace('Now exposed', 'Exposed') : group.label}</span>
+ <span className="min-w-0 text-soft">
+ {group.port && <span className="mono text-paper">{compact ? group.port.replace(/^[a-z+]+\//, '') : group.port} </span>}{group.text}
+ {group.count > 2 && <> <button type="button" className="link" aria-expanded={open === index} onClick={() => setOpen(open === index ? null : index)}>{open === index ? 'hide' : 'show all'}</button></>}
+ {open === index && <ul className="m-0 mt-1.5 list-none space-y-1 p-0 text-[11px] text-muted">{group.events.map((event, position) => <li key={`${event.time}-${position}`}>{formatAge(event.time)} ago · {event.detail}</li>)}</ul>}
+ </span>
+ </li>
+ ))}
+ </ul>
+ {groups.length > limit && <button type="button" className="link mt-1 text-xs" onClick={() => setAll((value) => !value)}>{all ? 'Show fewer' : `${groups.length - limit} more`}</button>}
+ </>
+}
+
+function counts(server) {
+ const listeners = server.network?.listeners || []
+ const ports = new Set(listeners.map((listener) => listener.port))
+ const reachable = new Set(listeners.filter((listener) => listener.scope !== 'loopback').map((listener) => listener.port))
+ return { listening: ports.size, reachable: reachable.size, local: ports.size - reachable.size }
+}
+
+export const listeningCount = (server) => counts(server).listening
+
+// Under a server's Overview: ports as chips naming their owner, and the week's changes in a few lines.
+export function NetworkCard({ server }) {
+ const network = server.network || { listeners: [], events: [] }
+ const rows = useMemo(() => listenerRows(server), [server])
+ if (!network.listeners.length && !network.events.length) return null
+ const total = counts(server)
+ const reachable = rows.filter((row) => row.reachable)
+ const local = rows.filter((row) => !row.reachable)
+ const risky = reachable.some((row) => row.risky)
+ return (
+ <section className="card overflow-hidden" aria-label={`Network on ${server.hostname}`}>
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 border-b border-line px-[18px] py-3.5">
+ <h2 className="m-0 text-sm font-semibold text-paper">Network</h2>
+ <span className="text-xs text-muted">{total.listening} listening · {total.reachable} reachable from other machines · firewall config read from files, not the live ruleset</span>
+ </div>
+ <div className="grid lg:grid-cols-[minmax(0,1.25fr)_minmax(0,1fr)] lg:divide-x lg:divide-line">
+ <div className="min-w-0 px-[18px] py-4">
+ {reachable.length > 0 && <>
+ <div className="mb-2.5 flex flex-wrap items-baseline justify-between gap-x-3"><h3 className="m-0 text-[13px] font-medium text-paper">Reachable from other machines <span className={risky || firewallSummary(server).enabled === false ? 'text-warn' : 'text-muted'}>{total.reachable}</span></h3><span className="text-[11px] text-muted">{firewallLine(server)}</span></div>
+ <ul className="m-0 flex list-none flex-wrap gap-1.5 p-0">{reachable.map((row) => <PortChip key={`${row.proto}-${row.label}`} row={row} />)}</ul>
+ </>}
+ {local.length > 0 && <>
+ <h3 className={`m-0 mb-2.5 text-[13px] font-medium text-paper ${reachable.length ? 'mt-5' : ''}`}>This machine only <span className="text-muted">{total.local}</span></h3>
+ <ul className="m-0 flex list-none flex-wrap gap-1.5 p-0">{local.map((row) => <PortChip key={`${row.proto}-${row.label}`} row={row} />)}</ul>
+ </>}
+ {!rows.length && <p className="m-0 text-xs text-muted">This collector has not reported its listening ports.</p>}
+ {risky && <p className="mb-0 mt-3 text-[11px] text-muted">Amber ports are admin panels or databases. Those usually shouldn't face the network.</p>}
+ </div>
+ <div className="min-w-0 border-t border-line px-[18px] py-4 lg:border-t-0">
+ <div className="mb-1 flex items-baseline justify-between"><h3 className="m-0 text-[13px] font-medium text-paper">Changes · 7 days</h3><span className="text-[11px] text-muted">{network.events.length ? `${network.events.length} ${network.events.length === 1 ? 'event' : 'events'}, grouped` : ''}</span></div>
+ <Changes events={network.events} />
+ </div>
+ </div>
+ </section>
+ )
+}
+
+function Stat({ label, children }) {
+ return <div className="min-w-0 px-[18px] py-3"><div className="truncate text-[11px] text-muted">{label}</div><div className="mt-1.5 whitespace-nowrap text-[17px] font-semibold text-paper">{children}</div></div>
+}
+
+const FILTERS = { reachable: (row) => row.reachable, local: (row) => !row.reachable, all: () => true }
+
+export function NetworkTab({ server, samples, minutes, onTab }) {
+ const [filter, setFilter] = useState('reachable')
+ const [sort, setSort] = useState('risk')
+ const [all, setAll] = useState(false)
+ const network = server.network || { listeners: [], events: [] }
+ const rows = useMemo(() => listenerRows(server), [server])
+ const traffic = useMemo(() => trafficRates(samples), [samples])
+ const total = counts(server)
+ const firewall = firewallSummary(server)
+ const risky = rows.filter((row) => row.risky).length
+ const latest = traffic[traffic.length - 1]
+ const peak = niceCeiling(Math.max(0.1, ...traffic.flatMap((point) => [point.in ?? 0, point.out ?? 0])))
+ const shown = sortListeners(rows.filter(FILTERS[filter]), sort)
+ const limit = 8
+ const visible = all ? shown : shown.slice(0, limit)
+ const hidden = all ? [] : shown.slice(limit)
+ const interfaces = server.system?.interfaces || []
+ const bound = (row) => (row.scope === 'any' ? '0.0.0.0' : row.scope === 'loopback' ? '127.0.0.1' : 'one address')
+ const reach = (row) => (row.scope === 'any' ? 'every network' : row.scope === 'loopback' ? 'this machine' : 'one network')
+ if (!network.listeners.length) {
+ return <p className="m-0 px-[18px] py-10 text-center text-[13px] text-muted">The collector on {server.hostname} has not reported its listening ports, so there is nothing to show here yet.</p>
+ }
+ return <>
+ <StatStrip columns="md:grid-cols-3 xl:grid-cols-5">
+ <Stat label="Listening">{total.listening} <span className="text-[11px] font-normal text-muted">ports</span></Stat>
+ <Stat label="Reachable from other machines"><span className={total.reachable ? 'text-warn' : ''}>{total.reachable}</span></Stat>
+ <Stat label="Admin panels or databases exposed"><span className={risky ? 'text-warn' : ''}>{risky}</span></Stat>
+ <Stat label="Firewall"><span className={`text-sm ${firewall.tone === 'warn' ? 'text-warn' : firewall.tone === 'unknown' ? 'text-muted' : ''}`}>{firewall.text}</span></Stat>
+ <Stat label="Traffic now">{rate(latest?.in)} <span className="text-[11px] font-normal text-muted">MB/s in</span> {rate(latest?.out)} <span className="text-[11px] font-normal text-muted">MB/s out</span></Stat>
+ </StatStrip>
+ <div className="grid xl:grid-cols-[minmax(0,1fr)_331px] xl:divide-x xl:divide-line">
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-3 px-[18px] py-3">
+ <div className="seg" role="group" aria-label="Show ports">
+ <button type="button" aria-pressed={filter === 'reachable'} onClick={() => setFilter('reachable')}>Reachable {total.reachable}</button>
+ <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
+ <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">
+ <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>
+ </tr></thead>
+ <tbody>
+ {visible.map((row) => (
+ <tr key={`${row.proto}-${row.label}`} className="h-[54px] border-t border-line" style={row.risky ? { boxShadow: 'inset 2px 0 0 var(--color-warn)' } : undefined}>
+ <td className="mono pl-[18px] text-paper">{row.label}</td>
+ <td className="text-soft">{row.proto}</td>
+ <td>
+ <div className={`text-[13px] font-medium ${row.owner ? 'text-paper' : 'text-muted'}`}>{row.owner || 'host process'}</div>
+ <div className="text-[11px] text-muted">{row.ownerKind === 'container' ? `container${row.what ? ` · ${row.what}` : ''}` : row.owner ? 'host process' : 'not published by a container'}</div>
+ </td>
+ <td className="mono text-soft">{bound(row)}</td>
+ <td className={row.scope === 'any' ? 'text-warn' : 'text-paper'}>{reach(row)}</td>
+ <td className="text-soft">{row.rule ? RULE_NAMES[row.rule] || 'allowed' : row.reachable ? 'no rule' : '—'}</td>
+ <td className="pr-[18px] text-muted">{row.reason}</td>
+ </tr>
+ ))}
+ {!visible.length && <tr className="border-t border-line"><td colSpan={7} className="px-[18px] py-6 text-center text-muted">No ports in this view.</td></tr>}
+ </tbody>
+ </table>
+ </div>
+ {hidden.length > 0 && <button type="button" onClick={() => setAll(true)} className="block h-10 w-full truncate border-0 border-t border-solid border-line bg-transparent px-[18px] text-left text-xs text-muted hover:bg-raised hover:text-soft">{hidden.length} more · {hidden.slice(0, 6).map((row) => `${row.owner || row.proto} ${row.label}`).join(', ')}{hidden.length > 6 ? '…' : ''}</button>}
+ </div>
+ <div className="min-w-0 border-t border-line px-[18px] py-4 xl:border-t-0">
+ <div className="mb-4 flex items-baseline gap-2"><h3 className="m-0 text-[13px] font-semibold text-paper">Traffic</h3><span className="text-xs text-muted">MB/s · last {rangeLabel(minutes)}</span></div>
+ <LineChart label={`Network traffic on ${server.hostname}`} points={traffic.map((point) => ({ time: point.time, value: point.in }))} second={traffic.map((point) => ({ time: point.time, value: point.out }))} max={peak} ticks={[peak, peak / 2, 0]} format={(tick) => String(Number(tick.toFixed(2)))} area height={92} gutter={28} />
+ <div className="mt-2.5 flex gap-5 pl-7 text-[11px] text-muted"><span><span className="mr-2 inline-block h-px w-3.5 bg-paper align-middle" />in</span><span><span className="mr-2 inline-block w-3.5 border-t border-dashed border-muted align-middle" />out</span></div>
+
+ <h3 className="m-0 mb-1 mt-6 text-[13px] font-semibold text-paper">Interfaces</h3>
+ {interfaces.length ? <ul className="m-0 list-none divide-y divide-line p-0">{interfaces.map((item) => (
+ <li key={item.name} className="grid h-9 grid-cols-[84px_minmax(0,1fr)_auto] items-center gap-2 text-xs">
+ <span className="mono truncate text-paper">{item.name}</span>
+ <span className="truncate text-soft">{[item.network, item.speed_mbit ? `${item.speed_mbit >= 1000 ? `${item.speed_mbit / 1000} Gbit/s` : `${item.speed_mbit} Mbit/s`}` : null].filter(Boolean).join(' · ') || 'no address'}</span>
+ <span className="text-muted">{item.rx_mbps != null ? `${rate(item.rx_mbps + (item.tx_mbps || 0))} MB/s` : ''}</span>
+ </li>
+ ))}</ul> : <p className="m-0 text-xs text-muted">Reported once this machine's collector is updated.</p>}
+
+ <div className="mb-1 mt-6 flex items-baseline justify-between"><h3 className="m-0 text-[13px] font-semibold text-paper">Changes <span className="ml-1.5 text-xs font-normal text-muted">7 days</span></h3><button type="button" className="link text-xs" onClick={() => onTab('events')}>Events tab</button></div>
+ <Changes events={network.events} limit={3} compact />
+ </div>
+ </div>
+ <p className="m-0 border-t border-line px-[18px] py-3 text-xs text-muted">Firewall rules are read from ufw, iptables and /etc/nftables.conf, not the live ruleset, and a rule is only matched to a port when the file names that port.{server.system?.listener_owners ? '' : ' Ports no container publishes belong to host processes; naming them needs the optional port-owners helper, which is off by default (see SECURITY.md).'}</p>
+ </>
+}
diff --git a/src/frontend/src/dashboard/ServerPanel.jsx b/src/frontend/src/dashboard/ServerPanel.jsx
new file mode 100644
index 0000000..65db7fd
--- /dev/null
+++ b/src/frontend/src/dashboard/ServerPanel.jsx
@@ -0,0 +1,145 @@
+// One server, one view: a header with what the machine is, tabs, and the live Overview tab.
+import { useState } from 'react'
+import { Link } from 'react-router-dom'
+import { LineChart, Meter } from './charts.jsx'
+import { forecastKey } from './data.js'
+import { forecastPhrase, formatPercent, formatUsedOfTotal, healthChecks, healthVerdict, mountLevel, niceCeiling, serverMounts, serverState, shortKernel } 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: '' }
+export const INTERVALS = [[15, '15 s'], [30, '30 s'], [60, '1 min'], [300, '5 min'], [900, '15 min']]
+export const TABS = ['overview', 'containers', 'network', 'system', 'events']
+
+export function intervalLabel(seconds) {
+ return INTERVALS.find(([value]) => value === seconds)?.[1] || (seconds < 60 ? `${seconds} s` : `${Math.round(seconds / 60)} min`)
+}
+
+function Metric({ label, value, unit, children }) {
+ return (
+ <div className="min-w-0 px-[18px] pb-5 pt-[26px]">
+ <div className="mb-5 flex items-baseline justify-between gap-3">
+ <span className="text-xs font-medium text-soft">{label}</span>
+ <span className="whitespace-nowrap"><span className="text-2xl font-semibold leading-none tracking-[-0.01em] text-paper">{value}</span>{unit && <span className="ml-2 text-[11px] text-muted">{unit}</span>}</span>
+ </div>
+ {children}
+ </div>
+ )
+}
+
+function HealthChecks({ server }) {
+ const [help, setHelp] = useState(false)
+ const checks = healthChecks(server)
+ return (
+ <div className="min-w-0 px-[18px] pb-4 pt-[22px]">
+ <div className="mb-2.5 flex items-baseline justify-between"><span className="text-xs font-medium text-soft">Health checks</span><span className="text-[11px] text-muted">{healthVerdict(checks)}</span></div>
+ <ul className="m-0 list-none divide-y divide-line p-0">
+ {checks.map((check) => (
+ <li key={check.key} className="grid h-[30px] grid-cols-[18px_84px_minmax(0,1fr)] items-center text-xs">
+ <span className={`dot ${TONE_DOT[check.tone]}`} style={{ width: 6, height: 6 }} />
+ <span className="text-muted">{check.label}</span>
+ <span className={`truncate ${check.tone === 'warn' ? 'text-warn' : check.tone === 'unknown' ? 'text-muted' : 'text-paper'}`} title={check.text}>
+ {check.text}{check.action && <> · <button type="button" className="link" aria-expanded={help} onClick={() => setHelp((open) => !open)}>{check.action}</button></>}
+ </span>
+ </li>
+ ))}
+ </ul>
+ {help && <p className="mb-0 mt-2 text-[11px] leading-[18px] text-muted">The internet check is off until this machine's collector is given targets: set <span className="mono text-soft">HOMELAB_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>}
+ </div>
+ )
+}
+
+export function DiskRows({ server, overview, forecasts }) {
+ const mounts = serverMounts(server)
+ if (!mounts.length) return null
+ return (
+ <div className="divide-y divide-line border-t border-line">
+ {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="grid min-h-[38px] grid-cols-[minmax(90px,150px)_minmax(80px,1fr)_auto] items-center gap-x-4 px-[18px] py-2 md:grid-cols-[150px_minmax(120px,1fr)_180px_200px]">
+ <span className="mono truncate text-paper" title={mount.fs_type ? `${mount.mount} (${mount.fs_type})` : mount.mount}>{mount.mount}</span>
+ <Meter percent={mount.used_pct} level={level} label={`${mount.mount} usage`} />
+ <span className={`whitespace-nowrap text-xs ${level === 2 ? 'text-signal' : level === 1 ? 'text-warn' : 'text-paper'}`}>{mount.total_gb != null ? `${formatUsedOfTotal(mount.used_gb, mount.total_gb, ' of ')} · ` : ''}{formatPercent(mount.used_pct)}</span>
+ <span className="hidden truncate text-xs text-muted md:block">{forecast || 'No clear growth trend'}</span>
+ </div>
+ )
+ })}
+ </div>
+ )
+}
+
+function OverviewTab({ server, overview, samples, forecasts }) {
+ const host = server.host
+ if (!host) return <p className="m-0 px-[18px] 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>
+ const series = (key) => samples.map((sample) => ({ time: sample.time, value: sample[key] }))
+ const cores = server.cpu_cores || 1
+ const loadPeak = Math.max(cores, ...samples.map((sample) => sample.load ?? 0))
+ 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">
+ <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>
+ <Metric label="Memory" value={formatPercent(host.ram_pct)}>
+ <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} />
+ </Metric>
+ <HealthChecks server={server} />
+ </div>
+ <DiskRows server={server} overview={overview} forecasts={forecasts} />
+ </>
+}
+
+export function ServerHeader({ server, isAdmin, onInterval }) {
+ const state = serverState(server)
+ const kernel = shortKernel(server.system?.kernel)
+ const meta = [server.os_info?.replace(/ \((.*)\)$/, ''), kernel ? `kernel ${kernel}` : null, server.cpu_cores ? `${server.cpu_cores} cores` : null, server.total_ram_gb ? `${Number(server.total_ram_gb.toFixed(1))} GB` : null, server.ip_address].filter(Boolean)
+ return (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-[18px] pb-1 pt-4">
+ <span className={`dot ${STATE_DOT[state]}`} />
+ <h2 className="m-0 text-[17px] font-semibold text-paper">{server.hostname}</h2>
+ {server.is_dashboard_host && <span className="chip">this machine</span>}
+ <span className="min-w-0 truncate text-xs text-muted">{meta.join(' · ')}</span>
+ <span className="ml-auto flex items-center gap-3">
+ <label className="flex items-center gap-3 text-xs text-muted">Check every
+ {isAdmin ? <select className="select" 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="font-medium text-paper">{intervalLabel(server.check_interval_seconds)}</span>}
+ </label>
+ <Link to={`/statistics?server=${server.id}`} className="btn">Full history</Link>
+ </span>
+ </div>
+ )
+}
+
+export function ServerTabs({ server, tab, onTab, listening }) {
+ const tabs = [
+ ['overview', 'Overview', null],
+ ['containers', 'Containers', server.containers?.length ? String(server.containers.length) : null],
+ ['network', 'Network', listening ? `${listening} ${listening === 1 ? 'port' : 'ports'}` : null],
+ ['system', 'System', null],
+ ['events', 'Events', '7 d'],
+ ]
+ return (
+ <div role="tablist" aria-label={`${server.hostname} sections`} className="no-scrollbar flex gap-7 overflow-x-auto border-b border-line px-7">
+ {tabs.map(([id, label, count]) => <button key={id} type="button" role="tab" id={`server-tab-${id}`} aria-selected={tab === id} aria-controls="server-tabpanel" className="tab" onClick={() => onTab(id)}>{label}{count && <small>{count}</small>}</button>)}
+ </div>
+ )
+}
+
+export function ServerPanel({ server, overview, tab, onTab, isAdmin, onInterval, samples, forecasts, listening, children }) {
+ return (
+ <section className="card overflow-hidden" aria-label={`Server ${server.hostname}`}>
+ <ServerHeader server={server} isAdmin={isAdmin} onInterval={onInterval} />
+ <ServerTabs server={server} tab={tab} onTab={onTab} listening={listening} />
+ <div role="tabpanel" id="server-tabpanel" aria-labelledby={`server-tab-${tab}`}>
+ {tab === 'overview' ? <OverviewTab server={server} overview={overview} samples={samples} forecasts={forecasts} /> : children}
+ </div>
+ </section>
+ )
+}
diff --git a/src/frontend/src/dashboard/SystemTab.jsx b/src/frontend/src/dashboard/SystemTab.jsx
new file mode 100644
index 0000000..2b075f9
--- /dev/null
+++ b/src/frontend/src/dashboard/SystemTab.jsx
@@ -0,0 +1,200 @@
+// Facts about the machine, grouped by the question they answer, each with one verdict line.
+import { useState } from 'react'
+import { Icon } from '../icons.jsx'
+import { Meter } from './charts.jsx'
+import { forecastKey, usePolled } from './data.js'
+import { bootHistory, forecastPhrase, formatPercent, formatSpan, formatUsedOfTotal, mountLevel, serverMounts, shortKernel } from './logic.js'
+
+const DAY = 24 * 3600 * 1000
+const HELPER_COMMAND = 'docker compose --profile system-events up -d'
+const PRUNE_COMMAND = 'docker image prune -a && docker builder prune'
+const when = (time) => new Date(time).toLocaleString([], { weekday: 'short', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', hour12: false })
+
+function Card({ title, aside, children, className = '' }) {
+ return (
+ <div className={`min-w-0 px-[18px] pb-5 pt-[18px] ${className}`}>
+ <div className="mb-3 flex items-baseline justify-between gap-3"><h3 className="m-0 text-[13px] font-semibold text-paper">{title}</h3>{aside && <span className="text-[11px] text-muted">{aside}</span>}</div>
+ {children}
+ </div>
+ )
+}
+
+function Rows({ items }) {
+ return <dl className="kv m-0">{items.filter(Boolean).map(([label, value, options = {}]) => <div key={label} className="contents"><dt>{label}</dt><dd className={`truncate ${options.mono ? 'mono' : ''} ${options.tone === 'warn' ? 'text-warn' : options.tone === 'muted' ? 'text-muted' : 'text-paper'}`} title={typeof value === 'string' ? value : undefined}>{value}</dd></div>)}</dl>
+}
+
+function Verdict({ tone, children }) {
+ return <p className={`mb-0 mt-3.5 flex items-center gap-2.5 text-xs ${tone === 'warn' ? 'text-warn' : 'text-paper'}`}><span className={`dot ${tone === 'warn' ? 'dot-warn' : 'dot-ok'}`} style={{ width: 6, height: 6 }} />{children}</p>
+}
+
+function Boots({ serverId }) {
+ const { data } = usePolled(`/monitoring/servers/${serverId}/events?days=30`, null)
+ const boots = bootHistory((data?.events || []).filter((event) => event.kind === 'reboot'))
+ const unclean = boots.filter((boot) => boot.unclean)
+ const slots = [...Array.from({ length: Math.max(0, 10 - boots.length) }, () => null), ...boots]
+ return <>
+ <div className="mt-3.5 flex gap-1" role="img" aria-label={`${boots.length} boots recorded in the last 30 days, ${unclean.length} unclean`}>
+ {slots.map((boot, index) => <span key={index} title={boot ? `${when(boot.time)} · ${boot.unclean ? 'after an unclean shutdown' : 'clean'}` : 'no boot recorded'} className={`h-4 flex-1 rounded-[2px] ${!boot ? 'border border-line' : boot.unclean ? 'bg-warn' : 'bg-rail'}`} />)}
+ </div>
+ <p className="mb-0 mt-2.5 text-xs text-muted">
+ {!data ? 'Loading boot history…' : !boots.length ? 'No reboot recorded in the last 30 days.' : unclean.length ? `${unclean.length === 1 ? 'One unclean boot' : `${unclean.length} unclean boots`}, the last on ${when(unclean[unclean.length - 1].time)}.` : `${boots.length} ${boots.length === 1 ? 'boot' : 'boots'} in the last 30 days, all after a clean shutdown.`}
+ </p>
+ </>
+}
+
+// What Docker's images and build cache take, how much of it nothing uses, and the command that frees it.
+function DockerDiskRow({ disk }) {
+ const [shown, setShown] = useState(false)
+ const [copied, setCopied] = useState(false)
+ const copy = async () => {
+ try { await navigator.clipboard.writeText(PRUNE_COMMAND); setCopied(true); setTimeout(() => setCopied(false), 1500) } catch { setCopied(false) }
+ }
+ const used = (disk.images_gb ?? 0) + (disk.build_cache_gb ?? 0)
+ const reclaimable = (disk.images_unused_gb ?? 0) + (disk.build_cache_unused_gb ?? 0)
+ const gb = (value) => `${Number(value.toFixed(value >= 10 ? 0 : 1))} GB`
+ return <>
+ <tr className="h-[42px] border-t border-line">
+ <td className="mono pl-[18px] text-paper">/var/lib/docker</td>
+ <td className="mono text-muted">—</td>
+ <td className="whitespace-nowrap text-soft">images + cache</td>
+ <td className="pr-6"><Meter percent={used ? (reclaimable / used) * 100 : 0} label="Share of Docker's disk use that nothing uses" /></td>
+ <td className="whitespace-nowrap pr-6 text-paper">{gb(used)} · {gb(reclaimable)} reclaimable</td>
+ <td className="text-soft">{disk.images_unused != null ? `${disk.images_unused} of ${disk.images} images not used by a container` : ''}</td>
+ <td className="pr-[18px]">{reclaimable >= 0.1 && <button type="button" className="btn btn-sm" aria-expanded={shown} onClick={() => setShown((open) => !open)}>{shown ? 'Hide command' : 'Show prune command'}</button>}</td>
+ </tr>
+ {shown && <tr className="border-t border-line bg-sunken"><td colSpan={7} className="px-[18px] py-3">
+ <div className="flex max-w-[780px] items-center gap-3 rounded-md border border-line bg-bg py-2 pl-3.5 pr-2"><code className="mono min-w-0 flex-1 truncate text-paper">{PRUNE_COMMAND}</code><button type="button" className="btn btn-sm" onClick={copy}><Icon name={copied ? 'check' : 'copy'} size={13} />{copied ? 'Copied' : 'Copy'}</button></div>
+ <p className="mb-0 mt-2 text-[11px] text-muted">Run it on this machine yourself; Infradeck never deletes anything. It removes every image no container uses and the unused build cache, so images you keep for later will have to be pulled again.</p>
+ </td></tr>}
+ </>
+}
+
+function HelperCard({ installed }) {
+ const [shown, setShown] = useState(false)
+ const [copied, setCopied] = useState(false)
+ const copy = async () => {
+ try { await navigator.clipboard.writeText(HELPER_COMMAND); setCopied(true); setTimeout(() => setCopied(false), 1500) } catch { setCopied(false) }
+ }
+ return (
+ <Card title={<>System helper <span className={`chip ml-2 align-middle font-normal ${installed ? 'chip-ok' : ''}`}>{installed ? 'installed' : 'not installed'}</span></>} className="lg:col-span-2">
+ <p className="m-0 max-w-[780px] text-xs leading-[21px] text-soft">
+ {installed ? 'The helper is running, so shutdown history, the names of processes the OOM killer stopped and kernel errors come from the kernel log rather than from counters.'
+ : "Without it, Infradeck can't read shutdown history, OOM process names or kernel errors, so those rows above come from counters and files and may be incomplete. It's a small read-only container whose only privilege is reading the kernel log."}
+ </p>
+ {!installed && <div className="mt-3.5 flex flex-wrap items-center gap-3">
+ <button type="button" className="btn" aria-expanded={shown} onClick={() => setShown((open) => !open)}><Icon name="download" size={14} />Install system helper</button>
+ <span className="text-xs text-muted">Read SECURITY.md first. Nothing here can change the machine.</span>
+ </div>}
+ {shown && !installed && <div className="mt-3 flex max-w-[780px] items-center gap-3 rounded-md border border-line bg-bg py-2 pl-3.5 pr-2">
+ <code className="mono min-w-0 flex-1 truncate text-paper">{HELPER_COMMAND}</code>
+ <button type="button" className="btn btn-sm" onClick={copy}><Icon name={copied ? 'check' : 'copy'} size={13} />{copied ? 'Copied' : 'Copy'}</button>
+ </div>}
+ {shown && !installed && <p className="mb-0 mt-2 text-[11px] text-muted">Run it on this machine, in the folder with the collector's compose file.</p>}
+ </Card>
+ )
+}
+
+export function SystemTab({ server, overview, forecasts, isAdmin, onDelete, deleting }) {
+ const host = server.host || {}
+ const system = server.system || {}
+ const events = server.system_events || []
+ const recent = (kind) => events.filter((event) => event.kind === kind && Date.now() - new Date(event.time).getTime() < DAY)
+ const ooms = recent('oom_kill')
+ const kernelErrors = [...recent('kernel_error'), ...recent('kernel_fault')]
+ const rebootKernel = shortKernel(system.reboot_kernel)
+ const bootedAt = host.system_uptime_seconds != null ? Date.now() - host.system_uptime_seconds * 1000 : null
+ const temperatures = system.temperatures || []
+ const collectorCurrent = system.collector_version && overview.version && system.collector_version === overview.version
+ const mounts = serverMounts(server)
+ const outdated = !system.collector_version
+
+ return <>
+ <div className="grid divide-y divide-line lg:grid-cols-3 lg:divide-x lg:divide-y-0">
+ <Card title="Operating system">
+ <Rows items={[
+ ['Distribution', server.os_info || 'Unknown'],
+ ['Kernel', system.kernel || 'Not reported', { mono: Boolean(system.kernel), tone: system.kernel ? undefined : 'muted' }],
+ ['Architecture', system.arch || 'Not reported', { mono: Boolean(system.arch), tone: system.arch ? undefined : 'muted' }],
+ ['Hostname', server.hostname, { mono: true }],
+ ]} />
+ {host.reboot_required ? <Verdict tone="warn">Reboot needed{rebootKernel ? ` for kernel ${rebootKernel}` : ''}</Verdict> : host.reboot_required === false && <Verdict>No reboot pending</Verdict>}
+ </Card>
+ <Card title="Updates" aside={system.updates_manager ? `${system.updates_manager}${system.updates_checked_at ? ` · checked ${formatSpan(Date.now() / 1000 - system.updates_checked_at)} ago` : ''}` : null}>
+ {system.updates_manager ? <Rows items={[
+ ['Pending', system.updates_pending == null ? 'Not reported' : `${system.updates_pending} ${system.updates_pending === 1 ? 'package' : 'packages'}`, { tone: system.updates_pending == null ? 'muted' : undefined }],
+ ['Security', system.updates_security == null ? 'Not reported' : system.updates_security ? `${system.updates_security} waiting` : 'None waiting', { tone: system.updates_security ? 'warn' : system.updates_security == null ? 'muted' : undefined }],
+ ['Automatic', system.auto_updates == null ? 'Not configured' : `unattended-upgrades ${system.auto_updates ? 'on' : 'off'}`, { tone: system.auto_updates === false ? 'warn' : system.auto_updates == null ? 'muted' : undefined }],
+ ['Last applied', system.updates_applied_at ? when(system.updates_applied_at * 1000) : 'Unknown', { tone: system.updates_applied_at ? undefined : 'muted' }],
+ ]} /> : <p className="m-0 text-xs leading-[21px] text-muted">{outdated ? 'Reported once this machine\'s collector is updated.' : 'Update state is read from apt, so it is only shown for Debian and Ubuntu.'}</p>}
+ </Card>
+ <Card title="Hardware">
+ <Rows items={[
+ ['CPU', [system.cpu_model, server.cpu_cores ? `${server.cpu_cores} cores` : null].filter(Boolean).join(' · ') || 'Unknown'],
+ ['Memory', server.total_ram_gb ? `${Number(server.total_ram_gb.toFixed(1))} GB · ${formatPercent(host.ram_pct)} used` : 'Unknown'],
+ ['Swap', system.swap_total_gb === 0 ? 'None' : `${system.swap_total_gb != null ? `${Number(system.swap_total_gb.toFixed(1))} GB · ` : ''}${formatPercent(host.swap_pct)} used`, { tone: host.swap_pct >= (overview.alert_thresholds?.swap_warning_pct ?? 50) ? 'warn' : undefined }],
+ ['Temperature', temperatures.length ? temperatures.slice(0, 3).map((sensor) => `${Math.round(sensor.celsius)} °C ${sensor.label}`).join(' · ') : 'No sensors visible', { tone: temperatures.length ? undefined : 'muted' }],
+ ]} />
+ </Card>
+ </div>
+ <div className="grid divide-y divide-line border-t border-line lg:grid-cols-3 lg:divide-x lg:divide-y-0">
+ <Card title="Uptime and boots" aside="last 10 boots">
+ <Rows items={[
+ ['Up since', bootedAt ? `${when(bootedAt)} · ${formatSpan(host.system_uptime_seconds)}` : 'Unknown'],
+ ['Last shutdown', host.last_shutdown === 'clean' ? 'Clean' : host.last_shutdown === 'unclean' ? 'Unclean: crash, power loss or forced reset' : 'Unknown without the system helper', { tone: host.last_shutdown === 'unclean' ? 'warn' : host.last_shutdown === 'clean' ? undefined : 'muted' }],
+ ]} />
+ <Boots serverId={server.id} />
+ </Card>
+ <Card title="Time">
+ <Rows items={[
+ ['Sync', host.ntp_synced == null ? 'Unknown' : `${system.time_service ? `${system.time_service} · ` : ''}${host.ntp_synced ? 'synced' : 'not synced'}`, { tone: host.ntp_synced === false ? 'warn' : host.ntp_synced == null ? 'muted' : undefined }],
+ ['Offset', system.clock_offset_ms == null ? 'Not reported' : `${Number(Math.abs(system.clock_offset_ms).toFixed(Math.abs(system.clock_offset_ms) < 10 ? 1 : 0))} ms`, { tone: system.clock_offset_ms == null ? 'muted' : undefined }],
+ ['Time zone', system.timezone || 'Not reported', { tone: system.timezone ? undefined : 'muted' }],
+ ]} />
+ {host.ntp_synced != null && <Verdict tone={host.ntp_synced ? 'ok' : 'warn'}>{host.ntp_synced ? 'Clock is fine' : 'Clock is not synchronized'}</Verdict>}
+ </Card>
+ <Card title="Kernel and memory pressure" aside="24 h">
+ <Rows items={[
+ ['OOM kills', host.oom_kill_total == null ? 'Unknown' : ooms.length ? `${ooms.length} · ${ooms[0].detail}` : 'None', { tone: ooms.length ? 'warn' : host.oom_kill_total == null ? 'muted' : undefined }],
+ ['Kernel errors', kernelErrors.length ? `${kernelErrors.length} · ${kernelErrors[0].detail}` : host.kernel_tainted == null ? 'Unknown' : 'None', { tone: kernelErrors.length ? 'warn' : host.kernel_tainted == null ? 'muted' : undefined }],
+ ['Disk errors', system.disk_io_errors == null ? 'No counter on these disks' : system.disk_io_errors ? `${system.disk_io_errors} I/O ${system.disk_io_errors === 1 ? 'error' : 'errors'} since boot` : 'None', { tone: system.disk_io_errors ? 'warn' : system.disk_io_errors == null ? 'muted' : undefined }],
+ ]} />
+ </Card>
+ </div>
+ <div className="grid divide-y divide-line border-t border-line lg:grid-cols-3 lg:divide-x lg:divide-y-0">
+ <Card title="Software">
+ <Rows items={[
+ ['Docker', host.docker_status === 'not_configured' ? 'Not found on this machine' : system.docker_version || (host.docker_status === 'unreachable' ? 'Unreachable' : 'Version not reported'), { tone: host.docker_status === 'unreachable' ? 'warn' : system.docker_version ? undefined : 'muted' }],
+ ['Collector', system.collector_version ? `${system.collector_version} · ${collectorCurrent ? 'up to date' : `dashboard is ${overview.version}`}` : 'Older than 0.9.2', { tone: system.collector_version && collectorCurrent ? undefined : 'warn' }],
+ ['Proxy', host.docker_status === 'not_configured' ? 'Not used' : 'Docker socket proxy, read-only'],
+ ['Port names', system.listener_owners ? 'port-owners helper running' : 'Off (optional helper)', { tone: system.listener_owners ? undefined : 'muted' }],
+ ['Checks every', formatSpan(server.check_interval_seconds)],
+ ]} />
+ {isAdmin && <button type="button" className="btn btn-sm mt-4 border-signal/50 text-signal hover:!border-signal hover:!bg-signal/10" onClick={() => onDelete(server)} disabled={deleting}>{deleting ? 'Removing…' : 'Remove this server'}</button>}
+ </Card>
+ <HelperCard installed={Boolean(system.helper_installed)} />
+ </div>
+ {mounts.length > 0 && <div className="border-t border-line">
+ <div className="flex items-baseline gap-2.5 px-[18px] pb-2 pt-[18px]"><h3 className="m-0 text-[13px] font-semibold text-paper">Disks and mounts</h3><span className="text-xs text-muted">forecast from the last 30 days</span></div>
+ <div className="custom-scroll overflow-x-auto">
+ <table className="w-full min-w-[820px] border-collapse text-left text-xs">
+ <thead><tr className="grid-head h-9"><th className="pl-[18px] font-medium">Mount</th><th className="font-medium">Device</th><th className="font-medium">Type</th><th className="w-[28%] font-medium">Used</th><th className="font-medium" /><th className="font-medium">Forecast</th><th className="pr-[18px] font-medium">Inodes</th></tr></thead>
+ <tbody>{mounts.map((mount) => {
+ const level = mountLevel(mount, overview.disk_thresholds, overview.mount_thresholds)
+ const inodeLevel = mount.inodes_pct >= (overview.disk_thresholds?.inodes_critical_pct ?? 95) ? 2 : mount.inodes_pct >= (overview.disk_thresholds?.inodes_warning_pct ?? 85) ? 1 : 0
+ return (
+ <tr key={mount.mount} className="h-[42px] border-t border-line">
+ <td className="mono pl-[18px] text-paper">{mount.mount}</td>
+ <td className="mono text-muted">{system.mount_devices?.[mount.mount] || '—'}</td>
+ <td className="text-soft">{mount.fs_type || '—'}</td>
+ <td className="pr-6"><Meter percent={mount.used_pct} level={level} label={`${mount.mount} usage`} /></td>
+ <td className={`whitespace-nowrap pr-6 ${level === 2 ? 'text-signal' : level === 1 ? 'text-warn' : 'text-paper'}`}>{mount.total_gb != null ? `${formatUsedOfTotal(mount.used_gb, mount.total_gb, ' of ')} · ` : ''}{formatPercent(mount.used_pct)}</td>
+ <td className="text-soft">{forecastPhrase(forecasts[forecastKey(server.id, mount.mount)]) || 'No clear growth trend'}</td>
+ <td className={`pr-[18px] ${inodeLevel === 2 ? 'text-signal' : inodeLevel === 1 ? 'text-warn' : 'text-soft'}`}>{mount.inodes_pct == null ? '—' : `${formatPercent(mount.inodes_pct)} used`}</td>
+ </tr>
+ )
+ })}{system.docker_disk && <DockerDiskRow disk={system.docker_disk} />}</tbody>
+ </table>
+ </div>
+ </div>}
+ </>
+}
diff --git a/src/frontend/src/dashboard/charts.jsx b/src/frontend/src/dashboard/charts.jsx
new file mode 100644
index 0000000..4655a55
--- /dev/null
+++ b/src/frontend/src/dashboard/charts.jsx
@@ -0,0 +1,68 @@
+// 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'
+
+const clock = (time) => (time ? new Date(time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false }) : '')
+
+// A small trend line with a dot on the latest value. ``max`` fixes the scale so rows can be compared.
+export function Sparkline({ values, max = 100, width = 76, height = 18, tone = 'paper', className = '' }) {
+ const known = (values || []).filter((value) => value != null)
+ const color = tone === 'signal' ? 'var(--color-signal)' : 'var(--color-soft)'
+ if (known.length < 2) return <svg width={width} height={height} className={className} aria-hidden="true"><line x1="0" x2={width - 3} y1={height - 2} y2={height - 2} stroke="var(--color-edge)" strokeWidth="1" /></svg>
+ const top = Math.max(max, ...known)
+ const usable = width - 3
+ const y = (value) => 1.5 + (1 - Math.max(0, value) / top) * (height - 3.5)
+ const points = values.map((value, index) => (value == null ? null : [(index / (values.length - 1)) * usable, y(value)])).filter(Boolean)
+ const last = points[points.length - 1]
+ return (
+ <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} className={className} aria-hidden="true">
+ <polyline points={points.map((point) => point.map((part) => part.toFixed(1)).join(',')).join(' ')} fill="none" stroke={color} strokeWidth="1.2" strokeLinejoin="round" strokeLinecap="round" />
+ <circle cx={last[0]} cy={last[1]} r="1.6" fill={color} />
+ </svg>
+ )
+}
+
+// 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 }) {
+ const gradient = useId()
+ const usable = (points || []).filter((point) => point.value != null)
+ const times = (points || []).map((point) => new Date(point.time).getTime())
+ const start = times[0]
+ const span = Math.max(1, (times[times.length - 1] ?? 0) - (start ?? 0))
+ const x = (time) => ((new Date(time).getTime() - start) / span) * 100
+ const y = (value) => (1 - Math.min(Math.max(value, 0), max) / max) * 100
+ const path = (series) => {
+ let drawing = false
+ return series.map((point) => {
+ if (point.value == null) { drawing = false; return '' }
+ const command = `${drawing ? 'L' : 'M'}${x(point.time).toFixed(2)},${y(point.value).toFixed(2)}`
+ drawing = true
+ return command
+ }).join(' ')
+ }
+ const line = usable.length > 1 ? path(points) : ''
+ const fill = area && usable.length > 1 ? `M${x(usable[0].time).toFixed(2)},100 ${usable.map((point) => `L${x(point.time).toFixed(2)},${y(point.value).toFixed(2)}`).join(' ')} L${x(usable[usable.length - 1].time).toFixed(2)},100 Z` : ''
+ return (
+ <figure className="m-0" aria-label={label} role="img">
+ <div className="relative" style={{ height, marginLeft: gutter }}>
+ {ticks.map((tick) => <span key={tick} aria-hidden="true" className="absolute right-full -translate-y-1/2 whitespace-nowrap pr-2.5 text-[11px] leading-none text-muted" style={{ top: `${y(tick)}%` }}>{format(tick)}</span>)}
+ <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="absolute inset-0 h-full w-full overflow-visible">
+ <defs><linearGradient id={gradient} x1="0" x2="0" y1="0" y2="1"><stop offset="0%" stopColor="var(--color-paper)" stopOpacity="0.2" /><stop offset="100%" stopColor="var(--color-paper)" stopOpacity="0.02" /></linearGradient></defs>
+ {ticks.map((tick) => <line key={tick} x1="0" x2="100" y1={y(tick)} y2={y(tick)} stroke="var(--color-line)" strokeWidth="1" vectorEffect="non-scaling-stroke" />)}
+ {fill && <path d={fill} fill={`url(#${gradient})`} />}
+ {second && <path d={path(second)} fill="none" stroke="var(--color-muted)" strokeWidth="1.2" strokeDasharray="3 3" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />}
+ {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>}
+ </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>
+ )
+}
+
+// A value's share of its limit as a thin bar. ``level``: 0 plain, 1 warning, 2 critical.
+export function Meter({ percent, level = 0, label, className = '' }) {
+ const value = Math.min(100, Math.max(0, percent ?? 0))
+ return <span className={`meter ${level === 2 ? 'meter-signal' : level === 1 ? 'meter-warn' : ''} ${className}`} role="meter" aria-label={label} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(value)}><i style={{ width: `${value}%`, minWidth: percent > 0 ? 3 : 0 }} /></span>
+}
diff --git a/src/frontend/src/dashboard/data.js b/src/frontend/src/dashboard/data.js
new file mode 100644
index 0000000..ad222b9
--- /dev/null
+++ b/src/frontend/src/dashboard/data.js
@@ -0,0 +1,55 @@
+// Data the Overview page loads next to the shared overview poll.
+import { useEffect, useRef, useState } from 'react'
+import { apiRequest } from '../api.js'
+import { daysUntilFull, seriesFor } from '../chartMath.js'
+
+// GET ``path`` now and every ``seconds`` while the tab is visible. A null path loads nothing.
+// Returns { data, error, reload }; data from a previous path is dropped as soon as the path changes.
+export function usePolled(path, seconds) {
+ const [state, setState] = useState({ path: null, data: null, error: '' })
+ const reloadRef = useRef(() => {})
+ useEffect(() => {
+ if (!path) return undefined
+ let active = true
+ const load = () => apiRequest(path, { method: 'GET' })
+ .then((data) => { if (active) setState({ path, data, error: '' }) })
+ .catch((error) => { if (active) setState((current) => ({ path, data: current.path === path ? current.data : null, error: error.message || 'Could not load this.' })) })
+ reloadRef.current = load
+ load()
+ const timer = seconds ? setInterval(() => { if (!document.hidden) load() }, seconds * 1000) : null
+ return () => { active = false; if (timer) clearInterval(timer) }
+ }, [path, seconds])
+ const current = state.path === path
+ return { data: current ? state.data : null, error: current ? state.error : '', reload: () => reloadRef.current() }
+}
+
+const FORECAST_TTL_MS = 10 * 60 * 1000
+const forecastCache = new Map() // "serverId:mount" -> { days, loadedAt }
+export const forecastKey = (serverId, mount) => `${serverId}:${mount}`
+
+// Days until each asked-for filesystem is full, from its last 30 days: { "serverId:mount": days | null }.
+// Slow-moving, so each one is asked for at most every ten minutes.
+export function useForecasts(wanted) {
+ const [, bump] = useState(0)
+ const signature = wanted.map((item) => forecastKey(item.serverId, item.mount)).sort().join('|')
+ useEffect(() => {
+ let active = true
+ for (const item of wanted) {
+ const key = forecastKey(item.serverId, item.mount)
+ const cached = forecastCache.get(key)
+ if (cached && Date.now() - cached.loadedAt < FORECAST_TTL_MS) continue
+ forecastCache.set(key, { days: cached?.days ?? null, loadedAt: Date.now() })
+ apiRequest(`/monitoring/servers/${item.serverId}/mounts/history?mount=${encodeURIComponent(item.mount)}&range=30d&metrics=used_pct`, { method: 'GET' })
+ .then((result) => {
+ const series = seriesFor(result.points, 'used_pct').filter((point) => point.avg !== null).map((point) => ({ t: point.t, value: point.avg }))
+ forecastCache.set(key, { days: daysUntilFull(series), loadedAt: Date.now() })
+ if (active) bump((value) => value + 1)
+ })
+ .catch(() => { forecastCache.delete(key) })
+ }
+ return () => { active = false }
+ // The list is rebuilt every render; its contents are what matter.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [signature])
+ return Object.fromEntries(wanted.map((item) => { const key = forecastKey(item.serverId, item.mount); return [key, forecastCache.get(key)?.days ?? null] }))
+}
diff --git a/src/frontend/src/dashboard/logic.js b/src/frontend/src/dashboard/logic.js
new file mode 100644
index 0000000..378d3ea
--- /dev/null
+++ b/src/frontend/src/dashboard/logic.js
@@ -0,0 +1,684 @@
+// Pure helpers for the Overview page: what state things are in, how to group, order and word them. No React in here.
+import { problemRank } from '../containerLogic.js'
+import { isOnline } from '../fleetLogic.js'
+
+// ---------- wording ----------
+
+// 64%, 11.7%, 0.03%: one decimal, two below 1, and no trailing ".0".
+export function formatPercent(value) {
+ if (value == null || !Number.isFinite(Number(value))) return '—'
+ const number = Number(value)
+ if (number !== 0 && Math.abs(number) < 1) return `${Number(number.toFixed(2))}%`
+ return `${Number(number.toFixed(1))}%`
+}
+
+// 2.93 GB, 393 MB, 26 MB from megabytes.
+export function formatMegabytes(value) {
+ if (value == null || !Number.isFinite(Number(value))) return '—'
+ const number = Number(value)
+ if (number >= 1024 * 1024) return `${(number / 1024 / 1024).toFixed(2)} TB`
+ if (number >= 1024) return `${(number / 1024).toFixed(number >= 10240 ? 1 : 2)} GB`
+ return `${Math.round(number)} MB`
+}
+
+// 27.2, 457, 7.3 with the unit left to the caller's sentence; TB above 1024 GB.
+export function gigabyteParts(value) {
+ if (value == null || !Number.isFinite(Number(value))) return { text: '?', unit: 'GB' }
+ const number = Number(value)
+ if (number >= 1024) return { text: String(Number((number / 1024).toFixed(1))), unit: 'TB' }
+ return { text: String(Number(number.toFixed(number >= 100 ? 0 : 1))), unit: 'GB' }
+}
+
+// "27.2 / 31.3 GB", or "5.3 / 7.3 TB".
+export function formatUsedOfTotal(usedGb, totalGb, separator = ' / ') {
+ const total = gigabyteParts(totalGb)
+ const used = total.unit === 'TB' ? String(Number((Number(usedGb) / 1024).toFixed(1))) : gigabyteParts(usedGb).text
+ return `${usedGb == null ? '?' : used}${separator}${total.text} ${total.unit}`
+}
+
+// A span in the largest sensible unit: 45 s, 12 min, 2 h, 41 d.
+export function formatSpan(seconds) {
+ if (seconds == null || !Number.isFinite(seconds)) return '—'
+ const value = Math.max(0, seconds)
+ if (value < 60) return `${Math.round(value)} s`
+ if (value < 3600) return `${Math.round(value / 60)} min`
+ if (value < 86400) return `${Math.round(value / 3600)} h`
+ return `${Math.round(value / 86400)} d`
+}
+
+export function formatAge(time, now = Date.now()) {
+ const moment = new Date(time).getTime()
+ return Number.isNaN(moment) ? '—' : formatSpan((now - moment) / 1000)
+}
+
+// How long it has been quiet: "2 h 14 min", "6 days".
+export function formatQuiet(seconds) {
+ if (seconds == null || !Number.isFinite(seconds)) return '—'
+ const value = Math.max(0, seconds)
+ if (value < 3600) return `${Math.max(1, Math.round(value / 60))} min`
+ if (value < 86400) return `${Math.floor(value / 3600)} h ${Math.floor((value % 3600) / 60)} min`
+ const days = Math.round(value / 86400)
+ return `${days} ${days === 1 ? 'day' : 'days'}`
+}
+
+// "Full in about 6 months" in a few words, or null when there is no trend to speak of.
+export function forecastPhrase(days, { short = false } = {}) {
+ if (days == null || !Number.isFinite(days)) return null
+ if (days <= 0) return short ? 'full now' : 'Full now'
+ let amount
+ if (days < 1) amount = short ? '<1 d' : 'less than a day'
+ else if (days < 60) amount = short ? `${Math.round(days)} d` : `about ${Math.round(days)} ${Math.round(days) === 1 ? 'day' : 'days'}`
+ else if (days < 730) amount = short ? `~${Math.round(days / 30)} mo` : `about ${Math.round(days / 30)} months`
+ else if (days < 3650) amount = short ? `~${Number((days / 365).toFixed(1))} y` : `about ${Number((days / 365).toFixed(1))} years`
+ else return null
+ return short ? `full in ${amount}` : `Full in ${amount}`
+}
+
+const MONTH_NAMES = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
+
+// "full around April 2027".
+export function forecastMonth(days, now = Date.now()) {
+ if (days == null || !Number.isFinite(days) || days <= 0 || days >= 3650) return null
+ const date = new Date(now + days * 86400000)
+ return `full around ${MONTH_NAMES[date.getMonth()]} ${date.getFullYear()}`
+}
+
+// A total over several containers, where two decimals would be false precision: 2.9 GB, 361 MB.
+export function formatMegabytesShort(value) {
+ if (value == null || !Number.isFinite(Number(value))) return '—'
+ return Number(value) >= 1024 ? `${Number((Number(value) / 1024).toFixed(1))} GB` : `${Math.round(Number(value))} MB`
+}
+
+// ---------- servers ----------
+
+// critical | warn | offline | ok, from what is open on the server.
+export function serverState(server, now = Date.now()) {
+ const open = server.alerts_by_severity || {}
+ if (open.CRITICAL) return 'critical'
+ if (server.last_seen_at && !isOnline(server, now)) return 'offline'
+ if (open.WARNING) return 'warn'
+ return 'ok'
+}
+
+export function serverStateLabel(server, now = Date.now()) {
+ const open = server.alerts_by_severity || {}
+ if (open.CRITICAL) return `${open.CRITICAL} critical`
+ if (server.last_seen_at && !isOnline(server, now)) return 'offline'
+ if (open.WARNING) return `${open.WARNING} ${open.WARNING === 1 ? 'warning' : 'warnings'}`
+ if (!server.last_seen_at) return 'waiting'
+ return 'healthy'
+}
+
+const STATE_RANK = { critical: 0, offline: 1, warn: 2, ok: 3 }
+const byHostname = (a, b) => a.hostname.localeCompare(b.hostname, undefined, { sensitivity: 'base', numeric: true })
+
+// Problems first while anything is open; by name once the fleet is healthy.
+export function sortServers(servers, now = Date.now()) {
+ return [...servers].sort((a, b) => STATE_RANK[serverState(a, now)] - STATE_RANK[serverState(b, now)] || byHostname(a, b))
+}
+
+export function serverMounts(server) {
+ if (server.mounts?.length) return server.mounts
+ const host = server.host
+ return host?.disk_usage_pct != null ? [{ mount: '/', used_pct: host.disk_usage_pct, inodes_pct: host.disk_inodes_pct }] : []
+}
+
+export function fullestMount(mounts) {
+ return mounts.reduce((fullest, mount) => (mount.used_pct != null && (!fullest || mount.used_pct > fullest.used_pct) ? mount : fullest), null)
+}
+
+// 0 fine, 1 warning, 2 critical, by the same thresholds the alert rules use.
+export function thresholdLevel(value, warning, critical) {
+ if (value == null) return 0
+ return value >= critical ? 2 : value >= warning ? 1 : 0
+}
+
+export function mountLevel(mount, thresholds = {}, mountThresholds = {}) {
+ const own = mountThresholds?.[mount.mount]
+ return thresholdLevel(mount.used_pct, own?.disk_warning_pct ?? thresholds.disk_warning_pct ?? 85, own?.disk_critical_pct ?? thresholds.disk_critical_pct ?? 95)
+}
+
+// "Debian 12 · 8 cores · 31 GB" and "10.0.0.21 · up 41 d".
+export function systemLines(server) {
+ const first = [server.os_info?.replace(/ \((.*)\)$/, '').replace(/ LTS$/, ''), server.cpu_cores ? `${server.cpu_cores} cores` : null, server.total_ram_gb ? `${Math.round(server.total_ram_gb)} GB` : null].filter(Boolean)
+ const uptime = server.host?.system_uptime_seconds
+ const second = [server.ip_address, uptime != null ? `up ${formatSpan(uptime)}` : null].filter(Boolean)
+ return [first.join(' · '), second.join(' · ')]
+}
+
+// The kernel release without the flavour: 6.8.0-84-generic -> 6.8.0-84.
+export const shortKernel = (kernel) => (kernel ? kernel.replace(/-(generic|amd64|arm64|cloud|lowlatency|virtual|pve|default)$/i, '') : null)
+
+// ---------- needs attention ----------
+
+export const needsAttention = (alert) => alert.severity === 'CRITICAL' || alert.severity === 'WARNING'
+
+// The one thing to do about an alert, chosen from the rule that raised it.
+export function attentionAction(alert) {
+ const rule = alert.rule_key || ''
+ if (rule.startsWith('network:')) return { label: 'Review ports', kind: 'network' }
+ if (alert.severity === 'CRITICAL') return { label: 'Open diagnosis', kind: 'agent' }
+ if (rule.startsWith('host:') || rule.startsWith('trend:')) return { label: 'See trend', kind: 'trend' }
+ if (rule.startsWith('container:')) return { label: 'Open container', kind: 'containers' }
+ return { label: 'Open diagnosis', kind: 'agent' }
+}
+
+// ---------- ports ----------
+
+// 9101, 9102, 9103, 9200 -> ["9101-9103", "9200"].
+export function collapseRanges(numbers) {
+ const sorted = [...new Set(numbers)].sort((a, b) => a - b)
+ const parts = []
+ for (let index = 0; index < sorted.length; index += 1) {
+ let end = index
+ while (end + 1 < sorted.length && sorted[end + 1] === sorted[end] + 1) end += 1
+ parts.push(end > index ? `${sorted[index]}-${sorted[end]}` : String(sorted[index]))
+ index = end
+ }
+ return parts
+}
+
+// "8080->80/tcp, 3478->3478/udp" -> [{ host: 8080, container: 80, proto: 'tcp' }, …], one per host port and protocol.
+export function parsePorts(text) {
+ const seen = new Set()
+ const ports = []
+ for (const part of (text || '').split(',')) {
+ const match = part.trim().match(/^(\d+)->(\d+)\/(tcp|udp)$/)
+ if (!match) continue
+ const key = `${match[3]}/${match[1]}`
+ if (seen.has(key)) continue
+ seen.add(key)
+ ports.push({ host: Number(match[1]), container: Number(match[2]), proto: match[3] })
+ }
+ return ports.sort((a, b) => a.host - b.host)
+}
+
+const DATABASE_PORTS = new Set([1433, 1521, 3306, 5432, 5984, 6379, 9042, 9200, 11211, 27017])
+const DATABASE_IMAGES = /(mariadb|mysql|postgres|mongo|redis|valkey|couchdb|influxdb|clickhouse|memcached|elasticsearch|cassandra)/i
+// Published ports of well-known admin panels, by what runs them.
+const ADMIN_PANELS = [
+ { image: /nginx-proxy-manager/i, ports: [81], reason: 'Admin login page' },
+ { image: /portainer/i, ports: [9000, 9443], reason: 'Controls Docker' },
+ { image: /portainer/i, ports: [8000], reason: 'Not needed without Edge', what: 'agent tunnel' },
+ { image: /(pgadmin|phpmyadmin|adminer|mongo-express)/i, ports: null, reason: 'Database admin page' },
+ { image: /(traefik)/i, ports: [8080], reason: 'Admin dashboard' },
+]
+const ADMIN_PORTS = new Map([[2375, 'Controls Docker, unencrypted'], [2376, 'Controls Docker'], [8006, 'Hypervisor admin page'], [9090, 'Admin page'], [10000, 'Admin page']])
+const WELL_KNOWN = new Map([['tcp/22', 'ssh'], ['tcp/53', 'dns'], ['udp/53', 'dns'], ['tcp/80', 'web'], ['tcp/443', 'web'], ['udp/1194', 'VPN'], ['udp/51820', 'VPN'], ['udp/123', 'time'], ['tcp/25', 'mail'], ['udp/5353', 'mDNS'], ['tcp/631', 'printing']])
+
+// What a listening port is, and whether it is something that usually shouldn't face the network.
+// ``owner`` is the container publishing it, when one does. Risky means: a database or an admin panel.
+export function classifyPort(proto, port, owner) {
+ const image = owner?.image || ''
+ if (owner) {
+ for (const panel of ADMIN_PANELS) {
+ if (panel.image.test(image) && (!panel.ports || panel.ports.includes(port))) return { what: panel.what || 'admin UI', risky: true, reason: panel.reason }
+ }
+ if (DATABASE_IMAGES.test(image) || (proto === 'tcp' && DATABASE_PORTS.has(port))) return { what: 'database', risky: true, reason: 'Databases rarely need this' }
+ const known = WELL_KNOWN.get(`${proto}/${port}`)
+ return { what: known === 'VPN' ? 'VPN' : 'web', risky: false, reason: known === 'web' ? 'Expected, public entry' : known ? 'Expected' : '' }
+ }
+ if (proto === 'tcp' && DATABASE_PORTS.has(port)) return { what: 'database', risky: true, reason: 'Databases rarely need this' }
+ if (proto === 'tcp' && ADMIN_PORTS.has(port)) return { what: 'admin UI', risky: true, reason: ADMIN_PORTS.get(port) }
+ return { what: WELL_KNOWN.get(`${proto}/${port}`) || '', risky: false, reason: '' }
+}
+
+// Every listening port of a server with its owner, where it is bound and what the firewall files say about it.
+// Ports that only differ in protocol (tcp+udp) or form a run under one owner are merged into one row.
+export function listenerRows(server) {
+ const owners = new Map()
+ for (const container of server.containers || []) {
+ for (const port of parsePorts(container.ports)) owners.set(`${port.proto}/${port.host}`, container)
+ }
+ const allowed = new Map((server.system?.firewall_allowed || []).map((rule) => [`${rule.proto}/${rule.port}`, rule.file]))
+ // From the optional port-owners helper. Docker's own port forwarder says nothing a container name doesn't.
+ const processes = new Map((server.system?.listener_owners || []).filter((item) => item.process !== 'docker-proxy').map((item) => [`${item.proto}/${item.port}`, item.process]))
+ const byPort = new Map()
+ for (const listener of server.network?.listeners || []) {
+ const key = String(listener.port)
+ const entry = byPort.get(key) || { port: listener.port, protos: new Set(), scopes: new Set(), firstSeen: listener.first_seen }
+ entry.protos.add(listener.proto)
+ entry.scopes.add(listener.scope)
+ if (listener.first_seen > entry.firstSeen) entry.firstSeen = listener.first_seen
+ byPort.set(key, entry)
+ }
+ const rows = [...byPort.values()].map((entry) => {
+ const protos = [...entry.protos].sort()
+ const proto = protos[0]
+ const owner = protos.map((item) => owners.get(`${item}/${entry.port}`)).find(Boolean) || null
+ const scope = entry.scopes.has('any') ? 'any' : entry.scopes.has('specific') ? 'specific' : 'loopback'
+ const kind = classifyPort(proto, entry.port, owner)
+ const rule = protos.map((item) => allowed.get(`${item}/${entry.port}`)).find(Boolean) || null
+ return {
+ port: entry.port, ports: [entry.port], proto: protos.join('+'), scope, reachable: scope !== 'loopback', firstSeen: entry.firstSeen,
+ owner: owner?.name || protos.map((item) => processes.get(`${item}/${entry.port}`)).find(Boolean) || (WELL_KNOWN.get(`${proto}/${entry.port}`) === 'ssh' ? 'sshd' : null), ownerKind: owner ? 'container' : 'host',
+ what: kind.what, risky: kind.risky && scope !== 'loopback', reason: scope === 'loopback' ? '' : kind.reason, rule,
+ }
+ })
+ // One row for a run of neighbouring ports (or 80 and 443) that share everything else.
+ const merged = []
+ for (const row of rows.sort((a, b) => a.port - b.port)) {
+ const twin = merged.find((item) => item.owner && item.owner === row.owner && item.ownerKind === row.ownerKind && item.proto === row.proto && item.scope === row.scope && item.risky === row.risky && item.what === row.what && item.rule === row.rule && !item.risky)
+ if (twin) twin.ports.push(row.port)
+ else merged.push(row)
+ }
+ return merged.map((row) => ({ ...row, label: row.ports.length > 2 || (row.ports.length === 2 && row.ports[1] === row.ports[0] + 1) ? collapseRanges(row.ports).join(', ') : row.ports.join(', ') }))
+}
+
+// Risky and reachable first, then reachable, then local; by port within each.
+export function sortListeners(rows, sort = 'risk') {
+ const rank = (row) => (row.risky ? 0 : row.reachable ? 1 : 2)
+ if (sort === 'port') return [...rows].sort((a, b) => a.port - b.port)
+ if (sort === 'owner') return [...rows].sort((a, b) => (a.owner || '~').localeCompare(b.owner || '~') || a.port - b.port)
+ return [...rows].sort((a, b) => rank(a) - rank(b) || a.port - b.port)
+}
+
+// What the firewall configuration files say overall: { text, tone, enabled }.
+export function firewallSummary(server) {
+ const files = server.network?.firewall || []
+ const ufw = files.find((file) => file.name === 'ufw-conf')
+ const rules = files.filter((file) => file.name !== 'ufw-conf' && file.rules > 0)
+ if (ufw?.enabled === false) return { short: 'ufw off', text: 'ufw inactive', tone: 'warn', enabled: false, rules }
+ if (ufw?.enabled === true) return { short: 'ufw on', text: 'ufw active', tone: 'ok', enabled: true, rules }
+ if (rules.length) return { short: rules[0].name, text: `${rules[0].name} rules`, tone: 'ok', enabled: true, rules }
+ return { short: 'no config found', text: 'no config found', tone: 'unknown', enabled: null, rules }
+}
+
+// "ufw disabled · nftables.conf 12 rules".
+export function firewallLine(server) {
+ const summary = firewallSummary(server)
+ const names = { ufw: 'ufw', ufw6: 'ufw6', nftables: 'nftables.conf', iptables: 'iptables', ip6tables: 'ip6tables' }
+ const parts = [summary.enabled === false ? 'ufw disabled' : summary.enabled === true && summary.short === 'ufw on' ? 'ufw enabled' : null, ...summary.rules.map((file) => `${names[file.name] || file.name} ${file.rules} rules`)].filter(Boolean)
+ return parts.length ? parts.join(' · ') : 'no firewall config found'
+}
+
+// Port events in plain words, with repeats on the same port folded into one "Re-bound ×12" line.
+// Events come newest first: [{ time, kind, detail }].
+export function groupNetworkEvents(events, now = Date.now()) {
+ const groups = []
+ const byPort = new Map()
+ for (const event of events) {
+ const match = event.detail.match(/^(New listener|Listener closed): (tcp|udp)\/(\d+) \((.+)\)$/)
+ if (!match) {
+ groups.push({ time: event.time, label: event.kind === 'firewall_weakened' ? 'Firewall weaker' : event.kind === 'network_notice' ? 'Notice' : 'Firewall', tone: event.kind === 'firewall_weakened' ? 'warn' : 'plain', port: null, text: event.detail, count: 1, events: [event] })
+ continue
+ }
+ const port = Number(match[3])
+ const group = byPort.get(port) || { port, opened: [], closed: [], events: [], protos: new Set() }
+ group.events.push(event)
+ group.protos.add(match[2])
+ ;(match[1] === 'New listener' ? group.opened : group.closed).push({ time: event.time, scope: match[4] })
+ if (!byPort.has(port)) { byPort.set(port, group); groups.push(group) }
+ }
+ return groups.map((group) => {
+ if (group.label) return { ...group, age: formatAge(group.time, now) }
+ const times = group.events.map((event) => new Date(event.time).getTime())
+ const newest = Math.max(...times)
+ const oldest = Math.min(...times)
+ const age = group.events.length > 1 && formatAge(oldest, now) !== formatAge(newest, now) ? `${formatAge(newest, now).replace(/ \w+$/, '')}–${formatAge(oldest, now)}` : formatAge(newest, now)
+ const proto = [...group.protos].sort().join('+')
+ const lastOpened = group.opened[0]
+ const lastClosed = group.closed[0]
+ const stillOpen = lastOpened && (!lastClosed || lastOpened.time >= lastClosed.time)
+ const common = { time: group.events[0].time, age, port: `${proto}/${group.port}`, count: group.events.length, events: group.events }
+ if (group.opened.length && group.closed.length) {
+ const exposedNow = stillOpen && lastOpened.scope !== 'loopback only'
+ const wasLocal = group.closed.some((item) => item.scope === 'loopback only')
+ if (exposedNow && wasLocal) return { ...common, label: 'Now exposed', tone: 'warn', text: `moved from loopback to ${lastOpened.scope}` }
+ return { ...common, label: group.events.length > 2 ? `Re-bound ×${group.events.length}` : 'Re-bound', tone: 'plain', text: stillOpen ? 'closed and opened again. Same exposure before and after.' : 'opened and closed again.' }
+ }
+ if (group.opened.length) return { ...common, label: lastOpened.scope === 'loopback only' ? 'Opened' : 'Now exposed', tone: lastOpened.scope === 'loopback only' ? 'plain' : 'warn', text: `now listens on ${lastOpened.scope.replace(' only', '')}` }
+ return { ...common, label: 'Closed', tone: 'plain', text: 'stopped listening' }
+ })
+}
+
+// ---------- containers ----------
+
+export const STANDALONE = 'Standalone'
+
+export function containerExposed(container, reachablePorts) {
+ return parsePorts(container.ports).some((port) => !reachablePorts || reachablePorts.has(`${port.proto}/${port.host}`))
+}
+
+// The host ports other machines can reach, as "tcp/8080" keys; null when the server reports no listeners at all.
+export function reachablePortSet(server) {
+ const listeners = server.network?.listeners || []
+ if (!listeners.length) return null
+ return new Set(listeners.filter((listener) => listener.scope !== 'loopback').map((listener) => `${listener.proto}/${listener.port}`))
+}
+
+export const CONTAINER_FILTERS = {
+ all: () => true,
+ problems: (container) => problemRank(container) < 2,
+ exposed: (container, reachable) => containerExposed(container, reachable),
+ restarted: (container) => (container.restart_count || 0) > 0,
+ stopped: (container) => ['exited', 'dead', 'created', 'paused'].includes(container.status),
+}
+
+const containerOrders = {
+ cpu: (a, b) => (b.cpu_pct ?? -1) - (a.cpu_pct ?? -1),
+ memory: (a, b) => (b.memory_used_mb ?? -1) - (a.memory_used_mb ?? -1),
+ name: () => 0,
+}
+const byName = (a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base', numeric: true })
+
+// Containers grouped by compose project with totals; problems first inside a group, standalone containers last.
+// ``sort`` orders both the groups (by their total) and the rows in them.
+export function groupContainers(containers, { sort = 'cpu', grouped = true } = {}) {
+ const order = containerOrders[sort] || containerOrders.cpu
+ const rows = (items) => [...items].sort((a, b) => problemRank(a) - problemRank(b) || order(a, b) || byName(a, b))
+ const total = (items, key) => items.reduce((sum, item) => sum + (item[key] ?? 0), 0)
+ const describe = (name, items) => ({ name, containers: rows(items), count: items.length, cpu: total(items, 'cpu_pct'), memoryMb: total(items, 'memory_used_mb'), problems: items.filter((item) => problemRank(item) < 2).length })
+ if (!grouped) return [describe(null, containers)]
+ const byProject = new Map()
+ for (const container of containers) {
+ const key = container.project || STANDALONE
+ if (!byProject.has(key)) byProject.set(key, [])
+ byProject.get(key).push(container)
+ }
+ const groups = [...byProject.entries()].map(([name, items]) => describe(name, items))
+ const groupOrder = sort === 'memory' ? (a, b) => b.memoryMb - a.memoryMb : sort === 'name' ? () => 0 : (a, b) => b.cpu - a.cpu
+ return groups.sort((a, b) => (a.name === STANDALONE) - (b.name === STANDALONE) || groupOrder(a, b) || a.name.localeCompare(b.name))
+}
+
+// "/srv/gitlab/config, /srv/gitlab/data" -> "/srv/gitlab/{config,data}"; unrelated paths stay listed.
+export function collapsePaths(text) {
+ const paths = (text || '').split(',').map((path) => path.trim()).filter(Boolean)
+ const byParent = new Map()
+ const result = []
+ for (const path of paths) {
+ const cut = path.lastIndexOf('/')
+ if (cut <= 0) { result.push({ parent: null, names: [path] }); continue }
+ const parent = path.slice(0, cut)
+ if (!byParent.has(parent)) { byParent.set(parent, { parent, names: [] }); result.push(byParent.get(parent)) }
+ byParent.get(parent).names.push(path.slice(cut + 1))
+ }
+ return result.map((item) => (item.parent === null ? item.names[0] : item.names.length === 1 ? `${item.parent}/${item.names[0]}` : `${item.parent}/{${item.names.join(',')}}`))
+}
+
+export function containerUptime(startedAt, now = Date.now()) {
+ const started = startedAt ? new Date(startedAt).getTime() : NaN
+ return Number.isNaN(started) || started <= 0 ? null : formatSpan((now - started) / 1000)
+}
+
+// ---------- health checks ----------
+
+const TAINT_FAULT_BITS = [4, 5, 7, 9, 14]
+const DAY = 24 * 3600 * 1000
+
+// The server panel's checklist: plain verdicts, amber only where something needs doing.
+// Each: { key, label, text, tone: ok | warn | unknown, action? }.
+export function healthChecks(server, now = Date.now()) {
+ const host = server.host || {}
+ const system = server.system || {}
+ const events = server.system_events || []
+ const checks = []
+ const listeners = server.network?.listeners || []
+ const exposed = new Set(listeners.filter((listener) => listener.scope !== 'loopback').map((listener) => listener.port)).size
+ const firewall = firewallSummary(server)
+ if (listeners.length || firewall.enabled !== null) {
+ checks.push({ key: 'firewall', label: 'Firewall', text: `${firewall.short}${listeners.length ? ` · ${exposed} ${exposed === 1 ? 'port' : 'ports'} exposed` : ''}`, tone: firewall.tone === 'warn' ? 'warn' : firewall.tone === 'unknown' ? 'unknown' : 'ok' })
+ } else checks.push({ key: 'firewall', label: 'Firewall', text: 'Not reported', tone: 'unknown' })
+
+ const kernel = shortKernel(system.reboot_kernel)
+ const rebootedAgo = host.system_uptime_seconds != null && host.system_uptime_seconds < DAY / 1000 ? ` · rebooted ${formatSpan(host.system_uptime_seconds)} ago` : ''
+ if (host.reboot_required) checks.push({ key: 'updates', label: 'Updates', text: kernel ? `Reboot needed for ${kernel}` : 'Reboot needed', tone: 'warn' })
+ else if (system.updates_security > 0) checks.push({ key: 'updates', label: 'Updates', text: `${system.updates_security} security ${system.updates_security === 1 ? 'update' : 'updates'} pending`, tone: 'warn' })
+ else if (host.reboot_required === false) checks.push({ key: 'updates', label: 'Updates', text: `${system.updates_pending > 0 ? `${system.updates_pending} pending, none security` : 'Up to date'}${rebootedAgo}`, tone: 'ok' })
+ else checks.push({ key: 'updates', label: 'Updates', text: 'Not reported on this system', tone: 'unknown' })
+
+ if (host.swap_pct != null && host.swap_pct >= 10) checks.push({ key: 'swap', label: 'Swap', text: `${formatPercent(host.swap_pct)} in use`, tone: host.swap_pct >= 25 ? 'warn' : 'ok' })
+
+ if (host.system_uptime_seconds == null) checks.push({ key: 'booted', label: 'Booted', text: 'Unknown', tone: 'unknown' })
+ else {
+ const shutdown = host.last_shutdown === 'clean' ? ' · clean shutdown' : host.last_shutdown === 'unclean' ? ' · unclean shutdown' : ''
+ checks.push({ key: 'booted', label: 'Booted', text: `${formatSpan(host.system_uptime_seconds)} ago${shutdown}`, tone: host.last_shutdown === 'unclean' ? 'warn' : 'ok' })
+ }
+
+ const service = system.time_service ? ` (${system.time_service.replace('systemd-', '')})` : ''
+ checks.push({ key: 'clock', label: 'Clock', text: host.ntp_synced == null ? 'Unknown' : host.ntp_synced ? `Synced${service}` : 'Not synced', tone: host.ntp_synced == null ? 'unknown' : host.ntp_synced ? 'ok' : 'warn' })
+
+ const ooms = events.filter((event) => event.kind === 'oom_kill' && now - new Date(event.time).getTime() < DAY).length
+ checks.push({ key: 'oom', label: 'OOM kills', text: host.oom_kill_total == null ? 'Unknown' : ooms ? `${ooms} in 24 h` : 'None in 24 h', tone: host.oom_kill_total == null ? 'unknown' : ooms ? 'warn' : 'ok' })
+
+ const faulty = host.kernel_tainted != null && TAINT_FAULT_BITS.some((bit) => (host.kernel_tainted >> bit) & 1)
+ const kernelErrors = events.filter((event) => (event.kind === 'kernel_error' || event.kind === 'kernel_fault') && now - new Date(event.time).getTime() < DAY).length
+ checks.push({ key: 'kernel', label: 'Kernel log', text: host.kernel_tainted == null ? 'Unknown' : faulty ? 'Faults reported' : kernelErrors ? `${kernelErrors} ${kernelErrors === 1 ? 'error' : 'errors'} in 24 h` : 'Clean', tone: host.kernel_tainted == null ? 'unknown' : faulty || kernelErrors ? 'warn' : 'ok' })
+
+ const internet = { ok: ['Reachable', 'ok'], degraded: ['Partly reachable', 'warn'], dns_failed: ['DNS failing', 'warn'], down: ['Down', 'warn'] }[host.internet_status]
+ if (internet) checks.push({ key: 'internet', label: 'Internet', text: `${internet[0]}${host.internet_latency_ms != null && internet[1] === 'ok' ? ` · ${host.internet_latency_ms} ms` : ''}`, tone: internet[1] })
+ else checks.push({ key: 'internet', label: 'Internet', text: 'Not checked', tone: 'unknown', action: 'set targets' })
+
+ if (host.docker_status === 'unreachable') checks.push({ key: 'docker', label: 'Docker', text: 'Unreachable', tone: 'warn' })
+ return checks
+}
+
+export function healthVerdict(checks) {
+ const warnings = checks.filter((check) => check.tone === 'warn').length
+ return warnings ? `${warnings} to look at` : 'all passing'
+}
+
+// ---------- charts and history ----------
+
+// MB/s in and out between consecutive check-ins, from running totals. A counter that went down (a reboot) is a gap.
+export function trafficRates(samples) {
+ const points = []
+ for (let index = 1; index < samples.length; index += 1) {
+ const before = samples[index - 1]
+ const after = samples[index]
+ const seconds = (new Date(after.time).getTime() - new Date(before.time).getTime()) / 1000
+ const rate = (key) => (seconds > 0 && after[key] != null && before[key] != null && after[key] >= before[key] ? (after[key] - before[key]) / seconds : null)
+ points.push({ time: after.time, in: rate('net_recv_mb'), out: rate('net_sent_mb') })
+ }
+ return points
+}
+
+// A round ceiling for a chart axis: 0.4 -> 0.5, 2.1 -> 4, 37 -> 50.
+export function niceCeiling(value) {
+ if (!Number.isFinite(value) || value <= 0) return 1
+ const magnitude = 10 ** Math.floor(Math.log10(value))
+ for (const step of [1, 2, 4, 5, 6, 8, 10]) if (value <= step * magnitude) return Number((step * magnitude).toPrecision(6))
+ return 10 * magnitude
+}
+
+// The last boots, oldest first: [{ time, unclean }], from reboot events (newest first).
+export function bootHistory(events, limit = 10) {
+ return events.filter((event) => event.kind === 'reboot').slice(0, limit).map((event) => ({ time: event.time, unclean: /unclean/i.test(event.detail) })).reverse()
+}
+
+// ---------- the event timeline ----------
+
+export const EVENT_SOURCES = { alert: 'Alerts', container: 'Containers', network: 'Network', system: 'System' }
+
+export function eventCategory(event) {
+ return event.source === 'collector' || event.source === 'infradeck' ? 'system' : event.source
+}
+
+const SOURCE_NAMES = { alert: 'Alert', container: 'Container', network: 'Network', system: 'System', collector: 'Collector', infradeck: 'Infradeck' }
+
+// One readable line per event: { source, tone, lead, text, tag }.
+export function describeEvent(event) {
+ const base = { source: SOURCE_NAMES[event.source] || event.source, tone: 'plain', lead: '', text: event.detail || '', tag: null }
+ switch (event.kind) {
+ case 'alert_opened':
+ return { ...base, tone: event.severity === 'CRITICAL' ? 'signal' : event.severity === 'WARNING' ? 'warn' : 'plain', lead: event.title, text: '', tag: event.resolved ? { text: 'resolved', tone: 'ok' } : event.severity === 'CRITICAL' ? { text: 'critical', tone: 'signal' } : event.severity === 'WARNING' ? { text: 'open', tone: 'warn' } : null }
+ case 'alert_resolved':
+ return { ...base, source: 'Alert resolved', tone: 'ok', lead: event.title, text: `cleared after ${formatSpan(event.duration_seconds)}` }
+ case 'collector_stopped':
+ return { ...base, tone: 'signal', lead: 'Stopped reporting', text: '· several check-ins missed', tag: { text: 'critical', tone: 'signal' } }
+ case 'collector_resumed':
+ return { ...base, tone: 'ok', lead: 'Reporting again', text: `after ${formatSpan(event.duration_seconds)}` }
+ case 'pending_collector':
+ return { ...base, tone: 'paper', lead: event.title, text: event.detail }
+ case 'port_opened': {
+ const exposed = !/loopback/.test(event.detail)
+ const match = event.detail.match(/(tcp|udp)\/\d+/)
+ return { ...base, tone: exposed ? 'warn' : 'plain', lead: match ? match[0] : '', text: event.detail.replace(/^New listener: (tcp|udp)\/\d+ /, 'started listening '), tag: exposed ? { text: 'exposed', tone: 'warn' } : null }
+ }
+ case 'port_closed': {
+ const match = event.detail.match(/(tcp|udp)\/\d+/)
+ return { ...base, lead: match ? match[0] : '', text: event.detail.replace(/^Listener closed: (tcp|udp)\/\d+ /, 'stopped listening ') }
+ }
+ case 'firewall_weakened':
+ return { ...base, tone: 'warn', tag: { text: 'weaker', tone: 'warn' } }
+ case 'oom_kill':
+ case 'kernel_fault':
+ case 'kernel_error':
+ case 'credentials_replaced':
+ return { ...base, tone: 'warn' }
+ case 'reboot':
+ return { ...base, tone: /unclean/i.test(event.detail) ? 'warn' : 'plain', tag: /unclean/i.test(event.detail) ? { text: 'unclean', tone: 'warn' } : null }
+ default: {
+ const match = event.detail.match(/^Container (\S+) (.*)$/)
+ return match ? { ...base, lead: match[1], text: match[2] } : base
+ }
+ }
+}
+
+// Folds runs of the same kind of event from the same source in the same hour into one row with the rest inside it.
+// Alerts are never folded: each one is its own story.
+export function groupRepeats(events) {
+ const groups = []
+ for (const event of events) {
+ const last = groups[groups.length - 1]
+ const hour = event.time.slice(0, 13)
+ if (last && event.source !== 'alert' && event.source !== 'collector' && last.source === event.source && last.kind === event.kind && last.hour === hour) last.events.push(event)
+ else groups.push({ source: event.source, kind: event.kind, hour, events: [event] })
+ }
+ return groups
+}
+
+const PLURAL_SOURCES = { container: 'Containers', network: 'Network', system: 'System' }
+
+// A folded group told in one line.
+export function describeGroup(group) {
+ const first = describeEvent(group.events[0])
+ if (group.events.length === 1) return { ...first, count: 1 }
+ const leads = [...new Set(group.events.map((event) => describeEvent(event).lead).filter(Boolean))]
+ const actions = { container_added: 'appeared', container_removed: 'were removed', image_changed: 'now run a different image build', port_opened: 'started listening', port_closed: 'stopped listening' }
+ const shown = leads.slice(0, 3).join(', ')
+ const rest = leads.length > 3 ? ` and ${leads.length - 3} more` : ''
+ return { ...first, source: `${PLURAL_SOURCES[group.source] || first.source} ×${group.events.length}`, lead: `${shown}${rest}`, text: actions[group.kind] || first.text, count: group.events.length, tag: first.tag }
+}
+
+const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
+const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
+const dayKey = (date) => `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`
+
+// "TODAY · MON 13 OCT" / "SUN 12 OCT".
+export function dayHeading(time, now = Date.now()) {
+ const date = new Date(time)
+ const label = `${WEEKDAYS[date.getDay()]} ${date.getDate()} ${MONTHS[date.getMonth()]}`.toUpperCase()
+ return dayKey(date) === dayKey(new Date(now)) ? `TODAY · ${label}` : label
+}
+
+export const BARS_PER_DAY = 5
+
+// The week on one strip: per day a few bars (how much happened, and whether any of it was an alert).
+export function eventStrip(events, days = 7, now = Date.now()) {
+ const today = new Date(now)
+ today.setHours(0, 0, 0, 0)
+ const strip = []
+ for (let offset = days - 1; offset >= 0; offset -= 1) {
+ const start = new Date(today.getTime())
+ start.setDate(start.getDate() - offset)
+ strip.push({ key: dayKey(start), start: start.getTime(), label: offset === 0 ? 'Today' : `${WEEKDAYS[start.getDay()]} ${start.getDate()}`, today: offset === 0, count: 0, bars: Array.from({ length: BARS_PER_DAY }, () => ({ count: 0, tone: 'plain' })) })
+ }
+ const byKey = new Map(strip.map((day) => [day.key, day]))
+ for (const event of events) {
+ const date = new Date(event.time)
+ const day = byKey.get(dayKey(date))
+ if (!day) continue
+ day.count += 1
+ const bar = day.bars[Math.min(BARS_PER_DAY - 1, Math.floor((date.getHours() * 60 + date.getMinutes()) / (1440 / BARS_PER_DAY)))]
+ bar.count += 1
+ const opening = event.kind === 'alert_opened' || event.kind === 'collector_stopped'
+ if (opening && event.severity === 'CRITICAL') bar.tone = 'signal'
+ else if (opening && event.severity === 'WARNING' && bar.tone !== 'signal') bar.tone = 'warn'
+ }
+ const peak = Math.max(1, ...strip.flatMap((day) => day.bars.map((bar) => bar.count)))
+ return strip.map((day) => ({ ...day, bars: day.bars.map((bar) => ({ ...bar, height: bar.count ? Math.max(0.12, bar.count / peak) : 0 })) }))
+}
+
+export function eventsToCsv(events) {
+ const quote = (value) => `"${String(value ?? '').replace(/"/g, '""')}"`
+ const lines = [['time', 'source', 'kind', 'severity', 'title', 'detail'].join(',')]
+ for (const event of events) lines.push([event.time, event.source, event.kind, event.severity || '', event.title || '', event.detail || ''].map(quote).join(','))
+ return lines.join('\n')
+}
+
+// ---------- adding a server ----------
+
+// The same two hardened containers (collector plus read-only Docker proxy), three ways to start them.
+export function installCommands({ url, token, name, collectorImage, proxyImage }) {
+ const nameLine = name ? `\n HOMELAB_SERVER_NAME: ${name}` : ''
+ const compose = `services:
+ collector:
+ image: ${collectorImage}
+ container_name: homelab-collector
+ restart: unless-stopped
+ environment:
+ HOMELAB_API_URL: ${url}
+ HOMELAB_JOIN_TOKEN: ${token}${nameLine}
+ HOMELAB_DOCKER_HOST: /run/docker-proxy/docker.sock
+ volumes:
+ - /proc:/host/proc:ro
+ - /:/hostfs:ro
+ - collector_state:/var/lib/homelab-collector
+ - docker_proxy_socket:/run/docker-proxy:ro
+ cap_drop: [ALL]
+ read_only: true
+ security_opt: [no-new-privileges:true]
+ docker-proxy:
+ image: ${proxyImage}
+ container_name: homelab-docker-proxy
+ restart: unless-stopped
+ user: "0:0"
+ network_mode: none
+ cap_drop: [ALL]
+ read_only: true
+ security_opt: [no-new-privileges:true]
+ volumes:
+ - /var/run/docker.sock:/var/run/docker.sock
+ - docker_proxy_socket:/run/docker-proxy
+volumes:
+ collector_state:
+ docker_proxy_socket:`
+ const hardened = '--restart unless-stopped --cap-drop ALL --read-only --security-opt no-new-privileges:true'
+ const nameFlag = name ? ` \\\n -e HOMELAB_SERVER_NAME=${name}` : ''
+ const dockerRun = `docker run -d --name homelab-docker-proxy ${hardened} \\
+ --user 0:0 --network none \\
+ -v /var/run/docker.sock:/var/run/docker.sock \\
+ -v homelab_docker_proxy_socket:/run/docker-proxy \\
+ ${proxyImage}
+docker run -d --name homelab-collector ${hardened} \\
+ -e HOMELAB_API_URL=${url} \\
+ -e HOMELAB_JOIN_TOKEN=${token}${nameFlag} \\
+ -e HOMELAB_DOCKER_HOST=/run/docker-proxy/docker.sock \\
+ -v /proc:/host/proc:ro -v /:/hostfs:ro \\
+ -v homelab_collector_state:/var/lib/homelab-collector \\
+ -v homelab_docker_proxy_socket:/run/docker-proxy:ro \\
+ ${collectorImage}`
+ const systemd = `sudo mkdir -p /etc/infradeck-collector
+sudo tee /etc/infradeck-collector/compose.yml >/dev/null <<'EOF'
+${compose}
+EOF
+sudo tee /etc/systemd/system/infradeck-collector.service >/dev/null <<'EOF'
+[Unit]
+Description=Infradeck collector
+Requires=docker.service
+After=docker.service network-online.target
+
+[Service]
+Type=oneshot
+RemainAfterExit=yes
+ExecStart=/usr/bin/docker compose -p homelab-collector -f /etc/infradeck-collector/compose.yml up -d
+ExecStop=/usr/bin/docker compose -p homelab-collector -f /etc/infradeck-collector/compose.yml down
+
+[Install]
+WantedBy=multi-user.target
+EOF
+sudo systemctl daemon-reload
+sudo systemctl enable --now infradeck-collector`
+ return { 'docker run': dockerRun, compose: `docker compose -p homelab-collector -f - up -d <<'EOF'\n${compose}\nEOF`, systemd }
+}
diff --git a/src/frontend/src/distributions.jsx b/src/frontend/src/distributions.jsx
index 9b4e913..7e06878 100644
--- a/src/frontend/src/distributions.jsx
+++ b/src/frontend/src/distributions.jsx
@@ -7,21 +7,21 @@ import { donutSlices } from './chartMath.js'
function ChartFrame({ title, subtitle, table, children, empty }) {
const [asTable, setAsTable] = useState(false)
return (
- <figure className="min-w-0 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 p-4">
+ <figure className="min-w-0 card p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
- <figcaption className="text-sm font-medium text-white">{title}</figcaption>
- {subtitle && <div className="text-xs text-[#7f8589]">{subtitle}</div>}
+ <figcaption className="text-sm font-medium text-paper">{title}</figcaption>
+ {subtitle && <div className="text-xs text-muted">{subtitle}</div>}
</div>
- {!empty && table && <button type="button" onClick={() => setAsTable((value) => !value)} className="shrink-0 rounded-lg border border-white/10 px-2 py-1 text-[11px] text-[#9aa0a6] hover:text-white">{asTable ? 'View as chart' : 'View as table'}</button>}
+ {!empty && table && <button type="button" onClick={() => setAsTable((value) => !value)} className="shrink-0 rounded-md border border-edge px-2 py-1 text-[11px] text-muted hover:text-paper">{asTable ? 'View as chart' : 'View as table'}</button>}
</div>
{empty ? (
- <div className="mt-3 flex min-h-32 items-center justify-center rounded-xl border border-dashed border-neutral-800 px-3 text-center text-xs text-[#7f8589]">{empty}</div>
+ <div className="mt-3 flex min-h-32 items-center justify-center rounded-md border border-dashed border-line px-3 text-center text-xs text-muted">{empty}</div>
) : asTable && table ? (
- <div className="mt-3 max-h-64 overflow-auto rounded-xl border border-[#1f2326]">
- <table className="w-full text-left text-xs text-[#bcbcbc]">
- <thead className="sticky top-0 bg-[#111417] text-[#9aa0a6]"><tr>{table.head.map((cell) => <th key={cell} className="px-3 py-2 font-medium">{cell}</th>)}</tr></thead>
- <tbody>{table.rows.map((row, index) => <tr key={index} className="border-t border-[#1f2326]">{row.map((cell, cellIndex) => <td key={cellIndex} className="px-3 py-1.5">{cell}</td>)}</tr>)}</tbody>
+ <div className="mt-3 max-h-64 overflow-auto rounded-md border border-line">
+ <table className="w-full text-left text-xs text-soft">
+ <thead className="sticky top-0 bg-ink text-muted"><tr>{table.head.map((cell) => <th key={cell} className="px-3 py-2 font-medium">{cell}</th>)}</tr></thead>
+ <tbody>{table.rows.map((row, index) => <tr key={index} className="border-t border-line">{row.map((cell, cellIndex) => <td key={cellIndex} className="px-3 py-1.5">{cell}</td>)}</tr>)}</tbody>
</table>
</div>
) : <div className="mt-3">{children}</div>}
@@ -31,8 +31,8 @@ function ChartFrame({ title, subtitle, table, children, empty }) {
function Legend({ items }) {
return (
- <ul className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-[#bcbcbc]">
- {items.map((item) => <li key={item.label} className="flex items-center gap-1.5"><span aria-hidden="true" className="h-2.5 w-2.5 rounded-sm" style={{ background: item.color }} />{item.label}{item.value !== undefined && <span className="text-[#7f8589]">{item.value}</span>}</li>)}
+ <ul className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-soft">
+ {items.map((item) => <li key={item.label} className="flex items-center gap-1.5"><span aria-hidden="true" className="h-2.5 w-2.5 rounded-sm" style={{ background: item.color }} />{item.label}{item.value !== undefined && <span className="text-muted">{item.value}</span>}</li>)}
</ul>
)
}
@@ -98,9 +98,9 @@ export function ColumnChart({ title, subtitle, categories, series, height = 190,
})}
</svg>
{hover && (
- <div role="status" className="pointer-events-none absolute z-10 rounded-xl border border-white/10 bg-[#111417]/95 px-3 py-2 text-xs text-[#e6e7ea] shadow-lg" style={{ top: 0, left: Math.min(Math.max(hover.x - 60, 0), Math.max(width - 140, 0)) }}>
- <div className="text-[#9aa0a6]">{categories[hover.index].label}</div>
- {series.map((item) => <div key={item.key}><span aria-hidden="true" className="mr-1.5 inline-block h-2 w-2 rounded-sm" style={{ background: item.color }} />{item.label} <span className="font-medium text-white">{categories[hover.index].values[item.key] || 0}{unit}</span></div>)}
+ <div role="status" className="pointer-events-none absolute z-10 rounded-md border border-edge bg-ink/95 px-3 py-2 text-xs text-[#e6e7ea] shadow-lg" style={{ top: 0, left: Math.min(Math.max(hover.x - 60, 0), Math.max(width - 140, 0)) }}>
+ <div className="text-muted">{categories[hover.index].label}</div>
+ {series.map((item) => <div key={item.key}><span aria-hidden="true" className="mr-1.5 inline-block h-2 w-2 rounded-sm" style={{ background: item.color }} />{item.label} <span className="font-medium text-paper">{categories[hover.index].values[item.key] || 0}{unit}</span></div>)}
</div>
)}
</div>
@@ -135,7 +135,7 @@ export function Donut({ title, subtitle, slices, centreLabel = 'total', empty =
}
// Ranked horizontal bars (top containers, servers by disk usage ...). rows: [{label, value, detail?}].
-export function BarList({ title, subtitle, rows, max = null, unit = '', color = '#7dd3fc', decimals = 0, empty = 'Nothing to show yet' }) {
+export function BarList({ title, subtitle, rows, max = null, unit = '', color = '#D0CEC8', decimals = 0, empty = 'Nothing to show yet' }) {
const scale = max ?? Math.max(1, ...rows.map((row) => row.value))
const table = { head: ['', `Value${unit ? ` (${unit.trim()})` : ''}`], rows: rows.map((row) => [row.label, row.value.toFixed(decimals)]) }
return (
@@ -144,10 +144,10 @@ export function BarList({ title, subtitle, rows, max = null, unit = '', color =
{rows.map((row) => (
<li key={row.label}>
<div className="flex items-baseline justify-between gap-3 text-xs">
- <span className="min-w-0 truncate text-[#cfcfcf]">{row.label}</span>
- <span className="shrink-0 text-white">{row.value.toFixed(decimals)}{unit}{row.detail ? <span className="text-[#7f8589]"> {row.detail}</span> : null}</span>
+ <span className="min-w-0 truncate text-soft">{row.label}</span>
+ <span className="shrink-0 text-paper">{row.value.toFixed(decimals)}{unit}{row.detail ? <span className="text-muted"> {row.detail}</span> : null}</span>
</div>
- <div className="mt-1 h-2 overflow-hidden rounded-full bg-white/10"><div className="h-full rounded-full" style={{ width: `${Math.min(Math.max((row.value / scale) * 100, 0), 100)}%`, background: row.color || color }} /></div>
+ <div className="mt-1 h-2 overflow-hidden rounded-full bg-edge"><div className="h-full rounded-full" style={{ width: `${Math.min(Math.max((row.value / scale) * 100, 0), 100)}%`, background: row.color || color }} /></div>
</li>
))}
</ul>
@@ -158,7 +158,7 @@ export function BarList({ title, subtitle, rows, max = null, unit = '', color =
const DAY_NAMES = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
// Average by hour of day (columns) and weekday (rows). grid: 7 rows of 24 numbers or null.
-export function Heatmap({ title, subtitle, grid, unit = '%', color = '#7dd3fc', empty = 'Not enough history yet' }) {
+export function Heatmap({ title, subtitle, grid, unit = '%', color = '#D0CEC8', empty = 'Not enough history yet' }) {
const [hover, setHover] = useState(null)
const values = grid.flat().filter((value) => value !== null)
const top = Math.max(1, ...values)
@@ -170,7 +170,7 @@ export function Heatmap({ title, subtitle, grid, unit = '%', color = '#7dd3fc',
<div className="min-w-[420px]">
{grid.map((row, day) => (
<div key={DAY_NAMES[day]} className="flex items-center gap-1 py-px">
- <span className="w-8 shrink-0 text-[10px] text-[#7f8589]">{DAY_NAMES[day]}</span>
+ <span className="w-8 shrink-0 text-[10px] text-muted">{DAY_NAMES[day]}</span>
{row.map((value, hour) => (
<button
key={hour}
@@ -185,10 +185,10 @@ export function Heatmap({ title, subtitle, grid, unit = '%', color = '#7dd3fc',
))}
</div>
))}
- <div className="mt-1 flex gap-1 pl-9 text-[10px] text-[#7f8589]">{[0, 6, 12, 18, 23].map((hour) => <span key={hour} style={{ position: 'relative', left: `${(hour / 24) * 100 - (hour === 23 ? 3 : 0)}%`, width: 0 }}>{hour}h</span>)}</div>
+ <div className="mt-1 flex gap-1 pl-9 text-[10px] text-muted">{[0, 6, 12, 18, 23].map((hour) => <span key={hour} style={{ position: 'relative', left: `${(hour / 24) * 100 - (hour === 23 ? 3 : 0)}%`, width: 0 }}>{hour}h</span>)}</div>
</div>
</div>
- <div className="mt-2 flex flex-wrap items-center justify-between gap-2 text-xs text-[#9aa0a6]">
+ <div className="mt-2 flex flex-wrap items-center justify-between gap-2 text-xs text-muted">
<span role="status">{hover ? `${DAY_NAMES[hover.day]} ${hover.hour}:00 · ${hover.value === null ? 'no data' : `${hover.value.toFixed(1)}${unit} on average`}` : `Brighter is busier, up to ${top.toFixed(0)}${unit}.`}</span>
<span aria-hidden="true" className="flex items-center gap-1.5">less
{[0, 0.25, 0.5, 0.75, 1].map((step) => <span key={step} className="h-3 w-5 rounded-[3px]" style={{ background: color, opacity: 0.15 + 0.85 * step }} />)}
diff --git a/src/frontend/src/fleetLogic.js b/src/frontend/src/fleetLogic.js
index 1642876..a1097e8 100644
--- a/src/frontend/src/fleetLogic.js
+++ b/src/frontend/src/fleetLogic.js
@@ -4,10 +4,10 @@ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', '
const pad = (value) => String(value).padStart(2, '0')
export const CONTAINER_STATES = [
- { key: 'running', label: 'Running', color: '#34d399' },
- { key: 'unhealthy', label: 'Unhealthy', color: '#f87171' },
- { key: 'restarting', label: 'Restarting', color: '#fbbf24' },
- { key: 'stopped', label: 'Stopped', color: '#94a3b8' },
+ { key: 'running', label: 'Running', color: '#6DBE8F' },
+ { key: 'unhealthy', label: 'Unhealthy', color: '#FF5A1F' },
+ { key: 'restarting', label: 'Restarting', color: '#E2B04A' },
+ { key: 'stopped', label: 'Stopped', color: '#6F6D69' },
]
export function containerState(container) {
@@ -37,7 +37,7 @@ export function topContainers(servers, key, count = 10) {
export function serversByDisk(servers, warning = 85, critical = 95) {
return servers
.filter((server) => typeof server.host?.disk_usage_pct === 'number')
- .map((server) => ({ label: server.hostname, value: server.host.disk_usage_pct, color: server.host.disk_usage_pct >= critical ? '#f87171' : server.host.disk_usage_pct >= warning ? '#fbbf24' : '#7dd3fc' }))
+ .map((server) => ({ label: server.hostname, value: server.host.disk_usage_pct, color: server.host.disk_usage_pct >= critical ? '#FF5A1F' : server.host.disk_usage_pct >= warning ? '#E2B04A' : '#D0CEC8' }))
.sort((a, b) => b.value - a.value || a.label.localeCompare(b.label))
}
@@ -49,7 +49,7 @@ export function isOnline(server, now = Date.now()) {
export function availabilityRows(availability) {
return availability
.filter((item) => item.percent !== null && item.percent !== undefined)
- .map((item) => ({ label: item.hostname, value: item.percent, color: item.percent >= 99 ? '#34d399' : item.percent >= 95 ? '#fbbf24' : '#f87171', detail: `${item.checkins} of about ${item.expected} check-ins` }))
+ .map((item) => ({ label: item.hostname, value: item.percent, color: item.percent >= 99 ? '#6DBE8F' : item.percent >= 95 ? '#E2B04A' : '#FF5A1F', detail: `${item.checkins} of about ${item.expected} check-ins` }))
.sort((a, b) => a.value - b.value || a.label.localeCompare(b.label))
}
diff --git a/src/frontend/src/icons.jsx b/src/frontend/src/icons.jsx
new file mode 100644
index 0000000..854e4b2
--- /dev/null
+++ b/src/frontend/src/icons.jsx
@@ -0,0 +1,29 @@
+// Line icons, 16px, drawn in the current text colour.
+const base = { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true }
+
+const paths = {
+ overview: <><rect x="2.5" y="2.5" width="11" height="4" rx="0.8" /><rect x="2.5" y="9.5" width="11" height="4" rx="0.8" /><path d="M5 4.5h.01M5 11.5h.01" /></>,
+ statistics: <><path d="M2.5 13.5h11" /><path d="M3 10l3-3.5 2.5 2L13 4" /></>,
+ agent: <><path d="M2.5 3.5h11v7.5H7l-3 2.5V11H2.5z" /><path d="M5.5 6.5h5M5.5 8.5h3" /></>,
+ account: <><circle cx="8" cy="5.5" r="2.5" /><path d="M3 13.5c.6-2.3 2.5-3.5 5-3.5s4.4 1.2 5 3.5" /></>,
+ admin: <><path d="M2.5 5h7M12.5 5h1M2.5 11h1M6.5 11h7" /><circle cx="11" cy="5" r="1.5" /><circle cx="5" cy="11" r="1.5" /></>,
+ signout: <><path d="M9.5 2.5h3.5v11H9.5" /><path d="M9 8H3M5.5 5.5L3 8l2.5 2.5" /></>,
+ search: <><circle cx="7" cy="7" r="4" /><path d="M10 10l3.5 3.5" /></>,
+ plus: <path d="M8 3v10M3 8h10" />,
+ check: <path d="M3 8.5l3.2 3L13 4.5" />,
+ logs: <path d="M3 4h10M3 8h7M3 12h9" />,
+ restart: <><path d="M13 8a5 5 0 1 1-1.6-3.7" /><path d="M13 2.5v3h-3" /></>,
+ download: <><path d="M8 2.5v8M5 7.5l3 3 3-3" /><path d="M3 13.5h10" /></>,
+ 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" />,
+}
+
+export function Icon({ name, size = 16, className = '' }) {
+ return <svg {...base} width={size} height={size} className={className}>{paths[name]}</svg>
+}
+
+// The disclosure triangle in front of a group or an expandable row.
+export function Caret({ open, className = '' }) {
+ return <svg width="9" height="9" viewBox="0 0 9 9" aria-hidden="true" className={`shrink-0 fill-current transition-transform ${open ? 'rotate-90' : ''} ${className}`}><path d="M2 0.8l5 3.7-5 3.7z" /></svg>
+}
diff --git a/src/frontend/src/index.css b/src/frontend/src/index.css
index af06278..49d424a 100644
--- a/src/frontend/src/index.css
+++ b/src/frontend/src/index.css
@@ -1,49 +1,91 @@
@import 'tailwindcss';
+@import '@fontsource-variable/inter';
+@import '@fontsource-variable/jetbrains-mono';
+
+/* Infradeck design tokens (design/web/infradeck-redesign.pdf). Signal orange is reserved for critical problems
+ and the one action that fixes them; warnings are amber; healthy is a small green dot; charts are drawn in Paper. */
+@theme {
+ --color-bg: #0e0e11;
+ --color-ink: #16161a;
+ --color-raised: #1b1b20;
+ --color-sunken: #131317;
+ --color-line: #25252b;
+ --color-edge: #33333a;
+ --color-rail: #3a3a40;
+ --color-paper: #f3f1ec;
+ --color-soft: #d0cec8;
+ --color-muted: #a9a69f;
+ --color-dim: #6f6d69;
+ --color-signal: #ff5a1f;
+ --color-warn: #e2b04a;
+ --color-ok: #6dbe8f;
+ --font-sans: 'Inter Variable', Inter, 'Segoe UI', system-ui, sans-serif;
+ --font-mono: 'JetBrains Mono Variable', 'DejaVu Sans Mono', ui-monospace, monospace;
+}
:root {
- font-family: Inter, 'Segoe UI', sans-serif;
- color: #f3f4f6;
- background: #05070a;
+ font-family: var(--font-sans);
+ font-feature-settings: 'tnum', 'cv11';
+ color: var(--color-paper);
+ background: var(--color-bg);
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
+ color-scheme: dark;
}
-* {
- box-sizing: border-box;
-}
-
-html {
- background: #05070a;
-}
+/* Element defaults sit in the base layer, below the component classes further down. */
+@layer base {
+ * {
+ box-sizing: border-box;
+ }
-body {
- margin: 0;
- min-height: 100vh;
- background:
- radial-gradient(circle at top left, rgba(255, 255, 255, 0.09), transparent 24%),
- radial-gradient(circle at top right, rgba(255, 255, 255, 0.06), transparent 28%),
- linear-gradient(180deg, #111417 0%, #090b0d 100%);
- color: #f3f4f6;
-}
+ html {
+ background: var(--color-bg);
+ }
-#root {
- min-height: 100vh;
-}
+ body {
+ margin: 0;
+ min-height: 100vh;
+ background: var(--color-bg);
+ color: var(--color-paper);
+ font-size: 13px;
+ line-height: 1.45;
+ }
-button,
-input,
-textarea {
- font: inherit;
-}
+ #root {
+ min-height: 100vh;
+ }
-/* iOS Safari zooms the page when a focused field's text is under 16px. */
-@media (max-width: 639px) {
+ button,
input,
select,
textarea {
- font-size: 16px !important;
+ font: inherit;
+ color: inherit;
+ }
+
+ button {
+ cursor: pointer;
+ }
+
+ button:disabled {
+ cursor: not-allowed;
+ }
+
+ :focus-visible {
+ outline: 2px solid var(--color-paper);
+ outline-offset: 2px;
+ }
+
+ /* iOS Safari zooms the page when a focused field's text is under 16px. */
+ @media (max-width: 639px) {
+ input,
+ select,
+ textarea {
+ font-size: 16px !important;
+ }
}
}
@@ -55,34 +97,524 @@ textarea {
display: none;
}
+/* Pages not yet moved to the new design keep these names; flat and hairline like the rest. */
.glass-panel {
- background: rgba(17, 20, 23, 0.9);
- border: 1px solid rgba(255, 255, 255, 0.08);
- box-shadow: 0 20px 50px rgba(0, 0, 0, 0.42);
- backdrop-filter: blur(18px);
+ background: var(--color-ink);
+ border: 1px solid var(--color-line);
}
.message-card {
- border: 1px solid rgba(255, 255, 255, 0.09);
- background: rgba(23, 27, 30, 0.92);
- box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--color-line);
+ background: var(--color-raised);
}
.command-block {
- background: rgba(14, 18, 20, 0.96);
- border: 1px solid rgba(255, 255, 255, 0.08);
- color: #e5e7eb;
+ background: var(--color-bg);
+ border: 1px solid var(--color-line);
+ color: var(--color-soft);
+}
+
+.custom-scroll {
+ scrollbar-width: thin;
+ scrollbar-color: var(--color-edge) transparent;
+}
+
+/* ---------- shared pieces ----------
+ In the components layer, so a utility class on the same element (pl-9, h-9) still wins. */
+
+@layer components {
+ .mono {
+ font-family: var(--font-mono);
+ font-size: 0.9em;
+ font-feature-settings: normal;
+ }
+
+ .card {
+ background: var(--color-ink);
+ border: 1px solid var(--color-line);
+ border-radius: 8px;
+ }
+
+ .btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ height: 32px;
+ padding: 0 12px;
+ border: 1px solid var(--color-edge);
+ border-radius: 6px;
+ background: var(--color-ink);
+ color: var(--color-paper);
+ font-size: 12px;
+ font-weight: 500;
+ white-space: nowrap;
+ transition: background-color 0.12s, border-color 0.12s;
+ }
+ .btn:hover:not(:disabled) {
+ background: var(--color-raised);
+ border-color: #45454d;
+ }
+ .btn:disabled {
+ color: var(--color-dim);
+ }
+ .btn-sm {
+ height: 26px;
+ padding: 0 9px;
+ }
+ .btn-primary {
+ background: var(--color-paper);
+ border-color: var(--color-paper);
+ color: var(--color-bg);
+ }
+ .btn-primary:hover:not(:disabled) {
+ background: #fff;
+ border-color: #fff;
+ }
+ .btn-primary:disabled {
+ background: var(--color-edge);
+ border-color: var(--color-edge);
+ color: var(--color-muted);
+ }
+ .btn-ghost {
+ border-color: transparent;
+ background: transparent;
+ color: var(--color-muted);
+ }
+
+ .field {
+ height: 32px;
+ width: 100%;
+ padding: 0 12px;
+ border: 1px solid var(--color-edge);
+ border-radius: 6px;
+ background: var(--color-bg);
+ color: var(--color-paper);
+ font-size: 12px;
+ outline: none;
+ }
+ .field::placeholder {
+ color: var(--color-dim);
+ }
+ .field:focus {
+ border-color: var(--color-muted);
+ }
+
+ .select {
+ appearance: none;
+ height: 32px;
+ padding: 0 30px 0 12px;
+ border: 1px solid var(--color-edge);
+ border-radius: 6px;
+ background: var(--color-ink)
+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' fill='none' stroke='%23F3F1EC' stroke-width='1.3'%3E%3Cpath d='M1 1l4 4 4-4'/%3E%3C/svg%3E")
+ no-repeat right 11px center;
+ color: var(--color-paper);
+ font-size: 12px;
+ font-weight: 500;
+ outline: none;
+ }
+ .select:focus-visible {
+ border-color: var(--color-muted);
+ }
+
+ .chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ height: 20px;
+ padding: 0 7px;
+ border: 1px solid var(--color-edge);
+ border-radius: 4px;
+ background: var(--color-raised);
+ color: var(--color-soft);
+ font-size: 11px;
+ white-space: nowrap;
+ }
+ .chip-signal {
+ border-color: color-mix(in srgb, var(--color-signal) 55%, transparent);
+ background: color-mix(in srgb, var(--color-signal) 10%, transparent);
+ color: var(--color-signal);
+ }
+ .chip-warn {
+ border-color: color-mix(in srgb, var(--color-warn) 55%, transparent);
+ background: color-mix(in srgb, var(--color-warn) 8%, transparent);
+ color: var(--color-warn);
+ }
+ .chip-ok {
+ border-color: color-mix(in srgb, var(--color-ok) 45%, transparent);
+ background: color-mix(in srgb, var(--color-ok) 8%, transparent);
+ color: var(--color-ok);
+ }
+
+ /* A listening port: the number in mono, its owner in muted text. */
+ .port {
+ display: inline-flex;
+ align-items: baseline;
+ gap: 7px;
+ height: 22px;
+ padding: 0 7px;
+ border: 1px solid var(--color-line);
+ border-radius: 4px;
+ background: var(--color-raised);
+ color: var(--color-paper);
+ font-family: var(--font-mono);
+ font-size: 12px;
+ line-height: 20px;
+ white-space: nowrap;
+ }
+ .port > span {
+ color: var(--color-dim);
+ }
+ .port-risky {
+ border-color: color-mix(in srgb, var(--color-warn) 60%, transparent);
+ background: color-mix(in srgb, var(--color-warn) 7%, transparent);
+ color: var(--color-warn);
+ }
+ .port-risky > span {
+ color: color-mix(in srgb, var(--color-warn) 75%, transparent);
+ }
+
+ .dot {
+ display: inline-block;
+ flex: none;
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--color-dim);
+ }
+ .dot-ok {
+ background: var(--color-ok);
+ }
+ .dot-warn {
+ background: var(--color-warn);
+ }
+ .dot-signal {
+ background: var(--color-signal);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-signal) 28%, transparent);
+ }
+
+ /* Segmented control: filters that sit in one bordered strip. */
+ .seg {
+ display: inline-flex;
+ padding: 2px;
+ border: 1px solid var(--color-edge);
+ border-radius: 6px;
+ background: var(--color-bg);
+ }
+ .seg > button {
+ height: 26px;
+ padding: 0 10px;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ background: transparent;
+ color: var(--color-soft);
+ font-size: 12px;
+ white-space: nowrap;
+ }
+ .seg > button[aria-pressed='true'],
+ .seg > button[aria-selected='true'] {
+ border-color: var(--color-edge);
+ background: var(--color-raised);
+ color: var(--color-paper);
+ font-weight: 500;
+ }
+
+ /* Thin meter under a value. */
+ .meter {
+ display: block;
+ height: 3px;
+ border-radius: 2px;
+ background: var(--color-edge);
+ overflow: hidden;
+ }
+ .meter > i {
+ display: block;
+ height: 100%;
+ border-radius: 2px;
+ background: var(--color-soft);
+ }
+ .meter-warn > i {
+ background: var(--color-warn);
+ }
+ .meter-signal > i {
+ background: var(--color-signal);
+ }
+
+ /* ---------- the rack: rows between two rails, the one that needs you pulled out ---------- */
+
+ .rack {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ gap: 7px;
+ padding: 15px 15px 15px 15px;
+ border-left: 2px solid var(--color-rail);
+ border-right: 2px solid var(--color-rail);
+ }
+
+ .drawer {
+ position: relative;
+ display: grid;
+ align-items: center;
+ min-height: 52px;
+ padding: 0 34px 0 26px;
+ border: 1px solid var(--color-edge);
+ border-radius: 3px;
+ background: var(--color-ink);
+ text-align: left;
+ color: inherit;
+ }
+ /* The screw holes at both ends of a rack unit. */
+ .drawer::before,
+ .drawer::after {
+ content: '';
+ position: absolute;
+ top: 50%;
+ width: 3px;
+ height: 3px;
+ margin-top: -1.5px;
+ border-radius: 50%;
+ background: var(--color-dim);
+ }
+ .drawer::before {
+ left: 11px;
+ }
+ .drawer::after {
+ right: 11px;
+ }
+ .drawer-out {
+ margin-left: 24px;
+ }
+ .drawer-critical {
+ border-color: var(--color-signal);
+ background: var(--color-signal);
+ color: var(--color-bg);
+ }
+ .drawer-critical::before,
+ .drawer-critical::after {
+ background: color-mix(in srgb, var(--color-bg) 60%, transparent);
+ }
+ .drawer-alert {
+ border-color: color-mix(in srgb, var(--color-signal) 70%, transparent);
+ box-shadow: inset 2px 0 0 var(--color-signal);
+ }
+ .drawer-selected {
+ border-color: #55545a;
+ box-shadow: inset 3px 0 0 var(--color-paper);
+ }
+ button.drawer:hover:not(.drawer-critical) {
+ background: var(--color-raised);
+ }
+ .drawer-ghost {
+ border-color: var(--color-line);
+ background: var(--color-sunken);
+ }
+ .ghost-bar {
+ display: block;
+ height: 7px;
+ border-radius: 4px;
+ background: var(--color-line);
+ }
+
+ /* ---------- tables inside cards ---------- */
+
+ .grid-head {
+ color: var(--color-muted);
+ font-size: 12px;
+ font-weight: 500;
+ }
+
+ .tab {
+ position: relative;
+ display: inline-flex;
+ align-items: baseline;
+ gap: 7px;
+ height: 44px;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--color-soft);
+ font-size: 13px;
+ font-weight: 500;
+ line-height: 44px;
+ white-space: nowrap;
+ }
+ .tab > small {
+ color: var(--color-dim);
+ font-size: 12px;
+ font-weight: 400;
+ }
+ .tab[aria-selected='true'] {
+ color: var(--color-paper);
+ }
+ .tab[aria-selected='true']::after {
+ content: '';
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: -1px;
+ height: 2px;
+ background: var(--color-paper);
+ }
+
+ .kv {
+ display: grid;
+ grid-template-columns: var(--kv-label, 108px) minmax(0, 1fr);
+ gap: 8px 12px;
+ font-size: 12px;
+ }
+ .kv > dt {
+ color: var(--color-muted);
+ }
+ .kv > dd {
+ margin: 0;
+ min-width: 0;
+ }
+
+ /* ---------- sign-in pages ---------- */
+
+ .auth-input {
+ display: block;
+ width: 100%;
+ height: 42px;
+ padding: 0 13px;
+ border: 1px solid var(--color-edge);
+ border-radius: 6px;
+ background: var(--color-ink);
+ color: var(--color-paper);
+ font-size: 14px;
+ outline: none;
+ transition: border-color 0.12s, box-shadow 0.12s;
+ }
+ .auth-input::placeholder {
+ color: var(--color-dim);
+ }
+ .auth-input:focus {
+ border-color: var(--color-paper);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-paper) 12%, transparent);
+ }
+ .auth-digit {
+ width: 56px;
+ max-width: calc((100% - 40px) / 6);
+ height: 56px;
+ padding: 0;
+ border: 1px solid var(--color-edge);
+ border-radius: 6px;
+ background: var(--color-ink);
+ color: var(--color-paper);
+ font-size: 24px;
+ font-weight: 600;
+ text-align: center;
+ outline: none;
+ caret-color: var(--color-paper);
+ }
+ .auth-digit:focus {
+ border-color: var(--color-paper);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-paper) 12%, transparent);
+ }
+ .auth-submit {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ width: 100%;
+ height: 44px;
+ border: 0;
+ border-radius: 6px;
+ background: var(--color-paper);
+ color: var(--color-bg);
+ font-size: 14px;
+ font-weight: 600;
+ transition: background-color 0.12s;
+ }
+ .auth-submit:hover:not(:disabled) {
+ background: #fff;
+ }
+ .auth-submit:disabled {
+ background: var(--color-edge);
+ color: var(--color-muted);
+ }
+ .auth-check {
+ appearance: none;
+ flex: none;
+ width: 16px;
+ height: 16px;
+ margin: 0;
+ border: 1px solid var(--color-muted);
+ border-radius: 3px;
+ background: transparent;
+ cursor: pointer;
+ }
+ .auth-check:checked {
+ border-color: var(--color-paper);
+ background: var(--color-paper)
+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='%230E0E11' stroke-width='2.2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3.5 8.5l3 3 6-6.5'/%3E%3C/svg%3E")
+ center / 14px no-repeat;
+ }
+
+ .link {
+ color: var(--color-muted);
+ text-decoration: underline;
+ text-underline-offset: 3px;
+ background: none;
+ border: 0;
+ padding: 0;
+ font-size: inherit;
+ }
+ .link:hover {
+ color: var(--color-paper);
+ }
}
-.custom-scroll::-webkit-scrollbar {
- width: 8px;
+@keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+.spinner {
+ width: 14px;
+ height: 14px;
+ border: 2px solid var(--color-edge);
+ border-top-color: var(--color-paper);
+ border-radius: 50%;
+ animation: spin 0.9s linear infinite;
+}
+@media (prefers-reduced-motion: reduce) {
+ .spinner {
+ animation: none;
+ }
}
-.custom-scroll::-webkit-scrollbar-track {
- background: rgba(15, 23, 42, 0.8);
+/* ---------- display choices (Account › Display) ---------- */
+
+/* Light theme: the same tokens with the roles swapped, so every page follows. */
+:root[data-theme='light'] {
+ --color-bg: #f6f5f1;
+ --color-ink: #ffffff;
+ --color-raised: #efede7;
+ --color-sunken: #f1efea;
+ --color-line: #e2dfd8;
+ --color-edge: #cfccc4;
+ --color-rail: #b9b6ae;
+ --color-paper: #16161a;
+ --color-soft: #3b3a3f;
+ --color-muted: #6b6963;
+ --color-dim: #96938c;
+ --color-signal: #e0440b;
+ --color-warn: #a8730a;
+ --color-ok: #2f8a5b;
+ color-scheme: light;
+}
+/* The wordmark is drawn in Paper for a dark page; on a light one it is flipped, keeping the orange unit. */
+:root[data-theme='light'] img[src='/logo.svg'] {
+ filter: invert(1) hue-rotate(180deg);
}
-.custom-scroll::-webkit-scrollbar-thumb {
- background: rgba(148, 163, 184, 0.35);
- border-radius: 999px;
+/* Compact: everything a notch smaller, so tables fit more rows. */
+:root[data-density='compact'] {
+ font-size: 14.5px;
+}
+:root[data-density='compact'] body {
+ zoom: 0.9;
}
diff --git a/src/frontend/src/overviewStore.js b/src/frontend/src/overviewStore.js
new file mode 100644
index 0000000..68a1439
--- /dev/null
+++ b/src/frontend/src/overviewStore.js
@@ -0,0 +1,68 @@
+// One shared poll of /monitoring/overview for whoever is on screen: the sidebar on every page, the Overview page
+// itself. It runs at the fastest pace any mounted reader asks for, and not at all while the tab is hidden.
+import { useEffect, useSyncExternalStore } from 'react'
+import { apiRequest } from './api.js'
+
+let snapshot = { data: null, error: '', loadedAt: 0 }
+const listeners = new Set()
+const readers = new Map() // token -> { seconds, onUnauthorized }
+let timer = null
+let timerSeconds = null
+let inFlight = null
+
+function publish(next) {
+ snapshot = { ...snapshot, ...next }
+ for (const listener of listeners) listener()
+}
+
+export function refreshOverview() {
+ if (inFlight) return inFlight
+ inFlight = apiRequest('/monitoring/overview', { method: 'GET' })
+ .then((data) => publish({ data, error: '', loadedAt: Date.now() }))
+ .catch((error) => {
+ // Signed out or expired: every reader hands the user back to the sign-in page.
+ if (error.status === 401) { for (const reader of readers.values()) reader.onUnauthorized?.(); return }
+ publish({ error: error.message || 'Could not load monitoring data.' })
+ })
+ .finally(() => { inFlight = null })
+ return inFlight
+}
+
+function reschedule() {
+ const seconds = readers.size && !document.hidden ? Math.min(...[...readers.values()].map((reader) => reader.seconds)) : null
+ if (seconds === timerSeconds) return
+ if (timer !== null) clearInterval(timer)
+ timer = seconds === null ? null : setInterval(refreshOverview, seconds * 1000)
+ timerSeconds = seconds
+}
+
+if (typeof document !== 'undefined') {
+ document.addEventListener('visibilitychange', () => {
+ if (!document.hidden && readers.size) refreshOverview()
+ reschedule()
+ })
+}
+
+const subscribe = (listener) => { listeners.add(listener); return () => listeners.delete(listener) }
+const getSnapshot = () => snapshot
+
+// { data, error, loadedAt } kept fresh every ``seconds`` while the component is mounted and ``enabled``.
+export function useOverview(enabled, seconds, onUnauthorized) {
+ useEffect(() => {
+ if (!enabled) return undefined
+ const token = {}
+ readers.set(token, { seconds, onUnauthorized })
+ if (Date.now() - snapshot.loadedAt > seconds * 1000) refreshOverview()
+ reschedule()
+ return () => { readers.delete(token); reschedule() }
+ // onUnauthorized is the app's sign-out handler; a new function each render must not restart the poll.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [enabled, seconds])
+ return useSyncExternalStore(subscribe, getSnapshot)
+}
+
+// Forget what was loaded, so the next person to sign in on this browser never sees the last one's fleet.
+export function resetOverview() {
+ snapshot = { data: null, error: '', loadedAt: 0 }
+ for (const listener of listeners) listener()
+}
diff --git a/src/frontend/src/prefs.js b/src/frontend/src/prefs.js
new file mode 100644
index 0000000..944c2a7
--- /dev/null
+++ b/src/frontend/src/prefs.js
@@ -0,0 +1,21 @@
+// How this browser shows Infradeck: theme and density apply at once and are remembered here, so the page doesn't
+// flash the wrong theme while the account loads. The account itself keeps the same choices on the server.
+const KEY = 'infradeck.display'
+
+export function storedDisplay() {
+ try { return JSON.parse(window.localStorage.getItem(KEY)) || {} } catch { return {} }
+}
+
+export function applyDisplay(display) {
+ const choice = { ...storedDisplay(), ...(display || {}) }
+ const system = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'
+ document.documentElement.dataset.theme = choice.theme === 'system' ? system : choice.theme === 'light' ? 'light' : 'dark'
+ document.documentElement.dataset.density = choice.density === 'compact' ? 'compact' : 'comfortable'
+ if (display) { try { window.localStorage.setItem(KEY, JSON.stringify(choice)) } catch { /* not remembered */ } }
+ return choice
+}
+
+// Where "/" should lead for this person: the page they chose to open on.
+export function landingPath() {
+ return { statistics: '/statistics', agent: '/agent' }[storedDisplay().open_on] || '/'
+}
diff --git a/src/frontend/src/shell.jsx b/src/frontend/src/shell.jsx
new file mode 100644
index 0000000..a5fc4ff
--- /dev/null
+++ b/src/frontend/src/shell.jsx
@@ -0,0 +1,326 @@
+// 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'
+import { Link, NavLink, useLocation, useNavigate } from 'react-router-dom'
+import { apiRequest } from './api.js'
+import { isOnline } from './fleetLogic.js'
+import { Icon } from './icons.jsx'
+import { formatQuiet, listenerRows, serverState, serverStateLabel, sortServers } from './dashboard/logic.js'
+import { useOverview } from './overviewStore.js'
+
+const SIDEBAR_REFRESH_SECONDS = 15
+
+const primaryNav = [
+ { label: 'Overview', to: '/', icon: 'overview', keys: 'O' },
+ { label: 'Statistics', to: '/statistics', icon: 'statistics', keys: 'S' },
+ { label: 'Agent', to: '/agent', icon: 'agent', keys: 'A' },
+]
+const secondaryNav = [
+ { label: 'Account', to: '/account', icon: 'account' },
+ { label: 'Admin', to: '/admin', icon: 'admin', adminOnly: true },
+]
+const pageTitles = { '/': 'Overview', '/statistics': 'Statistics', '/agent': 'Agent', '/account': 'Account', '/admin': 'Admin' }
+
+export const serverLink = (serverId, tab) => `/?server=${serverId}${tab && tab !== 'overview' ? `&tab=${tab}` : ''}`
+
+// First and last name: Karlo Kajba Šimanić -> KŠ.
+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() }
+const roleLabel = (role) => (role === 'admin' ? 'Owner' : 'Member')
+const instanceName = (user) => `${(user?.name || 'my').trim().split(/\s+/)[0].toLowerCase()}'s homelab`
+const isTyping = (target) => target instanceof HTMLElement && (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName))
+
+const STATE_DOT = { critical: 'dot-signal', warn: 'dot-warn', ok: 'dot-ok', offline: '' }
+
+// The share of expected check-ins that arrived this week, averaged over the fleet. Asked for rarely: it changes slowly.
+let weekAvailability = { value: null, loadedAt: 0 }
+function useWeekAvailability(enabled) {
+ const [value, setValue] = useState(weekAvailability.value)
+ useEffect(() => {
+ if (!enabled) return undefined
+ let active = true
+ const load = () => {
+ if (Date.now() - weekAvailability.loadedAt < 10 * 60 * 1000) return
+ apiRequest('/stats/fleet?range=7d', { method: 'GET' }).then((data) => {
+ const known = (data.availability || []).map((row) => row.percent).filter((percent) => percent != null)
+ weekAvailability = { value: known.length ? known.reduce((sum, percent) => sum + percent, 0) / known.length : null, loadedAt: Date.now() }
+ if (active) setValue(weekAvailability.value)
+ }).catch(() => {})
+ }
+ load()
+ const timer = setInterval(load, 60 * 1000)
+ return () => { active = false; clearInterval(timer) }
+ }, [enabled])
+ return value
+}
+
+function NavItem({ item, badge }) {
+ return (
+ <NavLink to={item.to} end={item.to === '/'} className={({ isActive }) => `relative flex h-8 items-center gap-3 rounded-md px-2.5 text-[13px] font-medium transition-colors ${isActive ? 'bg-raised text-paper' : 'text-soft hover:bg-ink hover:text-paper'}`}>
+ {({ isActive }) => <>
+ {isActive && <span aria-hidden="true" className="absolute -left-3.5 top-0 h-full w-[3px] rounded-r-sm bg-signal" />}
+ <Icon name={item.icon} className={isActive ? 'text-paper' : 'text-muted'} />
+ <span className="flex-1">{item.label}</span>
+ {badge ? <span className="flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-signal px-1 text-[11px] font-semibold text-bg" aria-label={`${badge} open incidents`}>{badge}</span>
+ : item.keys && <span aria-hidden="true" className="mono text-[10px] tracking-[0.25em] text-dim">G {item.keys}</span>}
+ </>}
+ </NavLink>
+ )
+}
+
+function AgentCard({ overview, error, availability }) {
+ const servers = overview?.servers || []
+ const open = (overview?.alerts_by_severity?.CRITICAL || 0) + (overview?.alerts_by_severity?.WARNING || 0)
+ const online = servers.filter((server) => isOnline(server)).length
+ let status = 'Online'
+ let dot = 'dot-ok'
+ let line
+ if (error && !overview) { status = 'Unreachable'; dot = ''; line = 'The dashboard backend is not answering.' }
+ else if (!servers.length) { status = 'Waiting'; dot = ''; line = 'No collectors yet · nothing to watch' }
+ else if (open === 0 && overview?.quiet) line = `Nothing open · quiet for ${formatQuiet((Date.now() - new Date(overview.quiet.quiet_since).getTime()) / 1000)}`
+ else line = `Collectors ${online}/${servers.length} reporting${availability != null ? ` · ${Number(availability.toFixed(2))}% this week` : ''}`
+ return (
+ <div className="rounded-md border border-line px-3 py-2.5">
+ <div className="flex items-center justify-between">
+ <span className="text-xs font-semibold text-paper">Incident agent</span>
+ <span className="flex items-center gap-1.5 text-[11px] text-soft"><span className={`dot ${dot}`} style={{ width: 6, height: 6 }} />{status}</span>
+ </div>
+ <div className="mt-1 text-[11px] leading-[17px] text-muted">{line}</div>
+ </div>
+ )
+}
+
+function Sidebar({ user, onLogout, overview, error }) {
+ const location = useLocation()
+ const availability = useWeekAvailability(Boolean(user))
+ const servers = useMemo(() => sortServers(overview?.servers || []), [overview])
+ const open = (overview?.alerts_by_severity?.CRITICAL || 0) + (overview?.alerts_by_severity?.WARNING || 0)
+ const selected = location.pathname === '/' ? new URLSearchParams(location.search).get('server') : null
+ return (
+ <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">
+ <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>
+
+ <nav aria-label="Main" className="mt-6 space-y-0.5">
+ {primaryNav.map((item) => <NavItem key={item.to} item={item} badge={item.to === '/agent' ? open : 0} />)}
+ </nav>
+
+ <div className="mt-6 flex items-center justify-between px-2 text-[11px] text-muted"><span>Fleet</span><span>{servers.length}</span></div>
+ <div className="custom-scroll mt-1.5 min-h-0 space-y-px overflow-y-auto">
+ {servers.map((server) => {
+ const state = serverState(server)
+ return (
+ <Link key={server.id} to={serverLink(server.id)} className={`flex h-[29px] items-center gap-3 rounded-md px-2 text-[13px] transition-colors hover:bg-ink ${String(server.id) === selected ? 'bg-ink' : ''}`}>
+ <span className={`dot ${STATE_DOT[state]}`} />
+ <span className="min-w-0 flex-1 truncate font-medium text-paper">{server.hostname}</span>
+ <span className="shrink-0 text-[11px] text-muted">{server.is_dashboard_host && state !== 'critical' && state !== 'offline' ? 'this machine' : serverStateLabel(server)}</span>
+ </Link>
+ )
+ })}
+ {overview && !servers.length && <div className="px-2 pt-1.5">
+ <div className="text-xs text-muted">No servers yet.</div>
+ {user?.role === 'admin' && <Link to="/" className="mt-2 block text-xs font-medium text-paper hover:underline">+ Connect a server</Link>}
+ </div>}
+ </div>
+
+ <nav aria-label="Settings" className="mt-6 space-y-0.5">
+ {secondaryNav.filter((item) => !item.adminOnly || user?.role === 'admin').map((item) => <NavItem key={item.to} item={item} />)}
+ </nav>
+
+ <div className="mt-auto pt-6"><AgentCard overview={overview} error={error} availability={availability} /></div>
+ {user && <div className="mt-4 flex items-center gap-2.5 px-1">
+ <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-line bg-raised text-[11px] font-semibold text-paper">{initials(user.name)}</span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-xs font-medium leading-4 text-paper">{user.name}</span>
+ <span className="block text-[11px] leading-4 text-muted">{roleLabel(user.role)}</span>
+ </span>
+ <button type="button" onClick={onLogout} aria-label="Sign out" title="Sign out" className="flex h-7 w-7 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)
+ useEffect(() => {
+ const timer = setInterval(() => tick((value) => value + 1), 1000)
+ return () => clearInterval(timer)
+ }, [])
+ if (!overview) return <span className="flex items-center gap-2 text-xs text-muted"><span className="dot" />{error ? 'Not connected' : 'Connecting…'}</span>
+ if (!overview.servers.length) return <span className="flex items-center gap-2 text-xs text-muted"><span className="dot" />No collectors reporting</span>
+ const seconds = Math.max(0, Math.round((Date.now() - loadedAt) / 1000))
+ const stale = Boolean(error) || seconds > 30
+ return <span className="flex items-center gap-2 whitespace-nowrap text-xs text-soft" title={error || undefined}><span className={`dot ${stale ? 'dot-warn' : 'dot-ok'}`} />{stale ? 'Stale' : 'Live'} · checked {seconds}s ago</span>
+}
+
+function paletteItems(overview, isAdmin) {
+ const items = [
+ { kind: 'Page', label: 'Overview', to: '/' }, { kind: 'Page', label: 'Statistics', to: '/statistics' }, { kind: 'Page', label: 'Agent', to: '/agent' }, { kind: 'Page', label: 'Account', to: '/account' },
+ ...(isAdmin ? [{ kind: 'Page', label: 'Admin', to: '/admin' }] : []),
+ ]
+ for (const server of overview?.servers || []) {
+ items.push({ kind: 'Server', label: server.hostname, hint: [server.ip_address, serverStateLabel(server)].filter(Boolean).join(' · '), to: serverLink(server.id) })
+ for (const container of server.containers || []) items.push({ kind: 'Container', label: container.name, hint: `${server.hostname} · ${container.status}`, search: `${container.name} ${container.image || ''}`, to: serverLink(server.id, 'containers') })
+ for (const row of listenerRows(server)) items.push({ kind: 'Port', label: `${row.proto}/${row.label}`, hint: [server.hostname, row.owner].filter(Boolean).join(' · '), search: `${row.proto}/${row.ports.join(' ')} ${row.ports.join(' ')} ${row.owner || ''}`, to: serverLink(server.id, 'network') })
+ }
+ return items
+}
+
+function CommandPalette({ overview, isAdmin, onClose }) {
+ const navigate = useNavigate()
+ const [query, setQuery] = useState('')
+ const [index, setIndex] = useState(0)
+ const listRef = useRef(null)
+ const all = useMemo(() => paletteItems(overview, isAdmin), [overview, isAdmin])
+ const needle = query.trim().toLowerCase()
+ const results = useMemo(() => (needle ? all.filter((item) => (item.search || item.label).toLowerCase().includes(needle)) : all.filter((item) => item.kind === 'Page' || item.kind === 'Server')).slice(0, 40), [all, needle])
+ const active = Math.min(index, Math.max(0, results.length - 1))
+ const go = (item) => { if (item) { navigate(item.to); onClose() } }
+
+ useEffect(() => { listRef.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({ block: 'nearest' }) }, [active])
+
+ const onKeyDown = (event) => {
+ if (event.key === 'Escape') onClose()
+ else if (event.key === 'ArrowDown') { event.preventDefault(); setIndex(Math.min(active + 1, results.length - 1)) }
+ else if (event.key === 'ArrowUp') { event.preventDefault(); setIndex(Math.max(active - 1, 0)) }
+ else if (event.key === 'Enter') { event.preventDefault(); go(results[active]) }
+ }
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-start justify-center bg-black/60 px-4 pt-[14vh]" onMouseDown={(event) => { if (event.target === event.currentTarget) onClose() }}>
+ <div role="dialog" aria-modal="true" aria-label="Jump to" className="w-full max-w-[560px] overflow-hidden rounded-lg border border-edge bg-ink">
+ <div className="flex items-center gap-3 border-b border-line px-4">
+ <Icon name="search" className="text-muted" />
+ <input autoFocus value={query} onChange={(event) => { setQuery(event.target.value); setIndex(0) }} onKeyDown={onKeyDown} placeholder="Jump to server, container, port…" aria-label="Jump to server, container or port" role="combobox" aria-expanded="true" aria-controls="palette-results" className="h-12 flex-1 bg-transparent text-[13px] text-paper outline-none placeholder:text-dim" />
+ <kbd className="mono rounded border border-line px-1.5 py-0.5 text-[10px] text-dim">esc</kbd>
+ </div>
+ <ul id="palette-results" ref={listRef} role="listbox" className="custom-scroll max-h-[46vh] overflow-y-auto p-1.5">
+ {results.map((item, position) => (
+ <li key={`${item.kind}-${item.to}-${item.label}-${item.hint || ''}`} role="option" aria-selected={position === active} onMouseEnter={() => setIndex(position)} onMouseDown={(event) => { event.preventDefault(); go(item) }} className={`flex cursor-pointer items-center gap-3 rounded-md px-2.5 py-2 text-[13px] ${position === active ? 'bg-raised' : ''}`}>
+ <span className="w-[68px] shrink-0 text-[11px] text-dim">{item.kind}</span>
+ <span className={`min-w-0 truncate font-medium text-paper ${item.kind === 'Port' ? 'mono' : ''}`}>{item.label}</span>
+ {item.hint && <span className="ml-auto min-w-0 truncate text-[11px] text-muted">{item.hint}</span>}
+ </li>
+ ))}
+ {!results.length && <li className="px-2.5 py-6 text-center text-[13px] text-muted">Nothing matches “{query.trim()}”.</li>}
+ </ul>
+ </div>
+ </div>
+ )
+}
+
+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">
+ <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
+ return <span key={`${crumb.label}-${position}`} className="flex min-w-0 items-center gap-3">
+ {position > 0 && <span aria-hidden="true" className="font-normal text-dim">/</span>}
+ {crumb.to && !last ? <Link to={crumb.to} className="font-medium text-muted hover:text-paper">{crumb.label}</Link> : <span aria-current={last ? 'page' : undefined} className="truncate text-paper">{crumb.label}</span>}
+ </span>
+ })}
+ </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">
+ <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>
+ </button>
+ </div>
+ </header>
+ )
+}
+
+function MobileTopBar({ user, onLogout }) {
+ const [menuOpen, setMenuOpen] = useState(false)
+
+ useEffect(() => {
+ if (!menuOpen) return undefined
+ const close = (event) => { if (event.key === 'Escape') setMenuOpen(false) }
+ window.addEventListener('keydown', close)
+ return () => window.removeEventListener('keydown', close)
+ }, [menuOpen])
+
+ 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>
+ )}
+ </div>
+ </header>
+ )
+}
+
+function MobileTabBar({ user, open }) {
+ const items = [...primaryNav, ...secondaryNav].filter((item) => !item.adminOnly || user?.role === 'admin')
+ 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}
+ </>}
+ </NavLink>
+ ))}
+ </div>
+ </nav>
+ )
+}
+
+// ``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 }) {
+ const location = useLocation()
+ const navigate = useNavigate()
+ const [paletteOpen, setPaletteOpen] = useState(false)
+ const { data: overview, error, loadedAt } = useOverview(Boolean(user) && !user.setup_required, SIDEBAR_REFRESH_SECONDS, onLogout)
+ const trail = crumbs || [{ label: pageTitles[location.pathname] || 'Infradeck' }]
+ const open = (overview?.alerts_by_severity?.CRITICAL || 0) + (overview?.alerts_by_severity?.WARNING || 0)
+
+ // ⌘K / Ctrl+K opens the palette; G then O, S or A jumps between the main pages.
+ useEffect(() => {
+ let armed = 0
+ const onKeyDown = (event) => {
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') { event.preventDefault(); setPaletteOpen(true); return }
+ if (event.metaKey || event.ctrlKey || event.altKey || isTyping(event.target)) return
+ const key = event.key.toLowerCase()
+ if (key === 'g') { armed = Date.now(); return }
+ const target = { o: '/', s: '/statistics', a: '/agent' }[key]
+ if (target && Date.now() - armed < 1200) { event.preventDefault(); navigate(target) }
+ armed = 0
+ }
+ window.addEventListener('keydown', onKeyDown)
+ return () => window.removeEventListener('keydown', onKeyDown)
+ }, [navigate])
+
+ 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>
+ </div>
+ <MobileTabBar user={user} open={open} />
+ {paletteOpen && <CommandPalette overview={overview} isAdmin={user?.role === 'admin'} onClose={() => setPaletteOpen(false)} />}
+ </div>
+ )
+}
diff --git a/src/frontend/src/statistics/ContainersTable.jsx b/src/frontend/src/statistics/ContainersTable.jsx
new file mode 100644
index 0000000..8d56659
--- /dev/null
+++ b/src/frontend/src/statistics/ContainersTable.jsx
@@ -0,0 +1,125 @@
+// A ranked table instead of a card per container: the ones that matter float to the top. Selecting a row opens
+// that container's own history on the same kind of timeline.
+import { useMemo, useState } from 'react'
+import { describeBucket } from '../chartMath.js'
+import { Sparkline } from '../dashboard/charts.jsx'
+import { usePolled } from '../dashboard/data.js'
+import { containerUptime, formatMegabytes, formatPercent } from '../dashboard/logic.js'
+import { Caret, Icon } from '../icons.jsx'
+import { Timeline } from './Timeline.jsx'
+import { findGaps } from './logic.js'
+
+const COLUMNS = 'grid-cols-[38px_minmax(150px,1.2fr)_minmax(120px,1fr)_84px_84px_104px_112px_80px_76px_70px]'
+const SORTS = [
+ ['avg_cpu', 'average CPU'], ['max_cpu', 'peak CPU'], ['avg_memory_mb', 'average memory'], ['max_memory_mb', 'peak memory'], ['swap', 'swap'], ['restarts', 'restarts'], ['name', 'name'],
+]
+const LIVE = new Set(['1h', '6h', '24h'])
+const SHOWN = 8
+const megabytes = (value) => formatMegabytes(value)
+
+function ContainerHistory({ serverId, container, range, compare }) {
+ const base = `/monitoring/servers/${serverId}/containers/${encodeURIComponent(container.container_id)}/history?range=${range.id}&metrics=cpu,memory_mb,restarts`
+ const { data, error } = usePolled(base, LIVE.has(range.id) ? 30 : null)
+ const { data: before } = usePolled(compare && range.previous ? `${base}&previous=true` : null, null)
+ // Memory is drawn in GB once it passes one, so the axis reads 4 GB rather than 4096 MB. The restart count is a
+ // running total with no average, so its highest value in each period is the value.
+ const inGb = useMemo(() => Math.max(0, ...(data?.points || []).map((point) => point.memory_mb?.max ?? 0)) >= 1024, [data])
+ const shape = (point, shift = 0) => {
+ const scale = (value) => (value == null ? null : inGb ? value / 1024 : value)
+ return { ...point, t: new Date(point.time).getTime() + shift, memory: point.memory_mb ? { avg: scale(point.memory_mb.avg ?? null), max: scale(point.memory_mb.max ?? null) } : null, restarts: point.restarts?.max != null ? { avg: point.restarts.max, max: point.restarts.max } : null }
+ }
+ const points = useMemo(() => (data?.points || []).map((point) => shape(point)),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [data, inGb])
+ const previous = useMemo(() => {
+ if (!before || !data) return null
+ const shift = new Date(data.end).getTime() - new Date(before.end).getTime()
+ return (before.points || []).map((point) => shape(point, shift))
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [before, data, inGb])
+ if (error) return <p className="m-0 border-l-2 border-warn bg-bg px-[18px] py-4 text-xs text-warn">{error}</p>
+ if (!data) return <p className="m-0 border-l-2 border-paper bg-bg px-[18px] py-6 text-xs text-muted">Loading the history of {container.name}…</p>
+ const start = new Date(data.start).getTime()
+ const end = new Date(data.end).getTime()
+ const utc = ['day', 'week', 'month'].includes(data.source)
+ const rows = [
+ { key: 'cpu', label: 'CPU', format: formatPercent, axis: (tick) => `${Math.round(tick)}%`, floor: 100 / 1.15, sub: 'Can pass 100% on more than one core' },
+ { key: 'memory', label: 'Memory', format: (value) => megabytes(inGb ? value * 1024 : value), axis: (tick) => (inGb ? `${Number(tick.toFixed(1))} GB` : `${Math.round(tick)} MB`), sub: container.memory_limit_mb ? `limit ${megabytes(container.memory_limit_mb)}` : undefined },
+ { key: 'restarts', label: 'Restart count', format: (value) => String(Math.round(value)), band: false, floor: 1, sub: 'Docker\'s running total' },
+ ]
+ // A container that was stopped has no CPU or memory figures: those periods are gaps too.
+ const reporting = points.filter((point) => point.cpu?.avg != null || point.memory?.avg != null).map((point) => point.t)
+ return (
+ <div className="border-l-2 border-paper bg-bg">
+ <Timeline compact title={container.name} note={`${container.image ? `${container.image} · ` : ''}one point per ${describeBucket(data.bucket_seconds)}`} rows={rows} points={points} previous={previous} start={start} end={end} bucketSeconds={data.bucket_seconds}
+ gaps={findGaps(reporting, data.bucket_seconds, end)} utc={utc} legend={{ current: `Last ${range.words}`, previous: previous ? `The ${range.previous}` : null }} />
+ </div>
+ )
+}
+
+export function ContainersTable({ server, usage, range, compare, selectedId, onSelect }) {
+ const [query, setQuery] = useState('')
+ const [sort, setSort] = useState('avg_cpu')
+ const [all, setAll] = useState(false)
+ const current = useMemo(() => new Map((server.containers || []).map((container) => [container.container_id, container])), [server])
+ const rows = useMemo(() => {
+ // Swap is the average over the range; until a container has history with it, what it holds right now.
+ const merged = (usage?.containers || []).map((item) => { const now = current.get(item.container_id) || null; return { ...item, now, swap: item.avg_swap_mb ?? now?.swap_mb ?? null } })
+ // A container that exists now but has no history in this range yet still belongs in the list.
+ for (const container of current.values()) if (!merged.some((item) => item.container_id === container.container_id)) merged.push({ container_id: container.container_id, name: container.name, avg_cpu: null, max_cpu: null, avg_memory_mb: null, max_memory_mb: null, restarts: null, sparkline: [], now: container, swap: container.swap_mb ?? null })
+ const order = sort === 'name' ? (a, b) => a.name.localeCompare(b.name) : (a, b) => (b[sort] ?? -1) - (a[sort] ?? -1) || a.name.localeCompare(b.name)
+ return merged.sort(order)
+ }, [usage, current, sort])
+ const needle = query.trim().toLowerCase()
+ const matching = needle ? rows.filter((row) => `${row.name} ${row.now?.image || ''}`.toLowerCase().includes(needle)) : rows
+ const visible = all || needle ? matching : matching.filter((row, index) => index < SHOWN || row.container_id === selectedId)
+ const rank = new Map(rows.map((row, index) => [row.container_id, index + 1]))
+ const top = Math.max(100, ...rows.flatMap((row) => row.sparkline || []).filter((value) => value != null))
+ const swapKnown = rows.some((row) => row.swap != null)
+
+ 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">
+ <h2 className="m-0 text-sm font-semibold text-paper">Containers</h2>
+ <span className="mr-auto text-xs text-muted">Top consumers over the last {range.words} · {rows.length} on {server.hostname}</span>
+ <label className="relative block w-full max-w-[220px]">
+ <Icon name="search" size={14} className="pointer-events-none absolute left-3 top-[9px] text-muted" />
+ <input type="search" className="field pl-9" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search containers" aria-label={`Search containers on ${server.hostname}`} />
+ </label>
+ <select className="select" aria-label="Sort containers" value={sort} onChange={(event) => setSort(event.target.value)}>{SORTS.map(([key, label]) => <option key={key} value={key}>Sort: {label}</option>)}</select>
+ </div>
+ {!usage ? <p className="m-0 border-t border-line px-[18px] py-8 text-center text-xs text-muted">Loading…</p> : !rows.length ? <p className="m-0 border-t border-line px-[18px] py-8 text-center text-xs text-muted">No containers reported on {server.hostname} in this range.</p> : (
+ <div className="custom-scroll overflow-x-auto"><div className="min-w-[1020px]">
+ <div className={`grid ${COLUMNS} grid-head h-10 items-center border-t border-line px-[18px]`}>
+ <span>#</span><span>Container</span><span>CPU · {range.label}</span><span className="text-right">Avg CPU</span><span className="text-right">Peak CPU</span><span className="text-right">Avg memory</span><span className="text-right">Peak memory</span><span className="text-right">Swap</span><span className="text-right">Restarts</span><span className="text-right">Uptime</span>
+ </div>
+ {visible.map((row) => {
+ const open = row.container_id === selectedId
+ const running = row.now?.status === 'running'
+ return (
+ <div key={row.container_id}>
+ <button type="button" aria-expanded={open} onClick={() => onSelect(open ? '' : row.container_id)} className={`grid w-full ${COLUMNS} h-[42px] items-center border-0 border-t border-solid border-line px-[18px] text-left text-[13px] transition-colors hover:bg-raised ${open ? 'bg-raised' : 'bg-transparent'}`}>
+ <span className="mono text-dim">{String(rank.get(row.container_id)).padStart(2, '0')}</span>
+ <span className="flex min-w-0 items-center gap-2.5 pr-3"><span className={`dot ${!row.now ? '' : running ? (row.now.healthcheck_status === 'unhealthy' ? 'dot-signal' : 'dot-ok') : 'dot-warn'}`} style={{ width: 6, height: 6 }} title={row.now ? row.now.status : 'no longer on this server'} /><span className="truncate font-medium text-paper" title={row.name}>{row.name}</span><Caret open={open} className="text-dim" /></span>
+ <span className="pr-4"><Sparkline values={row.sparkline} width={150} height={18} max={top} /></span>
+ <span className="text-right text-paper">{formatPercent(row.avg_cpu)}</span>
+ <span className={`text-right ${row.max_cpu >= 100 ? 'text-signal' : 'text-paper'}`}>{formatPercent(row.max_cpu)}</span>
+ <span className="text-right text-paper">{megabytes(row.avg_memory_mb)}</span>
+ <span className="text-right text-paper">{megabytes(row.max_memory_mb)}</span>
+ <span className={`text-right ${row.swap >= 1 ? 'text-warn' : 'text-soft'}`} title={row.max_swap_mb != null ? `average over the range · peak ${megabytes(row.max_swap_mb)}` : undefined}>{row.swap == null ? '—' : row.swap < 1 ? '0' : megabytes(row.swap)}</span>
+ <span className={`text-right ${row.restarts ? 'text-warn' : 'text-paper'}`}>{row.restarts ?? '—'}</span>
+ <span className="text-right text-soft">{(running && containerUptime(row.now.started_at)) || '—'}</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>
+ )
+ })}
+ {!visible.length && <p className="m-0 border-t border-line px-[18px] py-6 text-center text-xs text-muted">No containers match “{query.trim()}”.</p>}
+ </div></div>
+ )}
+ {rows.length > 0 && <p className="m-0 border-t border-line px-[18px] py-3 text-xs text-muted">
+ Showing {visible.length} of {rows.length}{matching.length > visible.length || (all && rows.length > SHOWN) ? <> · <button type="button" className="link" onClick={() => setAll((value) => !value)}>{all ? 'show fewer' : 'show all'}</button></> : ''} · Select a row to open its own history with the same timeline.{swapKnown ? '' : ' Swap per container appears once this machine\'s collector is updated.'}
+ </p>}
+ </section>
+ )
+}
diff --git a/src/frontend/src/statistics/Insights.jsx b/src/frontend/src/statistics/Insights.jsx
new file mode 100644
index 0000000..c8d254a
--- /dev/null
+++ b/src/frontend/src/statistics/Insights.jsx
@@ -0,0 +1,211 @@
+// The panels under the timeline: when the server is busy, how its time splits across load levels, how its disks
+// are filling up (with the forecast drawn, not just written) and how fast Docker and the collector answer.
+import { useMemo, useState } from 'react'
+import { seriesFor } from '../chartMath.js'
+import { forecastKey, usePolled } from '../dashboard/data.js'
+import { forecastMonth, forecastPhrase, formatPercent, niceCeiling } from '../dashboard/logic.js'
+import { MiniChart } from './Timeline.jsx'
+import { busiestHour, findGaps, percentile, projection, timeAtLevels } from './logic.js'
+
+const DAY_NAMES = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
+const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
+const pad = (value) => String(value).padStart(2, '0')
+const LIVE = new Set(['1h', '6h', '24h'])
+
+function MetricSwitch({ value, onChange, label }) {
+ return (
+ <div className="seg" role="group" aria-label={label}>
+ <button type="button" aria-pressed={value === 'cpu'} onClick={() => onChange('cpu')}>CPU</button>
+ <button type="button" aria-pressed={value === 'ram'} onClick={() => onChange('ram')}>Memory</button>
+ </div>
+ )
+}
+
+// ``table``: [asTable, setAsTable] adds the small "View as table" button every panel has.
+function CardHead({ title, detail, children, table }) {
+ return (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 border-b border-line px-[18px] py-3">
+ <h2 className="m-0 text-sm font-semibold text-paper">{title}</h2>
+ {detail && <span className="min-w-0 text-xs text-muted">{detail}</span>}
+ <span className="ml-auto flex flex-wrap items-center justify-end gap-3 text-xs text-soft">
+ {children}
+ {table && <button type="button" className="btn btn-sm" aria-pressed={table[0]} onClick={() => table[1]((value) => !value)}>{table[0] ? 'View as chart' : 'View as table'}</button>}
+ </span>
+ </div>
+ )
+}
+
+function DataTable({ head, rows }) {
+ return (
+ <div className="custom-scroll max-h-[300px] overflow-auto">
+ <table className="w-full border-collapse text-left text-xs">
+ <thead className="sticky top-0 bg-ink"><tr className="grid-head h-9">{head.map((cell, index) => <th key={`${cell}-${index}`} className={`font-medium ${index ? 'px-2 text-right' : 'pl-[18px]'} ${index === head.length - 1 ? 'pr-[18px]' : ''}`}>{cell}</th>)}</tr></thead>
+ <tbody>{rows.map((row, position) => <tr key={position} className="h-8 border-t border-line text-soft">{row.map((cell, index) => <td key={index} className={`whitespace-nowrap ${index ? 'px-2 text-right' : 'pl-[18px] text-muted'} ${index === row.length - 1 ? 'pr-[18px]' : ''}`}>{cell}</td>)}</tr>)}</tbody>
+ </table>
+ </div>
+ )
+}
+
+const stamp = (time, utc) => { const date = new Date(time); return utc ? `${date.getUTCDate()} ${MONTHS[date.getUTCMonth()]} ${date.getUTCFullYear()}` : `${date.getDate()} ${MONTHS[date.getMonth()]} ${pad(date.getHours())}:${pad(date.getMinutes())}` }
+
+export function BusyHours({ serverId }) {
+ const [metric, setMetric] = useState('cpu')
+ const [hover, setHover] = useState(null)
+ const table = useState(false)
+ const offset = -new Date().getTimezoneOffset()
+ const { data, error } = usePolled(`/stats/servers/${serverId}/heatmap?metric=${metric}&offset=${offset}`, null)
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'your time zone'
+ const grid = data?.cells
+ const values = grid ? grid.flat().filter((value) => value != null) : []
+ // The scale stops where most hours are, so one extreme hour doesn't turn everything else black.
+ const cap = values.length ? Math.max(5, niceCeiling(percentile(values, 90) * 1.4)) : 100
+ const peak = grid ? busiestHour(grid) : null
+ const name = metric === 'cpu' ? 'CPU' : 'memory'
+ return (
+ <section className="card overflow-hidden" aria-label="When it's busy">
+ <CardHead title="When it's busy" detail={`Average ${name} by hour, last 30 days, ${zone}`} table={grid && values.length ? table : null}><MetricSwitch value={metric} onChange={setMetric} label="Metric for the busy hours" /></CardHead>
+ {table[0] && grid && values.length > 0 ? <DataTable head={['', ...Array.from({ length: 24 }, (_, hour) => pad(hour))]} rows={grid.map((row, day) => [DAY_NAMES[day], ...row.map((value) => (value == null ? '–' : Math.round(value)))])} /> : <div className="px-[18px] pb-4 pt-4">
+ {error && <p className="m-0 text-xs text-warn">{error}</p>}
+ {!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]">
+ {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>
+ {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"
+ 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></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>
+ <span role="status">{hover ? `${DAY_NAMES[hover.day]} ${pad(hover.hour)}:00 · ${hover.value == null ? 'no data' : `${formatPercent(hover.value)} on average`}` : `Brighter is busier.${peak ? ` The ${pad(peak.hour)}:00 column is the busiest hour, ${formatPercent(peak.value)} on average.` : ''}`}</span>
+ </div>
+ </>}
+ </div>}
+ </section>
+ )
+}
+
+export function TimeAtLevels({ cpu, ram, words }) {
+ const [metric, setMetric] = useState('cpu')
+ const table = useState(false)
+ const { bands, sentence } = useMemo(() => timeAtLevels(metric === 'cpu' ? cpu : ram, metric === 'cpu' ? 'CPU' : 'memory'), [metric, cpu, ram])
+ const widest = Math.max(1, ...bands.map((band) => band.share))
+ return (
+ <section className="card overflow-hidden" aria-label="Time spent at each level">
+ <CardHead title="Time spent at each level" table={sentence ? table : null}><MetricSwitch value={metric} onChange={setMetric} label="Metric for the levels" /></CardHead>
+ {table[0] && sentence ? <DataTable head={['Level', 'Share of the time']} rows={bands.map((band) => [band.label, formatPercent(band.share)])} /> : <div className="px-[18px] pb-4 pt-4">
+ {sentence ? <>
+ <ul className="m-0 list-none space-y-[11px] p-0">
+ {bands.map((band) => (
+ <li key={band.label} className="grid grid-cols-[62px_minmax(0,1fr)_48px] items-center gap-3 text-xs">
+ <span className="text-soft">{band.label}</span>
+ <span className="block h-[9px]"><span className="block h-full rounded-[2px]" style={{ width: `${(band.share / widest) * 100}%`, minWidth: band.share > 0 ? 2 : 0, background: band.hot ? 'var(--color-signal)' : 'var(--color-soft)' }} /></span>
+ <span className="text-right text-paper">{formatPercent(band.share)}</span>
+ </li>
+ ))}
+ </ul>
+ <p className="mb-0 mt-5 text-xs leading-[19px] text-muted">{sentence.replace('of the time', `of the ${words}`)}</p>
+ </> : <p className="m-0 py-10 text-center text-xs text-muted">Not enough data in this range.</p>}
+ </div>}
+ </section>
+ )
+}
+
+function monthLabel(time, approximate = false) {
+ const date = new Date(time)
+ const part = date.getDate() <= 10 ? 'early-' : date.getDate() <= 20 ? 'mid-' : 'late-'
+ return `${approximate ? part : ''}${approximate ? ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][date.getMonth()] : MONTHS[date.getMonth()]} ${date.getFullYear()}`
+}
+
+function DiskCard({ server, mount, range, days, horizon }) {
+ const { data } = usePolled(`/monitoring/servers/${server.id}/mounts/history?mount=${encodeURIComponent(mount.mount)}&range=${range.id}&metrics=used_pct`, LIVE.has(range.id) ? 60 : null)
+ const series = useMemo(() => seriesFor(data?.points, 'used_pct'), [data])
+ const table = useState(false)
+ const start = data ? new Date(data.start).getTime() : null
+ const now = data ? new Date(data.end).getTime() : null
+ const last = series.length ? series[series.length - 1] : null
+ const ahead = last && now ? projection(now, last.avg, days, Math.max(1, (horizon - now) / 86400000)) : null
+ const end = ahead ? Math.max(horizon, now + 1) : now
+ const phrase = forecastPhrase(days)
+ const when = forecastMonth(days)
+ return (
+ <section className="card overflow-hidden" aria-label={`Disk ${mount.mount}`}>
+ <CardHead table={series.length ? table : null} title={<>Disk · <span className="mono">{mount.mount}</span></>} detail={mount.total_gb != null ? `${Number(mount.used_gb?.toFixed(1))} of ${Number(mount.total_gb.toFixed(1))} GB` : formatPercent(mount.used_pct)}>
+ {when && days < 730 ? <span>Full around <span className="font-semibold text-paper">{when.replace('full around ', '')}</span></span> : phrase ? <span>{phrase.replace(/about .*/, 'about')} <span className="font-semibold text-paper">{phrase.replace(/^Full in about /, '')}</span></span> : <span className="text-muted">No clear growth trend</span>}
+ </CardHead>
+ {table[0] && series.length ? <DataTable head={['Period', 'Used']} rows={[...series].reverse().map((point) => [stamp(point.t, data.bucket_seconds >= 86400), formatPercent(point.avg)])} /> : data ? (
+ <MiniChart series={series} start={start} end={end} bucketSeconds={data.bucket_seconds} gaps={findGaps(series.map((point) => point.t), data.bucket_seconds, now)} top={100} format={(tick) => `${tick}%`} band={false}
+ labels={ahead ? [{ t: start, label: monthDay(start) }, { t: now, label: monthDay(now) }, { t: end, label: monthLabel(end) }] : [{ t: start, label: monthDay(start) }, { t: now, label: monthDay(now) }]}>
+ {({ x, y }) => ahead && <>
+ <span aria-hidden="true" className="absolute inset-y-0 border-l border-line bg-paper/[0.03]" style={{ left: `${x(now)}%`, right: 0 }} />
+ <span aria-hidden="true" className="absolute top-1 -translate-x-full whitespace-nowrap pr-2 text-[11px] text-muted" style={{ left: `${x(now)}%` }}>last {range.words}</span>
+ <span aria-hidden="true" className="absolute top-1 whitespace-nowrap pl-2 text-[11px] text-muted" style={{ left: `${x(now)}%` }}>projection</span>
+ <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="absolute inset-0 h-full w-full overflow-visible" aria-hidden="true">
+ <line x1={x(ahead.from.t)} y1={y(ahead.from.value)} x2={x(ahead.to.t)} y2={y(ahead.to.value)} stroke="var(--color-soft)" strokeWidth="1.2" strokeDasharray="4 4" vectorEffect="non-scaling-stroke" />
+ </svg>
+ <span aria-hidden="true" className="absolute h-[7px] w-[7px] -translate-x-1/2 -translate-y-1/2 rounded-full" style={{ left: `${x(ahead.to.t)}%`, top: `${y(ahead.to.value)}%`, background: ahead.full ? 'var(--color-signal)' : 'var(--color-muted)' }} />
+ <span className={`absolute -translate-x-full whitespace-nowrap pr-3 text-[11px] ${ahead.full ? 'text-signal' : 'text-soft'}`} style={{ left: `${x(ahead.to.t)}%`, top: ahead.full ? `calc(${y(ahead.to.value)}% + 26px)` : `calc(${y(ahead.to.value)}% - 22px)` }}>
+ {ahead.full ? `100% around ${monthLabel(ahead.to.t, true)}` : `${formatPercent(ahead.to.value)} by ${['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][new Date(ahead.to.t).getMonth()]} · ${forecastPhrase(days, { short: true })}`}
+ </span>
+ </>}
+ </MiniChart>
+ ) : <p className="m-0 px-[18px] py-12 text-center text-xs text-muted">Loading…</p>}
+ </section>
+ )
+}
+
+const monthDay = (time) => { const date = new Date(time); return `${date.getDate()} ${MONTHS[date.getMonth()]}` }
+
+// Each filesystem with its forecast continued as a dashed line. All of them share one horizon (the day the
+// first one fills up), so the charts can be compared.
+export function Disks({ server, mounts, range, forecasts }) {
+ const now = Date.now()
+ const soonest = Math.min(...mounts.map((mount) => forecasts[forecastKey(server.id, mount.mount)]).filter((days) => days != null && days > 0 && days < 3650))
+ const horizon = now + (Number.isFinite(soonest) ? soonest : 180) * 86400000
+ if (!mounts.length) return null
+ return (
+ <div className="grid gap-5 xl:grid-cols-2">
+ {mounts.map((mount) => <DiskCard key={mount.mount} server={server} mount={mount} range={range} days={forecasts[forecastKey(server.id, mount.mount)]} horizon={horizon} />)}
+ </div>
+ )
+}
+
+const milliseconds = (value) => (value >= 10000 ? `${Number((value / 1000).toFixed(1))} s` : `${Math.round(value)} ms`)
+
+function ResponseCard({ title, detail, series, start, end, bucketSeconds, gaps, utc, summary, since }) {
+ const first = series.length ? series[0].t : null
+ const table = useState(false)
+ // A stretch at the start with no figures at all means the collector then didn't measure this yet.
+ const unmeasured = first != null && first - start > (end - start) * 0.05 && !gaps.some((gap) => gap.to <= first)
+ return (
+ <section className="card overflow-hidden" aria-label={title}>
+ <CardHead title={title} detail={detail} table={series.length ? table : null}>{summary}</CardHead>
+ {table[0] && series.length ? <DataTable head={['Period', 'Average', 'Highest']} rows={[...series].reverse().map((point) => [stamp(point.t, utc), point.avg == null ? '–' : milliseconds(point.avg), point.max == null ? '–' : milliseconds(point.max)])} /> : series.length ? (
+ <MiniChart series={series} start={start} end={end} bucketSeconds={bucketSeconds} gaps={gaps.filter((gap) => first == null || gap.from >= first)} format={(tick) => String(Math.round(tick))} utc={utc}>
+ {({ x }) => unmeasured && <span className="absolute inset-y-0 left-0 z-[1] flex items-center pl-2" style={{ width: `${x(first)}%`, background: 'repeating-linear-gradient(135deg, transparent 0 5px, color-mix(in srgb, var(--color-paper) 9%, transparent) 5px 6px)' }}><span className="whitespace-nowrap rounded bg-ink px-2 py-0.5 text-[11px] text-soft">Not measured before {since || monthDay(first)}</span></span>}
+ </MiniChart>
+ ) : <p className="m-0 px-[18px] py-12 text-center text-xs text-muted">Not measured in this range.</p>}
+ </section>
+ )
+}
+
+export function Reliability({ docker, collect, start, end, bucketSeconds, gaps, utc, interval }) {
+ if (!docker.length && !collect.length) return null
+ const figure = (label, value) => <span>{label} <span className="font-semibold text-paper">{value == null ? '–' : milliseconds(value)}</span></span>
+ return (
+ <div className="grid gap-5 xl:grid-cols-2">
+ <ResponseCard title="Docker API response time" detail="listing containers · ms" series={docker} start={start} end={end} bucketSeconds={bucketSeconds} gaps={gaps} utc={utc}
+ summary={<>{figure('median', percentile(docker.map((point) => point.avg), 50))}<span className="text-dim">·</span>{figure('p95', percentile(docker.map((point) => point.max ?? point.avg), 95))}</>} />
+ <ResponseCard title="Collector time per check-in" detail="ms" series={collect} start={start} end={end} bucketSeconds={bucketSeconds} gaps={gaps} utc={utc}
+ summary={<>{figure('median', percentile(collect.map((point) => point.avg), 50))}<span className="text-dim">·</span><span>budget {interval >= 60 ? `${Math.round(interval / 60)} min` : `${interval} s`}</span></>} />
+ </div>
+ )
+}
diff --git a/src/frontend/src/statistics/StatisticsPage.jsx b/src/frontend/src/statistics/StatisticsPage.jsx
new file mode 100644
index 0000000..d723a87
--- /dev/null
+++ b/src/frontend/src/statistics/StatisticsPage.jsx
@@ -0,0 +1,226 @@
+// The Statistics page: pick a server and a range, read the two or three things that stand out, then one shared
+// timeline, when it is busy, how the disks fill up and which containers use the most.
+import { useCallback, useMemo, useState } from 'react'
+import { Link, useSearchParams } from 'react-router-dom'
+import { describeBucket } from '../chartMath.js'
+import { forecastKey, useForecasts, usePolled } from '../dashboard/data.js'
+import { forecastMonth, forecastPhrase, formatPercent, fullestMount, serverMounts, serverState, sortServers } from '../dashboard/logic.js'
+import FleetStatistics from '../FleetStatistics.jsx'
+import { Icon } from '../icons.jsx'
+import { useOverview } from '../overviewStore.js'
+import { AppShell } from '../shell.jsx'
+import { apiRequest } from '../api.js'
+import { ContainersTable } from './ContainersTable.jsx'
+import { BusyHours, Disks, Reliability, TimeAtLevels } from './Insights.jsx'
+import { Timeline } from './Timeline.jsx'
+import { RANGES, RANGE_BY_ID, deltaPoints, eventMarks, findGaps, findings, formatMoment, summarize, timelineCsv } from './logic.js'
+
+const DEFAULT_RANGE = '7d'
+const RANGE_KEY = 'homelab.statisticsRange'
+const COMPARE_KEY = 'infradeck.statistics.compare'
+// Only short ranges change from one minute to the next.
+const LIVE = new Set(['1h', '6h', '24h'])
+const METRICS = ['cpu', 'ram', 'swap', 'load', 'disk', 'docker_ms', 'collect_ms']
+const STATE_DOT = { critical: 'dot-signal', warn: 'dot-warn', ok: 'dot-ok', offline: '' }
+const SOURCES = { detailed: 'check-ins grouped together', hour: 'hourly summaries', day: 'daily summaries', week: 'weekly summaries (UTC)', month: 'monthly summaries (UTC)' }
+
+function remembered(key, fallback, allowed) {
+ try {
+ const stored = window.localStorage.getItem(key)
+ return stored !== null && (!allowed || allowed(stored)) ? stored : fallback
+ } catch {
+ return fallback
+ }
+}
+function remember(key, value) {
+ try { window.localStorage.setItem(key, value) } catch { /* the choice just isn't remembered */ }
+}
+
+function download(name, text) {
+ const url = URL.createObjectURL(new Blob([text], { type: 'text/csv' }))
+ const link = document.createElement('a')
+ link.href = url
+ link.download = name
+ link.click()
+ URL.revokeObjectURL(url)
+}
+
+function Kpi({ label, value, tone, children }) {
+ return (
+ <div className="min-w-0 px-[18px] py-4">
+ <div className="text-xs text-soft">{label}</div>
+ <div className={`mt-2.5 text-2xl font-semibold leading-none ${tone === 'warn' ? 'text-warn' : tone === 'signal' ? 'text-signal' : 'text-paper'}`}>{value}</div>
+ <div className="mt-3 min-h-4 text-xs leading-4 text-muted">{children}</div>
+ </div>
+ )
+}
+
+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 }) {
+ 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)
+ const { data: before } = usePolled(compare && range.previous ? `${base}&previous=true` : null, null)
+ const { data: busiestData } = usePolled(`/stats/servers/${server.id}/busiest?range=${range.id}`, LIVE.has(range.id) ? 60 : null)
+ const { data: usage } = usePolled(`/stats/servers/${server.id}/containers?range=${range.id}`, LIVE.has(range.id) ? 60 : null)
+ const { data: spikeData } = usePolled(`/stats/servers/${server.id}/spikes?range=${range.id}`, LIVE.has(range.id) ? 60 : null)
+ const { data: eventData } = usePolled(`/monitoring/servers/${server.id}/events?days=${range.days}`, LIVE.has(range.id) ? 60 : null)
+ const mounts = useMemo(() => serverMounts(server).filter((mount) => mount.total_gb != null), [server])
+ const forecasts = useForecasts(mounts.map((mount) => ({ serverId: server.id, mount: mount.mount })))
+
+ const points = useMemo(() => parse(data?.points), [data])
+ const previous = useMemo(() => {
+ if (!before || !data) return null
+ const shift = new Date(data.end).getTime() - new Date(before.end).getTime()
+ return parse(before.points).map((point) => ({ ...point, t: point.t + shift }))
+ }, [before, data])
+ const series = useMemo(() => Object.fromEntries(METRICS.map((key) => [key, metric(points, key)])), [points])
+ const earlier = useMemo(() => (previous ? { cpu: summarize(metric(previous, 'cpu')), ram: summarize(metric(previous, 'ram')) } : null), [previous])
+ const busiest = useMemo(() => (busiestData ? { bucketSeconds: busiestData.bucket_seconds, points: busiestData.points.map((point) => ({ ...point, t: new Date(point.time).getTime() })) } : null), [busiestData])
+
+ const start = data ? new Date(data.start).getTime() : 0
+ const end = data ? new Date(data.end).getTime() : 0
+ const bucket = data?.bucket_seconds ?? 60
+ const utc = data ? ['day', 'week', 'month'].includes(data.source) : false
+ const gaps = useMemo(() => findGaps(points.map((point) => point.t), bucket, end), [points, bucket, end])
+ const disks = mounts.map((mount) => ({ mount: mount.mount, usedPct: mount.used_pct, days: forecasts[forecastKey(server.id, mount.mount)] }))
+ const noticed = useMemo(() => (points.length ? findings({ cpu: series.cpu, ram: series.ram, swap: series.swap, load: series.load, cores: server.cpu_cores, swapTotalGb: server.system?.swap_total_gb, bucketSeconds: bucket, gaps, events: eventData?.events, busiest, containers: server.containers, disks, spikes: spikeData?.spikes?.map((spike) => ({ ...spike, t: new Date(spike.time).getTime() })) }) : []),
+ // The forecasts arrive one by one; their values are what matters, not the array's identity.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [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 (!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)
+ const ram = summarize(series.ram)
+ const swap = summarize(series.swap)
+ const load = summarize(series.load)
+ const swapFinding = noticed.find((finding) => finding.key === 'swap')
+ const root = mounts.find((mount) => mount.mount === '/') || fullestMount(mounts)
+ const rootDays = root ? forecasts[forecastKey(server.id, root.mount)] : null
+ const cores = server.cpu_cores || 1
+ const swapWarn = overview.alert_thresholds?.swap_warning_pct ?? 50
+ const 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)}` },
+ ]
+
+ 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>
+ <Kpi label="Peak CPU" value={formatPercent(cpu.peak)}>{cpu.peakAt != null && <>{formatMoment(cpu.peakAt, { utc })} · <button type="button" className="link" onClick={() => jump(cpu.peakAt)}>jump to</button></>}</Kpi>
+ <Kpi label="Average memory" value={formatPercent(ram.average)}>{[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` : null, earlier ? deltaPoints(ram.average, earlier.ram.average) : null].filter(Boolean).join(' · ')}</Kpi>
+ <Kpi label="Peak memory" value={formatPercent(ram.peak)}>{ram.peakAt != null && <>{formatMoment(ram.peakAt, { utc })} · <button type="button" className="link" onClick={() => jump(ram.peakAt)}>jump to</button></>}</Kpi>
+ <Kpi label="Swap now" value={formatPercent(server.host?.swap_pct ?? swap.last)} tone={(server.host?.swap_pct ?? swap.last ?? 0) >= Math.min(swapWarn, 10) && swapFinding ? 'warn' : (server.host?.swap_pct ?? 0) >= swapWarn ? 'warn' : undefined}>{swapFinding ? `Climbing since ${formatMoment(swapFinding.at, { clock: false })}` : swap.peak != null ? `peak ${formatPercent(swap.peak)} in this range` : ''}</Kpi>
+ <Kpi label={root?.mount === '/' || !root ? 'Root disk' : `Disk ${root.mount}`} value={formatPercent(root?.used_pct ?? server.host?.disk_usage_pct)}>{rootDays != null ? (forecastMonth(rootDays) ? `F${forecastMonth(rootDays).slice(1)}` : forecastPhrase(rootDays) || 'No clear growth trend') : 'No clear growth trend'}</Kpi>
+ </section>
+
+ <section className="card overflow-hidden" aria-label="Noticed in this range">
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 border-b border-line px-[18px] py-3"><h2 className="m-0 text-sm font-semibold text-paper">Noticed in this range</h2><span className="text-xs text-muted">Computed from the data below. Nothing is guessed.</span></div>
+ {noticed.length ? <ol className="m-0 list-none divide-y divide-line p-0">
+ {noticed.map((finding, position) => (
+ <li key={finding.key} className="grid grid-cols-[30px_minmax(0,1fr)] items-start gap-x-2 px-[18px] py-3.5 sm:grid-cols-[38px_minmax(0,1fr)_auto]">
+ <span className="mono pt-0.5 text-dim">{String(position + 1).padStart(2, '0')}</span>
+ <span className="min-w-0"><span className="block text-[13px] font-semibold text-paper">{finding.title}</span><span className="mt-1 block text-[13px] leading-5 text-soft">{finding.text}</span></span>
+ {finding.at != null && <button type="button" className="btn btn-sm col-start-2 mt-2 justify-self-start sm:col-start-3 sm:mt-0" onClick={() => jump(finding.at)}>Show on timeline</button>}
+ </li>
+ ))}
+ </ol> : <p className="m-0 px-[18px] py-5 text-[13px] text-soft">{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.'}</p>}
+ </section>
+
+ <Timeline rows={rows} points={points} previous={previous} start={start} end={end} bucketSeconds={bucket} gaps={gaps} marks={marks} busiest={busiest} utc={utc} focus={focus}
+ note={points.length ? <span title={`Built from ${SOURCES[data.source] || data.source}.`}>{points.length} {points.length === 1 ? 'point' : 'points'}, one per {describeBucket(bucket)}. Line is the average, the band reaches the highest value in each {describeBucket(bucket)}.{utc ? ' Dates are UTC.' : ''}</span> : ''}
+ legend={{ current: `Last ${range.words}`, previous: previous ? `The ${range.previous}` : null }} />
+
+ <div className="grid gap-5 xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
+ <BusyHours key={server.id} serverId={server.id} />
+ <TimeAtLevels cpu={series.cpu} ram={series.ram} words={range.span} />
+ </div>
+
+ <Disks server={server} mounts={mounts} range={range} forecasts={forecasts} />
+ <Reliability docker={series.docker_ms} collect={series.collect_ms} start={start} end={end} bucketSeconds={bucket} gaps={gaps} utc={utc} interval={server.check_interval_seconds} />
+ <ContainersTable key={server.id} server={server} usage={usage && usage.server_id === server.id ? usage : null} range={range} compare={compare} selectedId={containerId} onSelect={(id) => choose({ container: id })} />
+ </>
+}
+
+export default function StatisticsPage({ user, onLogout }) {
+ const [searchParams, setSearchParams] = useSearchParams()
+ 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])
+ const rangeId = RANGE_BY_ID[searchParams.get('range')] ? searchParams.get('range') : remembered(RANGE_KEY, DEFAULT_RANGE, (value) => Boolean(RANGE_BY_ID[value]))
+ const range = RANGE_BY_ID[rangeId]
+ const wantsAll = searchParams.get('server') === 'all'
+ const requested = Number(searchParams.get('server'))
+ const server = wantsAll ? null : servers.find((item) => item.id === requested) || servers.find((item) => item.is_dashboard_host) || servers[0] || null
+
+ const choose = useCallback((changes) => {
+ const next = new URLSearchParams(searchParams)
+ for (const [key, value] of Object.entries(changes)) {
+ if (value === '' || value === null) next.delete(key)
+ else next.set(key, String(value))
+ }
+ setSearchParams(next, { replace: true })
+ }, [searchParams, setSearchParams])
+
+ const exportCsv = async () => {
+ if (!server) return
+ const data = await apiRequest(`/monitoring/servers/${server.id}/history?range=${range.id}&metrics=${METRICS.join(',')}`, { method: 'GET' })
+ download(`${server.hostname}-${range.id}.csv`, timelineCsv(data.points, METRICS))
+ }
+
+ const crumbs = [{ label: 'Statistics', to: '/statistics' }, { label: wantsAll ? 'All servers' : server?.hostname || '…' }]
+ return (
+ <AppShell user={user} onLogout={onLogout} crumbs={servers.length ? crumbs : undefined} bare>
+ <div className="space-y-6 px-3 pt-5 sm:px-4 lg:px-7 lg:pt-7">
+ <header className="flex flex-wrap items-end justify-between gap-4">
+ <div>
+ <h1 className="m-0 text-[21px] font-semibold leading-7 text-paper">Statistics</h1>
+ <p className="mb-0 mt-1.5 text-[13px] text-soft">{wantsAll ? 'How the whole fleet is doing: incidents, availability and who uses the most.' : 'How a server behaved over time. Hover anywhere on the timeline to read every metric at that moment.'}</p>
+ </div>
+ {server && <button type="button" className="btn" onClick={exportCsv}><Icon name="download" size={14} />Export CSV</button>}
+ </header>
+
+ {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 && (
+ <div className="card px-[18px] py-10 text-center">
+ <p className="m-0 text-sm font-medium text-paper">No server is reporting yet.</p>
+ <p className="mb-0 mt-2 text-[13px] text-muted">History appears here once a collector has checked in. <Link to="/" className="link">Connect a server on the Overview</Link>.</p>
+ </div>
+ )}
+
+ {servers.length > 0 && <>
+ <div className="card flex flex-wrap items-center gap-x-6 gap-y-3 px-[14px] py-2.5">
+ <div className="flex items-center gap-3"><span className="text-xs text-muted">Server</span>
+ <div className="seg flex-wrap" role="group" aria-label="Server">
+ <button type="button" aria-pressed={wantsAll} onClick={() => choose({ server: 'all', container: '' })}>All</button>
+ {servers.map((item) => <button key={item.id} type="button" aria-pressed={server?.id === item.id} onClick={() => choose({ server: item.id, container: '' })} className="!inline-flex items-center gap-2"><span className={`dot ${STATE_DOT[serverState(item)]}`} style={{ width: 6, height: 6 }} />{item.hostname}</button>)}
+ </div>
+ </div>
+ <div className="flex items-center gap-3"><span className="text-xs text-muted">Range</span>
+ <div className="seg flex-wrap" role="group" aria-label="Time range">
+ {RANGES.map((option) => <button key={option.id} type="button" aria-pressed={range.id === option.id} onClick={() => { remember(RANGE_KEY, option.id); choose({ range: option.id }) }}>{option.label}</button>)}
+ </div>
+ </div>
+ {!wantsAll && <label className={`ml-auto flex items-center gap-2.5 text-xs ${range.previous ? 'cursor-pointer text-soft' : 'text-dim'}`}>
+ <input type="checkbox" role="switch" className="peer sr-only" checked={compare && Boolean(range.previous)} disabled={!range.previous} onChange={(event) => { setCompare(event.target.checked); remember(COMPARE_KEY, event.target.checked ? 'on' : 'off') }} />
+ <span aria-hidden="true" className="relative h-[18px] w-8 rounded-full border border-edge bg-raised transition-colors after:absolute after:left-[2px] after:top-[2px] after:h-3 after:w-3 after:rounded-full after:bg-muted after:transition-all peer-checked:border-paper peer-checked:bg-paper peer-checked:after:left-[16px] peer-checked:after:bg-bg peer-focus-visible:outline peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-paper" />
+ {range.previous ? `Compare with ${range.previous}` : 'Nothing before “All” to compare with'}
+ </label>}
+ </div>
+
+ {wantsAll ? <FleetStatistics request={apiRequest} servers={servers} range={range.id} />
+ : server && <ServerStatistics key={`${server.id}-${range.id}`} server={server} overview={overview} range={range} compare={compare} containerId={searchParams.get('container') || ''} choose={choose} />}
+ </>}
+ </div>
+ </AppShell>
+ )
+}
diff --git a/src/frontend/src/statistics/Timeline.jsx b/src/frontend/src/statistics/Timeline.jsx
new file mode 100644
index 0000000..5ee0d43
--- /dev/null
+++ b/src/frontend/src/statistics/Timeline.jsx
@@ -0,0 +1,242 @@
+// One shared timeline: metrics stacked on the same time axis with one crosshair, so a CPU spike, a load spike and
+// what was running then all line up. Missing data is hatched instead of being a silent break in the line.
+import { useEffect, useMemo, useRef, useState } from 'react'
+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)'
+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']
+
+function useWidth(ref, fallback = 900) {
+ const [width, setWidth] = useState(fallback)
+ useEffect(() => {
+ const element = ref.current
+ if (!element) return undefined
+ const update = () => setWidth(Math.max(Math.round(element.getBoundingClientRect().width), 200))
+ update()
+ if (typeof ResizeObserver === 'undefined') return undefined
+ const observer = new ResizeObserver(update)
+ observer.observe(element)
+ return () => observer.disconnect()
+ }, [ref])
+ return width
+}
+
+// The top of a row's scale: a fixed 100 for percentages, otherwise a round number above the highest value.
+export function scaleTop(row, series, previous) {
+ if (row.max) return row.max
+ const peak = Math.max(0, row.floor || 0, ...series.map((point) => point.max ?? point.avg ?? 0), ...(previous || []).map((point) => point.avg ?? 0))
+ return niceCeiling(peak * 1.15 || 1)
+}
+
+// The drawing itself: band up to each period's maximum, the average as a line, the period before as a dashed
+// line, and hatching where nothing was reported. Sits in a relatively positioned box; x is time, y is 0..top.
+export function Plot({ series, previous, start, end, top, ticks, format, bucketSeconds, gaps = [], tone = 'paper', band = true, height, children }) {
+ const span = Math.max(1, end - start)
+ const x = (time) => ((time - start) / span) * 100
+ const y = (value) => (1 - Math.min(Math.max(value, 0), top) / top) * 100
+ const runs = useMemo(() => splitRuns(series.filter((point) => point.avg != null), bucketSeconds), [series, bucketSeconds])
+ const previousRuns = useMemo(() => splitRuns((previous || []).filter((point) => point.avg != null), bucketSeconds), [previous, bucketSeconds])
+ const line = (run) => run.map((point, index) => `${index ? 'L' : 'M'}${x(point.t).toFixed(2)},${y(point.avg).toFixed(2)}`).join(' ')
+ const area = (run) => `${run.map((point, index) => `${index ? 'L' : 'M'}${x(point.t).toFixed(2)},${y(point.max ?? point.avg).toFixed(2)}`).join(' ')} ${[...run].reverse().map((point) => `L${x(point.t).toFixed(2)},${y(point.avg).toFixed(2)}`).join(' ')} Z`
+ const color = TONE[tone] || TONE.paper
+ return (
+ <div className="relative" style={{ height, marginLeft: GUTTER, marginRight: PAD_RIGHT }}>
+ {ticks.map((tick) => <span key={tick} aria-hidden="true" className="absolute right-full -translate-y-1/2 whitespace-nowrap pr-2.5 text-[11px] leading-none text-muted" style={{ top: `${y(tick)}%` }}>{format(tick)}</span>)}
+ {gaps.map((gap) => <span key={gap.from} aria-hidden="true" className="absolute inset-y-0" style={{ left: `${Math.max(0, x(gap.from))}%`, width: `${Math.max(0.3, Math.min(100, x(gap.to)) - Math.max(0, x(gap.from)))}%`, background: HATCH }} />)}
+ <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="absolute inset-0 h-full w-full overflow-visible" aria-hidden="true">
+ {ticks.map((tick) => <line key={tick} x1="0" x2="100" y1={y(tick)} y2={y(tick)} stroke="var(--color-line)" strokeWidth="1" vectorEffect="non-scaling-stroke" />)}
+ {band && runs.map((run, index) => run.length > 1 && <path key={`band-${index}`} d={area(run)} fill="var(--color-paper)" fillOpacity="0.16" />)}
+ {previousRuns.map((run, index) => run.length > 1 && <path key={`previous-${index}`} d={line(run)} fill="none" stroke="var(--color-muted)" strokeWidth="1" strokeDasharray="3 3" vectorEffect="non-scaling-stroke" />)}
+ {runs.map((run, index) => (run.length > 1
+ ? <path key={`line-${index}`} d={line(run)} fill="none" stroke={color} strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
+ : <line key={`line-${index}`} x1={x(run[0].t) - 0.15} x2={x(run[0].t) + 0.15} y1={y(run[0].avg)} y2={y(run[0].avg)} stroke={color} strokeWidth="3" strokeLinecap="round" vectorEffect="non-scaling-stroke" />))}
+ </svg>
+ {children?.({ x, y })}
+ </div>
+ )
+}
+
+function nearest(points, time) {
+ if (!points.length) return -1
+ let low = 0
+ let high = points.length - 1
+ while (low < high) {
+ const middle = Math.floor((low + high) / 2)
+ if (points[middle].t < time) low = middle + 1
+ else high = middle
+ }
+ return low > 0 && time - points[low - 1].t < points[low].t - time ? low - 1 : low
+}
+
+// Time labels under the timeline: midnights for ranges of days, otherwise evenly spaced clock times.
+function axisTicks(start, end, utc) {
+ const span = end - start
+ const ticks = []
+ if (span > 36 * 3600000 && span <= 40 * 86400000 && !utc) {
+ const first = new Date(start)
+ first.setHours(0, 0, 0, 0)
+ const days = Math.ceil(span / 86400000)
+ const every = Math.max(1, Math.ceil(days / 8))
+ for (let day = 0, moment = first.getTime(); moment <= end; day += 1, moment = new Date(first.getFullYear(), first.getMonth(), first.getDate() + day).getTime()) {
+ if (moment >= start && day % every === 0) ticks.push({ t: moment, label: `${days <= 8 ? `${WEEKDAYS[new Date(moment).getDay()]} ` : ''}${new Date(moment).getDate()} ${MONTHS[new Date(moment).getMonth()]}` })
+ }
+ return ticks
+ }
+ for (let index = 0; index <= 6; index += 1) { const moment = start + (span * index) / 6; ticks.push({ t: moment, label: formatTime(moment, span / 1000, utc) }) }
+ return ticks
+}
+
+const tableValue = (value, row) => (value == null ? '–' : row.format(value))
+
+// ``rows``: [{ key, label, format, max?, floor?, tone?, sub?, band?, limit?: { value, label }, note?: { t, text } }]
+// ``points``: [{ t, samples, [key]: { avg, max } | null }]; ``previous`` the same for the period before, already
+// shifted onto this period's time axis. ``focus``: { t } scrolls into view and pins the crosshair there.
+export function Timeline({ title = 'Timeline', note, rows, points, previous, start, end, bucketSeconds, gaps = [], marks, busiest, utc = false, legend, focus, compact = false, action }) {
+ const wrap = useRef(null)
+ const width = useWidth(wrap)
+ const [hover, setHover] = useState(null)
+ const [pinned, setPinned] = useState(null)
+ const [asTable, setAsTable] = useState(false)
+ const labelWidth = compact ? 132 : width < 700 ? 104 : 170
+ const plotLeft = labelWidth + GUTTER
+ const plotWidth = Math.max(40, width - plotLeft - PAD_RIGHT)
+ 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])
+
+ // A finding's "Show on timeline" pins the crosshair on its moment.
+ useEffect(() => {
+ if (!focus?.t || !points.length) return
+ setPinned(nearest(points, focus.t))
+ wrap.current?.scrollIntoView({ behavior: 'smooth', block: 'center' })
+ }, [focus, points])
+
+ const active = hover ?? pinned
+ const index = active != null && active >= 0 && active < points.length ? active : null
+ const point = index != null ? points[index] : null
+ const crossX = point ? plotLeft + ((point.t - start) / span) * plotWidth : null
+ const move = (event) => {
+ const box = wrap.current.getBoundingClientRect()
+ const fraction = (event.clientX - box.left - plotLeft) / plotWidth
+ if (fraction < -0.02 || fraction > 1.02) { setHover(null); return }
+ setHover(nearest(points, start + Math.min(1, Math.max(0, fraction)) * span))
+ }
+ const onKeyDown = (event) => {
+ if (!points.length) return
+ const from = index ?? points.length - 1
+ if (event.key === 'ArrowLeft') { event.preventDefault(); setPinned(Math.max(0, from - 1)) } else if (event.key === 'ArrowRight') { event.preventDefault(); setPinned(Math.min(points.length - 1, from + 1)) } else if (event.key === 'Home') { event.preventDefault(); setPinned(0) } else if (event.key === 'End') { event.preventDefault(); setPinned(points.length - 1) } else if (event.key === 'Escape') setPinned(null)
+ }
+ const ticks = axisTicks(start, end, utc)
+ const who = point ? busiestAt(busiest, point.t) : null
+ const tooltipLeft = crossX == null ? 0 : crossX > width - 310 ? crossX - 286 : crossX + 14
+
+ return (
+ <section className={compact ? '' : 'card overflow-hidden'} aria-label={title}>
+ <div className={`flex flex-wrap items-center gap-x-3 gap-y-2 ${compact ? 'px-[18px] pb-2 pt-3' : 'border-b border-line px-[18px] py-3'}`}>
+ <h2 className={`m-0 font-semibold text-paper ${compact ? 'text-[13px]' : 'text-sm'}`}>{title}</h2>
+ {note && <span className="min-w-0 text-xs text-muted">{note}</span>}
+ <span className="ml-auto flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-soft">
+ {legend?.current && <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>}
+ {action}
+ <button type="button" className="btn btn-sm" aria-pressed={asTable} onClick={() => setAsTable((value) => !value)}>{asTable ? 'View as chart' : 'View as table'}</button>
+ </span>
+ </div>
+
+ {asTable ? (
+ <div className="custom-scroll max-h-[420px] overflow-auto">
+ <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-[18px] font-medium">Period</th>{rows.map((row) => <th key={row.key} className="pr-4 text-right font-medium">{row.label}{row.band === false ? '' : ' avg / max'}</th>)}</tr></thead>
+ <tbody>{[...points].reverse().map((item) => <tr key={item.t} className="h-8 border-t border-line text-soft"><td className="whitespace-nowrap pl-[18px] text-muted">{formatPeriod(item.t, bucketSeconds, utc)}</td>{rows.map((row) => <td key={row.key} className="pr-4 text-right">{tableValue(item[row.key]?.avg, row)}{row.band === false ? '' : ` / ${tableValue(item[row.key]?.max, row)}`}</td>)}</tr>)}</tbody>
+ </table>
+ {!points.length && <p className="m-0 px-[18px] py-8 text-center text-xs text-muted">Nothing was recorded in this range.</p>}
+ </div>
+ ) : (
+ <div ref={wrap} className="relative select-none outline-none focus-visible:ring-1 focus-visible:ring-paper" tabIndex={0} role="group" aria-label={`${title}. Use the left and right arrow keys to read each period.`} onPointerMove={move} onPointerLeave={() => setHover(null)} onPointerDown={(event) => { if (event.pointerType !== 'mouse') move(event) }} onKeyDown={onKeyDown}>
+ {marks && (
+ <div className="grid border-b border-line" style={{ gridTemplateColumns: `${labelWidth}px minmax(0, 1fr)` }}>
+ <div className="flex items-center border-r border-line px-[18px] text-xs text-soft">Events</div>
+ <div className="relative h-10 overflow-hidden" style={{ marginLeft: GUTTER, marginRight: PAD_RIGHT }}>
+ {marks.map((mark, position) => {
+ const left = ((mark.t - start) / span) * 100
+ const room = ((marks[position + 1]?.t ?? end) - mark.t) / span * plotWidth
+ const text = `${mark.label}${mark.count > 1 ? ` ×${mark.count}` : ''}`
+ return <span key={`${mark.t}-${mark.kind}`} className="absolute top-1/2 flex -translate-y-1/2 items-center gap-1.5 whitespace-nowrap text-[11px] text-muted" style={{ left: `${left}%` }} title={`${formatPeriod(mark.t, 60)} · ${text}${mark.detail ? ` · ${mark.detail}` : ''}`}>
+ <span className="h-[5px] w-[5px] shrink-0" style={{ background: mark.tone === 'signal' ? 'var(--color-signal)' : mark.tone === 'warn' ? 'var(--color-warn)' : 'var(--color-dim)' }} />
+ {room > text.length * 6.2 + 16 && <span className={mark.tone === 'plain' ? '' : 'text-soft'}>{text}</span>}
+ </span>
+ })}
+ {!marks.length && <span className="absolute left-0 top-1/2 -translate-y-1/2 text-[11px] text-dim">No events recorded in this range</span>}
+ </div>
+ </div>
+ )}
+
+ {rows.map((row) => {
+ const own = series[row.key]
+ const known = own.filter((item) => item.avg != null)
+ const top = scaleTop(row, own, before[row.key])
+ const value = point ? point[row.key]?.avg : known.length ? known[known.length - 1].avg : null
+ const height = compact ? 84 : 104
+ return (
+ <div key={row.key} className="grid border-b border-line last:border-b-0" style={{ gridTemplateColumns: `${labelWidth}px minmax(0, 1fr)` }}>
+ <div className={`min-w-0 border-r border-line px-[18px] ${compact ? 'py-3' : 'py-4'}`}>
+ <div className="text-[13px] font-medium text-paper">{row.label}</div>
+ <div className={`mt-2 font-semibold leading-none text-paper ${compact ? 'text-lg' : 'text-[21px]'}`}>{value == null ? '–' : row.format(value)}</div>
+ {row.sub && <div className="mt-2.5 text-[11px] leading-4 text-muted">{row.sub}</div>}
+ </div>
+ <div className="min-w-0 pb-2 pt-[18px]">
+ <Plot series={own} previous={before[row.key]} start={start} end={end} top={top} ticks={[top, top / 2, 0]} format={row.axis || row.format} bucketSeconds={bucketSeconds} gaps={gaps} tone={row.tone} band={row.band !== false} height={height}>
+ {({ 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)}%` }}><span className="absolute -top-[17px] right-0 text-[11px] text-signal">{row.limit.label}</span></span>}
+ {row.note && row.note.t >= start && row.note.t <= end && <span aria-hidden="true" className="absolute top-0 bottom-0 border-l border-dashed border-warn/70" style={{ left: `${x(row.note.t)}%` }}><span className="absolute -top-[5px] left-[-3px] flex items-center gap-1.5 whitespace-nowrap text-[11px] text-warn"><span className="h-[6px] w-[6px] bg-warn" />{row.note.text}</span></span>}
+ {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>
+ )
+ })}
+
+ <div className="grid" style={{ gridTemplateColumns: `${labelWidth}px minmax(0, 1fr)` }}>
+ <div className="border-r border-line" />
+ <div className="relative h-7" style={{ marginLeft: GUTTER, marginRight: PAD_RIGHT }} aria-hidden="true">
+ {ticks.map((tick, position) => <span key={tick.t} className={`absolute top-1.5 whitespace-nowrap text-[11px] text-muted ${position === ticks.length - 1 && (tick.t - start) / span > 0.93 ? '-translate-x-full' : position === 0 ? '' : '-translate-x-1/2'}`} style={{ left: `${((tick.t - start) / span) * 100}%` }}>{tick.label}</span>)}
+ </div>
+ </div>
+
+ {point && <span aria-hidden="true" className="pointer-events-none absolute w-px bg-paper/70" style={{ left: crossX, top: marks ? 41 : 0, bottom: 28 }} />}
+ {point && (
+ <div role="status" className="pointer-events-none absolute z-10 w-[272px] rounded-md border border-edge bg-bg px-3.5 py-3 text-xs shadow-[0_8px_24px_rgba(0,0,0,0.5)]" style={{ left: Math.max(4, tooltipLeft), top: marks ? 58 : 14 }}>
+ <div className="mb-2 text-[13px] font-semibold text-paper">{formatPeriod(point.t, bucketSeconds, utc)}</div>
+ {rows.map((row) => <div key={row.key} className="flex justify-between gap-4 py-[3px]"><span className="text-muted">{row.short || row.label}{row.pair ? ' avg / max' : ''}</span><span className="text-paper">{point[row.key]?.avg == null ? 'no data' : `${row.format(point[row.key].avg)}${row.pair && point[row.key].max != null ? ` / ${row.format(point[row.key].max)}` : ''}`}</span></div>)}
+ {who && <div className="mt-2 flex justify-between gap-4 border-t border-line pt-2"><span className="text-muted">Busiest</span><span className="mono truncate text-paper">{who.name} {Math.round(who.cpu)}%</span></div>}
+ </div>
+ )}
+ {!points.length && <p className="pointer-events-none absolute inset-x-0 top-1/2 m-0 -translate-y-1/2 text-center text-xs text-muted" style={{ paddingLeft: labelWidth }}>Nothing was recorded in this range.</p>}
+ </div>
+ )}
+ </section>
+ )
+}
+
+// One small chart in its own card body: used for response times and the disk forecasts.
+export function MiniChart({ series, start, end, bucketSeconds, gaps = [], top, format, height = 132, utc = false, labels, children, band = true }) {
+ const scale = top ?? niceCeiling(Math.max(1, ...series.map((point) => point.max ?? point.avg ?? 0)) * 1.1)
+ const span = Math.max(1, end - start)
+ const edge = labels || [{ t: start, label: formatTime(start, span / 1000, utc) }, { t: end, label: formatTime(end, span / 1000, utc) }]
+ return (
+ <div className="px-[18px] pb-3 pt-6">
+ <Plot series={series} start={start} end={end} top={scale} ticks={[scale, scale / 2, 0]} format={format} bucketSeconds={bucketSeconds} gaps={gaps} height={height} band={band}>{children}</Plot>
+ <div aria-hidden="true" className="relative mt-2 h-4 text-[11px] text-muted" style={{ marginLeft: GUTTER, marginRight: PAD_RIGHT }}>
+ {edge.map((tick, index) => <span key={tick.t} className={`absolute whitespace-nowrap ${index === edge.length - 1 ? '-translate-x-full' : index ? '-translate-x-1/2' : ''}`} style={{ left: `${((tick.t - start) / span) * 100}%` }}>{tick.label}</span>)}
+ </div>
+ </div>
+ )
+}
diff --git a/src/frontend/src/statistics/logic.js b/src/frontend/src/statistics/logic.js
new file mode 100644
index 0000000..cf313a6
--- /dev/null
+++ b/src/frontend/src/statistics/logic.js
@@ -0,0 +1,288 @@
+// Pure helpers for the Statistics page: what stands out in a range, gaps, bands, percentiles and wording.
+// Series are [{ t, avg, max, samples }] with t in milliseconds, oldest first. No React in here.
+import { formatMegabytes, formatPercent, formatSpan } from '../dashboard/logic.js'
+
+const DAY_MS = 86400000
+const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
+const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
+const pad = (value) => String(value).padStart(2, '0')
+
+export const RANGES = [
+ { id: '1h', label: '1 h', words: 'hour', previous: 'previous hour', short: 'previous hour', span: 'hour', days: 1 },
+ { id: '6h', label: '6 h', words: '6 hours', previous: 'previous 6 hours', short: 'previous 6 h', span: 'time', days: 1 },
+ { id: '24h', label: '24 h', words: '24 hours', previous: 'previous 24 hours', short: 'previous day', span: 'day', days: 2 },
+ { id: '7d', label: '7 days', words: '7 days', previous: 'previous 7 days', short: 'previous week', span: 'week', days: 7 },
+ { id: '30d', label: '30 days', words: '30 days', previous: 'previous 30 days', short: 'previous 30 days', span: 'time', days: 30 },
+ { id: '90d', label: '90 days', words: '90 days', previous: 'previous 90 days', short: 'previous 90 days', span: 'time', days: 90 },
+ { id: '1y', label: '1 year', words: 'year', previous: 'previous year', short: 'previous year', span: 'year', days: 366 },
+ { id: 'all', label: 'All', words: 'whole history', previous: null, short: null, span: 'time', days: 366 },
+]
+export const RANGE_BY_ID = Object.fromEntries(RANGES.map((range) => [range.id, range]))
+
+// "Thu 9 Oct 03:12", in the viewer's time zone, or just "Thu 9 Oct" for day-sized points.
+export function formatMoment(time, { clock = true, utc = false } = {}) {
+ const date = new Date(time)
+ const day = utc ? `${WEEKDAYS[date.getUTCDay()]} ${date.getUTCDate()} ${MONTHS[date.getUTCMonth()]}` : `${WEEKDAYS[date.getDay()]} ${date.getDate()} ${MONTHS[date.getMonth()]}`
+ return clock && !utc ? `${day} ${pad(date.getHours())}:${pad(date.getMinutes())}` : day
+}
+
+export const formatClock = (time) => { const date = new Date(time); return `${pad(date.getHours())}:${pad(date.getMinutes())}` }
+
+// "Thu 9 Oct, 03:00–03:30" for one point's period.
+export function formatPeriod(time, bucketSeconds, utc = false) {
+ if (utc || bucketSeconds >= 86400) return formatMoment(time, { clock: false, utc })
+ return `${formatMoment(time, { clock: false })}, ${formatClock(time)}–${formatClock(time + bucketSeconds * 1000)}`
+}
+
+// "+1.2 pts" between two percentages, or null when either is unknown.
+export function deltaPoints(current, previous) {
+ if (current == null || previous == null) return null
+ const delta = Number((current - previous).toFixed(1))
+ return `${delta > 0 ? '+' : delta < 0 ? '−' : '±'}${Math.abs(delta)} pts`
+}
+
+// Weighted average and highest maximum of a series, with the moment of the maximum.
+export function summarize(series) {
+ let total = 0
+ let weight = 0
+ let peak = null
+ for (const point of series) {
+ if (point.avg != null) { total += point.avg * (point.samples || 1); weight += point.samples || 1 }
+ const top = point.max ?? point.avg
+ if (top != null && (peak === null || top > peak.value)) peak = { value: top, t: point.t }
+ }
+ return { average: weight ? total / weight : null, peak: peak?.value ?? null, peakAt: peak?.t ?? null, last: series.length ? series[series.length - 1].avg : null }
+}
+
+// Stretches with no data, as [{ from, to }] in milliseconds: before the first point is not a gap (history may
+// simply start later), but a hole between points or a silence up to ``end`` is.
+export function findGaps(times, bucketSeconds, end) {
+ const step = bucketSeconds * 1000
+ const gaps = []
+ for (let index = 1; index < times.length; index += 1) {
+ if (times[index] - times[index - 1] > step * 1.5) gaps.push({ from: times[index - 1] + step, to: times[index] })
+ }
+ if (times.length && end != null && end - times[times.length - 1] > step * 2.5) gaps.push({ from: times[times.length - 1] + step, to: end })
+ return gaps
+}
+
+const span = (milliseconds) => {
+ const minutes = Math.round(milliseconds / 60000)
+ if (minutes < 60) return `${minutes} min`
+ if (minutes < 48 * 60) return minutes % 60 ? `${Math.floor(minutes / 60)} h ${minutes % 60} min` : `${Math.floor(minutes / 60)} h`
+ return formatSpan(milliseconds / 1000)
+}
+
+// The value of ``lookup`` ({ bucketSeconds, points: [{ t, name, cpu }] }) that covers a moment, or null.
+export function busiestAt(lookup, time) {
+ const points = lookup?.points
+ if (!points?.length) return null
+ let low = 0
+ let high = points.length - 1
+ while (low < high) {
+ const middle = Math.ceil((low + high) / 2)
+ if (points[middle].t <= time) low = middle
+ else high = middle - 1
+ }
+ const found = points[low]
+ return found.t <= time && time < found.t + lookup.bucketSeconds * 1000 ? found : null
+}
+
+function swapFinding({ swap, ram, swapTotalGb, containers }) {
+ const known = swap.filter((point) => point.avg != null)
+ if (known.length < 6) return null
+ const last = known[known.length - 1].avg
+ const lowest = Math.min(...known.map((point) => point.avg))
+ if (last < 10 || last - lowest < 5) return null
+ // Where the climb began: the last moment it was still within a point of its lowest.
+ let began = known[0]
+ for (const point of known) if (point.avg <= lowest + 1) began = point
+ if (began === known[known.length - 1]) return null
+ const ramPeak = Math.max(...ram.map((point) => point.max ?? point.avg ?? 0))
+ const amount = (percent) => (swapTotalGb ? `${Number(((percent / 100) * swapTotalGb).toFixed(1))} GB` : formatPercent(percent))
+ const holder = [...(containers || [])].filter((container) => container.swap_mb > 1).sort((a, b) => b.swap_mb - a.swap_mb)[0]
+ const roomy = ramPeak < 80
+ return {
+ key: 'swap', weight: 3 + (last - lowest) / 20, at: began.t, metric: 'swap', note: 'started climbing',
+ title: roomy ? 'Swap keeps growing while memory has room.' : 'Swap keeps growing.',
+ text: `Swap went from ${amount(lowest)} to ${amount(last)} since ${formatMoment(began.t, { clock: false })}${roomy ? `, but RAM never passed ${formatPercent(ramPeak)}. Something is being paged out and not coming back.` : `, with RAM as high as ${formatPercent(ramPeak)}. The machine is short of memory.`}${holder ? ` ${holder.name} holds the most swap (${formatMegabytes(holder.swap_mb)}).` : ''}`,
+ }
+}
+
+function spikeFinding({ cpu, busiest, bucketSeconds, spikes }) {
+ if (bucketSeconds > 3600 || cpu.length < 12) return null
+ const days = new Set(cpu.map((point) => Math.floor((point.t - new Date(point.t).getTimezoneOffset() * 60000) / DAY_MS)))
+ if (days.size < 3) return null
+ const byHour = new Map()
+ for (const point of cpu) {
+ if ((point.max ?? 0) < 90) continue
+ const date = new Date(point.t)
+ const entry = byHour.get(date.getHours()) || { days: new Set(), points: [] }
+ entry.days.add(Math.floor((point.t - date.getTimezoneOffset() * 60000) / DAY_MS))
+ entry.points.push(point)
+ byHour.set(date.getHours(), entry)
+ }
+ const [hour, entry] = [...byHour.entries()].sort((a, b) => b[1].days.size - a[1].days.size)[0] || []
+ if (entry === undefined || entry.days.size < 3 || entry.days.size < days.size * 0.6) return null
+ const quiet = cpu.filter((point) => new Date(point.t).getHours() !== hour && point.avg != null)
+ const rest = quiet.length ? quiet.reduce((sum, point) => sum + point.avg, 0) / quiet.length : null
+ const top = Math.max(...entry.points.map((point) => point.max))
+ const names = new Map()
+ for (const point of entry.points) { const who = busiestAt(busiest, point.t); if (who) names.set(who.name, (names.get(who.name) || 0) + 1) }
+ const culprit = [...names.entries()].sort((a, b) => b[1] - a[1])[0]
+ const when = hour < 6 || hour >= 22 ? 'night' : 'day'
+ const named = culprit && culprit[1] >= entry.points.length / 2 ? culprit[0] : null
+ // How long each one lasted, from the check-ins themselves when the range still has them.
+ const minutes = (spikes || []).filter((spike) => new Date(spike.t).getHours() === hour).map((spike) => Math.max(1, Math.round(spike.seconds / 60)))
+ const shortest = Math.min(...minutes)
+ const longest = Math.max(...minutes)
+ const lasting = minutes.length ? `Spikes last ${shortest === longest ? `about ${longest}` : `${shortest} to ${longest}`} ${longest === 1 ? 'minute' : 'minutes'}${named ? ` and ${named} is the busiest container each time` : ''}.` : `Seen on ${entry.days.size} of ${days.size} days${named ? `, and ${named} is the busiest container each time` : ''}.`
+ return {
+ key: 'spike', weight: 2 + entry.days.size / 10, at: entry.points[entry.points.length - 1].t, metric: 'cpu',
+ title: `CPU hits ${formatPercent(top)} at ${pad(hour)}:00 every ${when}.`,
+ text: `${lasting}${rest != null ? ` Average CPU stays around ${formatPercent(rest)} the rest of the day.` : ''}`,
+ // One mark per occurrence for the timeline's event row; what the job is, Infradeck can't know.
+ marks: entry.points.map((point) => ({ t: point.t, kind: 'cpu_spike', group: 'cpu_spike', label: `${when === 'night' ? 'nightly' : 'daily'} ${named ? `${named} ` : ''}peak`, tone: 'plain', count: 1, detail: `CPU reached ${formatPercent(point.max)}` })),
+ }
+}
+
+function gapFinding({ gaps, events, bucketSeconds }) {
+ const longest = [...gaps].sort((a, b) => (b.to - b.from) - (a.to - a.from))[0]
+ if (!longest || longest.to - longest.from < Math.max(10 * 60000, bucketSeconds * 2000)) return null
+ const rebooted = (events || []).some((event) => event.kind === 'reboot' && new Date(event.time).getTime() >= longest.from && new Date(event.time).getTime() <= longest.to + 10 * 60000)
+ const sameDay = new Date(longest.from).toDateString() === new Date(longest.to).toDateString()
+ const others = gaps.length - 1
+ return {
+ key: 'gap', weight: 1 + Math.min(2, (longest.to - longest.from) / (6 * 3600000)), at: longest.from, metric: 'cpu',
+ title: `No data for ${span(longest.to - longest.from)} on ${formatMoment(longest.from, { clock: false })}.`,
+ text: `Nothing was reported from ${sameDay ? formatClock(longest.from) : formatMoment(longest.from)} to ${sameDay ? formatClock(longest.to) : formatMoment(longest.to)}. ${rebooted ? 'The machine rebooted in that time.' : 'No reboot was recorded, so the machine stayed up and the collector itself was down or could not reach Infradeck.'}${others > 0 ? ` There ${others === 1 ? 'is one more shorter gap' : `are ${others} more shorter gaps`} in this range.` : ''}`,
+ }
+}
+
+function loadFinding({ load, cores }) {
+ if (!cores || load.length < 6) return null
+ const over = load.filter((point) => (point.avg ?? 0) > cores)
+ const share = over.length / load.length
+ if (share < 0.05) return null
+ return {
+ key: 'load', weight: 2 + share * 2, at: over[over.length - 1].t, metric: 'load',
+ title: `Load is above the ${cores} cores ${formatPercent(share * 100)} of the time.`,
+ text: `Work is queuing for the CPU in ${over.length} of ${load.length} periods, as high as ${Math.max(...over.map((point) => point.max ?? point.avg)).toFixed(2)}.`,
+ }
+}
+
+function memoryFinding({ ram }) {
+ const summary = summarize(ram)
+ if (summary.peak == null || summary.peak < 90) return null
+ return {
+ key: 'memory', weight: 2.5 + (summary.peak - 90) / 10, at: summary.peakAt, metric: 'ram',
+ title: `Memory reached ${formatPercent(summary.peak)}.`,
+ text: `The peak was on ${formatMoment(summary.peakAt)}; the average over the range is ${formatPercent(summary.average)}. Above 90% the kernel starts reclaiming and swapping.`,
+ }
+}
+
+function diskFinding({ disks }) {
+ const soon = (disks || []).filter((disk) => disk.days != null && disk.days < 60).sort((a, b) => a.days - b.days)[0]
+ if (!soon) return null
+ return {
+ key: 'disk', weight: 6 - soon.days / 60, at: null, metric: 'disk',
+ title: `${soon.mount} fills up in about ${Math.max(1, Math.round(soon.days))} days.`,
+ text: `It is ${formatPercent(soon.usedPct)} full and growing steadily over the last 30 days. The forecast is drawn in the disk charts below.`,
+ }
+}
+
+// The two or three things that stand out in the selected range, most important first. Every sentence is worked out
+// from the series passed in; nothing is guessed.
+export function findings(input, limit = 3) {
+ const found = [diskFinding(input), swapFinding(input), memoryFinding(input), spikeFinding(input), loadFinding(input), gapFinding(input)].filter(Boolean)
+ return found.sort((a, b) => b.weight - a.weight).slice(0, limit)
+}
+
+export const LEVELS = [[0, 10], [10, 20], [20, 30], [30, 50], [50, 80], [80, 100]]
+
+// How much of the time a percentage spent in each band, weighted by the check-ins behind every point, and one
+// sentence that says what it means.
+export function timeAtLevels(series, what = 'CPU') {
+ const totals = LEVELS.map(() => 0)
+ let all = 0
+ for (const point of series) {
+ if (point.avg == null) continue
+ const weight = point.samples || 1
+ const index = LEVELS.findIndex(([low, high], position) => point.avg >= low && (point.avg < high || position === LEVELS.length - 1))
+ if (index >= 0) { totals[index] += weight; all += weight }
+ }
+ const bands = LEVELS.map(([low, high], index) => ({ label: `${low}–${high}%`, share: all ? (totals[index] / all) * 100 : 0, hot: low >= 80 }))
+ if (!all) return { bands, sentence: '' }
+ const whole = (value) => (value >= 10 ? `${Math.round(value)}%` : formatPercent(value))
+ const under20 = bands[0].share + bands[1].share
+ const over80 = bands[5].share
+ const over50 = bands[4].share + over80
+ let sentence
+ if (over80 >= 10) sentence = `${whole(over80)} of the time the ${what} was above 80%. This machine is close to its limit.`
+ else if (under20 >= 90) sentence = `${whole(under20)} of the time the ${what} was under 20%. There's headroom for more services on this machine.`
+ else if (over50 >= 25) sentence = `${whole(over50)} of the time the ${what} was above 50%. It is well used, with some room left.`
+ else sentence = `${whole(100 - over50)} of the time the ${what} was under 50%.`
+ return { bands, sentence }
+}
+
+// The p-th percentile (0–100) of some numbers, by nearest rank; null for none.
+export function percentile(values, p) {
+ const sorted = values.filter((value) => value != null && Number.isFinite(value)).sort((a, b) => a - b)
+ if (!sorted.length) return null
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1))]
+}
+
+// The hour of the day that is busiest on average across the week, when it clearly stands out; else null.
+export function busiestHour(grid) {
+ const hours = Array.from({ length: 24 }, (_, hour) => { const values = grid.map((row) => row[hour]).filter((value) => value != null); return values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : null })
+ const known = hours.filter((value) => value != null)
+ if (known.length < 12) return null
+ const top = Math.max(...known)
+ const mean = known.reduce((sum, value) => sum + value, 0) / known.length
+ return top >= mean * 1.8 && top - mean >= 3 ? { hour: hours.indexOf(top), value: top } : null
+}
+
+// Short marks for the timeline's event row, oldest first: repeats of the same kind within a few hours become one.
+export function eventMarks(events, start, end, extra = []) {
+ const marks = []
+ const sorted = [...(events || [])].map((event) => ({ ...event, t: new Date(event.time).getTime() })).filter((event) => event.t >= start && event.t <= end).sort((a, b) => a.t - b.t)
+ for (const event of sorted) {
+ let label
+ let tone = 'plain'
+ const port = event.detail?.match(/(?:tcp|udp)\/(\d+)/)?.[1]
+ if (event.kind === 'collector_stopped') { label = 'Collector offline'; tone = 'plain' } else if (event.kind === 'collector_resumed') continue
+ else if (event.kind === 'alert_opened') { label = event.title; tone = event.severity === 'CRITICAL' ? 'signal' : event.severity === 'WARNING' ? 'warn' : 'plain' } else if (event.kind === 'alert_resolved') continue
+ else if (event.kind === 'reboot') { label = /unclean/i.test(event.detail) ? 'Unclean reboot' : 'Reboot'; tone = /unclean/i.test(event.detail) ? 'warn' : 'plain' } else if (event.kind === 'oom_kill') { label = 'OOM kill'; tone = 'warn' }
+ else if (event.kind === 'port_opened') { label = /loopback/.test(event.detail) ? `${port} opened` : `${port} exposed`; tone = /loopback/.test(event.detail) ? 'plain' : 'warn' } else if (event.kind === 'port_closed') label = `${port} closed`
+ else if (event.kind === 'image_changed') label = 'Images updated'
+ else if (event.kind === 'container_added') label = 'Container added'
+ else if (event.kind === 'container_removed') label = 'Container removed'
+ else if (event.kind === 'firewall_weakened') { label = 'Firewall weaker'; tone = 'warn' } else if (event.kind === 'firewall_changed') label = 'Firewall changed'
+ else if (event.kind === 'kernel_error' || event.kind === 'kernel_fault') { label = 'Kernel error'; tone = 'warn' } else if (event.kind === 'packages_updated') { const count = event.detail?.match(/^(\d+) packages?/)?.[1]; const manager = event.detail?.match(/by (\w+)/)?.[1] || 'package'; label = `${manager} upgrade${count ? ` · ${count} packages` : ''}`; tone = /waiting for reboot/.test(event.detail || '') ? 'warn' : 'plain' } else continue
+ const last = marks[marks.length - 1]
+ // A port that closes and opens again within a few hours was re-bound, which is one thing to show, not many.
+ const group = port && (event.kind === 'port_opened' || event.kind === 'port_closed') ? `port:${port}` : event.kind
+ const same = last && last.group === group && (event.kind !== 'alert_opened' || last.label === label) && event.t - last.t < 6 * 3600000
+ if (same) {
+ last.count += 1
+ if (group.startsWith('port:') && last.kind !== event.kind) { last.label = `${port} re-bound`; last.tone = 'plain' }
+ } else marks.push({ t: event.t, kind: event.kind, group, label, tone, count: 1, detail: event.detail || event.title || '' })
+ }
+ return [...marks, ...extra.filter((mark) => mark.t >= start && mark.t <= end)].sort((a, b) => a.t - b.t)
+}
+
+// The timeline as CSV: one line per point, average and maximum of every metric.
+export function timelineCsv(points, metrics) {
+ const head = ['time', 'samples', ...metrics.flatMap((metric) => [`${metric}_avg`, `${metric}_max`])]
+ const lines = [head.join(',')]
+ for (const point of points) lines.push([point.time, point.samples, ...metrics.flatMap((metric) => [point[metric]?.avg ?? '', point[metric]?.max ?? ''])].join(','))
+ return lines.join('\n')
+}
+
+// A dashed straight line from the latest disk reading to the day it is full: [{ t, value }], capped at ``horizon`` days.
+export function projection(lastTime, lastValue, daysUntilFull, horizonDays = 3650) {
+ if (lastValue == null || daysUntilFull == null || !Number.isFinite(daysUntilFull) || daysUntilFull <= 0) return null
+ const days = Math.min(daysUntilFull, horizonDays)
+ const value = lastValue + ((100 - lastValue) * days) / daysUntilFull
+ return { from: { t: lastTime, value: lastValue }, to: { t: lastTime + days * DAY_MS, value }, full: days === daysUntilFull }
+}
diff --git a/src/frontend/src/ui.jsx b/src/frontend/src/ui.jsx
new file mode 100644
index 0000000..7714195
--- /dev/null
+++ b/src/frontend/src/ui.jsx
@@ -0,0 +1,201 @@
+// 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 { apiRequest } from './api.js'
+import { Icon } from './icons.jsx'
+
+export function useCopy() {
+ const [copied, setCopied] = useState(false)
+ const copy = async (text) => {
+ try { await navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 1500) } catch { setCopied(false) }
+ }
+ return [copied, copy]
+}
+
+// GET ``path`` once (and again on reload()): { data, error, reload, setData }.
+export function useLoaded(path) {
+ const [state, setState] = useState({ data: null, error: '' })
+ const [version, setVersion] = useState(0)
+ useEffect(() => {
+ if (!path) return undefined
+ let active = true
+ apiRequest(path, { method: 'GET' }).then((data) => { if (active) setState({ data, error: '' }) }).catch((error) => { if (active) setState((current) => ({ data: current.data, error: error.message || 'Could not load this.' })) })
+ return () => { active = false }
+ }, [path, version])
+ return { ...state, reload: () => setVersion((value) => value + 1), setData: (data) => setState({ data, error: '' }) }
+}
+
+// Runs an async action and keeps its outcome: [{ busy, error, ok }, run].
+export function useAction() {
+ const [state, setState] = useState({ busy: false, error: '', ok: '' })
+ const run = async (work, done = '') => {
+ setState({ busy: true, error: '', ok: '' })
+ try { const result = await work(); setState({ busy: false, error: '', ok: done }); return result } catch (error) { setState({ busy: false, error: error.message || 'Something went wrong.', ok: '' }); return undefined }
+ }
+ return [state, run]
+}
+
+export function Notice({ tone = 'warn', children }) {
+ if (!children) return null
+ return <div role={tone === 'warn' ? 'alert' : 'status'} className={`rounded-md border px-3.5 py-2.5 text-xs leading-5 ${tone === 'warn' ? 'border-warn/40 text-warn' : tone === 'ok' ? 'border-ok/40 text-ok' : 'border-line text-soft'}`}>{children}</div>
+}
+
+export function Outcome({ state }) {
+ if (state.error) return <p role="alert" className="m-0 text-xs text-warn">{state.error}</p>
+ if (state.ok) return <p role="status" className="m-0 text-xs text-ok">{state.ok}</p>
+ return null
+}
+
+export function Switch({ checked, onChange, disabled = false, label }) {
+ return (
+ <label className={`relative inline-flex shrink-0 ${disabled ? 'opacity-50' : 'cursor-pointer'}`}>
+ <input type="checkbox" role="switch" className="peer sr-only" checked={Boolean(checked)} disabled={disabled} aria-label={label} onChange={(event) => onChange(event.target.checked)} />
+ <span aria-hidden="true" className="relative h-[18px] w-8 rounded-full border border-edge bg-raised transition-colors after:absolute after:left-[2px] after:top-[2px] after:h-3 after:w-3 after:rounded-full after:bg-muted after:transition-all peer-checked:border-paper peer-checked:bg-paper peer-checked:after:left-[16px] peer-checked:after:bg-bg peer-focus-visible:outline peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-paper" />
+ </label>
+ )
+}
+
+export function Check({ checked, onChange, disabled = false, label }) {
+ return <input type="checkbox" className="auth-check disabled:opacity-40" checked={Boolean(checked)} disabled={disabled} aria-label={label} onChange={(event) => onChange(event.target.checked)} />
+}
+
+// A setting on one line: an icon box, a title with a line under it, and something to do on the right.
+export function Row({ icon, title, detail, children, tone }) {
+ return (
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2 px-[18px] py-3.5">
+ {icon !== undefined && <span aria-hidden="true" className="mono flex h-[34px] w-[34px] shrink-0 items-center justify-center rounded-md border border-line bg-bg text-[11px] text-soft">{icon}</span>}
+ <span className="min-w-0 flex-1 basis-56">
+ <span className="block text-[13px] font-medium text-paper">{title}</span>
+ {detail && <span className={`mt-0.5 block text-xs ${tone === 'warn' ? 'text-warn' : 'text-muted'}`}>{detail}</span>}
+ </span>
+ <span className="flex flex-wrap items-center gap-2.5">{children}</span>
+ </div>
+ )
+}
+
+export function Section({ id, title, description, children, aside }) {
+ return (
+ <section id={id} aria-labelledby={`${id}-title`} className="scroll-mt-20 border-b border-line pb-9 last:border-b-0">
+ <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>
+ {aside}
+ </div>
+ <div className="mt-4 space-y-4">{children}</div>
+ </section>
+ )
+}
+
+// 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 }) {
+ const [active, setActive] = useState(sections[0]?.id)
+ useEffect(() => {
+ if (typeof IntersectionObserver === 'undefined') return undefined
+ const observer = new IntersectionObserver((entries) => {
+ const visible = entries.filter((entry) => entry.isIntersecting).sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top)[0]
+ if (visible) setActive(visible.target.id)
+ }, { rootMargin: '-80px 0px -60% 0px' })
+ for (const section of sections) { const element = document.getElementById(section.id); if (element) observer.observe(element) }
+ return () => observer.disconnect()
+ // The ids are fixed for a page; the counts next to them are not.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [sections.map((section) => section.id).join()])
+ const go = (id) => { setActive(id); document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' }) }
+ return (
+ <div className="px-3 pt-5 sm:px-4 lg:px-7 lg:pt-7">
+ <header className="flex flex-wrap items-end justify-between gap-4">
+ <div><h1 className="m-0 text-[21px] font-semibold leading-7 text-paper">{title}</h1><p className="mb-0 mt-1.5 text-[13px] text-soft">{description}</p></div>
+ {aside}
+ </header>
+ <div className="mt-7 grid items-start gap-x-10 gap-y-6 lg:grid-cols-[190px_minmax(0,1fr)]">
+ <nav aria-label={`${title} sections`} className="no-scrollbar -mx-3 flex gap-1 overflow-x-auto px-3 lg:sticky lg:top-20 lg:mx-0 lg:block lg:space-y-0.5 lg:px-0">
+ {sections.map((section) => (
+ <button key={section.id} type="button" aria-current={active === section.id ? 'true' : undefined} onClick={() => go(section.id)} className={`flex h-[31px] shrink-0 items-center justify-between gap-3 rounded-md border-0 px-2.5 text-left text-[13px] font-medium lg:w-full ${active === section.id ? 'bg-raised text-paper' : 'bg-transparent text-soft hover:bg-ink hover:text-paper'}`}>
+ {section.label}{section.count != null && <span className="text-xs font-normal text-muted">{section.count}</span>}
+ </button>
+ ))}
+ {footer && <div className="hidden lg:mt-3 lg:block lg:border-t lg:border-line lg:pt-3">{footer}</div>}
+ </nav>
+ <div className="min-w-0 space-y-9">{children}</div>
+ </div>
+ </div>
+ )
+}
+
+export function Field({ label, hint, children, className = '' }) {
+ return (
+ <label className={`block text-xs text-soft ${className}`}>
+ <span className="mb-1.5 block">{label}</span>
+ {children}
+ {hint && <span className="mt-1.5 block text-[11px] leading-4 text-muted">{hint}</span>}
+ </label>
+ )
+}
+
+// A secret that is shown once: the value, a copy button and what to do with it.
+export function ShownOnce({ value, children }) {
+ const [copied, copy] = useCopy()
+ return (
+ <div className="rounded-md border border-warn/40 px-3.5 py-3">
+ <p className="m-0 text-xs text-warn">{children}</p>
+ <div className="mt-2 flex items-center gap-3 rounded-md border border-line bg-bg py-1.5 pl-3 pr-1.5"><code className="mono min-w-0 flex-1 break-all text-paper">{value}</code><button type="button" className="btn btn-sm" onClick={() => copy(value)}><Icon name={copied ? 'check' : 'copy'} size={13} />{copied ? 'Copied' : 'Copy'}</button></div>
+ </div>
+ )
+}
+
+export const formatDate = (time) => new Date(time).toLocaleDateString([], { day: 'numeric', month: 'short', year: 'numeric' })
+
+// "4 s ago", "2 h ago", "6 d ago", or the date once it is more than a month back.
+export function ago(time) {
+ if (!time) return 'never'
+ const seconds = Math.max(0, (Date.now() - new Date(time).getTime()) / 1000)
+ if (seconds < 45) return seconds < 5 ? 'now' : `${Math.round(seconds)} s ago`
+ if (seconds < 3600) return `${Math.round(seconds / 60)} min ago`
+ if (seconds < 86400) return `${Math.round(seconds / 3600)} h ago`
+ if (seconds < 30 * 86400) return `${Math.round(seconds / 86400)} d ago`
+ return formatDate(time)
+}
+
+// "Firefox 131 on Linux" from a User-Agent header, or the header itself when it isn't a browser we know.
+export function describeBrowser(userAgent) {
+ if (!userAgent) return 'Unknown browser'
+ const browser = userAgent.match(/(Firefox|Edg|OPR|Chrome|Version)\/(\d+)/)
+ const names = { Edg: 'Edge', OPR: 'Opera', Version: 'Safari' }
+ const system = /iPhone/.test(userAgent) ? 'iPhone' : /iPad/.test(userAgent) ? 'iPad' : /Android/.test(userAgent) ? 'Android' : /Windows/.test(userAgent) ? 'Windows' : /Mac OS X/.test(userAgent) ? 'macOS' : /Linux/.test(userAgent) ? 'Linux' : null
+ if (!browser) return userAgent.slice(0, 60)
+ const name = browser[1] === 'Version' && !/Safari/.test(userAgent) ? 'Browser' : names[browser[1]] || browser[1]
+ 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 }) {
+ const [shown, setShown] = useState(false)
+ useEffect(() => {
+ if (!open) { setShown(false); return undefined }
+ const previous = document.activeElement
+ const frame = requestAnimationFrame(() => setShown(true))
+ const onKeyDown = (event) => { if (event.key === 'Escape') onClose() }
+ window.addEventListener('keydown', onKeyDown)
+ document.body.style.overflow = 'hidden'
+ return () => {
+ cancelAnimationFrame(frame)
+ window.removeEventListener('keydown', onKeyDown)
+ document.body.style.overflow = ''
+ if (previous instanceof HTMLElement) previous.focus()
+ }
+ // onClose is a new function each render; the drawer only reacts to opening and closing.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open])
+ if (!open) return null
+ return (
+ <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() }}>
+ <div role="dialog" aria-modal="true" aria-label={title} className={`flex h-full w-full flex-col border-l-2 border-rail bg-bg shadow-[-24px_0_48px_rgba(0,0,0,0.35)] transition-transform duration-200 ease-out motion-reduce:transition-none ${shown ? 'translate-x-0' : 'translate-x-full'}`} style={{ maxWidth: width }}>
+ <header className="flex items-start justify-between gap-4 border-b border-line px-6 pb-4 pt-5">
+ <div><h2 className="m-0 text-[17px] font-semibold text-paper">{title}</h2>{description && <p className="mb-0 mt-1.5 text-[13px] leading-5 text-muted">{description}</p>}</div>
+ <button type="button" autoFocus onClick={onClose} aria-label="Close" className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-edge bg-ink text-soft hover:bg-raised hover:text-paper"><Icon name="close" size={14} /></button>
+ </header>
+ <div className="custom-scroll min-h-0 flex-1 space-y-4 overflow-y-auto px-6 py-5">{children}</div>
+ </div>
+ </div>
+ )
+}
diff --git a/src/frontend/tests/dashboardLogic.test.js b/src/frontend/tests/dashboardLogic.test.js
new file mode 100644
index 0000000..92c96bd
--- /dev/null
+++ b/src/frontend/tests/dashboardLogic.test.js
@@ -0,0 +1,186 @@
+// Tests for the Overview page helpers. Run with `node --test` in this folder.
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import {
+ attentionAction, bootHistory, classifyPort, collapsePaths, collapseRanges, describeEvent, describeGroup, eventStrip, eventsToCsv, firewallLine, forecastMonth, forecastPhrase,
+ formatMegabytes, formatPercent, formatQuiet, formatSpan, formatUsedOfTotal, groupContainers, groupNetworkEvents, groupRepeats, healthChecks, healthVerdict, installCommands,
+ listenerRows, niceCeiling, parsePorts, serverState, serverStateLabel, shortKernel, sortListeners, sortServers, systemLines, trafficRates, CONTAINER_FILTERS, reachablePortSet,
+} from '../src/dashboard/logic.js'
+
+const NOW = new Date('2026-10-13T15:50:00Z').getTime()
+const seen = new Date(NOW - 4000).toISOString()
+
+test('numbers read the way the design writes them', () => {
+ assert.deepEqual([64, 11.7, 0.03, 0.449, 87.04, 0, null].map(formatPercent), ['64%', '11.7%', '0.03%', '0.45%', '87%', '0%', '—'])
+ assert.deepEqual([26, 393.4, 3000.3, 20000].map(formatMegabytes), ['26 MB', '393 MB', '2.93 GB', '19.5 GB'])
+ assert.equal(formatUsedOfTotal(27.2, 31.3), '27.2 / 31.3 GB')
+ assert.equal(formatUsedOfTotal(5427, 7475), '5.3 / 7.3 TB')
+ assert.equal(formatUsedOfTotal(79, 457, ' of '), '79 of 457 GB')
+ assert.deepEqual([4, 720, 7200, 41 * 86400].map(formatSpan), ['4 s', '12 min', '2 h', '41 d'])
+ assert.deepEqual([8040, 6 * 86400, 86400].map(formatQuiet), ['2 h 14 min', '6 days', '1 day'])
+})
+
+test('forecasts are short, and silent when there is no trend', () => {
+ assert.equal(forecastPhrase(180), 'Full in about 6 months')
+ assert.equal(forecastPhrase(180, { short: true }), 'full in ~6 mo')
+ assert.equal(forecastPhrase(6.8 * 365), 'Full in about 6.8 years')
+ assert.equal(forecastPhrase(null), null)
+ assert.equal(forecastPhrase(99999), null)
+ assert.equal(forecastMonth(180, NOW), 'full around April 2027')
+})
+
+test('a server is as bad as the worst thing open on it', () => {
+ const server = (name, open, lastSeen = seen) => ({ hostname: name, alerts_by_severity: open, last_seen_at: lastSeen, check_interval_seconds: 15 })
+ const fleet = [server('nas', {}), server('server', { WARNING: 2 }), server('homelab-01', { CRITICAL: 1, WARNING: 3 }), server('gone', {}, new Date(NOW - 3600e3).toISOString())]
+ assert.deepEqual(fleet.map((item) => serverState(item, NOW)), ['ok', 'warn', 'critical', 'offline'])
+ assert.deepEqual(fleet.map((item) => serverStateLabel(item, NOW)), ['healthy', '2 warnings', '1 critical', 'offline'])
+ assert.deepEqual(sortServers(fleet, NOW).map((item) => item.hostname), ['homelab-01', 'gone', 'server', 'nas'])
+ assert.deepEqual(systemLines({ os_info: 'Debian GNU/Linux 12 (bookworm)', cpu_cores: 8, total_ram_gb: 31.3, ip_address: '10.0.0.21', host: { system_uptime_seconds: 41 * 86400 } }), ['Debian GNU/Linux 12 · 8 cores · 31 GB', '10.0.0.21 · up 41 d'])
+ assert.equal(shortKernel('6.8.0-84-generic'), '6.8.0-84')
+})
+
+test('each alert gets the one action that fits its rule', () => {
+ assert.equal(attentionAction({ severity: 'WARNING', rule_key: 'network:exposed' }).label, 'Review ports')
+ assert.equal(attentionAction({ severity: 'CRITICAL', rule_key: 'container:gitlab:restart_loop' }).label, 'Open diagnosis')
+ assert.equal(attentionAction({ severity: 'WARNING', rule_key: 'host:swap' }).label, 'See trend')
+})
+
+test('published ports are parsed once per host port and runs are collapsed', () => {
+ assert.deepEqual(parsePorts('8080->80/tcp, 8080->80/tcp, 3478->3478/udp, junk'), [{ host: 3478, container: 3478, proto: 'udp' }, { host: 8080, container: 80, proto: 'tcp' }])
+ assert.deepEqual(collapseRanges([9103, 9101, 9102, 9200]), ['9101-9103', '9200'])
+})
+
+const server = {
+ containers: [
+ { name: 'mariadb', image: 'mariadb:11.4', ports: '3306->3306/tcp', status: 'running' },
+ { name: 'nginx-proxy-manager', image: 'jc21/nginx-proxy-manager:2', ports: '80->80/tcp, 443->443/tcp, 81->81/tcp', status: 'running' },
+ { name: 'coturn', image: 'coturn/coturn:4.6', ports: '3478->3478/tcp, 3478->3478/udp', status: 'running' },
+ { name: 'adguard', image: 'adguard/adguardhome', ports: '53->53/tcp', status: 'running' },
+ ],
+ system: { firewall_allowed: [{ proto: 'tcp', port: 22, file: 'nftables' }] },
+ network: {
+ listeners: [
+ { proto: 'tcp', port: 22, scope: 'any', first_seen: '2026-10-01T00:00:00Z' }, { proto: 'tcp', port: 80, scope: 'any', first_seen: '2026-10-01T00:00:00Z' }, { proto: 'tcp', port: 443, scope: 'any', first_seen: '2026-10-01T00:00:00Z' },
+ { proto: 'tcp', port: 81, scope: 'any', first_seen: '2026-10-01T00:00:00Z' }, { proto: 'tcp', port: 3306, scope: 'any', first_seen: '2026-10-01T00:00:00Z' },
+ { proto: 'tcp', port: 3478, scope: 'any', first_seen: '2026-10-01T00:00:00Z' }, { proto: 'udp', port: 3478, scope: 'any', first_seen: '2026-10-01T00:00:00Z' },
+ { proto: 'tcp', port: 53, scope: 'loopback', first_seen: '2026-10-01T00:00:00Z' }, { proto: 'tcp', port: 5173, scope: 'loopback', first_seen: '2026-10-01T00:00:00Z' },
+ ],
+ firewall: [{ name: 'ufw-conf', enabled: false, rules: 0 }, { name: 'nftables', rules: 12 }],
+ },
+}
+
+test('each port names its owner, and databases and admin panels are marked', () => {
+ const rows = listenerRows(server)
+ const byLabel = Object.fromEntries(rows.map((row) => [row.label, row]))
+ assert.deepEqual(Object.keys(byLabel).sort(), ['22', '3306', '3478', '53', '5173', '80, 443', '81'].sort())
+ assert.deepEqual([byLabel['3306'].owner, byLabel['3306'].what, byLabel['3306'].risky, byLabel['3306'].reason], ['mariadb', 'database', true, 'Databases rarely need this'])
+ assert.deepEqual([byLabel['81'].owner, byLabel['81'].what, byLabel['81'].risky], ['nginx-proxy-manager', 'admin UI', true])
+ assert.deepEqual([byLabel['80, 443'].owner, byLabel['80, 443'].risky, byLabel['80, 443'].reason], ['nginx-proxy-manager', false, 'Expected, public entry'])
+ assert.equal(byLabel['3478'].proto, 'tcp+udp')
+ assert.deepEqual([byLabel['22'].owner, byLabel['22'].rule, byLabel['3306'].rule], ['sshd', 'nftables', null])
+ assert.deepEqual([byLabel['53'].reachable, byLabel['53'].risky, byLabel['5173'].owner], [false, false, null])
+ assert.deepEqual(sortListeners(rows).slice(0, 2).map((row) => row.label), ['81', '3306'])
+ assert.equal(firewallLine(server), 'ufw disabled · nftables.conf 12 rules')
+ assert.equal(classifyPort('tcp', 5432, null).risky, true)
+ // With the optional port-owners helper, host processes get their names; a container still wins over docker-proxy.
+ const named = Object.fromEntries(listenerRows({ ...server, system: { ...server.system, listener_owners: [{ proto: 'tcp', port: 5173, process: 'node' }, { proto: 'tcp', port: 3306, process: 'docker-proxy' }, { proto: 'tcp', port: 22, process: 'sshd' }] } }).map((row) => [row.label, row]))
+ assert.deepEqual([named['5173'].owner, named['5173'].ownerKind, named['3306'].owner, named['3306'].ownerKind], ['node', 'host', 'mariadb', 'container'])
+})
+
+test('a container counts as exposed only when another machine can reach one of its ports', () => {
+ const reachable = reachablePortSet(server)
+ assert.deepEqual(server.containers.filter((container) => CONTAINER_FILTERS.exposed(container, reachable)).map((container) => container.name), ['mariadb', 'nginx-proxy-manager', 'coturn'])
+ assert.equal(reachablePortSet({ network: { listeners: [] } }), null)
+})
+
+test('noisy port events collapse into lines that say what actually changed', () => {
+ const at = (hours) => new Date(NOW - hours * 3600e3).toISOString()
+ const events = [
+ { time: at(20), kind: 'port_opened', detail: 'New listener: tcp/8081 (a specific address)' },
+ { time: at(20), kind: 'port_closed', detail: 'Listener closed: tcp/8081 (loopback only)' },
+ { time: at(50), kind: 'port_opened', detail: 'New listener: udp/3479 (all interfaces)' },
+ { time: at(50), kind: 'port_closed', detail: 'Listener closed: udp/3479 (all interfaces)' },
+ { time: at(70), kind: 'port_opened', detail: 'New listener: udp/3479 (all interfaces)' },
+ { time: at(72), kind: 'port_opened', detail: 'New listener: tcp/3478 (all interfaces)' },
+ { time: at(80), kind: 'firewall_weakened', detail: 'ufw was enabled and is now disabled' },
+ ]
+ const lines = groupNetworkEvents(events, NOW)
+ assert.deepEqual(lines.map((line) => [line.age, line.label, line.port, line.tone]), [
+ ['20 h', 'Now exposed', 'tcp/8081', 'warn'], ['2–3 d', 'Re-bound ×3', 'udp/3479', 'plain'], ['3 d', 'Now exposed', 'tcp/3478', 'warn'], ['3 d', 'Firewall weaker', null, 'warn'],
+ ])
+ assert.equal(lines[0].text, 'moved from loopback to a specific address')
+})
+
+test('containers group by compose project, busiest first, standalone last', () => {
+ const containers = [
+ { name: 'collabora', project: null, cpu_pct: 0.4, memory_used_mb: 393, status: 'running' },
+ { name: 'gitlab-runner', project: 'gitlab', cpu_pct: 0.03, memory_used_mb: 26, status: 'running' },
+ { name: 'gitlab', project: 'gitlab', cpu_pct: 58.3, memory_used_mb: 3000, status: 'running' },
+ { name: 'redis', project: 'infradeck', cpu_pct: 1, memory_used_mb: 20, status: 'exited' },
+ { name: 'backend', project: 'infradeck', cpu_pct: 5, memory_used_mb: 146, status: 'running' },
+ ]
+ const groups = groupContainers(containers)
+ assert.deepEqual(groups.map((group) => [group.name, group.count, group.problems]), [['gitlab', 2, 0], ['infradeck', 2, 1], ['Standalone', 1, 0]])
+ assert.deepEqual(groups[0].containers.map((container) => container.name), ['gitlab', 'gitlab-runner'])
+ assert.deepEqual(groups[1].containers.map((container) => container.name), ['redis', 'backend']) // the stopped one first
+ assert.equal(Math.round(groups[0].memoryMb), 3026)
+ assert.deepEqual(groupContainers(containers, { grouped: false })[0].count, 5)
+ assert.deepEqual(collapsePaths('/srv/gitlab/config, /srv/gitlab/logs, /srv/gitlab/data, web_cache, /etc/x'), ['/srv/gitlab/{config,logs,data}', 'web_cache', '/etc/x'])
+})
+
+test('health checks give plain verdicts and count what needs a look', () => {
+ const checks = healthChecks({
+ ...server,
+ host: { reboot_required: true, system_uptime_seconds: 10 * 86400, last_shutdown: 'clean', ntp_synced: true, oom_kill_total: 0, kernel_tainted: 0, swap_pct: 0 },
+ system: { reboot_kernel: '6.8.0-85-generic', time_service: 'chrony' }, system_events: [],
+ }, NOW)
+ const text = Object.fromEntries(checks.map((check) => [check.label, [check.text, check.tone]]))
+ assert.deepEqual(text.Firewall, ['ufw off · 6 ports exposed', 'warn'])
+ assert.deepEqual(text.Updates, ['Reboot needed for 6.8.0-85', 'warn'])
+ assert.deepEqual(text.Booted, ['10 d ago · clean shutdown', 'ok'])
+ assert.deepEqual(text.Clock, ['Synced (chrony)', 'ok'])
+ assert.deepEqual(text['OOM kills'], ['None in 24 h', 'ok'])
+ assert.deepEqual(text['Kernel log'], ['Clean', 'ok'])
+ assert.deepEqual(text.Internet, ['Not checked', 'unknown'])
+ assert.equal(healthVerdict(checks), '2 to look at')
+ assert.equal(healthVerdict(checks.filter((check) => check.tone !== 'warn')), 'all passing')
+})
+
+test('traffic is the change between check-ins, with a gap across a reboot', () => {
+ const samples = [{ time: '2026-10-13T15:00:00Z', net_recv_mb: 100, net_sent_mb: 50 }, { time: '2026-10-13T15:00:10Z', net_recv_mb: 121, net_sent_mb: 56 }, { time: '2026-10-13T15:00:20Z', net_recv_mb: 3, net_sent_mb: 1 }]
+ assert.deepEqual(trafficRates(samples).map((point) => [point.in, point.out]), [[2.1, 0.6], [null, null]])
+ assert.deepEqual([0.4, 2.1, 37, 5.2, 0].map(niceCeiling), [0.4, 4, 40, 6, 1])
+ assert.deepEqual(bootHistory([{ kind: 'reboot', time: 'b', detail: 'The host rebooted after a clean shutdown' }, { kind: 'oom_kill', time: 'x', detail: '' }, { kind: 'reboot', time: 'a', detail: 'The host restarted after an unclean shutdown (crash)' }]), [{ time: 'a', unclean: true }, { time: 'b', unclean: false }])
+})
+
+test('the timeline folds repeats, keeps alerts apart and draws the week', () => {
+ const at = (hours) => new Date(NOW - hours * 3600e3).toISOString()
+ const events = [
+ { time: at(1), source: 'alert', kind: 'alert_resolved', severity: 'WARNING', title: 'Memory usage on server is 93%', duration_seconds: 1080 },
+ { time: at(2), source: 'alert', kind: 'alert_opened', severity: 'WARNING', title: 'Memory usage on server is 93%', resolved: true },
+ { time: '2026-10-13T03:00:40Z', source: 'container', kind: 'image_changed', detail: 'Container jellyfin now runs a different image build (a to b)' },
+ { time: '2026-10-13T03:00:20Z', source: 'container', kind: 'image_changed', detail: 'Container collabora now runs a different image build (a to b)' },
+ { time: '2026-10-10T06:32:00Z', source: 'collector', kind: 'collector_stopped', severity: 'CRITICAL', title: 'Server server is offline' },
+ ]
+ const groups = groupRepeats(events)
+ assert.deepEqual(groups.map((group) => group.events.length), [1, 1, 2, 1])
+ const folded = describeGroup(groups[2])
+ assert.deepEqual([folded.source, folded.lead, folded.text], ['Containers ×2', 'jellyfin, collabora', 'now run a different image build'])
+ assert.deepEqual([describeEvent(events[0]).source, describeEvent(events[0]).text], ['Alert resolved', 'cleared after 18 min'])
+ assert.equal(describeEvent(events[4]).tag.text, 'critical')
+ const strip = eventStrip(events, 7, NOW)
+ assert.equal(strip.length, 7)
+ assert.equal(strip.at(-1).label, 'Today')
+ assert.equal(strip.reduce((sum, day) => sum + day.count, 0), 5)
+ assert.ok(strip.some((day) => day.bars.some((bar) => bar.tone === 'signal')))
+ assert.equal(eventsToCsv(events).split('\n').length, 6)
+})
+
+test('the install commands carry the token and the chosen name three ways', () => {
+ const commands = installCommands({ url: 'https://deck.home.lan/api', token: 'jt_abc', name: 'homelab-01', collectorImage: 'ghcr.io/x/collector@sha256:1', proxyImage: 'ghcr.io/x/proxy@sha256:2' })
+ assert.deepEqual(Object.keys(commands), ['docker run', 'compose', 'systemd'])
+ for (const command of Object.values(commands)) {
+ assert.ok(command.includes('jt_abc') && command.includes('homelab-01') && command.includes('ghcr.io/x/proxy@sha256:2'))
+ }
+ assert.ok(!installCommands({ url: 'u', token: 't', name: '', collectorImage: 'c', proxyImage: 'p' }).compose.includes('HOMELAB_SERVER_NAME'))
+})
diff --git a/src/frontend/tests/fleetLogic.test.js b/src/frontend/tests/fleetLogic.test.js
index bd505dd..298e8e9 100644
--- a/src/frontend/tests/fleetLogic.test.js
+++ b/src/frontend/tests/fleetLogic.test.js
@@ -33,8 +33,8 @@ test('top containers rank across servers, skip unknown values and honour the cou
})
test('servers are ranked by disk usage and coloured by the thresholds; servers without data are left out', () => {
- assert.deepEqual(serversByDisk(servers).map((row) => [row.label, row.value, row.color]), [['web01', 97, '#f87171'], ['nas', 91, '#fbbf24']])
- assert.equal(serversByDisk([{ hostname: 'x', host: { disk_usage_pct: 40 } }])[0].color, '#7dd3fc')
+ assert.deepEqual(serversByDisk(servers).map((row) => [row.label, row.value, row.color]), [['web01', 97, '#FF5A1F'], ['nas', 91, '#E2B04A']])
+ assert.equal(serversByDisk([{ hostname: 'x', host: { disk_usage_pct: 40 } }])[0].color, '#D0CEC8')
})
test('a server is online while it keeps reporting', () => {
@@ -46,7 +46,7 @@ test('a server is online while it keeps reporting', () => {
test('availability rows skip unknown servers, put the worst first and colour by how bad it is', () => {
const rows = availabilityRows([{ hostname: 'a', percent: 100, checkins: 10, expected: 10 }, { hostname: 'b', percent: 96.5, checkins: 9, expected: 10 }, { hostname: 'c', percent: null, checkins: 0, expected: 5 }, { hostname: 'd', percent: 80, checkins: 8, expected: 10 }])
- assert.deepEqual(rows.map((row) => [row.label, row.color]), [['d', '#f87171'], ['b', '#fbbf24'], ['a', '#34d399']])
+ assert.deepEqual(rows.map((row) => [row.label, row.color]), [['d', '#FF5A1F'], ['b', '#E2B04A'], ['a', '#6DBE8F']])
})
test('durations read naturally', () => {
diff --git a/src/frontend/tests/statisticsLogic.test.js b/src/frontend/tests/statisticsLogic.test.js
new file mode 100644
index 0000000..41b40b3
--- /dev/null
+++ b/src/frontend/tests/statisticsLogic.test.js
@@ -0,0 +1,104 @@
+// Tests for the Statistics page helpers. Run with `node --test` in this folder.
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { busiestAt, busiestHour, deltaPoints, eventMarks, findGaps, findings, percentile, projection, summarize, timeAtLevels, timelineCsv } from '../src/statistics/logic.js'
+
+const HOUR = 3600000
+const START = new Date(2026, 9, 6, 0, 0).getTime() // Tue 6 Oct, local time
+const half = (index) => START + index * 1800000
+const week = (value) => Array.from({ length: 336 }, (_, index) => ({ t: half(index), samples: 120, ...value(index, new Date(half(index))) }))
+
+test('summary figures carry the moment of the peak', () => {
+ const series = [{ t: 1, avg: 10, max: 20, samples: 1 }, { t: 2, avg: 30, max: 100, samples: 3 }, { t: 3, avg: null, max: null, samples: 1 }]
+ assert.deepEqual(summarize(series), { average: 25, peak: 100, peakAt: 2, last: null })
+ assert.equal(deltaPoints(9.7, 8.5), '+1.2 pts')
+ assert.equal(deltaPoints(50, 52.1), '−2.1 pts')
+ assert.equal(deltaPoints(5, null), null)
+})
+
+test('a hole between points is a gap; history starting late is not', () => {
+ const times = [half(4), half(5), half(6), half(17), half(18)]
+ assert.deepEqual(findGaps(times, 1800, half(18) + 1), [{ from: half(7), to: half(17) }])
+ assert.deepEqual(findGaps(times, 1800, half(30)), [{ from: half(7), to: half(17) }, { from: half(19), to: half(30) }])
+ assert.deepEqual(findGaps([], 1800, half(30)), [])
+})
+
+test('the busiest container is looked up by the period that covers a moment', () => {
+ const lookup = { bucketSeconds: 3600, points: [{ t: START, name: 'web', cpu: 5 }, { t: START + 3 * HOUR, name: 'gitlab', cpu: 94 }] }
+ assert.equal(busiestAt(lookup, START + 3.5 * HOUR).name, 'gitlab')
+ assert.equal(busiestAt(lookup, START + 2 * HOUR), null) // nothing reported for that hour
+ assert.equal(busiestAt(null, START), null)
+})
+
+test('findings name swap growth, a nightly spike and a gap, in plain words', () => {
+ const cpu = week((index, date) => (date.getHours() === 3 && date.getMinutes() === 0 ? { avg: 31, max: 100 } : { avg: 9, max: 22 })).filter((_, index) => index < 200 || index > 211)
+ const ram = week(() => ({ avg: 52, max: 59 }))
+ const swap = week((index) => ({ avg: index < 250 ? 0 : (index - 250) * 0.19, max: index < 250 ? 0 : (index - 250) * 0.19 }))
+ const load = week(() => ({ avg: 0.4, max: 2.1 }))
+ const busiest = { bucketSeconds: 3600, points: cpu.filter((point) => new Date(point.t).getHours() === 3).map((point) => ({ t: point.t - (point.t % HOUR), name: 'gitlab', cpu: 94 })) }
+ const result = findings({ cpu, ram, swap, load, cores: 4, swapTotalGb: 16, bucketSeconds: 1800, gaps: findGaps(cpu.map((point) => point.t), 1800, half(335)), events: [], busiest, containers: [{ name: 'gitlab', swap_mb: 1126 }, { name: 'web', swap_mb: 3 }], disks: [] })
+
+ assert.deepEqual(result.map((finding) => finding.key), ['swap', 'spike', 'gap'])
+ assert.equal(result[0].title, 'Swap keeps growing while memory has room.')
+ assert.match(result[0].text, /^Swap went from 0 GB to 2\.6 GB since Sun 11 Oct, but RAM never passed 59%\. .* gitlab holds the most swap \(1\.10 GB\)\.$/)
+ assert.equal(result[0].at, half(255)) // the last moment it was still within a point of its lowest
+ assert.equal(result[1].title, 'CPU hits 100% at 03:00 every night.')
+ assert.match(result[1].text, /^Seen on 7 of 7 days, and gitlab is the busiest container each time\. Average CPU stays around 9% the rest of the day\.$/)
+ assert.equal(result[1].marks.length, 7)
+ assert.equal(result[1].marks[0].label, 'nightly gitlab peak')
+ // With the check-ins still around, the spikes get a length.
+ const spikes = cpu.filter((point) => new Date(point.t).getHours() === 3 && new Date(point.t).getMinutes() === 0).map((point, index) => ({ t: point.t + 60000, seconds: index % 2 ? 14 * 60 : 8 * 60 }))
+ const timed = findings({ cpu, ram, swap, load, cores: 4, bucketSeconds: 1800, gaps: [], events: [], busiest, spikes, disks: [] }).find((finding) => finding.key === 'spike')
+ assert.match(timed.text, /^Spikes last 8 to 14 minutes and gitlab is the busiest container each time\. /)
+ assert.equal(result[2].title, 'No data for 6 h on Sat 10 Oct.')
+ assert.match(result[2].text, /^Nothing was reported from 04:00 to 10:00\. No reboot was recorded/)
+})
+
+test('a quiet range has no findings, and a full disk outranks everything', () => {
+ const flat = week(() => ({ avg: 5, max: 9 }))
+ const quiet = { cpu: flat, ram: flat, swap: week(() => ({ avg: 0, max: 0 })), load: week(() => ({ avg: 0.2, max: 0.5 })), cores: 4, bucketSeconds: 1800, gaps: [], events: [], disks: [] }
+ assert.deepEqual(findings(quiet), [])
+ const busy = findings({ ...quiet, ram: week(() => ({ avg: 80, max: 96 })), load: week(() => ({ avg: 5, max: 7 })), disks: [{ mount: '/', days: 12, usedPct: 91 }] })
+ assert.deepEqual(busy.map((finding) => finding.key), ['disk', 'load', 'memory'])
+ assert.equal(busy[0].title, '/ fills up in about 12 days.')
+})
+
+test('time at each level adds up and gets one sentence', () => {
+ const series = [...Array.from({ length: 63 }, () => ({ avg: 5, samples: 1 })), ...Array.from({ length: 35 }, () => ({ avg: 15, samples: 1 })), { avg: 25, samples: 1 }, { avg: 100, samples: 1 }]
+ const { bands, sentence } = timeAtLevels(series)
+ assert.deepEqual(bands.map((band) => [band.label, band.share]), [['0–10%', 63], ['10–20%', 35], ['20–30%', 1], ['30–50%', 0], ['50–80%', 0], ['80–100%', 1]])
+ assert.equal(sentence, "98% of the time the CPU was under 20%. There's headroom for more services on this machine.")
+ assert.match(timeAtLevels([{ avg: 95, samples: 1 }], 'memory').sentence, /above 80%/)
+ assert.equal(timeAtLevels([]).sentence, '')
+})
+
+test('percentiles, the busiest hour and the disk projection', () => {
+ assert.equal(percentile([12, 10, 31, 14, 11, null], 50), 12)
+ assert.equal(percentile([12, 10, 31, 14, 11], 95), 31)
+ assert.equal(percentile([], 50), null)
+ const grid = Array.from({ length: 7 }, () => Array.from({ length: 24 }, (_, hour) => (hour === 3 ? 31 : 6)))
+ assert.deepEqual(busiestHour(grid), { hour: 3, value: 31 })
+ assert.equal(busiestHour(Array.from({ length: 7 }, () => Array(24).fill(6))), null)
+ assert.deepEqual(projection(1000, 20, 80), { from: { t: 1000, value: 20 }, to: { t: 1000 + 80 * 86400000, value: 100 }, full: true })
+ assert.equal(projection(1000, 20, 8000).full, false)
+ assert.equal(projection(1000, 20, null), null)
+})
+
+test('event marks fold repeats and skip what is only noise on a chart', () => {
+ const at = (hours) => new Date(START + hours * HOUR).toISOString()
+ const events = [
+ { time: at(3), kind: 'image_changed', detail: 'Container a now runs a different image build' }, { time: at(3.1), kind: 'image_changed', detail: 'Container b now runs a different image build' },
+ { time: at(30), kind: 'collector_stopped', severity: 'CRITICAL', title: 'Server server is offline' }, { time: at(35), kind: 'collector_resumed', title: 'Server server is offline' },
+ { time: at(60), kind: 'port_opened', detail: 'New listener: tcp/8081 (a specific address)' }, { time: at(900), kind: 'reboot', detail: 'The host rebooted' },
+ { time: at(70), kind: 'packages_updated', detail: '41 packages updated by apt, kernel 6.8.0-85-generic waiting for reboot' },
+ { time: at(80), kind: 'port_opened', detail: 'New listener: udp/3479 (all interfaces)' }, { time: at(81), kind: 'port_closed', detail: 'Listener closed: udp/3479 (all interfaces)' }, { time: at(82), kind: 'port_opened', detail: 'New listener: udp/3479 (all interfaces)' },
+ ]
+ const marks = eventMarks(events, START, START + 7 * 24 * HOUR)
+ assert.deepEqual(marks.map((mark) => [mark.label, mark.count, mark.tone]), [['Images updated', 2, 'plain'], ['Collector offline', 1, 'plain'], ['8081 exposed', 1, 'warn'], ['apt upgrade · 41 packages', 1, 'warn'], ['3479 re-bound', 3, 'plain']])
+ assert.equal(eventMarks([], START, START + HOUR, [{ t: START + 60000, label: 'nightly peak' }, { t: START - 1, label: 'outside' }]).length, 1)
+})
+
+test('the timeline exports as CSV', () => {
+ const csv = timelineCsv([{ time: '2026-10-13T03:00:00+00:00', samples: 120, cpu: { avg: 31, max: 100 }, ram: null }], ['cpu', 'ram'])
+ assert.equal(csv, 'time,samples,cpu_avg,cpu_max,ram_avg,ram_max\n2026-10-13T03:00:00+00:00,120,31,100,,')
+})
diff --git a/tests/accounts/test_account_security.py b/tests/accounts/test_account_security.py
index d024441..7cf0246 100644
--- a/tests/accounts/test_account_security.py
+++ b/tests/accounts/test_account_security.py
@@ -951,3 +951,76 @@ def test_the_cleanup_of_old_session_data_never_stops_the_backend_from_starting(a
raise ConnectionError("redis is down")
assert auth.purge_legacy_session_keys(Broken()) == 0
+
+
+# --- staying signed in, and what the sign-in page may know ----------------------------------------------
+
+def _session_ttls(app):
+ return sorted(ttl for key, ttl in app.redis.ttls.items() if key.startswith("homelab:session:"))
+
+
+def _cookie_max_age(response):
+ header = next(value for name, value in response.headers.multi_items() if name == "set-cookie" and value.startswith(COOKIE))
+ return int(header.split("Max-Age=")[1].split(";")[0])
+
+
+def test_a_session_lasts_a_day_unless_you_ask_to_stay_signed_in(app):
+ plain = _login(TestClient(main.app), "[email protected]")
+ assert _session_ttls(app) == [auth.SESSION_TTL_SECONDS] and _cookie_max_age(plain) == auth.SESSION_TTL_SECONDS
+
+ kept = TestClient(main.app).post("/auth/login", json={"email": "[email protected]", "password": PASSWORD, "remember": True})
+ assert _session_ttls(app) == [auth.SESSION_TTL_SECONDS, auth.REMEMBER_SESSION_TTL_SECONDS] and _cookie_max_age(kept) == auth.REMEMBER_SESSION_TTL_SECONDS
+ assert auth.REMEMBER_SESSION_TTL_SECONDS >= 30 * 24 * 3600
+ assert any("staying signed in for 30 days" in message for message in _audit(app))
+ # Both still show up in the list of sessions, so the long one can be signed out.
+ assert len(auth.list_user_sessions(app.redis, 2, None)) == 2
+
+
+def test_a_limited_setup_session_is_short_even_when_staying_signed_in_was_ticked(app):
+ response = TestClient(main.app).post("/auth/login", json={"email": "[email protected]", "password": PASSWORD, "remember": True})
+
+ assert response.json()["setup_required"] is True
+ assert _session_ttls(app) == [auth.ENROLLMENT_SESSION_TTL_SECONDS] and _cookie_max_age(response) == auth.ENROLLMENT_SESSION_TTL_SECONDS
+
+
+def test_the_choice_to_stay_signed_in_is_kept_across_the_two_factor_step_on_the_server(app):
+ secret, _codes = _enroll(app, _signed_in())
+ app.redis.ttls.clear()
+ client = TestClient(main.app)
+ first = client.post("/auth/login", json={"email": "[email protected]", "password": PASSWORD, "remember": True}).json()
+ # The code step has no say in it: an extra field there is ignored.
+ second = client.post("/auth/login/2fa", json={"pending_token": first["pending_token"], "code": _code(app, secret, 30), "remember": False})
+ assert second.status_code == 200 and _cookie_max_age(second) == auth.REMEMBER_SESSION_TTL_SECONDS
+
+ app.redis.ttls.clear()
+ client = TestClient(main.app)
+ first = client.post("/auth/login", json={"email": "[email protected]", "password": PASSWORD}).json()
+ second = client.post("/auth/login/2fa", json={"pending_token": first["pending_token"], "code": _code(app, secret, 30), "remember": True})
+ assert second.status_code == 200 and _cookie_max_age(second) == auth.SESSION_TTL_SECONDS
+ assert auth.pending_two_factor_remember(app.redis, "x" * 30) is False and auth.pending_two_factor_remember(app.redis, None) is False
+
+
+def test_the_sign_in_page_learns_the_installs_name_and_nothing_private(app):
+ config = TestClient(main.app).get("/auth/config").json()
+
+ assert config == {"registration_enabled": False, "bootstrap_required": False, "instance_name": "admin's homelab", "server_count": 0, "version": main.APP_VERSION}
+
+
+def test_an_admin_can_name_the_install_and_reset_the_name(app):
+ admin = _signed_in()
+ _enroll(app, admin)
+
+ assert admin.put("/admin/settings", json={"instance_name": " Basement rack "}).json()["instance_name"] == "Basement rack"
+ assert TestClient(main.app).get("/auth/config").json()["instance_name"] == "Basement rack"
+ assert admin.get("/monitoring/overview").json()["instance_name"] == "Basement rack"
+ assert admin.put("/admin/settings", json={"instance_name": "x" * 61}).status_code == 400
+ assert admin.put("/admin/settings", json={"instance_name": ""}).json()["instance_name"] == "admin's homelab"
+ assert _signed_in("[email protected]").put("/admin/settings", json={"instance_name": "mine"}).status_code == 403
+
+
+def test_a_new_install_has_no_name_yet(app):
+ app.db.query(User).delete()
+ app.db.commit()
+
+ config = TestClient(main.app).get("/auth/config").json()
+ assert config["bootstrap_required"] is True and config["instance_name"] is None
diff --git a/tests/accounts/test_admin.py b/tests/accounts/test_admin.py
index ff07a05..ea92a25 100644
--- a/tests/accounts/test_admin.py
+++ b/tests/accounts/test_admin.py
@@ -154,7 +154,7 @@ def test_admin_can_turn_agent_chat_off_and_on(fleet, monkeypatch):
result = main.update_admin_settings(main.AdminSettingsRequest(agent_chat_enabled=False), session_id="s", db=fleet)
- assert result == {"metrics_retention_days": main.DEFAULT_METRICS_RETENTION_DAYS, "agent_chat_enabled": False, "alert_thresholds": rules.DEFAULT_THRESHOLDS, "mount_thresholds": {}, "require_2fa_for_admins": True, "secrets_configured": False}
+ assert result == {"instance_name": main.get_instance_name(fleet), "metrics_retention_days": main.DEFAULT_METRICS_RETENTION_DAYS, "agent_chat_enabled": False, "alert_thresholds": rules.DEFAULT_THRESHOLDS, "mount_thresholds": {}, "require_2fa_for_admins": True, "secrets_configured": False, "require_2fa_for_everyone": False, "disabled_rules": []}
_login_as(monkeypatch, 2)
assert main.agent_config(session_id="s", db=fleet) == {"chat_enabled": False}
diff --git a/tests/accounts/test_auth_backend.py b/tests/accounts/test_auth_backend.py
index 5df101d..0049bea 100644
--- a/tests/accounts/test_auth_backend.py
+++ b/tests/accounts/test_auth_backend.py
@@ -98,10 +98,12 @@ def test_registration_closed_still_allows_first_account(monkeypatch):
session = sessionmaker(bind=engine)()
monkeypatch.setattr(main, "ALLOW_REGISTRATION", False)
- assert main.auth_config(db=session) == {"registration_enabled": True, "bootstrap_required": True}
+ public = {"server_count": 0, "version": main.APP_VERSION}
+ assert main.auth_config(db=session) == {"registration_enabled": True, "bootstrap_required": True, "instance_name": None, **public}
session.add(User(name="Owner", email="[email protected]", password_hash="x"))
session.commit()
- assert main.auth_config(db=session) == {"registration_enabled": False, "bootstrap_required": False}
+ # The first account is not an admin here, so there is nobody to name the install after.
+ assert main.auth_config(db=session) == {"registration_enabled": False, "bootstrap_required": False, "instance_name": None, **public}
with pytest.raises(HTTPException) as exc:
main.auth_register(main.RegisterRequest(name="Stranger", email="[email protected]", password="correct-horse-battery-staple"), request=None, response=None, db=session)
diff --git a/tests/accounts/test_new_pages.py b/tests/accounts/test_new_pages.py
new file mode 100644
index 0000000..2f376a0
--- /dev/null
+++ b/tests/accounts/test_new_pages.py
@@ -0,0 +1,316 @@
+"""What the Agent, Account and Admin pages rest on: incidents you can act on, API tokens with a narrow reach,
+notification channels that can't be pointed inwards, invitations, rule switches and two-factor for everyone."""
+import os
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+
+os.environ.setdefault("DATABASE_URL", "sqlite://")
+os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")
+
+import bcrypt
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.pool import StaticPool
+from starlette.testclient import TestClient
+
+from src.backend import auth, incidents, main, notify, secrets_box
+from src.backend.models import ApiToken, AuditLog, Base, ContainerMetric, HostMetric, IncidentAlert, Invite, NotificationChannel, Server, User
+from tests.fakes import FakeRedis
+
+PASSWORD = "correct-horse-battery-staple"
+NOW = datetime.now(timezone.utc)
+
+
[email protected](autouse=True)
+def fast_bcrypt(monkeypatch):
+ real = bcrypt.gensalt
+ monkeypatch.setattr(bcrypt, "gensalt", lambda rounds=12, prefix=b"2b": real(rounds=4, prefix=prefix))
+
+
+def app(monkeypatch):
+ monkeypatch.setenv("SECRETS_KEY", secrets_box.generate_key())
+ redis = FakeRedis()
+ monkeypatch.setattr(main, "redis_client", redis)
+ monkeypatch.setattr(main, "SESSION_COOKIE_SECURE", False)
+ engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
+ Base.metadata.create_all(engine)
+ db = sessionmaker(bind=engine)()
+ password_hash = auth.hash_password(PASSWORD)
+ db.add_all([User(id=1, name="Karlo Owner", email="[email protected]", password_hash=password_hash, role="admin", totp_enabled=True),
+ User(id=2, name="Ana Admin", email="[email protected]", password_hash=password_hash, role="admin", totp_enabled=True),
+ User(id=3, name="Vid Viewer", email="[email protected]", password_hash=password_hash, role="user")])
+ db.add(Server(id=1, owner_id=1, hostname="alpha", cpu_cores=4, total_ram_gb=16.0, check_interval_seconds=60, last_seen_at=NOW))
+ db.add(IncidentAlert(id=42, server_id=1, severity="CRITICAL", title="Container gitlab is in a restart loop", description="gitlab restarted 6 times.", status="active", rule_key="container:gitlab:restart_loop", created_at=NOW - timedelta(minutes=12)))
+ db.add(IncidentAlert(id=43, server_id=1, severity="WARNING", title="Swap usage on alpha is 60%", description="swap", status="active", rule_key="host:swap", created_at=NOW - timedelta(hours=2)))
+ for index in range(30):
+ moment = NOW - timedelta(minutes=30 - index)
+ db.add(HostMetric(server_id=1, time=moment, cpu_utilization_pct=10, ram_pct=50, swap_pct=index * 2.0, load_1m=0.4))
+ db.add(ContainerMetric(server_id=1, container_id="g" * 64, name="gitlab", status="running", restart_count=index // 5, memory_used_mb=3900 if index % 5 == 4 else 2000, memory_limit_mb=4096, exit_code=137, oom_killed=index > 20, time=moment))
+ db.commit()
+ main.app.dependency_overrides[main.get_db] = lambda: db
+ yield SimpleNamespace(db=db, redis=redis)
+ main.app.dependency_overrides.clear()
+
+
+def signed_in(app, user_id):
+ """A browser session for one of the seeded accounts (skipping the two-factor step, which has its own tests)."""
+ client = TestClient(main.app)
+ session_id, _public = auth.create_session(app.redis, app.db.get(User, user_id))
+ client.cookies.set("homie_session", session_id)
+ return client
+
+
+# --- incidents ---------------------------------------------------------------------------------------
+
+def test_the_inbox_lists_open_incidents_most_severe_first_and_says_who_may_act(app):
+ inbox = signed_in(app, 3).get("/incidents").json()
+
+ assert [item["reference"] for item in inbox["open"]] == ["INC-0042", "INC-0043"] and inbox["can_act"] is False
+ assert [item["state"] for item in inbox["open"]] == ["diagnosed", "watching"] and inbox["muted"] == [] and inbox["resolved"] == []
+ assert signed_in(app, 1).get("/incidents").json()["can_act"] is True
+
+
+def test_a_diagnosis_is_built_from_the_stored_samples(app):
+ incident = signed_in(app, 3).get("/incidents/42").json()
+ found = incident["diagnosis"]
+
+ assert found["container"] == "gitlab" and found["evidence"]["limit"] == 4096 and len(found["evidence"]["marks"]) == 5
+ assert [signal["ok"] for signal in found["signals"]] == [True, True, True] and found["agreeing"] == 3
+ assert found["signals"][0]["text"] == "The restart count rose by 5 in this window."
+ assert found["steps"][0]["recommended"] and found["steps"][0]["command"] == "mem_limit: 6g" and found["steps"][-1]["title"] == "Confirm it's fixed"
+ assert found["note"] == "limit is 4.0 GB, peak 3.8 GB"
+ assert found["timeline"][-1]["text"].startswith("Incident opened")
+ swap = signed_in(app, 3).get("/incidents/43").json()["diagnosis"]
+ assert swap["evidence"]["title"] == "swap in use" and swap["evidence"]["series"][-1]["value"] == 58.0
+ assert signed_in(app, 3).get("/incidents/999").status_code == 404
+
+
+def test_a_container_name_never_becomes_part_of_a_command_unless_it_is_plain(app):
+ assert incidents._command_name("gitlab-ce_1") == "gitlab-ce_1"
+ assert incidents._command_name("x; rm -rf /") == "<container>" and incidents._command_name("$(id)") == "<container>" and incidents._command_name(None) == "<container>"
+
+
+def test_only_admins_acknowledge_mute_and_resolve_and_each_is_logged(app):
+ viewer, owner = signed_in(app, 3), signed_in(app, 1)
+ for action in ("acknowledge", "resolve", "mute", "unmute"):
+ assert viewer.post(f"/incidents/42/{action}").status_code == 403
+
+ assert owner.post("/incidents/42/acknowledge").json()["acknowledged_by"] == "Karlo Owner"
+ assert owner.post("/incidents/42/mute", json={"minutes": 60}).json()["muted_until"] is not None
+ inbox = owner.get("/incidents").json()
+ assert [item["id"] for item in inbox["open"]] == [43] and [item["id"] for item in inbox["muted"]] == [42]
+ overview = owner.get("/monitoring/overview").json()
+ assert overview["alerts_by_severity"] == {"WARNING": 1} and [alert["id"] for alert in overview["alerts"]] == [43] # muted: out of the count and the list
+ owner.post("/incidents/42/unmute")
+ resolved = owner.post("/incidents/42/resolve").json()
+ assert resolved["status"] == "resolved" and resolved["resolution"] == "Marked resolved by Karlo Owner"
+ assert owner.post("/incidents/42/resolve").status_code == 409
+ assert [row.message for row in app.db.query(AuditLog).filter(AuditLog.source == "incidents")][0].startswith("Acknowledged INC-0042")
+ assert owner.post("/incidents/42/mute", json={"minutes": 999999}).status_code == 422
+
+
+def test_the_overview_carries_the_agents_note_for_each_incident(app):
+ alerts = {alert["id"]: alert for alert in signed_in(app, 3).get("/monitoring/overview").json()["alerts"]}
+ assert alerts[42]["agent_note"] == "limit is 4.0 GB, peak 3.8 GB" and alerts[42]["reference"] == "INC-0042"
+
+
+# --- API tokens --------------------------------------------------------------------------------------
+
+def make_token(app, user_id, scope="read", **extra):
+ return signed_in(app, user_id).post("/account/tokens", json={"name": "script", "scope": scope, **extra})
+
+
+def with_token(token):
+ client = TestClient(main.app)
+ client.headers["Authorization"] = f"Bearer {token}"
+ return client
+
+
+def test_a_token_is_shown_once_stored_as_a_hash_and_reads_but_does_not_write(app):
+ created = make_token(app, 3).json()
+ token = created["token"]
+
+ assert token.startswith("idk_r_") and created["hint"] == token[-4:]
+ assert app.db.query(ApiToken).one().token_hash == main._hash_secret(token) and token not in str(signed_in(app, 3).get("/account").json())
+ client = with_token(token)
+ assert client.get("/monitoring/overview").status_code == 200 and client.get("/incidents").status_code == 200
+ assert client.post("/incidents/42/acknowledge").status_code == 403
+ assert app.db.query(ApiToken).one().last_used_at is not None
+
+
[email protected]("method, path", [("get", "/account"), ("post", "/account/tokens"), ("get", "/admin/users"), ("get", "/admin/settings"), ("get", "/auth/sessions"), ("get", "/conversations"), ("delete", "/monitoring/servers/1"), ("post", "/monitoring/join-tokens"), ("patch", "/monitoring/servers/1")])
+def test_no_token_reaches_the_account_admin_or_anything_that_changes_servers(app, method, path):
+ token = make_token(app, 1, "write").json()["token"] # the strongest token there is: an owner's write token
+ response = getattr(with_token(token), method)(path, **({"json": {"name": "another", "hostname": "x"}} if method in ("post", "patch") else {}))
+ assert response.status_code in (401, 403), (path, response.status_code)
+
+
+def test_a_write_token_acknowledges_but_only_for_an_admin_and_never_sees_pending_servers(app):
+ assert make_token(app, 3, "write").status_code == 403 # a viewer can't mint one
+ token = make_token(app, 1, "write").json()["token"]
+ client = with_token(token)
+
+ assert client.post("/incidents/42/acknowledge").status_code == 200
+ assert client.get("/monitoring/overview").json()["pending_collectors"] == []
+ app.db.get(User, 1).role = "user"
+ app.db.commit()
+ assert client.post("/incidents/42/mute").status_code == 403 # the owner's role changed: the token follows it
+
+
+def test_expired_revoked_and_unknown_tokens_are_refused(app):
+ created = make_token(app, 3, expires_in_days=1).json()
+ client = with_token(created["token"])
+ assert client.get("/incidents").status_code == 200
+ app.db.query(ApiToken).one().expires_at = NOW - timedelta(minutes=1)
+ app.db.commit()
+ assert client.get("/incidents").status_code == 401
+
+ fresh = make_token(app, 3).json()
+ assert signed_in(app, 2).delete(f"/account/tokens/{fresh['id']}").status_code == 404 # not someone else's to revoke
+ assert signed_in(app, 3).delete(f"/account/tokens/{fresh['id']}").status_code == 200
+ assert with_token(fresh["token"]).get("/incidents").status_code == 401
+ assert with_token("idk_r_" + "x" * 43).get("/incidents").status_code == 401
+ app.db.get(User, 3).is_active = False
+ app.db.commit()
+ assert with_token(make_token(app, 1).json()["token"]).get("/incidents").status_code == 200 # other accounts are unaffected
+
+
+# --- profile and preferences -------------------------------------------------------------------------
+
+def test_profile_and_preferences_keep_only_what_is_valid(app):
+ client = signed_in(app, 3)
+ account = client.get("/account").json()
+ assert account["role_name"] == "Viewer" and account["preferences"]["display"]["theme"] == "dark" and signed_in(app, 1).get("/account").json()["role_name"] == "Owner"
+
+ assert client.patch("/account/profile", json={"name": "Vid V.", "username": "Vid", "avatar_color": "#FF5A1F"}).json()["username"] == "vid"
+ assert client.patch("/account/profile", json={"username": "no spaces"}).status_code == 400 and client.patch("/account/profile", json={"avatar_color": "red"}).status_code == 400
+ assert signed_in(app, 2).patch("/account/profile", json={"username": "vid"}).status_code == 409
+ saved = client.put("/account/preferences", json={"display": {"theme": "light", "density": "tiny", "timezone": "Europe/Zagreb", "evil": "<script>"}, "quiet": {"enabled": True, "start": "23:00", "end": "07:00"}}).json()
+ assert saved["display"]["theme"] == "light" and saved["display"]["density"] == "comfortable" and saved["display"]["timezone"] == "Europe/Zagreb" and "evil" not in saved["display"]
+ assert client.put("/account/preferences", json={"display": {"timezone": "Mars/Olympus"}}).status_code == 400
+ assert client.put("/account/preferences", json={"quiet": {"start": "25:00", "end": "07:00"}}).status_code == 400
+
+
+# --- notification channels ---------------------------------------------------------------------------
+
+def outbox(monkeypatch):
+ sent = []
+ monkeypatch.setattr(notify, "resolve", lambda host, port: ["8.8.8.8"] if host == "ntfy.example" else ["10.0.0.5"] if host == "ntfy.lan" else ["127.0.0.1"])
+ monkeypatch.setattr(notify, "_post", lambda url, data, headers: (sent.append((url, data, headers)) or (True, "200")))
+ return sent
+
+
+def test_channels_cannot_point_inwards_and_only_admins_reach_the_local_network(app, outbox):
+ viewer, owner = signed_in(app, 3), signed_in(app, 1)
+ for bad in ("http://localhost:6379/", "http://ntfy.lan/topic", "file:///etc/passwd", "http://user:[email protected]/t", ""):
+ assert viewer.post("/account/channels", json={"kind": "ntfy", "target": bad}).status_code == 400, bad
+ assert owner.post("/account/channels", json={"kind": "ntfy", "target": "http://localhost:6379/"}).status_code == 400
+ assert owner.post("/account/channels", json={"kind": "ntfy", "target": "http://ntfy.lan/topic"}).status_code == 200
+
+ created = viewer.post("/account/channels", json={"kind": "ntfy", "target": "https://ntfy.example/infradeck-secret-topic"}).json()
+ assert created["display"] == "ntfy.example/…-topic" and "secret" not in str(viewer.get("/account").json()["channels"])
+ assert "infradeck-secret-topic" not in app.db.query(NotificationChannel).filter_by(user_id=3).one().target_enc # stored encrypted
+ tested = viewer.post(f"/account/channels/{created['id']}/test").json()
+ assert tested["last_ok"] is True and outbox[-1][0] == "https://ntfy.example/infradeck-secret-topic"
+ assert owner.post(f"/account/channels/{created['id']}/test").status_code == 404 and owner.delete(f"/account/channels/{created['id']}").status_code == 404
+ assert viewer.post("/account/channels", json={"kind": "email"}).status_code == 400 # no SMTP configured
+
+
+def test_an_address_that_later_resolves_inwards_is_refused_at_send_time(app, outbox, monkeypatch):
+ viewer = signed_in(app, 3)
+ created = viewer.post("/account/channels", json={"kind": "webhook", "target": "https://ntfy.example/hook"}).json()
+ monkeypatch.setattr(notify, "resolve", lambda host, port: ["169.254.169.254"])
+
+ tested = viewer.post(f"/account/channels/{created['id']}/test").json()
+ assert tested["last_ok"] is False and tested["last_status"] == "address refused" and outbox == []
+
+
+def test_incidents_are_sent_once_following_routing_quiet_hours_and_muting(app, outbox):
+ viewer = signed_in(app, 3)
+ channel = viewer.post("/account/channels", json={"kind": "ntfy", "target": "https://ntfy.example/t"}).json()
+
+ assert main.dispatch_notifications(app.db) == 2 and main.dispatch_notifications(app.db) == 0 # each incident once
+ critical = next(message for message in outbox if b"INC-0042" in message[1])
+ assert critical[2]["Priority"] == "5" and app.db.get(IncidentAlert, 42).notified_at is not None
+ alert = app.db.get(IncidentAlert, 43)
+ alert.status, alert.resolved_at = "resolved", datetime.now(timezone.utc)
+ app.db.commit()
+ assert main.dispatch_notifications(app.db) == 0 # "resolved" is off unless asked for
+ viewer.put("/account/preferences", json={"routing": {"resolved": {str(channel["id"]): True}, "critical": {str(channel["id"]): False}, "warning": {"999": True}}})
+ assert main.dispatch_notifications(app.db) == 1 and outbox[-1][2]["Title"].startswith("Resolved: ")
+
+ app.db.add(IncidentAlert(id=50, server_id=1, severity="WARNING", title="late warning", description="d", status="active", rule_key="host:memory"))
+ app.db.add(IncidentAlert(id=51, server_id=1, severity="CRITICAL", title="muted critical", description="d", status="active", rule_key="host:disk:/", muted_until=datetime.now(timezone.utc) + timedelta(hours=1)))
+ app.db.commit()
+ viewer.put("/account/preferences", json={"routing": {}, "quiet": {"enabled": True, "start": "00:00", "end": "23:59"}})
+ assert main.dispatch_notifications(app.db) == 0 # the warning waits, the muted one stays silent
+ viewer.put("/account/preferences", json={"quiet": {"enabled": False, "start": "00:00", "end": "23:59"}})
+ assert main.dispatch_notifications(app.db) == 1 and b"INC-0050" in outbox[-1][1]
+
+
+# --- admin -------------------------------------------------------------------------------------------
+
+def test_users_are_listed_and_changed_but_not_the_owner_or_yourself(app):
+ ana = signed_in(app, 2)
+ assert signed_in(app, 3).get("/admin/users").status_code == 403
+ assert [(user["name"], user["role_name"]) for user in ana.get("/admin/users").json()["users"]] == [("Karlo Owner", "Owner"), ("Ana Admin", "Admin"), ("Vid Viewer", "Viewer")]
+ assert ana.patch("/admin/users/1", json={"role": "user"}).status_code == 403 and ana.patch("/admin/users/2", json={"is_active": False}).status_code == 403
+
+ vid = signed_in(app, 3)
+ assert ana.patch("/admin/users/3", json={"is_active": False}).status_code == 200
+ assert vid.get("/incidents").status_code == 401 # signed out at once
+ assert ana.patch("/admin/users/3", json={"is_active": True, "role": "admin"}).json()["users"][2]["role_name"] == "Admin"
+
+
+def test_an_invitation_lets_one_person_in_while_registration_is_closed(app):
+ owner = signed_in(app, 1)
+ assert owner.post("/admin/invites", json={"email": "[email protected]"}).status_code == 409
+ invite = owner.post("/admin/invites", json={"email": "[email protected]", "role": "user"}).json()
+ assert app.db.query(Invite).one().token_hash == main._hash_secret(invite["token"]) and owner.get("/admin/users").json()["invites"][0]["email"] == "[email protected]"
+
+ guest = TestClient(main.app)
+ assert guest.get(f"/auth/invite?token={invite['token']}").json() == {"email": "[email protected]", "role": "user"}
+ body = {"name": "Luka", "password": PASSWORD}
+ assert guest.post("/auth/register", json={**body, "email": "[email protected]"}).status_code == 403 # closed without the invitation
+ assert guest.post("/auth/register", json={**body, "email": "[email protected]", "invite_token": invite["token"]}).status_code == 403 # not for this address
+ assert guest.post("/auth/register", json={**body, "email": "[email protected]", "invite_token": "x" * 40}).status_code == 403
+ assert guest.post("/auth/register", json={**body, "email": "[email protected]", "invite_token": invite["token"]}).json()["user"]["role"] == "user"
+ assert TestClient(main.app).post("/auth/register", json={**body, "email": "[email protected]", "invite_token": invite["token"]}).status_code == 403 # used
+ assert TestClient(main.app).get(f"/auth/invite?token={invite['token']}").status_code == 404
+
+
+def test_two_factor_can_be_required_of_everyone(app):
+ owner = signed_in(app, 1)
+ client = TestClient(main.app)
+ assert client.post("/auth/login", json={"email": "[email protected]", "password": PASSWORD}).json()["setup_required"] is False
+
+ assert owner.put("/admin/settings", json={"require_2fa_for_everyone": True}).json()["require_2fa_for_everyone"] is True
+ limited = TestClient(main.app)
+ assert limited.post("/auth/login", json={"email": "[email protected]", "password": PASSWORD}).json()["setup_required"] is True
+ assert limited.get("/monitoring/overview").status_code == 403 and limited.get("/auth/2fa/status").json()["required"] is True
+
+
+def test_a_rule_can_be_switched_off_and_the_table_shows_how_often_each_fired(app):
+ owner = signed_in(app, 1)
+ rules = {rule["kind"]: rule for rule in owner.get("/admin/rules").json()["rules"]}
+ assert rules["container:restart_loop"]["fired"] == 1 and rules["container:restart_loop"]["when"] == "Container restarts ≥ 3" and rules["container:restart_loop"]["window"] == "30 min"
+ assert rules["host:swap"]["enabled"] is True
+
+ saved = owner.put("/admin/settings", json={"disabled_rules": ["host:swap", "made:up"]}).json()
+ assert saved["disabled_rules"] == ["host:swap"]
+ firing = {"host:swap": ("WARNING", "t", "d"), "host:memory": ("WARNING", "t", "d")}
+ assert list(main._enabled_rules(app.db, firing)) == ["host:memory"]
+ assert signed_in(app, 3).get("/admin/rules").status_code == 403
+
+
+def test_a_server_is_renamed_and_keeps_the_name_and_the_install_describes_itself(app):
+ owner = signed_in(app, 1)
+ assert owner.patch("/monitoring/servers/1", json={"hostname": "media-box", "check_interval_seconds": 15}).json() == {"id": 1, "hostname": "media-box", "check_interval_seconds": 15}
+ assert app.db.get(Server, 1).name_locked is True and owner.patch("/monitoring/servers/1", json={"check_interval_seconds": 7}).status_code == 400
+ assert signed_in(app, 3).patch("/monitoring/servers/1", json={"hostname": "x"}).status_code == 403
+
+ system = owner.get("/admin/system").json()
+ assert system["version"] == main.APP_VERSION and system["database"]["host_rows"] == 30 and system["agent"]["incidents_this_month"] >= 1
diff --git a/tests/collectors/test_docker_proxy.py b/tests/collectors/test_docker_proxy.py
index 3cafd81..3f486d9 100644
--- a/tests/collectors/test_docker_proxy.py
+++ b/tests/collectors/test_docker_proxy.py
@@ -13,10 +13,10 @@ SECRET = "SUPER_SECRET_TOKEN_123"
INSPECT = {
"Id": CID, "Name": "/web", "RestartCount": 2, "Image": "sha256:" + "ab" * 32,
- "Config": {"Image": "nginx:1", "Env": [f"DB_PASSWORD={SECRET}"], "Labels": {"k": "v"}, "Cmd": ["nginx"]},
+ "Config": {"Image": "nginx:1", "Env": [f"DB_PASSWORD={SECRET}"], "Labels": {"k": "v", "secret": SECRET, "com.docker.compose.project": "shop"}, "Cmd": ["nginx"]},
"State": {"Status": "running", "StartedAt": "2026-01-01T00:00:00Z", "Pid": 99, "ExitCode": 137, "OOMKilled": True, "FinishedAt": "2026-01-02T03:04:05.123456789Z", "Error": f"failed: {SECRET}", "Health": {"Status": "healthy", "Log": [{"Output": SECRET}]}},
"NetworkSettings": {"Ports": {"80/tcp": [{"HostIp": "0.0.0.0", "HostPort": "8080"}]}, "SecondaryIPAddresses": None, "Networks": {"x": {"Gateway": "1"}}},
- "Mounts": [{"Source": "/etc/shadow"}], "HostConfig": {"Privileged": True}, "GraphDriver": {"Data": {}},
+ "Mounts": [{"Type": "bind", "Source": "/srv/web", "Destination": "/data", "Mode": SECRET, "RW": True}, {"Type": "volume", "Name": "web_cache", "Source": "/var/lib/docker/volumes/web_cache/_data", "Destination": "/cache", "Driver": "local"}, "junk"], "HostConfig": {"Privileged": True}, "GraphDriver": {"Data": {}},
}
LISTING = [{"Id": CID, "Names": ["/web"], "Image": "nginx:1", "State": "running", "Labels": {"secret": SECRET}, "Mounts": []}]
STATS = {"cpu_stats": {"cpu_usage": {"total_usage": 10}, "system_cpu_usage": 100, "online_cpus": 2}, "precpu_stats": {"cpu_usage": {"total_usage": 5}, "system_cpu_usage": 50},
@@ -41,9 +41,9 @@ def _fresh_collector_state():
@pytest.mark.parametrize("target", [
"/containers/json?all=1", f"/containers/{CID}/json", f"/containers/{CID}/stats?stream=false", f"/containers/{CID[:12]}/json",
- f"/containers/{CID}/stats?stream=false&one-shot=true",
+ f"/containers/{CID}/stats?stream=false&one-shot=true", "/version", "/system/df",
])
-def test_the_four_read_requests_are_allowed(target):
+def test_the_six_read_requests_are_allowed(target):
assert proxy.route("GET", target) is not None
@@ -55,7 +55,7 @@ def test_only_get_is_allowed(method):
@pytest.mark.parametrize("target", [
# other endpoints, including the ones that read container contents or start things
"/containers/json", # only the full list the collector asks for (?all=1) is allowed
- "/", "/version", "/info", "/images/json", "/volumes", "/networks", "/system/df", "/events", "/_ping", "/containers", "/containers/",
+ "/", "/version?x=1", "/v1.43/version", "/info", "/images/json", "/volumes", "/networks", "/system/df?type=image", "/system/info", "/events", "/_ping", "/containers", "/containers/",
f"/containers/{CID}/export", f"/containers/{CID}/archive?path=/etc/passwd", f"/containers/{CID}/logs", f"/containers/{CID}/top",
f"/containers/{CID}/attach", f"/containers/{CID}/exec", f"/containers/{CID}/start", f"/containers/{CID}/kill", f"/containers/{CID}/changes",
"/containers/create", "/containers/prune", "/exec/abc/start", "/build", "/commit", "/swarm", "/secrets", "/configs",
@@ -88,12 +88,36 @@ def test_inspect_output_drops_environment_and_everything_unneeded():
assert SECRET not in json.dumps(result)
assert result == {
- "Id": CID, "Name": "/web", "RestartCount": 2, "Image": "sha256:" + "ab" * 32, "Config": {"Image": "nginx:1"},
+ "Id": CID, "Name": "/web", "RestartCount": 2, "Image": "sha256:" + "ab" * 32, "Config": {"Image": "nginx:1", "Labels": {"com.docker.compose.project": "shop"}},
+ # Of a mount only where it comes from and where it lands; of the labels only the compose project.
+ "Mounts": [{"Type": "bind", "Source": "/srv/web", "Destination": "/data"}, {"Type": "volume", "Name": "web_cache", "Source": "/var/lib/docker/volumes/web_cache/_data", "Destination": "/cache"}],
"State": {"Status": "running", "StartedAt": "2026-01-01T00:00:00Z", "ExitCode": 137, "OOMKilled": True, "FinishedAt": "2026-01-02T03:04:05.123456789Z", "Health": {"Status": "healthy"}},
"NetworkSettings": {"Ports": {"80/tcp": [{"HostIp": "0.0.0.0", "HostPort": "8080"}]}},
}
+def test_version_output_keeps_only_the_version_numbers():
+ assert proxy.project_version({"Version": "27.3.1", "ApiVersion": "1.47", "KernelVersion": "6.8.0", "Os": "linux", "Components": [{"Details": {"x": SECRET}}]}) == {"Version": "27.3.1", "ApiVersion": "1.47"}
+ assert proxy.project_version(None) == {}
+
+
+def test_disk_usage_is_reduced_to_totals_with_no_names():
+ usage = {
+ "LayersSize": 9_000, "Images": [
+ {"Id": "sha256:a", "RepoTags": [SECRET], "Size": 5_000, "SharedSize": 1_000, "Containers": 2},
+ {"Id": "sha256:b", "RepoTags": ["old:1"], "Size": 4_000, "SharedSize": 1_000, "Containers": 0},
+ {"Id": "sha256:c", "Size": 500, "SharedSize": 900, "Containers": 0}, "junk",
+ ],
+ "Containers": [{"Names": [SECRET]}], "Volumes": [{"Name": SECRET, "UsageData": {"Size": 7}}],
+ "BuildCache": [{"ID": SECRET, "Size": 300, "InUse": True, "Shared": False}, {"Size": 200, "InUse": False, "Shared": False}, {"Size": 999, "InUse": False, "Shared": True}],
+ }
+ result = proxy.project_disk_usage(usage)
+
+ assert SECRET not in json.dumps(result)
+ assert result == {"images_bytes": 9_000, "images_unused_bytes": 3_000, "images_unused": 2, "images": 3, "build_cache_bytes": 500, "build_cache_unused_bytes": 200}
+ assert proxy.project_disk_usage([]) == {} and proxy.project_disk_usage({"Images": "x", "LayersSize": -5})["images_bytes"] == 0
+
+
def test_list_and_stats_output_are_cut_down():
assert SECRET not in json.dumps(proxy.project_list(LISTING))
assert proxy.project_list(LISTING) == [{"Id": CID, "Names": ["/web"], "Image": "nginx:1", "State": "running"}]
@@ -156,6 +180,7 @@ def test_collector_works_through_the_proxy_and_never_sees_secrets(stack):
assert (container["name"], container["image"], container["status"], container["restart_count"], container["healthcheck_status"]) == ("web", "nginx:1", "running", 2, "healthy")
assert container["ports"] == "8080->80/tcp" and container["memory_used_mb"] == 1.0 and container["pids"] == 3
+ assert container["project"] == "shop" and container["volumes"] == "/srv/web, web_cache"
assert SECRET not in json.dumps(container)
diff --git a/tests/history/test_container_stats.py b/tests/history/test_container_stats.py
new file mode 100644
index 0000000..097963f
--- /dev/null
+++ b/tests/history/test_container_stats.py
@@ -0,0 +1,170 @@
+"""The Statistics page's views of every container at once, and comparing a range with the one before it."""
+import os
+from datetime import datetime, timedelta, timezone
+
+os.environ.setdefault("DATABASE_URL", "sqlite://")
+os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")
+
+import pytest
+from fastapi.testclient import TestClient
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.pool import StaticPool
+
+from src.agent import collector
+from src.backend import history, main, rollups, stats
+from src.backend.models import Base, ContainerMetric, HostMetric, Server, User
+from tests.fakes import FakeRedis
+
+NOW = datetime(2026, 10, 13, 12, 0, tzinfo=timezone.utc)
+
+
+def db():
+ engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+ session.add(User(id=1, name="Owner", email="[email protected]", password_hash="x", role="admin"))
+ session.add(Server(id=1, owner_id=1, hostname="alpha", check_interval_seconds=60))
+ session.commit()
+ return session
+
+
+def seed(db, name, start, count, cpu, memory=100.0, restarts=lambda i: 0, status=lambda i: "running", step=timedelta(minutes=1)):
+ for index in range(count):
+ db.add(ContainerMetric(server_id=1, container_id=name * 8, name=name, status=status(index), cpu_pct=cpu(index), memory_used_mb=memory, restart_count=restarts(index), time=start + index * step))
+ db.commit()
+
+
+def by_name(result):
+ return {item["name"]: item for item in result["containers"]}
+
+
+def test_a_day_is_summed_from_the_check_ins_and_ranked_by_average_cpu(db):
+ seed(db, "web", NOW - timedelta(hours=2), 120, cpu=lambda i: 10.0 if i < 60 else 30.0, memory=200.0, restarts=lambda i: 3 if i < 100 else 5, status=lambda i: "exited" if i < 6 else "running")
+ seed(db, "db", NOW - timedelta(hours=2), 120, cpu=lambda i: 80.0 if i == 7 else 1.0, memory=900.0)
+
+ result = stats.container_usage(db, db.get(Server, 1), "24h", NOW)
+ usage = by_name(result)
+
+ assert [item["name"] for item in result["containers"]] == ["web", "db"]
+ assert (usage["web"]["avg_cpu"], usage["web"]["max_cpu"], usage["web"]["avg_memory_mb"]) == (20.0, 30.0, 200.0)
+ assert (usage["web"]["restarts"], usage["web"]["samples"], usage["web"]["down_samples"]) == (2, 120, 6)
+ assert usage["db"]["max_cpu"] == 80.0 and usage["db"]["restarts"] == 0
+ known = [value for value in usage["web"]["sparkline"] if value is not None]
+ assert len(usage["web"]["sparkline"]) == stats.SPARKLINE_POINTS and known[0] == 10.0 and known[-1] == 30.0
+
+
+def test_a_week_gives_the_same_answer_from_summaries_as_from_check_ins(db):
+ start = NOW - timedelta(days=3)
+ seed(db, "web", start, 3 * 24 * 4, cpu=lambda i: float(i % 50), step=timedelta(minutes=15))
+ before = by_name(stats.container_usage(db, db.get(Server, 1), "7d", NOW))["web"] # nothing summarised yet
+ rollups.run_rollups(db, NOW)
+ db.commit()
+ after = by_name(stats.container_usage(db, db.get(Server, 1), "7d", NOW))["web"]
+
+ assert after["samples"] == before["samples"] == 3 * 24 * 4
+ assert after["avg_cpu"] == pytest.approx(before["avg_cpu"]) and after["max_cpu"] == before["max_cpu"] == 49.0
+
+
+def test_the_busiest_container_is_named_for_each_period(db):
+ seed(db, "web", NOW - timedelta(minutes=30), 30, cpu=lambda i: 5.0)
+ seed(db, "backup", NOW - timedelta(minutes=30), 30, cpu=lambda i: 94.0 if 10 <= i < 15 else 1.0)
+
+ result = stats.busiest_containers(db, db.get(Server, 1), "1h", NOW)
+ names = [point["name"] for point in result["points"]]
+
+ assert result["bucket_seconds"] == 60 and len(names) == 30
+ assert names[9] == "web" and names[10:15] == ["backup"] * 5 and result["points"][10]["cpu"] == 94.0
+
+
+def test_the_busiest_container_over_a_week_comes_from_hourly_summaries_plus_what_is_not_summarised_yet(db):
+ seed(db, "web", NOW - timedelta(days=2), 2 * 24 * 4, cpu=lambda i: 90.0 if i == 0 else 3.0, step=timedelta(minutes=15))
+ rollups.run_rollups(db, NOW - timedelta(hours=6))
+ db.commit()
+
+ result = stats.busiest_containers(db, db.get(Server, 1), "7d", NOW)
+ assert result["bucket_seconds"] == 3600 and len(result["points"]) == 48
+ assert result["points"][0] == {"time": (NOW - timedelta(days=2)).isoformat(), "name": "web", "cpu": 90.0}
+
+
+def test_the_period_before_a_range_can_be_asked_for(db):
+ for index in range(120):
+ db.add(HostMetric(server_id=1, time=NOW - timedelta(minutes=120 - index, seconds=-30), cpu_utilization_pct=10.0 if index < 60 else 50.0))
+ db.commit()
+ current = history.history(db, history.HOST, 1, None, "1h", ("cpu",), 60, now=NOW)
+ before = history.history(db, history.HOST, 1, None, "1h", ("cpu",), 60, now=history.previous_end("1h", NOW))
+
+ assert {point["cpu"]["avg"] for point in current["points"]} == {50.0} and {point["cpu"]["avg"] for point in before["points"]} == {10.0}
+ assert before["end"] == (NOW - timedelta(hours=1)).isoformat() and history.previous_end("all", NOW) is None
+
+
+def test_the_endpoints_answer_and_refuse_what_makes_no_sense(db, monkeypatch):
+ main.app.dependency_overrides[main.get_db] = lambda: db
+ monkeypatch.setattr(main, "redis_client", FakeRedis())
+ monkeypatch.setattr(main, "_current_user", lambda session_id, db: {"id": 1, "role": "user"})
+ client = TestClient(main.app)
+ try:
+ db.add(HostMetric(server_id=1, time=datetime.now(timezone.utc) - timedelta(minutes=90), cpu_utilization_pct=7.0))
+ db.commit()
+ seed(db, "web", datetime.now(timezone.utc) - timedelta(minutes=10), 5, cpu=lambda i: 4.0)
+
+ assert client.get("/stats/servers/1/containers?range=24h").json()["containers"][0]["name"] == "web"
+ assert client.get("/stats/servers/1/busiest?range=1h").json()["points"][0]["name"] == "web"
+ previous = client.get("/monitoring/servers/1/history?range=1h&metrics=cpu&previous=true").json()
+ assert previous["previous"] is True and [point["cpu"]["avg"] for point in previous["points"]] == [7.0]
+ assert client.get("/monitoring/servers/1/history?range=all&previous=true").status_code == 422
+ assert client.get("/stats/servers/99/containers").status_code == 404 and client.get("/stats/servers/1/busiest?range=2h").status_code == 422
+ finally:
+ main.app.dependency_overrides.clear()
+
+
+def test_container_swap_is_read_from_its_cgroup_and_only_for_real_ids(tmp_path, monkeypatch):
+ cid = "ab" * 32
+ scope = tmp_path / f"sys/fs/cgroup/system.slice/docker-{cid}.scope"
+ scope.mkdir(parents=True)
+ (scope / "memory.swap.current").write_text(f"{84 * collector.MiB}\n")
+ monkeypatch.setattr(collector, "HOST_ROOT", tmp_path)
+
+ assert collector.container_swap_mb(cid) == 84.0
+ assert collector.container_swap_mb("cd" * 32) is None
+ assert collector.container_swap_mb("../../etc/passwd") is None
+
+
+def test_swap_per_container_is_averaged_over_the_range_and_survives_summarising(db):
+ start = NOW - timedelta(days=2)
+ for index in range(2 * 24 * 4):
+ db.add(ContainerMetric(server_id=1, container_id="gitlab00", name="gitlab", status="running", cpu_pct=1.0, memory_used_mb=100.0, swap_mb=1000.0 if index >= 96 else 0.0, restart_count=0, time=start + index * timedelta(minutes=15)))
+ db.commit()
+ before = by_name(stats.container_usage(db, db.get(Server, 1), "7d", NOW))["gitlab"]
+ rollups.run_rollups(db, NOW)
+ db.commit()
+ after = by_name(stats.container_usage(db, db.get(Server, 1), "7d", NOW))["gitlab"]
+
+ assert (before["avg_swap_mb"], before["max_swap_mb"]) == (500.0, 1000.0)
+ assert after["avg_swap_mb"] == pytest.approx(500.0) and after["max_swap_mb"] == 1000.0
+ series = history.history(db, history.CONTAINER, 1, "gitlab00", "30d", ("swap_mb",), 60, now=NOW)
+ assert series["points"][-1]["swap_mb"] == {"avg": 1000.0, "max": 1000.0}
+
+
+def test_cpu_spikes_have_a_length_even_when_shorter_than_a_chart_point(db):
+ server = db.get(Server, 1)
+ for index in range(120): # one check-in a minute; 100% for minutes 10-17 and 60-61, with one late check-in
+ if index == 14:
+ continue
+ db.add(HostMetric(server_id=1, time=NOW - timedelta(minutes=120 - index), cpu_utilization_pct=100.0 if 10 <= index < 18 or index in (60, 61) else 8.0))
+ db.commit()
+
+ result = stats.cpu_spikes(db, server, "24h", NOW)
+ assert result["available"] is True
+ assert [(spike["seconds"], spike["peak"]) for spike in result["spikes"]] == [(8 * 60, 100.0), (2 * 60, 100.0)]
+ assert result["spikes"][0]["time"] == (NOW - timedelta(minutes=110)).isoformat()
+ assert stats.cpu_spikes(db, server, "30d", NOW) == {"server_id": 1, "range": "30d", "available": False, "threshold": 90.0, "spikes": []}
+
+
+def test_installed_updates_become_an_event_once():
+ before = {"updates_applied_at": 1000.0, "updates_pending": 41, "updates_manager": "apt"}
+ assert main.packages_updated_detail(before, {**before, "updates_applied_at": 5000.0, "updates_pending": 0, "reboot_kernel": "6.8.0-85-generic"}) == "41 packages updated by apt, kernel 6.8.0-85-generic waiting for reboot"
+ assert main.packages_updated_detail(before, {**before, "updates_applied_at": 5000.0, "updates_pending": 43}) == "Packages installed or updated by apt"
+ assert main.packages_updated_detail(before, before) is None
+ assert main.packages_updated_detail({}, {"updates_applied_at": 5000.0}) is None # the first report is only a baseline
diff --git a/tests/monitoring/test_dashboard_data.py b/tests/monitoring/test_dashboard_data.py
new file mode 100644
index 0000000..ca91d63
--- /dev/null
+++ b/tests/monitoring/test_dashboard_data.py
@@ -0,0 +1,340 @@
+"""What the Overview page reads: machine facts from collectors (never trusted), sparklines, the all-clear summary
+and a server's event timeline."""
+import json
+import os
+from datetime import datetime, timedelta, timezone
+
+os.environ.setdefault("DATABASE_URL", "sqlite://")
+os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")
+
+import pytest
+from fastapi.testclient import TestClient
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.pool import StaticPool
+
+from src.agent import collector, system_helper
+from src.backend import dashboard, main
+from src.backend.models import Base, ContainerMetric, HostMetric, IncidentAlert, PendingCollector, Server, SystemEvent, User
+from tests.fakes import FakeRedis
+
+TOKEN = "token-one"
+NOW = datetime(2026, 10, 13, 12, 0, tzinfo=timezone.utc)
+
+
+def app(monkeypatch):
+ engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
+ Base.metadata.create_all(engine)
+ Session = sessionmaker(bind=engine)
+ with Session() as seed:
+ seed.add(User(id=1, name="Owner", email="[email protected]", password_hash="x", role="admin", is_active=True))
+ seed.add(Server(id=1, owner_id=1, hostname="alpha", check_interval_seconds=60, collector_token_hash=main._hash_secret(TOKEN), machine_id="machine-1", created_at=NOW - timedelta(days=60)))
+ seed.commit()
+
+ def get_db():
+ session = Session()
+ try:
+ yield session
+ finally:
+ session.close()
+
+ main.app.dependency_overrides[main.get_db] = get_db
+ monkeypatch.setattr(main, "redis_client", FakeRedis())
+ monkeypatch.setattr(main, "_current_user", lambda session_id, db: {"id": 1, "role": "admin"})
+ monkeypatch.setattr(main, "_require_admin", lambda session_id, db: {"id": 1, "role": "admin"})
+ monkeypatch.setattr(main, "_is_admin", lambda db, user_id: True)
+ client = TestClient(main.app, raise_server_exceptions=False)
+ client.Session = Session
+ yield client
+ main.app.dependency_overrides.clear()
+
+
+def ingest(client, body):
+ return client.post("/monitoring/metrics/ingest", content=json.dumps({"server_id": 1, **body}), headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"})
+
+
+def overview_server(client):
+ return client.get("/monitoring/overview").json()["servers"][0]
+
+
+# --- machine facts --------------------------------------------------------------------------
+
+def test_system_info_keeps_known_fields_and_drops_the_rest(app):
+ system = {
+ "kernel": "6.8.0-84-generic", "arch": "x86_64", "cpu_model": "Intel Core i5-8500T", "swap_total_gb": 4.0, "updates_pending": 23, "updates_security": 4,
+ "auto_updates": True, "helper_installed": False, "reboot_kernel": "6.8.0-85-generic", "clock_offset_ms": 0.4, "secret": "x", "html": "<script>",
+ "temperatures": [{"label": "coretemp", "celsius": 52.0}, {"label": "bad", "celsius": 9999}, "junk"],
+ "interfaces": [{"name": "eth0", "network": "10.0.0.12/24", "rx_mbps": 1.8, "tx_mbps": float("1e99"), "speed_mbit": 1000, "extra": 1}, {"name": "", "network": "x"}, {"name": "wg0", "network": "not a network"}],
+ "mount_devices": {"/": "nvme0n1p2", "/x": 5},
+ "firewall_allowed": [{"proto": "tcp", "port": 22, "file": "nftables"}, {"proto": "icmp", "port": 1, "file": "nftables"}, {"proto": "tcp", "port": 80, "file": "/etc/passwd"}],
+ }
+ assert ingest(app, {"server": {"system": system}, "host": {"cpu_utilization_pct": 5}}).status_code == 200
+
+ stored = overview_server(app)["system"]
+ assert stored["kernel"] == "6.8.0-84-generic" and stored["updates_security"] == 4 and stored["auto_updates"] is True and stored["reboot_kernel"] == "6.8.0-85-generic"
+ assert "secret" not in stored and "html" not in stored
+ assert stored["temperatures"] == [{"label": "coretemp", "celsius": 52.0}]
+ assert stored["interfaces"] == [{"name": "eth0", "network": "10.0.0.0/24", "rx_mbps": 1.8, "speed_mbit": 1000}, {"name": "wg0"}]
+ assert stored["mount_devices"] == {"/": "nvme0n1p2"}
+ assert stored["firewall_allowed"] == [{"proto": "tcp", "port": 22, "file": "nftables"}]
+
+
[email protected]("junk", [None, 5, "text", [], {"kernel": 5, "interfaces": "x", "temperatures": {}, "mount_devices": [], "firewall_allowed": 3, "updates_pending": -1, "auto_updates": "yes"}])
+def test_malformed_system_info_never_breaks_a_check_in(app, junk):
+ assert ingest(app, {"server": {"system": junk}, "host": {"cpu_utilization_pct": 5}}).status_code == 200
+ assert isinstance(overview_server(app)["system"], dict)
+
+
+def test_containers_carry_their_project_ports_and_volumes(app):
+ container = {"container_id": "c" * 64, "name": "gitlab", "status": "running", "project": "gitlab", "ports": "8080->80/tcp", "volumes": "/srv/gitlab/config, /srv/gitlab/data", "started_at": "2026-10-03T09:12:00Z"}
+ ingest(app, {"host": {"cpu_utilization_pct": 5}, "containers": [container, {"container_id": "d" * 64, "name": "solo", "status": "running", "project": 7}]})
+
+ by_name = {item["name"]: item for item in overview_server(app)["containers"]}
+ assert (by_name["gitlab"]["project"], by_name["gitlab"]["ports"], by_name["gitlab"]["started_at"]) == ("gitlab", "8080->80/tcp", "2026-10-03T09:12:00Z")
+ assert by_name["solo"]["project"] is None
+ assert app.get(f"/monitoring/servers/1/containers/{'c' * 64}").json()["volumes"] == "/srv/gitlab/config, /srv/gitlab/data"
+
+
+# --- adding a server ------------------------------------------------------------------------
+
+def test_a_pending_collector_shows_what_it_found_and_can_be_named(app):
+ registered = app.post("/monitoring/collectors/register", json={"hostname": "box", "machine_id": "machine-9", "details": {"cpu_cores": 4, "containers": 35, "mounts": 2, "helper_installed": False, "dashboard_host": True, "junk": "x"}})
+ assert registered.status_code == 200
+ [pending] = app.get("/monitoring/overview").json()["pending_collectors"]
+ assert pending["details"] == {"cpu_cores": 4, "containers": 35, "mounts": 2, "helper_installed": False, "dashboard_host": True}
+
+ assert app.post(f"/monitoring/pending-collectors/{pending['id']}/approve", json={"hostname": "alpha"}).status_code == 409 # taken
+ assert app.post(f"/monitoring/pending-collectors/{pending['id']}/approve", json={"hostname": "media-box"}).status_code == 200
+ with app.Session() as db:
+ server = db.query(Server).filter_by(machine_id="machine-9").one()
+ assert (server.hostname, server.name_locked) == ("media-box", True)
+ token = "token-nine"
+ server.collector_token_hash = main._hash_secret(token)
+ db.commit()
+ server_id = server.id
+ # The machine keeps calling itself "box"; the chosen name stays.
+ app.post("/monitoring/metrics/ingest", content=json.dumps({"server_id": server_id, "server": {"hostname": "box"}, "host": {"cpu_utilization_pct": 1}}), headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"})
+ with app.Session() as db:
+ assert db.get(Server, server_id).hostname == "media-box"
+
+
+def test_keeping_the_machines_own_name_does_not_lock_it(app):
+ app.post("/monitoring/collectors/register", json={"hostname": "box", "machine_id": "machine-9"})
+ [pending] = app.get("/monitoring/overview").json()["pending_collectors"]
+ app.post(f"/monitoring/pending-collectors/{pending['id']}/approve", json={"hostname": "box"})
+ with app.Session() as db:
+ assert db.query(Server).filter_by(machine_id="machine-9").one().name_locked is False
+
+
+# --- sparklines -----------------------------------------------------------------------------
+
+def test_downsample_averages_and_keeps_gaps():
+ assert dashboard.downsample([1, 2, 3], limit=5) == [1, 2, 3]
+ assert dashboard.downsample([0, 10, None, None, 4, 6], limit=3) == [5, None, 5]
+
+
+def test_sparklines_cover_recent_samples_only(app):
+ with app.Session() as db:
+ now = datetime.now(timezone.utc)
+ for minutes_ago, cpu in ((90, 99.0), (10, 20.0), (5, 40.0)):
+ db.add(HostMetric(server_id=1, time=now - timedelta(minutes=minutes_ago), cpu_utilization_pct=cpu))
+ db.add(ContainerMetric(server_id=1, container_id="c1", name="web", status="running", cpu_pct=cpu / 2, time=now - timedelta(minutes=minutes_ago)))
+ db.commit()
+
+ assert app.get("/monitoring/sparklines?minutes=30").json()["servers"] == {"1": [20.0, 40.0]}
+ assert app.get("/monitoring/servers/1/containers/sparklines?minutes=15").json()["containers"] == {"c1": [10.0, 20.0]}
+ assert app.get("/monitoring/servers/99/containers/sparklines").status_code == 404
+ live = app.get("/monitoring/servers/1/live?minutes=30").json()["samples"]
+ assert [sample["cpu"] for sample in live] == [20.0, 40.0] and set(live[0]) == {"time", "cpu", "ram", "load", "swap", "net_sent_mb", "net_recv_mb"}
+
+
+# --- the all-clear summary ------------------------------------------------------------------
+
+def test_longest_quiet_stretch_is_the_biggest_gap_between_incidents():
+ start, end = NOW - timedelta(days=10), NOW
+ spans = [(start + timedelta(days=1), start + timedelta(days=2)), (start + timedelta(days=1, hours=12), start + timedelta(days=3)), (start + timedelta(days=9), end)]
+ assert dashboard.longest_quiet_seconds(spans, start, end) == timedelta(days=6).total_seconds()
+ assert dashboard.longest_quiet_seconds([], start, end) == timedelta(days=10).total_seconds()
+ assert dashboard.longest_quiet_seconds([(start - timedelta(days=1), end + timedelta(days=1))], start, end) == 0
+
+
+def test_quiet_summary_names_the_last_incident_and_ignores_notices(app):
+ with app.Session() as db:
+ db.add(IncidentAlert(server_id=1, severity="CRITICAL", title="gitlab is in a restart loop", description="d", status="resolved", rule_key="container:gitlab:restart_loop", created_at=NOW - timedelta(hours=3), resolved_at=NOW - timedelta(hours=2)))
+ db.add(IncidentAlert(server_id=1, severity="INFO", title="alpha needs a reboot", description="d", status="resolved", rule_key="system:reboot_required", created_at=NOW - timedelta(hours=1), resolved_at=NOW - timedelta(minutes=5)))
+ db.commit()
+ summary = dashboard.quiet_summary(db, NOW)
+
+ assert summary["last_incident"]["title"] == "gitlab is in a restart loop" and summary["last_incident"]["hostname"] == "alpha"
+ assert summary["quiet_since"] == (NOW - timedelta(hours=2)).isoformat()
+ assert summary["longest_quiet_seconds_this_month"] == (NOW - timedelta(hours=3) - NOW.replace(day=1, hour=0)).total_seconds()
+
+
+def test_overview_reports_quiet_only_when_nothing_needs_attention(app):
+ assert app.get("/monitoring/overview").json()["quiet"] is not None
+ with app.Session() as db:
+ db.add(IncidentAlert(server_id=1, severity="WARNING", title="t", description="d", status="active", rule_key="host:memory"))
+ db.add(IncidentAlert(server_id=1, severity="INFO", title="n", description="d", status="active", rule_key="system:reboot_required"))
+ db.commit()
+ body = app.get("/monitoring/overview").json()
+ assert body["quiet"] is None and body["alerts_by_severity"] == {"WARNING": 1, "INFO": 1} and body["servers"][0]["alerts_by_severity"] == {"WARNING": 1, "INFO": 1}
+ assert {alert["rule_key"] for alert in body["alerts"]} == {"host:memory", "system:reboot_required"}
+
+
+# --- a server's timeline --------------------------------------------------------------------
+
+def test_events_merge_recorded_events_with_alerts_newest_first(app):
+ with app.Session() as db:
+ db.add(SystemEvent(server_id=1, time=NOW - timedelta(hours=5), kind="port_opened", detail="tcp/8081 (all interfaces) started listening"))
+ db.add(SystemEvent(server_id=1, time=NOW - timedelta(hours=9), kind="container_added", detail="Container web appeared"))
+ db.add(SystemEvent(server_id=1, time=NOW - timedelta(days=20), kind="reboot", detail="old"))
+ db.add(IncidentAlert(server_id=1, severity="WARNING", title="Memory usage on alpha is 93%", description="d", status="resolved", rule_key="host:memory", created_at=NOW - timedelta(hours=2), resolved_at=NOW - timedelta(hours=1, minutes=42)))
+ db.add(IncidentAlert(server_id=1, severity="CRITICAL", title="Server alpha is offline", description="d", status="resolved", rule_key=main.SERVER_OFFLINE_RULE, created_at=NOW - timedelta(days=3), resolved_at=NOW - timedelta(days=3) + timedelta(hours=5)))
+ db.commit()
+ events = dashboard.server_events(db, db.get(Server, 1), 7, NOW)
+
+ assert [(event["source"], event["kind"]) for event in events] == [
+ ("alert", "alert_resolved"), ("alert", "alert_opened"), ("network", "port_opened"), ("container", "container_added"), ("collector", "collector_resumed"), ("collector", "collector_stopped"),
+ ]
+ assert events[0]["duration_seconds"] == 18 * 60 and events[1]["resolved"] is True
+ assert app.get("/monitoring/servers/1/events?days=7").status_code == 200 and app.get("/monitoring/servers/99/events").status_code == 404
+
+
+# --- what the collector reads ---------------------------------------------------------------
+
+def test_firewall_allowed_names_only_ports_that_are_listening(tmp_path, monkeypatch):
+ (tmp_path / "etc/ufw").mkdir(parents=True)
+ (tmp_path / "etc/ufw/user.rules").write_text("-A ufw-user-input -p tcp --dport 22 -j ACCEPT\n-A ufw-user-input -p tcp -m multiport --dports 80,443 -j ACCEPT\n-A ufw-user-input -p tcp --dport 5432 -j DROP\n")
+ (tmp_path / "etc/nftables.conf").write_text("table inet filter {\n chain input {\n udp dport { 1194, 51820 } accept\n tcp dport 9000-9002 accept\n }\n}\n")
+ monkeypatch.setattr(collector, "HOST_ROOT", tmp_path)
+ listeners = [{"proto": "tcp", "port": 22, "scope": "any"}, {"proto": "tcp", "port": 443, "scope": "any"}, {"proto": "tcp", "port": 5432, "scope": "any"}, {"proto": "udp", "port": 1194, "scope": "any"}, {"proto": "tcp", "port": 9001, "scope": "any"}]
+
+ assert collector.firewall_allowed(listeners) == [
+ {"proto": "tcp", "port": 22, "file": "ufw"}, {"proto": "tcp", "port": 443, "file": "ufw"}, {"proto": "tcp", "port": 9001, "file": "nftables"}, {"proto": "udp", "port": 1194, "file": "nftables"},
+ ]
+ assert collector.firewall_allowed(None) == []
+
+
+def test_updates_come_from_the_files_apt_leaves_behind(tmp_path, monkeypatch):
+ for directory in ("etc/apt/apt.conf.d", "var/lib/update-notifier", "boot"):
+ (tmp_path / directory).mkdir(parents=True)
+ (tmp_path / "etc/debian_version").write_text("12\n")
+ (tmp_path / "var/lib/update-notifier/updates-available").write_text("\n23 updates can be applied immediately.\n4 of these updates are standard security updates.\n")
+ (tmp_path / "etc/apt/apt.conf.d/20auto-upgrades").write_text('APT::Periodic::Update-Package-Lists "1";\nAPT::Periodic::Unattended-Upgrade "1";\n')
+ for name in ("vmlinuz-6.8.0-9-generic", "vmlinuz-6.8.0-84-generic", "vmlinuz-6.8.0-85-generic", "vmlinuz", "initrd.img-6.8.0-99-generic"):
+ (tmp_path / "boot" / name).write_text("")
+ monkeypatch.setattr(collector, "HOST_ROOT", tmp_path)
+
+ info = collector.collect_updates("6.8.0-84-generic", True)
+ assert (info["updates_pending"], info["updates_security"], info["auto_updates"], info["reboot_kernel"]) == (23, 4, True, "6.8.0-85-generic")
+ assert "reboot_kernel" not in collector.collect_updates("6.8.0-85-generic", True)
+ assert "reboot_kernel" not in collector.collect_updates("6.8.0-84-generic", False)
+
+
+def test_interfaces_report_their_network_and_traffic_since_the_last_look(tmp_path, monkeypatch):
+ net = tmp_path / "1/net"
+ net.mkdir(parents=True)
+ header = "Inter-| Receive | Transmit\n face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed\n"
+ row = lambda name, rx, tx: f"{name}: {rx} 1 0 0 0 0 0 0 {tx} 1 0 0 0 0 0 0\n" # noqa: E731
+ (net / "route").write_text("Iface\tDestination\tGateway\tFlags\tRefCnt\tUse\tMetric\tMask\n" "eth0\t00000000\t0100000A\t0003\t0\t0\t0\t00000000\n" "eth0\t0000000A\t00000000\t0001\t0\t0\t0\t00FFFFFF\n")
+ monkeypatch.setattr(collector, "HOST_PROC", tmp_path)
+ monkeypatch.setattr(collector, "HOST_ROOT", tmp_path)
+ collector._interface_previous.clear()
+
+ (net / "dev").write_text(header + row("lo", 5, 5) + row("eth0", 1000, 2000) + row("veth12ab", 9, 9) + row("idle0", 0, 0))
+ assert collector.collect_interfaces(now=100.0) == [{"name": "eth0", "network": "10.0.0.0/24"}]
+ (net / "dev").write_text(header + row("eth0", 1000 + 4 * collector.MiB, 2000 + 2 * collector.MiB))
+ assert collector.collect_interfaces(now=102.0) == [{"name": "eth0", "network": "10.0.0.0/24", "rx_mbps": 2.0, "tx_mbps": 1.0}]
+ collector._interface_previous.clear()
+
+
+# --- data that needs more than the collector has ----------------------------------------------
+
+def _fake_host_proc(tmp_path):
+ """A host /proc with sshd listening on tcp/22, a resolver on udp/53 and a process that names itself oddly."""
+ net = tmp_path / "1/net"
+ net.mkdir(parents=True)
+ header = " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n"
+ (net / "tcp").write_text(header + " 0: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 1001 1 x\n"
+ " 1: 0100007F:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 1003 1 x\n"
+ " 2: 0A00000C:D431 0A000015:01BB 01 00000000:00000000 00:00000000 00000000 1000 0 1009 1 x\n")
+ (net / "udp").write_text(header + " 10: 3500007F:0035 00000000:0000 07 00000000:00000000 00:00000000 00000000 101 0 1002 2 x 0\n")
+ for pid, name, inodes in ((1, "systemd", [5]), (812, "sshd", [1001, 7]), (640, "systemd-resolve", [1002]), (3000, "evil\x1b[31m\nname", [1003]), (3001, "client", [1009])):
+ fd = tmp_path / str(pid) / "fd"
+ fd.mkdir(parents=True, exist_ok=True)
+ (tmp_path / str(pid) / "comm").write_text(name + "\n")
+ for number, inode in enumerate(inodes):
+ os.symlink(f"socket:[{inode}]", fd / str(number))
+ os.symlink("/etc/shadow", fd / "99")
+ return tmp_path
+
+
+def test_port_owners_name_the_process_behind_each_listening_port(tmp_path):
+ proc = _fake_host_proc(tmp_path)
+
+ assert system_helper.listening_sockets(proc) == {1001: ("tcp", 22), 1003: ("tcp", 8080), 1002: ("udp", 53)} # the connected socket is not a listener
+ owners = system_helper.port_owners(proc)
+ assert owners == [{"proto": "tcp", "port": 22, "process": "sshd"}, {"proto": "udp", "port": 53, "process": "systemd-resolve"}, {"proto": "tcp", "port": 8080, "process": "evil?[31m?name"}]
+ assert system_helper.port_owners(tmp_path / "missing") == []
+
+
+def test_the_collector_only_trusts_a_fresh_well_formed_port_owners_file(tmp_path):
+ path = tmp_path / "ports.json"
+ now = 1_000_000.0
+ stamp = datetime.fromtimestamp(now, timezone.utc).isoformat(timespec="seconds")
+ assert collector.collect_port_owners(path, now) is None # helper not running
+ path.write_text(json.dumps({"generated_at": stamp, "listeners": [{"proto": "tcp", "port": 22, "process": "sshd"}, {"proto": "icmp", "port": 1, "process": "x"}, {"proto": "tcp", "port": "22", "process": "x"}, "junk"]}))
+ assert collector.collect_port_owners(path, now) == [{"proto": "tcp", "port": 22, "process": "sshd"}]
+ assert collector.collect_port_owners(path, now + 3600) is None # stale
+ path.write_text("{not json")
+ assert collector.collect_port_owners(path, now) is None
+ link = tmp_path / "link.json"
+ os.symlink(path, link)
+ assert collector.collect_port_owners(link, now) is None # never follows a symlink
+
+
+def test_docker_disk_usage_and_port_owners_are_validated_before_they_are_stored(app):
+ system = {
+ "docker_disk": {"images_gb": 41.2, "images_unused_gb": 38.0, "build_cache_gb": 2.5, "build_cache_unused_gb": float("inf"), "images": 60, "images_unused": 44, "names": ["secret"]},
+ "disk_io_errors": 3,
+ "listener_owners": [{"proto": "tcp", "port": 22, "process": "sshd"}, {"proto": "tcp", "port": 99999, "process": "x"}, {"proto": "tcp", "port": 80, "process": "a" * 200}, {"proto": "tcp", "port": 81, "process": ""}],
+ }
+ ingest(app, {"server": {"system": system}, "host": {"cpu_utilization_pct": 5}})
+ stored = overview_server(app)["system"]
+
+ assert stored["docker_disk"] == {"images_gb": 41.2, "images_unused_gb": 38.0, "build_cache_gb": 2.5, "images": 60, "images_unused": 44}
+ assert stored["disk_io_errors"] == 3
+ assert stored["listener_owners"] == [{"proto": "tcp", "port": 22, "process": "sshd"}, {"proto": "tcp", "port": 80, "process": "a" * 64}]
+ # A collector without the helper sends no list at all, which is different from an empty one.
+ ingest(app, {"server": {"system": {"kernel": "6.8"}}, "host": {"cpu_utilization_pct": 5}})
+ assert "listener_owners" not in overview_server(app)["system"]
+
+
+def test_disk_error_counter_sums_the_disks_that_have_one(tmp_path, monkeypatch):
+ for disk, value in (("sda", "0x3"), ("sdb", "0x0a"), ("nvme0n1", None)):
+ (tmp_path / "sys/block" / disk / "device").mkdir(parents=True)
+ if value:
+ (tmp_path / "sys/block" / disk / "device/ioerr_cnt").write_text(value + "\n")
+ monkeypatch.setattr(collector, "HOST_ROOT", tmp_path)
+ assert collector.disk_io_errors() == 13
+ (tmp_path / "sys/block/sda/device/ioerr_cnt").unlink()
+ (tmp_path / "sys/block/sdb/device/ioerr_cnt").unlink()
+ assert collector.disk_io_errors() is None
+
+
+def test_docker_disk_usage_is_asked_for_rarely_and_survives_an_old_proxy(monkeypatch):
+ calls = []
+ answer = {"images_bytes": 2 * collector.GiB, "images_unused_bytes": collector.GiB, "build_cache_bytes": 0, "build_cache_unused_bytes": 0, "images": 5, "images_unused": 2}
+ monkeypatch.setattr(collector, "_docker_request", lambda path, endpoint: calls.append(endpoint) or answer)
+ monkeypatch.setattr(collector, "_docker_disk", {"value": None, "next": 0.0})
+
+ collector._remember_docker_disk("sock", now=10.0)
+ collector._remember_docker_disk("sock", now=20.0)
+ assert calls == ["/system/df"] and collector._docker_disk["value"] == {"images_gb": 2.0, "images_unused_gb": 1.0, "build_cache_gb": 0.0, "build_cache_unused_gb": 0.0, "images": 5, "images_unused": 2}
+
+ def refused(path, endpoint):
+ raise ValueError("403")
+ monkeypatch.setattr(collector, "_docker_request", refused)
+ collector._remember_docker_disk("sock", now=10.0 + collector.DOCKER_DISK_EVERY_SECONDS + 1)
+ assert collector._docker_disk["value"]["images_gb"] == 2.0 # the last known figure stays