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

perf: update dashboard widgets from server events instead of polling (#8531)

[._.]/ Adam Eivy048cf36d4a6e
diff --git a/client/src/components/BackupWidget.jsx b/client/src/components/BackupWidget.jsx
index 5837f29f32..7e587beb4e 100644
--- a/client/src/components/BackupWidget.jsx
+++ b/client/src/components/BackupWidget.jsx
@@ -15,11 +15,13 @@ import BrailleSpinner from './BrailleSpinner';
import toast from './ui/Toast';
import * as api from '../services/api';
import { useBackupRun } from '../hooks/useBackupRun';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useSocketResource } from '../hooks/useSocketResource';
import { useTimeTick } from '../hooks/useTimeTick';
import { equalByKeys, equalListByKeys } from '../lib/compareHelpers';
import { timeAgo, timeUntil } from '../utils/formatters';
+const RESOURCE_EVENTS = ['backup:changed'];
+
// ---------------------------------------------------------------------------
// Pure helpers
// ---------------------------------------------------------------------------
@@ -243,18 +245,18 @@ function RestorePanel({ snapshot, onClose, restoring, onRestoreStateChange }) {
// ---------------------------------------------------------------------------
function SnapshotList({ restoringSnapshotId, onRestoreStateChange }) {
- // Let errors throw — `useAutoRefetch` preserves the last-good data on
+ // Let errors throw — `useSocketResource` preserves the last-good data on
// transient failures. A `.catch(() => null)` here would wipe the snapshot
// list on every blip per the hook's documented gotcha.
- const { data: snapshots, loading } = useAutoRefetch(
+ const { data: snapshots, loading } = useSocketResource(
() => api.getBackupSnapshots({ silent: true }),
- 120000,
{
+ events: RESOURCE_EVENTS,
// Snapshots only change when a new backup lands or the rotation prunes
// the oldest — walk every rendered tuple (id + fileCount) so a stale
// server-side fileCount recount or a middle-row mutation can't hide
// behind the head/tail id check.
- compare: (prev, next) => equalListByKeys(prev, next, [
+ compare: (prev, next) => prev != null && equalListByKeys(prev, next, [
'selectionKey', 'id', 'source', 'fileCount', 'incomplete', 'failed',
]),
},
@@ -348,27 +350,36 @@ function SnapshotList({ restoringSnapshotId, onRestoreStateChange }) {
// ---------------------------------------------------------------------------
const BackupWidget = memo(function BackupWidget() {
- // Let errors throw — `useAutoRefetch` preserves the last-good status on
+ // Let errors throw — `useSocketResource` preserves the last-good status on
// transient failures so a blip doesn't drop the widget to its loading state.
- const { data: status } = useAutoRefetch(
+ const { data: status, updateData: updateStatus } = useSocketResource(
() => api.getBackupStatus({ silent: true }),
- 60000,
{
+ events: RESOURCE_EVENTS,
// Backup state only flips when a new run starts/finishes — comparing the
// monotonic timestamps + status + error + destPath captures every
- // visible change at the widget's resolution. Avoids per-poll re-renders
+ // visible change at the widget's resolution. Avoids redundant re-renders
// that would re-compute relative-time labels for no visual benefit.
- compare: (prev, next) => equalByKeys(prev, next, [
+ compare: (prev, next) => prev != null && equalByKeys(prev, next, [
'status', 'lastRun', 'nextRun', 'error', 'filesChanged', 'destPath',
]),
},
);
- const [handleBackupNow, triggering] = useBackupRun();
+ const [handleBackupNow, triggering] = useBackupRun(result => {
+ updateStatus(previous => ({
+ ...previous,
+ status: result.status,
+ lastRun: result.lastRun,
+ filesChanged: result.filesChanged,
+ pgBackup: result.pgBackup,
+ error: result.pgBackup?.status === 'failed' ? `DB dump ${result.pgBackup.reason}` : null,
+ }));
+ });
const [snapshotsOpen, setSnapshotsOpen] = useState(false);
const [restoringSnapshotId, setRestoringSnapshotId] = useState(null);
// Tick every minute so the dedup-skipped widget still recomputes
// `relativeTime(lastRun/nextRun)` labels and the `computeHealth` 25h/49h
- // thresholds when wall-clock time crosses a boundary even though the poll
+ // thresholds when wall-clock time crosses a boundary even though the resource
// payload is unchanged.
useTimeTick(60000);
diff --git a/client/src/components/CosDashboardWidget.jsx b/client/src/components/CosDashboardWidget.jsx
index 789a05beae..fedfb8165d 100644
--- a/client/src/components/CosDashboardWidget.jsx
+++ b/client/src/components/CosDashboardWidget.jsx
@@ -13,17 +13,19 @@ import {
Activity
} from 'lucide-react';
import * as api from '../services/api';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useSocketResource } from '../hooks/useSocketResource';
import { useTimeTick } from '../hooks/useTimeTick';
import { timeAgo, formatWeekdayDate, formatCount } from '../utils/formatters';
+const RESOURCE_EVENTS = ['cos:tasks:changed', 'cos:tasks:user:changed', 'cos:tasks:cos:changed', 'cos:agent:spawned', 'cos:agent:completed', 'cos:agents:changed', 'cos:status', 'cos:status:paused', 'cos:status:resumed', 'cos:learning:changed'];
+
/**
* CosDashboardWidget - Compact CoS status widget for the main Dashboard
* Shows today's progress, learning health, CoS running state, and recent tasks
*/
const CosDashboardWidget = memo(function CosDashboardWidget() {
- const { data: dashData, loading } = useAutoRefetch(async () => {
- // Let errors throw — `useAutoRefetch` preserves the last-good batch on
+ const { data: dashData, loading } = useSocketResource(async () => {
+ // Let errors throw — `useSocketResource` preserves the last-good batch on
// transient failures. Without this, a per-endpoint `.catch(() => null)`
// could mix fresh and stale sections (e.g. summary=null but
// learningSummary holding its prior value) and the widget would flicker
@@ -36,12 +38,13 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {
api.getCosActivityCalendar(8, silent)
]);
return { summary, learningSummary, recentTasks, activityCalendar };
- }, 30000, {
+ }, {
+ namespace: 'cos', events: RESOURCE_EVENTS,
// Re-render only when one of the aggregated counts actually moves —
// running agents, completed/failed counts, queue depth, learning
// success rate, every visible recent-task field, every per-day heatmap
- // cell, and the heatmap summary. The poll fires every 30s; without this
- // guard each tick re-renders the activity heatmap + recent tasks list
+ // cell, and the heatmap summary. Without this
+ // guard each invalidation re-renders the activity heatmap + recent tasks list
// even when nothing changed.
//
// Recent-tasks comparison walks every rendered field per row (id,
@@ -49,13 +52,14 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {
// time label is rendered client-side from `task.completedAt` via timeAgo
// and refreshed by the useTimeTick(60000) below, so the server's
// `task.completedRelative` string is intentionally ignored — it ships in
- // the payload but would freeze across deduped polls if we used it.
+ // the payload but would freeze across unchanged snapshots if we used it.
//
// Heatmap comparison walks every cell's (date, tasks, isToday) tuple plus
// summary totals — the per-day distribution can shift without changing
// top-level totals (e.g. a run moving from one day to another in
// late-arriving telemetry).
compare: (prev, next) => {
+ if (!prev) return false;
const prevTasks = prev.recentTasks?.tasks;
const nextTasks = next.recentTasks?.tasks;
const prevLen = prevTasks?.length ?? 0;
@@ -127,7 +131,7 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {
const { summary, learningSummary, recentTasks, activityCalendar } = dashData ?? {};
const [tasksExpanded, setTasksExpanded] = useState(false);
// Tick every minute so the client-side `timeAgo(task.completedAt)` labels
- // recompute against the latest wall-clock time across deduped polls.
+ // recompute against the latest wall-clock time across unchanged snapshots.
useTimeTick(60000);
// Don't render while loading
@@ -308,7 +312,7 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {
label without help from the server. The server's
`completedRelative` string ships in the payload but
we intentionally ignore it — it goes stale across
- deduped polls. */}
+ unchanged snapshots. */}
<span>{timeAgo(task.completedAt)}</span>
</div>
</div>
diff --git a/client/src/components/DecisionLogWidget.jsx b/client/src/components/DecisionLogWidget.jsx
index 20328152f9..0e9b2ad337 100644
--- a/client/src/components/DecisionLogWidget.jsx
+++ b/client/src/components/DecisionLogWidget.jsx
@@ -15,12 +15,14 @@ import {
Moon
} from 'lucide-react';
import * as api from '../services/api';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useSocketResource } from '../hooks/useSocketResource';
import { useTimeTick } from '../hooks/useTimeTick';
import { timeAgo } from '../utils/formatters';
import { equalByKeys, equalListByKeys } from '../lib/compareHelpers';
import ProvenanceChip from './ui/ProvenanceChip';
+const RESOURCE_EVENTS = ['cos:decisions:changed'];
+
// Every row here is a record of an autonomous choice the Chief of Staff made —
// what it skipped, switched, or deferred and why. That's read straight off the
// decision ledger it wrote as it ran, so the provenance is data-backed: a log
@@ -40,13 +42,13 @@ const DECISION_PROVENANCE = {
* exactly why the CoS took (or didn't take) action.
*/
const DecisionLogWidget = memo(function DecisionLogWidget() {
- // Let errors throw — `useAutoRefetch` preserves the last-good summary on
+ // Let errors throw — `useSocketResource` preserves the last-good summary on
// transient failures instead of dropping the widget back to its loading
// state on every blip.
- const { data: summary, loading } = useAutoRefetch(
+ const { data: summary, loading } = useSocketResource(
() => api.getCosDecisionSummary({ silent: true }),
- 60000,
{
+ namespace: 'cos', events: RESOURCE_EVENTS,
// Decision stream is append-only; same 24h totals + same per-decision
// tuple of every rendered field means nothing visible advanced this
// minute. Comparator walks: id (key + dedup), type (icon + label),
@@ -58,7 +60,7 @@ const DecisionLogWidget = memo(function DecisionLogWidget() {
// below — including the timestamp fields in this comparator would
// pointlessly break dedup on every backend mtime nudge. Keep this tuple
// in sync with the JSX above.
- compare: (prev, next) =>
+ compare: (prev, next) => prev != null &&
equalByKeys(prev.last24Hours, next.last24Hours, [
'total', 'skipped', 'switched', 'capacityFull',
'cooldownActive', 'selected', 'adjusted',
@@ -75,7 +77,7 @@ const DecisionLogWidget = memo(function DecisionLogWidget() {
);
const [expanded, setExpanded] = useState(false);
// Tick every minute so the `timeAgo(...)` relative-time labels on each
- // decision row roll over even when the poll payload is unchanged by the
+ // decision row roll over even when the resource snapshot is unchanged by the
// comparator.
useTimeTick(60000);
diff --git a/client/src/components/GoalProgressWidget.jsx b/client/src/components/GoalProgressWidget.jsx
index 5b0d52817c..eee2fdabb3 100644
--- a/client/src/components/GoalProgressWidget.jsx
+++ b/client/src/components/GoalProgressWidget.jsx
@@ -2,11 +2,13 @@ import { memo, useMemo } from 'react';
import { Link } from 'react-router';
import { ChevronRight, AlertTriangle, Target } from 'lucide-react';
import * as api from '../services/api';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useSocketResource } from '../hooks/useSocketResource';
import { useTimeTick } from '../hooks/useTimeTick';
import { equalListByKeys } from '../lib/compareHelpers';
import { CATEGORY_CONFIG, GOAL_TYPE_CONFIG } from './goals/GoalDetailPanel';
+const RESOURCE_EVENTS = ['goals:changed'];
+
const HORIZON_LABELS = {
'1-year': '1Y', '3-year': '3Y', '5-year': '5Y',
'10-year': '10Y', '20-year': '20Y', 'lifetime': 'Life'
@@ -26,13 +28,13 @@ const getDaysSince = (dateStr) => {
};
const GoalProgressWidget = memo(function GoalProgressWidget() {
- // Let errors throw — `useAutoRefetch` preserves the last-good goal set on
+ // Let errors throw — `useSocketResource` preserves the last-good goal set on
// transient failures rather than wiping the widget.
- const { data: goalsData, loading } = useAutoRefetch(
+ const { data: goalsData, loading } = useSocketResource(
() => api.getGoals({ silent: true }),
- 300000,
{
- // Goals rarely change at 5-minute cadence. Skip the re-render (and the
+ events: RESOURCE_EVENTS,
+ // Goal invalidations can leave the rendered values unchanged. Skip the re-render (and the
// useMemo recompute that re-derives stalled goals + avg progress) when
// the goal set and every rendered/derived per-goal field are unchanged.
// Covers: title, category, horizon, goalType (rendered as labels/icons),
@@ -41,7 +43,7 @@ const GoalProgressWidget = memo(function GoalProgressWidget() {
// drive `daysSinceUpdate` / `isStalled` (a backfilled or corrected
// progressHistory entry mutates the latest timestamp without changing
// array length).
- compare: (prev, next) => equalListByKeys(prev.goals, next.goals, [
+ compare: (prev, next) => prev != null && equalListByKeys(prev.goals, next.goals, [
'id', 'title', 'category', 'horizon', 'goalType', 'progress',
'status', 'parentId', 'urgency', 'createdAt', getLastProgressDate,
]),
@@ -75,7 +77,7 @@ const GoalProgressWidget = memo(function GoalProgressWidget() {
};
// `tick` is in the dep array on purpose — when the wall-clock hour rolls
// over the derivation re-runs so a goal can cross the stall threshold
- // without needing a new poll payload.
+ // without needing a new resource snapshot.
}, [goalsData, tick]);
if (loading || !goals.length) return null;
diff --git a/client/src/components/UpcomingTasksWidget.jsx b/client/src/components/UpcomingTasksWidget.jsx
index f4c6de91ad..2a06c7791d 100644
--- a/client/src/components/UpcomingTasksWidget.jsx
+++ b/client/src/components/UpcomingTasksWidget.jsx
@@ -10,16 +10,18 @@ import {
Sparkles
} from 'lucide-react';
import * as api from '../services/api';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useSocketResource } from '../hooks/useSocketResource';
+
+const RESOURCE_EVENTS = ['cos:schedule:changed', 'cos:scheduler:changed', 'cos:tasks:changed', 'cos:learning:changed', 'cos:config:changed'];
/**
* UpcomingTasksWidget - Shows a preview of upcoming scheduled tasks
* Helps users understand what the CoS will work on next
*/
const UpcomingTasksWidget = memo(function UpcomingTasksWidget() {
- const { data: upcoming, loading, error } = useAutoRefetch(
+ const { data: upcoming, loading, error } = useSocketResource(
() => api.getCosUpcomingTasks(6, { silent: true }),
- 60000
+ { namespace: 'cos', events: RESOURCE_EVENTS }
);
// Don't render during the initial load.
diff --git a/client/src/components/UpcomingTasksWidget.test.jsx b/client/src/components/UpcomingTasksWidget.test.jsx
index ab1f206314..059e9ad589 100644
--- a/client/src/components/UpcomingTasksWidget.test.jsx
+++ b/client/src/components/UpcomingTasksWidget.test.jsx
@@ -3,17 +3,17 @@ import { render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
// UpcomingTasksWidget's own logic is what response to a good/failed/absent
-// fetch should render — the polling/retry mechanics belong to useAutoRefetch
+// fetch should render — the subscription/retry mechanics belong to useSocketResource
// and are covered by its own test suite. Mocking the hook lets these tests
// pin the widget's render contract directly against each { data, loading,
// error } combination without fake timers or interval plumbing.
-const { mockUseAutoRefetch, mockGetCosUpcomingTasks } = vi.hoisted(() => ({
- mockUseAutoRefetch: vi.fn(),
+const { mockUseSocketResource, mockGetCosUpcomingTasks } = vi.hoisted(() => ({
+ mockUseSocketResource: vi.fn(),
mockGetCosUpcomingTasks: vi.fn(),
}));
-vi.mock('../hooks/useAutoRefetch', () => ({
- useAutoRefetch: (...args) => mockUseAutoRefetch(...args),
+vi.mock('../hooks/useSocketResource', () => ({
+ useSocketResource: (...args) => mockUseSocketResource(...args),
}));
vi.mock('../services/api', () => ({
@@ -43,25 +43,25 @@ beforeEach(() => {
describe('UpcomingTasksWidget', () => {
it('renders nothing during the initial load', () => {
- mockUseAutoRefetch.mockReturnValue({ data: null, loading: true, error: null });
+ mockUseSocketResource.mockReturnValue({ data: null, loading: true, error: null });
const { container } = renderWidget();
expect(container).toBeEmptyDOMElement();
});
it('renders nothing when there is genuinely no upcoming work and no error', () => {
- mockUseAutoRefetch.mockReturnValue({ data: [], loading: false, error: null });
+ mockUseSocketResource.mockReturnValue({ data: [], loading: false, error: null });
const { container } = renderWidget();
expect(container).toBeEmptyDOMElement();
});
it('shows an unavailable state instead of silently hiding when the first-ever fetch fails (#7527)', () => {
- mockUseAutoRefetch.mockReturnValue({ data: null, loading: false, error: new Error('boom') });
+ mockUseSocketResource.mockReturnValue({ data: null, loading: false, error: new Error('boom') });
renderWidget();
expect(screen.getByText('Schedule unavailable — retrying…')).toBeInTheDocument();
});
it('renders ready and scheduled tasks on a healthy load', () => {
- mockUseAutoRefetch.mockReturnValue({
+ mockUseSocketResource.mockReturnValue({
data: [
readyTask,
{
@@ -83,7 +83,7 @@ describe('UpcomingTasksWidget', () => {
});
it('keeps showing the last good schedule and flags it stale when a later fetch fails (#7527)', () => {
- mockUseAutoRefetch.mockReturnValue({
+ mockUseSocketResource.mockReturnValue({
data: [readyTask],
loading: false,
error: new Error('boom'),
diff --git a/client/src/components/dashboard/builtins/AutoFixMetricsWidget.jsx b/client/src/components/dashboard/builtins/AutoFixMetricsWidget.jsx
index ea8e8af69f..1436d3e50b 100644
--- a/client/src/components/dashboard/builtins/AutoFixMetricsWidget.jsx
+++ b/client/src/components/dashboard/builtins/AutoFixMetricsWidget.jsx
@@ -3,13 +3,15 @@ import { Link } from 'react-router';
import { Wrench, ArrowRight } from 'lucide-react';
import BrailleSpinner from '../../BrailleSpinner';
import * as api from '../../../services/api';
-import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
+import { useSocketResource } from '../../../hooks/useSocketResource';
import { formatDurationMs } from '../../../utils/formatters';
+const RESOURCE_EVENTS = ['cos:tasks:changed', 'cos:tasks:user:changed', 'cos:tasks:cos:changed'];
+
// Auto-fix telemetry (issue #2328). Self-fetches the aggregated
// GET /api/autofix/metrics (derived server-side from persisted
// metadata.diagnostics) — this data is NOT part of dashboardState, so unlike
-// the dashboardState-slice widgets this one owns its own poll. Renders the
+// the dashboardState-slice widgets this one owns its own subscription. Renders the
// overall auto-fix success rate, a daily success-rate trend sparkline, the
// fallback-tier breakdown, and median time-to-recovery.
@@ -24,8 +26,8 @@ const TIER_COLORS = {
// sentinel ("no data yet" must not read as 0%).
const pct = (rate) => (rate == null ? '—' : `${Math.round(rate * 100)}%`);
-// Stable serialization of every slice the widget renders — the poll de-dupe key.
-// Deliberately omits the server's `generatedAt` wall clock (changes every poll)
+// Stable serialization of every slice the widget renders — the resource comparison key.
+// Deliberately omits the server's `generatedAt` wall clock (changes every read)
// so identical data doesn't force a re-render, while any change to the rendered
// tiers / trend / recovery summary does.
const renderKey = (d) =>
@@ -79,17 +81,17 @@ function TrendSparkline({ trend }) {
}
function AutoFixMetricsWidget() {
- const { data, loading } = useAutoRefetch(
+ const { data, loading } = useSocketResource(
() => api.getAutoFixMetrics({ silent: true }),
- 60000,
{
+ namespace: 'cos', events: RESOURCE_EVENTS,
// Skip the re-render only when EVERY rendered slice is byte-identical.
- // `generatedAt` is the server's wall clock and changes every poll, so it
+ // `generatedAt` is the server's wall clock and changes every read, so it
// must be excluded — but the comparison otherwise serializes the full
// rendered payload (overall, per-tier rows, the trend series, the
// time-to-recovery summary) so a tier redistribution or a same-length
// trend whose values shifted still re-renders. The payload is tiny (a
- // few tiers + ≤30 trend days), so stringifying each poll is negligible.
+ // few tiers + ≤30 trend days), so stringifying each snapshot is negligible.
compare: (prev, next) => renderKey(prev) === renderKey(next),
},
);
diff --git a/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx b/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx
index 77b61050db..c546cc5c7a 100644
--- a/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx
+++ b/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx
@@ -2,11 +2,13 @@ import { useState } from 'react';
import { Link } from 'react-router';
import { ListTodo, Pin } from 'lucide-react';
import * as api from '../../../services/api';
-import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
+import { useSocketResource } from '../../../hooks/useSocketResource';
import { isThreadOverdue, threadNextLine } from '../../../lib/brainThreads.js';
import { formatCount, formatDateShort } from '../../../utils/formatters';
import ThreadSourceClosedAction from '../../brain/ThreadSourceClosedAction';
+const RESOURCE_EVENTS = ['brain:threads:changed'];
+
// The Brain bullet journal's open loops (#7664) with the next action on each,
// so what you are on the hook for is one glance away. A *thread* here is a
// tracked topic, never a message thread. Rows deep-link to `?thread=<id>`,
@@ -22,15 +24,15 @@ const WIDGET_STATUSES = 'open,waiting';
export default function OpenThreadsWidget() {
const [completed, setCompleted] = useState({});
- const { data, loading } = useAutoRefetch(
+ const { data, loading } = useSocketResource(
() => api.listThreads({ status: WIDGET_STATUSES, limit: ROWS, offset: 0 }, { silent: true }),
- 60_000,
+ { events: RESOURCE_EVENTS },
);
if (loading && !data) return null;
const fetchedRows = Array.isArray(data?.threads) ? data.threads : [];
- // Retain successful writes over a poll that started before completion.
+ // Retain successful writes over a read that started before completion.
// A genuinely newer record (e.g. reopened in Brain) becomes visible again.
const rows = fetchedRows.filter((t) => !completed[t.id] || t.updatedAt > completed[t.id]);
const total = (Number.isFinite(data?.total) ? data.total : fetchedRows.length) - (fetchedRows.length - rows.length);
diff --git a/client/src/components/dashboard/builtins/OpenThreadsWidget.test.jsx b/client/src/components/dashboard/builtins/OpenThreadsWidget.test.jsx
index ec3eb314a0..4a4ab3606c 100644
--- a/client/src/components/dashboard/builtins/OpenThreadsWidget.test.jsx
+++ b/client/src/components/dashboard/builtins/OpenThreadsWidget.test.jsx
@@ -2,11 +2,11 @@ import { describe, it, expect, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
-// The widget owns only what to show from a fetched list; the polling belongs
-// to useAutoRefetch, which has its own suite.
-const mockUseAutoRefetch = vi.fn();
-vi.mock('../../../hooks/useAutoRefetch', () => ({
- useAutoRefetch: (...args) => mockUseAutoRefetch(...args),
+// The widget owns only what to show from a fetched list; the subscription belongs
+// to useSocketResource, which has its own suite.
+const mockUseSocketResource = vi.fn();
+vi.mock('../../../hooks/useSocketResource', () => ({
+ useSocketResource: (...args) => mockUseSocketResource(...args),
}));
vi.mock('../../../services/api', () => ({ listThreads: vi.fn(), updateThread: vi.fn() }));
vi.mock('../../ui/Toast', () => ({ default: { error: vi.fn() } }));
@@ -19,21 +19,21 @@ const renderWidget = () => render(<MemoryRouter><OpenThreadsWidget /></MemoryRou
describe('OpenThreadsWidget', () => {
it('renders nothing until the first list arrives', () => {
- mockUseAutoRefetch.mockReturnValue({ data: null, loading: true });
+ mockUseSocketResource.mockReturnValue({ data: null, loading: true });
const { container } = renderWidget();
expect(container.innerHTML).toBe('');
});
it('asks the server for the first page of open + waiting threads only', () => {
- mockUseAutoRefetch.mockReturnValue({ data: null, loading: true });
+ mockUseSocketResource.mockReturnValue({ data: null, loading: true });
renderWidget();
- const fetchFn = mockUseAutoRefetch.mock.calls.at(-1)[0];
+ const fetchFn = mockUseSocketResource.mock.calls.at(-1)[0];
fetchFn();
expect(api.listThreads).toHaveBeenCalledWith({ status: 'open,waiting', limit: 6, offset: 0 }, { silent: true });
});
it('shows the next action on each row and deep-links it to its drawer', () => {
- mockUseAutoRefetch.mockReturnValue({
+ mockUseSocketResource.mockReturnValue({
loading: false,
data: {
total: 2,
@@ -51,7 +51,7 @@ describe('OpenThreadsWidget', () => {
});
it('links the overflow the page did not ship to the tab', () => {
- mockUseAutoRefetch.mockReturnValue({
+ mockUseSocketResource.mockReturnValue({
loading: false,
data: { total: 8, threads: Array.from({ length: 6 }, (_, i) => ({ id: `t${i}`, title: `Loop ${i}`, status: 'open' })) },
});
@@ -61,7 +61,7 @@ describe('OpenThreadsWidget', () => {
});
it('offers completion only for an unfinished thread with a positively closed source', () => {
- mockUseAutoRefetch.mockReturnValue({ loading: false, data: { threads: [
+ mockUseSocketResource.mockReturnValue({ loading: false, data: { threads: [
{ id: 'open', title: 'Open source', status: 'open', externalState: 'open' },
{ id: 'unknown', title: 'Unknown source', status: 'waiting', externalState: 'unknown' },
{ id: 'manual', title: 'Manual loop', status: 'open' },
@@ -77,7 +77,7 @@ describe('OpenThreadsWidget', () => {
it('removes a completed row and updates the count without fetching, tolerating stale polls and later reopening', async () => {
const thread = { id: 'closed', title: 'Closed source', status: 'waiting', externalState: 'closed', updatedAt: '2026-01-01T00:00:00.000Z' };
- mockUseAutoRefetch.mockReturnValue({ loading: false, data: { total: 8, threads: [thread] } });
+ mockUseSocketResource.mockReturnValue({ loading: false, data: { total: 8, threads: [thread] } });
let finish;
api.updateThread.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
const view = renderWidget();
@@ -92,10 +92,10 @@ describe('OpenThreadsWidget', () => {
expect(screen.getByText('7 open')).toBeTruthy();
expect(screen.queryByText(/No open loops/)).toBeNull();
expect(api.listThreads).not.toHaveBeenCalled();
- mockUseAutoRefetch.mockReturnValue({ loading: false, data: { total: 8, threads: [{ ...thread }] } });
+ mockUseSocketResource.mockReturnValue({ loading: false, data: { total: 8, threads: [{ ...thread }] } });
view.rerender(<MemoryRouter><OpenThreadsWidget /></MemoryRouter>);
expect(screen.queryByText('Closed source')).toBeNull();
- mockUseAutoRefetch.mockReturnValue({ loading: false, data: { total: 8, threads: [{ ...thread, updatedAt: '2026-01-03T00:00:00.000Z' }] } });
+ mockUseSocketResource.mockReturnValue({ loading: false, data: { total: 8, threads: [{ ...thread, updatedAt: '2026-01-03T00:00:00.000Z' }] } });
view.rerender(<MemoryRouter><OpenThreadsWidget /></MemoryRouter>);
expect(screen.getByText('Closed source')).toBeTruthy();
expect(screen.getByText('8 open')).toBeTruthy();
@@ -103,7 +103,7 @@ describe('OpenThreadsWidget', () => {
it('keeps the row after a failed completion, reports the error once and permits retry', async () => {
const thread = { id: 'closed', title: 'Closed source', status: 'open', externalState: 'closed' };
- mockUseAutoRefetch.mockReturnValue({ loading: false, data: { total: 1, threads: [thread] } });
+ mockUseSocketResource.mockReturnValue({ loading: false, data: { total: 1, threads: [thread] } });
api.updateThread.mockRejectedValueOnce(new Error('Connection lost')).mockResolvedValueOnce({ ...thread, status: 'done', updatedAt: '2026-01-02T00:00:00.000Z' });
renderWidget();
const button = screen.getByRole('button', { name: 'Mark "Closed source" done' });
@@ -118,7 +118,7 @@ describe('OpenThreadsWidget', () => {
});
it('offers to track one when the list is empty', () => {
- mockUseAutoRefetch.mockReturnValue({ loading: false, data: { total: 0, threads: [] } });
+ mockUseSocketResource.mockReturnValue({ loading: false, data: { total: 0, threads: [] } });
renderWidget();
expect(screen.getByText('Track one').closest('a')).toHaveAttribute('href', '/brain/threads');
});
diff --git a/client/src/components/dashboardWidgets.realtime.test.jsx b/client/src/components/dashboardWidgets.realtime.test.jsx
new file mode 100644
index 0000000000..4dcef8ccf1
--- /dev/null
+++ b/client/src/components/dashboardWidgets.realtime.test.jsx
@@ -0,0 +1,107 @@
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
+
+const { socket, api } = vi.hoisted(() => {
+ const handlers = new Map();
+ return {
+ socket: {
+ 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: vi.fn(),
+ receive: (event, data = {}) => { for (const fn of handlers.get(event) || []) fn(data); },
+ },
+ api: Object.fromEntries(['getGoals', 'getCosUpcomingTasks', 'getBackupStatus', 'getBackupSnapshots', 'getCosQuickSummary', 'getCosLearningSummary', 'getCosRecentTasks', 'getCosActivityCalendar', 'getCosDecisionSummary', 'listThreads', 'getAutoFixMetrics', 'triggerBackup'].map(name => [name, vi.fn()])),
+ };
+});
+vi.mock('../services/socket', () => ({ default: socket }));
+vi.mock('../services/api', () => api);
+vi.mock('./ui/Toast', () => ({ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));
+import GoalProgressWidget from './GoalProgressWidget';
+import UpcomingTasksWidget from './UpcomingTasksWidget';
+import BackupWidget from './BackupWidget';
+import CosDashboardWidget from './CosDashboardWidget';
+import DecisionLogWidget from './DecisionLogWidget';
+import OpenThreadsWidget from './dashboard/builtins/OpenThreadsWidget';
+import AutoFixMetricsWidget from './dashboard/builtins/AutoFixMetricsWidget';
+
+const flush = () => act(async () => {});
+const visible = state => {
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: state });
+ document.dispatchEvent(new Event('visibilitychange'));
+};
+const cases = [
+ { name: 'goals', Component: GoalProgressWidget, read: 'getGoals', event: 'goals:changed',
+ data: title => ({ goals: [{ id: 'example', title, status: 'active', progress: 25 }] }) },
+ { name: 'upcoming tasks', Component: UpcomingTasksWidget, read: 'getCosUpcomingTasks', event: 'cos:schedule:changed',
+ data: description => [{ taskType: 'example', description, status: 'ready' }] },
+ { name: 'backup status', Component: BackupWidget, read: 'getBackupStatus', event: 'backup:changed',
+ data: error => ({ status: 'error', error, lastRun: new Date().toISOString() }) },
+ { name: 'CoS summary', Component: CosDashboardWidget, read: 'getCosRecentTasks', event: 'cos:agent:completed',
+ data: description => ({ tasks: [{ id: 'example', description, taskType: 'example', success: true, completedAt: new Date().toISOString() }], summary: { total: 1, succeeded: 1 } }),
+ prepare: () => { fireEvent.click(screen.getByText('Recent Tasks')); } },
+ { name: 'decision log', Component: DecisionLogWidget, read: 'getCosDecisionSummary', event: 'cos:decisions:changed',
+ data: reason => ({ hasImpactfulDecisions: true, last24Hours: { total: 1, skipped: 1 }, impactfulDecisions: [{ id: 'example', type: 'task_skipped', reason, context: {}, timestamp: new Date().toISOString() }], transparencyScore: 100 }),
+ prepare: () => { fireEvent.click(screen.getByText('Recent Decisions')); } },
+ { name: 'open threads', Component: OpenThreadsWidget, read: 'listThreads', event: 'brain:threads:changed',
+ data: title => ({ threads: [{ id: 'example', title, status: 'open' }], total: 1 }) },
+ { name: 'auto-fix metrics', Component: AutoFixMetricsWidget, read: 'getAutoFixMetrics', event: 'cos:tasks:changed',
+ data: label => ({ total: 1, overall: { resolved: 1, successRate: 1 }, byTier: [{ tier: 1, label, strategy: label, total: 1, resolved: 1, successRate: 1 }], trend: [] }) },
+];
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ visible('visible');
+ api.getCosQuickSummary.mockResolvedValue({ today: { completed: 1 }, queue: {}, status: {} });
+ api.getCosLearningSummary.mockResolvedValue({});
+ api.getCosActivityCalendar.mockResolvedValue({ weeks: [], summary: {} });
+ api.getBackupStatus.mockResolvedValue({ status: 'never' });
+ api.getBackupSnapshots.mockResolvedValue([]);
+});
+afterEach(() => { cleanup(); vi.useRealTimers(); });
+
+describe('dashboard resource subscriptions', () => {
+ it.each(cases)('$name updates on events, never polls, and reconciles once per reconnect/reshow', async ({ Component, read, event, data, prepare }) => {
+ api[read].mockResolvedValue(data('Example before'));
+ render(<MemoryRouter><Component /></MemoryRouter>);
+ await flush();
+ prepare?.();
+ expect(screen.getByText('Example before', { exact: false })).toBeInTheDocument();
+ expect(api[read]).toHaveBeenCalledTimes(1);
+ await act(async () => { await vi.advanceTimersByTimeAsync(360_000); });
+ expect(api[read]).toHaveBeenCalledTimes(1);
+ api[read].mockResolvedValue(data('Example after'));
+ await act(async () => socket.receive(event));
+ expect(screen.getByText('Example after', { exact: false })).toBeInTheDocument();
+ expect(api[read]).toHaveBeenCalledTimes(2);
+ await act(async () => socket.receive('connect'));
+ expect(api[read]).toHaveBeenCalledTimes(3);
+ await act(async () => visible('hidden'));
+ await act(async () => { socket.receive(event); socket.receive('connect'); });
+ expect(api[read]).toHaveBeenCalledTimes(3);
+ await act(async () => visible('visible'));
+ expect(api[read]).toHaveBeenCalledTimes(4);
+ await act(async () => visible('visible'));
+ expect(api[read]).toHaveBeenCalledTimes(4);
+ });
+
+ it('refreshes the open snapshot list after backup finalization without a timer', async () => {
+ api.getBackupSnapshots.mockResolvedValue([{ id: 'example-before', fileCount: 1 }]);
+ render(<MemoryRouter><BackupWidget /></MemoryRouter>);
+ await flush();
+ fireEvent.click(screen.getByRole('button', { name: 'Snapshots' }));
+ await flush();
+ expect(screen.getByText('example-before')).toBeInTheDocument();
+ api.getBackupSnapshots.mockResolvedValue([{ id: 'example-after', fileCount: 2 }]);
+ await act(async () => socket.receive('backup:changed'));
+ expect(screen.getByText('example-after')).toBeInTheDocument();
+ await act(async () => { await vi.advanceTimersByTimeAsync(360_000); });
+ expect(api.getBackupSnapshots).toHaveBeenCalledTimes(2);
+ await act(async () => socket.receive('connect'));
+ expect(api.getBackupSnapshots).toHaveBeenCalledTimes(3);
+ await act(async () => visible('hidden'));
+ await act(async () => visible('visible'));
+ expect(api.getBackupSnapshots).toHaveBeenCalledTimes(4);
+ });
+});
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index 61ca22c425..a5f5bdbd51 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -44,6 +44,42 @@ const loomRunSnapshot = (production) => Object.freeze({
});
export const SOCKET_EVENT_CONTRACTS = Object.freeze({
+ 'goals:changed': {
+ direction: 'server-to-client',
+ summary: 'Invalidate goals after a local write or peer merge.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'backup:changed': {
+ direction: 'server-to-client',
+ summary: 'Invalidate backup status and snapshots after lifecycle or configuration changes.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'cos:decisions:changed': {
+ direction: 'server-to-client',
+ summary: 'Invalidate the decision summary after an appended or collapsed decision.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'cos:schedule:changed': {
+ direction: 'server-to-client',
+ summary: 'Invalidate upcoming tasks after schedule persistence.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'cos:scheduler:changed': {
+ direction: 'server-to-client',
+ summary: 'Invalidate upcoming tasks after scheduler registration, cancellation or execution.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'cos:agents:changed': {
+ direction: 'server-to-client',
+ summary: 'Invalidate agent aggregates after deletion or cleanup.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'cos:learning:changed': {
+ direction: 'server-to-client',
+ summary: 'Invalidate learning aggregates and upcoming estimates after persistence.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+
'digital-twin:changed': {
direction: 'server-to-client',
summary: 'Invalidate Digital Twin status/settings after persistence or completed peer sync; contains no personal data.',
diff --git a/server/services/backup.js b/server/services/backup.js
index 8d7c580caa..3ed88cc51a 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -6,6 +6,7 @@
* Integrates with eventScheduler for daily cron scheduling.
*/
+import { dashboardEvents } from './dashboardEvents.js';
import { spawn } from '../lib/childProcess.js';
import { killWithEscalation } from '../lib/killWithEscalation.js';
import { access, lstat, readdir, readFile, rm, stat, unlink, writeFile } from 'fs/promises';
@@ -543,6 +544,7 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl
releaseActiveSnapshot();
setBackupRunning(false, 'failure');
await saveState({ lastRun: new Date().toISOString(), status: 'error', error: err.message, pgBackup: null }).catch(() => {});
+ dashboardEvents.emit('backup:changed');
if (io) io.emit('backup:failed', { snapshotId, error: err.message });
throw err;
};
@@ -573,6 +575,7 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl
await ensureDir(dataDestDir);
activeSnapshotId = snapshotId;
await writeFile(markerPath(snapshotDir), '');
+ dashboardEvents.emit('backup:changed');
const excludeFlags = effectiveExcludes.flatMap(p => ['--exclude', p]);
changedFiles = await runRsync(PATHS.data, dataDestDir, excludeFlags);
@@ -633,6 +636,7 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl
});
}
+ dashboardEvents.emit('backup:changed');
return { ...result, prunedSnapshots: pruned.pruned };
} catch (err) {
return fail(err);
@@ -1063,6 +1067,7 @@ export async function deleteSnapshot(destPath, snapshotId, { source } = {}) {
});
}
await rm(snapshotDir, { recursive: true, force: true });
+ dashboardEvents.emit('backup:changed');
console.log(`💾 Backup snapshot deleted: ${resolvedSource}/${snapshotId}`);
return { deleted: true, snapshotId, source: resolvedSource };
}
@@ -1579,10 +1584,11 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, sou
}
/**
- * Get current backup state from disk.
+ * Get persisted backup state with the current in-process run status.
*/
export async function getState() {
- return readJSONFile(STATE_PATH, DEFAULT_STATE, { strict: true });
+ const state = await readJSONFile(STATE_PATH, DEFAULT_STATE, { strict: true });
+ return isRunning ? { ...state, status: 'running' } : state;
}
/**
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 1e65c76615..ea534e4f8d 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -2459,6 +2459,33 @@ describe('runBackup lifecycle', () => {
rmSync(destRoot, { recursive: true, force: true });
});
+ it.each([0, 1])('invalidates scheduled backups only after readable lifecycle transitions (exit %s)', async (exitCode) => {
+ const { dashboardEvents } = await import('./dashboardEvents.js');
+ const { getState, listSnapshots } = await import('./backup.js');
+ const reads = [];
+ const listener = () => reads.push(Promise.all([getState(), listSnapshots(destRoot)]));
+ dashboardEvents.on('backup:changed', listener);
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ try {
+ const pending = runBackup(destRoot, null).catch(error => error);
+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');
+ const [started, initialSnapshots] = await reads[0];
+ expect(started.status).toBe('running');
+ expect(initialSnapshots[0].incomplete).toBe(true);
+ proc.emit('close', exitCode);
+ const result = await pending;
+ expect(reads).toHaveLength(2);
+ const [finished, snapshots] = await reads[1];
+ expect(finished.status).toBe(exitCode ? 'error' : 'ok');
+ expect(snapshots[0].incomplete).toBe(false);
+ expect(Boolean(snapshots[0].failed)).toBe(Boolean(exitCode));
+ if (exitCode) expect(result).toBeInstanceOf(Error);
+ } finally {
+ dashboardEvents.off('backup:changed', listener);
+ }
+ });
+
it('rsyncs, writes a manifest and state, and emits started/completed', async () => {
const io = { emit: vi.fn() };
const proc = fakeProc();
diff --git a/server/services/dashboardEvents.js b/server/services/dashboardEvents.js
new file mode 100644
index 0000000000..52b7e9bed2
--- /dev/null
+++ b/server/services/dashboardEvents.js
@@ -0,0 +1,5 @@
+import { EventEmitter } from 'node:events';
+
+// Resource invalidations only: no personal records or configuration on the wire.
+// Writers emit after persistence; socket.js forwards to authenticated clients.
+export const dashboardEvents = new EventEmitter();
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index dd191f6659..001a5e3a0b 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -7,6 +7,7 @@
*/
import { meatspaceEvents } from './meatspaceEvents.js';
+import { dashboardEvents } from './dashboardEvents.js';
import { stat, readdir } from 'fs/promises';
import { join } from 'path';
import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';
@@ -437,6 +438,7 @@ async function applyGoalsRemote(remoteData) {
if (goalsChanged || remoteMaxTs > localMaxTs) {
await atomicWrite(GOALS_FILE, merged);
+ dashboardEvents.emit('goals:changed');
console.log(`🔄 Goals sync: merged ${mergedGoals.length} goals`);
return { applied: true, count: mergedGoals.length };
}
diff --git a/server/services/decisionLog.js b/server/services/decisionLog.js
index e958042186..1cc1181afa 100644
--- a/server/services/decisionLog.js
+++ b/server/services/decisionLog.js
@@ -7,6 +7,7 @@
*/
import { join } from 'path';
+import { dashboardEvents } from './dashboardEvents.js';
import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
import { cosEvents } from './cosEvents.js';
@@ -70,6 +71,7 @@ async function loadDecisions() {
async function saveDecisions(data) {
decisionCache = data;
await atomicWrite(DECISION_FILE, data);
+ dashboardEvents.emit('cos:decisions:changed');
}
/**
diff --git a/server/services/identity/store.js b/server/services/identity/store.js
index 7d0a08b318..185d735aec 100644
--- a/server/services/identity/store.js
+++ b/server/services/identity/store.js
@@ -1,4 +1,5 @@
import { meatspaceEvents } from '../meatspaceEvents.js';
+import { dashboardEvents } from '../dashboardEvents.js';
import { join } from 'path';
import { atomicWrite, PATHS, ensureDir, readJSONFileStrict } from '../../lib/fileUtils.js';
import { isMortalLoomEnabled, mlArrayIfEnabled, mlReplace } from '../mortalLoomStore.js';
@@ -153,4 +154,5 @@ export async function saveJSON(filePath, data) {
if (filePath === GOALS_FILE && (await isMortalLoomEnabled()) && Array.isArray(data.goals)) {
await mlReplace('goals', data.goals);
}
+ if (filePath === GOALS_FILE) dashboardEvents.emit('goals:changed');
}
diff --git a/server/services/identity/store.test.js b/server/services/identity/store.test.js
index c404688509..0781be0e93 100644
--- a/server/services/identity/store.test.js
+++ b/server/services/identity/store.test.js
@@ -1,4 +1,5 @@
import { meatspaceEvents } from '../meatspaceEvents.js';
+import { dashboardEvents } from '../dashboardEvents.js';
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
@@ -198,3 +199,18 @@ describe('loadJSON — status-less MortalLoom goals reach strict active-goal con
expect(status.sections.goals.status).toBe('unavailable');
});
});
+
+// Regression: persisted goal edits invalidate dashboards, unrelated identity writes do not.
+it('announces goal persistence only after the readable store has changed', async () => {
+ const listener = vi.fn();
+ dashboardEvents.on('goals:changed', listener);
+ try {
+ await saveJSON(GOALS_FILE, { goals: [{ id: 'example', title: 'Updated goal' }] });
+ expect(listener).toHaveBeenCalledTimes(1);
+ expect(await loadJSON(GOALS_FILE, DEFAULT_GOALS)).toMatchObject({ goals: [{ title: 'Updated goal' }] });
+ await saveJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);
+ expect(listener).toHaveBeenCalledTimes(1);
+ } finally {
+ dashboardEvents.off('goals:changed', listener);
+ }
+});
diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.js
index dcc5255d8d..a8f9217f2e 100644
--- a/server/services/mortalLoomStore.js
+++ b/server/services/mortalLoomStore.js
@@ -8,6 +8,7 @@
* up on the other after iCloud sync completes.
*/
+import { dashboardEvents } from './dashboardEvents.js';
import { homedir } from 'os';
import { join } from 'path';
import { stat } from 'fs/promises';
@@ -204,7 +205,6 @@ async function materializeNow(path) {
// retry the initial pin without duplicating the listener.
let listenerAttached = false;
let didInitialPin = false;
-
// One server watcher for external iCloud changes, including atomic replacement
// and recovery after transient unreadability; never one poll per browser.
let watchedPath = null;
@@ -232,6 +232,9 @@ function configureStoreWatcher(settings) {
// Retain the last good snapshot through eviction/read failures.
if (result.ok) {
invalidateMortalLoomChanges(previous, result.store);
+ if (JSON.stringify(previous?.goals) !== JSON.stringify(result.store?.goals)) {
+ dashboardEvents.emit('goals:changed');
+ }
previous = structuredClone(result.store);
}
} while (dirty);
@@ -276,6 +279,7 @@ export async function initMortalLoomStore() {
if (nextPath !== watchedPath) {
configureStoreWatcher(settings);
invalidateMeatspace(['overview', 'alcohol', 'body', 'blood', 'epigenetic', 'eyes', 'calendar']);
+ dashboardEvents.emit('goals:changed');
}
if (!settings?.mortalloom?.enabled) {
// Disable clears the dedup cache so a future re-enable (even with the
@@ -440,6 +444,7 @@ export async function readStore() {
async function writeStoreAtPath(path, data) {
await withTransientRetry(() => atomicWrite(path, data));
+ dashboardEvents.emit('goals:changed');
}
/** Atomic read → mutate → write. Ensures all array keys are initialized. */
@@ -830,6 +835,7 @@ export async function importToPortOS() {
await ensureDir(dataPath('digital-twin'));
localGoals.updatedAt = new Date().toISOString();
await atomicWrite(goalsPath, localGoals);
+ dashboardEvents.emit('goals:changed');
}
report.added.goals = gAdded; report.skipped.goals = gSkipped;
diff --git a/server/services/mortalLoomStore.test.js b/server/services/mortalLoomStore.test.js
index 8787b46ab9..24e4f7b8b4 100644
--- a/server/services/mortalLoomStore.test.js
+++ b/server/services/mortalLoomStore.test.js
@@ -1120,34 +1120,45 @@ describe('overview invalidation from MortalLoom', () => {
store._resetMortalLoomInitForTest();
settingsEvents.removeAllListeners();
const { meatspaceEvents } = await import('./meatspaceEvents.js');
+ const { dashboardEvents } = await import('./dashboardEvents.js');
+ const goalsChanged = vi.fn();
+ dashboardEvents.on('goals:changed', goalsChanged);
const changed = vi.fn();
meatspaceEvents.on('changed', changed);
try {
- readFileMock.mockResolvedValue(JSON.stringify({ bodyEntries: [] }));
+ readFileMock.mockResolvedValue(JSON.stringify({ bodyEntries: [], goals: [] }));
await store.initMortalLoomStore();
await store.initMortalLoomStore();
await vi.advanceTimersByTimeAsync(0);
changed.mockClear();
- readFileMock.mockResolvedValue(JSON.stringify({ bodyEntries: [{ date: '2026-01-01', weightLbs: 170 }] }));
+ goalsChanged.mockClear();
+ readFileMock.mockResolvedValue(JSON.stringify({ bodyEntries: [{ date: '2026-01-01', weightLbs: 170 }], goals: [{ id: 'example-goal' }] }));
await vi.advanceTimersByTimeAsync(10_000);
expect(changed).toHaveBeenCalledExactlyOnceWith({ resources: ['body'] });
+ expect(goalsChanged).toHaveBeenCalledTimes(1);
changed.mockClear();
+ goalsChanged.mockClear();
readFileMock.mockRejectedValueOnce(Object.assign(new Error('unreadable'), { code: 'EACCES' }));
await vi.advanceTimersByTimeAsync(10_000);
expect(changed).not.toHaveBeenCalled();
+ expect(goalsChanged).not.toHaveBeenCalled();
readFileMock.mockResolvedValue(JSON.stringify({ bodyEntries: [{ date: '2026-01-01', weightLbs: 172 }] }));
await vi.advanceTimersByTimeAsync(10_000);
expect(changed).toHaveBeenCalledExactlyOnceWith({ resources: ['body'] });
+ expect(goalsChanged).toHaveBeenCalledTimes(1);
settingsEvents.emit('settings:updated', { mortalloom: { enabled: false } });
changed.mockClear();
+ goalsChanged.mockClear();
const reads = readFileMock.mock.calls.length;
await vi.advanceTimersByTimeAsync(30_000);
expect(readFileMock).toHaveBeenCalledTimes(reads);
expect(changed).not.toHaveBeenCalled();
+ expect(goalsChanged).not.toHaveBeenCalled();
} finally {
store._resetMortalLoomInitForTest();
settingsEvents.removeAllListeners();
meatspaceEvents.off('changed', changed);
+ dashboardEvents.off('goals:changed', goalsChanged);
vi.useRealTimers();
}
});
diff --git a/server/services/socket.js b/server/services/socket.js
index 00be48ec55..adf68319ba 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -1,4 +1,6 @@
import { meatspaceEvents } from './meatspaceEvents.js';
+import { dashboardEvents } from './dashboardEvents.js';
+import { settingsEvents } from './settings.js';
import { recordEvents } from './sharing/recordEvents.js';
import { fableLoomRunEvents } from './fableLoom/runEvents.js';
import { cosEvents } from './cosEvents.js';
@@ -425,6 +427,28 @@ function broadcastToErrors(event, data) { broadcastToSet(errorSubscribers, event
// Set up CoS event forwarding
function setupCosEventForwarding() {
+ // Dashboard invalidations deliberately omit decisions, prompts and settings.
+ for (const event of ['goals:changed', 'backup:changed']) {
+ dashboardEvents.on(event, () => ioInstance?.emit(event, {}));
+ }
+ for (const event of ['cos:schedule:changed', 'cos:decisions:changed']) {
+ dashboardEvents.on(event, () => broadcastToCos(event, {}));
+ }
+ settingsEvents.on('settings:updated', () => ioInstance?.emit('backup:changed', {}));
+ for (const [source, target] of [
+ ['scheduler:scheduled', 'cos:scheduler:changed'],
+ ['scheduler:ran', 'cos:scheduler:changed'],
+ ['scheduler:cancelled', 'cos:scheduler:changed'],
+ ['agents:changed', 'cos:agents:changed'],
+ ['learning:changed', 'cos:learning:changed'],
+ ]) {
+ cosEvents.on(source, data => {
+ broadcastToCos(target, {});
+ if (target === 'cos:scheduler:changed' && data?.id === 'backup-daily') {
+ ioInstance?.emit('backup:changed', {});
+ }
+ });
+ }
// Status events
cosEvents.on('goals:changed', data => broadcastToCos('cos:goals:changed', data));
cosEvents.on('status', (data) => broadcastToCos('cos:status', data));
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index 95805f5892..463af8be1d 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -1,4 +1,5 @@
import { meatspaceEvents, invalidateMeatspace } from './meatspaceEvents.js';
+import { dashboardEvents } from './dashboardEvents.js';
import { emitRecordUpdated, emitRecordDeleted, emitRecordInvalidated } from './sharing/recordEvents.js';
import { fableLoomRunEvents } from './fableLoom/runEvents.js';
import { trainingEvents } from './loraTraining/events.js';
@@ -157,6 +158,34 @@ describe('socket.js — initSocket', () => {
expect(io.emitted).toEqual([['meatspace:death-clock:changed', {}]]);
});
+ it('forwards dashboard invalidations without source records and gates CoS events on subscription', () => {
+ const subscriber = makeSocket('dashboard-subscriber');
+ const other = makeSocket('dashboard-other');
+ io.connect(subscriber);
+ io.connect(other);
+ createdSockets.push(subscriber, other);
+ subscriber.handlers['cos:subscribe']();
+ for (const [source, target] of [
+ ['scheduler:scheduled', 'cos:scheduler:changed'],
+ ['scheduler:ran', 'cos:scheduler:changed'], ['scheduler:cancelled', 'cos:scheduler:changed'],
+ ['agents:changed', 'cos:agents:changed'], ['learning:changed', 'cos:learning:changed'],
+ ]) {
+ queueListeners.cos.find(([event]) => event === source)[1]({ privateContent: 'Example private record' });
+ expect(subscriber.emitted).toContainEqual([target, {}]);
+ expect(other.emitted.some(([event]) => event === target)).toBe(false);
+ }
+ dashboardEvents.emit('cos:decisions:changed');
+ expect(subscriber.emitted).toContainEqual(['cos:decisions:changed', {}]);
+ expect(other.emitted.some(([event]) => event === 'cos:decisions:changed')).toBe(false);
+ dashboardEvents.emit('cos:schedule:changed');
+ expect(subscriber.emitted).toContainEqual(['cos:schedule:changed', {}]);
+ expect(other.emitted.some(([event]) => event === 'cos:schedule:changed')).toBe(false);
+ io.emitted.length = 0;
+ dashboardEvents.emit('goals:changed', { privateContent: 'Example goal' });
+ dashboardEvents.emit('backup:changed', { destPath: '/private/example' });
+ expect(io.emitted).toEqual([['goals:changed', {}], ['backup:changed', {}]]);
+ });
+
it('forwards Digital Twin changes without leaking source records', () => {
io.emitted.length = 0;
for (const event of ['meta:changed', 'sync:completed', 'traits:updated', 'taste:profile-updated', 'interview:analyzed']) {
diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.js
index c7686d2e74..784e62cd51 100644
--- a/server/services/taskLearning/store.js
+++ b/server/services/taskLearning/store.js
@@ -458,6 +458,7 @@ export async function saveLearningData(data) {
_learningCache = structuredClone(data);
_learningCacheTime = Date.now();
cosEvents.emit('goals:changed', {});
+ cosEvents.emit('learning:changed');
}
/**
diff --git a/server/services/taskScheduleStore.js b/server/services/taskScheduleStore.js
index 97bda9deb6..d0f8c9b036 100644
--- a/server/services/taskScheduleStore.js
+++ b/server/services/taskScheduleStore.js
@@ -1,5 +1,6 @@
/** Persisted task schedule state and prompt-default compatibility upgrades. */
+import { dashboardEvents } from './dashboardEvents.js';
import { existsSync } from 'fs';
import { join } from 'path';
import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
@@ -303,6 +304,7 @@ async function saveScheduleNow(schedule) {
await ensureDataDir();
schedule.lastUpdated = new Date().toISOString();
await atomicWrite(SCHEDULE_FILE, schedule);
+ dashboardEvents.emit('cos:schedule:changed');
}
export function saveSchedule(schedule) {