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
refactor: route every cos:* subscriber through useSocketSubscription
[._.]/ Adam Eivy6cac52db9ef7
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex c938986b4a..7bcbf630d5 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -96,7 +96,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `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. || `useSocketResource` | Initial resource read plus global/room-event, reconnect and tab-show reconciliation; single-flight reads, identity guards, an enabled gate and immediate mutation updates. | Views replacing content polls with existing socket invalidations. || `useFableLoomRun` | Revisioned editorial/production snapshots, identity-safe mutation replies and entry/reconnect/reshow recovery. | FableLoom run views. |-| `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. |+| `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, `onResubscribe` refetches whatever a consumer may have missed while disconnected, and `payload`/`releasePayload` let one consumer set and later release a server-side room mode (ChiefOfStaff's `taskLists`). | 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; the caller re-renders on connect/disconnect. `useSocketConnected` (same file) returns the live connected flag as a boolean. | You need to subscribe to a socket event, or show connection state (`components/SocketReconnectingPill.jsx`). || `useItermSession` | Socket.IO `iterm:*` state for the Shell page's iTerm2 view (#8114): list subscription, URL-selected attach with a strict pending-target guard, byte-exact input, and an xterm sized to iTerm2's own grid (never fit, never resized back). Never touches `shell:*`. |diff --git a/client/src/hooks/useAgentFeedbackToast.jsx b/client/src/hooks/useAgentFeedbackToast.jsxindex c66df66581..5ae378bb5d 100644--- a/client/src/hooks/useAgentFeedbackToast.jsx+++ b/client/src/hooks/useAgentFeedbackToast.jsx@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback, useRef } from 'react';import toast from '../components/ui/Toast';import { ThumbsUp, ThumbsDown, Loader2, AlertTriangle } from 'lucide-react';import socket from '../services/socket';+import { useSocketSubscription } from './useSocketSubscription';import * as api from '../services/api';import OutputBlocks from '../components/cos/OutputBlocks';import { isAgentFeedbackEligible } from '../lib/cosAgentFeedback';@@ -162,10 +163,12 @@ export function useAgentFeedbackToast() {}}, []);- useEffect(() => {- // Subscribe to CoS events- socket.emit('cos:subscribe');+ // Refcounted with the other cos:* consumers and re-emitted on every reconnect+ // (the server clears its subscriber Set on disconnect); a bare emit here only+ // worked while a sibling Layout hook happened to re-subscribe the same socket.+ useSocketSubscription('cos');+ useEffect(() => {// Handle agent completion eventsconst handleAgentCompleted = (data) => {const agentId = data?.id || data?.agentId;@@ -221,7 +224,6 @@ export function useAgentFeedbackToast() {return () => {socket.off('cos:agent:completed', handleAgentCompleted);- // Don't unsubscribe from cos since other components may use it};}, [submitFeedback]);diff --git a/client/src/hooks/useAgentFeedbackToast.test.jsx b/client/src/hooks/useAgentFeedbackToast.test.jsxindex 11d78673da..b208d7ec15 100644--- a/client/src/hooks/useAgentFeedbackToast.test.jsx+++ b/client/src/hooks/useAgentFeedbackToast.test.jsx@@ -1,13 +1,15 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { renderHook, cleanup } from '@testing-library/react';+import { renderHook, cleanup, act } from '@testing-library/react';// Capture the `cos:agent:completed` handler so tests can drive completions.const handlers = new Map();+const emitted = [];vi.mock('../services/socket', () => ({default: {+ connected: true,on: (event, fn) => { handlers.set(event, fn); },off: (event, fn) => { if (handlers.get(event) === fn) handlers.delete(event); },- emit: () => {},+ emit: (event, payload) => { emitted.push([event, payload]); },},}));@@ -26,9 +28,23 @@ const completed = (overrides = {}) => ({});describe('useAgentFeedbackToast', () => {- beforeEach(() => { handlers.clear(); toastSpy.mockClear(); });+ beforeEach(() => { handlers.clear(); emitted.length = 0; toastSpy.mockClear(); });afterEach(cleanup);+ // The server clears its per-socket subscriber Set on disconnect, so with no+ // sibling cos:* consumer mounted this hook must re-subscribe on its own+ // (#12033) or a completion after the first reconnect toasts nothing.+ it('re-subscribes to cos:* on reconnect with only this hook mounted, and still toasts', () => {+ renderHook(() => useAgentFeedbackToast());+ expect(emitted.filter(([e]) => e === 'cos:subscribe')).toHaveLength(1);++ act(() => { handlers.get('connect')?.(); });+ expect(emitted.filter(([e]) => e === 'cos:subscribe')).toHaveLength(2);++ fire(completed());+ expect(toastSpy).toHaveBeenCalledTimes(1);+ });+it('prompts for a rating when a manual user task completes', () => {renderHook(() => useAgentFeedbackToast());fire(completed());diff --git a/client/src/hooks/useCosTaskUpdates.js b/client/src/hooks/useCosTaskUpdates.jsindex 4a93e0f516..4352a505f5 100644--- a/client/src/hooks/useCosTaskUpdates.js+++ b/client/src/hooks/useCosTaskUpdates.js@@ -1,5 +1,6 @@import { useEffect, useRef } from 'react';import socket from '../services/socket';+import { useSocketSubscription } from './useSocketSubscription';/*** Subscribes a surface to the shared CoS task lifecycle and forwards each task@@ -9,8 +10,9 @@ export function useCosTaskUpdates(onTaskUpdate) {const onTaskUpdateRef = useRef(onTaskUpdate);onTaskUpdateRef.current = onTaskUpdate;+ useSocketSubscription('cos');+useEffect(() => {- const subscribe = () => socket.emit('cos:subscribe');const emitTaskUpdate = task => {if (task) onTaskUpdateRef.current?.(task);};@@ -33,8 +35,6 @@ export function useCosTaskUpdates(onTaskUpdate) {}};- subscribe();- socket.on('connect', subscribe);socket.on('cos:tasks:changed', handleTaskChanged);socket.on('cos:tasks:user:changed', handleTaskListChanged);socket.on('cos:tasks:user:completed', handleTaskCompleted);@@ -42,7 +42,6 @@ export function useCosTaskUpdates(onTaskUpdate) {socket.on('cos:agent:completed', handleAgentCompleted);return () => {- socket.off('connect', subscribe);socket.off('cos:tasks:changed', handleTaskChanged);socket.off('cos:tasks:user:changed', handleTaskListChanged);socket.off('cos:tasks:user:completed', handleTaskCompleted);diff --git a/client/src/hooks/useOnDemandTaskToast.js b/client/src/hooks/useOnDemandTaskToast.jsindex 10bc6075ce..ed8a3aa9c7 100644--- a/client/src/hooks/useOnDemandTaskToast.js+++ b/client/src/hooks/useOnDemandTaskToast.js@@ -2,6 +2,7 @@ import { createElement, useEffect } from 'react';import MaintenanceRunStatus, { maintenanceRunProgress } from '../components/cos/tabs/schedule/MaintenanceRunStatus';import toast from '../components/ui/Toast';import socket from '../services/socket';+import { useSocketSubscription } from './useSocketSubscription';import { timeUntil } from '../utils/formatters';import { formatLiReason } from '../utils/layeredIntelligenceReasons';import { formatSkipCauses } from '../lib/perpetualSkipCauses';@@ -65,10 +66,9 @@ function maintenanceNeedsAttention(run) {* high in the tree (Layout), alongside useErrorNotifications.*/export function useOnDemandTaskToast() {+ useSocketSubscription('cos');+useEffect(() => {- const subscribe = () => socket.emit('cos:subscribe');- subscribe();- socket.on('connect', subscribe);const maintenanceStates = new Map();const handleMaintenance = run => {if (run.historyOnly) return;@@ -223,14 +223,12 @@ export function useOnDemandTaskToast() {socket.on('cos:schedule:on-demand-empty', handleEmpty);socket.on('cos:schedule:on-demand-handled', handleHandled);return () => {- socket.off('connect', subscribe);socket.off('cos:maintenance:updated', handleMaintenance);socket.off('cos:schedule:on-demand-empty', handleEmpty);socket.off('cos:schedule:on-demand-handled', handleHandled);for (const state of maintenanceStates.values()) {if (state.toastId) toast.dismiss(state.toastId);}- // Don't unsubscribe from cos — other components share the room.};}, []);}diff --git a/client/src/hooks/useSocketSubscription.js b/client/src/hooks/useSocketSubscription.jsindex 51d1536311..4bb48303f9 100644--- a/client/src/hooks/useSocketSubscription.js+++ b/client/src/hooks/useSocketSubscription.js@@ -45,21 +45,46 @@ function getEntry(namespace) {* redundant refetch in the common case (mount while already-connecting,* HTTP fetch already fresh) — cheap next to silently missing a real miss.*+ * - `payload` / `releasePayload`: a consumer that changes how the server+ * serves the room (ChiefOfStaff's `{ taskLists: 'invalidate' }` mode, which+ * `registerSubscriber` stores on the server-side socket) emits its own+ * `<namespace>:subscribe` with `payload` at mount and on every `connect`,+ * regardless of the refcount — the shared subscription may already exist+ * and the server would otherwise never hear about the mode. At unmount it+ * emits `releasePayload` the same way, BEFORE any final unsubscribe,+ * because the mode outlives room membership on the server socket. Both are+ * read through refs: a fresh object literal per render must not churn the+ * subscription.+ ** Pass no namespace for broadcast-only consumers; no room is acquired.** @param {string} namespace - a namespace registered server-side via* `registerSubscriber` (e.g. 'notifications', 'errors', 'instances', 'loops').- * @param {{ onResubscribe?: () => void, enabled?: boolean }} [options]+ * @param {{ onResubscribe?: () => void, enabled?: boolean, payload?: object, releasePayload?: object }} [options]*/-export function useSocketSubscription(namespace, { onResubscribe, enabled = true } = {}) {+export function useSocketSubscription(namespace, {+ onResubscribe, enabled = true, payload, releasePayload,+} = {}) {const onResubscribeRef = useRef(onResubscribe);onResubscribeRef.current = onResubscribe;+ const payloadRef = useRef(payload);+ payloadRef.current = payload;+ const releasePayloadRef = useRef(releasePayload);+ releasePayloadRef.current = releasePayload;useEffect(() => {if (!namespace || !enabled) return;const entry = getEntry(namespace);- const callback = () => onResubscribeRef.current?.();+ const subscribeWithPayload = () => {+ if (payloadRef.current !== undefined) socket.emit(`${namespace}:subscribe`, payloadRef.current);+ };+ // Registered before the shared handler fires below, so on connect the+ // bare subscribe lands first and this consumer's mode overrides it.+ const callback = () => {+ subscribeWithPayload();+ onResubscribeRef.current?.();+ };entry.callbacks.add(callback);if (entry.count === 0) {@@ -71,10 +96,14 @@ export function useSocketSubscription(namespace, { onResubscribe, enabled = truesocket.on('connect', entry.connectHandler);}entry.count += 1;+ subscribeWithPayload();return () => {entry.callbacks.delete(callback);entry.count -= 1;+ if (releasePayloadRef.current !== undefined) {+ socket.emit(`${namespace}:subscribe`, releasePayloadRef.current);+ }if (entry.count <= 0) {socket.emit(`${namespace}:unsubscribe`);if (entry.connectHandler) socket.off('connect', entry.connectHandler);diff --git a/client/src/hooks/useSocketSubscription.test.jsx b/client/src/hooks/useSocketSubscription.test.jsxindex e946d207e8..d51cffeb0a 100644--- a/client/src/hooks/useSocketSubscription.test.jsx+++ b/client/src/hooks/useSocketSubscription.test.jsx@@ -111,6 +111,40 @@ describe('useSocketSubscription', () => {expect(emitted.filter(([e]) => e === 'cos:subscribe')).toHaveLength(2);});+ it('emits a payload consumer\'s mode at mount, on every reconnect, and its release at unmount', () => {+ // ChiefOfStaff: the cos room is already held by Layout's toast hooks, so+ // the refcount alone would never tell the server about the page's+ // task-list mode — the mode is per server-side socket and outlives the+ // page, so it must be released explicitly when the page goes away.+ const cosSubscribes = () => emitted.filter(([e]) => e === 'cos:subscribe').map(([, p]) => p);+ const layout = renderHook(() => useSocketSubscription('cos'));+ const page = renderHook(() => useSocketSubscription('cos', {+ payload: { taskLists: 'invalidate' }, releasePayload: { taskLists: 'full' },+ }));+ expect(cosSubscribes()).toEqual([undefined, { taskLists: 'invalidate' }]);++ fire('connect');+ // Bare resubscribe first, then the mode on top of it.+ expect(cosSubscribes().slice(2)).toEqual([undefined, { taskLists: 'invalidate' }]);++ page.unmount();+ expect(cosSubscribes().at(-1)).toEqual({ taskLists: 'full' });+ expect(emitted.some(([e]) => e === 'cos:unsubscribe')).toBe(false);++ fire('connect');+ expect(cosSubscribes().at(-1)).toBeUndefined();+ layout.unmount();+ expect(emitted.filter(([e]) => e === 'cos:unsubscribe')).toHaveLength(1);+ });++ it('releases a payload consumer\'s mode before the final unsubscribe', () => {+ const { unmount } = renderHook(() => useSocketSubscription('cos', {+ payload: { taskLists: 'invalidate' }, releasePayload: { taskLists: 'full' },+ }));+ unmount();+ expect(emitted.slice(-2)).toEqual([['cos:subscribe', { taskLists: 'full' }], ['cos:unsubscribe', undefined]]);+ });+it('drops its connect listener once the last consumer unmounts', () => {const { unmount } = renderHook(() => useSocketSubscription('agents'));expect(handlers.get('connect')?.size ?? 0).toBe(1);diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 044d4ba765..0530d32161 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -1,6 +1,7 @@import { useState, useEffect, useCallback, useMemo, useRef, lazy, Suspense } from 'react';import { useParams, useNavigate, useSearchParams } from 'react-router';import { useSocket } from '../hooks/useSocket';+import { useSocketSubscription } from '../hooks/useSocketSubscription';import { useLocalStorageBool } from '../hooks/useLocalStorageBool';import { useValidTab } from '../hooks/useValidTab';import { useInstanceFeatures } from '../hooks/useInstanceFeatures.js';@@ -35,6 +36,11 @@ import StatCard from '../components/cos/StatCard';import StatusBubble, { StatusPill, isGenericStatusMessage } from '../components/cos/StatusBubble';import EventLog from '../components/cos/EventLog';import ActionableInsightsBanner from '../components/cos/ActionableInsightsBanner';+// cos:subscribe task-list modes (server/services/socket.js registerSubscriber):+// the page fetches its own lists on invalidation; everyone else gets full lists.+const COS_PAGE_SUBSCRIBE = { taskLists: 'invalidate' };+const COS_PAGE_RELEASE = { taskLists: 'full' };+const AgentsTab = lazy(() => import('../components/cos/tabs/AgentsTab'));// Task editing is not needed to view agents, so keep its forms and drag/drop@@ -226,6 +232,10 @@ export default function ChiefOfStaff() {// overwrite a fresher optimistic mutation or fetchQueue result.const queueSeqRef = useRef(0);const socket = useSocket();+ // The cos:* room, refcounted with the always-mounted Layout consumers, in the+ // page's lighter "invalidate" task-list mode while it is open; the shared+ // socket goes back to full task lists when it unmounts.+ useSocketSubscription('cos', { payload: COS_PAGE_SUBSCRIBE, releasePayload: COS_PAGE_RELEASE });// Verified animated records for the avatar selector and rigged playback (#5894).const { records: riggedAvatars } = useAvatarCapabilities();@@ -494,19 +504,8 @@ export default function ChiefOfStaff() {useEffect(() => {if (!socket) return;- // Subscribe when socket is connected (or already connected)- const subscribe = () => {- socket.emit('cos:subscribe', { taskLists: 'invalidate' });- };-- // Subscribe now if already connected, AND always re-subscribe on every- // (re)connect — the server rebuilds an empty per-socket subscriber Set on- // reconnect, so registering the listener only in the else branch left- // cos:* events dead after a reconnect when the socket was already connected- // at mount. Cleanup below offs this listener.- if (socket.connected) subscribe();+ // Reconnect recovery; the subscription itself lives in useSocketSubscription above.const reconnect = () => {- subscribe();appsReadRef.current = null;fetchData();setCompletedRevision(value => value + 1);@@ -674,12 +673,7 @@ export default function ChiefOfStaff() {socket.on('cos:status:resumed', handleConfigChanged);socket.on('apps:changed', handleAppsChanged);- // Don't emit cos:unsubscribe — the cos:* namespace is shared with- // useOpenWorldData (OpenWorld), useAgentFeedbackToast, and other always-mounted- // consumers; the server's per-socket subscriber Set has no ref count.- // Unsubscribing here would yank events out from under them.return () => {- socket.emit('cos:subscribe', { taskLists: 'full' });socket.off('connect', reconnect);socket.off('providers:changed', handleProvidersChanged);socket.off('cos:config:changed', handleConfigChanged);diff --git a/client/src/socketSubscriptionConventions.test.js b/client/src/socketSubscriptionConventions.test.jsindex 70dc8a6a5c..fd00b84a3c 100644--- a/client/src/socketSubscriptionConventions.test.js+++ b/client/src/socketSubscriptionConventions.test.js@@ -20,10 +20,11 @@* 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+ * Two 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).+ * allowlist below with a reason. The `cos` namespace has NO allowlist left+ * (#12033): every cos:* consumer goes through the hook, including the one+ * that changes the server's task-list mode (`payload` / `releasePayload`).** ## What this guard CANNOT see*@@ -61,20 +62,16 @@ 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/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',};+// The namespaces every consumer must reach through the hook — no allowlist+// row may name one of these. A cos:* row quietly re-admitted the bug class+// this guard exists for (#12033: a Layout toast hook that never re-subscribed+// on reconnect, carried by whichever sibling happened to).+const NO_ALLOWLIST_NAMESPACES = ['cos'];+const scannedFiles = () => trackedSourceFiles(CLIENT_ROOT);const emitsSubscribe = (file) => SUBSCRIBE_CALL.test(readFileSync(join(CLIENT_ROOT, file), 'utf8'));@@ -103,6 +100,14 @@ describe('socket namespace subscriptions go through useSocketSubscription', () =).toEqual([]);});+ it('never allowlists a cos:* subscriber', () => {+ const rows = Object.entries(ALLOWED).filter(([file]) => {+ const source = readFileSync(join(CLIENT_ROOT, file), 'utf8');+ return NO_ALLOWLIST_NAMESPACES.some((ns) => new RegExp(`emit\\(\\s*['"]${ns}:subscribe['"]`).test(source));+ });+ expect(rows.map(([file]) => file), 'cos:* subscribers go through useSocketSubscription (#12033)').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', () => {