Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Add service worker for offline app-shell and low-bandwidth asset caching

[._.]/ Adam Eivy48e41d43dc32
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
new file mode 100644
index 0000000000..9b45065c80
--- /dev/null
+++ b/.changelog/NEXT.md
@@ -0,0 +1,5 @@
+# Unreleased
+
+## Features
+
+- **PortOS now installs a service worker for offline app-shell loading and low-bandwidth caching** — the modern replacement for the long-deprecated AppCache manifest. After the first online visit, the built app shell (`index.html`) and the content-hashed JS/CSS chunks are cached, so the UI loads instantly on repeat visits, keeps rendering when the server is briefly unreachable (flaky Tailnet links), and stops re-pulling megabytes of vendor JS on every navigation over a slow connection. Google Fonts and static public assets (icons, textures, manifest) are cached too. Real-time and large/dynamic routes — `/api/*`, `/socket.io/*`, and `/data/*` media — are **never** cached, so live data and streamed assets always hit the network (HTTP Range preserved for `/data`). Navigations stay network-first so a fresh build is always picked up when online, and the existing build-id / stale-chunk-reload machinery still handles "the server rebuilt while a tab was open." The worker registers only in a production **secure context** (HTTPS, or `localhost`) — it is a progressive enhancement that silently no-ops over a plain-HTTP Tailnet hostname and in the Vite dev server (where it also tears down any stale worker). Implemented as a hand-rolled worker (`client/public/sw.js`) with no new dependency; registration lives in `client/src/lib/registerServiceWorker.js`. The PWA manifest gained explicit `id`/`scope` for a deterministic installed-app identity.
diff --git a/client/public/manifest.json b/client/public/manifest.json
index 85406a62fb..7c51154c24 100644
--- a/client/public/manifest.json
+++ b/client/public/manifest.json
@@ -2,6 +2,8 @@
"name": "PortOS",
"short_name": "PortOS",
"description": "Personal Operating System",
+ "id": "/",
+ "scope": "/",
"start_url": "/",
"display": "standalone",
"background_color": "#01051F",
diff --git a/client/public/sw.js b/client/public/sw.js
new file mode 100644
index 0000000000..fa5a0a40a7
--- /dev/null
+++ b/client/public/sw.js
@@ -0,0 +1,221 @@
+/* PortOS service worker — offline app-shell + low-bandwidth asset caching.
+ *
+ * This is the modern replacement for the long-deprecated AppCache manifest.
+ * It caches the built app shell (index.html) and the content-hashed JS/CSS
+ * chunks so PortOS loads instantly on repeat visits, keeps working when the
+ * server is briefly unreachable (flaky Tailnet links), and stops re-pulling
+ * megabytes of vendor JS on every navigation over a slow connection.
+ *
+ * Design constraints specific to PortOS:
+ * - `/api/*`, `/socket.io/*` and `/data/*` are NEVER cached. They are
+ * real-time / large / user-specific — the app is inherently online for
+ * data, only the *shell* is made offline-capable here.
+ * - Vite emits content-hashed filenames under `/assets/`, so those are
+ * immutable and safe to serve cache-first. A new build produces new
+ * filenames (cache miss → fetched fresh), so cache-first never pins stale
+ * code. The existing build-id / stale-chunk-reload machinery
+ * (server/lib/buildId.js, client/src/utils/staleChunkReload.js) still
+ * handles the "server rebuilt while a tab was open" case.
+ * - Navigations are network-first so a fresh build is always picked up when
+ * online; the cached shell is the offline fallback only.
+ *
+ * Bump CACHE_VERSION to invalidate every cache (e.g. when these strategies
+ * change). Changing this file's bytes is itself what triggers the browser to
+ * install the updated worker.
+ */
+
+const CACHE_VERSION = 'v1';
+const SHELL_CACHE = `portos-shell-${CACHE_VERSION}`;
+const ASSET_CACHE = `portos-assets-${CACHE_VERSION}`;
+const STATIC_CACHE = `portos-static-${CACHE_VERSION}`;
+const FONT_CACHE = `portos-fonts-${CACHE_VERSION}`;
+
+const CURRENT_CACHES = new Set([SHELL_CACHE, ASSET_CACHE, STATIC_CACHE, FONT_CACHE]);
+
+// Stable key the offline shell is stored under, independent of the request URL
+// (every SPA navigation resolves to the same index.html on the server).
+const SHELL_KEY = '/index.html';
+
+// Cap the immutable-asset cache so many rebuilds don't grow it without bound.
+// Old build chunks accumulate here (their hashed names never collide); trim to
+// the most-recently-added entries. Generous because a single build's chunk set
+// is well under this.
+const ASSET_CACHE_MAX_ENTRIES = 120;
+
+// Same-origin static assets that are safe to serve stale-while-revalidate:
+// fonts, icons, the PWA manifest, sky textures, the logo. Matched by path.
+const STATIC_PATH_RE = /^\/(fonts|sky)\//;
+const STATIC_FILE_RE = /^\/(manifest\.json|favicon\.(?:ico|svg)|apple-touch-icon\.png|icon-\d+\.png|portos-logo\.png)$/;
+
+// External font hosts — cache-first is a big low-bandwidth win (Google serves
+// these with long max-age already, but the browser HTTP cache is evicted more
+// aggressively than a named SW cache).
+const FONT_HOSTS = new Set(['fonts.googleapis.com', 'fonts.gstatic.com']);
+
+self.addEventListener('install', (event) => {
+ // Adopt the new worker as soon as it's installed. Combined with network-first
+ // navigations + the app's stale-chunk reload, this is safe: an open tab keeps
+ // its in-memory JS, and its next navigation re-fetches the fresh shell.
+ self.skipWaiting();
+ event.waitUntil(
+ caches.open(SHELL_CACHE).then((cache) =>
+ // Pre-warm the shell so the very first offline navigation works even if
+ // the user never revisited "/" online. Best-effort — a failure here must
+ // not abort activation.
+ cache.add(new Request('/', { cache: 'reload' })).catch(() => {})
+ )
+ );
+});
+
+self.addEventListener('activate', (event) => {
+ event.waitUntil(
+ (async () => {
+ // Enabling navigation preload (speeds up network-first navigations) and
+ // pruning caches from older worker versions are independent — run them
+ // concurrently so activation isn't lengthened on a slow link.
+ const enablePreload = self.registration.navigationPreload
+ ? self.registration.navigationPreload.enable().catch(() => {})
+ : Promise.resolve();
+ const cleanup = caches.keys().then((names) =>
+ Promise.all(
+ names
+ .filter((name) => name.startsWith('portos-') && !CURRENT_CACHES.has(name))
+ .map((name) => caches.delete(name))
+ )
+ );
+ await Promise.all([enablePreload, cleanup]);
+ await self.clients.claim();
+ })()
+ );
+});
+
+// Allow the page to trigger an immediate takeover (e.g. an "update ready"
+// prompt) without a full reload race.
+self.addEventListener('message', (event) => {
+ if (event.data && event.data.type === 'SKIP_WAITING') self.skipWaiting();
+});
+
+self.addEventListener('fetch', (event) => {
+ const { request } = event;
+
+ // Only GET is cacheable; everything else (POST/PUT/socket upgrades) passes
+ // straight through to the network.
+ if (request.method !== 'GET') return;
+
+ let url;
+ try {
+ url = new URL(request.url);
+ } catch {
+ return; // Malformed URL — let the browser handle it.
+ }
+
+ const isSameOrigin = url.origin === self.location.origin;
+
+ // External font stylesheets + font files: cache-first.
+ if (FONT_HOSTS.has(url.hostname)) {
+ event.respondWith(cacheFirst(request, FONT_CACHE));
+ return;
+ }
+
+ // Never touch other cross-origin requests.
+ if (!isSameOrigin) return;
+
+ // Never cache dynamic / real-time / large-media routes. Let them hit the
+ // network directly (also preserves HTTP Range for /data media).
+ if (
+ url.pathname.startsWith('/api/') ||
+ url.pathname.startsWith('/socket.io/') ||
+ url.pathname.startsWith('/data/')
+ ) {
+ return;
+ }
+
+ // SPA navigations: network-first, fall back to the cached shell offline.
+ if (request.mode === 'navigate') {
+ event.respondWith(navigationHandler(event));
+ return;
+ }
+
+ // Content-hashed, immutable build output: cache-first.
+ if (url.pathname.startsWith('/assets/')) {
+ event.respondWith(cacheFirst(request, ASSET_CACHE, ASSET_CACHE_MAX_ENTRIES));
+ return;
+ }
+
+ // Static public assets (icons, fonts, manifest, textures): stale-while-revalidate.
+ if (STATIC_PATH_RE.test(url.pathname) || STATIC_FILE_RE.test(url.pathname)) {
+ event.respondWith(staleWhileRevalidate(request, STATIC_CACHE));
+ return;
+ }
+
+ // Anything else same-origin: try network, fall back to any cached copy.
+ event.respondWith(networkFallingBackToCache(request));
+});
+
+// --- strategies ---------------------------------------------------------
+
+async function navigationHandler(event) {
+ const cache = await caches.open(SHELL_CACHE);
+ try {
+ // Prefer the browser's navigation-preload response when available.
+ const preload = await event.preloadResponse;
+ const response = preload || (await fetch(event.request));
+ if (response && response.ok) {
+ cache.put(SHELL_KEY, response.clone()).catch(() => {});
+ }
+ return response;
+ } catch {
+ const cached = await cache.match(SHELL_KEY);
+ if (cached) return cached;
+ // Last resort: whatever we have for this exact navigation URL.
+ const exact = await caches.match(event.request);
+ if (exact) return exact;
+ return Response.error();
+ }
+}
+
+async function cacheFirst(request, cacheName, maxEntries) {
+ const cache = await caches.open(cacheName);
+ const cached = await cache.match(request);
+ if (cached) return cached;
+ const response = await fetch(request);
+ // Cache successful basic/opaque responses. Opaque (cross-origin fonts) can't
+ // be inspected but are safe to store and replay.
+ if (response && (response.ok || response.type === 'opaque')) {
+ await cache.put(request, response.clone());
+ if (maxEntries) trimCache(cache, maxEntries);
+ }
+ return response;
+}
+
+async function staleWhileRevalidate(request, cacheName) {
+ const cache = await caches.open(cacheName);
+ const cached = await cache.match(request);
+ const network = fetch(request)
+ .then((response) => {
+ if (response && response.ok) cache.put(request, response.clone()).catch(() => {});
+ return response;
+ })
+ .catch(() => null);
+ return cached || (await network) || Response.error();
+}
+
+async function networkFallingBackToCache(request) {
+ try {
+ return await fetch(request);
+ } catch {
+ const cached = await caches.match(request);
+ if (cached) return cached;
+ return Response.error();
+ }
+}
+
+// Trim a cache to its N most-recently-added entries (cache.keys() preserves
+// insertion order, so the oldest are at the front). Takes an already-open
+// cache handle. Fire-and-forget; only enumerates on the rare over-cap put.
+async function trimCache(cache, maxEntries) {
+ const keys = await cache.keys();
+ if (keys.length <= maxEntries) return;
+ const excess = keys.slice(0, keys.length - maxEntries);
+ await Promise.all(excess.map((key) => cache.delete(key)));
+}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index dd4bf3e60b..cae386ffa5 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -93,6 +93,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `mediaNavigation.js` | `getAdjacentMedia(items, item)` — prev/next computation for lightboxes. |
| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. |
| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image src (`imageUrl` → served `image:<file>` bytes → null). Shared by MoodBoardDetail + MoodBoardReferenceStrip. |
+| `registerServiceWorker.js` | `registerServiceWorker()` / `unregisterServiceWorkers()` — wires up the offline app-shell + low-bandwidth asset-caching service worker (`public/sw.js`). Registers only in a production secure context (HTTPS or localhost); no-ops over plain-HTTP Tailnet and tears down any stale SW in dev. Called once from `main.jsx`. |
| `safeStorage.js` | `safeReadStorage` / `safeWriteStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage) and treats missing storage as absent (`null`). Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme` / `useCitySettings`. |
| `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. |
| `sketchCanvas.js` | Pure stroke model + 2D-context renderer for the media annotation canvas (`createStroke`, `appendPoint`, `undoStrokes`, `drawStrokes`, `clampSize`). Points stored in natural-pixel space; erase strokes use `destination-out`. Used by `AnnotationCanvas.jsx` / `MediaAnnotate.jsx` (#2036). |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 4609395e35..c31883e0b4 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -66,6 +66,7 @@ export * from './manuscriptFormat.js';
export * from './mediaNavigation.js';
export * from './mediaSearch.js';
export * from './moodBoardItemSrc.js';
+export * from './registerServiceWorker.js';
export * from './safeStorage.js';
export * from './sameJsonShape.js';
export * from './sketchCanvas.js';
diff --git a/client/src/lib/registerServiceWorker.js b/client/src/lib/registerServiceWorker.js
new file mode 100644
index 0000000000..cceaf09f4d
--- /dev/null
+++ b/client/src/lib/registerServiceWorker.js
@@ -0,0 +1,81 @@
+// Service-worker registration — the modern replacement for AppCache, giving
+// PortOS an offline-capable app shell and low-bandwidth asset caching.
+//
+// The worker itself lives at `client/public/sw.js` (served from `/sw.js` at the
+// site root so its scope is `/`). This module only decides *whether* to
+// register it and wires the register/unregister lifecycle. It is intentionally
+// side-effect-free at import time — call `registerServiceWorker()` explicitly
+// (from `main.jsx`) so the barrel import in tests stays inert.
+//
+// Secure-context note: `navigator.serviceWorker` only exists in a secure
+// context — HTTPS, or `http://localhost`. PortOS accessed over a plain-HTTP
+// Tailnet hostname (no cert provisioned) is NOT a secure context, so the
+// feature simply no-ops there. Provisioning a cert (`npm run setup:cert`)
+// flips the app to HTTPS and the worker activates. This is a progressive
+// enhancement — the app is fully functional without it.
+
+const SW_URL = '/sw.js';
+
+// True only under the Vite dev server, where a caching SW would fight
+// hot-module reload. `import.meta.hot` is the HMR handle the dev server
+// injects; a production `vite build` statically replaces it with `undefined`.
+// We deliberately do NOT gate on `import.meta.env.PROD`: Vite derives that from
+// `NODE_ENV`, and a CoS/worktree (or any) build shell that exports
+// `NODE_ENV=development` would flip it to `false` and silently disable the SW
+// in a real production bundle. `import.meta.hot` depends only on the dev-server
+// vs. build distinction, not on the ambient environment.
+function isDevServer() {
+ return Boolean(import.meta.hot);
+}
+
+function swSupported() {
+ return typeof navigator !== 'undefined' && 'serviceWorker' in navigator;
+}
+
+/**
+ * Register the PortOS service worker in production secure contexts, and tear
+ * down any previously-registered worker everywhere else (notably the dev
+ * server, so a stale prod SW can't shadow `npm run dev`).
+ *
+ * Registration is deferred to the window `load` event so it never competes
+ * with first paint for bandwidth — the whole point is a faster first load.
+ *
+ * @returns {void}
+ */
+export function registerServiceWorker() {
+ if (!swSupported()) return;
+
+ if (isDevServer()) {
+ // Dev server over a secure context: make sure no production SW is lingering
+ // from a previous `npm start` on the same origin (it would shadow HMR).
+ unregisterServiceWorkers();
+ return;
+ }
+
+ const register = () => {
+ navigator.serviceWorker.register(SW_URL).catch((err) => {
+ // A registration failure is non-fatal — the app runs uncached.
+ console.warn(`⚠️ Service worker registration failed: ${err?.message || err}`);
+ });
+ };
+
+ // swSupported() already guaranteed a browser context (navigator.serviceWorker
+ // exists only in a secure browser context), so window/document are present.
+ if (document.readyState === 'complete') {
+ register();
+ } else {
+ window.addEventListener('load', register, { once: true });
+ }
+}
+
+/**
+ * Unregister every service worker for this origin. Used to disable caching in
+ * dev, or as an escape hatch if the SW ever needs to be pulled.
+ *
+ * @returns {Promise<void>}
+ */
+export async function unregisterServiceWorkers() {
+ if (!swSupported() || !navigator.serviceWorker.getRegistrations) return;
+ const registrations = await navigator.serviceWorker.getRegistrations().catch(() => []);
+ await Promise.all(registrations.map((reg) => reg.unregister().catch(() => {})));
+}
diff --git a/client/src/lib/registerServiceWorker.test.js b/client/src/lib/registerServiceWorker.test.js
new file mode 100644
index 0000000000..54cee98a0d
--- /dev/null
+++ b/client/src/lib/registerServiceWorker.test.js
@@ -0,0 +1,69 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { registerServiceWorker, unregisterServiceWorkers } from './registerServiceWorker.js';
+
+// These tests run in the node env in CI (no jsdom) AND in the client's own
+// jsdom vitest, so `navigator`/`window`/`document` are stubbed per-case.
+// `registerServiceWorker()` picks its branch from `import.meta.hot` (dev server
+// → tear down; production build → register), whose ambient value differs
+// between those two runners — so the register-path assertions below are
+// deliberately branch-agnostic. The production register path is proved
+// end-to-end by the headless-Chrome verification, not here.
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('unregisterServiceWorkers', () => {
+ it('no-ops when service workers are unsupported', async () => {
+ vi.stubGlobal('navigator', {});
+ await expect(unregisterServiceWorkers()).resolves.toBeUndefined();
+ });
+
+ it('unregisters every existing registration', async () => {
+ const unregA = vi.fn().mockResolvedValue(true);
+ const unregB = vi.fn().mockResolvedValue(true);
+ vi.stubGlobal('navigator', {
+ serviceWorker: {
+ getRegistrations: vi.fn().mockResolvedValue([{ unregister: unregA }, { unregister: unregB }]),
+ },
+ });
+ await unregisterServiceWorkers();
+ expect(unregA).toHaveBeenCalledOnce();
+ expect(unregB).toHaveBeenCalledOnce();
+ });
+
+ it('swallows a failing getRegistrations', async () => {
+ vi.stubGlobal('navigator', {
+ serviceWorker: { getRegistrations: vi.fn().mockRejectedValue(new Error('nope')) },
+ });
+ await expect(unregisterServiceWorkers()).resolves.toBeUndefined();
+ });
+});
+
+describe('registerServiceWorker', () => {
+ it('no-ops without service worker support', () => {
+ vi.stubGlobal('navigator', {});
+ expect(() => registerServiceWorker()).not.toThrow();
+ });
+
+ it('takes exactly one lifecycle path (register OR tear down) without throwing', async () => {
+ const register = vi.fn().mockResolvedValue({ scope: '/' });
+ const getRegistrations = vi.fn().mockResolvedValue([]);
+ vi.stubGlobal('navigator', { serviceWorker: { register, getRegistrations } });
+ // readyState 'complete' → register fires synchronously (no window 'load'
+ // deferral), keeping the assertion deterministic across both test runners.
+ vi.stubGlobal('document', { readyState: 'complete' });
+ vi.stubGlobal('window', { addEventListener: vi.fn() });
+
+ expect(() => registerServiceWorker()).not.toThrow();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ const registered = register.mock.calls.length > 0;
+ const toreDown = getRegistrations.mock.calls.length > 0;
+ // Exactly one branch runs.
+ expect(registered).not.toBe(toreDown);
+ // If it registered, it must target the root-scoped worker.
+ if (registered) expect(register).toHaveBeenCalledWith('/sw.js');
+ });
+});
diff --git a/client/src/main.jsx b/client/src/main.jsx
index 46d47f97f2..6951749c3c 100644
--- a/client/src/main.jsx
+++ b/client/src/main.jsx
@@ -7,9 +7,14 @@ import ErrorBoundary from './components/ErrorBoundary';
import { ThemeProvider } from './components/ThemeContext';
import { isStaleChunkError, reloadOnceForStaleChunk } from './utils/staleChunkReload';
import { reportClientError } from './lib/clientErrorReporter';
+import { registerServiceWorker } from './lib/registerServiceWorker';
import App from './App';
import './index.css';
+// Offline app-shell + low-bandwidth asset caching (production, secure-context
+// only — no-op in dev and over plain-HTTP Tailnet). See lib/registerServiceWorker.
+registerServiceWorker();
+
// Vite emits `vite:preloadError` when a code-split chunk's preload 404s —
// usually because the server rebuilt and the chunk filename changed while
// this tab was still open. Catching it here reloads before React's error