feat: update ready reloade stuck

Task #55 completed by ClaudeQueue

ClaudeQueue
This commit is contained in:
Claude Worker
2026-07-01 02:38:45 +00:00
parent 50cf655b71
commit 395af38246
2 changed files with 157 additions and 10 deletions

View File

@@ -10,10 +10,14 @@
*
* Auto-update flow:
* 1. New SW installs alongside the old one.
* 2. activate: broadcast SW_UPDATE_AVAILABLE to all clients.
* 2. activate: if an older *versioned shell cache* is found (i.e. this
* activation is genuinely replacing a previous deploy, not just the
* first-ever install of a freshly (re)registered worker), broadcast
* SW_UPDATE_AVAILABLE to all clients.
* 3. Client shows "Update ready" banner.
* 4. User clicks → client sends { type: 'SKIP_WAITING' }.
* 5. SW calls skipWaiting() → takes over → client reloads.
* 4. User clicks "Refresh UI" → client (hardReloadUI in app.js) wipes every
* cache, unregisters the SW, and hard-navigates to fetch everything
* fresh from the network.
* ========================================================================== */
// BUILD_TAG is injected by the server at request time (GET /sw.js).
@@ -22,6 +26,15 @@
const VERSION = typeof __BUILD_TAG__ !== 'undefined' ? __BUILD_TAG__ : 'v1.0.3';
const CACHE = 'ytplayer-' + VERSION;
// Prefix shared by every versioned app-shell cache (ytplayer-<VERSION>).
// Utility caches (ytplayer-thumbs, ytplayer-fonts) intentionally do NOT
// match this — they aren't versioned and must survive every activate.
const SHELL_CACHE_PREFIX = 'ytplayer-';
const UTILITY_CACHES = new Set(['ytplayer-thumbs', 'ytplayer-fonts']);
function isVersionedShellCache(key) {
return key.startsWith(SHELL_CACHE_PREFIX) && !UTILITY_CACHES.has(key);
}
// Files that form the installable app shell.
const SHELL = [
'/',
@@ -48,16 +61,33 @@ self.addEventListener('install', (e) => {
// ---- Activate: evict old caches, claim clients, notify about update ----
self.addEventListener('activate', (e) => {
e.waitUntil((async () => {
// Delete every cache that isn't the current version
const keys = await caches.keys();
await Promise.all(
keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))
);
// Was there a *previous deploy's* app-shell cache lying around? If so,
// this activation is a genuine version bump — worth telling the client
// about. If the only versioned shell cache present is our own CACHE (or
// none at all), this is the first-ever activation of a freshly
// (re)registered worker — e.g. right after hardReloadUI() unregisters
// the old SW and hard-navigates — and there is nothing new to report.
// Without this check, that harmless re-install would re-broadcast
// SW_UPDATE_AVAILABLE and immediately reopen the "Update ready" banner
// the user just dismissed by clicking "Reload now".
const staleShellCaches = keys.filter((k) => isVersionedShellCache(k) && k !== CACHE);
const isGenuineUpdate = staleShellCaches.length > 0;
// Delete every stale *versioned shell* cache — never the utility caches
// (thumbs/fonts), which aren't tied to a deploy version and should
// survive every activate.
await Promise.all(staleShellCaches.map((k) => caches.delete(k)));
// Claim all open clients immediately (new installs)
await self.clients.claim();
// Broadcast to every open window so the app can show an update banner
const all = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
all.forEach((c) => c.postMessage({ type: 'SW_UPDATE_AVAILABLE', version: VERSION }));
if (isGenuineUpdate) {
// Broadcast to every open window so the app can show an update banner
const all = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
all.forEach((c) => c.postMessage({ type: 'SW_UPDATE_AVAILABLE', version: VERSION }));
}
})());
});

117
frontend/sw.test.js Normal file
View File

@@ -0,0 +1,117 @@
'use strict';
/**
* Unit tests for the service worker's activate handler (Task #55).
*
* Bug: "Update ready / Reload now" got stuck in a loop. Root cause —
* activate() unconditionally broadcast SW_UPDATE_AVAILABLE to every open
* client, even when this activation was just the first-ever install of a
* freshly (re)registered worker (e.g. right after the "Refresh UI" button's
* hardReloadUI() wipes every cache, unregisters the SW, and hard-navigates).
* That harmless re-install re-announced "update available" and immediately
* reopened the banner the user had just dismissed.
*
* sw.js runs in a ServiceWorkerGlobalScope, which Node doesn't provide, so
* these tests load the real source into a minimal vm sandbox that mocks
* `self`, `caches`, and `self.clients`, then drive the registered
* `activate` listener directly.
*/
const { test } = require('node:test');
const assert = require('node:assert');
const vm = require('node:vm');
const fs = require('node:fs');
const path = require('node:path');
const SW_SOURCE = fs.readFileSync(path.join(__dirname, 'sw.js'), 'utf8');
// Builds a fresh sandboxed SW environment with the given starting cache keys
// and returns handles to drive/inspect it.
function loadSw(initialCacheKeys) {
const cacheStore = new Set(initialCacheKeys);
const deleted = [];
const clientMessages = [];
const listeners = {};
const self_ = {
addEventListener(type, fn) {
(listeners[type] = listeners[type] || []).push(fn);
},
clients: {
async claim() {},
async matchAll() {
return [{ postMessage: (msg) => clientMessages.push(msg) }];
},
},
};
const caches_ = {
async keys() { return Array.from(cacheStore); },
async delete(key) { deleted.push(key); return cacheStore.delete(key); },
async open(key) {
cacheStore.add(key);
return { addAll: async () => {}, match: async () => undefined, put: async () => {} };
},
};
const sandbox = {
self: self_,
caches: caches_,
fetch: async () => { throw new Error('fetch not mocked'); },
Response: class { constructor(body, init) { this.body = body; Object.assign(this, init); } },
URL,
console,
};
vm.createContext(sandbox);
vm.runInContext(SW_SOURCE, sandbox, { filename: 'sw.js' });
async function triggerActivate() {
let waitPromise = Promise.resolve();
const event = { waitUntil: (p) => { waitPromise = p; } };
for (const fn of listeners.activate || []) fn(event);
await waitPromise;
}
return { triggerActivate, deleted, clientMessages, cacheStoreRemaining: () => Array.from(cacheStore) };
}
test('activate does NOT broadcast on a fresh install (only the current-version cache exists)', async () => {
const sw = loadSw(['ytplayer-v1.0.3']); // default VERSION fallback in sw.js is 'v1.0.3'
await sw.triggerActivate();
assert.deepStrictEqual(sw.clientMessages, [], 'no update banner should be triggered on first-ever install');
assert.deepStrictEqual(sw.deleted, [], 'nothing stale to evict on a fresh install');
});
test('activate DOES broadcast when an older versioned shell cache is present (genuine update)', async () => {
const sw = loadSw(['ytplayer-v1.0.3', 'ytplayer-v1.0.2']);
await sw.triggerActivate();
assert.strictEqual(sw.clientMessages.length, 1, 'a genuine version bump should notify clients once');
assert.strictEqual(sw.clientMessages[0].type, 'SW_UPDATE_AVAILABLE');
assert.deepStrictEqual(sw.deleted, ['ytplayer-v1.0.2'], 'the stale shell cache should be evicted');
});
test('activate never deletes the utility caches (thumbs/fonts), broadcast or not', async () => {
const sw = loadSw(['ytplayer-v1.0.3', 'ytplayer-thumbs', 'ytplayer-fonts']);
await sw.triggerActivate();
assert.deepStrictEqual(sw.clientMessages, [], 'utility caches alone are not a version bump');
assert.deepStrictEqual(sw.deleted, [], 'utility caches must survive activate');
assert.deepStrictEqual(
sw.cacheStoreRemaining().sort(),
['ytplayer-fonts', 'ytplayer-thumbs', 'ytplayer-v1.0.3'].sort()
);
});
test('activate reports an update and still preserves utility caches together', async () => {
const sw = loadSw(['ytplayer-v1.0.3', 'ytplayer-v1.0.2', 'ytplayer-thumbs', 'ytplayer-fonts']);
await sw.triggerActivate();
assert.strictEqual(sw.clientMessages.length, 1);
assert.deepStrictEqual(sw.deleted, ['ytplayer-v1.0.2']);
assert.deepStrictEqual(
sw.cacheStoreRemaining().sort(),
['ytplayer-fonts', 'ytplayer-thumbs', 'ytplayer-v1.0.3'].sort()
);
});