Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(web): remove app-shell service worker caching (#8148)

dev-rb85b932d4f8c6
diff --git a/.agents/rules/web/startup-bundle.md b/.agents/rules/web/startup-bundle.md
index 9363b9fcb1..5916013b48 100644
--- a/.agents/rules/web/startup-bundle.md
+++ b/.agents/rules/web/startup-bundle.md
@@ -25,9 +25,8 @@ alwaysApply: false
background, the rail column, and the desktop app's content card — no app
content. The first shell to mount dismisses it (`dismissBootShell`). Keep its
rail width and desktop inset in step with `SidebarRail` and `SplitLayout`.
-- Production web builds register `public/sw.js`: it serves the cached
- `index.html` and content-hashed assets from Cache Storage and moves tabs to
- newer builds. Set localStorage `macro:sw` to `off` to bypass it while
- debugging.
+- Do not register an asset-caching service worker. Keep `public/sw.js` at its
+ deployed URL so existing workers can update, clear their shell and asset
+ caches, and unregister; it must not intercept requests.
- The build fails if any emitted file exceeds CloudFront's 10 MB compression
limit; split it rather than raising the limit.
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index b1b0a42e82..ca273991d3 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -6,6 +6,9 @@
- `bun run format`: format changes with biome
- `bun run knip`: to check for dead code
- Email rendering is isolated in `packages/email-renderer` at the repository root. Run `just test-email-rendering` for its Node and Chromium suites. Add fixtures under `packages/email-renderer/tests/fixtures`, run `just test-email-rendering-update`, and review changed images. These are renderer tests, not inbox e2e.
+- The app does not register a service worker. Keep `public/sw.js` as a retirement
+ endpoint for existing installations; see the [startup bundle rule](../../.agents/rules/web/startup-bundle.md).
+ Loro uses async WASM loading and HTML preloads independently of service workers.
## Verifying a change in a real browser
diff --git a/apps/web/public/sw.js b/apps/web/public/sw.js
index b5c1ea42c6..3b0dececd0 100644
--- a/apps/web/public/sw.js
+++ b/apps/web/public/sw.js
@@ -1,203 +1,26 @@
/**
- * Macro web app service worker (scope /app/). Registered by
- * src/lib/service-worker/register.ts in production web builds only.
- *
- * - Navigations get the cached app shell (index.html) immediately and
- * revalidate it in the background, so a new tab skips the HTML round trip.
- * A shell is cached only after its entry JS, CSS, and preloaded WASM are, so
- * a cached shell can always boot.
- * - Content-hashed assets are immutable: served cache-first from Cache
- * Storage, tagged with the build that fetched them, and pruned to the
- * current and previous builds.
- * - When revalidation finds a newer build, open tabs get a
- * `macro:newer-build` message so a tab still on the cached build can move
- * to it.
- *
- * Kill switch: ship a sw.js whose install handler calls
- * `self.registration.unregister()`; a client also unregisters it when its
- * localStorage `macro:sw` is `off`.
+ * Retire the former app-shell and asset cache worker. Keep this URL available
+ * so installed workers can update, release their caches, and unregister.
+ * New app builds do not register a service worker.
*/
-
-const SHELL_CACHE = 'macro-shell-v1';
-const ASSET_CACHE = 'macro-assets-v1';
-const SCOPE_PATH = new URL(self.registration.scope).pathname;
-const SHELL_KEY = `${SCOPE_PATH}__shell`;
-const BUILD_HEADER = 'x-macro-build';
-const ASSETS_HEADER = 'x-macro-shell-assets';
-
-// Vite output names end in an 8-character base64url content hash.
-const HASHED_ASSET =
- /-(?=[A-Za-z0-9_-]*[A-Z0-9_])[A-Za-z0-9_-]{8}\.(?:js|css|wasm|woff2?|ttf|svg|png|jpe?g|webp|glb)$/;
-
self.addEventListener('install', (event) => {
- self.skipWaiting();
- // Warm the shell for the next tab; a failure only means a cold next tab.
- event.waitUntil(refreshShell(new Request(SCOPE_PATH)).catch(() => {}));
+ event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', (event) => {
event.waitUntil(
(async () => {
- const keep = new Set([SHELL_CACHE, ASSET_CACHE]);
- for (const name of await caches.keys()) {
- if (name.startsWith('macro-') && !keep.has(name)) {
- await caches.delete(name);
- }
- }
- await self.clients.claim();
+ const names = await caches.keys();
+ await Promise.all(
+ names
+ .filter(
+ (name) =>
+ name.startsWith('macro-shell-') ||
+ name.startsWith('macro-assets-')
+ )
+ .map((name) => caches.delete(name))
+ );
+ await self.registration.unregister();
})()
);
});
-
-self.addEventListener('fetch', (event) => {
- const { request } = event;
- if (request.method !== 'GET') return;
- const url = new URL(request.url);
- if (url.origin !== self.location.origin) return;
- if (!url.pathname.startsWith(SCOPE_PATH)) return;
-
- if (request.mode === 'navigate') {
- // The cached shell carries the app's frame options. A framed page (a
- // booking link in the website's dialog) needs the ones served for its path.
- if (request.destination === 'iframe') return;
- // Mirror the routing lambda: paths that look like files are not the app.
- const leaf = url.pathname.split('/').pop() ?? '';
- if (leaf.includes('.') && !url.pathname.includes('@')) return;
- event.respondWith(serveShell(event));
- } else if (HASHED_ASSET.test(url.pathname)) {
- event.respondWith(serveAsset(request));
- }
-});
-
-async function serveShell(event) {
- const cache = await caches.open(SHELL_CACHE);
- const cached = await cache.match(SHELL_KEY);
- const refreshed = refreshShell(event.request).catch(() => undefined);
- if (cached && (await shellAssetsCached(cached))) {
- event.waitUntil(refreshed);
- return cached;
- }
- // No bootable shell yet: wait for the network, falling back to whatever
- // is cached when offline.
- const response = await refreshed;
- return response ?? cached ?? Response.error();
-}
-
-/** Fetches index.html, caches it as the shell once its entry is cached, and returns the network response. */
-async function refreshShell(request) {
- const response = await fetch(request, { cache: 'no-store' });
- if (!response.ok || response.redirected) return response;
- if (!response.headers.get('content-type')?.includes('text/html')) {
- return response;
- }
- const html = await response.clone().text();
- const build = /<meta name="macro-bundle-build" content="(\d+)"/.exec(
- html
- )?.[1];
- if (!build) return response;
-
- const cache = await caches.open(SHELL_CACHE);
- const current = await cache.match(SHELL_KEY);
- const currentBuild = current?.headers.get(BUILD_HEADER);
- if (currentBuild === build && (await shellAssetsCached(current))) {
- return response;
- }
-
- // The routing lambda adds a per-document <title>; the shell serves every route.
- const shell = html.replace(/<title data-sm="">[\s\S]*?<\/title>/, '');
- const assets = entryAssets(shell);
- const assetCache = await caches.open(ASSET_CACHE);
- await Promise.all(
- assets.map(async (path) => {
- if (await assetCache.match(path)) return;
- const assetResponse = await fetch(path);
- if (!assetResponse.ok) throw new Error(`Failed to cache ${path}`);
- await assetCache.put(path, tagged(assetResponse, build));
- })
- );
- // Keep the document's own headers (COOP for login popups, frame options).
- const headers = new Headers(response.headers);
- for (const name of ['content-length', 'content-encoding', 'date', 'age']) {
- headers.delete(name);
- }
- headers.set(BUILD_HEADER, build);
- headers.set(ASSETS_HEADER, assets.join(' '));
- await cache.put(SHELL_KEY, new Response(shell, { headers }));
-
- if (currentBuild && Number(build) > Number(currentBuild)) {
- for (const client of await self.clients.matchAll({ type: 'window' })) {
- client.postMessage({ type: 'macro:newer-build', build });
- }
- }
- if (currentBuild !== build) {
- await pruneAssets(new Set([build, currentBuild ?? build]), new Set(assets));
- }
- return response;
-}
-
-/**
- * The entry module, its preloads, and stylesheets referenced by a shell. A
- * `rel="preload"` asset (Loro's WASM) is needed to boot, so it counts too.
- */
-function entryAssets(html) {
- const paths = new Set();
- for (const match of html.matchAll(
- /<(?:script|link)\b[^>]*\b(?:src|href)="([^"]+)"[^>]*>/g
- )) {
- const tag = match[0];
- const isEntry =
- tag.startsWith('<script') ||
- /\brel="(?:stylesheet|modulepreload|preload)"/.test(tag);
- const path = new URL(match[1], self.location.origin).pathname;
- if (isEntry && HASHED_ASSET.test(path)) paths.add(path);
- }
- return [...paths];
-}
-
-async function shellAssetsCached(shell) {
- const assets = shell.headers.get(ASSETS_HEADER)?.split(' ') ?? [];
- if (assets.length === 0) return false;
- const assetCache = await caches.open(ASSET_CACHE);
- const hits = await Promise.all(assets.map((path) => assetCache.match(path)));
- return hits.every(Boolean);
-}
-
-async function serveAsset(request) {
- const cache = await caches.open(ASSET_CACHE);
- const hit = await cache.match(request, { ignoreVary: true });
- if (hit) return hit;
- const response = await fetch(request);
- if (response.ok && response.type === 'basic') {
- const shell = await (await caches.open(SHELL_CACHE)).match(SHELL_KEY);
- const build = shell?.headers.get(BUILD_HEADER) ?? '';
- cache.put(request, tagged(response.clone(), build)).catch(() => {});
- }
- return response;
-}
-
-/** Copies a response with the build that fetched it, for pruning. */
-function tagged(response, build) {
- const headers = new Headers(response.headers);
- headers.set(BUILD_HEADER, build);
- return new Response(response.body, {
- status: response.status,
- statusText: response.statusText,
- headers,
- });
-}
-
-/**
- * Drops cached assets fetched by builds other than `keep`, except the current
- * shell's own: an asset whose hash survived several builds (Loro's WASM) is
- * still tagged with the build that first fetched it.
- */
-async function pruneAssets(keep, shellAssets) {
- const cache = await caches.open(ASSET_CACHE);
- for (const request of await cache.keys()) {
- if (shellAssets.has(new URL(request.url).pathname)) continue;
- const response = await cache.match(request);
- if (!keep.has(response?.headers.get(BUILD_HEADER) ?? '')) {
- await cache.delete(request);
- }
- }
-}
diff --git a/apps/web/scripts/retain-recent-builds.sh b/apps/web/scripts/retain-recent-builds.sh
index 20be5ebfe4..6276467e0c 100644
--- a/apps/web/scripts/retain-recent-builds.sh
+++ b/apps/web/scripts/retain-recent-builds.sh
@@ -52,8 +52,7 @@ fi
key_prefix=${prefix:+$prefix/}
records_prefix=${key_prefix}_builds
-# The build number the shell advertises as `macro-bundle-build`, so a record
-# sorts by the same clock the service worker compares builds with.
+# Use the same build timestamp as the bundle manifest and app update checks.
manifest=$dist_root/bundle-manifest.json
if [ ! -f "$manifest" ]; then
echo "no bundle manifest at $manifest" >&2
diff --git a/apps/web/src/index.tsx b/apps/web/src/index.tsx
index b3d6f47358..971d452fc6 100644
--- a/apps/web/src/index.tsx
+++ b/apps/web/src/index.tsx
@@ -14,7 +14,6 @@ import { promptReloadForFailedLoad } from '@core/util/reloadForNewerBuild';
import { initMonochromeIcons } from '@ui/utils/monochromeIcons';
import { ErrorBoundary, render } from 'solid-js/web';
import { FatalError } from './components/app/FatalError';
-import { registerServiceWorker } from './lib/service-worker/register';
import { Root } from './routes/Root';
// Override global fetch with platformFetch for Tauri compatibility
@@ -114,7 +113,6 @@ async function main() {
}
renderApp();
- registerServiceWorker();
}
// unawaited
diff --git a/apps/web/src/lib/service-worker/register.ts b/apps/web/src/lib/service-worker/register.ts
deleted file mode 100644
index f2ecbc30c8..0000000000
--- a/apps/web/src/lib/service-worker/register.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';
-import { isTauri } from '@core/util/platform';
-import { reloadForNewerBuild } from '@core/util/reloadForNewerBuild';
-
-/**
- * Set localStorage `macro:sw` to `off` to unregister the worker. Its caches
- * are cleared on the first load it no longer controls.
- */
-const OPT_OUT_KEY = 'macro:sw';
-/** How long after load an untouched tab may silently reload into a newer build. */
-const SILENT_RELOAD_WINDOW_MS = 10_000;
-
-let interacted = false;
-
-/** The bundle build this page booted, from index.html. */
-function runningBuild(): number {
- const content = document
- .querySelector<HTMLMetaElement>('meta[name="macro-bundle-build"]')
- ?.getAttribute('content');
- return Number(content);
-}
-
-function optedOut(): boolean {
- try {
- return localStorage.getItem(OPT_OUT_KEY) === 'off';
- } catch {
- return false;
- }
-}
-
-async function unregister(): Promise<void> {
- const registrations = await navigator.serviceWorker.getRegistrations();
- await Promise.all(
- registrations.map((registration) => registration.unregister())
- );
- const names = await caches.keys();
- await Promise.all(
- names
- .filter((name) => name.startsWith('macro-'))
- .map((name) => caches.delete(name))
- );
-}
-
-/**
- * The worker cached a newer build than this tab runs: a tab that booted the
- * cached shell right after a deploy. Untouched tabs reload straight away (the
- * boot shell shows again); otherwise the regular newer-build flow decides.
- */
-function onWorkerMessage(event: MessageEvent<unknown>): void {
- const data = event.data as { type?: unknown; build?: unknown } | null;
- if (data?.type !== 'macro:newer-build') return;
- const running = runningBuild();
- if (!Number.isFinite(running) || Number(data.build) <= running) return;
- if (!interacted && performance.now() < SILENT_RELOAD_WINDOW_MS) {
- window.location.reload();
- return;
- }
- reloadForNewerBuild(undefined, String(data.build));
-}
-
-/**
- * Registers public/sw.js, which serves the app shell and hashed assets from
- * Cache Storage so new tabs skip the HTML round trip. Production web only:
- * Tauri ships its own bundle and dev servers rebuild assets in place.
- */
-export function registerServiceWorker(): void {
- if (!import.meta.env.PROD || isTauri()) return;
- if (!('serviceWorker' in navigator) || !window.isSecureContext) return;
- if (!window.location.pathname.startsWith(ROUTER_BASE_CONCAT.slice(0, -1))) {
- return;
- }
- if (optedOut()) {
- void unregister().catch(() => {});
- return;
- }
-
- for (const type of ['pointerdown', 'keydown'] as const) {
- window.addEventListener(type, () => (interacted = true), {
- capture: true,
- once: true,
- });
- }
- navigator.serviceWorker.addEventListener('message', onWorkerMessage);
-
- // Registration installs the worker, which fetches the shell and entry
- // assets; keep that off the critical path of this load.
- const register = () =>
- navigator.serviceWorker
- .register(`${ROUTER_BASE_CONCAT}sw.js`, { scope: ROUTER_BASE_CONCAT })
- .catch((error: unknown) =>
- console.warn('Service worker registration failed', error)
- );
- const whenIdle = () =>
- 'requestIdleCallback' in window
- ? window.requestIdleCallback(register, { timeout: 5000 })
- : setTimeout(register, 1000);
- if (document.readyState === 'complete') whenIdle();
- else window.addEventListener('load', whenIdle, { once: true });
-}
diff --git a/apps/web/vite.base.ts b/apps/web/vite.base.ts
index e486499a91..37f43a9191 100644
--- a/apps/web/vite.base.ts
+++ b/apps/web/vite.base.ts
@@ -170,8 +170,7 @@ const HTML_PRELOADS = [
/**
* Adds `<link rel="preload">` for HTML_PRELOADS, so their downloads start with
- * the HTML instead of after the entry runs. The service worker caches preloads
- * with the shell.
+ * the HTML instead of after the entry runs.
*/
function htmlPreloads(): Plugin {
let base = '/';