Skip to content

Add notification, push, deep-link, and mobile navigation test coverage #1728

Closed

Description

@propr-dev

Context

This feature crosses database persistence, authentication, lifecycle projection, browser APIs, service-worker events, and responsive UI. A release without layered tests risks duplicate pushes, cross-user receipt leaks, destructive deep-link behavior, or mobile-only regressions.

Requirements

  • Add migration and service tests for event deduplication, per-user receipts, counts, and cursor pagination.
  • Add API tests proving session ownership for preferences, subscriptions, read, and dismiss operations.
  • Add projector tests for every notification kind and duplicate lifecycle payloads.
  • Add dispatcher tests for category preferences, quiet hours, transient retries, and 410 cleanup.
  • Add service-worker tests for push payload fallback, badge updates, safe URL filtering, and notification click routing.
  • Add React tests for enrollment, denied permission, iOS installation guidance, Inbox grouping, optimistic rollback, and action confirmation.
  • Add route-level tests for bottom navigation and one-shot plan intents.
  • Add a browser smoke test for install metadata and mobile layout.
  • Keep live push-provider calls out of normal CI.

Acceptance Criteria

  • Every notification kind has a projection test.
  • Tests prove one user's receipt cannot modify another user's state.
  • Tests prove a URL intent cannot directly execute a plan or stop a task.
  • Tests prove API/auth responses are excluded from service-worker caching.
  • CI remains deterministic without VAPID secrets or external push access.
  • The suite covers 320px and 390px mobile viewports plus desktop.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Aug 2, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Test each boundary independently and add a small route-level smoke suite. Real Apple Push Notification service delivery is unsuitable for deterministic CI, so the server transport and browser PushManager are injected or mocked. The highest-risk invariants are authentication ownership, idempotency, safe URL handling, and confirmation before mutations.

    File: test/notificationService.test.ts (new file)

    Why this file: Core persistence behavior should be validated against the real test database rather than mocked SQL.

    import { beforeEach, describe, expect, it } from 'vitest';
    import {
      createNotificationEvent,
      dismissNotification,
      getUnreadNotificationCount,
      listNotifications,
      markNotificationRead,
    } from '../packages/core/src/services/notificationService.js';
    import { db } from '../packages/core/src/db/connection.js';
    
    describe('notification persistence', () => {
      beforeEach(async () => {
        await db('notification_receipts').delete();
        await db('notification_events').delete();
      });
    
      it('deduplicates repeated lifecycle events', async () => {
        const input = {
          kind: 'plan_ready' as const,
          category: 'plans' as const,
          title: 'Ready',
          body: 'Review it',
          targetType: 'plan' as const,
          targetId: 'draft-1',
          deepLink: '/studio/draft-1',
          dedupeKey: 'draft-1:review:1',
        };
        expect(await createNotificationEvent(input)).toBe(await createNotificationEvent(input));
        expect(Number((await db('notification_events').count({ count: '*' }).first())?.count)).toBe(1);
      });
    
      it('keeps read and dismissal state isolated by user', async () => {
        const id = await createNotificationEvent({
          kind: 'task_failed', category: 'tasks', title: 'Failed', body: 'Open task',
          targetType: 'task', targetId: 'task-1', deepLink: '/tasks/task-1', dedupeKey: 'task-1:failed:1',
        });
        await markNotificationRead('user-a', id);
        expect(await getUnreadNotificationCount('user-a')).toBe(0);
        expect(await getUnreadNotificationCount('user-b')).toBe(1);
        await dismissNotification('user-a', id);
        expect((await listNotifications('user-a', { limit: 10 })).notifications).toHaveLength(0);
        expect((await listNotifications('user-b', { limit: 10 })).notifications).toHaveLength(1);
      });
    });

    File: test/notificationProjector.test.ts (new file)

    Why this file: Lifecycle mapping is where product semantics are encoded; table-driven cases make omissions visible.

    import { describe, expect, it } from 'vitest';
    import { DRAFT_UPDATE, INDEXING_UPDATE, TASK_UPDATE } from '@propr/shared';
    import { projectPublishedEvent } from '../packages/core/src/services/notificationProjector.js';
    import { db } from '../packages/core/src/db/connection.js';
    
    it.each([
      [DRAFT_UPDATE, { draftId: 'd1', status: 'review', timestamp: '2026-08-02T10:00:00.000Z' }, 'plan_ready'],
      [TASK_UPDATE, { taskId: 't1', status: 'failed', timestamp: '2026-08-02T10:01:00.000Z' }, 'task_failed'],
      [TASK_UPDATE, { taskId: 't2', status: 'completed', commandMode: 'implementation', timestamp: '2026-08-02T10:02:00.000Z' }, 'implementation_completed'],
      [TASK_UPDATE, { taskId: 't3', status: 'completed', commandMode: 'review', timestamp: '2026-08-02T10:03:00.000Z' }, 'review_completed'],
      [INDEXING_UPDATE, { repository: 'org/repo', status: 'failed', timestamp: '2026-08-02T10:04:00.000Z' }, 'indexing_failed'],
    ])('projects %s payload into %s', async (channel, payload, expectedKind) => {
      await projectPublishedEvent(channel, payload);
      await projectPublishedEvent(channel, payload);
      const rows = await db('notification_events').where({ kind: expectedKind });
      expect(rows).toHaveLength(1);
    });

    File: test/webPushDispatcher.test.ts (new file)

    Why this file: Delivery retries and subscription revocation must be verified without a real push provider.

    import { beforeEach, expect, it, vi } from 'vitest';
    
    vi.mock('web-push', () => ({
      default: {
        setVapidDetails: vi.fn(),
        sendNotification: vi.fn(),
      },
    }));
    
    it('revokes a subscription after a 410 response', async () => {
      const webPush = (await import('web-push')).default;
      vi.mocked(webPush.sendNotification).mockRejectedValueOnce({ statusCode: 410 });
      // Seed one event, enabled preference, active subscription, and pending delivery
      // with test fixtures, then run a single batch.
      const { dispatchWebPushBatch } = await import('../packages/core/src/services/webPushDispatcher.js');
      await dispatchWebPushBatch(1);
      expect(webPush.sendNotification).toHaveBeenCalledTimes(1);
      // Assert the fixture subscription now has revoked_at and the delivery is failed.
    });

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

    Why this file: Permission prompts and PushManager enrollment are browser-only state transitions that need deterministic mocks.

    import { act, renderHook } from '@testing-library/react';
    import { expect, it, vi } from 'vitest';
    import { usePushNotifications } from './usePushNotifications';
    
    it('requests permission only when enable is invoked', async () => {
      const requestPermission = vi.fn().mockResolvedValue('granted');
      Object.defineProperty(window, 'Notification', { value: { permission: 'default', requestPermission }, configurable: true });
      const { result } = renderHook(() => usePushNotifications());
      expect(requestPermission).not.toHaveBeenCalled();
      await act(() => result.current.enable());
      expect(requestPermission).toHaveBeenCalledTimes(1);
    });

    File: propr-ui/src/pages/InboxPage.test.tsx (new file)

    Why this file: The dedicated mobile workflow needs grouping and optimistic error-state coverage.

    it('groups failed work separately and restores a failed optimistic dismissal', async () => {
      mockGetNotifications.mockResolvedValue({ notifications: [failedTask, completedTask], unreadCount: 2, nextCursor: null });
      mockDismissNotification.mockRejectedValueOnce(new Error('Offline'));
      renderInbox();
      expect(await screen.findByRole('heading', { name: 'Needs attention' })).toBeVisible();
      expect(screen.getByRole('heading', { name: 'Completed' })).toBeVisible();
      await user.click(screen.getAllByRole('button', { name: /dismiss/i })[0]);
      expect(await screen.findByText(failedTask.title)).toBeVisible();
      expect(screen.getByText('Offline')).toBeVisible();
    });

    File: propr-ui/src/components/TaskPlanner/PlanEditor.notificationIntent.test.tsx (new file)

    Why this file: This guards the critical rule that URL navigation alone never starts agent execution.

    it('shows confirmation without executing approve_execute automatically', async () => {
      renderPlanEditorAt('/studio/draft-1?intent=approve_execute');
      expect(await screen.findByRole('dialog', { name: /approve and continue/i })).toBeVisible();
      expect(mockHandleApproveAndExecute).not.toHaveBeenCalled();
      await user.click(screen.getByRole('button', { name: 'Confirm' }));
      expect(mockHandleApproveAndExecute).toHaveBeenCalledTimes(1);
    });

    File: propr-ui/e2e/pwa-mobile.spec.ts (new file)

    Why this file: A route-level browser smoke test catches manifest linkage, fixed-navigation overlap, and small-viewport overflow.

    import { expect, test } from '@playwright/test';
    
    for (const viewport of [{ width: 320, height: 700 }, { width: 390, height: 844 }]) {
      test(`mobile navigation and Inbox fit ${viewport.width}px`, async ({ page }) => {
        await page.setViewportSize(viewport);
        await authenticateDemoSession(page);
        await page.goto('/inbox');
        await expect(page.getByRole('navigation', { name: 'Primary mobile navigation' })).toBeVisible();
        await expect(page.getByText('Inbox', { exact: true }).last()).toBeVisible();
        const overflow = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth);
        expect(overflow).toBe(false);
      });
    }
    
    test('document exposes install metadata', async ({ page }) => {
      await page.goto('/');
      await expect(page.locator('link[rel=manifest]')).toHaveAttribute('href', '/manifest.webmanifest');
      await expect(page.locator('link[rel=apple-touch-icon]')).toHaveAttribute('href', '/icons/apple-touch-icon.png');
    });
  2. propr-dev commented on Aug 25, 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: 1728/gpt-5.6-sol-add-notification-push-dee-20260825-0038-akp
    • Base Branch: 1716-epic-failed-to-3m8
    • Worktree: issue-1728-20260825-0038-gpt-5.6-sol-akp

    🔍 Track Task Execution

  3. added a commit that references this issue on Aug 25, 2026
  4. added a commit that references this issue on Aug 25, 2026
  5. 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