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: refresh CoS Mind views from socket events (#8603)

[._.]/ Adam Eivy8481005897e8
diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsx
index 50a937b400..a6e9a5ae5b 100644
--- a/client/src/components/cos/tabs/ConfigTab.jsx
+++ b/client/src/components/cos/tabs/ConfigTab.jsx
@@ -14,7 +14,7 @@ import {
} from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
-import { useAutoRefetch } from '../../../hooks/useAutoRefetch.js';
+import { useSocketResource } from '../../../hooks/useSocketResource.js';
import PersistentMindProfileControls from '../PersistentMindProfileControls';
import { PersistentMindThoughtStatus } from '../PersistentMindRuntimePanel';
import ConfigRow from './ConfigRow';
@@ -153,6 +153,8 @@ function DomainAutomationControl({ config, usage, onDomainChange, onBudgetChange
);
}
+const MIND_STATUS_EVENTS = ['cos:mind:event', 'cos:mind:status', 'cos:config:changed'];
+
function PersistentMindStatus({ mind, loaded, error }) {
const state = mind?.state;
const model = mind?.profile?.model;
@@ -214,7 +216,6 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, r
const [saveStatus, setSaveStatus] = useState('idle');
const [profileSaving, setProfileSaving] = useState(false);
const [budgetUsage, setBudgetUsage] = useState({});
- const [mindStatus, setMindStatus] = useState({ data: null, loaded: false, error: null });
const configSaveQueueRef = useRef(Promise.resolve());
const pendingSaveCountRef = useRef(0);
const failedSaveKeysRef = useRef(new Set());
@@ -326,18 +327,13 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, r
.catch(() => {})
), []);
- const refreshMindStatus = useCallback(() => (
- api.getPersistentMind({ limit: 1 }, { silent: true })
- .then((data) => setMindStatus({ data, loaded: true, error: null }))
- .catch((error) => setMindStatus((current) => ({
- ...current,
- loaded: true,
- error: error?.message || 'Persistent mind status is unavailable',
- })))
- ), []);
+ const { data: mindData, loading: mindLoading, error: mindError, refetch: refreshMindStatus } = useSocketResource(
+ () => api.getPersistentMind({ limit: 1 }, { silent: true }),
+ { namespace: 'cos', events: MIND_STATUS_EVENTS },
+ );
+ const mindStatus = { data: mindData, loaded: !mindLoading, error: mindError ? mindError.message || 'Persistent mind status is unavailable' : null };
useEffect(() => { void refreshBudgetUsage(); }, [refreshBudgetUsage]);
- useAutoRefetch(refreshMindStatus, 15_000, { pollOnly: true });
// Built-in styles plus the install's verified animated records (#5894). A
// record entry carries its state coverage in the label, so what the
diff --git a/client/src/components/cos/tabs/ConfigTab.test.jsx b/client/src/components/cos/tabs/ConfigTab.test.jsx
index e597da617a..1eb8beeee9 100644
--- a/client/src/components/cos/tabs/ConfigTab.test.jsx
+++ b/client/src/components/cos/tabs/ConfigTab.test.jsx
@@ -24,6 +24,17 @@ const localLlm = vi.hoisted(() => ({
getToolUseModels: vi.fn(),
}));
+const socket = vi.hoisted(() => {
+ const handlers = new Map();
+ return {
+ on: (event, handler) => { if (!handlers.has(event)) handlers.set(event, new Set()); handlers.get(event).add(handler); },
+ off: (event, handler) => handlers.get(event)?.delete(handler),
+ emit: vi.fn(),
+ emitServer: event => handlers.get(event)?.forEach(handler => handler()),
+ };
+});
+vi.mock('../../../services/socket', () => ({ default: socket }));
+
vi.mock('../../../services/api', () => api);
vi.mock('../../../services/apiLocalLlm', () => localLlm);
vi.mock('../../ui/Toast', () => ({ default: toast }));
@@ -433,3 +444,39 @@ describe('render loop guard (#8348)', () => {
expect(providerHook.setSelectedModel).toHaveBeenCalledWith('gpt-5');
});
});
+
+it('reconciles Mind status on events, reconnect and reshow without polling or reads after unmount', async () => {
+ const view = renderConfig();
+ await screen.findByText('Waiting for the next wake');
+ vi.useFakeTimers();
+ try {
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(api.getPersistentMind).toHaveBeenCalledTimes(1);
+ api.getPersistentMind.mockResolvedValue({ state: { queuedMessageCount: 9 }, profile: {} });
+ for (const event of ['cos:mind:event', 'cos:mind:status', 'connect']) {
+ const before = api.getPersistentMind.mock.calls.length;
+ await act(async () => socket.emitServer(event));
+ expect(api.getPersistentMind).toHaveBeenCalledTimes(before + 1);
+ expect(screen.getByLabelText('Queued persistent mind messages')).toHaveTextContent('9');
+ }
+ const before = api.getPersistentMind.mock.calls.length;
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });
+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));
+ await act(async () => socket.emitServer('cos:mind:status'));
+ expect(api.getPersistentMind).toHaveBeenCalledTimes(before);
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));
+ expect(api.getPersistentMind).toHaveBeenCalledTimes(before + 1);
+ view.unmount();
+ await act(async () => {
+ socket.emitServer('connect');
+ socket.emitServer('cos:mind:event');
+ document.dispatchEvent(new Event('visibilitychange'));
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+ expect(api.getPersistentMind).toHaveBeenCalledTimes(before + 1);
+ } finally {
+ vi.useRealTimers();
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
+ }
+});
diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsx
index b26ce057b2..89117fc901 100644
--- a/client/src/components/cos/tabs/MindTab.jsx
+++ b/client/src/components/cos/tabs/MindTab.jsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router';
-import { useAutoRefetch } from '../../../hooks/useAutoRefetch.js';
+import { useVisibilityEvent } from '../../../hooks/useVisibilityEvent.js';
import useMounted from '../../../hooks/useMounted';
import useProviderModels from '../../../hooks/useProviderModels';
import { useSocket } from '../../../hooks/useSocket';
@@ -132,6 +132,7 @@ export default function MindTab() {
const deferredRuntimeRef = useRef(false);
const runtimeLoadedRef = useRef(false);
const visibilityPendingRef = useRef(false);
+ const deferredVisibilityRef = useRef(false);
const deferredVisibilityRefreshRef = useRef(false);
const visibilityLoadedRef = useRef(false);
const runtimeMountedRef = useMounted();
@@ -156,6 +157,7 @@ export default function MindTab() {
}, [activePanel]);
const loadHistory = useCallback(async ({ reset = false } = {}) => {
+ if (!runtimeMountedRef.current) return;
if (loadPendingRef.current) {
deferredLoadRef.current = true;
return;
@@ -173,6 +175,7 @@ export default function MindTab() {
try {
do {
const response = await api.getPersistentMind({ cursor, limit: PAGE_LIMIT }, { silent: true });
+ if (!runtimeMountedRef.current) return;
accumulated = mergeEvents(accumulated, response.events || []);
sawGap ||= response.gap === true;
cursor = response.gap === true ? response.cursor : response.cursor || cursor;
@@ -197,11 +200,11 @@ export default function MindTab() {
setLoadError(null);
if (needsMore) deferredLoadRef.current = true;
} catch (error) {
- setLoadError(error?.message || 'Could not load the persistent mind');
+ if (runtimeMountedRef.current) setLoadError(error?.message || 'Could not load the persistent mind');
} finally {
- setLoading(false);
+ if (runtimeMountedRef.current) setLoading(false);
loadPendingRef.current = false;
- if (deferredLoadRef.current) {
+ if (runtimeMountedRef.current && deferredLoadRef.current) {
deferredLoadRef.current = false;
void loadHistory();
}
@@ -209,6 +212,7 @@ export default function MindTab() {
}, []);
const loadRuntime = useCallback(async () => {
+ if (!runtimeMountedRef.current) return;
if (runtimePendingRef.current) {
deferredRuntimeRef.current = true;
return;
@@ -236,7 +240,9 @@ export default function MindTab() {
}, []);
const loadVisibility = useCallback(async ({ refresh = false } = {}) => {
+ if (!runtimeMountedRef.current) return;
if (visibilityPendingRef.current) {
+ deferredVisibilityRef.current = true;
deferredVisibilityRefreshRef.current ||= refresh;
return;
}
@@ -255,7 +261,8 @@ export default function MindTab() {
} finally {
if (runtimeMountedRef.current) setVisibilityLoading(false);
visibilityPendingRef.current = false;
- if (runtimeMountedRef.current && deferredVisibilityRefreshRef.current) {
+ if (runtimeMountedRef.current && deferredVisibilityRef.current) {
+ deferredVisibilityRef.current = false;
const deferredRefresh = deferredVisibilityRefreshRef.current;
deferredVisibilityRefreshRef.current = false;
void loadVisibility({ refresh: deferredRefresh });
@@ -263,25 +270,36 @@ export default function MindTab() {
}
}, [runtimeMountedRef]);
- useEffect(() => { void loadHistory({ reset: true }); }, [loadHistory]);
- useAutoRefetch(loadRuntime, 10_000, { pollOnly: true });
- useAutoRefetch(loadVisibility, 30_000, { pollOnly: true });
+ const refresh = useCallback(() => {
+ if (document.visibilityState === 'hidden') return;
+ void loadHistory();
+ void loadRuntime();
+ void loadVisibility();
+ }, [loadHistory, loadRuntime, loadVisibility]);
+
+ const lastVisibilityRef = useRef(document.visibilityState);
+ useVisibilityEvent((state) => {
+ const changed = lastVisibilityRef.current !== state;
+ lastVisibilityRef.current = state;
+ if (changed && state === 'visible') refresh();
+ });
useEffect(() => {
- const refresh = () => {
- void loadHistory();
- void loadRuntime();
- void loadVisibility();
+ refresh();
+ const refreshVisibility = () => {
+ if (document.visibilityState !== 'hidden') void loadVisibility();
};
socket.on('connect', refresh);
socket.on('cos:mind:event', refresh);
socket.on('cos:mind:status', refresh);
+ socket.on('cos:mind:visibility', refreshVisibility);
return () => {
socket.off('connect', refresh);
socket.off('cos:mind:event', refresh);
socket.off('cos:mind:status', refresh);
+ socket.off('cos:mind:visibility', refreshVisibility);
};
- }, [loadHistory, loadRuntime, loadVisibility, socket]);
+ }, [refresh, loadVisibility, socket]);
useEffect(() => {
const onCallState = (snapshot) => setCallState(snapshot?.error ? null : snapshot);
diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsx
index 105faea67a..7f2a85240d 100644
--- a/client/src/components/cos/tabs/MindTab.test.jsx
+++ b/client/src/components/cos/tabs/MindTab.test.jsx
@@ -87,6 +87,68 @@ const renderTab = (path = '/cos/mind') => render(
);
describe('MindTab', () => {
+ it('retains an in-flight visibility invalidation but drops queued reads after unmount', async () => {
+ let resolveVisibility;
+ api.getPersistentMindVisibility.mockReturnValueOnce(new Promise(resolve => { resolveVisibility = resolve; }));
+ const view = renderTab();
+ await screen.findByText('Review the next bounded slice.');
+ act(() => socket.emitServer('cos:mind:visibility', {}));
+ expect(api.getPersistentMindVisibility).toHaveBeenCalledTimes(1);
+ await act(async () => resolveVisibility({ readiness: 'ready' }));
+ expect(api.getPersistentMindVisibility).toHaveBeenCalledTimes(2);
+
+ let resolveHistory;
+ api.getPersistentMind.mockReturnValueOnce(new Promise(resolve => { resolveHistory = resolve; }));
+ act(() => socket.emitServer('cos:mind:event', {}));
+ act(() => socket.emitServer('cos:mind:status', {}));
+ const before = api.getPersistentMind.mock.calls.length;
+ view.unmount();
+ await act(async () => resolveHistory(response({ hasMore: true })));
+ expect(api.getPersistentMind).toHaveBeenCalledTimes(before);
+ });
+
+ it('reconciles Mind consumers from events and reshow without recurring API reads', async () => {
+ const view = renderTab();
+ await screen.findByText('Review the next bounded slice.');
+ vi.useFakeTimers();
+ const reads = [api.getPersistentMind, api.getPersistentMindRuntime, api.getPersistentMindVisibility];
+ const counts = () => reads.map(read => read.mock.calls.length);
+ try {
+ const initial = counts();
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(counts()).toEqual(initial);
+ for (const name of ['cos:mind:event', 'cos:mind:status', 'connect']) {
+ const before = counts();
+ await act(async () => socket.emitServer(name, {}));
+ expect(counts()).toEqual(before.map(count => count + 1));
+ }
+ const before = counts();
+ await act(async () => socket.emitServer('cos:mind:visibility', {}));
+ expect(counts()).toEqual([before[0], before[1], before[2] + 1]);
+ const hidden = counts();
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });
+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));
+ await act(async () => socket.emitServer('cos:mind:event', {}));
+ expect(counts()).toEqual(hidden);
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));
+ expect(counts()).toEqual(hidden.map(count => count + 1));
+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));
+ expect(counts()).toEqual(hidden.map(count => count + 1));
+ view.unmount();
+ await act(async () => {
+ socket.emitServer('connect');
+ socket.emitServer('cos:mind:event', {});
+ socket.emitServer('cos:mind:visibility', {});
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+ expect(counts()).toEqual(hidden.map(count => count + 1));
+ } finally {
+ vi.useRealTimers();
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
+ }
+ });
+
it('shows a prominent chosen identity and refreshes a rename from the trajectory notification', async () => {
api.getPersistentMind.mockResolvedValue(response({ identity: { mindId: 'cos-persistent-mind', name: 'Example Star' } }));
renderTab();
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index 61ca22c425..774440513c 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -54,6 +54,11 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
summary: 'Invalidate death-clock projection after local or federated inputs change.',
payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
},
+ 'cos:mind:visibility': {
+ direction: 'server-to-client',
+ summary: 'Coalesced environment visibility invalidation for subscribed CoS views; no private records.',
+ payloadSchema: { type: 'object', required: ['invalidated'], properties: { invalidated: { type: 'boolean', enum: [true] } }, additionalProperties: false },
+ },
'cos:goals:changed': {
direction: 'server-to-client',
summary: 'Invalidate operational goal progress after learning statistics persist.',
diff --git a/server/services/socket.js b/server/services/socket.js
index 00be48ec55..2ea676d97c 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -423,6 +423,18 @@ function broadcastToCos(event, data) {
// Broadcast to error subscribers only
function broadcastToErrors(event, data) { broadcastToSet(errorSubscribers, event, data); }
+// Environment changes need no Mind turn. Coalesce bursts into one bounded,
+// payload-free invalidation and send it only to existing CoS subscribers.
+let mindVisibilityTimer = null;
+function invalidateMindVisibility() {
+ if (!cosSubscribers.size || mindVisibilityTimer) return;
+ mindVisibilityTimer = setTimeout(() => {
+ mindVisibilityTimer = null;
+ broadcastToCos('cos:mind:visibility', { invalidated: true });
+ }, 250);
+ mindVisibilityTimer.unref?.();
+}
+
// Set up CoS event forwarding
function setupCosEventForwarding() {
// Status events
@@ -493,6 +505,10 @@ function setupCosEventForwarding() {
// Programmatic scheduled handlers report what they actually did — no agent
// task is created, so there is nothing else for the user to watch.
cosEvents.on('schedule:on-demand-handled', (data) => broadcastToCos('cos:schedule:on-demand-handled', data));
+ for (const event of ['config:changed', 'status', 'status:paused', 'status:resumed',
+ 'agent:spawned', 'agent:updated', 'agent:completed', 'health:check', 'health:critical']) {
+ cosEvents.on(event, invalidateMindVisibility);
+ }
}
// Set up error event forwarding
@@ -520,6 +536,7 @@ function setupErrorEventForwarding() {
// Set up apps event forwarding - broadcasts to ALL clients
function setupAppsEventForwarding() {
appsEvents.on('changed', (data) => {
+ invalidateMindVisibility();
if (ioInstance) {
ioInstance.emit('apps:changed', data);
}
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index 95805f5892..31e37459b3 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -151,6 +151,34 @@ describe('socket.js — initSocket', () => {
meatspaceEvents.removeAllListeners();
});
+ it('coalesces environment changes into payload-free Mind visibility invalidations for subscribers', () => {
+ vi.useFakeTimers();
+ const subscriber = makeSocket('mind-subscriber');
+ const outsider = makeSocket('mind-outsider');
+ createdSockets.push(subscriber, outsider);
+ io.connect(subscriber);
+ io.connect(outsider);
+ subscriber.handlers['cos:subscribe']();
+ try {
+ for (const name of ['config:changed', 'agent:spawned', 'agent:completed', 'health:check']) {
+ queueListeners.cos.filter(([event]) => event === name).forEach(([, handler]) => handler({ privateContent: 'example private record' }));
+ }
+ vi.advanceTimersByTime(249);
+ expect(subscriber.emitted.filter(([name]) => name === 'cos:mind:visibility')).toEqual([]);
+ vi.advanceTimersByTime(1);
+ expect(subscriber.emitted.filter(([name]) => name === 'cos:mind:visibility')).toEqual([
+ ['cos:mind:visibility', { invalidated: true }],
+ ]);
+ expect(outsider.emitted.filter(([name]) => name === 'cos:mind:visibility')).toEqual([]);
+ subscriber.handlers['cos:unsubscribe']();
+ queueListeners.cos.filter(([event]) => event === 'health:check').forEach(([, handler]) => handler({}));
+ vi.advanceTimersByTime(60_000);
+ expect(subscriber.emitted.filter(([name]) => name === 'cos:mind:visibility')).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('forwards death-clock invalidations without personal data', () => {
io.emitted.length = 0;
meatspaceEvents.emit('death-clock:changed', {});