Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
PWA push: notify this device when the app is closed
Pixel (kwant bot)6d081e1d9b5a
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex ffcb2886..d1229caf 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -63,6 +63,7 @@ import {import { Profile, describeProfileSwitch, profilesApi } from './profiles';import {NotifyEvent,+ NotifyKind,SearchHit,TOAST_KINDS,browserNotifyEnabled,@@ -93,6 +94,7 @@ import { claudeNeedsSignIn } from './claudeLogin';import { personFetch } from './auth';import { teamChannelOf, teamOfChannel } from './teamChannel';import { PromptContext, suggestedPrompts } from './suggestedPrompts';+import { isNotificationOpen, showDeviceNotification } from './push';// Kwant and Tools editors are their own chunks. They stay mounted (rendering nothing while closed),// so both load right after start-up and opening them never waits.@@ -337,19 +339,31 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({return;}if (!shouldShowOsNotification({ enabled: browserNotifyEnabled(), permission: notificationPermission(), hidden: document.hidden, kind: n.kind })) return;- try {- const note = new Notification(n.title, { body: n.body, tag: `kwnt-${n.kind}-${n.channel_id ?? n.kwant_id}` });- note.onclick = () => {- window.focus();- if (n.kind === 'skill_proposed') openSkillsRef.current(n.kwant_id);- else if (n.kind === 'human_step' && openHumanStepRef.current(n.kwant_id)) setIsVmPaneOpen(true);- else if (!(n.kind === 'question_asked' && openQuestionRef.current(n.kwant_id))) openTargetRef.current(target);- note.close();- };- } catch {- // Some mobile browsers only allow notifications from a service worker.- }+ showDeviceNotification({ ...n, space_id: n.space_id ?? space.id }, () => openNotifiedRef.current(n)).catch(() => undefined);};+ // A tap on a notification: the bot's skill, question or browser step, else its chat.+ const openNotified = (n: Pick<NotifyEvent, 'kind' | 'kwant_id' | 'channel_id'>) => {+ const target = { channel_id: n.channel_id, kwant_id: n.kwant_id };+ if (n.kind === 'skill_proposed') openSkillsRef.current(n.kwant_id);+ else if (n.kind === 'human_step' && openHumanStepRef.current(n.kwant_id)) setIsVmPaneOpen(true);+ else if (!(n.kind === 'question_asked' && openQuestionRef.current(n.kwant_id))) openTargetRef.current(target);+ };+ const openNotifiedRef = useRef(openNotified);+ openNotifiedRef.current = openNotified;+ // Taps on notifications shown through the service worker (pushes and this page's own) arrive+ // here; another space's are the shell's.+ useEffect(() => {+ const sw = 'serviceWorker' in navigator ? navigator.serviceWorker : null;+ if (!sw) return;+ const onMessage = (e: MessageEvent) => {+ const m = e.data;+ if (!isNotificationOpen(m) || !m.kwant_id) return;+ if (m.space_id && m.space_id !== space.id) return;+ openNotifiedRef.current({ kind: m.kind as NotifyKind, kwant_id: m.kwant_id, channel_id: m.channel_id });+ };+ sw.addEventListener('message', onMessage);+ return () => sw.removeEventListener('message', onMessage);+ }, [space.id]);const showNotificationRef = useRef(showNotification);showNotificationRef.current = showNotification;const refreshProfiles = useCallback(() => {diff --git a/frontend/src/Shell.tsx b/frontend/src/Shell.tsxindex 15dfe4b7..89694a27 100644--- a/frontend/src/Shell.tsx+++ b/frontend/src/Shell.tsx@@ -23,6 +23,7 @@ import {spacesApi,} from './spaces';import { NotifyEvent, TOAST_KINDS, browserNotifyEnabled, notificationPermission, shouldShowOsNotification } from './continuity';+import { isNotificationOpen, resyncPushOnLoad, showDeviceNotification, targetFromQuery } from './push';const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) => ({ default: m.SettingsModal })));@@ -77,7 +78,9 @@ export const App: React.FC = () => {useEffect(() => {reload().then((list) => {if (!list) return;- const route = parseSpacePath(window.location.pathname);+ // A notification's `/?space=…&channel=…` link counts as the chat's own address.+ const q = targetFromQuery(window.location.search);+ const route = q ? { spaceId: q.spaceId, channelId: q.channelId ?? undefined, botId: q.botId ?? undefined } : parseSpacePath(window.location.pathname);const s = pickSpace(list, route.spaceId, lastSpace());if (!s) return;const fromUrl = route.spaceId === s.id && (route.channelId || route.botId) ? { channelId: route.channelId, botId: route.botId } : null;@@ -157,16 +160,7 @@ export const App: React.FC = () => {return;}if (!shouldShowOsNotification({ enabled: browserNotifyEnabled(), permission: notificationPermission(), hidden: document.hidden, kind: n.kind })) return;- try {- const note = new Notification(n.title, { body: n.body, tag: `kwnt-${sid}-${n.kind}-${n.channel_id ?? n.kwant_id}` });- note.onclick = () => {- window.focus();- go();- note.close();- };- } catch {- // Some mobile browsers only allow notifications from a service worker.- }+ showDeviceNotification({ ...n, space_id: sid }, go).catch(() => undefined);} catch {// not an event we know}@@ -174,6 +168,27 @@ export const App: React.FC = () => {return () => sse.close();}, [activeCount, switchTo, reload]);+ // A tap on a notification from another space (sw.js posts it): switch there. The open space's+ // own are SpaceApp's, which can also open a question or browser step.+ useEffect(() => {+ const sw = 'serviceWorker' in navigator ? navigator.serviceWorker : null;+ if (!sw) return;+ const onMessage = (e: MessageEvent) => {+ const m = e.data;+ if (!isNotificationOpen(m) || !m.space_id || m.space_id === currentRef.current) return;+ if (!spaces?.some((s) => s.id === m.space_id)) return;+ switchTo(m.space_id, m.channel_id ? { channelId: m.channel_id } : m.kwant_id ? { botId: m.kwant_id } : null);+ };+ sw.addEventListener('message', onMessage);+ return () => sw.removeEventListener('message', onMessage);+ }, [spaces, switchTo]);++ // Re-tell the server about this device's push subscription (it drops one the push service+ // rejected, or on sign-out), once per load.+ useEffect(() => {+ resyncPushOnLoad().catch(() => undefined);+ }, []);+const openCreate = useCallback(() => {playSfx('click');// Archived spaces keep their names and colours, so they count as taken.diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex dd589824..19d9d059 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -10,6 +10,9 @@ import {notificationPermission,webhookUrlError,} from '../continuity';+import { deviceNotifyHint, deviceNotifySupport, isAndroid, notifyEnv as browserNotifyEnv, subscribePush, swRegistration, unsubscribePush } from '../push';++const readNotifyEnv = () => ({ ...browserNotifyEnv(), android: isAndroid(navigator) });import { isSfxMuted, playSfx, toggleSfxMute } from '../audio/chiptune';import { useAuth } from './AuthGate';import { SignedInDevices } from './DeviceSignIn';@@ -74,6 +77,10 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tconst [notifyOn, setNotifyOn] = useState<NotifyKind[]>(NOTIFY_KINDS.map((k) => k.id));const [browserNotify, setBrowserNotify] = useState(browserNotifyEnabled);const [permission, setPermission] = useState(notificationPermission);+ const [notifyEnv] = useState(() => readNotifyEnv());+ const support = deviceNotifySupport(notifyEnv);+ const [notifyBusy, setNotifyBusy] = useState(false);+ const [notifyError, setNotifyError] = useState<string | null>(null);const webhookError = webhookUrlError(webhookUrl);// Kept as typed text so a half-typed value can be shown with its error; null until loaded.const [limits, setLimits] = useState<Record<TurnLimitKey, string> | null>(null);@@ -99,6 +106,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tsetSaveError(null);setPermission(notificationPermission());setBrowserNotify(browserNotifyEnabled());+ setNotifyError(null);fetch('/api/settings').then((r) => r.json()).then((data: SettingsData) => {@@ -126,22 +134,44 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tif (!isOpen) return null;- // Permission is only ever asked from this click, never on load.+ // Permission is only ever asked from this click, never on load. On: this page's notifications+ // and, where the browser has push, a subscription so they come with kwant closed. Off: both go.const toggleBrowserNotify = async () => {+ if (notifyBusy) return;playSfx('click');+ setNotifyError(null);if (browserNotify) {localStorage.setItem(BROWSER_NOTIFY_KEY, 'off');setBrowserNotify(false);+ if (support === 'push') {+ setNotifyBusy(true);+ const reg = await swRegistration();+ if (reg) await unsubscribePush(reg).catch(() => undefined);+ setNotifyBusy(false);+ }return;}let p = notificationPermission();if (p === 'default') p = await Notification.requestPermission();setPermission(p);- if (p === 'granted') {- localStorage.setItem(BROWSER_NOTIFY_KEY, 'on');- setBrowserNotify(true);+ if (p !== 'granted') return;+ localStorage.setItem(BROWSER_NOTIFY_KEY, 'on');+ setBrowserNotify(true);+ if (support !== 'push') return;+ setNotifyBusy(true);+ try {+ const reg = await swRegistration();+ if (!reg) throw new Error('The app isn’t set up in this browser yet. Reload the page and try again.');+ await subscribePush(reg);+ } catch (err) {+ const why = (err instanceof Error ? err.message : 'unknown error').replace(/[.!?]?$/, (m) => m || '.');+ setNotifyError(`Couldn’t set up notifications for when the app is closed: ${why} You’ll still get them while it’s open.`);+ } finally {+ setNotifyBusy(false);}};+ const notifyHint = deviceNotifyHint({ support, permission, on: browserNotify, android: notifyEnv.android, standalone: notifyEnv.standalone });+ const notifyBlocked = support === 'insecure' || support === 'ios-install' || support === 'unsupported';const handleSave = async (e: React.FormEvent) => {e.preventDefault();@@ -419,29 +449,35 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t<span>Notifications</span></legend>- <div className="flex items-start gap-3 bg-zinc-950/60 p-3 rounded-xl border border-zinc-800">- <div className="flex-1">- <p id="browser-notify-label" className="text-xs font-medium text-zinc-200">Notify me on this computer</p>- <p className="text-[11px] text-zinc-500">- Only while this tab is in the background. Each notification names its space.- {permission === 'denied' && <span className="text-amber-300"> Blocked by your browser; allow notifications for this site in its settings.</span>}- {permission === 'unsupported' && <span className="text-amber-300"> This browser can't show notifications.</span>}+ <div className="flex items-start gap-3 bg-zinc-950/60 p-3 rounded-xl border border-zinc-800" data-testid="device-notify">+ <div className="flex-1 min-w-0">+ <p id="browser-notify-label" className="text-xs font-medium text-zinc-200">Notify me on this device</p>+ <p id="browser-notify-hint" className={`text-[11px] ${notifyHint.warn ? 'text-amber-300' : 'text-zinc-500'}`}>+ {notifyHint.text}</p>+ {notifyError && (+ <p className="mt-1 text-[11px] text-rose-400" role="alert">+ {notifyError}+ </p>+ )}</div>+ {/* The track stays 36×20; the button around it is a 44×44 tap target. */}<buttontype="button"role="switch"aria-checked={browserNotify}aria-labelledby="browser-notify-label"- disabled={permission === 'unsupported' || (permission === 'denied' && !browserNotify)}+ aria-describedby="browser-notify-hint"+ aria-busy={notifyBusy}+ disabled={notifyBusy || (!browserNotify && (notifyBlocked || permission === 'denied'))}onClick={toggleBrowserNotify}- className={`relative shrink-0 w-9 h-5 rounded-full transition-colors disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${- browserNotify ? 'bg-sky-600' : 'bg-zinc-700'- }`}+ className="group shrink-0 -m-3 p-3 rounded-full disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500">- <span- className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform motion-reduce:transition-none ${browserNotify ? 'translate-x-4' : ''}`}- />+ <span className={`relative block w-9 h-5 rounded-full transition-colors ${browserNotify ? 'bg-sky-600' : 'bg-zinc-700'}`}>+ <span+ className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform motion-reduce:transition-none ${browserNotify ? 'translate-x-4' : ''}`}+ />+ </span></button></div>diff --git a/frontend/src/push.ts b/frontend/src/push.tsnew file mode 100644index 00000000..19640597--- /dev/null+++ b/frontend/src/push.ts@@ -0,0 +1,250 @@+// Notifications on this device: the OS notification the open page shows, and Web Push, which+// reaches the installed app (or the browser) when kwant is closed. The server sends a push for+// each kind ticked under "Tell me when" to every subscribed device (src/server/push.rs); the+// service worker (sw.js) shows it. Page and push use the same tag, so one replaces the other.+import { BROWSER_NOTIFY_KEY, NotifyEvent, notificationPermission } from './continuity';+import { isIos, isStandalone } from './pwa';+import { spacePath } from './spaces';++/** Same as the server's push tag: `kwnt-<space|none>-<kind>-<channel|bot>`. */+export function notificationTag(n: Pick<NotifyEvent, 'kind' | 'kwant_id' | 'channel_id'> & { space_id?: string | null }): string {+ return `kwnt-${n.space_id || 'none'}-${n.kind}-${n.channel_id ?? n.kwant_id}`;+}++/** Where a tap on the notification goes: the chat's own address, or the app's start. */+export function notificationPath(n: { space_id?: string | null; channel_id?: string | null; kwant_id?: string | null }): string {+ if (!n.space_id) return '/';+ return spacePath(n.space_id, { channelId: n.channel_id, botId: n.channel_id ? null : n.kwant_id });+}++/** What a tap on a notification asks the open app to show (sw.js posts it; App and Shell act on it). */+export interface NotificationOpen {+ type: 'kwnt-notification-open';+ kind: string;+ space_id: string | null;+ channel_id: string | null;+ kwant_id: string | null;+}++export function isNotificationOpen(m: unknown): m is NotificationOpen {+ return !!m && typeof m === 'object' && (m as { type?: unknown }).type === 'kwnt-notification-open';+}++/** `?space=…&channel=…` / `&kwant=…`: the push payload's url, for a link opened outside the worker. */+export function targetFromQuery(search: string): { spaceId: string | null; channelId: string | null; botId: string | null } | null {+ const q = new URLSearchParams(search);+ const spaceId = q.get('space');+ const channelId = q.get('channel');+ const botId = channelId ? null : q.get('kwant');+ if (!spaceId && !channelId && !botId) return null;+ return { spaceId, channelId, botId };+}++// ---------------------------------------------------------------------------+// Can this device get notifications, and how?++export type DeviceNotifySupport =+ /** Push and page notifications: works with kwant closed. */+ | 'push'+ /** Only the open page's notifications (no service worker or push here). */+ | 'page'+ /** Plain http on another computer: browsers allow neither. */+ | 'insecure'+ /** iPhone or iPad in Safari: push needs the Home Screen app. */+ | 'ios-install'+ | 'unsupported';++export interface NotifyEnv {+ secure: boolean;+ ios: boolean;+ standalone: boolean;+ notification: boolean;+ serviceWorker: boolean;+ pushManager: boolean;+}++export function deviceNotifySupport(e: NotifyEnv): DeviceNotifySupport {+ if (!e.secure) return 'insecure';+ if (e.ios && !e.standalone) return 'ios-install';+ if (e.serviceWorker && e.pushManager && e.notification) return 'push';+ return e.notification ? 'page' : 'unsupported';+}++export function notifyEnv(win: Window = window): NotifyEnv {+ return {+ secure: win.isSecureContext,+ ios: isIos(win.navigator),+ standalone: isStandalone(win),+ notification: 'Notification' in win,+ serviceWorker: 'serviceWorker' in win.navigator,+ pushManager: 'PushManager' in win,+ };+}++/** The line under "Notify me on this device": what it does, or why it can't be on. */+export function deviceNotifyHint(s: {+ support: DeviceNotifySupport;+ permission: NotificationPermission | 'unsupported';+ on: boolean;+ android: boolean;+ standalone: boolean;+}): { text: string; warn: boolean } {+ switch (s.support) {+ case 'insecure':+ return { text: 'Notifications need https://. Open this site through its https address to turn this on.', warn: true };+ case 'ios-install':+ return { text: 'On iPhone and iPad, add kwant bots to your Home Screen first: tap Share, then Add to Home Screen. Then turn this on in that app.', warn: true };+ case 'unsupported':+ return { text: "This browser can't show notifications.", warn: true };+ }+ if (s.permission === 'denied') {+ const how = s.android && s.standalone+ ? 'Long-press the kwant bots icon, tap App info, then Notifications, and allow them.'+ : "Allow notifications for this site in the browser's site settings (the icon left of the address), then come back.";+ return { text: `Notifications are blocked for this site. ${how}`, warn: true };+ }+ if (s.support === 'page') return { text: 'Only while this tab is open in the background. Each notification names its space.', warn: false };+ return { text: s.on ? 'Comes through even when the app is closed. Tap one to open its chat.' : 'Get a notification when a bot needs you, even with the app closed.', warn: false };+}++export const isAndroid = (nav: Pick<Navigator, 'userAgent'>): boolean => /Android/.test(nav.userAgent);++// ---------------------------------------------------------------------------+// The subscription++/** base64url (the server's VAPID public key) to the bytes `pushManager.subscribe` wants. */+export function base64UrlToBytes(s: string): Uint8Array<ArrayBuffer> {+ const b64 = s.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '');+ const bin = atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4));+ const out = new Uint8Array(new ArrayBuffer(bin.length));+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);+ return out;+}++/** Whether a subscription was made with this server key (a new key means subscribing again). */+export function sameKey(a: ArrayBuffer | null | undefined, b: Uint8Array): boolean {+ if (!a) return false;+ const x = new Uint8Array(a);+ return x.length === b.length && x.every((v, i) => v === b[i]);+}++type Fetch = (input: string, init?: RequestInit) => Promise<Response>;++async function errorOf(res: Response, what: string): Promise<Error> {+ const data = await res.json().catch(() => null);+ return new Error(data && typeof data.error === 'string' ? data.error : `${what} failed (HTTP ${res.status}).`);+}++/** The service worker's registration, or null where there isn't one (dev server, plain http). */+export async function swRegistration(nav: Navigator = navigator): Promise<ServiceWorkerRegistration | null> {+ if (!('serviceWorker' in nav)) return null;+ return (await nav.serviceWorker.getRegistration('/').catch(() => undefined)) ?? null;+}++/** Subscribes this device (or reuses its subscription) and tells the server. Idempotent: the+ * server keeps one entry per endpoint, so this also re-syncs after the server dropped it. */+export async function subscribePush(reg: ServiceWorkerRegistration, fetchFn: Fetch = fetch): Promise<PushSubscription> {+ const keyRes = await fetchFn('/api/push/key');+ if (!keyRes.ok) throw await errorOf(keyRes, 'Getting the server key');+ const { public_key } = (await keyRes.json()) as { public_key?: string };+ if (!public_key) throw new Error('The server has no push key.');+ const key = base64UrlToBytes(public_key);+ let sub = await reg.pushManager.getSubscription();+ if (sub && !sameKey(sub.options?.applicationServerKey, key)) {+ await sub.unsubscribe().catch(() => false);+ sub = null;+ }+ sub ??= await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key });+ const res = await fetchFn('/api/push/subscribe', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(sub.toJSON()),+ });+ if (!res.ok) throw await errorOf(res, 'Saving the subscription');+ return sub;+}++/** Stops pushes to this device, on the server and in the browser. */+export async function unsubscribePush(reg: ServiceWorkerRegistration, fetchFn: Fetch = fetch): Promise<void> {+ const sub = await reg.pushManager.getSubscription();+ if (!sub) return;+ await fetchFn('/api/push/unsubscribe', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ endpoint: sub.endpoint }),+ }).catch(() => undefined);+ await sub.unsubscribe().catch(() => false);+}++/** On app load: if this device has notifications on, make sure the server still has it. */+export async function resyncPush(opts: {+ enabled: boolean;+ permission: NotificationPermission | 'unsupported';+ support: DeviceNotifySupport;+ registration: () => Promise<ServiceWorkerRegistration | null>;+ fetchFn?: Fetch;+}): Promise<'synced' | 'skipped' | 'failed'> {+ if (!opts.enabled || opts.permission !== 'granted' || opts.support !== 'push') return 'skipped';+ const reg = await opts.registration();+ if (!reg) return 'skipped';+ try {+ await subscribePush(reg, opts.fetchFn);+ return 'synced';+ } catch {+ return 'failed';+ }+}++/** Runs resyncPush once with this page's state. */+export function resyncPushOnLoad(win: Window = window): Promise<string> {+ let enabled = false;+ try {+ enabled = win.localStorage.getItem(BROWSER_NOTIFY_KEY) === 'on';+ } catch {+ enabled = false;+ }+ return resyncPush({+ enabled,+ permission: notificationPermission(),+ support: deviceNotifySupport(notifyEnv(win)),+ registration: () => swRegistration(win.navigator),+ });+}++// ---------------------------------------------------------------------------+// The open page's own notification++const ICON = '/icons/icon-192.png';++/** Shows `n` as an OS notification. Through the service worker where there is one (Android+ * Chrome only allows that), so a tap goes through sw.js like a push; the constructor elsewhere. */+export async function showDeviceNotification(+ n: NotifyEvent & { space_id?: string | null },+ onClick: () => void,+ nav: Navigator = navigator,+): Promise<void> {+ const tag = notificationTag(n);+ const reg = await swRegistration(nav);+ if (reg) {+ await reg.showNotification(n.title, {+ body: n.body,+ tag,+ icon: ICON,+ badge: ICON,+ data: {+ path: notificationPath(n),+ kind: n.kind,+ space_id: n.space_id ?? null,+ channel_id: n.channel_id ?? null,+ kwant_id: n.kwant_id ?? null,+ },+ });+ return;+ }+ const note = new Notification(n.title, { body: n.body, tag, icon: ICON });+ note.onclick = () => {+ window.focus();+ onClick();+ note.close();+ };+}diff --git a/frontend/sw.js b/frontend/sw.jsindex dc6ea374..9b55b9a3 100644--- a/frontend/sw.js+++ b/frontend/sw.js@@ -59,3 +59,94 @@ self.addEventListener('fetch', (event) => {caches.open(CACHE).then((cache) => cache.match(request).then((hit) => hit || fetch(request))),);});++// ---------------------------------------------------------------------------+// Notifications. The server pushes {title, body, kind, space_id, channel_id, kwant_id, url, tag}+// (src/server/push.rs) to each device that turned on "Notify me on this device"; the open page+// shows its own through showNotification with the same tag and data (src/push.ts).++/** The chat's address in the app: /s/<space>/c/<channel> or /s/<space>/b/<bot>. */+function notificationPath(p) {+ if (!p.space_id) return typeof p.url === 'string' && p.url.startsWith('/') && !p.url.startsWith('//') ? p.url : '/';+ const base = `/s/${encodeURIComponent(p.space_id)}`;+ if (p.channel_id) return `${base}/c/${encodeURIComponent(p.channel_id)}`;+ if (p.kwant_id) return `${base}/b/${encodeURIComponent(p.kwant_id)}`;+ return base;+}++function windows() {+ return self.clients.matchAll({ type: 'window', includeUncontrolled: true });+}++/** kwant is open and in front of the person: the app shows it itself (a toast, the chat). */+function inFront(client) {+ return client.focused && client.visibilityState === 'visible';+}++self.addEventListener('push', (event) => {+ let p = {};+ try {+ p = event.data ? event.data.json() : {};+ } catch {+ p = {};+ }+ const title = typeof p.title === 'string' && p.title ? p.title : 'kwant';+ const data = {+ path: notificationPath(p),+ kind: p.kind || null,+ space_id: p.space_id || null,+ channel_id: p.channel_id || null,+ kwant_id: p.kwant_id || null,+ };+ event.waitUntil(+ windows().then((list) => {+ if (list.some(inFront)) return undefined;+ return self.registration.showNotification(title, {+ body: typeof p.body === 'string' ? p.body : '',+ tag: typeof p.tag === 'string' && p.tag ? p.tag : undefined,+ icon: '/icons/icon-192.png',+ badge: '/icons/icon-192.png',+ data,+ });+ }),+ );+});++self.addEventListener('notificationclick', (event) => {+ event.notification.close();+ const d = event.notification.data || {};+ const path = typeof d.path === 'string' && d.path.startsWith('/') && !d.path.startsWith('//') ? d.path : '/';+ event.waitUntil(+ windows().then((list) => {+ const client = list.find((c) => new URL(c.url).origin === self.location.origin);+ if (!client) return self.clients.openWindow(path);+ // The open app switches to the chat itself: no reload, and it can open a question or step.+ client.postMessage({+ type: 'kwnt-notification-open',+ kind: d.kind || '',+ space_id: d.space_id || null,+ channel_id: d.channel_id || null,+ kwant_id: d.kwant_id || null,+ });+ return client.focus().catch(() => self.clients.openWindow(path));+ }),+ );+});++// The browser replaced the subscription (expiry, key rotation): tell the server about the new one.+self.addEventListener('pushsubscriptionchange', (event) => {+ const old = event.oldSubscription;+ const options = (old && old.options) || (event.newSubscription && event.newSubscription.options);+ const post = (path, body) =>+ fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify(body) });+ event.waitUntil(+ Promise.resolve(event.newSubscription || (options ? self.registration.pushManager.subscribe(options) : null))+ .then((sub) => {+ if (!sub) return undefined;+ return post('/api/push/subscribe', sub.toJSON()).then(() =>+ old && old.endpoint !== sub.endpoint ? post('/api/push/unsubscribe', { endpoint: old.endpoint }) : undefined,+ );+ })+ .catch(() => undefined),+ );+});diff --git a/frontend/tests/push.test.mjs b/frontend/tests/push.test.mjsnew file mode 100644index 00000000..cd93d206--- /dev/null+++ b/frontend/tests/push.test.mjs@@ -0,0 +1,298 @@+// Notifications on this device: the push helpers (src/push.ts) and the service worker's push,+// notificationclick and pushsubscriptionchange handlers (sw.js).+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import vm from 'node:vm';+import { fileURLToPath } from 'node:url';+import { loadBundled } from './bundle.mjs';++const root = fileURLToPath(new URL('..', import.meta.url));+const ORIGIN = 'https://kwant.example';+const p = await loadBundled(`export * from './src/push.ts';`);++test('the page uses the same tag as the server, so a push replaces the page’s notification', () => {+ // Same cases as payload_shape_ttl_and_urgency in src/server/push.rs+ assert.equal(p.notificationTag({ space_id: 'sp 1', kind: 'approval_needed', channel_id: 'c1', kwant_id: 'k1' }), 'kwnt-sp 1-approval_needed-c1');+ assert.equal(p.notificationTag({ kind: 'turn_finished', channel_id: null, kwant_id: 'k1' }), 'kwnt-none-turn_finished-k1');+ assert.equal(p.notificationTag({ space_id: null, kind: 'turn_finished', channel_id: null, kwant_id: 'k1' }), 'kwnt-none-turn_finished-k1');+});++test('a notification opens the chat’s own address', () => {+ assert.equal(p.notificationPath({ space_id: 'sp 1', channel_id: 'c/1', kwant_id: 'k1' }), '/s/sp%201/c/c%2F1');+ assert.equal(p.notificationPath({ space_id: 's', channel_id: null, kwant_id: 'k1' }), '/s/s/b/k1');+ assert.equal(p.notificationPath({ space_id: null, channel_id: 'c1', kwant_id: 'k1' }), '/');+});++test('the push url’s query works as a link too', () => {+ assert.deepEqual(p.targetFromQuery('?space=sp%201&channel=c1'), { spaceId: 'sp 1', channelId: 'c1', botId: null });+ assert.deepEqual(p.targetFromQuery('?space=s&kwant=k1'), { spaceId: 's', channelId: null, botId: 'k1' });+ assert.deepEqual(p.targetFromQuery('?kwant=k1'), { spaceId: null, channelId: null, botId: 'k1' });+ assert.equal(p.targetFromQuery(''), null);+ assert.equal(p.targetFromQuery('?utm=x'), null);+});++test('what this device can do: push, page only, or why not', () => {+ const env = { secure: true, ios: false, standalone: false, notification: true, serviceWorker: true, pushManager: true };+ assert.equal(p.deviceNotifySupport(env), 'push', 'Android Chrome, desktop Chrome/Firefox/Safari');+ assert.equal(p.deviceNotifySupport({ ...env, secure: false }), 'insecure');+ assert.equal(p.deviceNotifySupport({ ...env, ios: true, notification: false, pushManager: false }), 'ios-install', 'Safari tab on an iPhone');+ assert.equal(p.deviceNotifySupport({ ...env, ios: true, standalone: true }), 'push', 'Home Screen app on iOS 16.4+');+ assert.equal(p.deviceNotifySupport({ ...env, ios: true, standalone: true, pushManager: false, notification: false }), 'unsupported', 'older iOS');+ assert.equal(p.deviceNotifySupport({ ...env, pushManager: false }), 'page');+ assert.equal(p.deviceNotifySupport({ ...env, serviceWorker: false, pushManager: false, notification: false }), 'unsupported');+});++test('the line under the switch says what it does or how to fix it', () => {+ const base = { support: 'push', permission: 'default', on: false, android: false, standalone: false };+ assert.match(p.deviceNotifyHint(base).text, /even with the app closed/);+ assert.equal(p.deviceNotifyHint(base).warn, false);+ assert.match(p.deviceNotifyHint({ ...base, on: true, permission: 'granted' }).text, /even when the app is closed/);+ assert.match(p.deviceNotifyHint({ ...base, support: 'page' }).text, /Only while this tab is open/);+ const insecure = p.deviceNotifyHint({ ...base, support: 'insecure' });+ assert.ok(insecure.warn && /https/.test(insecure.text));+ const ios = p.deviceNotifyHint({ ...base, support: 'ios-install', permission: 'unsupported' });+ assert.ok(ios.warn && /Add to Home Screen/.test(ios.text));+ const deniedAndroidApp = p.deviceNotifyHint({ ...base, permission: 'denied', android: true, standalone: true });+ assert.ok(deniedAndroidApp.warn && /App info/.test(deniedAndroidApp.text));+ assert.match(p.deviceNotifyHint({ ...base, permission: 'denied' }).text, /site settings/);+ assert.match(p.deviceNotifyHint({ ...base, support: 'unsupported', permission: 'unsupported' }).text, /can't show/);+});++test('the server key decodes from base64url, with or without padding', () => {+ const bytes = Uint8Array.from({ length: 65 }, (_, i) => (i * 37 + 4) & 255);+ const b64url = Buffer.from(bytes).toString('base64url');+ assert.deepEqual([...p.base64UrlToBytes(b64url)], [...bytes]);+ assert.deepEqual([...p.base64UrlToBytes(b64url + '=')], [...bytes]);+ assert.ok(p.sameKey(bytes.buffer, bytes));+ assert.ok(!p.sameKey(bytes.slice(1).buffer, bytes));+ assert.ok(!p.sameKey(null, bytes));+});++/** A fake server and pushManager. */+function fakes({ key = 'AQID', existing = null, subscribeStatus = 204, keyStatus = 200 } = {}) {+ const calls = [];+ const fetchFn = async (url, init = {}) => {+ calls.push({ url, method: init.method ?? 'GET', body: init.body ? JSON.parse(init.body) : undefined });+ if (url === '/api/push/key') return new Response(JSON.stringify({ public_key: key }), { status: keyStatus });+ if (url === '/api/push/subscribe') {+ return subscribeStatus === 204 ? new Response(null, { status: 204 }) : new Response(JSON.stringify({ error: 'endpoint must be https' }), { status: subscribeStatus });+ }+ return new Response(null, { status: 204 });+ };+ const made = [];+ const sub = (endpoint, keyBytes) => ({+ endpoint,+ options: { applicationServerKey: keyBytes.buffer },+ unsubscribed: false,+ async unsubscribe() { this.unsubscribed = true; current = null; return true; },+ toJSON() { return { endpoint, expirationTime: null, keys: { p256dh: 'pk', auth: 'au' } }; },+ });+ let current = existing ? sub(existing.endpoint, existing.key) : null;+ const old = current;+ const reg = {+ pushManager: {+ getSubscription: async () => current,+ subscribe: async (opts) => {+ made.push(opts);+ current = sub(`https://fcm.googleapis.com/fcm/send/${made.length}`, opts.applicationServerKey);+ return current;+ },+ },+ };+ return { calls, fetchFn, reg, made, old, current: () => current };+}++test('turning it on subscribes with the server key and tells the server', async () => {+ const f = fakes();+ const sub = await p.subscribePush(f.reg, f.fetchFn);+ assert.equal(f.made.length, 1);+ assert.equal(f.made[0].userVisibleOnly, true);+ assert.deepEqual([...f.made[0].applicationServerKey], [1, 2, 3]);+ assert.deepEqual(f.calls.map((c) => `${c.method} ${c.url}`), ['GET /api/push/key', 'POST /api/push/subscribe']);+ assert.deepEqual(f.calls[1].body, sub.toJSON());+});++test('an existing subscription for the same key is reused; one for an old key is replaced', async () => {+ const same = fakes({ existing: { endpoint: 'https://push.example/a', key: new Uint8Array([1, 2, 3]) } });+ await p.subscribePush(same.reg, same.fetchFn);+ assert.equal(same.made.length, 0);+ assert.equal(same.calls[1].body.endpoint, 'https://push.example/a');++ const rotated = fakes({ existing: { endpoint: 'https://push.example/old', key: new Uint8Array([9, 9, 9]) } });+ await p.subscribePush(rotated.reg, rotated.fetchFn);+ assert.ok(rotated.old.unsubscribed, 'the old-key subscription is dropped');+ assert.equal(rotated.made.length, 1);+ assert.notEqual(rotated.calls[1].body.endpoint, 'https://push.example/old');+});++test('a server refusal surfaces its message', async () => {+ const f = fakes({ subscribeStatus: 400 });+ await assert.rejects(p.subscribePush(f.reg, f.fetchFn), /endpoint must be https/);+ const noKey = fakes({ keyStatus: 401 });+ await assert.rejects(p.subscribePush(noKey.reg, noKey.fetchFn), /HTTP 401/);+});++test('turning it off unsubscribes on the server and in the browser', async () => {+ const f = fakes({ existing: { endpoint: 'https://push.example/a', key: new Uint8Array([1, 2, 3]) } });+ await p.unsubscribePush(f.reg, f.fetchFn);+ assert.deepEqual(f.calls, [{ url: '/api/push/unsubscribe', method: 'POST', body: { endpoint: 'https://push.example/a' } }]);+ assert.ok(f.old.unsubscribed);+ const none = fakes();+ await p.unsubscribePush(none.reg, none.fetchFn);+ assert.deepEqual(none.calls, [], 'nothing to drop, no request');+});++test('on load, an enabled device re-syncs its subscription; anything else is left alone', async () => {+ const f = fakes({ existing: { endpoint: 'https://push.example/a', key: new Uint8Array([1, 2, 3]) } });+ const opts = { enabled: true, permission: 'granted', support: 'push', registration: async () => f.reg, fetchFn: f.fetchFn };+ assert.equal(await p.resyncPush(opts), 'synced');+ assert.equal(f.calls.at(-1).url, '/api/push/subscribe');+ for (const off of [{ enabled: false }, { permission: 'default' }, { permission: 'denied' }, { support: 'page' }, { support: 'ios-install' }]) {+ const g = fakes();+ assert.equal(await p.resyncPush({ ...opts, ...off, registration: async () => g.reg, fetchFn: g.fetchFn }), 'skipped', JSON.stringify(off));+ assert.equal(g.calls.length, 0);+ }+ assert.equal(await p.resyncPush({ ...opts, registration: async () => null }), 'skipped', 'no service worker (dev server)');+ const bad = fakes({ subscribeStatus: 400 });+ assert.equal(await p.resyncPush({ ...opts, registration: async () => bad.reg, fetchFn: bad.fetchFn }), 'failed');+});++test('the page shows its notification through the service worker, with the push’s tag and target', async () => {+ const shown = [];+ const reg = { showNotification: async (title, opts) => shown.push({ title, opts }) };+ const nav = { serviceWorker: { getRegistration: async () => reg } };+ let clicked = 0;+ await p.showDeviceNotification(+ { kind: 'approval_needed', kwant_id: 'k1', kwant_name: 'Ada', channel_id: 'c1', title: 'Ada needs approval', body: 'Run tests?', space_id: 's1' },+ () => clicked++,+ nav,+ );+ assert.equal(shown.length, 1);+ assert.equal(shown[0].title, 'Ada needs approval');+ assert.equal(shown[0].opts.tag, 'kwnt-s1-approval_needed-c1');+ assert.deepEqual(shown[0].opts.data, { path: '/s/s1/c/c1', kind: 'approval_needed', space_id: 's1', channel_id: 'c1', kwant_id: 'k1' });+ assert.equal(clicked, 0, 'the tap goes through sw.js');+ assert.ok(p.isNotificationOpen({ type: 'kwnt-notification-open' }));+ assert.ok(!p.isNotificationOpen({ type: 'other' }) && !p.isNotificationOpen(null));+});++// ---------------------------------------------------------------------------+// sw.js++/** Objects made inside the worker's vm context, compared as plain data. */+const plain = (v) => JSON.parse(JSON.stringify(v));++function loadWorker({ clients = [] } = {}) {+ const code = readFileSync(`${root}/sw.js`, 'utf8').replace('__KWNT_SW_VERSION__', 'v').replace('__KWNT_SW_SHELL__', '[]');+ const handlers = {};+ const log = { shown: [], opened: [], posted: [], focused: [], fetched: [], subscribed: [] };+ const win = (url, { focused = false, visible = false } = {}) => ({+ url: new URL(url, ORIGIN).href,+ focused,+ visibilityState: visible ? 'visible' : 'hidden',+ postMessage: (m) => log.posted.push({ url, m }),+ focus: async function () { log.focused.push(url); return this; },+ });+ const list = clients.map((c) => win(c.url, c));+ const self = {+ location: { origin: ORIGIN },+ addEventListener: (type, fn) => { handlers[type] = fn; },+ registration: {+ showNotification: async (title, opts) => { log.shown.push({ title, ...opts }); },+ pushManager: { subscribe: async (opts) => { log.subscribed.push(opts); return { endpoint: 'https://push.example/new', toJSON: () => ({ endpoint: 'https://push.example/new' }) }; } },+ },+ clients: {+ matchAll: async () => list,+ openWindow: async (url) => { log.opened.push(url); },+ claim: async () => undefined,+ },+ };+ vm.runInNewContext(code, {+ self,+ URL,+ caches: {},+ fetch: async (url, init) => { log.fetched.push({ url, body: JSON.parse(init.body) }); return { ok: true }; },+ });+ const run = async (type, extra) => {+ let waited;+ handlers[type]({ ...extra, waitUntil: (pr) => { waited = pr; } });+ await waited;+ };+ return {+ log,+ push: (payload) => run('push', { data: payload === undefined ? null : { json: () => (typeof payload === 'string' ? JSON.parse(payload) : payload) } }),+ click: (data) => {+ const n = { data, closed: false, close() { this.closed = true; } };+ return run('notificationclick', { notification: n }).then(() => n);+ },+ change: (extra) => run('pushsubscriptionchange', extra),+ };+}++const PAYLOAD = {+ title: 'Ada needs approval',+ body: 'Run the tests?',+ kind: 'approval_needed',+ space_id: 's1',+ channel_id: 'c1',+ kwant_id: 'k1',+ url: '/?space=s1&channel=c1',+ tag: 'kwnt-s1-approval_needed-c1',+};++test('a push with kwant closed shows a notification with the server’s tag and the chat to open', async () => {+ const sw = loadWorker();+ await sw.push(PAYLOAD);+ assert.equal(sw.log.shown.length, 1);+ const n = sw.log.shown[0];+ assert.equal(n.title, 'Ada needs approval');+ assert.equal(n.body, 'Run the tests?');+ assert.equal(n.tag, 'kwnt-s1-approval_needed-c1');+ assert.equal(n.icon, '/icons/icon-192.png');+ assert.deepEqual(plain(n.data), { path: '/s/s1/c/c1', kind: 'approval_needed', space_id: 's1', channel_id: 'c1', kwant_id: 'k1' });+});++test('a push while kwant is in front is left to the app; a background tab still gets it', async () => {+ const front = loadWorker({ clients: [{ url: '/s/s1/c/other', focused: true, visible: true }] });+ await front.push(PAYLOAD);+ assert.equal(front.log.shown.length, 0);+ const behind = loadWorker({ clients: [{ url: '/s/s1/c/c1', focused: false, visible: false }] });+ await behind.push(PAYLOAD);+ assert.equal(behind.log.shown.length, 1);+});++test('odd pushes still show something safe', async () => {+ const sw = loadWorker();+ await sw.push(undefined);+ await sw.push({ title: '', url: '//evil.example/x' });+ await sw.push({ title: 'x', kwant_id: 'k1', url: '/?kwant=k1' });+ assert.deepEqual(sw.log.shown.map((n) => [n.title, n.data.path]), [['kwant', '/'], ['kwant', '/'], ['x', '/?kwant=k1']]);+});++test('a tap focuses the open app and asks it to open the chat', async () => {+ const sw = loadWorker({ clients: [{ url: '/s/s1/c/zz' }] });+ const n = await sw.click({ path: '/s/s1/c/c1', kind: 'question_asked', space_id: 's1', channel_id: 'c1', kwant_id: 'k1' });+ assert.ok(n.closed);+ assert.deepEqual(plain(sw.log.posted.map((x) => x.m)), [{ type: 'kwnt-notification-open', kind: 'question_asked', space_id: 's1', channel_id: 'c1', kwant_id: 'k1' }]);+ assert.deepEqual(sw.log.focused, ['/s/s1/c/zz']);+ assert.deepEqual(sw.log.opened, []);+});++test('a tap with kwant closed opens it on the chat, and never off-site', async () => {+ const sw = loadWorker();+ await sw.click({ path: '/s/s1/b/k1', kind: 'turn_finished', space_id: 's1', kwant_id: 'k1' });+ await sw.click({ path: '//evil.example/' });+ await sw.click(undefined);+ assert.deepEqual(sw.log.opened, ['/s/s1/b/k1', '/', '/']);+});++test('a replaced subscription is sent to the server and the old one dropped', async () => {+ const sw = loadWorker();+ await sw.change({ oldSubscription: { endpoint: 'https://push.example/old', options: { userVisibleOnly: true, applicationServerKey: 'k' } } });+ assert.equal(sw.log.subscribed.length, 1);+ assert.deepEqual(sw.log.fetched, [+ { url: '/api/push/subscribe', body: { endpoint: 'https://push.example/new' } },+ { url: '/api/push/unsubscribe', body: { endpoint: 'https://push.example/old' } },+ ]);+});