swarm-ui: make it installable as a PWA

Closes #4282. mara: "scope looks good" — approving the plan posted
there (manifest + icons + minimal shell-only service worker + iOS meta
tags) and both explicit questions (network-first-with-offline-fallback,
never cache /api/*).

docs/web-ui/design-guide.md's "Layout & viewport" section already
asserted swarm-ui is installable as a PWA — this is what actually backs
it.

- manifest.webmanifest: name/icons/start_url/standalone display, theme
  #cba6f7 / background #1e1e2e matching the mocha --purple/--bg values.
- sw.js: plain JS, not TypeScript — the DOM lib swarm-ui's own tsconfig
  uses and the WebWorker lib a service worker's globals need are
  mutually exclusive in one tsc program, not worth a second tsconfig for
  a self-contained ~100-line file. Scoped to the app shell only, never
  touches /api/* at all, network-first with offline-fallback-to-cache
  (not cache-first) since main.js/main.css are unhashed filenames and a
  cache-first SW would risk wedging an operator on stale JS after a
  deploy.
- index.html: manifest link, theme-color meta, iOS
  apple-mobile-web-app-* tags (Safari ignores the manifest spec).
- main.tsx: feature-detected SW registration.
- branding/hyperhive-maskable.svg: hyperhive.svg's own artwork already
  fills nearly its whole canvas, so a maskable icon needs a padded
  variant or an OS mask crops the outer ring/corner brackets — embeds
  the original via a scaled <image> ref rather than duplicating markup.
- nix/packages/swarm-ui.nix: rasterizes icon-192/512/512-maskable.png
  from the branding SVGs at build time via librsvg, rather than
  checking in static PNGs.

Verified for real: typecheck+build green, and a real headless-chromium
tab driven over CDP confirms the service worker registers and becomes
the active controller, and a simulated-offline reload still serves the
full cached shell rather than a browser error page. nix build .#swarm-ui
also verified green, including the rasterized icon output.
This commit is contained in:
iris 2026-09-12 00:59:50 +02:00 committed by mara
commit 9ad700a1a1
8 changed files with 205 additions and 1 deletions

View file

@ -0,0 +1,13 @@
<svg width="300" height="300" viewBox="0 0 300 300" role="img" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>HyperHive (maskable)</title>
<desc>Padded variant of hyperhive.svg for Android adaptive/maskable icon masks —
the OS crops a maskable icon to an arbitrary shape (circle, squircle, ...) and
only guarantees the inner ~80% "safe zone" survives; hyperhive.svg's own
artwork already fills nearly its whole canvas (a ~5% margin, meant for a
plain square/rounded-square favicon, not an aggressive crop), so used
directly here it would lose its outer ring and corner brackets on a circular
mask. This wrapper embeds the original at 80% scale, centered, over a
matching solid background instead of duplicating its markup.</desc>
<rect width="300" height="300" fill="#0a0600"/>
<image xlink:href="hyperhive.svg" x="30" y="30" width="240" height="240"/>
</svg>

After

Width:  |  Height:  |  Size: 923 B

View file

@ -16,6 +16,17 @@
// dist/static/swarm-ui.css served at /static/swarm-ui.css — just the
// shared base reset now (@import resolved
// from @hive/shared), NOT component styles
// dist/manifest.webmanifest served at /manifest.webmanifest (PWA)
// dist/sw.js served at /sw.js (PWA) — plain JS, no
// esbuild pass needed (see its own
// top comment for why); copied as-is.
//
// PWA icons (icon-192.png/icon-512.png/icon-512-maskable.png) are NOT
// produced here — like favicon.svg, they're rasterized from
// branding/*.svg and copied in by nix/packages/swarm-ui.nix's
// installPhase, outside the npm tree this script builds. A plain `npm
// run build` here has no `/icon-*.png`, same as it's always had no
// `/favicon.svg`.
//
// Not yet wired into any Rust binary's `ServeDir` — swarm-controller
// only serves `/health` today (see swarm-controller/README.md); this
@ -62,5 +73,7 @@ for (const entry of ["colors.css", "theme.css", "swarm-ui.css"]) {
}
copyFileSync(src("index.html"), dist("index.html"));
copyFileSync(src("manifest.webmanifest"), dist("manifest.webmanifest"));
copyFileSync(src("sw.js"), dist("sw.js"));
console.log("swarm-ui build ok →", dist(""));

View file

@ -5,6 +5,19 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>hyperhive swarm</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<!-- PWA installability — design-guide.md's "Layout & viewport"
section already asserted swarm-ui is installable; this is what
actually backs it. `manifest.webmanifest` + icons are
nix-packaged (nix/packages/swarm-ui.nix), same as favicon.svg
above — not part of the plain npm build output. -->
<link rel="manifest" href="/manifest.webmanifest" />
<meta name="theme-color" content="#cba6f7" />
<!-- Safari ignores the manifest spec entirely — these are its own
"Add to Home Screen" affordances, same icon/name the manifest
already declares for every other browser. -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-title" content="swarm" />
<link rel="apple-touch-icon" href="/icon-192.png" />
<link rel="stylesheet" href="/static/colors.css" />
<link rel="stylesheet" href="/static/theme.css" />
<link rel="stylesheet" href="/static/swarm-ui.css" />

View file

@ -5,3 +5,17 @@ const root = document.getElementById("root");
if (root) {
render(<App />, root);
}
// PWA installability — see sw.js's own top comment for
// what it does and does not cache. Feature-detected: older browsers
// without service-worker support just don't get the install affordance,
// nothing here depends on it existing.
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker.register("/sw.js").catch((err: unknown) => {
// Never surfaces to the operator — a failed SW registration means
// "not installable this session," not "the app is broken."
console.error("swarm-ui: service worker registration failed", err);
});
});
}

View file

@ -0,0 +1,14 @@
{
"name": "hyperhive swarm",
"short_name": "swarm",
"description": "Swarm-level operator UI — agent roster, hives, jobs, issues across the swarm.",
"start_url": "/",
"display": "standalone",
"background_color": "#1e1e2e",
"theme_color": "#cba6f7",
"icons": [
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" },
{ "src": "/icon-512-maskable.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
]
}

View file

@ -0,0 +1,109 @@
// Minimal service worker — satisfies PWA installability so swarm-ui can
// actually be "Add to Home Screen"d (design-guide.md's "Layout &
// viewport" section already asserted this as fact before this service
// worker existed to make it true). NOT a data cache: scoped to the app
// shell only (the SPA's own HTML/JS/CSS/manifest), and explicitly never
// touches `/api/*` — an ops dashboard silently showing stale status from
// a cached fetch would be worse than showing nothing (mara: "scope looks
// good" — approving that as a hard rule, not a short-TTL middle ground).
//
// Network-first for the shell, not cache-first: `main.js`/`main.css` are
// unhashed filenames, so a cache-first strategy would risk wedging an
// operator on yesterday's JS after a deploy until they manually cleared
// it (a deploy changes the nix store path serving these but not the URL
// the browser cached against — a separate, already-filed fix). This SW
// only ever serves its cache on a FAILED fetch (offline/flaky network),
// never in preference to a successful network response.
//
// Plain JS, not TypeScript, deliberately — the DOM lib swarm-ui's own
// tsconfig uses and the WebWorker lib a service worker's globals
// (`self`, `ExtendableEvent`, `FetchEvent`, `caches`, ...) need are
// mutually exclusive in one tsc program, and this file is small/
// self-contained enough that a second tsconfig just to typecheck it
// isn't worth the config surface. Same treatment `build.mjs` already
// gets in this package.
//
// CACHE_VERSION is bumped by hand for now — once the filenames above are
// content-hashed, the cache name can derive from the build itself and
// this manual step goes away.
const CACHE_VERSION = "v1";
const CACHE_NAME = `swarm-ui-shell-${CACHE_VERSION}`;
// Every navigation (any client-side route wouter handles — /agents,
// /hives, ...) falls back to this single cached document when offline,
// same as nginx's own `try_files $uri /index.html` does online: the SPA
// only ever has one real HTML document regardless of path.
const SHELL_DOCUMENT = "/";
const SHELL_ASSETS = [
SHELL_DOCUMENT,
"/static/main.js",
"/static/main.css",
"/static/colors.css",
"/static/theme.css",
"/static/swarm-ui.css",
"/manifest.webmanifest",
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(SHELL_ASSETS)),
);
// Take over from any previous SW as soon as this one's installed — an
// operator installing the PWA for the first time (or after a SW
// update) shouldn't need a second reload before it's in control.
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((names) =>
Promise.all(
names
.filter((name) => name !== CACHE_NAME)
.map((name) => caches.delete(name)),
),
)
.then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
// Same-origin only, and never `/api/*` — that's swarm-controller's
// live data, not the static shell this SW is scoped to. Letting the
// event fall through (no `respondWith`) means the browser handles it
// exactly as if this SW didn't exist.
if (url.origin !== self.location.origin || url.pathname.startsWith("/api/")) {
return;
}
// Any navigation (full-page load or wouter's client-side route change
// reaching the network) — network-first, falling back to the cached
// shell document on failure regardless of which path was requested,
// since every route renders the same SPA shell.
if (event.request.mode === "navigate") {
event.respondWith(
fetch(event.request).catch(() => caches.match(SHELL_DOCUMENT)),
);
return;
}
// A specific shell asset — network-first, cache the fresh response for
// next time, fall back to whatever's cached on failure. Anything not
// in this list (a future asset this SW doesn't know about yet) passes
// straight through untouched rather than silently going uncached.
if (!SHELL_ASSETS.includes(url.pathname)) {
return;
}
event.respondWith(
fetch(event.request)
.then((response) => {
const copy = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, copy));
return response;
})
.catch(() => caches.match(event.request)),
);
});

View file

@ -197,6 +197,7 @@ in
# `packages.default`'s closure.
swarm-ui = pkgs.callPackage ./swarm-ui.nix {
branding-svg = ../../branding/hyperhive.svg;
branding-svg-maskable = ../../branding/hyperhive-maskable.svg;
};
# Bundled browser assets — see ./frontend.nix. Output is

View file

@ -1,4 +1,9 @@
{ buildNpmPackage, branding-svg }:
{
buildNpmPackage,
branding-svg,
branding-svg-maskable,
librsvg,
}:
# Static build of the swarm-level UI shell (project-bootstrap scope:
# empty start page, no functionality yet — see
@ -31,6 +36,14 @@
# `./frontend.nix` copies for the dashboard) is likewise copied in
# during install — it lives outside the npm tree.
# PWA icons: rasterized from the branding SVGs at build time via
# `librsvg`'s `rsvg-convert` rather than checking in static PNGs, so the
# SVG stays the one thing to update if the mark ever changes.
# `branding-svg-maskable` is a separate, padded source (see
# `branding/hyperhive-maskable.svg`'s own comment) — `hyperhive.svg`'s
# artwork already fills nearly its whole canvas, so a maskable icon needs
# real margin or an OS mask crops into it.
buildNpmPackage {
pname = "hyperhive-swarm-ui";
version = "0.0.0";
@ -39,6 +52,8 @@ buildNpmPackage {
# See `./frontend.nix`'s comment on the same line.
npmDepsHash = builtins.readFile ../../frontend/npm-deps-hash;
nativeBuildInputs = [ librsvg ];
buildPhase = ''
runHook preBuild
npm run build --workspace=packages/swarm-ui
@ -51,6 +66,18 @@ buildNpmPackage {
mkdir -p $out
cp -r packages/swarm-ui/dist/. $out/
cp ${branding-svg} $out/favicon.svg
rsvg-convert -w 192 -h 192 ${branding-svg} -o $out/icon-192.png
rsvg-convert -w 512 -h 512 ${branding-svg} -o $out/icon-512.png
# `branding-svg-maskable` embeds `branding-svg` via a relative
# `<image>` reference (see that file's own comment) — each is passed
# in as its own single-file store path, so the sibling reference
# only resolves once both live together in one directory again.
mkdir -p "$TMPDIR/branding"
cp ${branding-svg} "$TMPDIR/branding/hyperhive.svg"
cp ${branding-svg-maskable} "$TMPDIR/branding/hyperhive-maskable.svg"
rsvg-convert -w 512 -h 512 "$TMPDIR/branding/hyperhive-maskable.svg" \
-o $out/icon-512-maskable.png
runHook postInstall
'';