((resolve) => {
+ resolveDelete = resolve;
+ }),
+ );
+
+ render();
+ await waitFor(() => {
+ expect(mocks.deleteSubscription).toHaveBeenCalledWith('old-token');
+ });
+ localStorage.setItem(
+ 'push:pending-delete',
+ JSON.stringify(['old-token', 'new-token']),
+ );
+ resolveDelete?.();
+
+ await waitFor(() => {
+ expect(localStorage.getItem('push:pending-delete')).toBe('new-token');
+ });
+ });
+
+ it('offers repair when browser subscription creation fails after permission', async () => {
+ localStorage.setItem('viewed', '[1]');
+ registration.pushManager.subscribe = vi.fn(async () => {
+ mocks.order.push('subscribe');
+ throw new Error('subscription failed');
+ });
+
+ render();
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Enable alerts' }),
+ );
+
+ expect(
+ await screen.findByRole('button', { name: 'Repair alerts' }),
+ ).toBeInTheDocument();
+ expect(mocks.order).toEqual(['permission', 'subscribe']);
+ expect(mocks.putSubscription).not.toHaveBeenCalled();
+ });
+
+ it('does not fetch config or render controls in an unsupported browser', async () => {
+ Reflect.deleteProperty(window, 'PushManager');
+ localStorage.setItem('viewed', '[1]');
+
+ render();
+
+ await waitFor(() => {
+ expect(screen.queryByTestId('push-notification-opt-in')).toBeNull();
+ });
+ expect(mocks.fetchConfig).not.toHaveBeenCalled();
+ expect(requestPermission).not.toHaveBeenCalled();
+ });
+
+ it('does not enroll when durable token storage is unavailable', async () => {
+ const descriptor = Object.getOwnPropertyDescriptor(window, 'localStorage');
+ const unavailableStorage = {
+ getItem: vi.fn(() => null),
+ setItem: vi.fn(() => {
+ throw new DOMException('Storage unavailable', 'QuotaExceededError');
+ }),
+ removeItem: vi.fn(),
+ clear: vi.fn(),
+ key: vi.fn(() => null),
+ length: 0,
+ };
+ Object.defineProperty(window, 'localStorage', {
+ configurable: true,
+ value: unavailableStorage,
+ });
+
+ try {
+ render();
+ window.dispatchEvent(new Event(STORY_INTERACTION_EVENT));
+
+ await waitFor(() => {
+ expect(screen.queryByTestId('push-notification-opt-in')).toBeNull();
+ });
+ expect(mocks.fetchConfig).not.toHaveBeenCalled();
+ expect(requestPermission).not.toHaveBeenCalled();
+ } finally {
+ if (descriptor) Object.defineProperty(window, 'localStorage', descriptor);
+ }
+ });
+
+ it('does not offer push in an ordinary iOS browser tab', async () => {
+ Object.defineProperty(navigator, 'userAgent', {
+ configurable: true,
+ value: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)',
+ });
+ try {
+ localStorage.setItem('viewed', '[1]');
+ render();
+
+ await waitFor(() => {
+ expect(screen.queryByTestId('push-notification-opt-in')).toBeNull();
+ });
+ expect(mocks.fetchConfig).not.toHaveBeenCalled();
+ expect(requestPermission).not.toHaveBeenCalled();
+ } finally {
+ Reflect.deleteProperty(navigator, 'userAgent');
+ }
+ });
+});
diff --git a/src/components/PushNotificationOptIn.tsx b/src/components/PushNotificationOptIn.tsx
new file mode 100644
index 0000000..16da32e
--- /dev/null
+++ b/src/components/PushNotificationOptIn.tsx
@@ -0,0 +1,52 @@
+import { BellRing, X } from 'lucide-react';
+import { usePushNotifications } from '../hooks/usePushNotifications';
+import { Button } from './ui';
+
+export function PushNotificationOptIn() {
+ const {
+ status,
+ shouldOffer,
+ isRepair,
+ threshold,
+ enable,
+ dismiss,
+ } = usePushNotifications();
+
+ if (!shouldOffer) return null;
+ const enabling = status === 'enabling';
+ const action = isRepair ? 'Repair alerts' : 'Enable alerts';
+
+ return (
+
+ );
+}
diff --git a/src/components/index.ts b/src/components/index.ts
index c8ec494..33d59c1 100644
--- a/src/components/index.ts
+++ b/src/components/index.ts
@@ -18,3 +18,4 @@ export { FullScreenComment, FullScreenCommentSkeleton, FullScreenCommentSkeleton
export { CommentsSection } from './CommentsSection';
export { StateView } from './StateView';
export { NetworkStatusBar } from './NetworkStatusBar';
+export { PushNotificationOptIn } from './PushNotificationOptIn';
diff --git a/src/hooks/usePushNotifications.ts b/src/hooks/usePushNotifications.ts
new file mode 100644
index 0000000..d3d5b7c
--- /dev/null
+++ b/src/hooks/usePushNotifications.ts
@@ -0,0 +1,584 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import {
+ applicationServerKey,
+ createPushToken,
+ deletePushSubscription,
+ fetchPushConfig,
+ isPushApiConfigured,
+ PushApiError,
+ putPushSubscription,
+ type PushConfig,
+} from '../api/push';
+import { getServiceWorkerRegistration } from '../pwa/serviceWorker';
+import {
+ STORY_INTERACTION_EVENT,
+} from '../utils/storyInteraction';
+import {
+ VIEWED_DETAIL_TIMES_KEY,
+ VIEWED_KEY,
+ VIEWED_TITLE_TIMES_KEY,
+} from '../utils/viewedItems';
+
+const TOKEN_KEY = 'push:token';
+const OFFER_HANDLED_KEY = 'push:offer-handled';
+const RECONCILED_AT_KEY = 'push:reconciled-at';
+const PENDING_DELETE_KEY = 'push:pending-delete';
+const RECONCILE_INTERVAL_MS = 24 * 60 * 60 * 1000;
+const STORAGE_PROBE_KEY = 'push:storage-probe';
+let pendingDeleteFlush: Promise | null = null;
+
+export type PushNotificationStatus =
+ | 'checking'
+ | 'off'
+ | 'enabling'
+ | 'on'
+ | 'sync-error'
+ | 'denied'
+ | 'unsupported'
+ | 'offline'
+ | 'not-ready'
+ | 'capacity-full'
+ | 'repair';
+
+interface PushRuntime {
+ config: PushConfig;
+ applicationServerKey: Uint8Array;
+ registration: ServiceWorkerRegistration;
+ subscription: PushSubscription | null;
+ needsRepair: boolean;
+}
+
+export interface PushNotificationsState {
+ status: PushNotificationStatus;
+ shouldOffer: boolean;
+ isRepair: boolean;
+ threshold: number;
+ enable: () => void;
+ dismiss: () => void;
+}
+
+function storageGet(key: string): string | null {
+ try {
+ return localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+
+function storageSet(key: string, value: string): boolean {
+ try {
+ localStorage.setItem(key, value);
+ return localStorage.getItem(key) === value;
+ } catch {
+ return false;
+ }
+}
+
+function storageRemove(key: string): void {
+ try {
+ localStorage.removeItem(key);
+ } catch {
+ /* Push remains best-effort if storage is unavailable. */
+ }
+}
+
+function storageRemoveIfValue(key: string, expected: string): void {
+ if (storageGet(key) === expected) storageRemove(key);
+}
+
+function canPersistPushState(): boolean {
+ try {
+ const previous = localStorage.getItem(STORAGE_PROBE_KEY);
+ localStorage.setItem(STORAGE_PROBE_KEY, '1');
+ const stored = localStorage.getItem(STORAGE_PROBE_KEY) === '1';
+ if (previous === null) localStorage.removeItem(STORAGE_PROBE_KEY);
+ else localStorage.setItem(STORAGE_PROBE_KEY, previous);
+ return stored;
+ } catch {
+ return false;
+ }
+}
+
+function pendingDeleteTokens(): string[] {
+ const stored = storageGet(PENDING_DELETE_KEY);
+ if (!stored) return [];
+ try {
+ const value = JSON.parse(stored) as unknown;
+ if (Array.isArray(value)) {
+ return [...new Set(value.filter(
+ (token): token is string =>
+ typeof token === 'string' && token.length > 0 && token.length <= 128,
+ ))];
+ }
+ } catch {
+ /* A single-token marker from an earlier release is intentionally plain text. */
+ }
+ return stored.length <= 128 ? [stored] : [];
+}
+
+function writePendingDeleteTokens(tokens: readonly string[]): void {
+ const unique = [...new Set(tokens)];
+ if (unique.length === 0) {
+ storageRemove(PENDING_DELETE_KEY);
+ } else if (unique.length === 1) {
+ storageSet(PENDING_DELETE_KEY, unique[0] ?? '');
+ } else {
+ storageSet(PENDING_DELETE_KEY, JSON.stringify(unique));
+ }
+}
+
+function enqueuePendingDelete(token: string): boolean {
+ const tokens = pendingDeleteTokens();
+ if (!tokens.includes(token)) tokens.push(token);
+ writePendingDeleteTokens(tokens);
+ return pendingDeleteTokens().includes(token);
+}
+
+function removePendingDelete(token: string): void {
+ writePendingDeleteTokens(
+ pendingDeleteTokens().filter((candidate) => candidate !== token),
+ );
+}
+
+function hasStoryInteraction(): boolean {
+ return [
+ VIEWED_KEY,
+ VIEWED_TITLE_TIMES_KEY,
+ VIEWED_DETAIL_TIMES_KEY,
+ ].some((key) => storageGet(key) !== null);
+}
+
+function isIosBrowserTab(): boolean {
+ const iosDevice =
+ /iPad|iPhone|iPod/u.test(navigator.userAgent) ||
+ (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
+ if (!iosDevice) return false;
+ const standalone =
+ window.matchMedia('(display-mode: standalone)').matches ||
+ (navigator as Navigator & { standalone?: boolean }).standalone === true;
+ return !standalone;
+}
+
+function isSupported(): boolean {
+ return (
+ isPushApiConfigured() &&
+ typeof window !== 'undefined' &&
+ window.isSecureContext !== false &&
+ 'serviceWorker' in navigator &&
+ 'PushManager' in window &&
+ 'Notification' in window &&
+ !isIosBrowserTab() &&
+ canPersistPushState()
+ );
+}
+
+function keyMatches(
+ subscription: PushSubscription,
+ expected: Uint8Array,
+): boolean {
+ const current = subscription.options.applicationServerKey;
+ if (!current) return false;
+ const bytes = new Uint8Array(current);
+ return (
+ bytes.byteLength === expected.byteLength &&
+ bytes.every((byte, index) => byte === expected[index])
+ );
+}
+
+function markOfferHandled(): void {
+ storageSet(OFFER_HANDLED_KEY, '1');
+}
+
+function isDefinitivePutFailure(error: unknown): error is PushApiError {
+ return error instanceof PushApiError && (
+ error.code === 'capacity_full' ||
+ error.code === 'subscription_conflict' ||
+ [400, 401, 403, 404, 409, 410, 413, 415, 422].includes(error.status)
+ );
+}
+
+async function retireToken(token: string): Promise {
+ const queued = enqueuePendingDelete(token);
+ let deleted = false;
+ if (queued) {
+ await flushPendingDelete();
+ deleted = !pendingDeleteTokens().includes(token);
+ } else if (navigator.onLine) {
+ try {
+ await deletePushSubscription(token);
+ deleted = true;
+ } catch {
+ /* Keep the current token so a later lifecycle refresh can retry. */
+ }
+ }
+ if (deleted || pendingDeleteTokens().includes(token)) {
+ storageRemoveIfValue(TOKEN_KEY, token);
+ if (storageGet(TOKEN_KEY) === null) storageRemove(RECONCILED_AT_KEY);
+ }
+}
+
+async function flushPendingDelete(): Promise {
+ if (!navigator.onLine) return;
+ pendingDeleteFlush ??= (async () => {
+ for (const token of pendingDeleteTokens()) {
+ try {
+ await deletePushSubscription(token);
+ removePendingDelete(token);
+ } catch {
+ /* Keep this token queued for the next lifecycle refresh. */
+ }
+ }
+ })().finally(() => {
+ pendingDeleteFlush = null;
+ });
+ await pendingDeleteFlush;
+}
+
+export function usePushNotifications(): PushNotificationsState {
+ const [status, setStatus] = useState('checking');
+ const [runtime, setRuntime] = useState(null);
+ const [engaged, setEngaged] = useState(hasStoryInteraction);
+ const [offerHandled, setOfferHandled] = useState(
+ () => storageGet(OFFER_HANDLED_KEY) === '1',
+ );
+ const runtimeRef = useRef(null);
+ const refreshGeneration = useRef(0);
+ const enrollmentInFlight = useRef(false);
+ const refreshPending = useRef(false);
+
+ const refresh = useCallback(() => {
+ if (enrollmentInFlight.current) {
+ refreshPending.current = true;
+ return;
+ }
+ const generation = ++refreshGeneration.current;
+ if (!isSupported()) {
+ setRuntime(null);
+ runtimeRef.current = null;
+ setStatus(isPushApiConfigured() ? 'unsupported' : 'not-ready');
+ return;
+ }
+ if (Notification.permission === 'denied') {
+ setStatus('checking');
+ void (async () => {
+ const token = storageGet(TOKEN_KEY);
+ const registration = await getServiceWorkerRegistration().catch(
+ () => null,
+ );
+ const subscription = registration
+ ? await registration.pushManager.getSubscription().catch(() => null)
+ : null;
+ if (subscription) {
+ await subscription.unsubscribe().catch(() => false);
+ }
+ if (token) await retireToken(token);
+ await flushPendingDelete();
+ if (generation !== refreshGeneration.current) return;
+ runtimeRef.current = null;
+ setRuntime(null);
+ markOfferHandled();
+ setOfferHandled(true);
+ setStatus('denied');
+ })();
+ return;
+ }
+
+ setStatus((current) => {
+ if (!navigator.onLine) return 'offline';
+ return current === 'on' ? current : 'checking';
+ });
+ void (async () => {
+ const registration = await getServiceWorkerRegistration();
+ const subscription = await registration.pushManager.getSubscription();
+ if (generation !== refreshGeneration.current) return;
+ const token = storageGet(TOKEN_KEY);
+
+ if (Notification.permission === 'denied') {
+ if (subscription) {
+ await subscription.unsubscribe().catch(() => false);
+ }
+ if (token) await retireToken(token);
+ await flushPendingDelete();
+ runtimeRef.current = null;
+ setRuntime(null);
+ markOfferHandled();
+ setOfferHandled(true);
+ setStatus('denied');
+ return;
+ }
+
+ if (!subscription && token) await retireToken(token);
+ if (!navigator.onLine) {
+ runtimeRef.current = null;
+ setRuntime(null);
+ setStatus('offline');
+ return;
+ }
+
+ await flushPendingDelete();
+ const config = await fetchPushConfig();
+ if (generation !== refreshGeneration.current) return;
+ if (hasStoryInteraction()) setEngaged(true);
+ if (!config.applicationServerKey) {
+ runtimeRef.current = null;
+ setRuntime(null);
+ setStatus('not-ready');
+ return;
+ }
+ const expectedKey = applicationServerKey(config.applicationServerKey);
+
+ if (!subscription) {
+ const needsRepair =
+ Notification.permission === 'granted' &&
+ (token !== null || config.enabled);
+ const next: PushRuntime = {
+ config,
+ applicationServerKey: expectedKey,
+ registration,
+ subscription: null,
+ needsRepair,
+ };
+ runtimeRef.current = next;
+ setRuntime(next);
+ setStatus(
+ next.needsRepair ? 'repair' : config.enabled ? 'off' : 'not-ready',
+ );
+ return;
+ }
+
+ const needsRepair = !token || !keyMatches(subscription, expectedKey);
+ let currentSubscription: PushSubscription | null = subscription;
+ if (needsRepair) {
+ const unsubscribed = await subscription.unsubscribe().catch(() => false);
+ if (generation !== refreshGeneration.current) return;
+ if (unsubscribed) currentSubscription = null;
+ }
+ const next: PushRuntime = {
+ config,
+ applicationServerKey: expectedKey,
+ registration,
+ subscription: currentSubscription,
+ needsRepair,
+ };
+ runtimeRef.current = next;
+ setRuntime(next);
+ if (needsRepair) {
+ setStatus('repair');
+ return;
+ }
+
+ setStatus('on');
+ const reconciledAt = Number(storageGet(RECONCILED_AT_KEY) ?? 0);
+ if (
+ Number.isFinite(reconciledAt) &&
+ Date.now() - reconciledAt < RECONCILE_INTERVAL_MS
+ ) {
+ return;
+ }
+ try {
+ await putPushSubscription(token, subscription);
+ storageSet(RECONCILED_AT_KEY, String(Date.now()));
+ } catch {
+ if (generation === refreshGeneration.current) setStatus('sync-error');
+ }
+ })().catch(() => {
+ if (generation !== refreshGeneration.current) return;
+ setStatus(navigator.onLine ? 'sync-error' : 'offline');
+ });
+ }, []);
+
+ useEffect(() => {
+ refresh();
+ const onRefresh = () => refresh();
+ const onVisibility = () => {
+ if (document.visibilityState === 'visible') refresh();
+ };
+ window.addEventListener('focus', onRefresh);
+ window.addEventListener('pageshow', onRefresh);
+ window.addEventListener('online', onRefresh);
+ window.addEventListener('offline', onRefresh);
+ document.addEventListener('visibilitychange', onVisibility);
+ return () => {
+ refreshGeneration.current += 1;
+ window.removeEventListener('focus', onRefresh);
+ window.removeEventListener('pageshow', onRefresh);
+ window.removeEventListener('online', onRefresh);
+ window.removeEventListener('offline', onRefresh);
+ document.removeEventListener('visibilitychange', onVisibility);
+ };
+ }, [refresh]);
+
+ useEffect(() => {
+ const onInteraction = () => setEngaged(true);
+ window.addEventListener(STORY_INTERACTION_EVENT, onInteraction);
+ return () => window.removeEventListener(STORY_INTERACTION_EVENT, onInteraction);
+ }, []);
+
+ const dismiss = useCallback(() => {
+ markOfferHandled();
+ setOfferHandled(true);
+ setStatus('off');
+ }, []);
+
+ const enable = useCallback(() => {
+ const current = runtimeRef.current;
+ if (
+ !current ||
+ enrollmentInFlight.current ||
+ status === 'enabling' ||
+ !navigator.onLine
+ ) {
+ return;
+ }
+
+ enrollmentInFlight.current = true;
+ setStatus('enabling');
+ const subscribe = async (): Promise => {
+ const existing = current.subscription;
+ if (existing && !current.needsRepair) return existing;
+ if (existing) await existing.unsubscribe();
+ return current.registration.pushManager.subscribe({
+ userVisibleOnly: true,
+ applicationServerKey: current.applicationServerKey,
+ });
+ };
+
+ let enrollment: Promise;
+ if (Notification.permission === 'granted') {
+ enrollment = subscribe();
+ } else if (Notification.permission === 'default') {
+ enrollment = Notification.requestPermission().then((permission) => {
+ markOfferHandled();
+ setOfferHandled(true);
+ return permission === 'granted' ? subscribe() : null;
+ });
+ } else {
+ enrollment = Promise.resolve(null);
+ }
+
+ void enrollment
+ .then(async (subscription) => {
+ markOfferHandled();
+ setOfferHandled(true);
+ if (!subscription) {
+ setStatus(Notification.permission === 'denied' ? 'denied' : 'off');
+ return;
+ }
+
+ const previousToken = storageGet(TOKEN_KEY);
+ let token = previousToken ?? createPushToken();
+ if (!storageSet(TOKEN_KEY, token)) {
+ await subscription.unsubscribe().catch(() => false);
+ const repair = {
+ ...current,
+ subscription: null,
+ needsRepair: true,
+ };
+ runtimeRef.current = repair;
+ setRuntime(repair);
+ setStatus('sync-error');
+ return;
+ }
+ storageRemove(RECONCILED_AT_KEY);
+ const next = { ...current, subscription, needsRepair: false };
+ runtimeRef.current = next;
+ setRuntime(next);
+ try {
+ await putPushSubscription(token, subscription);
+ storageSet(RECONCILED_AT_KEY, String(Date.now()));
+ setStatus('on');
+ } catch (error) {
+ let enrollmentError = error;
+ if (
+ previousToken &&
+ enrollmentError instanceof PushApiError &&
+ enrollmentError.code === 'subscription_conflict'
+ ) {
+ await retireToken(previousToken);
+ token = createPushToken();
+ if (!storageSet(TOKEN_KEY, token)) {
+ await subscription.unsubscribe().catch(() => false);
+ const repair = {
+ ...next,
+ subscription: null,
+ needsRepair: true,
+ };
+ runtimeRef.current = repair;
+ setRuntime(repair);
+ setStatus('sync-error');
+ return;
+ }
+ try {
+ await putPushSubscription(token, subscription);
+ storageSet(RECONCILED_AT_KEY, String(Date.now()));
+ setStatus('on');
+ return;
+ } catch (replacementError) {
+ enrollmentError = replacementError;
+ }
+ }
+ if (isDefinitivePutFailure(enrollmentError)) {
+ await subscription.unsubscribe().catch(() => false);
+ await retireToken(token);
+ const repair = {
+ ...next,
+ subscription: null,
+ needsRepair: true,
+ };
+ runtimeRef.current = repair;
+ setRuntime(repair);
+ setStatus(
+ enrollmentError.code === 'capacity_full'
+ ? 'capacity-full'
+ : 'sync-error',
+ );
+ return;
+ }
+ // The PUT may have committed before the response was lost. Keep the
+ // token/subscription and reconcile idempotently on the next lifecycle event.
+ setStatus('sync-error');
+ }
+ })
+ .catch(() => {
+ const latest = runtimeRef.current;
+ if (latest && Notification.permission === 'granted') {
+ const repair = {
+ ...latest,
+ needsRepair: true,
+ };
+ runtimeRef.current = repair;
+ setRuntime(repair);
+ }
+ setStatus('sync-error');
+ })
+ .finally(() => {
+ enrollmentInFlight.current = false;
+ if (refreshPending.current) {
+ refreshPending.current = false;
+ refresh();
+ }
+ });
+ }, [refresh, status]);
+
+ const shouldOffer = useMemo(() => {
+ if (!runtime || !navigator.onLine) return false;
+ if (status === 'enabling') return true;
+ if (runtime.needsRepair) return status === 'repair' || status === 'sync-error';
+ if (!runtime.config.enabled) return false;
+ return (
+ !offerHandled &&
+ engaged &&
+ Notification.permission === 'default' &&
+ status === 'off'
+ );
+ }, [engaged, offerHandled, runtime, status]);
+
+ return {
+ status,
+ shouldOffer,
+ isRepair: runtime?.needsRepair ?? false,
+ threshold: runtime?.config.threshold ?? 1000,
+ enable,
+ dismiss,
+ };
+}
diff --git a/src/main.tsx b/src/main.tsx
index 2851b4b..63511fb 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App'
import { pruneExpiredViewed } from './utils/viewedItems'
+import { preloadServiceWorkerRegistration } from './pwa/serviceWorker'
// Clean up expired viewed entries on app load (runs exactly once)
pruneExpiredViewed();
@@ -19,8 +20,6 @@ createRoot(document.getElementById('root')!).render(
// clients.claim, so a new deploy takes over on the next load.
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
window.addEventListener('load', () => {
- navigator.serviceWorker.register('/sw.js').catch(() => {
- /* offline support is optional β ignore registration failures */
- });
+ preloadServiceWorkerRegistration();
});
}
diff --git a/src/pwa/serviceWorker.test.ts b/src/pwa/serviceWorker.test.ts
new file mode 100644
index 0000000..f37292d
--- /dev/null
+++ b/src/pwa/serviceWorker.test.ts
@@ -0,0 +1,55 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ getServiceWorkerRegistration,
+ resetServiceWorkerRegistrationForTests,
+} from './serviceWorker';
+
+function installServiceWorkerMock(value: {
+ register: () => Promise;
+ ready: Promise;
+}): void {
+ Object.defineProperty(navigator, 'serviceWorker', {
+ configurable: true,
+ value,
+ });
+}
+
+afterEach(() => {
+ resetServiceWorkerRegistrationForTests();
+ vi.useRealTimers();
+});
+
+describe('service worker registration', () => {
+ it('reuses an active bounded registration', async () => {
+ const registration = {
+ active: {},
+ } as ServiceWorkerRegistration;
+ const register = vi.fn().mockResolvedValue(registration);
+ installServiceWorkerMock({
+ register,
+ ready: Promise.resolve(registration),
+ });
+
+ await expect(getServiceWorkerRegistration()).resolves.toBe(registration);
+ await expect(getServiceWorkerRegistration()).resolves.toBe(registration);
+ expect(register).toHaveBeenCalledExactlyOnceWith('/sw.js?push-dev=1');
+ });
+
+ it('rejects instead of waiting forever for readiness', async () => {
+ vi.useFakeTimers();
+ const registration = { active: null } as unknown as ServiceWorkerRegistration;
+ installServiceWorkerMock({
+ register: vi.fn().mockResolvedValue(registration),
+ ready: new Promise(() => {
+ /* Deliberately unresolved. */
+ }),
+ });
+
+ const pending = getServiceWorkerRegistration(100);
+ void pending.catch(() => {
+ /* Attach a handler before advancing timers to avoid an unhandled rejection. */
+ });
+ await vi.advanceTimersByTimeAsync(100);
+ await expect(pending).rejects.toThrow('service_worker_ready_timeout');
+ });
+});
diff --git a/src/pwa/serviceWorker.ts b/src/pwa/serviceWorker.ts
new file mode 100644
index 0000000..34d297a
--- /dev/null
+++ b/src/pwa/serviceWorker.ts
@@ -0,0 +1,68 @@
+const DEFAULT_TIMEOUT_MS = 8_000;
+const SERVICE_WORKER_URL = import.meta.env.DEV
+ ? '/sw.js?push-dev=1'
+ : '/sw.js';
+
+let registrationPromise: Promise | null = null;
+
+function withTimeout(
+ promise: Promise,
+ timeoutMs: number,
+ message: string,
+): Promise {
+ return new Promise((resolve, reject) => {
+ const timeout = window.setTimeout(() => reject(new Error(message)), timeoutMs);
+ promise.then(
+ (value) => {
+ window.clearTimeout(timeout);
+ resolve(value);
+ },
+ (error: unknown) => {
+ window.clearTimeout(timeout);
+ reject(error instanceof Error ? error : new Error(message));
+ },
+ );
+ });
+}
+
+export function supportsServiceWorkers(): boolean {
+ return typeof navigator !== 'undefined' && 'serviceWorker' in navigator;
+}
+
+export function getServiceWorkerRegistration(
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+): Promise {
+ if (!supportsServiceWorkers()) {
+ return Promise.reject(new Error('service_worker_unsupported'));
+ }
+
+ registrationPromise ??= (async () => {
+ const registered = await withTimeout(
+ navigator.serviceWorker.register(SERVICE_WORKER_URL),
+ timeoutMs,
+ 'service_worker_registration_timeout',
+ );
+ if (registered.active) return registered;
+ return withTimeout(
+ navigator.serviceWorker.ready,
+ timeoutMs,
+ 'service_worker_ready_timeout',
+ );
+ })().catch((error: unknown) => {
+ registrationPromise = null;
+ throw error;
+ });
+
+ return registrationPromise;
+}
+
+export function preloadServiceWorkerRegistration(): void {
+ if (!supportsServiceWorkers()) return;
+ void getServiceWorkerRegistration().catch(() => {
+ /* Progressive enhancement: the app remains usable without a service worker. */
+ });
+}
+
+export function resetServiceWorkerRegistrationForTests(): void {
+ registrationPromise = null;
+}
diff --git a/src/utils/storyInteraction.ts b/src/utils/storyInteraction.ts
new file mode 100644
index 0000000..e0b9f56
--- /dev/null
+++ b/src/utils/storyInteraction.ts
@@ -0,0 +1,6 @@
+export const STORY_INTERACTION_EVENT = 'hackertok:story-interaction';
+
+export function announceStoryInteraction(): void {
+ if (typeof window === 'undefined') return;
+ window.dispatchEvent(new Event(STORY_INTERACTION_EVENT));
+}
diff --git a/src/utils/viewedItems.ts b/src/utils/viewedItems.ts
index 657ecd9..3b3578d 100644
--- a/src/utils/viewedItems.ts
+++ b/src/utils/viewedItems.ts
@@ -1,4 +1,5 @@
import { useSyncExternalStore } from 'react';
+import { announceStoryInteraction } from './storyInteraction';
/** Track viewed items in localStorage. */
@@ -175,19 +176,24 @@ export function markViewedWithTime(
ttlHours = kind === 'title' ? TITLE_CLICK_TTL_HOURS : DETAIL_VIEW_TTL_HOURS,
): void {
const id = Number(itemId);
+ const viewedAt = Date.now();
if (kind === 'title') markViewed(id);
addToSessionViewed(id);
const map = kind === 'title' ? titleTimeMap : detailTimeMap;
- const nextExpiry = Date.now() + ttlHours * 3_600_000;
+ const nextExpiry = viewedAt + ttlHours * 3_600_000;
const times = map.load();
const merged = Math.max(times[id] ?? 0, nextExpiry);
// Skip the stringify + write when the merge changes nothing β e.g. re-viewing
// an item whose hide window is already longer, or an idempotent re-finalize.
- if (merged === times[id]) return;
+ if (merged === times[id]) {
+ announceStoryInteraction();
+ return;
+ }
times[id] = merged;
map.save();
+ announceStoryInteraction();
}
export function pruneExpiredViewed(): void {
diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts
index 11f02fe..f7dc9cd 100644
--- a/src/vite-env.d.ts
+++ b/src/vite-env.d.ts
@@ -1 +1,9 @@
///
+
+interface ImportMetaEnv {
+ readonly VITE_PUSH_API_URL?: string;
+}
+
+interface ImportMeta {
+ readonly env: ImportMetaEnv;
+}
diff --git a/vite.config.js b/vite.config.js
index 03e0401..9b32d39 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1,7 +1,7 @@
///
import { fileURLToPath } from 'node:url'
import { createHash } from 'node:crypto'
-import { defineConfig } from 'vite'
+import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
@@ -10,7 +10,7 @@ import tailwindcss from '@tailwindcss/vite'
// script-src avoids 'unsafe-inline' by hashing executable inline scripts from
// the FINAL html (order: 'post') so hashes can't drift; inert blocks like
//