Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(brain): retry a failed graph load automatically, with bounded backoff

M3gA-Mind8b20eb528496
diff --git a/app/src/pages/Brain.tsx b/app/src/pages/Brain.tsx
index 8e233e6f35..ae4eea8442 100644
--- a/app/src/pages/Brain.tsx
+++ b/app/src/pages/Brain.tsx
@@ -39,6 +39,16 @@ const navIcon = (d: string) => (
const BRAIN_TABS: readonly BrainTab[] = ['welcome', 'graph', 'goals', 'sources', 'sync'];
+/**
+ * Backoff ladder for automatically retrying a failed graph load.
+ *
+ * Written out rather than computed from an exponent because the two things a
+ * reader needs — how long the wait is, and that there are exactly three of
+ * them — are then both visible. The last element is the bound: once the ladder
+ * is spent the error stays on screen and manual Refresh is the way back.
+ */
+const RETRY_DELAYS_MS: readonly number[] = [2_000, 4_000, 8_000];
+
/**
* Canonical text header (title + one-line description) per functional tab.
*/
@@ -93,8 +103,22 @@ export default function Brain() {
useEffect(() => {
let cancelled = false;
+ // The pending automatic retry, if one is scheduled. Effect-scoped, so a
+ // dependency change or an unmount cancels it in the cleanup below.
+ let retryTimer: ReturnType<typeof setTimeout> | undefined;
+ // Index into RETRY_DELAYS_MS. Effect-scoped too, which is what makes a
+ // manual Refresh (a `refreshKey` change re-runs this effect) start the
+ // ladder over rather than inheriting a spent one.
+ let attempt = 0;
+
const load = async () => {
- console.debug('[brain] graph fetch: entry mode=%s', mode);
+ // Any load supersedes a retry still waiting, so a manual Refresh or a
+ // `memory-tree-completed` event cannot race a timer into a double fetch.
+ if (retryTimer !== undefined) {
+ clearTimeout(retryTimer);
+ retryTimer = undefined;
+ }
+ console.debug('[brain] graph fetch: entry mode=%s attempt=%d', mode, attempt);
setError(null);
try {
const resp = await memoryTreeGraphExport(mode);
@@ -114,10 +138,28 @@ export default function Brain() {
// this PR was invisible, and with the warning below would be a FALSE
// "your data is stale" on data that is not.
setError(null);
+ // Success resets the ladder: the NEXT transient failure gets the full
+ // set of retries rather than resuming where an old failure left off.
+ attempt = 0;
} catch (err) {
if (cancelled) return;
console.error('[brain] graph fetch failed', err);
setError(err instanceof Error ? err.message : String(err));
+
+ const delay = RETRY_DELAYS_MS[attempt];
+ if (delay === undefined) {
+ // Bounded on purpose. Past this point the failure is very unlikely to
+ // be transient, and retrying forever would hammer the core and hide a
+ // real outage behind a spinner. The error stays on screen and the
+ // manual Refresh in `MemoryControls` remains the way back.
+ console.warn('[brain] graph fetch: retries exhausted after %d attempts', attempt);
+ return;
+ }
+ console.debug('[brain] graph fetch: scheduling retry %d in %dms', attempt + 1, delay);
+ attempt += 1;
+ retryTimer = setTimeout(() => {
+ void load();
+ }, delay);
}
};
void load();
@@ -128,6 +170,7 @@ export default function Brain() {
window.addEventListener('openhuman:memory-tree-completed', onTreeDone);
return () => {
cancelled = true;
+ if (retryTimer !== undefined) clearTimeout(retryTimer);
window.removeEventListener('openhuman:memory-tree-completed', onTreeDone);
};
// `authUserId` is a dependency so a logout→login (identity becomes
diff --git a/app/src/pages/__tests__/Brain.autoRetry.test.tsx b/app/src/pages/__tests__/Brain.autoRetry.test.tsx
new file mode 100644
index 0000000000..610ed7bce9
--- /dev/null
+++ b/app/src/pages/__tests__/Brain.autoRetry.test.tsx
@@ -0,0 +1,218 @@
+/**
+ * Brain graph — AUTOMATIC recovery from a transient failure (#5904).
+ *
+ * `Brain.errorRecovery.test.tsx` covers recovery that a user or an in-product
+ * event triggers: manual Refresh, and the `openhuman:memory-tree-completed`
+ * listener. Neither is automatic — before #5904 a failed load simply stayed
+ * failed until something else happened, so a blip during a background refresh
+ * left the panel stuck until the user noticed and pressed a button.
+ *
+ * What is pinned here is the ladder in `Brain.tsx` (`RETRY_DELAYS_MS`):
+ * retries fire on their own, they are BOUNDED, a success resets them, and a
+ * pending one is cancelled on unmount.
+ *
+ * Timers are faked because the delays are seconds long; `advanceTimersByTimeAsync`
+ * is used rather than `advanceTimersByTime` so the promise inside each retry
+ * settles before the assertion reads the call count.
+ */
+import { act, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { renderWithProviders } from '../../test/test-utils';
+import Brain from '../Brain';
+
+const graphExportMock = vi.hoisted(() => vi.fn());
+// Controllable authenticated identity so we can simulate a logout→login cycle
+// (userId null → set) and assert the graph reloads (#4149).
+const coreAuthRef = vi.hoisted(() => ({ current: 'user-A' as string | null }));
+const navigateSpy = vi.hoisted(() => vi.fn());
+
+vi.mock('react-router-dom', async importOriginal => {
+ const actual = await importOriginal<typeof import('react-router-dom')>();
+ return { ...actual, useNavigate: () => navigateSpy };
+});
+
+vi.mock('../../utils/tauriCommands', () => ({
+ memoryTreeGraphExport: graphExportMock,
+ isTauri: () => false,
+}));
+
+vi.mock('../../providers/CoreStateProvider', () => ({
+ useCoreState: () => ({
+ snapshot: {
+ auth: { userId: coreAuthRef.current, isAuthenticated: coreAuthRef.current != null },
+ },
+ }),
+}));
+
+vi.mock('../../components/intelligence/MemoryGraph', async () => {
+ const React = await import('react');
+ return {
+ MemoryGraph: ({ nodes }: { nodes: unknown[] }) =>
+ React.createElement('div', { 'data-testid': 'memory-graph' }, `nodes:${nodes.length}`),
+ };
+});
+
+vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
+
+vi.mock('../../components/layout/ChipTabs', async () => {
+ const React = await import('react');
+ return {
+ default: ({ children }: { children?: React.ReactNode }) =>
+ React.createElement('div', null, children),
+ };
+});
+vi.mock('../../components/ui/BetaBanner', () => ({ default: () => null }));
+vi.mock('../../components/intelligence/MemoryControls', () => ({ MemoryControls: () => null }));
+vi.mock('../../components/intelligence/MemoryTreeStatusPanel', async () => {
+ const React = await import('react');
+ return {
+ MemoryTreeStatusPanel: () => React.createElement('div', { 'data-testid': 'brain-sync' }),
+ };
+});
+vi.mock('../../components/intelligence/MemorySourcesRegistry', async () => {
+ const React = await import('react');
+ return {
+ MemorySourcesRegistry: () => React.createElement('div', { 'data-testid': 'brain-sources' }),
+ };
+});
+vi.mock('../../components/intelligence/Toast', () => ({ ToastContainer: () => null }));
+vi.mock('../../components/intelligence/SyncAuditPanel', async () => {
+ const React = await import('react');
+ return {
+ SyncAuditPanel: () => React.createElement('div', { 'data-testid': 'brain-sync-audit' }),
+ };
+});
+
+const makeGraph = (n: number) => ({
+ nodes: Array.from({ length: n }, (_, i) => ({ id: `n${i}`, kind: 'summary', label: `N${i}` })),
+ edges: [],
+ content_root_abs: '/tmp/content',
+});
+
+/** Mirrors `RETRY_DELAYS_MS` in `Brain.tsx`. */
+const RETRY_DELAYS_MS = [2_000, 4_000, 8_000];
+const TOTAL_LADDER_MS = RETRY_DELAYS_MS.reduce((a, b) => a + b, 0);
+
+const renderBrain = async () => {
+ await act(async () => {
+ renderWithProviders(<Brain />, { initialEntries: ['/?tab=graph'] });
+ });
+};
+
+describe('Brain graph — automatic retry', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // `clearAllMocks` clears CALLS but not implementations, and several tests
+ // here set a persistent `mockRejectedValue`. Without an explicit reset that
+ // rejection leaks into the next test and silently changes its call counts.
+ graphExportMock.mockReset();
+ coreAuthRef.current = 'user-A';
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it('retries a failed load on its own, with no user action', async () => {
+ graphExportMock
+ .mockRejectedValueOnce(new Error('transient blip'))
+ .mockResolvedValue(makeGraph(2));
+
+ await renderBrain();
+ // One attempt so far, and it failed.
+ expect(graphExportMock).toHaveBeenCalledTimes(1);
+ expect(screen.queryByTestId('memory-graph')).not.toBeInTheDocument();
+
+ // Nothing is dispatched and nothing is clicked — only time passes.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(RETRY_DELAYS_MS[0]);
+ });
+
+ expect(graphExportMock).toHaveBeenCalledTimes(2);
+ expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:2');
+ });
+
+ it('does not fire the retry before its delay has elapsed', async () => {
+ // Otherwise "it retried" could be satisfied by an immediate re-fetch loop,
+ // which is the thing a backoff exists to prevent.
+ graphExportMock.mockRejectedValue(new Error('down'));
+
+ await renderBrain();
+ expect(graphExportMock).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(RETRY_DELAYS_MS[0] - 1);
+ });
+ expect(graphExportMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops after the ladder is exhausted rather than retrying forever', async () => {
+ graphExportMock.mockRejectedValue(new Error('backend is down'));
+
+ await renderBrain();
+
+ // Walk the whole ladder: 1 initial attempt + one per delay.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(TOTAL_LADDER_MS);
+ });
+ expect(graphExportMock).toHaveBeenCalledTimes(1 + RETRY_DELAYS_MS.length);
+
+ // Far beyond it, the count must not move. This is the assertion that
+ // distinguishes a bounded ladder from an infinite one.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(TOTAL_LADDER_MS * 10);
+ });
+ expect(graphExportMock).toHaveBeenCalledTimes(1 + RETRY_DELAYS_MS.length);
+ });
+
+ it('resets the ladder after a success, so a later failure retries again', async () => {
+ // Fail, recover on the first retry, then fail again. If `attempt` were not
+ // reset on success the second failure would resume mid-ladder and this
+ // would come out one call short.
+ graphExportMock
+ .mockRejectedValueOnce(new Error('blip one'))
+ .mockResolvedValueOnce(makeGraph(2))
+ .mockRejectedValue(new Error('blip two'));
+
+ await renderBrain();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(RETRY_DELAYS_MS[0]);
+ });
+ expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:2');
+ expect(graphExportMock).toHaveBeenCalledTimes(2);
+
+ // A second failure, triggered the in-product way.
+ await act(async () => {
+ window.dispatchEvent(new Event('openhuman:memory-tree-completed'));
+ });
+ expect(graphExportMock).toHaveBeenCalledTimes(3);
+
+ // The full ladder is available again: 3 more retries on top of that call.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(TOTAL_LADDER_MS);
+ });
+ expect(graphExportMock).toHaveBeenCalledTimes(3 + RETRY_DELAYS_MS.length);
+ });
+
+ it('cancels a pending retry when the panel unmounts', async () => {
+ // A timer that outlives the component would fetch (and setState) against an
+ // unmounted tree.
+ graphExportMock.mockRejectedValue(new Error('down'));
+
+ let unmount!: () => void;
+ await act(async () => {
+ ({ unmount } = renderWithProviders(<Brain />, { initialEntries: ['/?tab=graph'] }));
+ });
+ expect(graphExportMock).toHaveBeenCalledTimes(1);
+
+ unmount();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(TOTAL_LADDER_MS * 2);
+ });
+ expect(graphExportMock).toHaveBeenCalledTimes(1);
+ });
+});