Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: keep notification unread badges aligned with server totals (#6656)
[._.]/ Adam Eivy518565902730
diff --git a/client/src/hooks/useNotifications.js b/client/src/hooks/useNotifications.jsindex 0e868846d1..2ec6014aba 100644--- a/client/src/hooks/useNotifications.js+++ b/client/src/hooks/useNotifications.js@@ -1,4 +1,4 @@-import { useState, useEffect, useCallback } from 'react';+import { useState, useEffect, useCallback, useRef } from 'react';import { useSocket } from './useSocket';import * as api from '../services/api';@@ -8,19 +8,31 @@ export function useNotifications() {const [loading, setLoading] = useState(true);const socket = useSocket();+ const countGeneration = useRef(0);++ // The total covers the full store, not just the loaded page. A socket total+ // or newer request supersedes any count request already in flight.+ const refreshCount = useCallback(async () => {+ const generation = ++countGeneration.current;+ await api.getNotificationCount().then(({ count }) => {+ if (generation === countGeneration.current) setUnreadCount(count);+ }).catch(err => {+ console.error(`❌ Failed to load notification count: ${err.message}`);+ });+ }, []);+// Fetch initial notificationsuseEffect(() => {let cancelled = false;const fetchNotifications = async () => {setLoading(true);try {- const [notifs, countData] = await Promise.all([+ const [notifs] = await Promise.all([api.getNotifications({ limit: 50 }),- api.getNotificationCount()+ refreshCount()]);if (cancelled) return;setNotifications(notifs);- setUnreadCount(countData.count);} catch (err) {if (cancelled) return;console.error(`❌ Failed to load notifications: ${err.message}`);@@ -30,8 +42,8 @@ export function useNotifications() {};fetchNotifications();- return () => { cancelled = true; };- }, []);+ return () => { cancelled = true; countGeneration.current++; };+ }, [refreshCount]);// Subscribe to socket eventsuseEffect(() => {@@ -40,8 +52,7 @@ export function useNotifications() {socket.emit('notifications:subscribe');const handleAdded = (notification) => {- setNotifications(prev => [notification, ...prev]);- setUnreadCount(prev => prev + 1);+ setNotifications(prev => [notification, ...prev.filter(n => n.id !== notification.id)]);};const handleRemoved = ({ id }) => {@@ -55,12 +66,12 @@ export function useNotifications() {};const handleCount = (count) => {+ countGeneration.current++;setUnreadCount(count);};const handleCleared = () => {setNotifications([]);- setUnreadCount(0);};socket.on('notifications:added', handleAdded);@@ -87,34 +98,34 @@ export function useNotifications() {setNotifications(prev =>prev.map(n => n.id === id ? { ...n, read: true } : n));- setUnreadCount(prev => Math.max(0, prev - 1));- }, []);+ await refreshCount();+ }, [refreshCount]);const markAllAsRead = useCallback(async () => {await api.markAllNotificationsRead();setNotifications(prev => prev.map(n => ({ ...n, read: true })));- setUnreadCount(0);- }, []);+ await refreshCount();+ }, [refreshCount]);const removeNotification = useCallback(async (id) => {await api.deleteNotification(id);setNotifications(prev => prev.filter(n => n.id !== id));- }, []);+ await refreshCount();+ }, [refreshCount]);const clearAll = useCallback(async () => {await api.clearNotifications();setNotifications([]);- setUnreadCount(0);- }, []);+ await refreshCount();+ }, [refreshCount]);const refresh = useCallback(async () => {- const [notifs, countData] = await Promise.all([+ const [notifs] = await Promise.all([api.getNotifications({ limit: 50 }),- api.getNotificationCount()+ refreshCount()]);setNotifications(notifs);- setUnreadCount(countData.count);- }, []);+ }, [refreshCount]);return {notifications,diff --git a/client/src/hooks/useNotifications.test.jsx b/client/src/hooks/useNotifications.test.jsxindex 8ceefcf29c..5b95dbc281 100644--- a/client/src/hooks/useNotifications.test.jsx+++ b/client/src/hooks/useNotifications.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react';import { MemoryRouter } from 'react-router';const api = vi.hoisted(() => ({@@ -52,7 +52,7 @@ function NotificationSurface() {}beforeEach(() => {- vi.clearAllMocks();+ vi.resetAllMocks();api.getNotifications.mockResolvedValue([NOTIFICATION]);api.getNotificationCount.mockResolvedValue({ count: 1 });});@@ -76,3 +76,130 @@ describe('useNotifications response contract', () => {expect(screen.getByRole('button', { name: 'View notification: Example notification' })).toBeInTheDocument();});});++function deferred() {+ let resolve;+ let reject;+ const promise = new Promise((res, rej) => { resolve = res; reject = rej; });+ return { promise, resolve, reject };+}++function deliver(event, payload) {+ const handler = socket.on.mock.calls.find(([name]) => name === event)?.[1];+ expect(handler).toBeTypeOf('function');+ handler(payload);+}++async function loadedHook() {+ const hook = renderHook(() => useNotifications());+ await waitFor(() => expect(hook.result.current.loading).toBe(false));+ return hook;+}++describe('authoritative unread totals', () => {+ it.each(['socket-first', 'http-first'])('keeps the remaining unread badge and row with %s delivery', async (order) => {+ const second = { ...NOTIFICATION, id: 'n2', title: 'Remaining notification' };+ api.getNotifications.mockResolvedValue([NOTIFICATION, second]);+ api.getNotificationCount.mockResolvedValue({ count: 2 });+ const mutation = deferred();+ api.markNotificationRead.mockReturnValue(mutation.promise);+ render(<MemoryRouter><NotificationSurface /></MemoryRouter>);+ await waitFor(() => expect(screen.getByTestId('notification-loading')).toHaveTextContent('false'));+ fireEvent.click(screen.getByRole('button', { name: 'Notifications (2 unread)' }));+ fireEvent.click(screen.getByRole('button', { name: 'Mark notification as read: Example notification' }));+ api.getNotificationCount.mockResolvedValue({ count: 1 });++ const socketUpdate = () => {+ deliver('notifications:updated', { ...NOTIFICATION, read: true });+ deliver('notifications:count', 1);+ };+ if (order === 'socket-first') act(socketUpdate);+ await act(async () => { mutation.resolve(); await mutation.promise; });+ if (order === 'http-first') act(socketUpdate);++ expect(screen.getByRole('button', { name: 'Notifications (1 unread)' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Mark notification as read: Remaining notification' })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Mark notification as read: Example notification' })).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Mark all notifications as read' })).toBeInTheDocument();+ });++ // Each public mutation needs an HTTP fallback when no socket event arrives.+ it.each([+ ['markAsRead', ['n1'], 73],+ ['markAllAsRead', [], 0],+ ['removeNotification', ['n1'], 73],+ ['clearAll', [], 0]+ ])('reconciles %s without socket delivery', async (method, args, count) => {+ api.getNotifications.mockResolvedValue(Array.from({ length: 50 }, (_, i) => ({ ...NOTIFICATION, id: 'n' + i })));+ api.getNotificationCount.mockResolvedValue({ count: 74 });+ const { result } = await loadedHook();+ expect(result.current.unreadCount).toBe(74);+ api.getNotificationCount.mockResolvedValue({ count });+ await act(async () => { await result.current[method](...args); });+ expect(result.current.unreadCount).toBe(count);+ expect(api.getNotificationCount).toHaveBeenCalledTimes(2);+ });++ it('discards delayed initial and refresh counts after a socket total', async () => {+ const initial = deferred();+ api.getNotificationCount.mockReturnValueOnce(initial.promise);+ const { result } = renderHook(() => useNotifications());+ act(() => deliver('notifications:count', 80));+ await act(async () => { initial.resolve({ count: 2 }); });+ expect(result.current.unreadCount).toBe(80);+ const refresh = deferred();+ api.getNotificationCount.mockReturnValueOnce(refresh.promise);+ let refreshing;+ act(() => { refreshing = result.current.refresh(); });+ act(() => deliver('notifications:count', 81));+ await act(async () => { refresh.resolve({ count: 3 }); await refreshing; });+ expect(result.current.unreadCount).toBe(81);+ });++ it('lets a newer count request supersede an older request', async () => {+ const { result } = await loadedHook();+ const older = deferred();+ api.getNotificationCount.mockReturnValueOnce(older.promise).mockResolvedValueOnce({ count: 9 });+ let refreshing;+ act(() => { refreshing = result.current.refresh(); });+ await act(async () => { await result.current.markAsRead('n1'); });+ await act(async () => { older.resolve({ count: 2 }); await refreshing; });+ expect(result.current.unreadCount).toBe(9);+ });++ it.each(['markAllAsRead', 'clearAll'])('does not zero a newer socket total when %s completes', async (method) => {+ const { result } = await loadedHook();+ const mutation = deferred();+ const fallback = deferred();+ api[method === 'clearAll' ? 'clearNotifications' : 'markAllNotificationsRead'].mockReturnValueOnce(mutation.promise);+ api.getNotificationCount.mockReturnValueOnce(fallback.promise);+ let pending;+ act(() => { pending = result.current[method](); });+ act(() => deliver('notifications:count', 7));+ await act(async () => { mutation.resolve(); });+ expect(result.current.unreadCount).toBe(7);+ act(() => deliver('notifications:count', 8));+ await act(async () => { fallback.resolve({ count: 0 }); await pending; });+ expect(result.current.unreadCount).toBe(8);+ });++ it('preserves the last total on count failure and applies record events idempotently', async () => {+ const { result } = await loadedHook();+ act(() => {+ deliver('notifications:added', NOTIFICATION);+ deliver('notifications:added', NOTIFICATION);+ });+ expect(result.current.notifications).toHaveLength(1);+ expect(result.current.unreadCount).toBe(1);+ api.getNotificationCount.mockRejectedValueOnce(new Error('Count unavailable'));+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});+ await act(async () => { await result.current.markAsRead('n1'); });+ expect(result.current.unreadCount).toBe(1);+ expect(result.current.notifications[0].read).toBe(true);+ expect(log).toHaveBeenCalledWith('❌ Failed to load notification count: Count unavailable');+ log.mockRestore();+ act(() => deliver('notifications:cleared'));+ expect(result.current.notifications).toEqual([]);+ expect(result.current.unreadCount).toBe(1);+ });+});