Skip to content

Build the browser push enrollment flow and notification preferences settings #1722

Closed

Description

@propr-dev

Context

Browsers require notification permission to be requested from a user gesture. iOS/iPadOS additionally requires the web app to be installed on the Home Screen before Web Push enrollment is available. Users also need category, badge, and quiet-hour controls before push is enabled.

Requirements

  • Add a typed notification API client.
  • Add a hook that reports service-worker, Push API, permission, installation, and subscription state.
  • Convert the VAPID URL-safe public key correctly for PushManager.subscribe.
  • Request permission only from an explicit Enable button.
  • Register the subscription with the authenticated backend.
  • Support disabling push by revoking the backend subscription and unsubscribing locally.
  • Add notification preferences to Settings with category toggles, badge preference, timezone, and quiet hours.
  • Explain the iOS Home Screen requirement when applicable.
  • Surface missing VAPID configuration without showing a broken Enable button.
  • Reconcile an existing browser subscription after login or account changes.

Acceptance Criteria

  • No permission prompt appears on initial page load.
  • Enabling notifications from a user click creates one backend subscription.
  • Repeated enablement is idempotent.
  • Disabling removes both the browser and backend subscription.
  • Denied permission produces instructions instead of retry loops.
  • Settings persist after reload.
  • iOS Safari outside standalone mode tells the user to add ProPR to the Home Screen.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Aug 2, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Separate the API client, browser capability hook, and settings presentation. This makes permission logic testable without rendering the full Settings page. Automatic permission requests were rejected because browsers block them, they create a poor trust experience, and iOS requires a direct user gesture. Preference saves are explicit to avoid silent network writes while toggling several controls.

    File: propr-ui/src/api/notificationsApi.ts (new file)

    Why this file: It gives the UI a typed boundary for notification configuration, preferences, subscriptions, Inbox state, and receipts.

    import type {
      NotificationConfigResponse,
      NotificationListResponse,
      NotificationPreferences,
      WebPushSubscriptionInput,
    } from '@propr/shared';
    import { API_BASE_URL, apiFetch, handleApiResponse } from './proprApi';
    
    async function jsonRequest<T>(path: string, init?: RequestInit): Promise<T> {
      const response = await apiFetch(`${API_BASE_URL}/api/notifications${path}`, {
        credentials: 'include',
        ...init,
        headers: init?.body ? { 'Content-Type': 'application/json', ...init.headers } : init?.headers,
      });
      await handleApiResponse(response);
      return response.json() as Promise<T>;
    }
    
    export const getNotificationConfig = () => jsonRequest<NotificationConfigResponse>('/config');
    export const getNotificationPreferences = () => jsonRequest<NotificationPreferences>('/preferences');
    export const updateNotificationPreferences = (preferences: NotificationPreferences) =>
      jsonRequest<NotificationPreferences>('/preferences', { method: 'PUT', body: JSON.stringify(preferences) });
    export const registerPushSubscription = (subscription: WebPushSubscriptionInput) =>
      jsonRequest<{ success: true }>('/subscriptions', { method: 'POST', body: JSON.stringify(subscription) });
    export const revokePushSubscription = async (endpoint: string): Promise<void> => {
      const response = await apiFetch(`${API_BASE_URL}/api/notifications/subscriptions`, {
        method: 'DELETE',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ endpoint }),
      });
      if (response.status !== 204) await handleApiResponse(response);
    };
    export const getNotifications = (cursor?: string) =>
      jsonRequest<NotificationListResponse>(`/?limit=30${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`);
    export const markNotificationRead = (id: string) =>
      jsonRequest<{ success: true; unreadCount: number }>(`/${encodeURIComponent(id)}/read`, { method: 'POST' });
    export const dismissNotification = (id: string) =>
      jsonRequest<{ success: true; unreadCount: number }>(`/${encodeURIComponent(id)}/dismiss`, { method: 'POST' });
    export const getUnreadNotificationCount = () =>
      jsonRequest<{ unreadCount: number }>('/unread-count');

    File: propr-ui/src/hooks/usePushNotifications.ts (new file)

    Why this file: Browser capability and permission transitions are asynchronous and platform-specific. A hook keeps these concerns out of the settings component.

    import { useCallback, useEffect, useState } from 'react';
    import {
      getNotificationConfig,
      registerPushSubscription,
      revokePushSubscription,
    } from '../api/notificationsApi';
    
    const decodeVapidKey = (value: string): Uint8Array => {
      const padded = value + '='.repeat((4 - value.length % 4) % 4);
      const binary = atob(padded.replace(/-/g, '+').replace(/_/g, '/'));
      return Uint8Array.from(binary, character => character.charCodeAt(0));
    };
    
    const isStandalone = (): boolean =>
      window.matchMedia('(display-mode: standalone)').matches ||
      Boolean((navigator as Navigator & { standalone?: boolean }).standalone);
    
    export function usePushNotifications() {
      const supported = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window;
      const [configured, setConfigured] = useState(false);
      const [permission, setPermission] = useState<NotificationPermission>(supported ? Notification.permission : 'denied');
      const [subscribed, setSubscribed] = useState(false);
      const [busy, setBusy] = useState(true);
      const [error, setError] = useState<string | null>(null);
    
      const currentSubscription = useCallback(async () => {
        if (!supported) return null;
        const registration = await navigator.serviceWorker.ready;
        return registration.pushManager.getSubscription();
      }, [supported]);
    
      useEffect(() => {
        if (!supported) {
          setBusy(false);
          return;
        }
        Promise.all([getNotificationConfig(), currentSubscription()])
          .then(([config, subscription]) => {
            setConfigured(config.configured);
            setSubscribed(Boolean(subscription));
          })
          .catch(reason => setError((reason as Error).message))
          .finally(() => setBusy(false));
      }, [currentSubscription, supported]);
    
      const enable = useCallback(async () => {
        setBusy(true);
        setError(null);
        try {
          const config = await getNotificationConfig();
          if (!config.configured || !config.vapidPublicKey) throw new Error('Web Push is not configured on this ProPR server');
          const nextPermission = await Notification.requestPermission();
          setPermission(nextPermission);
          if (nextPermission !== 'granted') throw new Error('Notification permission was not granted');
          const registration = await navigator.serviceWorker.ready;
          const subscription = await registration.pushManager.subscribe({
            userVisibleOnly: true,
            applicationServerKey: decodeVapidKey(config.vapidPublicKey),
          });
          await registerPushSubscription(subscription.toJSON() as Parameters<typeof registerPushSubscription>[0]);
          setSubscribed(true);
        } catch (reason) {
          setError((reason as Error).message);
        } finally {
          setBusy(false);
        }
      }, []);
    
      const disable = useCallback(async () => {
        setBusy(true);
        setError(null);
        try {
          const subscription = await currentSubscription();
          if (subscription) {
            // Revoke server delivery before deleting the browser endpoint so a
            // transient unsubscribe failure cannot leave a still-active backend row.
            await revokePushSubscription(subscription.endpoint);
            await subscription.unsubscribe();
          }
          setSubscribed(false);
        } catch (reason) {
          setError((reason as Error).message);
        } finally {
          setBusy(false);
        }
      }, [currentSubscription]);
    
      return {
        supported,
        configured,
        permission,
        subscribed,
        busy,
        error,
        standalone: isStandalone(),
        enable,
        disable,
      };
    }

    File: propr-ui/src/pages/SettingsPage/NotificationPreferencesSection.tsx (new file)

    Why this file: This component makes push enrollment and delivery policy visible in the existing Settings workflow.

    import React, { useEffect, useState } from 'react';
    import type { NotificationCategory, NotificationPreferences } from '@propr/shared';
    import { getNotificationPreferences, updateNotificationPreferences } from '../../api/notificationsApi';
    import { usePushNotifications } from '../../hooks/usePushNotifications';
    
    const labels: Record<NotificationCategory, string> = {
      plans: 'Plans ready for review',
      tasks: 'Task progress and failures',
      pull_requests: 'Pull requests needing attention',
      indexing: 'Repository indexing failures',
      system: 'System failures',
    };
    
    export function NotificationPreferencesSection() {
      const push = usePushNotifications();
      const [preferences, setPreferences] = useState<NotificationPreferences | null>(null);
      const [saving, setSaving] = useState(false);
      const [message, setMessage] = useState<string | null>(null);
    
      useEffect(() => {
        void getNotificationPreferences().then(setPreferences).catch(error => setMessage(error.message));
      }, []);
    
      if (!preferences) return <section className='rounded-lg border p-4'>Loading notification preferences…</section>;
    
      const save = async () => {
        setSaving(true);
        setMessage(null);
        try {
          const updated = await updateNotificationPreferences({ ...preferences, pushEnabled: push.subscribed });
          setPreferences(updated);
          setMessage('Notification preferences saved.');
        } catch (error) {
          setMessage((error as Error).message);
        } finally {
          setSaving(false);
        }
      };
    
      return (
        <section className='rounded-lg border border-slate-200 bg-white p-4 space-y-4'>
          <div>
            <h2 className='font-semibold text-slate-900'>Notifications</h2>
            <p className='text-sm text-slate-600'>Choose what appears in the Inbox and on this device.</p>
          </div>
    
          {!push.supported && <p className='text-sm text-amber-700'>This browser does not expose the Web Push API.</p>}
          {push.supported && !push.standalone && /iPad|iPhone|iPod/.test(navigator.userAgent) && (
            <p className='text-sm text-amber-700'>On iPhone or iPad, add ProPR to the Home Screen, open the installed app, then enable notifications here.</p>
          )}
          {push.supported && !push.configured && <p className='text-sm text-amber-700'>The server administrator has not configured VAPID keys.</p>}
          {push.error && <p className='text-sm text-red-600'>{push.error}</p>}
    
          <button
            type='button'
            disabled={push.busy || !push.supported || !push.configured}
            onClick={push.subscribed ? push.disable : push.enable}
            className='rounded-md bg-teal-700 px-3 py-2 text-sm text-white disabled:opacity-50'
          >
            {push.busy ? 'Updating…' : push.subscribed ? 'Disable push on this device' : 'Enable push on this device'}
          </button>
    
          <div className='grid gap-2'>
            {(Object.keys(labels) as NotificationCategory[]).map(category => (
              <label key={category} className='flex items-center gap-2 text-sm'>
                <input
                  type='checkbox'
                  checked={preferences.categories[category]}
                  onChange={event => setPreferences(current => current && ({
                    ...current,
                    categories: { ...current.categories, [category]: event.target.checked },
                  }))}
                />
                {labels[category]}
              </label>
            ))}
          </div>
    
          <label className='flex items-center gap-2 text-sm'>
            <input type='checkbox' checked={preferences.badgeEnabled} onChange={event => setPreferences({ ...preferences, badgeEnabled: event.target.checked })} />
            Show unread count on the installed app icon
          </label>
    
          <div className='grid grid-cols-1 sm:grid-cols-3 gap-3'>
            <label className='text-sm'>Quiet from<input type='time' value={preferences.quietHoursStart ?? ''} onChange={event => setPreferences({ ...preferences, quietHoursStart: event.target.value || null })} className='block w-full rounded border p-2' /></label>
            <label className='text-sm'>Quiet until<input type='time' value={preferences.quietHoursEnd ?? ''} onChange={event => setPreferences({ ...preferences, quietHoursEnd: event.target.value || null })} className='block w-full rounded border p-2' /></label>
            <label className='text-sm'>Timezone<input value={preferences.timezone} onChange={event => setPreferences({ ...preferences, timezone: event.target.value })} className='block w-full rounded border p-2' /></label>
          </div>
    
          <button type='button' onClick={save} disabled={saving} className='rounded-md border px-3 py-2 text-sm disabled:opacity-50'>
            {saving ? 'Saving…' : 'Save notification preferences'}
          </button>
          {message && <p className='text-sm text-slate-600'>{message}</p>}
        </section>
      );
    }

    File: propr-ui/src/pages/SettingsPage/index.tsx

    Why this file: The section belongs in the existing settings surface rather than a disconnected PWA-only page.

    --- a/propr-ui/src/pages/SettingsPage/index.tsx
    +++ b/propr-ui/src/pages/SettingsPage/index.tsx
    @@ -1,5 +1,6 @@
    +import { NotificationPreferencesSection } from './NotificationPreferencesSection';
    @@ -80,6 +81,7 @@
    +        <NotificationPreferencesSection />
  2. propr-dev commented on Aug 24, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using codex agent with gpt-5.6-sol model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: codex
    • Model: gpt-5.6-sol
    • Branch: 1722/gpt-5.6-sol-build-the-browser-push-en-20260824-1134-ztd
    • Base Branch: 1716-epic-failed-to-3m8
    • Worktree: issue-1722-20260824-1134-gpt-5.6-sol-ztd

    🔍 Track Task Execution

  3. added a commit that references this issue on Aug 24, 2026
  4. added a commit that references this issue on Aug 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions