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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-3174]): serve a renderable fallback page when the SW has no offline shell cached
[._.]/ Adam Eivyb00c4f4c6287
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f216ca3328..0bb3cbdea2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,9 @@# Unreleased Changes+## Offline reliability++- **[issue-3174] A dropped connection on first visit no longer strands the tab on a dead browser network-error page.** If the service worker hasn't finished caching the offline app shell yet (a fresh install, or a deploy that just activated) and a page navigation fails over a flaky link, the tab used to hit an opaque, unrecoverable network error with no way to retry. It now shows a plain "Connection failed" page with a Retry button instead.+## Music Video- **A track that "Analyze" reports as having no detectable tempo can now get a beat map by hand.** The offline detector deliberately reports no BPM rather than guessing when a track's beats aren't strong/periodic enough or its tempo falls outside its search range — which used to leave the whole beat grid (timeline, AI Plan, Auto-arrange, beat-snapped render) permanently unusable. When Analyze finds no tempo, a "set it by ear" row now appears: enter a BPM (or use Tap tempo) and the first downbeat's offset, and the same beat/downbeat/section map the auto path produces gets cached on the project.diff --git a/client/eslint.config.js b/client/eslint.config.jsindex 1a69731523..9f86fb3422 100644--- a/client/eslint.config.js+++ b/client/eslint.config.js@@ -11,6 +11,7 @@ const browserGlobals = {requestAnimationFrame: 'readonly', cancelAnimationFrame: 'readonly',queueMicrotask: 'readonly',fetch: 'readonly', URL: 'readonly', URLSearchParams: 'readonly',+ Request: 'readonly', Response: 'readonly',EventSource: 'readonly',FormData: 'readonly', File: 'readonly', FileReader: 'readonly',Blob: 'readonly', Event: 'readonly', CustomEvent: 'readonly',diff --git a/client/public/sw.js b/client/public/sw.jsindex 9162602eac..1f56d54fa1 100644--- a/client/public/sw.js+++ b/client/public/sw.js@@ -57,6 +57,47 @@ const CURRENT_CACHES = new Set([SHELL_CACHE, ASSET_CACHE, STATIC_CACHE, FONT_CAC// (every SPA navigation resolves to the same index.html on the server).const SHELL_KEY = '/index.html';+// Last-resort HTML for a failed navigation when NEITHER the offline shell nor+// an exact-URL cache entry exists (e.g. the very first install, before the+// precache has committed, combined with a flaky-link fetch failure). A bare+// `Response.error()` here is an opaque network-error the browser can't render+// — a dead tab with no way to recover, since the SW sits upstream of React+// ever mounting. This is a minimal, dependency-free page so it needs no fetch+// of its own to render.+const OFFLINE_FALLBACK_HTML = `<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>PortOS — Connection failed</title>+<style>+ body { margin: 0; display: flex; align-items: center; justify-content: center; min-height: 100vh;+ font-family: system-ui, -apple-system, sans-serif; background: #111827; color: #e5e7eb; text-align: center; }+ .box { max-width: 22rem; padding: 2rem; }+ h1 { font-size: 1.25rem; margin: 0 0 0.5rem; }+ p { color: #9ca3af; margin: 0 0 1.25rem; }+ button { font: inherit; padding: 0.6rem 1.4rem; border-radius: 0.4rem; border: none;+ background: #3b82f6; color: #fff; cursor: pointer; }+ button:hover { background: #2563eb; }+</style>+</head>+<body>+<div class="box">+ <h1>Connection failed</h1>+ <p>PortOS couldn't reach the server, and no offline copy of this page is cached yet.</p>+ <button onclick="location.reload()">Retry</button>+</div>+</body>+</html>`;++function offlineFallbackResponse() {+ return new Response(OFFLINE_FALLBACK_HTML, {+ status: 503,+ statusText: 'Service Unavailable',+ headers: { 'Content-Type': 'text/html; charset=utf-8' },+ });+}+// 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@@ -260,7 +301,9 @@ async function navigationHandler(event, onCachingSettled) {// Last resort: whatever we have for this exact navigation URL.const exact = await caches.match(event.request).catch(() => null);if (exact) return exact;- return Response.error();+ // Nothing cached at all — render an actionable page instead of an opaque+ // network-error response.+ return offlineFallbackResponse();}}diff --git a/client/src/test/sw.test.js b/client/src/test/sw.test.jsnew file mode 100644index 0000000000..d64f631a50--- /dev/null+++ b/client/src/test/sw.test.js@@ -0,0 +1,130 @@+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import vm from 'node:vm';+import path from 'node:path';+import { describe, it, expect } from 'vitest';++// sw.js is a plain classic service-worker script (no ES imports/exports — it's+// registered without { type: 'module' }), served as-is from client/public/.+// To exercise navigationHandler's fallback branches without extracting it out+// of the worker, evaluate the real file in an isolated vm sandbox that+// implements just enough of the SW globals (self, caches, fetch, Response) to+// drive its 'fetch' event listener, then read back the Response it produces.++const SW_PATH = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../public/sw.js');+const SW_SOURCE = readFileSync(SW_PATH, 'utf-8');++function createSandbox() {+ const listeners = {};+ // name -> Map(url -> Response)+ const cacheStores = new Map();++ function openCache(name) {+ if (!cacheStores.has(name)) cacheStores.set(name, new Map());+ const store = cacheStores.get(name);+ return {+ match: async (req) => store.get(typeof req === 'string' ? req : req.url),+ put: async (req, res) => store.set(typeof req === 'string' ? req : req.url, res),+ keys: async () => [...store.keys()].map((url) => ({ url })),+ delete: async (req) => store.delete(typeof req === 'string' ? req : req.url),+ };+ }++ const cachesApi = {+ open: async (name) => openCache(name),+ // Global lookup across every opened cache, mirroring the real Cache Storage API.+ match: async (req) => {+ const key = typeof req === 'string' ? req : req.url;+ for (const store of cacheStores.values()) {+ if (store.has(key)) return store.get(key);+ }+ return undefined;+ },+ keys: async () => [...cacheStores.keys()],+ delete: async (name) => cacheStores.delete(name),+ };++ const sandbox = {+ caches: cachesApi,+ console,+ Response,+ Request,+ URL,+ fetch: async () => {+ throw new Error('network unavailable');+ },+ };+ sandbox.self = {+ addEventListener: (type, handler) => {+ listeners[type] = handler;+ },+ skipWaiting: () => {},+ location: { origin: 'https://portos.example' },+ registration: {}, // no navigationPreload in this sandbox+ clients: { claim: async () => {} },+ };+ sandbox.globalThis = sandbox;+ vm.createContext(sandbox);+ vm.runInContext(SW_SOURCE, sandbox, { filename: 'sw.js' });++ return { listeners, cacheStores, cachesApi, openCache };+}++function makeNavigationEvent(url) {+ const event = {+ request: { method: 'GET', url, mode: 'navigate' },+ preloadResponse: Promise.resolve(undefined),+ respondWith: (promise) => {+ event._responded = promise;+ },+ waitUntil: () => {},+ };+ return event;+}++async function dispatchNavigation(listeners, url) {+ const event = makeNavigationEvent(url);+ listeners.fetch(event);+ return event._responded;+}++describe('sw.js navigationHandler — offline fallback branches', () => {+ const NAV_URL = 'https://portos.example/local-llm/playground?backend=ollama&model=x';++ it('serves the cached offline shell when the network fetch fails and a shell is cached', async () => {+ const { listeners, openCache } = createSandbox();+ const shellCache = openCache('portos-shell-v1');+ await shellCache.put('/index.html', new Response('<html>shell</html>', { status: 200 }));++ const response = await dispatchNavigation(listeners, NAV_URL);++ expect(response.status).toBe(200);+ await expect(response.text()).resolves.toBe('<html>shell</html>');+ });++ it('serves an exact cached response for the navigation URL when no shell is cached', async () => {+ const { listeners, openCache } = createSandbox();+ const exactCache = openCache('some-other-cache');+ await exactCache.put(NAV_URL, new Response('<html>exact match</html>', { status: 200 }));++ const response = await dispatchNavigation(listeners, NAV_URL);++ await expect(response.text()).resolves.toBe('<html>exact match</html>');+ });++ it('returns a renderable fallback page (not Response.error()) when nothing is cached', async () => {+ const { listeners } = createSandbox();++ const response = await dispatchNavigation(listeners, NAV_URL);++ // Response.error() produces an opaque, unreadable network-error response+ // (type 'error', status 0) — the bug this issue is about. The fix must+ // return something the browser can actually render.+ expect(response.type).not.toBe('error');+ expect(response.status).toBeGreaterThan(0);+ expect(response.headers.get('content-type')).toMatch(/text\/html/);+ const body = await response.text();+ expect(body).toMatch(/connection failed/i);+ expect(body).toMatch(/retry|reload/i);+ });+});