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: refresh Brain views from socket changes (#8550)
[._.]/ Adam Eivy7bfb799f54a5
diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsxindex 5e79281a7d..2dab4969a7 100644--- a/client/src/components/brain/tabs/LinksTab.jsx+++ b/client/src/components/brain/tabs/LinksTab.jsx@@ -34,7 +34,8 @@ import BrailleSpinner from '../../BrailleSpinner';import toast from '../../ui/Toast';import InlineConfirmRow from '../../ui/InlineConfirmRow';import { timeAgo } from '../../../utils/formatters';-import { useAutoRefetch } from '../../../hooks/useAutoRefetch';+import { sameJsonShape } from '../../../lib/sameJsonShape';+import { useSocketResource } from '../../../hooks/useSocketResource';import BucketBoard from '../links/BucketBoard';import RepoRestudyPanel from '../RepoRestudyPanel';import LinkChip from '../links/LinkChip';@@ -86,34 +87,17 @@ const CLONE_STATUS_STYLES = {failed: 'text-port-error'};-/** A clone the server is still working on — the only reason this tab polls. */-const isCloneInFlight = (link) => link.cloneStatus === 'cloning' || link.cloneStatus === 'pending';+const LINK_EVENTS = ['brain:links:changed'];-const CLONE_POLL_INTERVAL_MS = 3000;--// Give up polling a clone that has shown no progress for roughly this long. A-// server restart mid-clone strands the record at `cloning` forever (only the-// promise callbacks in `cloneRepoInBackground` reset it), and without this-// bound the poll below becomes the permanent steady state of the Links tab.-// Any status change restarts the count; once it expires the badge says so-// (#5463 tracks giving the stranded record itself a way back).-const CLONE_POLL_STALL_MS = 10 * 60 * 1000;--// Counted in TICKS, not wall-clock: `useAutoRefetch` pauses while the tab is-// hidden, so a wall-clock deadline would be tripped by the resume tick alone-// after the user left the tab backgrounded — abandoning a clone that may well-// have finished. Ticks only accrue while we are actually looking.-const CLONE_POLL_STALL_TICKS = Math.ceil(CLONE_POLL_STALL_MS / CLONE_POLL_INTERVAL_MS);--// The fields the background clone and its post-clone intake write. The poll+// The fields the background clone and its post-clone intake write. The event read// merges ONLY these onto the record it already has, so a response that was// already in flight when the user renamed a link or dragged its chip cannot// revert that edit with a pre-edit snapshot of the whole record. All five are// server-owned; nothing in this tab edits them locally.const CLONE_PROGRESS_FIELDS = ['cloneStatus', 'cloneError', 'localPath', 'malwareScan', 'repoStudy'];-// `malwareScan` / `repoStudy` arrive as fresh objects on every fetch, so they-// need a value comparison — otherwise every tick would look like a change and+// `malwareScan` / `repoStudy` arrive as fresh objects on every event read, so they+// need a value comparison — otherwise every event would look like a change and// re-render the whole list. A false "changed" costs one render; there is no// false "same" for equal content the server serializes consistently.const sameFieldValue = (a, b) => a === b || JSON.stringify(a) === JSON.stringify(b);@@ -158,77 +142,57 @@ export default function LinksTab({ onRefresh }) {setLoading(false);}, []);+ const readChanges = useCallback(async ({ reconcile, events }) => {+ if (reconcile) {+ const [data, bucketData] = await Promise.all([+ api.getBrainLinks({ limit: 5000, silent: true }),+ api.getBrainBuckets({ silent: true })+ ]);+ return { links: data.links || [], buckets: bucketData.buckets || [] };+ }+ const ids = [...new Set(events.map(({ payload }) => payload.id))];+ const updates = await Promise.all(ids.map(id => api.getBrainLink(id, { silent: true })+ .then(fresh => ({ id, fresh }))+ .catch(error => {+ if (error?.status === 404) return { id, gone: true };+ return { id }; // Keep this record on transient failure; other updates still land.+ })));+ return { updates };+ }, []);+ const { data: changes, loading: reading } = useSocketResource(readChanges, {+ events: LINK_EVENTS,+ matchesEvent: payload => typeof payload?.id === 'string',+ compare: sameJsonShape+ });useEffect(() => {- let active = true;- fetchLinks();- api.getBrainBuckets({ silent: true })- .then(data => { if (active) setBuckets(data.buckets || []); })- .catch(() => { if (active) setBuckets([]); });- return () => { active = false; };- }, [fetchLinks]);-- // Poll ONLY the links whose clone is in flight, patching each fresh record- // into local state. Re-running `fetchLinks` here re-read and re-parsed every- // link record server-side (one file read per link, up to 5000) and replaced- // the whole array — re-rendering every bucket board, chip, and search result- // — every 3s just to move one status badge (#5442).- const inFlight = links.filter(isCloneInFlight);- const inFlightIds = inFlight.map(l => l.id);- // Identity of the in-flight SET and its statuses. A change here is progress,- // so it restarts the no-progress tick count; an unrelated `links` update (an- // edit, a bucket drag) leaves both the count and the poll callback alone.- const inFlightKey = inFlight.map(l => `${l.id}:${l.cloneStatus}`).join('|');-- const [stalledPollKey, setStalledPollKey] = useState(null);- // Ticks since the in-flight set last moved.- const noProgressTicksRef = useRef(0);- useEffect(() => {- noProgressTicksRef.current = 0;- }, [inFlightKey]);-- // Depends on `inFlightKey` alone: the same key means the same ids, so the- // closure over `inFlightIds` can never go stale.- const pollInFlightClones = useCallback(async () => {- if (noProgressTicksRef.current >= CLONE_POLL_STALL_TICKS) {- setStalledPollKey(inFlightKey);+ if (!reading) setLoading(false);+ if (!changes) return;+ if (changes.links) {+ setLinks(changes.links);+ setBuckets(changes.buckets);return;}- noProgressTicksRef.current += 1;- // A 404 means the user deleted the bookmark mid-clone: drop it, or its id- // stays in the in-flight set and is polled until the stall bound. Any other- // failure is transient and leaves that link exactly as it is.- const settled = await Promise.all(inFlightIds.map(id => api.getBrainLink(id, { silent: true })- .then(fresh => ({ id, fresh }))- .catch(err => ({ id, gone: err?.status === 404 }))));- const byId = new Map(settled.map(r => [r.id, r]));+ // Merge only server-owned progress fields so a late read cannot undo a+ // local rename or bucket drag. Completed clones still receive scan updates.setLinks(prev => {+ const byId = new Map(changes.updates.map(update => [update.id, update]));let changed = false;const next = [];for (const link of prev) {const result = byId.get(link.id);+ byId.delete(link.id);if (result?.gone) { changed = true; continue; }const patch = result?.fresh ? cloneProgressPatch(result.fresh, link) : null;if (!patch) { next.push(link); continue; }changed = true;next.push({ ...link, ...patch });}- // Unchanged records keep their identity — and an all-quiet tick keeps the- // array itself — so the boards, chips, and search don't re-render.+ for (const result of byId.values()) {+ if (result.fresh) { next.push(result.fresh); changed = true; }+ }return changed ? next : prev;});- }, [inFlightKey]);-- // True once the poll gave up: the badges below say so rather than showing a- // spinner for a status nothing is watching any more.- const cloneWatchStalled = inFlightIds.length > 0 && stalledPollKey === inFlightKey;-- useAutoRefetch(pollInFlightClones, CLONE_POLL_INTERVAL_MS, {- enabled: inFlightIds.length > 0 && !cloneWatchStalled,- // The initial `fetchLinks` already delivered current statuses, so the first- // tick belongs one interval out, not immediately on enable.- immediate: false,- pollOnly: true- });+ }, [changes, reading]);// Client-side filter (type / bucket membership) then keyword search.const matchesFilter = (link) => {@@ -290,7 +254,7 @@ export default function LinksTab({ onRefresh }) {setInputNote('');setInputTags('');setShowDetails(false);- fetchLinks();+ setLinks(prev => prev.some(link => link.id === result.id) ? prev : [result, ...prev]);onRefresh?.();}};@@ -403,7 +367,7 @@ export default function LinksTab({ onRefresh }) {toast.success('Link updated');setEditingId(null);setEditForm({});- fetchLinks();+ setLinks(prev => prev.map(link => link.id === result.id ? result : link));}};@@ -421,7 +385,7 @@ export default function LinksTab({ onRefresh }) {toast.success('Link deleted');setConfirmingDeleteId(null);- fetchLinks();+ setLinks(prev => prev.filter(link => link.id !== linkId));onRefresh?.();};@@ -433,7 +397,7 @@ export default function LinksTab({ onRefresh }) {if (result) {toast.success('Clone started');- fetchLinks();+ // The persisted clone transition arrives through brain:links:changed.}};@@ -964,14 +928,6 @@ export default function LinksTab({ onRefresh }) {{link.cloneStatus === 'cloning' && 'Cloning...'}{link.cloneStatus === 'pending' && 'Pending clone'}{link.cloneStatus === 'failed' && 'Clone failed'}- {cloneWatchStalled && isCloneInFlight(link) && (- <span- className="text-gray-500"- title="No change for 10 minutes — this tab stopped checking. Reload the page to resume."- >- (stalled)- </span>- )}</span>{/* Clone error */}diff --git a/client/src/components/brain/tabs/LinksTab.test.jsx b/client/src/components/brain/tabs/LinksTab.test.jsxindex 853e95c021..c330229529 100644--- a/client/src/components/brain/tabs/LinksTab.test.jsx+++ b/client/src/components/brain/tabs/LinksTab.test.jsx@@ -1,7 +1,14 @@+import { StrictMode } from 'react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { act, fireEvent, render, screen } from '@testing-library/react';import { MemoryRouter } from 'react-router';+vi.mock('../../../services/socket', async () => {+ const { EventEmitter } = await import('node:events');+ return { default: new EventEmitter() };+});+import socket from '../../../services/socket';+vi.mock('../../../services/api', () => ({getBrainLinks: vi.fn(),getBrainLink: vi.fn(),@@ -24,15 +31,8 @@ vi.mock('../../../services/api', () => ({vi.mock('../../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }));-// Counting stub: the board is the most expensive consumer of the `links`-// array, so its render count is the direct measure of "the poll does not-// replace the array on every tick".-let bucketBoardRenders = 0;vi.mock('../links/BucketBoard', () => ({- default: () => {- bucketBoardRenders += 1;- return <div data-testid="bucket-board" />;- },+ default: () => <div data-testid="bucket-board" />,}));// LinksTab mounts its own `DndContext` (buckets + the flat link list share@@ -82,7 +82,7 @@ const link = (id, cloneStatus, overrides = {}) => ({// Mount and settle the initial `getBrainLinks` + `getBrainBuckets` round-trip.async function renderTab() {- const result = render(<MemoryRouter><LinksTab /></MemoryRouter>);+ const result = render(<StrictMode><MemoryRouter><LinksTab /></MemoryRouter></StrictMode>);await act(async () => { await Promise.resolve(); await Promise.resolve(); });return result;}@@ -91,7 +91,6 @@ const tick = (ms = 3000) => act(async () => { await vi.advanceTimersByTimeAsync(beforeEach(() => {vi.clearAllMocks();- bucketBoardRenders = 0;dndState.context = null;vi.useFakeTimers();getBrainBuckets.mockResolvedValue({ buckets: [] });@@ -101,185 +100,71 @@ afterEach(() => {vi.useRealTimers();});-describe('LinksTab clone-status polling', () => {- it('polls only the in-flight ids, never the whole collection again', async () => {+const invalidate = (...ids) => act(async () => {+ for (const id of ids) socket.emit('brain:links:changed', { id });+});++describe('LinksTab socket updates', () => {+ it('reads only changed ids and updates completed clones without timer-driven reads', async () => {getBrainLinks.mockResolvedValue({ links: [link('a', 'cloning'), link('b', 'cloned')] });- getBrainLink.mockResolvedValue(link('a', 'cloning'));+ getBrainLink.mockResolvedValue(link('a', 'cloned'));await renderTab();-- expect(getBrainLinks).toHaveBeenCalledTimes(1);+ await tick(600_000);expect(getBrainLink).not.toHaveBeenCalled();-- await tick();+ expect(getBrainLinks).toHaveBeenCalledTimes(1);+ await invalidate('a', 'a');expect(getBrainLink).toHaveBeenCalledTimes(1);expect(getBrainLink).toHaveBeenCalledWith('a', { silent: true });-- await tick();- expect(getBrainLink).toHaveBeenCalledTimes(2);- expect(getBrainLink.mock.calls.every(([id]) => id === 'a')).toBe(true);- // The whole-collection fetch happened once, at mount, and never again.- expect(getBrainLinks).toHaveBeenCalledTimes(1);- });-- it('polls a pending clone too, and every in-flight id in one tick', async () => {- getBrainLinks.mockResolvedValue({- links: [link('a', 'cloning'), link('b', 'pending'), link('c', 'none')],- });- getBrainLink.mockImplementation(async (id) => link(id, 'cloning'));- await renderTab();-- await tick();- expect(getBrainLink.mock.calls.map(([id]) => id).sort()).toEqual(['a', 'b']);- });-- it('patches the fresh status in and stops polling once nothing is in flight', async () => {- getBrainLinks.mockResolvedValue({ links: [link('a', 'cloning'), link('b', 'cloned')] });- getBrainLink.mockResolvedValue(link('a', 'cloned'));- await renderTab();-- expect(screen.getByText('Cloning...')).toBeTruthy();-- await tick();expect(screen.queryByText('Cloning...')).toBeNull();expect(screen.getAllByText('Cloned')).toHaveLength(2);-- const callsAfterCompletion = getBrainLink.mock.calls.length;- await tick(9000);- expect(getBrainLink).toHaveBeenCalledTimes(callsAfterCompletion);+ getBrainLink.mockResolvedValue(link('a', 'cloned', {+ malwareScan: { reportId: '11111111-1111-4111-8111-111111111111', status: 'queued' },+ }));+ await invalidate('a');+ expect(screen.getByTitle(/Malware scan queued/)).toBeTruthy();+ await tick(60_000);+ expect(getBrainLink).toHaveBeenCalledTimes(2);+ expect(getBrainLinks).toHaveBeenCalledTimes(1);});- it('leaves the other links intact when one in-flight id fails transiently', async () => {- getBrainLinks.mockResolvedValue({ links: [link('a', 'cloning'), link('c', 'cloning')] });- getBrainLink.mockImplementation(async (id) => {- if (id === 'a') throw Object.assign(new Error('Server unreachable'), { status: 503 });- return link('c', 'cloned');+ it('retains failed records, removes deleted records and merges only clone progress', async () => {+ getBrainLinks.mockResolvedValue({ links: [+ link('a', 'cloning'), link('b', 'cloning'),+ link('c', 'cloning', { title: 'renamed-locally' })+ ] });+ getBrainLink.mockImplementation(async id => {+ if (id === 'a') throw Object.assign(new Error('Unavailable'), { status: 503 });+ if (id === 'b') throw Object.assign(new Error('Gone'), { status: 404 });+ return link('c', 'cloned', { localPath: '/repos/example' });});await renderTab();-- await tick();- expect(screen.getByText('Cloning...')).toBeTruthy();- expect(screen.getByText('Cloned')).toBeTruthy();+ await invalidate('a', 'b', 'c');expect(screen.getByText('repo-a')).toBeTruthy();- expect(screen.getByText('repo-c')).toBeTruthy();- });-- // Without this the deleted record keeps its slot in the in-flight set and is- // polled every 3s until the stall bound expires.- it('drops a link deleted mid-clone and stops polling it', async () => {- getBrainLinks.mockResolvedValue({ links: [link('a', 'cloning'), link('c', 'cloning')] });- getBrainLink.mockImplementation(async (id) => {- if (id === 'a') throw Object.assign(new Error('Link not found'), { status: 404 });- return link('c', 'cloning');- });- await renderTab();-- await tick();- expect(screen.queryByText('repo-a')).toBeNull();- expect(screen.getByText('repo-c')).toBeTruthy();-- getBrainLink.mockClear();- await tick();- expect(getBrainLink.mock.calls.map(([id]) => id)).toEqual(['c']);- });-- // The poll's job is the clone badge; it must not carry a pre-edit snapshot of- // the rest of the record back over a local change.- it('merges only the clone-progress fields, never the whole record', async () => {- getBrainLinks.mockResolvedValue({ links: [link('a', 'cloning', { title: 'renamed-locally' })] });- getBrainLink.mockResolvedValue(link('a', 'cloned', { title: 'repo-a', localPath: '/repos/a' }));- await renderTab();-- await tick();- expect(screen.getByText('Cloned')).toBeTruthy();- // The clone's own localPath landed…- expect(screen.getByText('repos/a')).toBeTruthy();- // …but the stale title from the same response did not.+ expect(screen.queryByText('repo-b')).toBeNull();expect(screen.getByText('renamed-locally')).toBeTruthy();- expect(screen.queryByText('repo-a')).toBeNull();- });-- it('does not re-render the list from a replaced array when a tick brings no change', async () => {- getBrainLinks.mockResolvedValue({ links: [link('a', 'cloning')] });- getBrainLink.mockResolvedValue(link('a', 'cloning'));- await renderTab();-- const before = bucketBoardRenders;- await tick(9000);- expect(getBrainLink).toHaveBeenCalledTimes(3);- expect(bucketBoardRenders).toBe(before);- });-- // A server restart mid-clone strands the record at `cloning` forever, so an- // unbounded poll would become the tab's permanent steady state.- it('gives up on a clone stuck with no status change past the stall window', async () => {- getBrainLinks.mockResolvedValue({ links: [link('a', 'cloning')] });- getBrainLink.mockResolvedValue(link('a', 'cloning'));- await renderTab();-- await tick(10 * 60 * 1000);- const stalledAt = getBrainLink.mock.calls.length;- expect(stalledAt).toBeGreaterThan(0);-- await tick(60 * 1000);- expect(getBrainLink).toHaveBeenCalledTimes(stalledAt);- // …and says so, rather than spinning on a status nothing is watching.- expect(screen.getByText('Cloning...')).toBeTruthy();- expect(screen.getByText('(stalled)')).toBeTruthy();+ expect(screen.queryByText('repo-c')).toBeNull();+ expect(screen.getByText('Cloned')).toBeTruthy();});- // The stall bound counts ticks, not wall-clock: useAutoRefetch pauses while- // the tab is hidden, so a wall-clock deadline would be tripped by the resume- // tick alone and abandon a clone that may well have finished.- it('does not count time the tab spent hidden against the stall bound', async () => {+ it('reconciles once on reconnect and tab re-show, then detaches on unmount', async () => {getBrainLinks.mockResolvedValue({ links: [link('a', 'cloning')] });- getBrainLink.mockResolvedValue(link('a', 'cloning'));- await renderTab();-- const hidden = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');- await tick(20 * 60 * 1000);+ const view = await renderTab();+ getBrainLinks.mockResolvedValue({ links: [link('a', 'cloned')] });+ await act(async () => { socket.emit('connect'); });+ expect(getBrainLinks).toHaveBeenCalledTimes(2);+ expect(screen.getByText('Cloned')).toBeTruthy();+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });+ await invalidate('a');expect(getBrainLink).not.toHaveBeenCalled();-- hidden.mockReturnValue('visible');+ visibility.mockReturnValue('visible');await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });- expect(getBrainLink).toHaveBeenCalledTimes(1);- expect(screen.queryByText('(stalled)')).toBeNull();- hidden.mockRestore();- });-- // The post-clone intake writes these in a second update, right after the- // status flips — the poll has to carry them or the chips never appear.- it('carries the post-clone intake fields through', async () => {- getBrainLinks.mockResolvedValue({ links: [link('a', 'cloning')] });- getBrainLink.mockResolvedValue(link('a', 'cloning', {- malwareScan: { reportId: '11111111-1111-4111-8111-111111111111', status: 'queued' },- }));- await renderTab();-- await tick();- expect(screen.getByTitle(/Malware scan queued/)).toBeTruthy();-- // …and an unchanged object on the next tick is not treated as a change.- const renders = bucketBoardRenders;- await tick();- expect(bucketBoardRenders).toBe(renders);- });-- it('restarts the stall window when a clone actually progresses', async () => {- getBrainLinks.mockResolvedValue({ links: [link('a', 'pending')] });- getBrainLink.mockResolvedValue(link('a', 'pending'));- await renderTab();-- await tick(9 * 60 * 1000);- getBrainLink.mockResolvedValue(link('a', 'cloning'));- await tick();- expect(screen.getByText('Cloning...')).toBeTruthy();-- // Without the reset the window would have expired 2 minutes in; the status- // change bought a fresh 10 minutes.- getBrainLink.mockResolvedValue(link('a', 'cloning'));- const beforeExtra = getBrainLink.mock.calls.length;- await tick(3 * 60 * 1000);- expect(getBrainLink.mock.calls.length).toBeGreaterThan(beforeExtra);+ expect(getBrainLinks).toHaveBeenCalledTimes(3);+ expect(getBrainBuckets).toHaveBeenCalledTimes(3);+ visibility.mockRestore();+ view.unmount();+ await invalidate('a');+ expect(getBrainLink).not.toHaveBeenCalled();});});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 381d948c7b..c38b829e8b 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -88,7 +88,7 @@ grep -i "what you want to do" client/src/hooks/README.md| Hook | Purpose | Use when ||---|---|---|| `useCosTaskUpdates` | Shared five-event CoS task lifecycle subscription; re-subscribes on socket reconnect and forwards normalized task updates to the current callback. | A CoS task surface with its own task-status reducer. |-| `useSocketResource` | Initial resource read plus room-event, reconnect and tab-show reconciliation; single-flight reads, identity guards and immediate mutation updates. | Views replacing content polls with existing socket invalidations. |+| `useSocketResource` | Initial resource read plus room/broadcast event, reconnect and tab-show reconciliation; single-flight reads, identity guards and immediate mutation updates. | Views replacing content polls with existing socket invalidations. || `useSocketSubscription` | Refcounted `<namespace>:subscribe`/`unsubscribe` for a `registerSubscriber` room: the first mounted consumer subscribes and re-emits on every socket reconnect, the last to unmount unsubscribes, and `onResubscribe` refetches whatever a consumer may have missed while disconnected. | Any hook/page that emits a literal `<ns>:subscribe` for `cos`/`errors`/`notifications`/`agents`/`instances`/`loops`/`beeper` — don't hand-roll the reconnect dance; `client/src/socketSubscriptionConventions.test.js` enforces this. || `useAccountSyncStatus` | Per-account busy/auth state and deduplicated HTTP/socket sync outcomes. | Calendar and Messages sync controls. || `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 20725724d8..315edb2869 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -246,4 +246,5 @@ export * from './useActionQueue.js';export * from './usePagedCollection.js';export * from './useGoalOrganize.js';+export * from './useSocketResource.js';diff --git a/client/src/hooks/useSocketResource.js b/client/src/hooks/useSocketResource.jsindex 6ac26bb8de..3f9843bda7 100644--- a/client/src/hooks/useSocketResource.js+++ b/client/src/hooks/useSocketResource.js@@ -7,14 +7,18 @@ const visible = () => document.visibilityState !== 'hidden';/*** Read once, then reconcile a resource on room events, reconnect and tab show.+ * Omit namespace for globally broadcast events. fetchFn receives+ * { reconcile, events: [{ event, payload }] } for targeted invalidation reads.* Keep events stable (module-level). fetchFn returns data without setting state.* resourceKey cancels old reads; updateData applies mutation responses and* prevents an older in-flight read from overwriting them.*/-export function useSocketResource(fetchFn, { namespace, events, resourceKey = null, matchesEvent = () => true }) {+export function useSocketResource(fetchFn, { namespace, events, resourceKey = null, matchesEvent = () => true, compare }) {const [state, setState] = useState({ key: resourceKey, data: null, loading: true, error: null });const fetchRef = useRef(fetchFn);const matchesRef = useRef(matchesEvent);+ const compareRef = useRef(compare);+ compareRef.current = compare;fetchRef.current = fetchFn;matchesRef.current = matchesEvent;const controller = useRef(null);@@ -29,7 +33,11 @@ export function useSocketResource(fetchFn, { namespace, events, resourceKey = nulet pending = null;let dirty = false;let revision = 0;- const read = () => {+ let reconcile = false;+ let invalidations = [];+ const read = (invalidation = null) => {+ if (invalidation) invalidations.push(invalidation);+ else reconcile = true;if (disposed) return Promise.resolve();if (pending) {dirty = true;@@ -41,9 +49,16 @@ export function useSocketResource(fetchFn, { namespace, events, resourceKey = nudo {dirty = false;const started = revision;- await Promise.resolve().then(() => fetchRef.current()).then(data => {+ const request = { reconcile, events: invalidations };+ reconcile = false;+ invalidations = [];+ await Promise.resolve().then(() => fetchRef.current(request)).then(data => {if (!disposed && started === revision) {- setState({ key: resourceKey, data, loading: false, error: null });+ setState(previous => ({+ key: resourceKey,+ data: compareRef.current?.(previous.data, data) ? previous.data : data,+ loading: false, error: null+ }));}}, error => {if (!disposed && started === revision) {@@ -64,15 +79,23 @@ export function useSocketResource(fetchFn, { namespace, events, resourceKey = nu},};setState({ key: resourceKey, data: null, loading: true, error: null });- const invalidate = payload => {- if (visible() && matchesRef.current(payload)) read();- };- for (const event of events) socket.on(event, invalidate);+ const handlers = events.map(event => {+ const invalidate = payload => {+ if (visible() && matchesRef.current(payload, event)) read({ event, payload });+ };+ socket.on(event, invalidate);+ return [event, invalidate];+ });+ // Broadcast domains have no subscription room. Room consumers already+ // reconcile through useSocketSubscription, so never attach both paths.+ const reconnect = () => { if (visible()) read(); };+ if (!namespace) socket.on('connect', reconnect);if (visible()) read();return () => {disposed = true;controller.current = null;- for (const event of events) socket.off(event, invalidate);+ for (const [event, handler] of handlers) socket.off(event, handler);+ if (!namespace) socket.off('connect', reconnect);};}, [namespace, events, resourceKey]);diff --git a/client/src/hooks/useSocketSubscription.js b/client/src/hooks/useSocketSubscription.jsindex 9949b44d78..3f4ed1b359 100644--- a/client/src/hooks/useSocketSubscription.js+++ b/client/src/hooks/useSocketSubscription.js@@ -45,6 +45,8 @@ function getEntry(namespace) {* redundant refetch in the common case (mount while already-connecting,* HTTP fetch already fresh) — cheap next to silently missing a real miss.*+ * Pass no namespace for broadcast-only consumers; no room is acquired.+ ** @param {string} namespace - a namespace registered server-side via* `registerSubscriber` (e.g. 'notifications', 'errors', 'instances', 'loops').* @param {{ onResubscribe?: () => void }} [options]@@ -54,6 +56,7 @@ export function useSocketSubscription(namespace, { onResubscribe } = {}) {onResubscribeRef.current = onResubscribe;useEffect(() => {+ if (!namespace) return;const entry = getEntry(namespace);const callback = () => onResubscribeRef.current?.();diff --git a/client/src/pages/Brain.jsx b/client/src/pages/Brain.jsxindex 9bcb596763..b2c1238669 100644--- a/client/src/pages/Brain.jsx+++ b/client/src/pages/Brain.jsx@@ -5,7 +5,7 @@ import {Brain as BrainIcon} from 'lucide-react';import PageSkeleton from '../components/ui/PageSkeleton';import PageHeader from '../components/PageHeader';import TabPills from '../components/ui/TabPills';-import { useAutoRefetch } from '../hooks/useAutoRefetch';+import { useSocketResource } from '../hooks/useSocketResource';import { sameJsonShape } from '../lib/sameJsonShape';import { TABS, FULL_BLEED_TAB_IDS } from '../components/brain/constants';@@ -29,6 +29,8 @@ const SpotifyTab = lazy(() => import('../components/brain/tabs/SpotifyTab'));const YoutubeTab = lazy(() => import('../components/brain/tabs/YoutubeTab'));const ThreadsTab = lazy(() => import('../components/brain/tabs/ThreadsTab'));+const BRAIN_EVENTS = ['brain:changed'];+export default function Brain() {const { tab } = useParams();const navigate = useNavigate();@@ -38,9 +40,7 @@ export default function Brain() {// is derived from the TABS registry so it can't drift from the tab list.const fullBleed = FULL_BLEED_TAB_IDS.has(activeTab);- // Let errors throw — `useAutoRefetch` preserves the last-good data on- // transient failures. `silent: true` keeps the 30s poll from spamming- // toasts when a single blip would otherwise fire two of them.+ // Preserve the last good snapshot when a reconciliation read fails.const fetchData = useCallback(async () => {const [summary, settings] = await Promise.all([api.getBrainSummary({ silent: true }),@@ -49,7 +49,8 @@ export default function Brain() {return { summary, settings };}, []);- const { data, loading, refetch } = useAutoRefetch(fetchData, 30_000, {+ const { data, loading, refetch } = useSocketResource(fetchData, {+ events: BRAIN_EVENTS,compare: sameJsonShape,});const summary = data?.summary ?? null;diff --git a/client/src/pages/Brain.test.jsx b/client/src/pages/Brain.test.jsxindex 8de9b36719..d4b0d26a86 100644--- a/client/src/pages/Brain.test.jsx+++ b/client/src/pages/Brain.test.jsx@@ -10,6 +10,12 @@ const api = vi.hoisted(() => ({getBrainSettings: vi.fn(),}));+vi.mock('../services/socket', async () => {+ const { EventEmitter } = await import('node:events');+ return { default: new EventEmitter() };+});+import socket from '../services/socket';+vi.mock('../services/api', () => api);// Keep this suite scoped to the tab bar itself — each lazy tab body has its@@ -73,3 +79,26 @@ describe('Brain mobile tab navigation', () => {expect(await screen.findByTestId('memory-tab')).toBeInTheDocument();});});++it('updates its summary from events without polling and reconciles once on reconnect', async () => {+ await renderSettledAt('links');+ vi.useFakeTimers();+ try {+ await act(async () => { await vi.advanceTimersByTimeAsync(90_000); });+ expect(api.getBrainSummary).toHaveBeenCalledTimes(1);+ api.getBrainSummary.mockResolvedValue({ counts: { links: 7 }, needsReview: 2 });+ await act(async () => { socket.emit('brain:changed', { type: 'links', id: 'example' }); });+ expect(screen.getByText('7 links')).toBeInTheDocument();+ expect(screen.getByText('2 needs review')).toBeInTheDocument();+ await act(async () => { socket.emit('connect'); });+ expect(api.getBrainSummary).toHaveBeenCalledTimes(3);+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });+ visibility.mockReturnValue('visible');+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });+ expect(api.getBrainSummary).toHaveBeenCalledTimes(4);+ visibility.mockRestore();+ } finally {+ vi.useRealTimers();+ }+});diff --git a/client/src/pages/BrainScanReport.jsx b/client/src/pages/BrainScanReport.jsxindex 115e0ae08e..d813c69fa7 100644--- a/client/src/pages/BrainScanReport.jsx+++ b/client/src/pages/BrainScanReport.jsx@@ -4,7 +4,9 @@ import { ArrowLeft, FileText, RefreshCw, ShieldAlert, ShieldCheck, Skull } fromimport * as api from '../services/api';import MarkdownOutput from '../components/cos/MarkdownOutput';import PageSkeleton from '../components/ui/PageSkeleton';-import { useAutoRefetch } from '../hooks/useAutoRefetch';+import { useSocketResource } from '../hooks/useSocketResource';++const REPORT_EVENTS = ['brain:links:changed'];const VERDICT_STYLES = {CLEAN: { Icon: ShieldCheck, className: 'bg-port-success/15 text-port-success border-port-success/30' },@@ -35,7 +37,10 @@ function ScanReportForLink({ id }) {]);return { id, link, report };}, [id]);- const { data, loading, refetch } = useAutoRefetch(fetchReport, 30_000);+ const { data, loading, refetch } = useSocketResource(fetchReport, {+ events: REPORT_EVENTS,+ matchesEvent: payload => payload?.id === id+ });if (loading || (data && data.id !== id)) {return (<Shell>diff --git a/client/src/pages/BrainScanReport.test.jsx b/client/src/pages/BrainScanReport.test.jsxindex 40a37d01c9..a548e64943 100644--- a/client/src/pages/BrainScanReport.test.jsx+++ b/client/src/pages/BrainScanReport.test.jsx@@ -2,6 +2,12 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { act, render, screen, waitFor } from '@testing-library/react';import { MemoryRouter, Routes, Route, useNavigate } from 'react-router';+vi.mock('../services/socket', async () => {+ const { EventEmitter } = await import('node:events');+ return { default: new EventEmitter() };+});+import socket from '../services/socket';+vi.mock('../services/api', () => ({getBrainLink: vi.fn(),getBrainScanReport: vi.fn(),@@ -112,3 +118,40 @@ describe('BrainScanReport', () => {expect(screen.queryByText('First link')).not.toBeInTheDocument();});});++it('filters scan events, coalesces mid-read changes, and reconciles without polling', async () => {+ api.getBrainLink.mockResolvedValue({ title: 'Example Link', url: 'https://example.com' });+ api.getBrainScanReport.mockResolvedValue('Initial report');+ await renderPage();+ vi.useFakeTimers();+ try {+ await act(async () => { await vi.advanceTimersByTimeAsync(90_000); });+ expect(api.getBrainScanReport).toHaveBeenCalledTimes(1);+ await act(async () => { socket.emit('brain:links:changed', { id: 'other' }); });+ expect(api.getBrainScanReport).toHaveBeenCalledTimes(1);+ let resolveRead;+ api.getBrainScanReport.mockReturnValueOnce(new Promise(resolve => { resolveRead = resolve; }));+ await act(async () => { socket.emit('brain:links:changed', { id: 'abc' }); });+ api.getBrainScanReport.mockResolvedValue('Completed report');+ await act(async () => {+ socket.emit('brain:links:changed', { id: 'abc' });+ socket.emit('brain:links:changed', { id: 'abc' });+ });+ expect(api.getBrainScanReport).toHaveBeenCalledTimes(2);+ await act(async () => { resolveRead('Earlier report'); });+ expect(api.getBrainScanReport).toHaveBeenCalledTimes(3);+ expect(screen.getByTestId('markdown')).toHaveTextContent('Completed report');+ api.getBrainScanReport.mockRejectedValueOnce(new Error('Unavailable'));+ await act(async () => { socket.emit('connect'); });+ expect(api.getBrainScanReport).toHaveBeenCalledTimes(4);+ expect(screen.getByTestId('markdown')).toHaveTextContent('Completed report');+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });+ visibility.mockReturnValue('visible');+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });+ expect(api.getBrainScanReport).toHaveBeenCalledTimes(5);+ visibility.mockRestore();+ } finally {+ vi.useRealTimers();+ }+});diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex 81cf8b6de3..3bb33fd3bc 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -26,6 +26,17 @@ const input = (schema, summary) => Object.freeze({});export const SOCKET_EVENT_CONTRACTS = Object.freeze({+ 'brain:changed': {+ direction: 'server-to-client',+ summary: 'Invalidate Brain summary/settings after a persisted change.',+ payloadSchema: { type: 'object', properties: { type: { type: 'string' }, id: { type: 'string' } }, required: ['type'], additionalProperties: false },+ },+ 'brain:links:changed': {+ direction: 'server-to-client',+ summary: 'Invalidate one link including clone progress and scan-report completion.',+ payloadSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false },+ },+'app:deploy': input(appDeploySchema, 'Deploy a managed app with allowlisted flags.'),'app:standardize': input(appStandardizeSchema, 'Standardize one registered app.'),'app:update': input(appUpdateSchema, 'Run the update lifecycle for one registered app.'),diff --git a/server/services/socket.js b/server/services/socket.jsindex c5b7b476e3..fd6238e617 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -9,7 +9,7 @@ import { platformAccountEvents } from './platformAccounts.js';import { updateEvents } from './updateChecker.js';import { scheduleEvents } from './automationScheduler.js';import { activityEvents } from './agentActivity.js';-import { brainEvents } from './brainStorage.js';+import { brainEvents, BRAIN_ENTITY_TYPES } from './brainStorage.js';import { moltworldWsEvents } from './moltworldWs.js';import { beeperSocketEvents } from './beeperSocketEvents.js';import { queueEvents } from './moltworldQueue.js';@@ -512,6 +512,18 @@ function setupAgentEventForwarding() {// Set up brain event forwarding - broadcast to all clientsfunction setupBrainEventForwarding() {+ // Invalidation only: record bodies, local paths and settings stay behind HTTP.+ const changed = (type, id) => {+ ioInstance?.emit('brain:changed', { type, id });+ if (type === 'links') ioInstance?.emit('brain:links:changed', { id });+ };+ for (const type of BRAIN_ENTITY_TYPES) {+ brainEvents.on(`${type}:upserted`, ({ id }) => changed(type, id));+ brainEvents.on(`${type}:deleted`, ({ id }) => changed(type, id));+ }+ brainEvents.on('record:changed', ({ type, id }) => changed(type, id));+ brainEvents.on('meta:changed', () => changed('meta'));+brainEvents.on('classified', (data) => {if (ioInstance) {ioInstance.emit('brain:classified', data);diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex ae1ad2550b..cc949a367f 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -3,7 +3,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// Preserve installed once-only listeners across Vitest's per-test mock-call// clearing, just as the process-wide event buses retain their subscriptions.-const queueListeners = vi.hoisted(() => ({ cos: [], review: [] }));+const queueListeners = vi.hoisted(() => ({ cos: [], review: [], brain: [] }));/*** Tests for socket.js initSocket behavior.@@ -35,7 +35,7 @@ vi.mock('./updateChecker.js', () => ({ updateEvents: { on: vi.fn() } }));vi.mock('../lib/buildId.js', () => ({ getBuildId: vi.fn(() => 'test-build-id') }));vi.mock('./automationScheduler.js', () => ({ scheduleEvents: { on: vi.fn() } }));vi.mock('./agentActivity.js', () => ({ activityEvents: { on: vi.fn() } }));-vi.mock('./brainStorage.js', () => ({ brainEvents: { on: vi.fn() } }));+vi.mock('./brainStorage.js', () => ({ BRAIN_ENTITY_TYPES: ['links', 'inbox', 'memories'], brainEvents: { on: vi.fn((...args) => queueListeners.brain.push(args)) } }));vi.mock('./moltworldWs.js', () => ({ moltworldWsEvents: { on: vi.fn() } }));vi.mock('./moltworldQueue.js', () => ({ queueEvents: { on: vi.fn() } }));// The Beeper realtime bus is a real EventEmitter here — the relay boundary test@@ -145,6 +145,25 @@ describe('socket.js — initSocket', () => {authEvents.removeAllListeners('sessions:revoked-all');});+ it('forwards persisted Brain changes as bounded invalidations', () => {+ const dispatch = (event, payload) => {+ const listener = queueListeners.brain.find(([name]) => name === event)?.[1];+ expect(listener).toBeTypeOf('function');+ listener(payload);+ };+ io.emitted.length = 0;+ dispatch('links:upserted', { id: 'example-link', record: { localPath: '/private/example', malwareScan: { status: 'completed' } } });+ expect(io.emitted).toEqual([+ ['brain:changed', { type: 'links', id: 'example-link' }],+ ['brain:links:changed', { id: 'example-link' }]+ ]);+ io.emitted.length = 0;+ dispatch('record:changed', { type: 'links', id: 'remote-link' });+ dispatch('meta:changed', { defaultProvider: 'example' });+ expect(io.emitted).toContainEqual(['brain:links:changed', { id: 'remote-link' }]);+ expect(io.emitted).toContainEqual(['brain:changed', { type: 'meta', id: undefined }]);+ });+beforeEach(() => {vi.mocked(detachSocketSessions).mockClear();vi.mocked(registerVoiceHandlers).mockClear();