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: re-subscribe socket namespaces on reconnect (#8110)

[._.]/ Adam Eivya10ae18b6d14
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index a169075044..3c000320fd 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -85,6 +85,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| Hook | Purpose | Use when |
|---|---|---|
| `useCosTaskUpdates` | Shared five-event CoS task lifecycle subscription; re-subscribes on socket reconnect and forwards normalized task updates to the current callback. | A CoS task surface with its own task-status reducer. |
+| `useSocketSubscription` | Refcounted `<namespace>:subscribe`/`unsubscribe` for a `registerSubscriber` room: the first mounted consumer subscribes and re-emits on every socket reconnect, the last to unmount unsubscribes, and `onResubscribe` refetches whatever a consumer may have missed while disconnected. | Any hook/page that emits a literal `<ns>:subscribe` for `cos`/`errors`/`notifications`/`agents`/`instances`/`loops`/`beeper` — don't hand-roll the reconnect dance; `client/src/socketSubscriptionConventions.test.js` enforces this. |
| `useAccountSyncStatus` | Per-account busy/auth state and deduplicated HTTP/socket sync outcomes. | Calendar and Messages sync controls. |
| `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. |
| `useShellSession` | All Socket.IO `shell:*` session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (`pendingAttachRef {target,generation}`, `claim`, `userIdleRef`, `mountedRef`), URL sync, and every session action. Returns `{ terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendImage, sendCommand, sendCd, sendCtrlB, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession }` so the route stays presentational. `sendCd(path)` sends a FOLDER over `shell:cd` rather than composing a `cd` line — the server renders it for the session's actual shell (`server/lib/shellCd.js`), which is the only form that works on a Windows cmd.exe session. `sendCommand(cmd)` submits with CR, never `\n` (see `SUBMIT_KEY` in `server/lib/tuiHandshake.js`). `sendImage(file, message)` is the one operation that leaves the socket — it POSTs to `/api/shell/sessions/:id/image` so a running agent TUI gets the photo's path pasted into its prompt. | The Shell page (`pages/Shell.jsx`) — don't re-roll the single-subscriber PTY attach lifecycle. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 2d7b8f5192..f468818411 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -167,6 +167,7 @@ export * from './useCosTaskUpdates.js';
export * from './usePrevious.js';
export * from './useShellSession.js';
export * from './useSocket.js';
+export * from './useSocketSubscription.js';
export * from './useTimeTick.js';
export * from './useUpdateChecker.jsx';
export * from './useVisibilityEvent.js';
diff --git a/client/src/hooks/useErrorNotifications.js b/client/src/hooks/useErrorNotifications.js
index e6beaf1024..be767b3b36 100644
--- a/client/src/hooks/useErrorNotifications.js
+++ b/client/src/hooks/useErrorNotifications.js
@@ -1,6 +1,7 @@
import { useEffect, useCallback } from 'react';
import toast from '../components/ui/Toast';
import socket from '../services/socket';
+import { useSocketSubscription } from './useSocketSubscription';
// Render an error's context object as a single-line suffix (empty when absent)
// so the console stays on one interpolated line instead of expanding a group.
@@ -16,13 +17,18 @@ export function useErrorNotifications() {
toast('Recovery agent dispatched', { icon: '🔧' });
}, []);
+ // Re-emits `errors:subscribe` on every socket reconnect, since the server's
+ // per-socket subscriber Set is empty on the reconnected socket — without
+ // this, error toasts (including the unattended-run `BACKUP_DB_DUMP_FAILED`
+ // toast this hook exists to surface) go silent for the rest of the tab's
+ // life after the first server restart/self-update.
+ useSocketSubscription('errors');
+
useEffect(() => {
- // Subscribe to targeted error broadcasts. We listen to ONLY `error:notified`
+ // Listen to targeted error broadcasts. We listen to ONLY `error:notified`
// (subscriber-scoped) and skip `error:occurred` (broadcast-to-all) — the
// server emits both for every error, so listening to both doubled every
// toast. The Toast layer also dedupes by content as a defense in depth.
- socket.emit('errors:subscribe');
-
const handleError = (error) => {
// A degraded DB backup is warning-severity (the file backup succeeded)
// but MUST still surface — its whole point is "find out the day it
@@ -87,7 +93,6 @@ export function useErrorNotifications() {
socket.on('error:recover:requested', handleRecoveryRequested);
return () => {
- socket.emit('errors:unsubscribe');
socket.off('error:notified', handleError);
socket.off('system:critical-error', handleCriticalError);
socket.off('error:recover:requested', handleRecoveryRequested);
diff --git a/client/src/hooks/useErrorNotifications.test.jsx b/client/src/hooks/useErrorNotifications.test.jsx
new file mode 100644
index 0000000000..abacc6c243
--- /dev/null
+++ b/client/src/hooks/useErrorNotifications.test.jsx
@@ -0,0 +1,66 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { renderHook, act, cleanup } from '@testing-library/react';
+
+const handlers = new Map();
+const emitted = [];
+vi.mock('../services/socket', () => ({
+ default: {
+ connected: true,
+ on: (event, fn) => {
+ if (!handlers.has(event)) handlers.set(event, new Set());
+ handlers.get(event).add(fn);
+ },
+ off: (event, fn) => { handlers.get(event)?.delete(fn); },
+ emit: (event, payload) => { emitted.push([event, payload]); },
+ },
+}));
+
+const toast = vi.hoisted(() => {
+ const fn = vi.fn();
+ fn.error = vi.fn();
+ fn.success = vi.fn();
+ return fn;
+});
+vi.mock('../components/ui/Toast', () => ({ default: toast }));
+
+const { useErrorNotifications } = await import('./useErrorNotifications.js');
+
+const fire = (event, payload) => act(() => {
+ for (const fn of [...(handlers.get(event) || [])]) fn(payload);
+});
+
+beforeEach(() => {
+ handlers.clear();
+ emitted.length = 0;
+ toast.mockClear();
+ toast.error.mockClear();
+ toast.success.mockClear();
+});
+afterEach(cleanup);
+
+describe('useErrorNotifications reconnect (#8110)', () => {
+ it('re-emits errors:subscribe on every socket reconnect', () => {
+ renderHook(() => useErrorNotifications());
+ expect(emitted.filter(([e]) => e === 'errors:subscribe')).toHaveLength(1);
+
+ fire('connect');
+ fire('connect');
+ // Mounted while already connected (socket.connected: true), so both
+ // 'connect' events are genuine reconnects.
+ expect(emitted.filter(([e]) => e === 'errors:subscribe')).toHaveLength(3);
+ });
+
+ it('keeps surfacing server errors as toasts after a reconnect', () => {
+ renderHook(() => useErrorNotifications());
+ fire('connect');
+
+ fire('error:notified', { code: 'SOMETHING_FAILED', message: 'Something failed', severity: 'error' });
+ expect(toast.error).toHaveBeenCalledWith('Something failed', expect.any(Object));
+ });
+
+ it('unsubscribes on unmount', () => {
+ const { unmount } = renderHook(() => useErrorNotifications());
+ unmount();
+ expect(emitted.some(([e]) => e === 'errors:unsubscribe')).toBe(true);
+ });
+});
diff --git a/client/src/hooks/useNotifications.js b/client/src/hooks/useNotifications.js
index 2ec6014aba..cd6425b1cf 100644
--- a/client/src/hooks/useNotifications.js
+++ b/client/src/hooks/useNotifications.js
@@ -1,12 +1,12 @@
import { useState, useEffect, useCallback, useRef } from 'react';
-import { useSocket } from './useSocket';
+import socket from '../services/socket';
+import { useSocketSubscription } from './useSocketSubscription';
import * as api from '../services/api';
export function useNotifications() {
const [notifications, setNotifications] = useState([]);
const [unreadCount, setUnreadCount] = useState(0);
const [loading, setLoading] = useState(true);
- const socket = useSocket();
const countGeneration = useRef(0);
@@ -21,6 +21,14 @@ export function useNotifications() {
});
}, []);
+ const refresh = useCallback(async () => {
+ const [notifs] = await Promise.all([
+ api.getNotifications({ limit: 50 }),
+ refreshCount()
+ ]);
+ setNotifications(notifs);
+ }, [refreshCount]);
+
// Fetch initial notifications
useEffect(() => {
let cancelled = false;
@@ -45,12 +53,16 @@ export function useNotifications() {
return () => { cancelled = true; countGeneration.current++; };
}, [refreshCount]);
- // Subscribe to socket events
- useEffect(() => {
- if (!socket) return;
-
- socket.emit('notifications:subscribe');
+ // Namespace subscription: this is the sole `notifications:*` consumer
+ // (mounted once, high in the tree, from Layout.jsx) now that OpenWorld's
+ // retired useOpenWorldData no longer shares it, so it's safe to unsubscribe
+ // on unmount. Re-emits `notifications:subscribe` on every socket reconnect
+ // and refetches the list + count so a bell that went silent during a server
+ // restart/self-update catches back up without a page reload.
+ useSocketSubscription('notifications', { onResubscribe: refresh });
+ // Subscribe to socket data events
+ useEffect(() => {
const handleAdded = (notification) => {
setNotifications(prev => [notification, ...prev.filter(n => n.id !== notification.id)]);
};
@@ -80,10 +92,6 @@ export function useNotifications() {
socket.on('notifications:count', handleCount);
socket.on('notifications:cleared', handleCleared);
- // notifications:* is a shared namespace; OpenWorld's useOpenWorldData also
- // subscribes. The server keeps a per-socket Set with no ref count, so
- // emitting notifications:unsubscribe here would also remove OpenWorld's
- // events. Just drop the listeners; disconnect cleans up Set membership.
return () => {
socket.off('notifications:added', handleAdded);
socket.off('notifications:removed', handleRemoved);
@@ -91,7 +99,7 @@ export function useNotifications() {
socket.off('notifications:count', handleCount);
socket.off('notifications:cleared', handleCleared);
};
- }, [socket]);
+ }, []);
const markAsRead = useCallback(async (id) => {
await api.markNotificationRead(id);
@@ -119,14 +127,6 @@ export function useNotifications() {
await refreshCount();
}, [refreshCount]);
- const refresh = useCallback(async () => {
- const [notifs] = await Promise.all([
- api.getNotifications({ limit: 50 }),
- refreshCount()
- ]);
- setNotifications(notifs);
- }, [refreshCount]);
-
return {
notifications,
unreadCount,
diff --git a/client/src/hooks/useNotifications.test.jsx b/client/src/hooks/useNotifications.test.jsx
index dc24c3b71e..d4349b4c18 100644
--- a/client/src/hooks/useNotifications.test.jsx
+++ b/client/src/hooks/useNotifications.test.jsx
@@ -13,13 +13,14 @@ const api = vi.hoisted(() => ({
}));
const socket = vi.hoisted(() => ({
+ connected: true,
emit: vi.fn(),
on: vi.fn(),
off: vi.fn()
}));
vi.mock('../services/api', () => api);
-vi.mock('./useSocket', () => ({ useSocket: () => socket }));
+vi.mock('../services/socket', () => ({ default: socket }));
import NotificationDropdown from '../components/NotificationDropdown.jsx';
import { useNotifications } from './useNotifications.js';
@@ -101,6 +102,26 @@ async function loadedHook() {
return hook;
}
+describe('reconnect resubscribes and refetches (#8110)', () => {
+ it('re-emits notifications:subscribe and refetches the list + count after a reconnect', async () => {
+ socket.connected = true;
+ await loadedHook();
+ expect(api.getNotifications).toHaveBeenCalledTimes(1);
+ expect(api.getNotificationCount).toHaveBeenCalledTimes(1);
+
+ const connectHandler = socket.on.mock.calls.find(([name]) => name === 'connect')?.[1];
+ expect(connectHandler).toBeTypeOf('function');
+
+ api.getNotifications.mockClear();
+ api.getNotificationCount.mockClear();
+ await act(async () => { connectHandler(); });
+
+ expect(socket.emit).toHaveBeenCalledWith('notifications:subscribe');
+ expect(api.getNotifications).toHaveBeenCalledTimes(1);
+ expect(api.getNotificationCount).toHaveBeenCalledTimes(1);
+ });
+});
+
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' };
diff --git a/client/src/hooks/useSocketSubscription.js b/client/src/hooks/useSocketSubscription.js
new file mode 100644
index 0000000000..25c13badab
--- /dev/null
+++ b/client/src/hooks/useSocketSubscription.js
@@ -0,0 +1,88 @@
+import { useEffect, useRef } from 'react';
+import socket from '../services/socket';
+
+/**
+ * Module-level refcount registry, keyed by namespace, backing the server's
+ * refcount-FREE subscriber Set (`registerSubscriber` in
+ * `server/services/socket.js`) with a correct client-side refcount.
+ *
+ * The server keeps room membership per server-side socket OBJECT — a Set that
+ * `disconnect` clears entirely (server/services/socket.js:167). When the
+ * shared client socket reconnects (server restart, PM2 reload, self-update,
+ * laptop sleep, a Wi-Fi/Tailscale blip), the server sees a brand new socket
+ * belonging to no subscriber set, so every namespace has to be re-subscribed.
+ * This registry does that once per namespace, for as long as at least one
+ * consumer is mounted, instead of every hook re-implementing its own
+ * `socket.on('connect', subscribe)`.
+ */
+const registry = new Map();
+
+function getEntry(namespace) {
+ let entry = registry.get(namespace);
+ if (!entry) {
+ // Whether the socket was already connected when this namespace's FIRST
+ // consumer mounted. If it wasn't, the socket's own upcoming 'connect'
+ // event is the initial connection establishing, not a reconnect — the
+ // first synchronous `emit` below already covers it, so onResubscribe
+ // must wait for the connect AFTER that one.
+ entry = { count: 0, connectHandler: null, callbacks: new Set(), sawInitialConnect: socket.connected };
+ registry.set(namespace, entry);
+ }
+ return entry;
+}
+
+/**
+ * Subscribe this component to a shared `<namespace>:subscribe` socket room
+ * for as long as it is mounted, backed by a module-level refcount so several
+ * consumers of the same namespace share one subscription:
+ *
+ * - The FIRST mounted consumer of a namespace emits `<namespace>:subscribe`
+ * and re-emits it on every socket `connect` (initial connect and every
+ * reconnect) for as long as any consumer holds the namespace.
+ * - The LAST consumer to unmount emits `<namespace>:unsubscribe`.
+ * - `onResubscribe`, if given, runs after every `<namespace>:subscribe`
+ * re-emission triggered by a socket `connect` event — so a consumer can
+ * refetch whatever it may have missed while disconnected. It does NOT run
+ * for the very first subscribe a mount performs; callers that also need
+ * the initial fetch already do that themselves (e.g. in a companion
+ * effect), and re-running it here would just duplicate that first fetch.
+ *
+ * @param {string} namespace - a namespace registered server-side via
+ * `registerSubscriber` (e.g. 'notifications', 'errors', 'instances', 'loops').
+ * @param {{ onResubscribe?: () => void }} [options]
+ */
+export function useSocketSubscription(namespace, { onResubscribe } = {}) {
+ const onResubscribeRef = useRef(onResubscribe);
+ onResubscribeRef.current = onResubscribe;
+
+ useEffect(() => {
+ const entry = getEntry(namespace);
+
+ const callback = () => onResubscribeRef.current?.();
+ entry.callbacks.add(callback);
+
+ if (entry.count === 0) {
+ socket.emit(`${namespace}:subscribe`);
+ entry.connectHandler = () => {
+ socket.emit(`${namespace}:subscribe`);
+ if (!entry.sawInitialConnect) {
+ entry.sawInitialConnect = true;
+ return;
+ }
+ for (const cb of entry.callbacks) cb();
+ };
+ socket.on('connect', entry.connectHandler);
+ }
+ entry.count += 1;
+
+ return () => {
+ entry.callbacks.delete(callback);
+ entry.count -= 1;
+ if (entry.count <= 0) {
+ socket.emit(`${namespace}:unsubscribe`);
+ if (entry.connectHandler) socket.off('connect', entry.connectHandler);
+ registry.delete(namespace);
+ }
+ };
+ }, [namespace]);
+}
diff --git a/client/src/hooks/useSocketSubscription.test.jsx b/client/src/hooks/useSocketSubscription.test.jsx
new file mode 100644
index 0000000000..bb3d175314
--- /dev/null
+++ b/client/src/hooks/useSocketSubscription.test.jsx
@@ -0,0 +1,119 @@
+import {
+ describe, it, expect, vi, beforeEach, afterEach,
+} from 'vitest';
+import { renderHook, act, cleanup } from '@testing-library/react';
+
+// Mock the socket singleton so the test can drive the 'connect' handlers the
+// hook registers and observe the subscribe/unsubscribe emits.
+const handlers = new Map();
+const emitted = [];
+const socketState = { connected: false };
+vi.mock('../services/socket', () => ({
+ default: {
+ get connected() { return socketState.connected; },
+ on: (event, fn) => {
+ if (!handlers.has(event)) handlers.set(event, new Set());
+ handlers.get(event).add(fn);
+ },
+ off: (event, fn) => { handlers.get(event)?.delete(fn); },
+ emit: (event, payload) => { emitted.push([event, payload]); },
+ },
+}));
+
+const { useSocketSubscription } = await import('./useSocketSubscription.js');
+
+const fire = (event, payload) => act(() => {
+ for (const fn of [...(handlers.get(event) || [])]) fn(payload);
+});
+
+beforeEach(() => {
+ handlers.clear();
+ emitted.length = 0;
+ socketState.connected = false;
+});
+afterEach(cleanup);
+
+describe('useSocketSubscription', () => {
+ it('subscribes once at mount and RE-SUBSCRIBES on every reconnect', () => {
+ // The server rebuilds an empty per-socket subscriber Set on reconnect
+ // (server/services/socket.js registerSubscriber), so a one-shot emit at
+ // mount goes permanently dead the first time it fires (#8110).
+ renderHook(() => useSocketSubscription('notifications'));
+ expect(emitted.filter(([e]) => e === 'notifications:subscribe')).toHaveLength(1);
+
+ fire('connect');
+ fire('connect');
+ expect(emitted.filter(([e]) => e === 'notifications:subscribe')).toHaveLength(3);
+ });
+
+ it('does not call onResubscribe for the very first connect after mount', () => {
+ // Mounting before the socket has ever connected means the upcoming
+ // 'connect' is the initial connection establishing, not a reconnect — the
+ // synchronous subscribe emit at mount already covers it, and the caller's
+ // own initial-fetch effect (not this hook) is responsible for that first load.
+ const onResubscribe = vi.fn();
+ renderHook(() => useSocketSubscription('loops', { onResubscribe }));
+
+ fire('connect'); // first-ever connect
+ expect(onResubscribe).not.toHaveBeenCalled();
+
+ fire('connect'); // a genuine reconnect
+ expect(onResubscribe).toHaveBeenCalledTimes(1);
+ });
+
+ it('calls onResubscribe on every reconnect when mounted while already connected', () => {
+ socketState.connected = true;
+ const onResubscribe = vi.fn();
+ renderHook(() => useSocketSubscription('errors', { onResubscribe }));
+
+ fire('connect');
+ fire('connect');
+ expect(onResubscribe).toHaveBeenCalledTimes(2);
+ });
+
+ it('always calls the CURRENT onResubscribe, not the one from first render', () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ socketState.connected = true;
+ const { rerender } = renderHook(
+ ({ onResubscribe }) => useSocketSubscription('errors', { onResubscribe }),
+ { initialProps: { onResubscribe: first } }
+ );
+ rerender({ onResubscribe: second });
+
+ fire('connect');
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledTimes(1);
+ });
+
+ it('unsubscribes only when the LAST consumer of a namespace unmounts', () => {
+ const a = renderHook(() => useSocketSubscription('instances'));
+ const b = renderHook(() => useSocketSubscription('instances'));
+
+ // One subscribe for the namespace, not two.
+ expect(emitted.filter(([e]) => e === 'instances:subscribe')).toHaveLength(1);
+
+ a.unmount();
+ expect(emitted.some(([e]) => e === 'instances:unsubscribe')).toBe(false);
+
+ b.unmount();
+ expect(emitted.filter(([e]) => e === 'instances:unsubscribe')).toHaveLength(1);
+ });
+
+ it('resubscribing after the last consumer unmounts starts a fresh subscription', () => {
+ const first = renderHook(() => useSocketSubscription('cos'));
+ first.unmount();
+ expect(emitted.filter(([e]) => e === 'cos:subscribe')).toHaveLength(1);
+ expect(emitted.filter(([e]) => e === 'cos:unsubscribe')).toHaveLength(1);
+
+ renderHook(() => useSocketSubscription('cos'));
+ expect(emitted.filter(([e]) => e === 'cos:subscribe')).toHaveLength(2);
+ });
+
+ it('drops its connect listener once the last consumer unmounts', () => {
+ const { unmount } = renderHook(() => useSocketSubscription('agents'));
+ expect(handlers.get('connect')?.size ?? 0).toBe(1);
+ unmount();
+ expect(handlers.get('connect')?.size ?? 0).toBe(0);
+ });
+});
diff --git a/client/src/pages/DataManager.jsx b/client/src/pages/DataManager.jsx
index 7d96b28fff..9c016c6e7f 100644
--- a/client/src/pages/DataManager.jsx
+++ b/client/src/pages/DataManager.jsx
@@ -8,6 +8,8 @@ import toast from '../components/ui/Toast';
import socket from '../services/socket';
import { useAsyncAction } from '../hooks/useAsyncAction';
import { useConfirmDelete } from '../hooks/useConfirmDelete';
+import { useSocketSubscription } from '../hooks/useSocketSubscription';
+import useMounted from '../hooks/useMounted';
import InlineConfirmRow from '../components/ui/InlineConfirmRow';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
@@ -24,41 +26,53 @@ const TOMBSTONE_KIND_PLURAL = { universe: 'universes', series: 'series', issue:
// in both `universe` and `pipeline`): partial progress is still useful.
function TombstoneGcSection() {
const [refused, setRefused] = useState(null); // null = still loading
+ const mountedRef = useMounted();
+ const backfillTimerRef = useRef(null);
+
+ const fetchStatus = useCallback(() => {
+ api.getTombstoneSweepStatus({ silent: true })
+ .then((r) => { if (mountedRef.current && Array.isArray(r?.refused)) setRefused(r.refused); })
+ .catch(() => { if (mountedRef.current) setRefused((prev) => prev ?? []); });
+ }, [mountedRef]);
// Subscribe to peer-state changes so toggling a snapshot-mode peer's
// sync category (or disabling it) re-evaluates the refusal status
// without a page reload — otherwise the button stays stuck disabled
// even after the user has resolved the underlying refusal condition.
//
+ // This is DataManager's only `instances:*` consumer, so it must hold its
+ // own `instances:subscribe` — it previously only listened for
+ // `instances:peers:updated` without ever subscribing, and the server sends
+ // that event only to the `instances` subscriber Set (registerSubscriber in
+ // server/services/socket.js), so the handler below could never fire; only
+ // the Instances page (which unsubscribes when you navigate away) held that
+ // subscription. `useSocketSubscription` also re-subscribes on reconnect and
+ // refetches via `onResubscribe`, so a peer change missed while disconnected
+ // is caught up on the next connect.
+ //
// `instances:peers:updated` fires from `updatePeer` BEFORE the async
// `autoSubscribePeerToAllRecords` backfill creates per-record subs, so an
// immediate fetch sees the pre-backfill state. Schedule a follow-up fetch
// after a short delay to capture the post-backfill subs; debounce so a
// rapid burst of peer updates collapses to one delayed fetch.
+ useSocketSubscription('instances', { onResubscribe: fetchStatus });
+
useEffect(() => {
- let cancelled = false;
- let backfillTimer = null;
- const fetchStatus = () => {
- api.getTombstoneSweepStatus({ silent: true })
- .then((r) => { if (!cancelled && Array.isArray(r?.refused)) setRefused(r.refused); })
- .catch(() => { if (!cancelled) setRefused((prev) => prev ?? []); });
- };
const refreshAfterPeerChange = () => {
fetchStatus();
- if (backfillTimer) clearTimeout(backfillTimer);
- backfillTimer = setTimeout(() => {
- backfillTimer = null;
- if (!cancelled) fetchStatus();
+ if (backfillTimerRef.current) clearTimeout(backfillTimerRef.current);
+ backfillTimerRef.current = setTimeout(() => {
+ backfillTimerRef.current = null;
+ if (mountedRef.current) fetchStatus();
}, 1500);
};
fetchStatus();
socket.on('instances:peers:updated', refreshAfterPeerChange);
return () => {
- cancelled = true;
- if (backfillTimer) clearTimeout(backfillTimer);
+ if (backfillTimerRef.current) clearTimeout(backfillTimerRef.current);
socket.off('instances:peers:updated', refreshAfterPeerChange);
};
- }, []);
+ }, [fetchStatus, mountedRef]);
const [runSweep, sweeping] = useAsyncAction(async () => {
const result = await api.sweepTombstonesNow({ graceMs: 0 }, { silent: true });
diff --git a/client/src/pages/DataManager.test.jsx b/client/src/pages/DataManager.test.jsx
index 386eeefc79..2b30a60dba 100644
--- a/client/src/pages/DataManager.test.jsx
+++ b/client/src/pages/DataManager.test.jsx
@@ -1,6 +1,8 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, waitFor, fireEvent } from '@testing-library/react';
+import { render, screen, waitFor, fireEvent, act } from '@testing-library/react';
import DataManager from './DataManager';
+import socket from '../services/socket';
+import { getTombstoneSweepStatus } from '../services/api';
// A directory with no server-side CATEGORIES entry comes back `classified: false`
// with both permission flags off. The row must explain *why* Archive/Purge are
@@ -20,7 +22,7 @@ vi.mock('../services/api', () => ({
sweepTombstonesNow: vi.fn(),
}));
-vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));
+vi.mock('../services/socket', () => ({ default: { connected: true, on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));
const UNKNOWN_DESCRIPTION = "Not classified — PortOS doesn't know if this is safe to remove";
@@ -38,6 +40,40 @@ const overview = {
],
};
+// #8110: TombstoneGcSection listened for `instances:peers:updated` without
+// ever emitting `instances:subscribe` — the server sends that event only to
+// its `instances` subscriber Set, so the handler could never fire unless some
+// OTHER page (Instances.jsx) happened to hold the subscription. It must now
+// hold its own subscription and re-subscribe + refetch after a reconnect.
+describe('DataManager tombstone GC peer-refusal subscription (#8110)', () => {
+ beforeEach(() => {
+ getDataOverview.mockReset().mockResolvedValue(overview);
+ getDataCategory.mockReset().mockResolvedValue({ key: 'mystery-dir', items: [] });
+ getTombstoneSweepStatus.mockClear();
+ socket.emit.mockClear();
+ });
+
+ it('subscribes to the instances room on mount', async () => {
+ render(<DataManager />);
+ await waitFor(() => expect(screen.getByText(UNKNOWN_DESCRIPTION)).toBeInTheDocument());
+ expect(socket.emit).toHaveBeenCalledWith('instances:subscribe');
+ });
+
+ it('re-subscribes and refetches refusal status after a socket reconnect', async () => {
+ render(<DataManager />);
+ await waitFor(() => expect(screen.getByText(UNKNOWN_DESCRIPTION)).toBeInTheDocument());
+ const initialCalls = getTombstoneSweepStatus.mock.calls.length;
+
+ const connectHandler = socket.on.mock.calls.find(([event]) => event === 'connect')?.[1];
+ expect(connectHandler).toBeTypeOf('function');
+ socket.emit.mockClear();
+ await act(async () => connectHandler());
+
+ expect(socket.emit).toHaveBeenCalledWith('instances:subscribe');
+ await waitFor(() => expect(getTombstoneSweepStatus.mock.calls.length).toBeGreaterThan(initialCalls));
+ });
+});
+
describe('DataManager unclassified rows (#3285)', () => {
beforeEach(() => {
getDataOverview.mockReset().mockResolvedValue(overview);
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 643a38e77b..bbdb5ba95e 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -13,6 +13,7 @@ import {
import { useSearchParams } from 'react-router';
import Drawer from '../components/Drawer';
import useDrawerTab from '../hooks/useDrawerTab';
+import { useSocketSubscription } from '../hooks/useSocketSubscription';
import toast from '../components/ui/Toast';
import Pill from '../components/ui/Pill';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
@@ -1541,7 +1542,6 @@ function InstancesContent() {
.catch(() => { if (active) setParityReports({}); })
]).finally(() => { if (active) setLoading(false); });
- socket.emit('instances:subscribe');
const handlePeersUpdated = (updatedPeers) => {
setPeers(updatedPeers);
};
@@ -1554,11 +1554,17 @@ function InstancesContent() {
return () => {
active = false;
- socket.emit('instances:unsubscribe');
socket.off('instances:peers:updated', handlePeersUpdated);
};
}, [fetchData]);
+ // Namespace subscription, separate from the effect above so a reconnect's
+ // refetch doesn't re-run (and re-race) the tailnet/exposure/parity-report
+ // reads that only belong on mount. Re-emits `instances:subscribe` on every
+ // socket reconnect and refetches peers/syncStatus, since the server's
+ // per-socket subscriber Set is empty on the reconnected socket.
+ useSocketSubscription('instances', { onResubscribe: fetchData });
+
if (loading) {
return (
<PageSkeleton
diff --git a/client/src/pages/Instances.test.jsx b/client/src/pages/Instances.test.jsx
index d9302f700c..009ee8c027 100644
--- a/client/src/pages/Instances.test.jsx
+++ b/client/src/pages/Instances.test.jsx
@@ -41,7 +41,7 @@ vi.mock('../services/api', () => ({
stopTailcatServe: vi.fn(),
}));
-vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));
+vi.mock('../services/socket', () => ({ default: { connected: true, on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));
describe('AddPeerForm port default', () => {
beforeEach(() => {
@@ -401,6 +401,25 @@ describe('Instances page connection drawers', () => {
expect(api.updateSettings).not.toHaveBeenCalled();
});
+ // #8110: the server rebuilds an empty per-socket subscriber Set on every
+ // reconnect (restart, self-update, sleep, a network blip). Without a
+ // reconnect-driven re-subscribe, peer updates and sync progress go silent
+ // for the rest of the tab's life after the first reconnect.
+ it('re-subscribes instances:* and refetches peers on a socket reconnect', async () => {
+ renderUI(<MemoryRouter><Instances /></MemoryRouter>);
+ await screen.findByRole('button', { name: 'Sync now' });
+ expect(socket.emit).toHaveBeenCalledWith('instances:subscribe');
+ const getInstancesCalls = api.getInstances.mock.calls.length;
+
+ const connectHandler = socket.on.mock.calls.find(([event]) => event === 'connect')?.[1];
+ expect(connectHandler).toBeTypeOf('function');
+ socket.emit.mockClear();
+ await act(async () => connectHandler());
+
+ expect(socket.emit).toHaveBeenCalledWith('instances:subscribe');
+ await waitFor(() => expect(api.getInstances.mock.calls.length).toBeGreaterThan(getInstancesCalls));
+ });
+
// Regression: removing the last peer must not hide orphan/serve recovery or
// the saved route that would keep unattended rendering pointed at that peer.
it('keeps actionable recovery and the add CTA after the last peer disappears', async () => {
diff --git a/client/src/pages/Loops.jsx b/client/src/pages/Loops.jsx
index 93a58754fe..942d21fe7c 100644
--- a/client/src/pages/Loops.jsx
+++ b/client/src/pages/Loops.jsx
@@ -11,6 +11,7 @@ import { timeAgo } from '../components/feature-agents/constants';
import { formatCount, formatDurationMs } from '../utils/formatters';
import BrailleSpinner from '../components/BrailleSpinner';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useSocketSubscription } from '../hooks/useSocketSubscription';
import { clickableProps } from '../lib/a11yKeyboard.js';
import EmptyState from '../components/EmptyState';
import ProviderModelSelector from '../components/ProviderModelSelector';
@@ -362,17 +363,21 @@ export default function Loops() {
useEffect(() => {
fetchProviders();
- socket.emit('loops:subscribe');
const refreshEvents = ['loop:created', 'loop:stopped', 'loop:resumed', 'loop:deleted', 'loop:updated'];
const handleRefresh = () => fetchLoops();
refreshEvents.forEach(e => socket.on(e, handleRefresh));
return () => {
- socket.emit('loops:unsubscribe');
refreshEvents.forEach(e => socket.off(e, handleRefresh));
};
}, [fetchLoops, fetchProviders]);
+ // Re-emits `loops:subscribe` on every socket reconnect and refetches the
+ // list, since the server's per-socket subscriber Set is empty on the
+ // reconnected socket — without this, live output and status updates go
+ // silent after a server restart/self-update until the page is reloaded.
+ useSocketSubscription('loops', { onResubscribe: fetchLoops });
+
const handleAction = async (action, id) => {
const entry = ACTION_MAP[action];
if (!entry) return;
diff --git a/client/src/pages/Loops.test.jsx b/client/src/pages/Loops.test.jsx
index 345cea90fd..ed01ea81fc 100644
--- a/client/src/pages/Loops.test.jsx
+++ b/client/src/pages/Loops.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from 'vitest';
-import { render, screen } from '@testing-library/react';
+import { render, screen, waitFor, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
vi.mock('../services/api', () => ({
@@ -13,7 +13,7 @@ vi.mock('../services/api', () => ({
}));
vi.mock('../services/socket', () => ({
- default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },
+ default: { connected: true, on: vi.fn(), off: vi.fn(), emit: vi.fn() },
}));
// Mirror the real hook's on-mount fetch (the page clears `loading` only from
@@ -31,6 +31,29 @@ vi.mock('../hooks/useAutoRefetch', async () => {
});
import Loops from './Loops';
+import socket from '../services/socket';
+import * as api from '../services/api';
+
+describe('Loops reconnect resubscribe (#8110)', () => {
+ // The server rebuilds an empty per-socket subscriber Set on every reconnect
+ // (restart, self-update, sleep, a network blip). Without a reconnect-driven
+ // re-subscribe, the live output and status streams went silent for the rest
+ // of the tab's life after the first reconnect.
+ it('re-subscribes loops:* and refetches the list on a socket reconnect', async () => {
+ render(<Loops />);
+ await screen.findByText('No loops yet');
+ expect(socket.emit).toHaveBeenCalledWith('loops:subscribe');
+ const getLoopsCalls = api.getLoops.mock.calls.length;
+
+ const connectHandler = socket.on.mock.calls.find(([event]) => event === 'connect')?.[1];
+ expect(connectHandler).toBeTypeOf('function');
+ socket.emit.mockClear();
+ await act(async () => connectHandler());
+
+ expect(socket.emit).toHaveBeenCalledWith('loops:subscribe');
+ await waitFor(() => expect(api.getLoops.mock.calls.length).toBeGreaterThan(getLoopsCalls));
+ });
+});
describe('Loops new-loop form label associations', () => {
it('pairs the Interval label with the custom-interval input via explicit htmlFor/id', async () => {
diff --git a/client/src/socketSubscriptionConventions.test.js b/client/src/socketSubscriptionConventions.test.js
new file mode 100644
index 0000000000..326c933a84
--- /dev/null
+++ b/client/src/socketSubscriptionConventions.test.js
@@ -0,0 +1,133 @@
+// @vitest-environment node
+
+/**
+ * Repo-wide guard: a client file that emits `<ns>:subscribe` for a
+ * `registerSubscriber` namespace goes through `hooks/useSocketSubscription.js`.
+ *
+ * The server keeps room membership per server-side socket OBJECT
+ * (`registerSubscriber` in `server/services/socket.js`) with NO ref count —
+ * `disconnect` clears the whole subscriber Set. A one-shot `socket.emit('<ns>:subscribe')`
+ * at mount therefore goes permanently dead the first time the shared client
+ * socket reconnects (server restart, PM2 reload, self-update, laptop sleep, a
+ * Wi-Fi/Tailscale blip): the server sees a brand new socket belonging to no
+ * subscriber set. `useNotifications`, `useErrorNotifications`,
+ * `pages/Instances.jsx` and `pages/Loops.jsx` all shipped this bug (#8110) —
+ * the bell, error toasts, and the Instances/Loops live streams went silent
+ * for the rest of the tab's life after the first reconnect.
+ *
+ * `useSocketSubscription` centralizes the fix: subscribe once (refcounted
+ * across consumers of the same namespace), re-emit on every socket `connect`,
+ * and optionally refetch via `onResubscribe`. New namespace subscribers must
+ * use it instead of re-implementing the reconnect dance (or forgetting it).
+ *
+ * A handful of hooks predate this fix and already implement the correct
+ * `socket.on('connect', subscribe)` pattern by hand; they sit on the
+ * allowlist below with a reason rather than being forced to migrate in the
+ * same change (explicitly sanctioned by #8110's acceptance criteria).
+ *
+ * ## What this guard CANNOT see
+ *
+ * It is a source grep, not an AST pass:
+ * - A subscribe built from a dynamic template string (`` `${ns}:subscribe` ``)
+ * is invisible — that is also `useSocketSubscription`'s own internal form,
+ * so this is by design: the hook itself is exempted by path, not pattern.
+ * - It cannot tell an allowlisted file's *sanctioned* connect-resubscribe
+ * from a second, unguarded emit added to the same file later.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { existsSync, readFileSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { trackedSourceFiles } from './test/trackedFiles.js';
+
+const CLIENT_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+// The namespaces `registerSubscriber` wires up in server/services/socket.js.
+const SUBSCRIBER_NAMESPACES = ['cos', 'errors', 'notifications', 'agents', 'instances', 'loops', 'beeper'];
+
+const SUBSCRIBE_CALL = new RegExp(
+ `emit\\(\\s*['"](?:${SUBSCRIBER_NAMESPACES.join('|')}):subscribe['"]`
+);
+
+// The hook itself — the only file allowed to emit these literals unconditionally.
+const HOOK_FILE = 'src/hooks/useSocketSubscription.js';
+
+/**
+ * Files allowed to emit a namespace subscribe directly, each with the reason
+ * it is not the bug class this guard hunts for.
+ */
+const ALLOWED = {
+ // Already implement `subscribe(); socket.on('connect', subscribe);` by hand,
+ // predating useSocketSubscription — correct today, migration optional per
+ // #8110's acceptance criteria rather than mandatory in the same change.
+ 'src/hooks/useCosTaskUpdates.js': 're-subscribes cos:* on connect already',
+ 'src/hooks/useBeeperRealtime.js': 're-subscribes beeper:* on connect already',
+ 'src/hooks/useMoltworldWs.js': 're-subscribes agents:* on connect already',
+ 'src/hooks/useOnDemandTaskToast.js': 're-subscribes cos:* on connect already',
+ 'src/components/cos/tabs/schedule/MaintenanceRunForm.jsx': 're-subscribes cos:* on connect already',
+ 'src/pages/ChiefOfStaff.jsx': 're-subscribes cos:* on connect already (two taskLists modes)',
+ // Does not itself re-subscribe on connect, but rides on the shared cos:*
+ // namespace that useCosTaskUpdates (always mounted from Layout) keeps alive
+ // across reconnects — the server Set has no ref count, so any one consumer
+ // re-adding the socket restores every cos:* listener. Out of scope for
+ // #8110, which named only notifications/errors/instances/loops as the
+ // namespaces that went fully dark (no other consumer covering them).
+ 'src/hooks/useAgentFeedbackToast.jsx': 'rides on cos:* kept alive by useCosTaskUpdates; not independently broken',
+};
+
+const scannedFiles = () => trackedSourceFiles(CLIENT_ROOT);
+
+const emitsSubscribe = (file) => SUBSCRIBE_CALL.test(readFileSync(join(CLIENT_ROOT, file), 'utf8'));
+
+describe('socket namespace subscriptions go through useSocketSubscription', () => {
+ it('has no raw <ns>:subscribe emit outside the hook and its allowlist', () => {
+ const files = scannedFiles().filter((file) => file !== HOOK_FILE);
+ // A broken `git ls-files` (wrong cwd, detached checkout) would otherwise
+ // make this guard pass by scanning nothing at all.
+ expect(files.length).toBeGreaterThan(100);
+
+ const violations = files.filter((file) => !(file in ALLOWED) && emitsSubscribe(file));
+
+ expect(
+ violations,
+ 'These files emit a raw `<ns>:subscribe` for a registerSubscriber namespace. The '
+ + 'server rebuilds an empty per-socket subscriber Set on every reconnect (restart, '
+ + 'self-update, sleep, a network blip), so a one-shot emit at mount goes permanently '
+ + "dead the first time it fires (#8110).\n"
+ + "Fix: `useSocketSubscription(namespace, { onResubscribe })` from "
+ + "`client/src/hooks/useSocketSubscription.js` — it refcounts across consumers of the "
+ + "same namespace, re-emits subscribe on every connect, and calls `onResubscribe` so "
+ + "you can refetch what was missed while disconnected.\n"
+ + 'If this file already re-subscribes correctly on `connect` by hand, add it to '
+ + `ALLOWED in this file with a one-line reason.\nOffenders:\n ${violations.join('\n ')}`,
+ ).toEqual([]);
+ });
+
+ // Burn-down: an allowlist entry that no longer needs to be there must go, or
+ // the list quietly becomes a list of files nobody has looked at in a year.
+ it('has no stale allowlist entry', () => {
+ const missing = Object.keys(ALLOWED).filter((file) => !existsSync(join(CLIENT_ROOT, file)));
+ expect(missing, `Allowlisted files that no longer exist:\n ${missing.join('\n ')}`).toEqual([]);
+
+ const noLongerNeeded = Object.keys(ALLOWED).filter((file) => !emitsSubscribe(file));
+ expect(
+ noLongerNeeded,
+ 'These files are allowlisted but no longer emit a raw `<ns>:subscribe`. Delete their '
+ + `rows from ALLOWED.\n ${noLongerNeeded.join('\n ')}`,
+ ).toEqual([]);
+ });
+
+ // Guards the guard: a detector that stopped recognizing the banned call would
+ // make the scan above vacuously green and let the bug class walk back in.
+ it('recognizes a namespace subscribe and nothing that merely looks like one', () => {
+ expect(SUBSCRIBE_CALL.test("socket.emit('notifications:subscribe')")).toBe(true);
+ expect(SUBSCRIBE_CALL.test('socket.emit("loops:subscribe")')).toBe(true);
+ expect(SUBSCRIBE_CALL.test("socket.emit('cos:subscribe', { taskLists: 'full' })")).toBe(true);
+
+ expect(SUBSCRIBE_CALL.test("socket.emit('notifications:unsubscribe')")).toBe(false);
+ expect(SUBSCRIBE_CALL.test("socket.emit('loop:output')")).toBe(false);
+ expect(SUBSCRIBE_CALL.test("socket.emit(`${namespace}:subscribe`)")).toBe(false);
+ expect(SUBSCRIBE_CALL.test("socket.on('notifications:subscribed', handler)")).toBe(false);
+ });
+});