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: make useAutoRefetch single-flight so a slow poll cannot overwrite a newer one (#8272)
[._.]/ Adam Eivyc975c38db0fe
diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsxindex e6da5e73f2..5e79281a7d 100644--- a/client/src/components/brain/tabs/LinksTab.jsx+++ b/client/src/components/brain/tabs/LinksTab.jsx@@ -180,10 +180,8 @@ export default function LinksTab({ onRefresh }) {const inFlightKey = inFlight.map(l => `${l.id}:${l.cloneStatus}`).join('|');const [stalledPollKey, setStalledPollKey] = useState(null);- // Ticks since the in-flight set last moved, and a monotonic id so a slow- // response can't land on top of a newer one.+ // Ticks since the in-flight set last moved.const noProgressTicksRef = useRef(0);- const pollGenerationRef = useRef(0);useEffect(() => {noProgressTicksRef.current = 0;}, [inFlightKey]);@@ -196,16 +194,12 @@ export default function LinksTab({ onRefresh }) {return;}noProgressTicksRef.current += 1;- const generation = ++pollGenerationRef.current;// 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 }))));- // A response slower than the interval would otherwise patch a finished- // clone back to `cloning`, restarting the poll and the stall count.- if (generation !== pollGenerationRef.current) return;const byId = new Map(settled.map(r => [r.id, r]));setLinks(prev => {let changed = false;diff --git a/client/src/components/brain/tabs/LinksTab.test.jsx b/client/src/components/brain/tabs/LinksTab.test.jsxindex 8e40764f73..853e95c021 100644--- a/client/src/components/brain/tabs/LinksTab.test.jsx+++ b/client/src/components/brain/tabs/LinksTab.test.jsx@@ -246,26 +246,6 @@ describe('LinksTab clone-status polling', () => {hidden.mockRestore();});- it('ignores a poll response overtaken by a newer one', async () => {- getBrainLinks.mockResolvedValue({ links: [link('a', 'cloning')] });- // The first tick's response resolves only after the second tick's has been- // applied — it must not patch the finished clone back to `cloning`.- let release;- const slow = new Promise(resolve => { release = resolve; });- getBrainLink- .mockImplementationOnce(async () => { await slow; return link('a', 'cloning'); })- .mockResolvedValue(link('a', 'cloned', { localPath: '/repos/a' }));- await renderTab();-- await tick();- await tick();- expect(screen.getByText('Cloned')).toBeTruthy();-- await act(async () => { release(); await Promise.resolve(); });- expect(screen.getByText('Cloned')).toBeTruthy();- expect(screen.queryByText('Cloning...')).toBeNull();- });-// 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 () => {diff --git a/client/src/components/instances/TailcatServePanel.test.jsx b/client/src/components/instances/TailcatServePanel.test.jsxindex a1800bb933..4f2cc0d138 100644--- a/client/src/components/instances/TailcatServePanel.test.jsx+++ b/client/src/components/instances/TailcatServePanel.test.jsx@@ -99,20 +99,3 @@ it('does not overwrite a start receipt with an older in-flight status read', asyawait act(async () => resolveRead(stopped));expect(screen.getByRole('button', { name: 'Stop' })).toBeInTheDocument();});--it('keeps the newest status when visibility refreshes overlap', async () => {- let resolveOld;- getTailcatServe.mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve; }))- .mockResolvedValue({ ...stopped, status: 'failed', lastError: 'Process exited' });- render(<TailcatServePanel />);- await act(async () => {- Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });- document.dispatchEvent(new Event('visibilitychange'));- Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });- document.dispatchEvent(new Event('visibilitychange'));- });- expect(await screen.findByText('Process exited')).toBeInTheDocument();- await act(async () => resolveOld(serving));- expect(screen.getByText('Process exited')).toBeInTheDocument();- expect(screen.queryByRole('button', { name: 'Stop' })).not.toBeInTheDocument();-});diff --git a/client/src/components/instances/TailcatServeProvider.jsx b/client/src/components/instances/TailcatServeProvider.jsxindex 30bda0432f..b0ecee5326 100644--- a/client/src/components/instances/TailcatServeProvider.jsx+++ b/client/src/components/instances/TailcatServeProvider.jsx@@ -9,13 +9,15 @@ const ServeContext = createContext(null);export function TailcatServeProvider({ children }) {const [status, setStatus] = useState(null);const [busy, setBusy] = useState(false);- const operation = useRef({ busy: false, generation: 0, read: 0 });+ // useAutoRefetch is single-flight, so polls never overlap each other; the+ // generation only has to fence a poll against a mutation that started while+ // it was pending.+ const operation = useRef({ busy: false, generation: 0 });const load = useCallback(async () => {if (operation.current.busy) return;const generation = operation.current.generation;- const read = ++operation.current.read;const data = await getTailcatServe({ silent: true });- if (!operation.current.busy && generation === operation.current.generation && read === operation.current.read) setStatus(data);+ if (!operation.current.busy && generation === operation.current.generation) setStatus(data);}, []);useAutoRefetch(load, 10_000, { pollOnly: true });diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex abe6600885..fa27ad05db 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -109,7 +109,7 @@ grep -i "what you want to do" client/src/hooks/README.md|---|---|---|| `useAnchorReveal` | `useAnchorReveal(getTarget, key, { reveal? })` — scroll a freshly-opened element into view + flash a tint over it; re-fires when `key` changes; no-op when `key` is falsy or `getTarget()` is null. | Reveal an editorial finding's anchored manuscript text on open / prev-next step (#1601). || `useArmedAction` | Two-click-arm `[armed, fire]` confirmation. | Destructive button needing a confirm tap. (Project memory: user finds this less discoverable — prefer inline confirm rows for new UI.) |-| `useAutoRefetch` | Poll-based refetch on an interval. `{ pollOnly: true }` skips internal data/loading state for side-effect-only callers (returns `{ refetch }` only). | Data needs periodic refresh (no socket / SSE available). |+| `useAutoRefetch` | Poll-based refetch on an interval, single-flight per instance (ticks during a pending fetch are dropped; mid-flight `refetch()` calls share one trailing fetch). `{ pollOnly: true }` skips internal data/loading state for side-effect-only callers (returns `{ refetch }` only). | Data needs periodic refresh (no socket / SSE available). || `useSystemActivity` | One shared bounded system-activity snapshot. Socket invalidation coalesces to a single read; reconnect and reshow reconcile missed frames. A failed read stays unknown, never idle. | Update banner and the live-activity widget. GPU samples stay on a visible-only poll — they have no event. || `useAutoSizeTextarea` | `[ref, resize]` — grows a `<textarea>` to fit its content (no scroll / hand-resize); recomputes before paint on value change. | A textarea that should auto-fit content. Prefer the `AutoSizeTextarea` UI component, which wraps this. || `useChartColors` | Resolves the `--port-*` theme tokens (accent/success/warning/error, `chart-1..4`, grid, axis, tooltip surfaces) to concrete `rgb()` strings via `getComputedStyle`, re-resolving on theme switch. | A recharts card needs theme-following colors — SVG `fill`/`stroke` props can't read CSS vars, so pass these resolved strings instead of hardcoded hex. |diff --git a/client/src/hooks/useAutoRefetch.js b/client/src/hooks/useAutoRefetch.jsindex 4fe6395596..ec1ae3e230 100644--- a/client/src/hooks/useAutoRefetch.js+++ b/client/src/hooks/useAutoRefetch.js@@ -20,6 +20,15 @@ import { useVisibilityEvent } from './useVisibilityEvent.js';* Don't call it from effects that fire on mount/route change without a* visibility gate, or the "pauses while hidden" guarantee leaks.*+ * Each hook instance is single-flight: at most one `fetchFn` call is pending+ * at a time, so a slow response can never land after (and overwrite) a newer+ * one, and a stalled request can't pile up a new request per tick. Interval+ * and visibility ticks that arrive while a fetch is pending are dropped. A+ * `refetch()` that arrives while a fetch is pending queues ONE trailing fetch+ * (the pending one may predate the caller's mutation); every `refetch()` made+ * during that window shares the trailing fetch's promise. Unmounting drops a+ * queued trailing fetch — its promise resolves `undefined` without fetching.+ ** @param {Function} fetchFn - async; returns the new data, or any value if* used purely for its side effects (see `pollOnly`).* @param {number} intervalMs - poll cadence; changing restarts the interval.@@ -59,6 +68,13 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {const [error, setError] = useState(null);const fetchRef = useRef(fetchFn);const compareRef = useRef(compare);+ // The pending fetch (`{ promise, owner }`) or null. `owner` is the poll+ // effect's cancellation token for a tick-started fetch, or null for a manual+ // one — see `startFetch`.+ const inFlightRef = useRef(null);+ // A `refetch()` that arrived mid-flight: `{ promise, resolve }`, or null.+ const trailingRef = useRef(null);+ const disposedRef = useRef(false);useEffect(() => {fetchRef.current = fetchFn;@@ -80,25 +96,67 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {});}, [pollOnly]);+ // Runs one fetch as the instance's single in-flight request. A tick-started+ // fetch carries its poll effect's token as `owner`, so a result landing after+ // that effect was torn down (unmount, or `enabled` flipped off) is dropped —+ // unless a newer poll effect adopted it (see `loadData`). A manual fetch has+ // no owner and applies unless the hook unmounted. When it settles, a queued+ // trailing refetch starts, or is abandoned if the hook unmounted meanwhile.+ const startFetch = useCallback(function runFetch(owner) {+ const run = { owner, promise: null };+ const shouldApply = () => !disposedRef.current && !run.owner?.cancelled;+ // Claimed before the call: a fetchFn that throws synchronously settles+ // (and runs `finally`) before the IIFE returns.+ inFlightRef.current = run;+ run.promise = (async () => {+ try {+ const result = await fetchRef.current();+ if (shouldApply()) {+ applyResult(result);+ if (!pollOnly) setLoading(false);+ }+ return result;+ } catch (err) {+ console.warn(`⚠️ Auto-refetch failed: ${err?.message ?? String(err)}`);+ if (shouldApply() && !pollOnly) {+ setLoading(false);+ setError(toFetchError(err));+ }+ return undefined;+ } finally {+ inFlightRef.current = null;+ const trailing = trailingRef.current;+ trailingRef.current = null;+ if (trailing) trailing.resolve(disposedRef.current ? undefined : runFetch(null).promise);+ }+ })();+ return run;+ }, [applyResult, pollOnly]);+// Stable, unconditional refetch for callers (Refresh buttons, post-mutation// refresh paths, and key-change effects that need an immediate fetch with// the new closure). Bypasses the visibility short-circuit — when a user// clicks Refresh the tab is by definition visible.- const refetch = useCallback(async () => {- try {- const result = await fetchRef.current();- applyResult(result);- if (!pollOnly) setLoading(false);- return result;- } catch (err) {- console.warn(`⚠️ Auto-refetch failed: ${err?.message ?? String(err)}`);- if (!pollOnly) {- setLoading(false);- setError(toFetchError(err));- }- return undefined;+ const refetch = useCallback(() => {+ if (!inFlightRef.current) return startFetch(null).promise;+ if (!trailingRef.current) {+ let resolve;+ const promise = new Promise((r) => { resolve = r; });+ trailingRef.current = { promise, resolve };}- }, [applyResult, pollOnly]);+ return trailingRef.current.promise;+ }, [startFetch]);++ useEffect(() => {+ disposedRef.current = false;+ return () => {+ disposedRef.current = true;+ // Drop a queued follow-up now rather than when the pending fetch+ // settles, so nothing fires after unmount.+ trailingRef.current?.resolve(undefined);+ trailingRef.current = null;+ };+ }, []);const loadOnVisibleRef = useRef(null);@@ -108,22 +166,19 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {return undefined;}- let cancelled = false;+ const token = { cancelled: false };- const loadData = async () => {+ const loadData = () => {if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;- try {- const result = await fetchRef.current();- if (cancelled) return;- applyResult(result);- if (!pollOnly) setLoading(false);- } catch (err) {- console.warn(`⚠️ Auto-refetch failed: ${err?.message ?? String(err)}`);- if (!cancelled && !pollOnly) {- setLoading(false);- setError(toFetchError(err));- }+ const pending = inFlightRef.current;+ if (pending) {+ // Coalesce: never stack a second request. A tick-started fetch owned+ // by a torn-down poll effect (StrictMode remount, interval change,+ // enabled re-toggle) is adopted so its result still lands.+ if (pending.owner) pending.owner = token;+ return;}+ startFetch(token);};loadOnVisibleRef.current = loadData;@@ -131,11 +186,11 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {const interval = setInterval(loadData, intervalMs);return () => {- cancelled = true;+ token.cancelled = true;clearInterval(interval);loadOnVisibleRef.current = null;};- }, [intervalMs, enabled, immediate, applyResult, pollOnly]);+ }, [intervalMs, enabled, immediate, startFetch]);useVisibilityEvent((state) => {if (state === 'visible') loadOnVisibleRef.current?.();diff --git a/client/src/hooks/useAutoRefetch.test.jsx b/client/src/hooks/useAutoRefetch.test.jsxindex fe663abedd..db474c852f 100644--- a/client/src/hooks/useAutoRefetch.test.jsx+++ b/client/src/hooks/useAutoRefetch.test.jsx@@ -1,3 +1,4 @@+import { StrictMode } from 'react';import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { renderHook, act, waitFor } from '@testing-library/react';import { useAutoRefetch } from './useAutoRefetch';@@ -10,6 +11,25 @@ const fireVisibilityChange = () => {document.dispatchEvent(new Event('visibilitychange'));};+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++// A fetchFn whose every call stays pending until the test settles it, with a+// live count of overlapping calls.+const deferredFetch = () => {+ const calls = [];+ let active = 0;+ let maxActive = 0;+ const fn = vi.fn(() => {+ active += 1;+ maxActive = Math.max(maxActive, active);+ let resolve;+ const promise = new Promise((r) => { resolve = r; }).finally(() => { active -= 1; });+ calls.push({ resolve });+ return promise;+ });+ return { fn, calls, maxActive: () => maxActive };+};+describe('useAutoRefetch', () => {beforeEach(() => {setVisibility('visible');@@ -332,4 +352,107 @@ describe('useAutoRefetch', () => {expect(result.current.data).toBeNull();expect(compare).not.toHaveBeenCalled();});++ describe('single-flight', () => {+ it('drops interval and visibility ticks while a fetch is pending', async () => {+ const { fn, calls } = deferredFetch();+ const { result } = renderHook(() => useAutoRefetch(fn, 15));+ expect(fn).toHaveBeenCalledTimes(1);++ await sleep(80); // several interval ticks+ act(() => fireVisibilityChange());+ expect(fn).toHaveBeenCalledTimes(1);++ await act(async () => { calls[0].resolve('first'); });+ expect(result.current.data).toBe('first');+ await waitFor(() => expect(fn).toHaveBeenCalledTimes(2)); // polling resumes+ });++ it('coalesces refetches during a pending fetch into one trailing fetch', async () => {+ const { fn, calls, maxActive } = deferredFetch();+ const { result } = renderHook(() => useAutoRefetch(fn, 60_000));+ expect(fn).toHaveBeenCalledTimes(1);++ let p1;+ let p2;+ act(() => {+ p1 = result.current.refetch();+ p2 = result.current.refetch();+ });+ expect(p2).toBe(p1);+ expect(fn).toHaveBeenCalledTimes(1);++ await act(async () => { calls[0].resolve('older'); });+ expect(fn).toHaveBeenCalledTimes(2);+ expect(result.current.data).toBe('older');++ await act(async () => { calls[1].resolve('newer'); });+ await expect(p1).resolves.toBe('newer');+ expect(result.current.data).toBe('newer');+ expect(fn).toHaveBeenCalledTimes(2);+ expect(maxActive()).toBe(1);+ });++ it('serializes pollOnly fetches so side-effect writes land in request order', async () => {+ const { fn, calls, maxActive } = deferredFetch();+ const writes = [];+ const fetchFn = () => fn().then((v) => { writes.push(v); });+ const { result } = renderHook(() => useAutoRefetch(fetchFn, 10, { pollOnly: true }));++ act(() => { result.current.refetch(); });+ await sleep(50);+ expect(fn).toHaveBeenCalledTimes(1);++ await act(async () => { calls[0].resolve(1); });+ await waitFor(() => expect(fn).toHaveBeenCalledTimes(2));+ await act(async () => { calls[1].resolve(2); });+ expect(writes).toEqual([1, 2]);+ expect(maxActive()).toBe(1);+ });++ it('abandons a queued trailing refetch on unmount', async () => {+ const { fn, calls } = deferredFetch();+ const { result, unmount } = renderHook(() => useAutoRefetch(fn, 60_000));+ let trailing;+ act(() => { trailing = result.current.refetch(); });++ unmount();+ await expect(trailing).resolves.toBeUndefined();+ await act(async () => { calls[0].resolve('late'); });+ await sleep(20);+ expect(fn).toHaveBeenCalledTimes(1);+ });++ it('keeps polling after a fetchFn that throws synchronously', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const fetchFn = vi.fn()+ .mockImplementationOnce(() => { throw new Error('sync'); })+ .mockResolvedValue('ok');+ const { result } = renderHook(() => useAutoRefetch(fetchFn, 15));+ await waitFor(() => expect(result.current.data).toBe('ok'));+ warn.mockRestore();+ });++ it('applies the initial fetch under StrictMode remount', async () => {+ const { fn, calls } = deferredFetch();+ const { result } = renderHook(() => useAutoRefetch(fn, 60_000), { wrapper: StrictMode });+ expect(fn).toHaveBeenCalledTimes(1);++ await act(async () => { calls[0].resolve('first'); });+ expect(result.current.data).toBe('first');+ expect(result.current.loading).toBe(false);+ });++ it('drops a pending poll result once polling is disabled', async () => {+ const { fn, calls } = deferredFetch();+ const { result, rerender } = renderHook(+ ({ enabled }) => useAutoRefetch(fn, 60_000, { enabled }),+ { initialProps: { enabled: true } },+ );+ rerender({ enabled: false });++ await act(async () => { calls[0].resolve('stale'); });+ expect(result.current.data).toBeNull();+ });+ });});