Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: expire dashboard time windows with server events (#8531)
[._.]/ Adam Eivydfb10501aa6b
diff --git a/client/src/components/CosDashboardWidget.jsx b/client/src/components/CosDashboardWidget.jsxindex 4b562be490..d0efa967ab 100644--- a/client/src/components/CosDashboardWidget.jsx+++ b/client/src/components/CosDashboardWidget.jsx@@ -17,7 +17,7 @@ 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:updated', 'cos:agent:completed', 'cos:agents:changed', 'cos:status', 'cos:status:paused', 'cos:status:resumed', 'cos:learning:changed'];+const RESOURCE_EVENTS = ['cos:day:changed', 'cos:tasks:changed', 'cos:tasks:user:changed', 'cos:tasks:cos:changed', 'cos:agent:spawned', 'cos:agent:updated', '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 Dashboarddiff --git a/client/src/components/dashboardWidgets.realtime.test.jsx b/client/src/components/dashboardWidgets.realtime.test.jsxindex 970407a0d1..0851ae33bf 100644--- a/client/src/components/dashboardWidgets.realtime.test.jsx+++ b/client/src/components/dashboardWidgets.realtime.test.jsx@@ -86,6 +86,18 @@ describe('dashboard resource subscriptions', () => {expect(api[read]).toHaveBeenCalledTimes(4);});+ it('reconciles CoS day aggregates on the server midnight event', async () => {+ api.getCosRecentTasks.mockResolvedValue({ tasks: [], summary: {} });+ api.getCosQuickSummary.mockResolvedValue({ today: { completed: 7, succeeded: 7 }, queue: {}, status: { running: true } });+ render(<MemoryRouter><CosDashboardWidget /></MemoryRouter>);+ await flush();+ expect(screen.getByText('7')).toBeInTheDocument();+ api.getCosQuickSummary.mockResolvedValue({ today: { completed: 0, succeeded: 0 }, queue: {}, status: { running: true } });+ await act(async () => socket.receive('cos:day:changed'));+ expect(screen.queryByText('7')).not.toBeInTheDocument();+ expect(api.getCosQuickSummary).toHaveBeenCalledTimes(2);+ });+it('advances overdue coloring and schedule countdowns with no network reads', async () => {vi.setSystemTime(new Date('2026-01-01T12:00:00Z'));api.listThreads.mockResolvedValue({ threads: [{ id: 'example', title: 'Example deadline', status: 'open', dueAt: '2026-01-01T12:00:30Z' }], total: 1 });diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex a5f5bdbd51..f96126d4df 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -44,6 +44,11 @@ const loomRunSnapshot = (production) => Object.freeze({});export const SOCKET_EVENT_CONTRACTS = Object.freeze({+ 'cos:day:changed': {+ direction: 'server-to-client',+ summary: 'Invalidate UTC-day aggregates when the current activity-calendar day expires.',+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },+ },'goals:changed': {direction: 'server-to-client',summary: 'Invalidate goals after a local write or peer merge.',diff --git a/server/services/cosActivityCalendar.js b/server/services/cosActivityCalendar.jsindex 65c3519e47..80fb8f283c 100644--- a/server/services/cosActivityCalendar.js+++ b/server/services/cosActivityCalendar.js@@ -9,7 +9,7 @@* `archiveStaleAgents`) plus the completed agents still resident in* `state.agents` — so it is correct the moment a run finishes. Both are* process-cached (`loadAgentIndex` memoizes, `loadState` holds `stateCache`),- * so the widget's 30-second poll costs no disk I/O.+ * so event-triggered dashboard reads cost no disk I/O.** It replaces the `data/cos/productivity.json` aggregate this used to read* (#7599). That file had no automatic writer: nothing in the server called the@@ -38,6 +38,7 @@* learning rather than this grid.*/+import { scheduleDashboardExpiry } from './dashboardEvents.js';import { loadState } from './cosState.js';import { loadAgentIndex } from './cosAgentIndex.js';@@ -102,6 +103,9 @@ async function countRunsByDate(sinceStr) {export async function getActivityCalendar(weeks = 12) {const today = new Date();const todayStr = dayKey(today);+ const nextDay = new Date(today);+ nextDay.setUTCHours(24, 0, 0, 0);+ scheduleDashboardExpiry('cos:day:changed', nextDay.getTime());// Sunday of the current week, then back N-1 whole weeks — so the grid is// exactly `weeks` columns wide whatever weekday it is read on.diff --git a/server/services/cosActivityCalendar.test.js b/server/services/cosActivityCalendar.test.jsindex 86ae26950a..47d48a3b33 100644--- a/server/services/cosActivityCalendar.test.js+++ b/server/services/cosActivityCalendar.test.js@@ -140,3 +140,27 @@ describe('getActivityCalendar', () => {expect(summary).toMatchObject({ activeDays: 0, totalTasks: 0 });});});+++it('invalidates the day-boundary snapshot once across simultaneous dashboard reads', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-01-01T23:59:30Z'));+ const { dashboardEvents, scheduleDashboardExpiry } = await import('./dashboardEvents.js');+ const changed = vi.fn();+ dashboardEvents.on('cos:day:changed', changed);+ try {+ const before = await getActivityCalendar(1);+ await getActivityCalendar(1);+ expect(before.weeks.flat().find(day => day.isToday).date).toBe('2026-01-01');+ await vi.advanceTimersByTimeAsync(30_000);+ expect(changed).toHaveBeenCalledTimes(1);+ const after = await getActivityCalendar(1);+ expect(after.weeks.flat().find(day => day.isToday).date).toBe('2026-01-02');+ await vi.advanceTimersByTimeAsync(60_000);+ expect(changed).toHaveBeenCalledTimes(1);+ } finally {+ scheduleDashboardExpiry('cos:day:changed', null);+ dashboardEvents.off('cos:day:changed', changed);+ vi.useRealTimers();+ }+});diff --git a/server/services/dashboardEvents.js b/server/services/dashboardEvents.jsindex 52b7e9bed2..d0e8b17aed 100644--- a/server/services/dashboardEvents.js+++ b/server/services/dashboardEvents.js@@ -3,3 +3,22 @@ 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();++const expiries = new Map();++// Time-window resources become stale even without a write. Arm one shared,+// one-shot invalidation per domain, at its actual next expiry (never a poll).+// A subsequent resource read arms the next boundary; no consumer means no work.+export function scheduleDashboardExpiry(event, expiresAt) {+ const previous = expiries.get(event);+ if (previous?.at === expiresAt) return;+ if (previous) clearTimeout(previous.timer);+ expiries.delete(event);+ if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return;+ const timer = setTimeout(() => {+ expiries.delete(event);+ dashboardEvents.emit(event);+ }, Math.min(expiresAt - Date.now(), 2147483647));+ timer.unref?.();+ expiries.set(event, { at: expiresAt, timer });+}diff --git a/server/services/decisionLog.js b/server/services/decisionLog.jsindex 1cc1181afa..6ffb08a042 100644--- a/server/services/decisionLog.js+++ b/server/services/decisionLog.js@@ -7,7 +7,7 @@*/import { join } from 'path';-import { dashboardEvents } from './dashboardEvents.js';+import { dashboardEvents, scheduleDashboardExpiry } from './dashboardEvents.js';import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';import { cosEvents } from './cosEvents.js';@@ -165,6 +165,9 @@ export async function getDecisionSummary() {return ts > oneDayAgo;});+ scheduleDashboardExpiry('cos:decisions:changed', Math.min(...recentDecisions.map(d =>+ new Date(d.lastTimestamp || d.timestamp).getTime() + 24 * 60 * 60 * 1000)));+// Group by type, using collapsed countconst byType = {};for (const d of recentDecisions) {diff --git a/server/services/decisionLog.test.js b/server/services/decisionLog.test.jsindex fd06c6ae18..77fc9a2d8c 100644--- a/server/services/decisionLog.test.js+++ b/server/services/decisionLog.test.js@@ -283,6 +283,31 @@ describe('decisionLog.js', () => {});describe('getDecisionSummary', () => {+ it('invalidates once when the next collapsed decision leaves the rolling window', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-01-02T12:00:00Z'));+ const { dashboardEvents, scheduleDashboardExpiry } = await import('./dashboardEvents.js');+ const changed = vi.fn();+ dashboardEvents.on('cos:decisions:changed', changed);+ try {+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions: [{+ id: 'example', type: DECISION_TYPES.TASK_SKIPPED, reason: 'Example', count: 2,+ timestamp: '2026-01-01T11:00:00Z', lastTimestamp: '2026-01-01T12:00:30Z',+ }] }));+ expect((await getDecisionSummary()).last24Hours.total).toBe(2);+ await getDecisionSummary(); // another browser shares the same expiry+ await vi.advanceTimersByTimeAsync(30_000);+ expect(changed).toHaveBeenCalledTimes(1);+ expect((await getDecisionSummary()).last24Hours.total).toBe(0);+ await vi.advanceTimersByTimeAsync(60_000);+ expect(changed).toHaveBeenCalledTimes(1);+ } finally {+ scheduleDashboardExpiry('cos:decisions:changed', null);+ dashboardEvents.off('cos:decisions:changed', changed);+ vi.useRealTimers();+ }+ });+it('should return summary for last 24 hours', async () => {const now = new Date();const recentTimestamp = new Date(now.getTime() - 1000 * 60 * 60).toISOString(); // 1 hour agodiff --git a/server/services/socket.js b/server/services/socket.jsindex adf68319ba..6e877d26b6 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -431,7 +431,7 @@ function setupCosEventForwarding() {for (const event of ['goals:changed', 'backup:changed']) {dashboardEvents.on(event, () => ioInstance?.emit(event, {}));}- for (const event of ['cos:schedule:changed', 'cos:decisions:changed']) {+ for (const event of ['cos:schedule:changed', 'cos:decisions:changed', 'cos:day:changed']) {dashboardEvents.on(event, () => broadcastToCos(event, {}));}settingsEvents.on('settings:updated', () => ioInstance?.emit('backup:changed', {}));diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex fe30d6310c..4ad2d60617 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -175,6 +175,9 @@ describe('socket.js — initSocket', () => {expect(subscriber.emitted).toContainEqual([target, {}]);expect(other.emitted.some(([event]) => event === target)).toBe(false);}+ dashboardEvents.emit('cos:day:changed');+ expect(subscriber.emitted).toContainEqual(['cos:day:changed', {}]);+ expect(other.emitted.some(([event]) => event === 'cos:day:changed')).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);