Skip to content

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

fix(ui): correct memory engine error alert display

Steven Enamakel731f1a09fba8
diff --git a/app/src/components/intelligence/MemoryEngineRow.tsx b/app/src/components/intelligence/MemoryEngineRow.tsx
index 36882b76c5..1cbe72509f 100644
--- a/app/src/components/intelligence/MemoryEngineRow.tsx
+++ b/app/src/components/intelligence/MemoryEngineRow.tsx
@@ -1,12 +1,8 @@
-import debug from 'debug';
-import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useT } from '../../lib/i18n/I18nContext';
-import { memoryEngineGet, memoryEnginesList } from '../../utils/tauriCommands/memoryEngine';
import { Button } from '../ui';
-
-const log = debug('brain:memory-engine-row');
+import { useMemoryEngine } from './useMemoryEngineCapabilities';
/**
* "Memory engine: <label> · Change" — a one-line summary on the Brain page that
@@ -16,24 +12,8 @@ const log = debug('brain:memory-engine-row');
export default function MemoryEngineRow() {
const { t } = useT();
const navigate = useNavigate();
- const [engine, setEngine] = useState<{ id: string; label: string } | null>(null);
-
- useEffect(() => {
- let cancelled = false;
- void (async () => {
- try {
- const [list, state] = await Promise.all([memoryEnginesList(), memoryEngineGet()]);
- if (cancelled) return;
- const label = list.engines.find(e => e.id === state.driver)?.label ?? state.driver;
- setEngine({ id: state.driver, label });
- } catch (err) {
- log('unavailable: %o', err);
- }
- })();
- return () => {
- cancelled = true;
- };
- }, []);
+ const { id, label } = useMemoryEngine();
+ const engine = id ? { id, label: label ?? id } : null;
if (!engine) return null;
return (
diff --git a/app/src/components/intelligence/MemoryFamilyGate.tsx b/app/src/components/intelligence/MemoryFamilyGate.tsx
index dc8ba7ff7b..7ef719bbf2 100644
--- a/app/src/components/intelligence/MemoryFamilyGate.tsx
+++ b/app/src/components/intelligence/MemoryFamilyGate.tsx
@@ -1,7 +1,7 @@
import type { ReactNode } from 'react';
import { useT } from '../../lib/i18n/I18nContext';
-import { useMemoryEngineCapabilities } from './useMemoryEngineCapabilities';
+import { useMemoryEngine } from './useMemoryEngineCapabilities';
interface MemoryFamilyGateProps {
/** Capability family the wrapped content needs (e.g. `tree`, `goals`). */
@@ -10,15 +10,47 @@ interface MemoryFamilyGateProps {
}
/**
- * Renders `children` when the bound memory engine has `family` (or when that is
- * not yet known), otherwise a friendly "Not available with <engine>" state in
- * place of an error.
+ * Renders `children` when the bound memory engine has `family`, otherwise a
+ * friendly "Not available with <engine>" state in place of an error. While the
+ * engine is still loading it shows a skeleton instead of the children (so a
+ * feature the engine lacks never flashes an error first). When the core cannot
+ * answer at all it fails open. Memory paused on the `null` driver (a failed
+ * engine bind) gates every family.
*/
export default function MemoryFamilyGate({ family, children }: MemoryFamilyGateProps) {
const { t } = useT();
- const { id, label, capabilities } = useMemoryEngineCapabilities();
+ const { loading, id, label, capabilities, current, error } = useMemoryEngine();
- if (!id || !capabilities || capabilities.has(family)) return <>{children}</>;
+ if (loading) {
+ return (
+ <div
+ data-testid="memory-family-loading"
+ aria-busy="true"
+ className="animate-pulse space-y-2 rounded-lg border border-line px-4 py-6">
+ <div className="h-3 w-1/3 rounded bg-line" />
+ <div className="h-3 w-2/3 rounded bg-line" />
+ </div>
+ );
+ }
+
+ if (id === 'null') {
+ return (
+ <div
+ data-testid="memory-family-unavailable"
+ data-family={family}
+ className="rounded-lg border border-line px-4 py-6 text-center">
+ <p className="text-sm font-medium text-content">{t('memoryEngine.paused')}</p>
+ {current?.last_error ? (
+ <p className="mt-1 text-xs text-content-muted">{current.last_error}</p>
+ ) : null}
+ <p className="mt-1 text-xs text-content-muted">{t('memoryEngine.unavailableHint')}</p>
+ </div>
+ );
+ }
+
+ if (error !== null || !id || !capabilities || capabilities.has(family)) {
+ return <>{children}</>;
+ }
const engine = t(`memoryEngine.engine.${id}.label`, label ?? id);
return (
diff --git a/app/src/components/intelligence/useMemoryEngineCapabilities.ts b/app/src/components/intelligence/useMemoryEngineCapabilities.ts
index 9d94e50b88..1020caa6f7 100644
--- a/app/src/components/intelligence/useMemoryEngineCapabilities.ts
+++ b/app/src/components/intelligence/useMemoryEngineCapabilities.ts
@@ -1,52 +1,129 @@
import debug from 'debug';
-import { useEffect, useState } from 'react';
+import { useCallback, useEffect, useState } from 'react';
-import { memoryEngineGet, memoryEnginesList } from '../../utils/tauriCommands/memoryEngine';
+import {
+ type MemoryEngineDescriptor,
+ memoryEngineGet,
+ memoryEnginesList,
+ type MemoryEngineState,
+} from '../../utils/tauriCommands/memoryEngine';
-const log = debug('brain:memory-engine-capabilities');
+const log = debug('brain:memory-engine');
-export interface MemoryEngineCapabilities {
+/** How long a fetched engine snapshot is reused by views mounting close together. */
+export const MEMORY_ENGINE_CACHE_TTL_MS = 5000;
+
+export interface MemoryEngineView {
+ /** True until the first answer (or failure) arrives. */
+ loading: boolean;
/** Id of the bound engine; null until the core answers or if it cannot. */
id: string | null;
/** Human label of the bound engine (falls back to the id). */
label: string | null;
/** Capability families the bound engine advertises; null while unknown. */
capabilities: ReadonlySet<string> | null;
+ /** Every selectable engine (empty until known). */
+ engines: MemoryEngineDescriptor[];
+ /** The raw `engine_get` state (fell_back_from, last_error, ...); null until known. */
+ current: MemoryEngineState | null;
+ /** Error from the last fetch, when it failed. */
+ error: unknown;
+ /** Re-fetch now (deduplicated with any fetch already in flight). */
+ refresh: () => Promise<void>;
+}
+
+interface Snapshot {
+ loading: boolean;
+ engines: MemoryEngineDescriptor[];
+ current: MemoryEngineState | null;
+ error: unknown;
+ fetchedAt: number;
}
-const UNKNOWN: MemoryEngineCapabilities = { id: null, label: null, capabilities: null };
+const INITIAL: Snapshot = { loading: true, engines: [], current: null, error: null, fetchedAt: 0 };
+
+let snapshot: Snapshot = INITIAL;
+let inflight: Promise<void> | null = null;
+const listeners = new Set<(s: Snapshot) => void>();
+
+function publish(next: Snapshot) {
+ snapshot = next;
+ listeners.forEach(fn => fn(next));
+}
/**
- * The active memory engine and the capability families it advertises, from
- * `engine_get` + `engines_list`.
+ * One `engines_list` + `engine_get` per view: concurrent callers share the
+ * in-flight request and callers within the TTL share its result.
+ */
+function fetchSnapshot(force: boolean): Promise<void> {
+ if (inflight) return inflight;
+ const fresh = snapshot.fetchedAt > 0 && Date.now() - snapshot.fetchedAt < MEMORY_ENGINE_CACHE_TTL_MS;
+ if (!force && fresh && snapshot.error === null) return Promise.resolve();
+ inflight = (async () => {
+ try {
+ const [list, current] = await Promise.all([memoryEnginesList(), memoryEngineGet()]);
+ log('loaded engines=%d active=%s', list.engines.length, current.driver);
+ publish({
+ loading: false,
+ engines: list.engines,
+ current,
+ error: null,
+ fetchedAt: Date.now(),
+ });
+ } catch (err) {
+ log('unavailable: %o', err);
+ publish({ ...snapshot, loading: false, error: err, fetchedAt: Date.now() });
+ } finally {
+ inflight = null;
+ }
+ })();
+ return inflight;
+}
+
+/** Drop the cached snapshot (after a switch) so the next reader re-fetches. */
+export function invalidateMemoryEngine(): void {
+ snapshot = { ...snapshot, fetchedAt: 0 };
+}
+
+/** Test seam: forget everything, including subscribers' last value. */
+export function resetMemoryEngineCacheForTests(): void {
+ snapshot = INITIAL;
+ inflight = null;
+}
+
+/**
+ * The active memory engine, its capability families and the engine list — one
+ * shared cache behind the Brain row, the family gates and the settings panel.
*
* Fails open: while loading, or if the core does not answer, `capabilities` is
* null and callers must treat every family as available. Hiding a working
* feature because a status probe failed would be worse than showing an error.
*/
-export function useMemoryEngineCapabilities(): MemoryEngineCapabilities {
- const [state, setState] = useState<MemoryEngineCapabilities>(UNKNOWN);
+export function useMemoryEngine(): MemoryEngineView {
+ const [snap, setSnap] = useState<Snapshot>(snapshot);
useEffect(() => {
- let cancelled = false;
- void (async () => {
- try {
- const [list, current] = await Promise.all([memoryEnginesList(), memoryEngineGet()]);
- if (cancelled) return;
- const entry = list.engines.find(e => e.id === current.driver);
- setState({
- id: current.driver,
- label: entry?.label ?? current.driver,
- capabilities: entry ? new Set(entry.capabilities) : null,
- });
- } catch (err) {
- log('capabilities unavailable: %o', err);
- }
- })();
+ listeners.add(setSnap);
+ setSnap(snapshot);
+ void fetchSnapshot(false);
return () => {
- cancelled = true;
+ listeners.delete(setSnap);
};
}, []);
- return state;
+ const refresh = useCallback(() => fetchSnapshot(true), []);
+ const entry = snap.current ? snap.engines.find(e => e.id === snap.current?.driver) : undefined;
+ return {
+ loading: snap.loading,
+ id: snap.current?.driver ?? null,
+ label: snap.current ? (entry?.label ?? snap.current.driver) : null,
+ capabilities: entry ? new Set(entry.capabilities) : null,
+ engines: snap.engines,
+ current: snap.current,
+ error: snap.error,
+ refresh,
+ };
}
+
+/** Back-compat alias for callers that only need the id / label / capabilities. */
+export const useMemoryEngineCapabilities = useMemoryEngine;
diff --git a/app/src/components/settings/panels/MemoryEngineErrorAlert.tsx b/app/src/components/settings/panels/MemoryEngineErrorAlert.tsx
new file mode 100644
index 0000000000..a78bc135a5
--- /dev/null
+++ b/app/src/components/settings/panels/MemoryEngineErrorAlert.tsx
@@ -0,0 +1,72 @@
+import { useNavigate } from 'react-router-dom';
+
+import { useT } from '../../../lib/i18n/I18nContext';
+import { Alert, AlertDescription, Button } from '../../ui';
+import { classifyMemoryEngineError, type MemoryEngineErrorKind } from './memoryEngineUtils';
+
+/** Friendly text for a classified engine error; generic otherwise. */
+export function useMemoryEngineErrorText(): (kind: MemoryEngineErrorKind) => string {
+ const { t } = useT();
+ return kind =>
+ kind === 'insufficient_credits'
+ ? t('memoryEngine.error.insufficientCredits')
+ : kind === 'session_expired'
+ ? t('memoryEngine.error.sessionExpired')
+ : kind === 'backend_unavailable'
+ ? t('memoryEngine.error.backendUnavailable')
+ : t('memoryEngine.error.generic');
+}
+
+interface MemoryEngineErrorAlertProps {
+ /** The raw error (Error, string or core message). */
+ error: unknown;
+ /** Kind already classified by the caller; derived from `error` when omitted. */
+ kind?: MemoryEngineErrorKind;
+ /** Shown instead of the generic text when the error is not an engine error. */
+ fallbackText?: string;
+}
+
+/**
+ * The top-up / sign-in / backend-unavailable states for a memory-engine error,
+ * shared by the engine panel and every memory view that surfaces core errors.
+ */
+export default function MemoryEngineErrorAlert({
+ error,
+ kind,
+ fallbackText,
+}: MemoryEngineErrorAlertProps) {
+ const { t } = useT();
+ const navigate = useNavigate();
+ const errorText = useMemoryEngineErrorText();
+ const resolved = kind ?? classifyMemoryEngineError(error);
+
+ return (
+ <Alert variant="destructive" data-testid={`memory-engine-error-${resolved}`}>
+ <AlertDescription>
+ <span>{resolved === 'other' && fallbackText ? fallbackText : errorText(resolved)}</span>
+ {resolved === 'insufficient_credits' ? (
+ <Button
+ variant="tertiary"
+ size="xs"
+ className="ml-2"
+ analyticsId="memory-engine-open-billing"
+ data-testid="memory-engine-open-billing"
+ onClick={() => navigate('/settings/account')}>
+ {t('memoryEngine.error.openBilling')}
+ </Button>
+ ) : null}
+ {resolved === 'session_expired' ? (
+ <Button
+ variant="tertiary"
+ size="xs"
+ className="ml-2"
+ analyticsId="memory-engine-sign-in"
+ data-testid="memory-engine-sign-in"
+ onClick={() => navigate('/')}>
+ {t('memoryEngine.error.signIn')}
+ </Button>
+ ) : null}
+ </AlertDescription>
+ </Alert>
+ );
+}