fix(service-worker): let the app subscribe to reload-required and update-waiting (R-6.3)

Tabs that did not request an activation only observe()d
ACTIVATED_RELOAD_REQUIRED, and the host contract had no way to tell the
app. Worse, the worker targeted that broadcast at the requester's build,
so a tab on another build dropped it as TARGET_BUILD_MISMATCH. A waiting
worker produced by the periodic registration.update() was never reported
either.

- ServiceWorkerRuntimeHost gains optional onReloadRequired/onUpdateWaiting
  (additive; existing host implementations still type-check).
- The page controller notifies reload subscribers when an expected worker
  source sends ACTIVATED_RELOAD_REQUIRED, and watches `updatefound` +
  `statechange` to announce an update that reached `installed` while an
  active worker exists (a first install is never announced). Listeners
  are removed on stop(); a throwing subscriber is isolated.
- Worker post-commit/reject notifications are untargeted; the requester
  still pairs by nonce.
- Test fixtures: registration and workers are now EventTarget-backed.

RED before fix (listener called 0 times):
- announces an update that finished installing as waiting (R-6.3)
- page ↔ worker activation seam > tells a tab that did not ask that a
  reload is required (R-6.3)
Gates: check:architecture, check:types:{app,test,service-worker}, lint,
test:component pass. test:unit passes except the pre-existing
removal-fixture.test.ts case that needs generated release evidence
under artifacts/ (absent in a fresh worktree; unrelated to this diff).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-24 12:28:38 +09:00
co-authored by Claude Opus 5.5
parent 47832fbe65
commit fb8a3b5e1d
4 changed files with 172 additions and 27 deletions
@@ -277,7 +277,7 @@ export function createServiceWorkerRuntime(
);
const drained = await drainClients(clients, nonce);
if (!drained) {
notifyClients(clients, "ACTIVATE_REJECTED", parsed.message.sourceBuildId, nonce);
notifyClients(clients, "ACTIVATE_REJECTED", nonce);
return "REJECTED";
}
@@ -287,28 +287,25 @@ export function createServiceWorkerRuntime(
try {
await scope.skipWaiting();
} catch {
notifyClients(clients, "ACTIVATE_REJECTED", parsed.message.sourceBuildId, nonce);
notifyClients(clients, "ACTIVATE_REJECTED", nonce);
return "REJECTED";
}
// Post-commit notifications are per-client best effort.
notifyClients(clients, "ACTIVATE_ACCEPTED", parsed.message.sourceBuildId, nonce);
notifyClients(
clients,
"ACTIVATED_RELOAD_REQUIRED",
parsed.message.sourceBuildId,
nonce,
);
notifyClients(clients, "ACTIVATE_ACCEPTED", nonce);
notifyClients(clients, "ACTIVATED_RELOAD_REQUIRED", nonce);
return "ACCEPTED";
}
/**
* SW-08. One client's `postMessage()` throwing must not break the whole
* activation event; delivery is isolated per client.
*
* R-6.3. Untargeted: every tab, whatever build it runs, has to see
* ACTIVATED_RELOAD_REQUIRED. The requester pairs its reply by nonce.
*/
function notifyClients(
clients: readonly WorkerClientLike[],
kind: "ACTIVATE_REJECTED" | "ACTIVATE_ACCEPTED" | "ACTIVATED_RELOAD_REQUIRED",
targetBuildId: string,
nonce: string,
): void {
for (const client of clients) {
@@ -317,7 +314,6 @@ export function createServiceWorkerRuntime(
createServiceWorkerMessage({
kind,
sourceBuildId: config.identity.buildId,
targetBuildId,
nonce,
}),
);
@@ -63,6 +63,9 @@ export function createServiceWorkerPageController(
let resetInFlight: Promise<ServiceWorkerResetOutcome> | null = null;
let stopped = false;
const pendingStops = new Set<() => void>();
let updateFoundListener: (() => void) | null = null;
const reloadRequiredListeners = new Set<() => void>();
const updateWaitingListeners = new Set<() => void>();
const observe = (event: string, outcome: string) =>
dependencies.observe?.({ event, outcome });
@@ -178,6 +181,7 @@ export function createServiceWorkerPageController(
}
attachMessageListener(container);
watchForUpdates(registration);
scheduleUpdateChecks();
if (registration.waiting) {
@@ -239,6 +243,13 @@ export function createServiceWorkerPageController(
observe("client_drain", rejected ? "BLOCKED" : "DRAINED");
return;
}
// R-6.3. Sent to every tab once any tab's activation committed.
if (
parsed.message.kind === "ACTIVATED_RELOAD_REQUIRED" &&
isExpectedWorkerSource(event.source)
) {
notify(reloadRequiredListeners);
}
observe("message", parsed.message.kind);
};
container.addEventListener("message", messageListener);
@@ -261,6 +272,35 @@ export function createServiceWorkerPageController(
);
}
/**
* R-6.3. An update found by the periodic check (or by another tab) reaches
* `waiting` without any message, so the registration's own events are
* watched. A first install has no active worker and activates on its own,
* so it is never announced as waiting.
*/
function watchForUpdates(watched: ServiceWorkerRegistration): void {
if (updateFoundListener) return;
let lastWatched: ServiceWorker | null = null;
const watchInstalling = () => {
const worker = watched.installing;
if (!worker || worker === lastWatched) return;
lastWatched = worker;
worker.addEventListener("statechange", () => {
if (
worker.state === "installed" &&
watched.waiting === worker &&
watched.active
) {
notify(updateWaitingListeners);
}
});
};
updateFoundListener = watchInstalling;
watched.addEventListener("updatefound", updateFoundListener);
// The update may have been found before this listener existed.
watchInstalling();
}
function scheduleUpdateChecks(): void {
// §17.14. At most one check per 6 hours, and none while the page is hidden.
if (updateTimer) return;
@@ -485,10 +525,45 @@ export function createServiceWorkerPageController(
dependencies.container.removeEventListener("message", messageListener);
messageListener = null;
}
if (updateFoundListener && registration) {
registration.removeEventListener("updatefound", updateFoundListener);
updateFoundListener = null;
}
reloadRequiredListeners.clear();
updateWaitingListeners.clear();
nonces.clear();
}
return Object.freeze({ start, requestActivation, resetOwnedCaches, stop });
return Object.freeze({
start,
requestActivation,
resetOwnedCaches,
stop,
onReloadRequired: (listener: () => void) =>
subscribe(reloadRequiredListeners, listener),
onUpdateWaiting: (listener: () => void) =>
subscribe(updateWaitingListeners, listener),
});
}
function subscribe(
listeners: Set<() => void>,
listener: () => void,
): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
function notify(listeners: ReadonlySet<() => void>): void {
for (const listener of [...listeners]) {
try {
listener();
} catch {
// A failing subscriber cannot break the message or event handler.
}
}
}
function canPostMessage(
+11
View File
@@ -149,4 +149,15 @@ export interface ServiceWorkerRuntimeHost {
requestActivation(): Promise<ServiceWorkerActivationOutcome>;
resetOwnedCaches(): Promise<ServiceWorkerResetOutcome>;
stop(): Promise<void>;
/**
* R-6.3. A new worker was activated (by any tab), so this page runs under a
* worker of another build and should reload. Every tab is told, including
* the one that asked. Returns the unsubscribe function.
*/
onReloadRequired?(listener: () => void): () => void;
/**
* R-6.3. An update finished installing and waits for `requestActivation()`.
* Returns the unsubscribe function.
*/
onUpdateWaiting?(listener: () => void): () => void;
}