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: update Ambient from resource events instead of polling (#8555)

[._.]/ Adam Eivy5d144bbf2248
diff --git a/client/src/pages/Ambient.jsx b/client/src/pages/Ambient.jsx
index 9867e6e2db..fbdffd05a2 100644
--- a/client/src/pages/Ambient.jsx
+++ b/client/src/pages/Ambient.jsx
@@ -2,11 +2,15 @@ import { useState, useEffect, useMemo, useRef } from 'react';
import { useNavigate } from 'react-router';
import { ArrowLeft, Maximize, Minimize } from 'lucide-react';
import * as api from '../services/api';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useSocketResource } from '../hooks/useSocketResource';
+import { useSocket } from '../hooks/useSocket';
import { formatClockTime, formatDateFull, formatTimeOfDay } from '../utils/formatters';
import DeathClockCountdown from '../components/DeathClockCountdown';
-const REFRESH_INTERVAL = 30000;
+const CALENDAR_EVENTS = ['calendar:sync:completed'];
+const DEATH_CLOCK_EVENTS = ['meatspace:death-clock:changed'];
+const GOAL_EVENTS = ['cos:goals:changed'];
+const SUMMARY_EVENTS = ['cos:status', 'cos:status:paused', 'cos:status:resumed', 'cos:agent:spawned', 'cos:agent:updated', 'cos:agent:completed'];
const IDLE_DELAY = 3000;
const goalColor = (rate) =>
@@ -30,21 +34,49 @@ export default function Ambient() {
const [isFullscreen, setIsFullscreen] = useState(false);
const idleTimer = useRef(null);
- const { data } = useAutoRefetch(async () => {
+ const socket = useSocket();
+ const day = time.toDateString();
+ // A tab may resume after midnight before its next clock tick. Reads record
+ // their own day so the tick cannot duplicate reconnect/tab-show reconciliation.
+ const reconciledDays = useRef({ deathClock: day, summary: day, calendar: day });
+ const { data: deathData, refetch: refreshDeathClock } = useSocketResource(() => {
+ reconciledDays.current.deathClock = new Date().toDateString();
+ return api.getDeathClock();
+ }, {
+ events: DEATH_CLOCK_EVENTS
+ });
+ const { data: cosSummary, refetch: refreshSummary } = useSocketResource(() => {
+ reconciledDays.current.summary = new Date().toDateString();
+ return api.getCosQuickSummary({ silent: true });
+ }, {
+ namespace: 'cos', events: SUMMARY_EVENTS
+ });
+ const { data: goals } = useSocketResource(() => api.getCosGoalProgressSummary({ silent: true }), {
+ namespace: 'cos', events: GOAL_EVENTS
+ });
+ const { data: calendarEvents, refetch: refreshCalendar } = useSocketResource(async () => {
const now = new Date();
- const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate()).toISOString();
- const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).toISOString();
-
- const [deathClock, cosSummary, goals, events, health] = await Promise.all([
- api.getDeathClock().catch(() => null),
- api.getCosQuickSummary({ silent: true }).catch(() => null),
- api.getCosGoalProgressSummary({ silent: true }).catch(() => null),
- api.getCalendarEvents({ start: startOfDay, end: endOfDay }).catch(() => []),
- api.checkHealth().catch(() => null),
- ]);
+ reconciledDays.current.calendar = now.toDateString();
+ const params = {
+ startDate: new Date(now.getFullYear(), now.getMonth(), now.getDate()).toISOString(),
+ endDate: new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).toISOString(),
+ limit: 200
+ };
+ const events = [];
+ let page;
+ do {
+ page = await api.getCalendarEvents({ ...params, offset: events.length });
+ events.push(...page.events);
+ } while (page.events.length && events.length < page.total);
+ return events;
+ }, { events: CALENDAR_EVENTS });
- return { deathClock, cosSummary, goals, events, health };
- }, REFRESH_INTERVAL);
+ useEffect(() => {
+ if (document.visibilityState === 'hidden') return;
+ if (reconciledDays.current.deathClock !== day) refreshDeathClock();
+ if (reconciledDays.current.summary !== day) refreshSummary();
+ if (reconciledDays.current.calendar !== day) refreshCalendar();
+ }, [day, refreshDeathClock, refreshSummary, refreshCalendar]);
useEffect(() => {
const interval = setInterval(() => setTime(new Date()), 1000);
@@ -82,18 +114,14 @@ export default function Ambient() {
return () => document.removeEventListener('fullscreenchange', handleChange);
}, []);
- const cosSummary = data?.cosSummary;
const today = useMemo(() => cosSummary?.today || {}, [cosSummary]);
- const goals = data?.goals;
- const deathData = data?.deathClock;
const upcomingEvents = useMemo(() => {
- const events = Array.isArray(data?.events) ? data.events : [];
- const now = new Date();
+ const events = Array.isArray(calendarEvents) ? calendarEvents : [];
return events
- .filter(e => new Date(e.end || e.start) >= now)
+ .filter(e => new Date(e.endTime || e.end || e.startTime || e.start) >= time)
.slice(0, 6);
- }, [data?.events]);
+ }, [calendarEvents, time]);
return (
// Ambient mode is a full-screen always-on display for a dim room, so it
@@ -163,7 +191,7 @@ export default function Ambient() {
<div className="min-w-0">
<div className="text-sm text-gray-300 truncate">{event.summary || event.title}</div>
<div className="text-xs text-gray-600">
- {event.allDay ? 'All day' : `${formatTimeOfDay(event.start)} – ${formatTimeOfDay(event.end)}`}
+ {(event.isAllDay ?? event.allDay) ? 'All day' : `${formatTimeOfDay(event.startTime || event.start)} – ${formatTimeOfDay(event.endTime || event.end)}`}
</div>
</div>
</div>
@@ -224,8 +252,8 @@ export default function Ambient() {
}`}>
<span>PortOS Ambient</span>
<span className="flex items-center gap-2">
- <span className={`w-1.5 h-1.5 rounded-full ${data?.health ? 'bg-port-success' : 'bg-gray-700'}`} />
- {data?.health ? 'System Online' : 'Connecting...'}
+ <span className={`w-1.5 h-1.5 rounded-full ${socket.connected ? 'bg-port-success' : 'bg-gray-700'}`} />
+ {socket.connected ? 'System Online' : 'Connecting...'}
</span>
</div>
</div>
diff --git a/client/src/pages/Ambient.test.jsx b/client/src/pages/Ambient.test.jsx
new file mode 100644
index 0000000000..bbbcddb46b
--- /dev/null
+++ b/client/src/pages/Ambient.test.jsx
@@ -0,0 +1,131 @@
+import { act, cleanup, render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import Ambient from './Ambient';
+import * as api from '../services/api';
+import socket from '../services/socket';
+import { formatClockTime, formatDateFull } from '../utils/formatters';
+
+vi.mock('../services/api', () => ({
+ getDeathClock: vi.fn(), getCosQuickSummary: vi.fn(),
+ getCosGoalProgressSummary: vi.fn(), getCalendarEvents: vi.fn(), checkHealth: vi.fn()
+}));
+vi.mock('../services/socket', () => {
+ const handlers = new Map();
+ return { default: {
+ connected: true, emit: vi.fn(),
+ 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),
+ dispatch: (event, payload) => { for (const fn of handlers.get(event) || []) fn(payload); }
+ } };
+});
+vi.mock('../components/DeathClockCountdown', () => ({ default: ({ deathDate }) => <div>{deathDate}</div> }));
+const reads = () => [api.getDeathClock, api.getCosQuickSummary, api.getCosGoalProgressSummary, api.getCalendarEvents].map(fn => fn.mock.calls.length);
+const flush = async (fn = () => {}) => act(async () => { fn(); });
+const mount = () => flush(() => render(<MemoryRouter><Ambient /></MemoryRouter>));
+const event = (name) => flush(() => socket.dispatch(name));
+const visibility = (state) => flush(() => {
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: state });
+ document.dispatchEvent(new Event('visibilitychange'));
+});
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(2026, 0, 15, 12, 0, 0));
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
+ vi.clearAllMocks();
+ socket.connected = true;
+ api.getDeathClock.mockResolvedValue({ deathDate: '2080-01-01', percentComplete: 25 });
+ api.getCosQuickSummary.mockResolvedValue({ today: { running: 1 }, status: { running: true } });
+ api.getCosGoalProgressSummary.mockResolvedValue({ goals: [{ name: 'Example goal', successRate: 50 }] });
+ api.getCalendarEvents.mockResolvedValue({ events: [{ id: 'example', title: 'Example meeting',
+ startTime: new Date(2026, 0, 15, 12).toISOString(), endTime: new Date(2026, 0, 15, 12, 1).toISOString() }], total: 1 });
+});
+afterEach(() => { cleanup(); vi.useRealTimers(); });
+
+describe('Ambient resource updates', () => {
+ it('renders each affected resource on its event without rereading unrelated resources', async () => {
+ await mount();
+ expect(reads()).toEqual([1, 1, 1, 1]);
+ expect(screen.getByText('Example meeting')).toBeTruthy();
+ api.getCalendarEvents.mockResolvedValue({ events: [{ id: 'new', title: 'Changed meeting', isAllDay: true, startTime: new Date(2026, 0, 15, 13).toISOString() }], total: 1 });
+ await event('calendar:sync:completed');
+ expect(screen.getByText('Changed meeting')).toBeTruthy();
+ expect(screen.getByText('All day')).toBeTruthy();
+ expect(reads()).toEqual([1, 1, 1, 2]);
+ api.getDeathClock.mockResolvedValue({ deathDate: '2085-01-01', percentComplete: 20 });
+ await event('meatspace:death-clock:changed');
+ expect(screen.getByText('2085-01-01')).toBeTruthy();
+ expect(reads()).toEqual([2, 1, 1, 2]);
+ api.getCosQuickSummary.mockResolvedValue({ today: { running: 7 } });
+ await event('cos:agent:spawned');
+ expect(screen.getByText('7')).toBeTruthy();
+ expect(reads()).toEqual([2, 2, 1, 2]);
+ api.getCosGoalProgressSummary.mockResolvedValue({ goals: [{ name: 'Updated goal', successRate: 80 }] });
+ await event('cos:goals:changed');
+ expect(screen.getByText('Updated goal')).toBeTruthy();
+ expect(reads()).toEqual([2, 2, 2, 2]);
+ expect(socket.emit.mock.calls.filter(([name]) => name === 'cos:subscribe')).toHaveLength(1);
+ });
+
+ it('keeps the clock and upcoming events current past 30 seconds without polling', async () => {
+ await mount();
+ await flush(() => vi.advanceTimersByTime(61000));
+ expect(reads()).toEqual([1, 1, 1, 1]);
+ expect(api.checkHealth).not.toHaveBeenCalled();
+ expect(screen.queryByText('Example meeting')).toBeNull();
+ expect(screen.getByText(formatClockTime(new Date()))).toBeTruthy();
+ });
+
+ it('reconciles exactly once on reconnect and tab re-show, and uses socket connectivity', async () => {
+ await mount();
+ socket.connected = false;
+ await event('disconnect');
+ expect(screen.getByText('Connecting...')).toBeTruthy();
+ expect(reads()).toEqual([1, 1, 1, 1]);
+ socket.connected = true;
+ await event('connect');
+ expect(reads()).toEqual([2, 2, 2, 2]);
+ expect(screen.getByText('System Online')).toBeTruthy();
+ await visibility('hidden');
+ await event('calendar:sync:completed');
+ expect(reads()).toEqual([2, 2, 2, 2]);
+ await visibility('visible');
+ expect(reads()).toEqual([3, 3, 3, 3]);
+ await visibility('visible');
+ expect(reads()).toEqual([3, 3, 3, 3]);
+ });
+
+ it('reconciles date-bound resources at midnight with the new local date range', async () => {
+ vi.setSystemTime(new Date(2026, 0, 15, 23, 59, 59));
+ await mount();
+ await flush(() => vi.advanceTimersByTime(2000));
+ expect(reads()).toEqual([2, 2, 1, 2]);
+ expect(api.getCalendarEvents).toHaveBeenLastCalledWith({
+ startDate: new Date(2026, 0, 16).toISOString(),
+ endDate: new Date(2026, 0, 17).toISOString(), limit: 200, offset: 0
+ });
+ expect(screen.getByText(formatDateFull(new Date()))).toBeTruthy();
+ });
+
+ it('reconciles once when a suspended tab returns on a new day before its next clock tick', async () => {
+ await mount();
+ await visibility('hidden');
+ vi.setSystemTime(new Date(2026, 0, 16, 8));
+ await visibility('visible');
+ await flush(() => vi.advanceTimersByTime(1000));
+ expect(reads()).toEqual([2, 2, 2, 2]);
+ expect(screen.getByText(formatDateFull(new Date()))).toBeTruthy();
+ });
+
+ it('reads all calendar pages and preserves the last snapshot when an event read fails', async () => {
+ api.getCalendarEvents.mockResolvedValueOnce({ events: [{ id: 'past', title: 'Past', endTime: new Date(2026, 0, 15, 11).toISOString() }], total: 2 })
+ .mockResolvedValueOnce({ events: [{ id: 'future', title: 'Later meeting', startTime: new Date(2026, 0, 15, 13).toISOString() }], total: 2 });
+ await mount();
+ expect(screen.getByText('Later meeting')).toBeTruthy();
+ expect(api.getCalendarEvents.mock.calls[1][0].offset).toBe(1);
+ api.getCalendarEvents.mockRejectedValueOnce(new Error('offline'));
+ await event('calendar:sync:completed');
+ expect(screen.getByText('Later meeting')).toBeTruthy();
+ });
+});
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index e06a9239ad..07f9a024ee 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -49,6 +49,16 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
summary: 'Invalidate Digital Twin status/settings after persistence or completed peer sync; contains no personal data.',
payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
},
+ 'meatspace:death-clock:changed': {
+ direction: 'server-to-client',
+ summary: 'Invalidate death-clock projection after local or federated inputs change.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'cos:goals:changed': {
+ direction: 'server-to-client',
+ summary: 'Invalidate operational goal progress after learning statistics persist.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
'portos:auto-update:changed': {
direction: 'server-to-client',
summary: 'Invalidate updater status after runtime, configuration or external git ref changes.',
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index 068a9343ae..dd191f6659 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -6,6 +6,7 @@
* No data is ever lost — unique records from both sides are kept (union semantics).
*/
+import { meatspaceEvents } from './meatspaceEvents.js';
import { stat, readdir } from 'fs/promises';
import { join } from 'path';
import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';
@@ -562,6 +563,7 @@ async function applyMeatspaceRemote(remoteData) {
const { merged, changed } = mergeObjectLWW(local, remoteFile, 'updatedAt');
if (changed) {
await atomicWrite(filePath, merged);
+ if (filename === 'config.json') meatspaceEvents.emit('death-clock:changed', {});
totalApplied++;
}
} else {
diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.js
index fee3044301..8b51123c22 100644
--- a/server/services/digital-twin-sync.js
+++ b/server/services/digital-twin-sync.js
@@ -55,6 +55,7 @@
* account id (#3532) — see mergeSocialAccounts.
*/
+import { meatspaceEvents } from './meatspaceEvents.js';
import { join, basename } from 'path';
import { readdir, readFile, unlink } from 'fs/promises';
import { existsSync } from 'fs';
@@ -797,6 +798,7 @@ async function applyMerge(path, remote, mergeFn, { dir } = {}) {
if (!changed) return 0;
if (dir) await ensureDir(dir);
await atomicWrite(path, merged);
+ if (path === LONGEVITY_FILE) meatspaceEvents.emit('death-clock:changed', {});
return 1;
}
diff --git a/server/services/identity/store.js b/server/services/identity/store.js
index 306d3f0322..7d0a08b318 100644
--- a/server/services/identity/store.js
+++ b/server/services/identity/store.js
@@ -1,3 +1,4 @@
+import { meatspaceEvents } from '../meatspaceEvents.js';
import { join } from 'path';
import { atomicWrite, PATHS, ensureDir, readJSONFileStrict } from '../../lib/fileUtils.js';
import { isMortalLoomEnabled, mlArrayIfEnabled, mlReplace } from '../mortalLoomStore.js';
@@ -147,6 +148,7 @@ export async function loadJSON(filePath, defaultVal, { strict = false } = {}) {
export async function saveJSON(filePath, data) {
await ensureIdentityDir();
await atomicWrite(filePath, data);
+ if (filePath === LONGEVITY_FILE) meatspaceEvents.emit('death-clock:changed', {});
// Mirror goals array into MortalLoom.json so iOS/macOS app sees the change.
if (filePath === GOALS_FILE && (await isMortalLoomEnabled()) && Array.isArray(data.goals)) {
await mlReplace('goals', data.goals);
diff --git a/server/services/identity/store.test.js b/server/services/identity/store.test.js
index ac609599bb..c404688509 100644
--- a/server/services/identity/store.test.js
+++ b/server/services/identity/store.test.js
@@ -1,3 +1,4 @@
+import { meatspaceEvents } from '../meatspaceEvents.js';
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
@@ -31,7 +32,7 @@ vi.mock('../taste-questionnaire.js', () => ({
getTasteProfile: vi.fn(async () => ({ completedCount: 0, totalSections: 0, lastSessionAt: null })),
}));
-const { loadJSON, normalizeGoal, GOALS_FILE, LONGEVITY_FILE, DEFAULT_GOALS, DEFAULT_LONGEVITY, PORTOS_GOAL_DEFAULTS } = await import('./store.js');
+const { saveJSON, loadJSON, normalizeGoal, GOALS_FILE, LONGEVITY_FILE, DEFAULT_GOALS, DEFAULT_LONGEVITY, PORTOS_GOAL_DEFAULTS } = await import('./store.js');
const { getIdentityStatus } = await import('./status.js');
afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
@@ -43,6 +44,17 @@ beforeEach(() => {
vi.spyOn(console, 'warn').mockImplementation(() => {});
});
+it('invalidates the death clock after saving longevity but not unrelated identity records', async () => {
+ const changed = vi.fn();
+ meatspaceEvents.on('death-clock:changed', changed);
+ await saveJSON(LONGEVITY_FILE, { lifeExpectancy: { adjusted: 85 } });
+ expect(changed).toHaveBeenCalledExactlyOnceWith({});
+ expect(await loadJSON(LONGEVITY_FILE, null)).toEqual({ lifeExpectancy: { adjusted: 85 } });
+ await saveJSON(GOALS_FILE, { goals: [] });
+ expect(changed).toHaveBeenCalledTimes(1);
+ meatspaceEvents.off('death-clock:changed', changed);
+});
+
describe('loadJSON — swallowing (default) behavior is unchanged (#2726)', () => {
it('returns the default when the file was never written', async () => {
expect(await loadJSON(GOALS_FILE, DEFAULT_GOALS)).toEqual(DEFAULT_GOALS);
diff --git a/server/services/meatspace.configWrites.test.js b/server/services/meatspace.configWrites.test.js
index af9c5afd84..2522adc47d 100644
--- a/server/services/meatspace.configWrites.test.js
+++ b/server/services/meatspace.configWrites.test.js
@@ -28,6 +28,7 @@ vi.mock('./mortalLoomStore.js', () => ({
vi.mock('fs/promises', () => ({ readFile: vi.fn(async () => '{}') }));
const meatspace = await import('./meatspace.js');
+const { meatspaceEvents } = await import('./meatspaceEvents.js');
const initialConfig = () => ({
birthDate: null,
@@ -51,6 +52,18 @@ describe('meatspace config write serialization (#4913)', () => {
store.goals = null;
});
+ it('invalidates the death clock only after its changed inputs persist', async () => {
+ const snapshots = [];
+ const listener = payload => snapshots.push({ payload, config: structuredClone(store.config) });
+ meatspaceEvents.on('death-clock:changed', listener);
+ await meatspace.updateBirthDate('1980-01-01', { syncGoals: false });
+ await meatspace.updateLifestyle({ sleepHoursPerNight: 8 });
+ meatspaceEvents.off('death-clock:changed', listener);
+ expect(snapshots).toHaveLength(2);
+ expect(snapshots[0]).toMatchObject({ payload: {}, config: { birthDate: '1980-01-01' } });
+ expect(snapshots[1].config.lifestyle.sleepHoursPerNight).toBe(8);
+ });
+
it('retains simultaneous config and lifestyle patches', async () => {
await Promise.all([
meatspace.updateConfig({ sex: 'female', sexSource: 'manual' }),
diff --git a/server/services/meatspace.js b/server/services/meatspace.js
index 029d581e16..fa9e0fb131 100644
--- a/server/services/meatspace.js
+++ b/server/services/meatspace.js
@@ -5,6 +5,7 @@
* and LEV 2045 tracker. Reads genome/longevity data from Digital Twin.
*/
+import { meatspaceEvents } from './meatspaceEvents.js';
import { readFile } from 'fs/promises';
import { join } from 'path';
import { atomicWrite, PATHS, ensureDir, readJSONFile, readJSONFileStrict } from '../lib/fileUtils.js';
@@ -72,6 +73,7 @@ async function loadConfig() {
async function saveConfig(config) {
await ensureMeatspaceDir();
await atomicWrite(CONFIG_FILE, config);
+ meatspaceEvents.emit('death-clock:changed', {});
}
// === Sex Detection ===
diff --git a/server/services/meatspaceEvents.js b/server/services/meatspaceEvents.js
new file mode 100644
index 0000000000..cd979a4c70
--- /dev/null
+++ b/server/services/meatspaceEvents.js
@@ -0,0 +1,4 @@
+import { EventEmitter } from 'node:events';
+
+// Invalidation only: personal inputs remain behind the normal API boundary.
+export const meatspaceEvents = new EventEmitter();
diff --git a/server/services/socket.js b/server/services/socket.js
index c23232c3ab..61a61a7d4a 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -1,3 +1,4 @@
+import { meatspaceEvents } from './meatspaceEvents.js';
import { recordEvents } from './sharing/recordEvents.js';
import { fableLoomRunEvents } from './fableLoom/runEvents.js';
import { cosEvents } from './cosEvents.js';
@@ -226,6 +227,7 @@ function registerAuthRevocationHandler(io) {
}
function setupEventForwarding() {
+ meatspaceEvents.on('death-clock:changed', data => ioInstance?.emit('meatspace:death-clock:changed', data));
setupCosEventForwarding();
setupErrorEventForwarding();
setupAppsEventForwarding();
@@ -414,6 +416,7 @@ function broadcastToErrors(event, data) { broadcastToSet(errorSubscribers, event
// Set up CoS event forwarding
function setupCosEventForwarding() {
// Status events
+ cosEvents.on('goals:changed', data => broadcastToCos('cos:goals:changed', data));
cosEvents.on('status', (data) => broadcastToCos('cos:status', data));
for (const event of ['config:changed', 'status:paused', 'status:resumed']) {
cosEvents.on(event, data => broadcastToCos(`cos:${event}`, data));
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index 92fb4f3416..2326b2eeb0 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -1,3 +1,4 @@
+import { meatspaceEvents } from './meatspaceEvents.js';
import { emitRecordUpdated, emitRecordDeleted, emitRecordInvalidated } from './sharing/recordEvents.js';
import { fableLoomRunEvents } from './fableLoom/runEvents.js';
import { trainingEvents } from './loraTraining/events.js';
@@ -147,6 +148,13 @@ describe('socket.js — initSocket', () => {
}
createdSockets.length = 0;
authEvents.removeAllListeners('sessions:revoked-all');
+ meatspaceEvents.removeAllListeners();
+ });
+
+ it('forwards death-clock invalidations without personal data', () => {
+ io.emitted.length = 0;
+ meatspaceEvents.emit('death-clock:changed', {});
+ expect(io.emitted).toEqual([['meatspace:death-clock:changed', {}]]);
});
it('forwards Digital Twin changes without leaking source records', () => {
diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.js
index 8b45faf9eb..c7686d2e74 100644
--- a/server/services/taskLearning/store.js
+++ b/server/services/taskLearning/store.js
@@ -457,6 +457,7 @@ export async function saveLearningData(data) {
await atomicWrite(LEARNING_FILE, data);
_learningCache = structuredClone(data);
_learningCacheTime = Date.now();
+ cosEvents.emit('goals:changed', {});
}
/**
diff --git a/server/services/taskLearning/store.test.js b/server/services/taskLearning/store.test.js
index b93147881b..06450be154 100644
--- a/server/services/taskLearning/store.test.js
+++ b/server/services/taskLearning/store.test.js
@@ -1,3 +1,4 @@
+import { cosEvents } from '../cosEvents.js';
import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'fs';
import { tmpdir } from 'os';
@@ -694,7 +695,10 @@ describe('taskLearning store strict reads (#4115)', () => {
});
it('round-trips a readable file (the strict flag does not break the happy path)', async () => {
+ const changed = vi.fn();
+ cosEvents.once('goals:changed', changed);
await saveLearningData({ byTaskType: { docs: { completed: 3 } } });
+ expect(changed).toHaveBeenCalledWith({});
clearLearningCache();
expect((await loadLearningData()).byTaskType.docs.completed).toBe(3);