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: live-update Memory tab on pending approvals and raise a persistent card on critical health (#10018)

Adam Eivy090eb70718af
diff --git a/client/src/components/cos/tabs/MemoryTab.archive.test.jsx b/client/src/components/cos/tabs/MemoryTab.archive.test.jsx
index 5eda40c748..0ebeedf5a7 100644
--- a/client/src/components/cos/tabs/MemoryTab.archive.test.jsx
+++ b/client/src/components/cos/tabs/MemoryTab.archive.test.jsx
@@ -12,6 +12,7 @@ vi.mock('../../../services/api', () => ({
deleteMemory: vi.fn(),
}));
+vi.mock('../../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));
vi.mock('../../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
vi.mock('../../../hooks/useProviderModels', () => ({
default: () => ({
diff --git a/client/src/components/cos/tabs/MemoryTab.jsx b/client/src/components/cos/tabs/MemoryTab.jsx
index f24704a1a7..162591aae4 100644
--- a/client/src/components/cos/tabs/MemoryTab.jsx
+++ b/client/src/components/cos/tabs/MemoryTab.jsx
@@ -4,6 +4,8 @@ import {Trash2, X, Check, XCircle, Pencil, AlertTriangle, Brain, Bot} from 'luci
import toast from '../../ui/Toast';
import Banner from '../../ui/Banner';
import * as api from '../../../services/api';
+import socket from '../../../services/socket';
+import { useSocketSubscription } from '../../../hooks/useSocketSubscription';
import { MEMORY_TYPES, MEMORY_TYPE_COLORS } from '../constants';
import { getAppName, formatDateNumeric, formatPercent } from '../../../utils/formatters';
import MemoryTimeline from './MemoryTimeline';
@@ -111,6 +113,25 @@ export default function MemoryTab({ apps = [] }) {
fetchData();
}, [fetchData]);
+ // New approvals are pushed by the server (`cos:memory:approval-needed`); refresh
+ // only the pending queue + counts so an open tab never flashes its full loading
+ // state, and reconcile after a reconnect that may have dropped an event.
+ const refreshPending = useCallback(async () => {
+ const appId = sourceFilter === 'brain' ? 'brain' : sourceFilter === 'cos' ? '__not_brain' : undefined;
+ const [pendingRes, statsRes] = await Promise.all([
+ api.getMemories({ status: 'pending_approval', limit: 50, appId }).catch(() => null),
+ api.getMemoryStats().catch(() => null)
+ ]);
+ if (pendingRes) setPendingMemories(pendingRes.memories || []);
+ if (statsRes) setStats(statsRes);
+ }, [sourceFilter]);
+
+ useSocketSubscription('cos', { onResubscribe: refreshPending });
+ useEffect(() => {
+ socket.on('cos:memory:approval-needed', refreshPending);
+ return () => socket.off('cos:memory:approval-needed', refreshPending);
+ }, [refreshPending]);
+
const handleSearch = async () => {
if (!searchQuery.trim()) {
setSearchResults(null);
diff --git a/client/src/components/cos/tabs/MemoryTab.live.test.jsx b/client/src/components/cos/tabs/MemoryTab.live.test.jsx
new file mode 100644
index 0000000000..0075a34b75
--- /dev/null
+++ b/client/src/components/cos/tabs/MemoryTab.live.test.jsx
@@ -0,0 +1,72 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+vi.mock('../../../services/api', () => ({
+ getCosConfig: vi.fn(),
+ getMemories: vi.fn(),
+ getMemoryStats: vi.fn(),
+ getEmbeddingStatus: vi.fn(),
+ getMemoryBackendStatus: vi.fn(),
+ deleteMemory: vi.fn(),
+}));
+
+const socket = vi.hoisted(() => ({ on: vi.fn(), off: vi.fn(), emit: vi.fn() }));
+vi.mock('../../../services/socket', () => ({ default: socket }));
+vi.mock('../../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+vi.mock('../../../hooks/useProviderModels', () => ({
+ default: () => ({
+ providers: [], availableModels: [], setSelectedProviderId: vi.fn(),
+ setSelectedModel: vi.fn(), selectedProviderId: '', selectedModel: '',
+ }),
+}));
+vi.mock('./MemoryTimeline', () => ({ default: () => null }));
+vi.mock('./MemoryEditModal', () => ({ default: () => null }));
+vi.mock('../../ui/InlineConfirmRow', () => ({
+ default: ({ question, confirmText, onConfirm, onCancel }) => (
+ <div>
+ <p>{question}</p>
+ <button type="button" onClick={onConfirm}>{confirmText}</button>
+ <button type="button" onClick={onCancel}>Cancel</button>
+ </div>
+ ),
+}));
+
+import * as api from '../../../services/api';
+import MemoryTab from './MemoryTab';
+
+const pending = {
+ id: 'synthetic-pending-1',
+ content: 'A synthetic pending memory',
+ type: 'fact',
+ status: 'pending_approval',
+ createdAt: '2026-10-01T12:00:00.000Z',
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.getCosConfig.mockResolvedValue({});
+ api.getMemories.mockResolvedValue({ memories: [] });
+ api.getMemoryStats.mockResolvedValue({ active: 0, pendingApproval: 0 });
+ api.getEmbeddingStatus.mockResolvedValue({ available: false });
+ api.getMemoryBackendStatus.mockResolvedValue({ backend: 'postgres' });
+});
+
+describe('MemoryTab live approvals', () => {
+ it('shows a newly pending memory when cos:memory:approval-needed arrives, without navigation', async () => {
+ render(
+ <MemoryRouter initialEntries={['/cos/memory']}>
+ <MemoryTab apps={[]} />
+ </MemoryRouter>
+ );
+ await waitFor(() => expect(socket.on).toHaveBeenCalledWith('cos:memory:approval-needed', expect.any(Function)));
+ expect(screen.queryByText('A synthetic pending memory')).toBeNull();
+
+ api.getMemories.mockImplementation(async (params = {}) => ({ memories: params.status === 'pending_approval' ? [pending] : [] }));
+ const handler = socket.on.mock.calls.find(([event]) => event === 'cos:memory:approval-needed')[1];
+ await act(async () => { await handler({ memories: [{ id: pending.id }] }); });
+
+ expect(await screen.findByText('A synthetic pending memory')).toBeTruthy();
+ expect(screen.getByText('Pending Approval (1)')).toBeTruthy();
+ });
+});
diff --git a/client/src/hooks/useActionQueue.js b/client/src/hooks/useActionQueue.js
index 92daae96e1..8a953365e9 100644
--- a/client/src/hooks/useActionQueue.js
+++ b/client/src/hooks/useActionQueue.js
@@ -9,7 +9,7 @@ import { ACTION_QUEUE_CHANGED, INSTANCE_FEATURES_CHANGED } from '../constants/ev
const EVENTS = [
'connect', 'brain:classified', 'brain:threads:changed',
'cos:tasks:user:changed', 'cos:tasks:cos:changed', 'cos:agent:completed',
- 'cos:memory:approved', 'cos:memory:rejected', 'cos:agent:feedback',
+ 'cos:memory:approval-needed', 'cos:memory:approved', 'cos:memory:rejected', 'cos:agent:feedback',
'messages:changed', 'messages:draft:created', 'messages:draft:sent',
'backup:started', 'backup:completed', 'backup:failed',
'review:item:created', 'review:item:updated', 'review:item:deleted',
diff --git a/server/services/cos.js b/server/services/cos.js
index 13193b1153..637da0341e 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -100,6 +100,7 @@ import { ensureInstanceId } from './instanceIdentity.js';
import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';
import { retryTasksResolvedByInvestigation } from './investigationRetry.js';
import { notifyIfPrLeftOrphaned } from './orphanedPrNotifier.js';
+import { notifyCriticalHealth, clearCriticalHealthIfRecovered } from './healthCriticalNotifier.js';
const RESUME_DEQUEUE_DELAY_MS = 500;
// CD recovery normally resolves in <100ms; hold start() at most this long so
@@ -1609,6 +1610,16 @@ export async function init() {
.catch(err => console.error(`❌ Orphaned-PR check failed for task ${data?.task?.id}: ${err.message}`));
});
+ // A critical health transition reaches the bell even when no CoS view is open.
+ cosEvents.on('health:critical', (issues) => {
+ notifyCriticalHealth(issues)
+ .catch(err => console.error(`❌ Critical-health notification failed: ${err.message}`));
+ });
+ cosEvents.on('health:check', (check) => {
+ clearCriticalHealthIfRecovered(check)
+ .catch(err => console.error(`❌ Critical-health recovery check failed: ${err.message}`));
+ });
+
cosEvents.on('tasks:user:added', () => {
if (isDaemonRunning()) scheduleDequeue();
});
diff --git a/server/services/healthCriticalNotifier.js b/server/services/healthCriticalNotifier.js
new file mode 100644
index 0000000000..1405c05d9a
--- /dev/null
+++ b/server/services/healthCriticalNotifier.js
@@ -0,0 +1,53 @@
+/**
+ * Critical-health notifier.
+ *
+ * The CoS health monitor emits `health:critical` with the error-level issues it
+ * found (a failed PM2 restart, an unreadable process list). The socket bridge
+ * only reaches an open CoS view, so a transition nobody was watching vanished.
+ * This turns it into a persistent notification card in the bell.
+ *
+ * The monitor re-emits on every interval while the condition persists, so the
+ * card is deduped on the issue SET: an unchanged set raises nothing, a changed
+ * set replaces the old card, and a `health:check` with no error-level issues
+ * retracts it. Machine-local — `data/notifications.json` is never federated.
+ */
+
+import { addNotification, exists, removeByMetadata, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';
+
+const SOURCE = 'cos-health-critical';
+
+const issueKey = (issues) => [...new Set(issues.map(i => i.message))].sort().join('\n');
+
+/**
+ * @param {Array<{ message: string, category?: string }>} issues - `health:critical` payload
+ * @returns {Promise<boolean>} whether a card was raised
+ */
+export async function notifyCriticalHealth(issues) {
+ if (!Array.isArray(issues) || issues.length === 0) return false;
+ const key = issueKey(issues);
+ if (await exists(NOTIFICATION_TYPES.HEALTH_ISSUE, 'healthCriticalKey', key)) return false;
+ await removeByMetadata('source', SOURCE);
+ const shown = issues.slice(0, 5).map(i => i.message);
+ const more = issues.length > shown.length ? ` (+${issues.length - shown.length} more)` : '';
+ await addNotification({
+ type: NOTIFICATION_TYPES.HEALTH_ISSUE,
+ title: `Critical health: ${issues.length} issue${issues.length === 1 ? '' : 's'}`,
+ description: `${shown.join('; ')}${more}`,
+ priority: PRIORITY_LEVELS.CRITICAL,
+ link: '/system-resources/overview',
+ metadata: { source: SOURCE, healthCriticalKey: key },
+ });
+ return true;
+}
+
+/**
+ * Retract the card once a health check reports no error-level issues.
+ *
+ * @param {{ issues?: Array<{ type?: string }> }} check - `health:check` payload
+ * @returns {Promise<boolean>} whether a card was retracted
+ */
+export async function clearCriticalHealthIfRecovered(check) {
+ if ((check?.issues ?? []).some(i => i.type === 'error')) return false;
+ const { removed } = await removeByMetadata('source', SOURCE);
+ return removed > 0;
+}
diff --git a/server/services/healthCriticalNotifier.test.js b/server/services/healthCriticalNotifier.test.js
new file mode 100644
index 0000000000..0bbcd771d9
--- /dev/null
+++ b/server/services/healthCriticalNotifier.test.js
@@ -0,0 +1,65 @@
+/**
+ * Contract: one persistent card per distinct critical-issue set, replaced when
+ * the set changes, retracted on recovery — never re-raised for an unchanged set.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+vi.mock('./notifications.js', () => ({
+ addNotification: vi.fn().mockResolvedValue({}),
+ exists: vi.fn().mockResolvedValue(false),
+ removeByMetadata: vi.fn().mockResolvedValue({ success: true, removed: 0 }),
+ NOTIFICATION_TYPES: { HEALTH_ISSUE: 'health_issue' },
+ PRIORITY_LEVELS: { CRITICAL: 'critical' },
+}));
+
+import { notifyCriticalHealth, clearCriticalHealthIfRecovered } from './healthCriticalNotifier.js';
+import { addNotification, exists, removeByMetadata } from './notifications.js';
+
+const issues = [
+ { type: 'error', category: 'processes', message: 'PM2 process read failed' },
+ { type: 'error', category: 'processes', message: 'Restart failed: example-app' },
+];
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ exists.mockResolvedValue(false);
+ removeByMetadata.mockResolvedValue({ success: true, removed: 0 });
+});
+
+describe('notifyCriticalHealth', () => {
+ it('raises a critical health card naming the issues', async () => {
+ expect(await notifyCriticalHealth(issues)).toBe(true);
+ const card = addNotification.mock.calls[0][0];
+ expect(card).toMatchObject({ type: 'health_issue', priority: 'critical' });
+ expect(card.description).toContain('Restart failed: example-app');
+ expect(removeByMetadata).toHaveBeenCalledWith('source', 'cos-health-critical');
+ });
+
+ it('stays silent when the same issue set is already announced, regardless of order', async () => {
+ exists.mockResolvedValue(true);
+ expect(await notifyCriticalHealth(issues)).toBe(false);
+ expect(await notifyCriticalHealth([...issues].reverse())).toBe(false);
+ expect(exists.mock.calls[0][2]).toBe(exists.mock.calls[1][2]);
+ expect(addNotification).not.toHaveBeenCalled();
+ expect(removeByMetadata).not.toHaveBeenCalled();
+ });
+
+ it('ignores an empty or malformed payload', async () => {
+ expect(await notifyCriticalHealth([])).toBe(false);
+ expect(await notifyCriticalHealth(undefined)).toBe(false);
+ expect(addNotification).not.toHaveBeenCalled();
+ });
+});
+
+describe('clearCriticalHealthIfRecovered', () => {
+ it('retracts the card when no error-level issue remains (warnings do not keep it)', async () => {
+ removeByMetadata.mockResolvedValue({ success: true, removed: 1 });
+ expect(await clearCriticalHealthIfRecovered({ issues: [{ type: 'warning', message: 'High process count' }] })).toBe(true);
+ expect(removeByMetadata).toHaveBeenCalledWith('source', 'cos-health-critical');
+ });
+
+ it('keeps the card while an error-level issue persists', async () => {
+ expect(await clearCriticalHealthIfRecovered({ issues })).toBe(false);
+ expect(removeByMetadata).not.toHaveBeenCalled();
+ });
+});