import { useCallback, useEffect, useRef, useState } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { RUN_EVENTS_URL } from '../api/client'; import type { RunEvent } from '../api/types'; import type { NotificationToggleState } from '../ui'; import { useAuth } from '../auth/useAuth'; const STORAGE_KEY = 'liqa-run-notifications'; const RETRY_MIN_MS = 1_000; const RETRY_MAX_MS = 30_000; export function createRunEventSource(): EventSource { return new EventSource(RUN_EVENTS_URL, { withCredentials: true }); } function supported(): boolean { return typeof window !== 'undefined' && 'Notification' in window && 'EventSource' in window; } /** The stored choice: `null` until the user toggles notifications explicitly. */ function readEnabled(): boolean | null { try { const value = localStorage.getItem(STORAGE_KEY); return value === null ? null : value === '1'; } catch { return null; } } function writeEnabled(enabled: boolean): void { try { localStorage.setItem(STORAGE_KEY, enabled ? '1' : '0'); } catch { // storage unavailable: the choice just doesn't persist } } /** * Opt-in browser notifications for run start/finish, driven by the server's * run events stream (so runs started from the API, MCP or the scheduler are * covered too). Returns `null` when the browser lacks Notification/EventSource. */ export function useRunNotifications(): { state: NotificationToggleState; toggle: () => void; } | null { const auth = useAuth(); const isSupported = supported(); const { t } = useTranslation(); const navigate = useNavigate(); const queryClient = useQueryClient(); const [stored, setStored] = useState(readEnabled); const [permission, setPermission] = useState(() => isSupported ? Notification.permission : 'denied', ); // Permission granted outside the toggle (browser prompt or site settings) // enables notifications unless the user turned them off explicitly const enabled = stored ?? permission === 'granted'; // Follow permission changes made in the browser's site settings useEffect(() => { if (!isSupported) return; const sync = () => setPermission(Notification.permission); let status: PermissionStatus | undefined; let cancelled = false; navigator.permissions ?.query({ name: 'notifications' }) .then((s) => { if (cancelled) return; status = s; status.addEventListener('change', sync); }) .catch(() => {}); window.addEventListener('focus', sync); return () => { cancelled = true; status?.removeEventListener('change', sync); window.removeEventListener('focus', sync); }; }, [isSupported]); // Latest callbacks without reopening the stream when they change const handlers = useRef({ t, navigate }); useEffect(() => { handlers.current = { t, navigate }; }); const active = isSupported && enabled && permission === 'granted' && (!auth.enabled || auth.status === 'authenticated'); useEffect(() => { if (!active) return; let source: EventSource; let retryTimer: ReturnType | undefined; let retryDelay = RETRY_MIN_MS; const onEvent = (message: MessageEvent) => { let event: RunEvent; try { event = JSON.parse(message.data) as RunEvent; } catch { return; } if (event.type === 'run.finished') { void queryClient.invalidateQueries({ queryKey: ['runs'] }); } const { t: translate, navigate: go } = handlers.current; const key = event.type === 'run.started' ? 'run_started' : event.status === 'pass' ? 'run_pass' : 'run_fail'; const notification = new Notification( translate(`notifications.${key}_title`, { scenario: event.scenarioName }), { body: translate(`notifications.${key}_body`), // finished replaces started for the same run tag: event.runId, }, ); notification.onclick = () => { window.focus(); go(`/scenarios/${event.scenarioId}/runs/${event.runId}`); notification.close(); }; }; const connect = () => { source = createRunEventSource(); source.addEventListener('open', () => { retryDelay = RETRY_MIN_MS; }); // The browser retries transient errors itself, but some failures close // the stream for good (e.g. Firefox drops quiet connections after a // network change), so reopen it with backoff source.addEventListener('error', () => { if (source.readyState !== EventSource.CLOSED) return; retryTimer = setTimeout(connect, retryDelay); retryDelay = Math.min(retryDelay * 2, RETRY_MAX_MS); }); source.addEventListener('run.started', onEvent as EventListener); source.addEventListener('run.finished', onEvent as EventListener); }; connect(); return () => { clearTimeout(retryTimer); source.close(); }; }, [active, queryClient]); const toggle = useCallback(() => { if (!isSupported) return; if (Notification.permission === 'default') { void Notification.requestPermission().then((result) => { setPermission(result); if (result === 'granted') { setStored(true); writeEnabled(true); } }); return; } if (Notification.permission !== 'granted') { setPermission(Notification.permission); return; } const next = !enabled; setStored(next); writeEnabled(next); }, [isSupported, enabled]); if (!isSupported) return null; return { state: permission === 'denied' ? 'blocked' : active ? 'on' : 'off', toggle, }; }