Skip to content

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

fix: guard the notifications reconnect refetch against unmount and failure

[._.]/ Adam Eivyeb4e377beecd
diff --git a/client/src/hooks/useNotifications.js b/client/src/hooks/useNotifications.js
index cd6425b1cf..7b6f6ce6a4 100644
--- a/client/src/hooks/useNotifications.js
+++ b/client/src/hooks/useNotifications.js
@@ -1,6 +1,7 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import socket from '../services/socket';
import { useSocketSubscription } from './useSocketSubscription';
+import useMounted from './useMounted';
import * as api from '../services/api';
export function useNotifications() {
@@ -8,7 +9,9 @@ export function useNotifications() {
const [unreadCount, setUnreadCount] = useState(0);
const [loading, setLoading] = useState(true);
+ const mountedRef = useMounted();
const countGeneration = useRef(0);
+ const listGeneration = 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.
@@ -21,37 +24,32 @@ export function useNotifications() {
});
}, []);
- const refresh = useCallback(async () => {
- const [notifs] = await Promise.all([
- api.getNotifications({ limit: 50 }),
- refreshCount()
- ]);
- setNotifications(notifs);
- }, [refreshCount]);
+ // The one list loader, shared by mount, reconnect and the public refresh:
+ // a response that lands after unmount or behind a newer load is dropped,
+ // and a failure logs instead of surfacing as an unhandled rejection (#12042).
+ const loadNotifications = useCallback(async (initial = false) => {
+ const generation = ++listGeneration.current;
+ const fresh = () => mountedRef.current && generation === listGeneration.current;
+ if (initial) setLoading(true);
+ try {
+ const [notifs] = await Promise.all([
+ api.getNotifications({ limit: 50 }),
+ refreshCount()
+ ]);
+ if (fresh()) setNotifications(notifs);
+ } catch (err) {
+ if (fresh()) console.error(`❌ Failed to load notifications: ${err.message}`);
+ } finally {
+ if (initial && fresh()) setLoading(false);
+ }
+ }, [refreshCount, mountedRef]);
+
+ const refresh = useCallback(() => loadNotifications(), [loadNotifications]);
- // Fetch initial notifications
useEffect(() => {
- let cancelled = false;
- const fetchNotifications = async () => {
- setLoading(true);
- try {
- const [notifs] = await Promise.all([
- api.getNotifications({ limit: 50 }),
- refreshCount()
- ]);
- if (cancelled) return;
- setNotifications(notifs);
- } catch (err) {
- if (cancelled) return;
- console.error(`❌ Failed to load notifications: ${err.message}`);
- } finally {
- if (!cancelled) setLoading(false);
- }
- };
-
- fetchNotifications();
- return () => { cancelled = true; countGeneration.current++; };
- }, [refreshCount]);
+ loadNotifications(true);
+ return () => { listGeneration.current++; countGeneration.current++; };
+ }, [loadNotifications]);
// Namespace subscription: this is the sole `notifications:*` consumer
// (mounted once, high in the tree, from Layout.jsx) now that OpenWorld's
diff --git a/client/src/hooks/useNotifications.test.jsx b/client/src/hooks/useNotifications.test.jsx
index d4349b4c18..09adaacc1c 100644
--- a/client/src/hooks/useNotifications.test.jsx
+++ b/client/src/hooks/useNotifications.test.jsx
@@ -122,6 +122,56 @@ describe('reconnect resubscribes and refetches (#8110)', () => {
});
});
+describe('guarded reconnect refetch (#12042)', () => {
+ const connect = () => {
+ const handler = socket.on.mock.calls.find(([name]) => name === 'connect')?.[1];
+ expect(handler).toBeTypeOf('function');
+ return handler;
+ };
+ const loadFailures = (spy) => spy.mock.calls.map(([line]) => String(line)).filter((line) => line.startsWith('❌ Failed to load notifications'));
+
+ it('logs a failed resubscribe refetch instead of rejecting, and keeps the list', async () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const { result } = await loadedHook();
+ api.getNotifications.mockRejectedValueOnce(new Error('boom'));
+
+ // An unhandled rejection here would fail the run; the hook must absorb it.
+ await act(async () => { connect()(); });
+
+ expect(loadFailures(errorSpy)).toEqual(['❌ Failed to load notifications: boom']);
+ expect(result.current.notifications).toEqual([NOTIFICATION]);
+ errorSpy.mockRestore();
+ });
+
+ it('ignores a resubscribe response that lands after unmount', async () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const { unmount } = await loadedHook();
+ const late = deferred();
+ api.getNotifications.mockReturnValueOnce(late.promise);
+ act(() => { connect()(); });
+ unmount();
+
+ // The only observable trace of an unguarded late response is its failure
+ // log — React drops the setState silently — so reject it and expect silence.
+ await act(async () => { late.reject(new Error('too late')); await late.promise.catch(() => {}); });
+ expect(loadFailures(errorSpy)).toEqual([]);
+ errorSpy.mockRestore();
+ });
+
+ it('lets a newer load supersede a slower one', async () => {
+ const slow = deferred();
+ api.getNotifications.mockReturnValueOnce(slow.promise);
+ const { result } = renderHook(() => useNotifications());
+ const newer = { ...NOTIFICATION, id: 'n2', title: 'Newer notification' };
+ api.getNotifications.mockResolvedValueOnce([newer]);
+ await act(async () => { connect()(); });
+ expect(result.current.notifications).toEqual([newer]);
+
+ await act(async () => { slow.resolve([NOTIFICATION]); await slow.promise; });
+ expect(result.current.notifications).toEqual([newer]);
+ });
+});
+
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' };