Skip to content

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

feat(memory): prompt a top-up when a memory action is out of credits

M3gA-Mind3ecf69e9b9af
diff --git a/app/src/components/memory/MemoryAddSourceDialog.tsx b/app/src/components/memory/MemoryAddSourceDialog.tsx
index 69a73de415..cb5c3272ff 100644
--- a/app/src/components/memory/MemoryAddSourceDialog.tsx
+++ b/app/src/components/memory/MemoryAddSourceDialog.tsx
@@ -9,9 +9,11 @@ import { useT } from '../../lib/i18n/I18nContext';
import {
DOCUMENT_SOURCE_KINDS,
type DocumentSourceKind,
+ isOutOfCreditsMessage,
type SourceAddRequest,
} from '../../services/api/memoryApi';
import { Button, Label, ModalShell, NativeSelect, TextField } from '../ui';
+import { MemoryCreditsPrompt } from './MemoryErrorAlert';
import { parsePositiveInt } from './memoryFormat';
import { sourceKindLabel, sourceTargetHint } from './memorySourceLabels';
@@ -142,11 +144,17 @@ export default function MemoryAddSourceDialog({
{t('memoryPage.documents.scheduleHelp')}
</p>
</div>
- {error !== null && (
- <p className="text-xs text-coral-600" role="alert" data-testid="memory-add-source-error">
- {error}
- </p>
- )}
+ {error !== null &&
+ (isOutOfCreditsMessage(error, t) ? (
+ <MemoryCreditsPrompt message={error} data-testid="memory-add-source-error" />
+ ) : (
+ <p
+ className="text-xs text-coral-600"
+ role="alert"
+ data-testid="memory-add-source-error">
+ {error}
+ </p>
+ ))}
</form>
</ModalShell>
);
diff --git a/app/src/components/memory/MemoryAskTab.test.tsx b/app/src/components/memory/MemoryAskTab.test.tsx
index 6df33fc988..8a6f141e9d 100644
--- a/app/src/components/memory/MemoryAskTab.test.tsx
+++ b/app/src/components/memory/MemoryAskTab.test.tsx
@@ -164,7 +164,37 @@ describe('MemoryAskTab', () => {
hoisted.recall.mockRejectedValue(new Error('ENGINE: upstream timeout'));
renderWithProviders(<MemoryAskTab fetchModes={['hybrid']} />);
ask('anything');
- expect(await screen.findByTestId('memory-ask-error')).toHaveTextContent('upstream timeout');
+ const error = await screen.findByTestId('memory-ask-error');
+ expect(error).toHaveTextContent('upstream timeout');
+ expect(error).toHaveAttribute('data-variant', 'destructive');
+ expect(screen.queryByTestId('memory-top-up')).not.toBeInTheDocument();
+ });
+
+ it('prompts a top-up, not an error, when recall is out of credits', async () => {
+ hoisted.recall.mockRejectedValue(
+ Object.assign(new Error('insufficient credits: [USER_INSUFFICIENT_CREDITS] HTTP 402'), {
+ data: { code: 'INSUFFICIENT_CREDITS', kind: 'INSUFFICIENT_CREDITS' },
+ })
+ );
+ renderWithProviders(<MemoryAskTab fetchModes={['hybrid']} />);
+ ask('anything');
+ const prompt = await screen.findByTestId('memory-ask-error');
+ expect(prompt).toHaveAttribute('data-kind', 'out-of-credits');
+ expect(prompt).toHaveAttribute('data-variant', 'warning');
+ expect(prompt).toHaveTextContent('Out of credits');
+ expect(prompt).toHaveTextContent('Top up to restore it');
+ expect(prompt).not.toHaveTextContent('HTTP 402');
+ expect(screen.getByTestId('memory-top-up')).toHaveTextContent('Top up');
+ });
+
+ it('prompts a top-up for a core that only sends the code as text', async () => {
+ hoisted.recall.mockRejectedValue(new Error('INSUFFICIENT_CREDITS: top up'));
+ renderWithProviders(<MemoryAskTab fetchModes={['hybrid']} />);
+ ask('anything');
+ expect(await screen.findByTestId('memory-ask-error')).toHaveAttribute(
+ 'data-kind',
+ 'out-of-credits'
+ );
});
it('previews the pack a turn would get for a chosen agent', async () => {
diff --git a/app/src/components/memory/MemoryAskTab.tsx b/app/src/components/memory/MemoryAskTab.tsx
index d126d123ab..fff1c04dbc 100644
--- a/app/src/components/memory/MemoryAskTab.tsx
+++ b/app/src/components/memory/MemoryAskTab.tsx
@@ -25,8 +25,6 @@ import {
type RecallAnswer,
} from '../../services/api/memoryApi';
import {
- Alert,
- AlertDescription,
Button,
Card,
Label,
@@ -36,6 +34,7 @@ import {
ToggleGroupRoot,
} from '../ui';
import { CenteredLoadingState } from '../ui/LoadingState';
+import MemoryErrorAlert from './MemoryErrorAlert';
import MemoryHitRow from './MemoryHitRow';
import MemoryPackPreview from './MemoryPackPreview';
@@ -167,11 +166,7 @@ export default function MemoryAskTab({ fetchModes }: MemoryAskTabProps) {
</form>
</Card>
- {error !== null && (
- <Alert variant="destructive" data-testid="memory-ask-error">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
- )}
+ {error !== null && <MemoryErrorAlert message={error} data-testid="memory-ask-error" />}
{busy && <CenteredLoadingState label={t('memoryPage.ask.thinking')} />}
diff --git a/app/src/components/memory/MemoryBackgroundTab.tsx b/app/src/components/memory/MemoryBackgroundTab.tsx
index aa71018e98..483beb5df7 100644
--- a/app/src/components/memory/MemoryBackgroundTab.tsx
+++ b/app/src/components/memory/MemoryBackgroundTab.tsx
@@ -19,6 +19,7 @@ import {
} from '../../services/api/memoryApi';
import { Alert, AlertDescription, Badge, Button, Card } from '../ui';
import { CenteredLoadingState } from '../ui/LoadingState';
+import MemoryErrorAlert from './MemoryErrorAlert';
import { fill, formatTimestamp } from './memoryFormat';
import { JOB_OUTCOME_VARIANT, jobKindLabel, jobOutcomeLabel } from './memoryLifecycleLabels';
@@ -94,11 +95,7 @@ export default function MemoryBackgroundTab() {
return (
<div className="space-y-4 animate-fade-up" data-testid="memory-background-tab">
- {error !== null && (
- <Alert variant="destructive" data-testid="memory-background-error">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
- )}
+ {error !== null && <MemoryErrorAlert message={error} data-testid="memory-background-error" />}
{notice !== null && (
<Alert variant="success" data-testid="memory-background-notice">
<AlertDescription>{notice}</AlertDescription>
diff --git a/app/src/components/memory/MemoryBrainIngestDialog.tsx b/app/src/components/memory/MemoryBrainIngestDialog.tsx
index f5348acd3a..e9b142738e 100644
--- a/app/src/components/memory/MemoryBrainIngestDialog.tsx
+++ b/app/src/components/memory/MemoryBrainIngestDialog.tsx
@@ -7,7 +7,7 @@
import { useId, useState } from 'react';
import { useT } from '../../lib/i18n/I18nContext';
-import type { BrainIngestRequest } from '../../services/api/memoryApi';
+import { type BrainIngestRequest, isOutOfCreditsMessage } from '../../services/api/memoryApi';
import {
Button,
Label,
@@ -17,6 +17,7 @@ import {
ToggleGroupItem,
ToggleGroupRoot,
} from '../ui';
+import { MemoryCreditsPrompt } from './MemoryErrorAlert';
type IngestFrom = 'text' | 'path';
@@ -157,14 +158,17 @@ export default function MemoryBrainIngestDialog({
onChange={e => setSource(e.target.value)}
/>
</div>
- {error !== null && (
- <p
- className="text-xs text-coral-600"
- role="alert"
- data-testid="memory-brain-ingest-error">
- {error}
- </p>
- )}
+ {error !== null &&
+ (isOutOfCreditsMessage(error, t) ? (
+ <MemoryCreditsPrompt message={error} data-testid="memory-brain-ingest-error" />
+ ) : (
+ <p
+ className="text-xs text-coral-600"
+ role="alert"
+ data-testid="memory-brain-ingest-error">
+ {error}
+ </p>
+ ))}
</form>
</ModalShell>
);
diff --git a/app/src/components/memory/MemoryBrainSearch.tsx b/app/src/components/memory/MemoryBrainSearch.tsx
index dc08e3dcf4..1cd41b4cf8 100644
--- a/app/src/components/memory/MemoryBrainSearch.tsx
+++ b/app/src/components/memory/MemoryBrainSearch.tsx
@@ -9,8 +9,9 @@ import { type FormEvent, useState } from 'react';
import { useT } from '../../lib/i18n/I18nContext';
import { type Hit, memoryBrainSearch, memoryErrorMessage } from '../../services/api/memoryApi';
-import { Alert, AlertDescription, Button, Card, NativeSelect, TextField } from '../ui';
+import { Button, Card, NativeSelect, TextField } from '../ui';
import { CenteredLoadingState } from '../ui/LoadingState';
+import MemoryErrorAlert from './MemoryErrorAlert';
import MemoryHitRow from './MemoryHitRow';
import { brainSourceLabel } from './memoryLifecycleLabels';
@@ -95,9 +96,7 @@ export default function MemoryBrainSearch({ sources }: MemoryBrainSearchProps) {
{error !== null && (
<div className="px-4 pb-3">
- <Alert variant="destructive" data-testid="memory-brain-search-error">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
+ <MemoryErrorAlert message={error} data-testid="memory-brain-search-error" />
</div>
)}
diff --git a/app/src/components/memory/MemoryBrainTab.test.tsx b/app/src/components/memory/MemoryBrainTab.test.tsx
index 08da2839b0..c39e83fc1b 100644
--- a/app/src/components/memory/MemoryBrainTab.test.tsx
+++ b/app/src/components/memory/MemoryBrainTab.test.tsx
@@ -174,6 +174,17 @@ describe('MemoryBrainTab', () => {
expect(screen.getByTestId('memory-brain-ingest')).toBeInTheDocument();
});
+ it('prompts a top-up in the ingest dialog when the account is out of credits', async () => {
+ hoisted.ingest.mockRejectedValue(new Error('INSUFFICIENT_CREDITS: HTTP 402'));
+ renderWithProviders(<MemoryBrainTab />);
+ fireEvent.click(await screen.findByTestId('memory-brain-add'));
+ fireEvent.change(screen.getByTestId('memory-brain-ingest-text'), { target: { value: 'x' } });
+ fireEvent.click(screen.getByTestId('memory-brain-ingest-submit'));
+ const prompt = await screen.findByTestId('memory-brain-ingest-error');
+ expect(prompt).toHaveAttribute('data-kind', 'out-of-credits');
+ expect(screen.getByTestId('memory-top-up')).toBeInTheDocument();
+ });
+
it('shows a load error', async () => {
hoisted.sources.mockRejectedValue(new Error('MEMORY_OFF'));
renderWithProviders(<MemoryBrainTab />);
diff --git a/app/src/components/memory/MemoryBrainTab.tsx b/app/src/components/memory/MemoryBrainTab.tsx
index b68044528a..e10ef9d41a 100644
--- a/app/src/components/memory/MemoryBrainTab.tsx
+++ b/app/src/components/memory/MemoryBrainTab.tsx
@@ -27,6 +27,7 @@ import { Alert, AlertDescription, Button, Card, ConfirmDialog } from '../ui';
import { CenteredLoadingState } from '../ui/LoadingState';
import MemoryBrainIngestDialog from './MemoryBrainIngestDialog';
import MemoryBrainSearch from './MemoryBrainSearch';
+import MemoryErrorAlert from './MemoryErrorAlert';
import { fill } from './memoryFormat';
import { brainSourceLabel } from './memoryLifecycleLabels';
import MemorySyncedSources from './MemorySyncedSources';
@@ -128,11 +129,7 @@ export default function MemoryBrainTab() {
return (
<div className="space-y-4 animate-fade-up" data-testid="memory-brain-tab">
- {error !== null && (
- <Alert variant="destructive" data-testid="memory-brain-error">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
- )}
+ {error !== null && <MemoryErrorAlert message={error} data-testid="memory-brain-error" />}
{notice !== null && (
<Alert variant="success" data-testid="memory-brain-notice">
<AlertDescription>{notice}</AlertDescription>
diff --git a/app/src/components/memory/MemoryConversationsBackfill.tsx b/app/src/components/memory/MemoryConversationsBackfill.tsx
index bd90a0fb44..e32c666357 100644
--- a/app/src/components/memory/MemoryConversationsBackfill.tsx
+++ b/app/src/components/memory/MemoryConversationsBackfill.tsx
@@ -21,6 +21,7 @@ import {
memoryErrorMessage,
} from '../../services/api/memoryApi';
import { Alert, AlertDescription, Button, Card, ConfirmDialog, Progress } from '../ui';
+import MemoryErrorAlert from './MemoryErrorAlert';
import { fill } from './memoryFormat';
const log = debug('openhuman:memory:backfill');
@@ -157,11 +158,7 @@ export default function MemoryConversationsBackfill() {
<AlertDescription>{state.error || t('memoryPage.backfill.failed')}</AlertDescription>
</Alert>
)}
- {error !== null && (
- <Alert variant="destructive" data-testid="memory-backfill-error">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
- )}
+ {error !== null && <MemoryErrorAlert message={error} data-testid="memory-backfill-error" />}
</div>
{consentOpen && view && (
diff --git a/app/src/components/memory/MemoryConversationsTab.tsx b/app/src/components/memory/MemoryConversationsTab.tsx
index ca51a75e7d..49d3f94f2d 100644
--- a/app/src/components/memory/MemoryConversationsTab.tsx
+++ b/app/src/components/memory/MemoryConversationsTab.tsx
@@ -21,9 +21,10 @@ import {
memoryPolicyGet,
memoryPolicySet,
} from '../../services/api/memoryApi';
-import { Alert, AlertDescription, Button, Card, Switch } from '../ui';
+import { Button, Card, Switch } from '../ui';
import { CenteredLoadingState } from '../ui/LoadingState';
import MemoryConversationsBackfill from './MemoryConversationsBackfill';
+import MemoryErrorAlert from './MemoryErrorAlert';
import { fill } from './memoryFormat';
import MemoryHitRow from './MemoryHitRow';
@@ -121,9 +122,7 @@ export default function MemoryConversationsTab() {
return (
<div className="space-y-4 animate-fade-up" data-testid="memory-conversations-tab">
{error !== null && (
- <Alert variant="destructive" data-testid="memory-conversations-error">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
+ <MemoryErrorAlert message={error} data-testid="memory-conversations-error" />
)}
{policy !== null && (
diff --git a/app/src/components/memory/MemoryErrorAlert.test.tsx b/app/src/components/memory/MemoryErrorAlert.test.tsx
new file mode 100644
index 0000000000..4a881decac
--- /dev/null
+++ b/app/src/components/memory/MemoryErrorAlert.test.tsx
@@ -0,0 +1,83 @@
+import { fireEvent, screen } from '@testing-library/react';
+import { Route, Routes } from 'react-router-dom';
+import { describe, expect, it } from 'vitest';
+
+import { useT } from '../../lib/i18n/I18nContext';
+import { memoryErrorMessage } from '../../services/api/memoryApi';
+import { renderWithProviders } from '../../test/test-utils';
+import MemoryErrorAlert from './MemoryErrorAlert';
+
+/** Renders the alert for `err` the way the memory views do: via memoryErrorMessage. */
+function Harness({ err, retry }: { err: unknown; retry?: boolean }) {
+ const { t } = useT();
+ const message = memoryErrorMessage(err, t);
+ return (
+ <MemoryErrorAlert message={message} data-testid="alert">
+ {retry ? (
+ <>
+ <span>{message}</span> <button type="button">Retry</button>
+ </>
+ ) : undefined}
+ </MemoryErrorAlert>
+ );
+}
+
+function renderAt(err: unknown, retry = false) {
+ renderWithProviders(
+ <Routes>
+ <Route path="/" element={<Harness err={err} retry={retry} />} />
+ <Route path="/settings/account" element={<div data-testid="billing-page" />} />
+ </Routes>
+ );
+}
+
+const coded = (code: string, message = 'engine detail') =>
+ Object.assign(new Error(message), { data: { code, kind: code } });
+
+describe('MemoryErrorAlert', () => {
+ it('turns INSUFFICIENT_CREDITS into a top-up prompt, not an error', () => {
+ renderAt(coded('INSUFFICIENT_CREDITS', 'insufficient credits: HTTP 402'));
+ const alert = screen.getByTestId('alert');
+ expect(alert).toHaveAttribute('data-kind', 'out-of-credits');
+ expect(alert).toHaveAttribute('data-variant', 'warning');
+ expect(alert).toHaveTextContent('Out of credits');
+ expect(alert).toHaveTextContent('nothing stored has been lost');
+ expect(alert).not.toHaveTextContent('HTTP 402');
+ });
+
+ it('sends Top up to the billing page', () => {
+ renderAt(coded('INSUFFICIENT_CREDITS'));
+ fireEvent.click(screen.getByTestId('memory-top-up'));
+ expect(screen.getByTestId('billing-page')).toBeInTheDocument();
+ });
+
+ it.each([
+ ['UNAVAILABLE', "Memory can't be reached right now"],
+ ['ENGINE', 'engine detail'],
+ ['UNAUTHORIZED', 'engine detail'],
+ ])('keeps the error alert for %s', (code, text) => {
+ renderAt(coded(code));
+ const alert = screen.getByTestId('alert');
+ expect(alert).toHaveAttribute('data-variant', 'destructive');
+ expect(alert).toHaveTextContent(text);
+ expect(alert).not.toHaveAttribute('data-kind');
+ expect(screen.queryByTestId('memory-top-up')).not.toBeInTheDocument();
+ });
+
+ it('keeps the error alert for an error with no code', () => {
+ renderAt(new Error('something broke'));
+ expect(screen.getByTestId('alert')).toHaveAttribute('data-variant', 'destructive');
+ expect(screen.queryByTestId('memory-top-up')).not.toBeInTheDocument();
+ });
+
+ it('renders the caller content (e.g. a retry) for other errors only', () => {
+ renderAt(coded('ENGINE'), true);
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();
+ });
+
+ it('drops the retry for out of credits: a retry cannot succeed until a top-up', () => {
+ renderAt(coded('INSUFFICIENT_CREDITS'), true);
+ expect(screen.queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument();
+ expect(screen.getByTestId('memory-top-up')).toBeInTheDocument();
+ });
+});
diff --git a/app/src/components/memory/MemoryErrorAlert.tsx b/app/src/components/memory/MemoryErrorAlert.tsx
new file mode 100644
index 0000000000..1a952f3839
--- /dev/null
+++ b/app/src/components/memory/MemoryErrorAlert.tsx
@@ -0,0 +1,75 @@
+/**
+ * How a failed memory action is shown. An exhausted credit balance
+ * (`INSUFFICIENT_CREDITS`) is a prompt to top up, not an error: it explains
+ * that nothing stored was lost and links to billing. Every other failure keeps
+ * the destructive alert.
+ */
+import type { ReactNode } from 'react';
+import { useNavigate } from 'react-router-dom';
+
+import { useT } from '../../lib/i18n/I18nContext';
+import { isOutOfCreditsMessage } from '../../services/api/memoryApi';
+import { Alert, AlertDescription, AlertTitle, Button } from '../ui';
+
+/** Where the app sends every "top up" action (`open_billing` in useAppNotices). */
+const BILLING_ROUTE = '/settings/account';
+
+interface MemoryCreditsPromptProps {
+ /** The out-of-credits explanation. */
+ message: string;
+ className?: string;
+ 'data-testid'?: string;
+}
+
+/** "Out of credits: top up", with a button to billing. */
+export function MemoryCreditsPrompt({
+ message,
+ className,
+ 'data-testid': testId,
+}: MemoryCreditsPromptProps) {
+ const { t } = useT();
+ const navigate = useNavigate();
+ return (
+ <Alert variant="warning" className={className} data-testid={testId} data-kind="out-of-credits">
+ <AlertTitle>{t('memory.outOfCredits.title')}</AlertTitle>
+ <AlertDescription className="flex flex-wrap items-center gap-2">
+ <span>{message}</span>
+ <Button
+ type="button"
+ size="xs"
+ variant="primary"
+ data-testid="memory-top-up"
+ onClick={() => navigate(BILLING_ROUTE)}>
+ {t('memory.outOfCredits.action')}
+ </Button>
+ </AlertDescription>
+ </Alert>
+ );
+}
+
+interface MemoryErrorAlertProps {
+ /** The message `memoryErrorMessage(err, t)` produced. */
+ message: string;
+ className?: string;
+ 'data-testid'?: string;
+ /** Replaces the message inside the error alert (e.g. message + retry). */
+ children?: ReactNode;
+}
+
+/** The credits prompt for an exhausted balance, else the error alert. */
+export default function MemoryErrorAlert({
+ message,
+ className,
+ 'data-testid': testId,
+ children,
+}: MemoryErrorAlertProps) {
+ const { t } = useT();
+ if (isOutOfCreditsMessage(message, t)) {
+ return <MemoryCreditsPrompt message={message} className={className} data-testid={testId} />;
+ }
+ return (
+ <Alert variant="destructive" className={className} data-testid={testId}>
+ <AlertDescription>{children ?? message}</AlertDescription>
+ </Alert>
+ );
+}
diff --git a/app/src/components/memory/MemoryExplorerTab.tsx b/app/src/components/memory/MemoryExplorerTab.tsx
index 1eab3c43fc..4b7dfcf757 100644
--- a/app/src/components/memory/MemoryExplorerTab.tsx
+++ b/app/src/components/memory/MemoryExplorerTab.tsx
@@ -30,8 +30,9 @@ import {
memoryItemsList,
type PathStep,
} from '../../services/api/memoryApi';
-import { Alert, AlertDescription, Button, Card, NativeSelect } from '../ui';
+import { Button, Card, NativeSelect } from '../ui';
import { CenteredLoadingState } from '../ui/LoadingState';
+import MemoryErrorAlert from './MemoryErrorAlert';
import { facetLabel, facetValueLabel, isMonoFacet, nextFacet } from './memoryFacetLabels';
import { fill } from './memoryFormat';
import MemoryHitRow from './MemoryHitRow';
@@ -159,21 +160,19 @@ export default function MemoryExplorerTab() {
</nav>
{error !== null && (
- <Alert variant="destructive" data-testid="memory-explorer-error">
- <AlertDescription>
- <span>{error}</span>{' '}
- <Button
- type="button"
- variant="tertiary"
- size="xs"
- onClick={() => {
- setError(null);
- setReloadKey(k => k + 1);
- }}>
- {t('common.retry')}
- </Button>
- </AlertDescription>
- </Alert>
+ <MemoryErrorAlert message={error} data-testid="memory-explorer-error">
+ <span>{error}</span>{' '}
+ <Button
+ type="button"
+ variant="tertiary"
+ size="xs"
+ onClick={() => {
+ setError(null);
+ setReloadKey(k => k + 1);
+ }}>
+ {t('common.retry')}
+ </Button>
+ </MemoryErrorAlert>
)}
<Card
diff --git a/app/src/components/memory/MemoryImportBanner.tsx b/app/src/components/memory/MemoryImportBanner.tsx
index 14bbc05728..129ee96084 100644
--- a/app/src/components/memory/MemoryImportBanner.tsx
+++ b/app/src/components/memory/MemoryImportBanner.tsx
@@ -20,6 +20,7 @@ import {
memoryImportStatus,
} from '../../services/api/memoryApi';
import { Alert, AlertDescription, AlertTitle, Button, ConfirmDialog, Progress } from '../ui';
+import MemoryErrorAlert from './MemoryErrorAlert';
import { fill } from './memoryFormat';
const log = debug('openhuman:memory:import');
@@ -64,9 +65,9 @@ export default function MemoryImportBanner({ engineLabel }: MemoryImportBannerPr
setState(res.state);
} catch (err) {
log('status failed: %o', err);
- setError(memoryErrorMessage(err));
+ setError(memoryErrorMessage(err, t));
}
- }, []);
+ }, [t]);
const running = state?.phase === 'running';
useEffect(() => {
@@ -85,7 +86,7 @@ export default function MemoryImportBanner({ engineLabel }: MemoryImportBannerPr
setConsentOpen(false);
} catch (err) {
log('import start failed: %o', err);
- setError(memoryErrorMessage(err));
+ setError(memoryErrorMessage(err, t));
setConsentOpen(false);
} finally {
setStarting(false);
@@ -170,9 +171,7 @@ export default function MemoryImportBanner({ engineLabel }: MemoryImportBannerPr
)}
{error !== null && (
- <Alert variant="destructive" className="mt-3" data-testid="memory-import-error">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
+ <MemoryErrorAlert message={error} className="mt-3" data-testid="memory-import-error" />
)}
{consentOpen && (
diff --git a/app/src/components/memory/MemoryItemDialog.tsx b/app/src/components/memory/MemoryItemDialog.tsx
index 2201d4ae47..15b22a4ce0 100644
--- a/app/src/components/memory/MemoryItemDialog.tsx
+++ b/app/src/components/memory/MemoryItemDialog.tsx
@@ -15,8 +15,9 @@ import {
memoryItemsGet,
type MemoryMeta,
} from '../../services/api/memoryApi';
-import { Alert, AlertDescription, Badge, Button, ModalShell } from '../ui';
+import { Badge, Button, ModalShell } from '../ui';
import { CenteredLoadingState } from '../ui/LoadingState';
+import MemoryErrorAlert from './MemoryErrorAlert';
import { facetLabel } from './memoryFacetLabels';
import { formatTimestamp, KIND_VARIANT, kindLabel } from './memoryFormat';
@@ -137,11 +138,7 @@ export default function MemoryItemDialog({ id, onClose, onForgotten }: MemoryIte
</div>
}>
<div className="space-y-4">
- {error !== null && (
- <Alert variant="destructive" data-testid="memory-item-error">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
- )}
+ {error !== null && <MemoryErrorAlert message={error} data-testid="memory-item-error" />}
{missing ? (
<p className="text-sm text-content-muted" data-testid="memory-item-missing">
{t('memoryPage.explorer.itemMissing')}
diff --git a/app/src/components/memory/MemoryLearningsTab.tsx b/app/src/components/memory/MemoryLearningsTab.tsx
index 8a0b2ca587..328f59f0f2 100644
--- a/app/src/components/memory/MemoryLearningsTab.tsx
+++ b/app/src/components/memory/MemoryLearningsTab.tsx
@@ -25,8 +25,9 @@ import {
memoryJobsList,
memoryLearn,
} from '../../services/api/memoryApi';
-import { Alert, AlertDescription, Button, Card, Label, NativeSelect, TextArea } from '../ui';
+import { Button, Card, Label, NativeSelect, TextArea } from '../ui';
import { CenteredLoadingState } from '../ui/LoadingState';
+import MemoryErrorAlert from './MemoryErrorAlert';
import MemoryHitRow from './MemoryHitRow';
const log = debug('openhuman:memory:learnings');
@@ -214,11 +215,7 @@ export default function MemoryLearningsTab() {
</form>
</Card>
- {error !== null && (
- <Alert variant="destructive" data-testid="memory-learnings-error">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
- )}
+ {error !== null && <MemoryErrorAlert message={error} data-testid="memory-learnings-error" />}
{items === null ? (
<CenteredLoadingState label={t('memoryPage.loading')} />
diff --git a/app/src/components/memory/MemoryPackPreview.tsx b/app/src/components/memory/MemoryPackPreview.tsx
index e13b6e1075..3254ca3b7c 100644
--- a/app/src/components/memory/MemoryPackPreview.tsx
+++ b/app/src/components/memory/MemoryPackPreview.tsx
@@ -22,8 +22,9 @@ import {
memoryPolicyGet,
type PackPreview,
} from '../../services/api/memoryApi';
-import { Alert, AlertDescription, Badge, Button, Card, Label, NativeSelect, TextArea } from '../ui';
+import { Badge, Button, Card, Label, NativeSelect, TextArea } from '../ui';
import { CenteredLoadingState } from '../ui/LoadingState';
+import MemoryErrorAlert from './MemoryErrorAlert';
import { fill } from './memoryFormat';
const log = debug('openhuman:memory:pack');
@@ -127,11 +128,7 @@ export default function MemoryPackPreview() {
</form>
</Card>
- {error !== null && (
- <Alert variant="destructive" data-testid="memory-pack-error">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
- )}
+ {error !== null && <MemoryErrorAlert message={error} data-testid="memory-pack-error" />}
{busy && <CenteredLoadingState label={t('memoryPage.pack.building')} />}
diff --git a/app/src/components/memory/MemorySettingsTab.tsx b/app/src/components/memory/MemorySettingsTab.tsx
index d2a170f34b..c0c5eb0c85 100644
--- a/app/src/components/memory/MemorySettingsTab.tsx
+++ b/app/src/components/memory/MemorySettingsTab.tsx
@@ -22,8 +22,9 @@ import {
memoryPolicySet,
type PolicyUpdate,
} from '../../services/api/memoryApi';
-import { Alert, AlertDescription, Card, NumberField, Switch } from '../ui';
+import { Card, NumberField, Switch } from '../ui';
import { CenteredLoadingState } from '../ui/LoadingState';
+import MemoryErrorAlert from './MemoryErrorAlert';
import { parseIntInRange } from './memoryFormat';
const log = debug('openhuman:memory:settings');
@@ -175,9 +176,7 @@ export default function MemorySettingsTab() {
if (policy === null || drafts === null) {
return error !== null ? (
- <Alert variant="destructive" data-testid="memory-settings-error">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
+ <MemoryErrorAlert message={error} data-testid="memory-settings-error" />
) : (
<CenteredLoadingState label={t('memoryPage.loading')} />
);
@@ -187,11 +186,7 @@ export default function MemorySettingsTab() {
return (
<div className="space-y-4 animate-fade-up" data-testid="memory-settings-tab">
- {error !== null && (
- <Alert variant="destructive" data-testid="memory-settings-error">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
- )}
+ {error !== null && <MemoryErrorAlert message={error} data-testid="memory-settings-error" />}
<Card
title={t('memoryPage.settings.recallTitle')}
diff --git a/app/src/components/memory/MemorySyncedSources.test.tsx b/app/src/components/memory/MemorySyncedSources.test.tsx
index f9fe14ebfe..4ff0214527 100644
--- a/app/src/components/memory/MemorySyncedSources.test.tsx
+++ b/app/src/components/memory/MemorySyncedSources.test.tsx
@@ -107,6 +107,20 @@ describe('MemorySyncedSources', () => {
expect(hoisted.add).toHaveBeenCalledWith({ kind: 'github', target: 'acme/missing' });
});
+ it('prompts a top-up in the add dialog when the account is out of credits', async () => {
+ hoisted.add.mockRejectedValue(new Error('INSUFFICIENT_CREDITS: HTTP 402'));
+ renderWithProviders(<MemorySyncedSources />);
+ fireEvent.click(await screen.findByTestId('memory-sources-add'));
+ fireEvent.change(screen.getByTestId('memory-add-source-target'), {
+ target: { value: '/Users/me/notes' },
+ });
+ fireEvent.click(screen.getByTestId('memory-add-source-submit'));
+ const prompt = await screen.findByTestId('memory-add-source-error');
+ expect(prompt).toHaveAttribute('data-kind', 'out-of-credits');
+ expect(prompt).not.toHaveTextContent('HTTP 402');
+ expect(screen.getByTestId('memory-top-up')).toBeInTheDocument();
+ });
+
it('syncs one source and marks it syncing', async () => {
hoisted.sync.mockResolvedValue({ started: ['s1'] });
renderWithProviders(<MemorySyncedSources />);
diff --git a/app/src/components/memory/MemorySyncedSources.tsx b/app/src/components/memory/MemorySyncedSources.tsx
index 04219c7dc1..cbaf7fb911 100644
--- a/app/src/components/memory/MemorySyncedSources.tsx
+++ b/app/src/components/memory/MemorySyncedSources.tsx
@@ -20,9 +20,10 @@ import {
type Source,
type SourceAddRequest,
} from '../../services/api/memoryApi';
-import { Alert, AlertDescription, Badge, Button, Card, Checkbox, ConfirmDialog } from '../ui';
+import { Badge, Button, Card, Checkbox, ConfirmDialog } from '../ui';
import { CenteredLoadingState } from '../ui/LoadingState';
import MemoryAddSourceDialog from './MemoryAddSourceDialog';
+import MemoryErrorAlert from './MemoryErrorAlert';
import { fill, formatTimestamp } from './memoryFormat';
import { SOURCE_STATUS_VARIANT, sourceKindLabel, sourceStatusLabel } from './memorySourceLabels';
@@ -148,9 +149,7 @@ export default function MemorySyncedSources() {
return (
<div className="space-y-4" data-testid="memory-synced-sources">
{error !== null && (
- <Alert variant="destructive" data-testid="memory-synced-sources-error">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
+ <MemoryErrorAlert message={error} data-testid="memory-synced-sources-error" />
)}
<Card
diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts
index b0b3ba0300..ce675f1821 100644
--- a/app/src/lib/i18n/ar.ts
+++ b/app/src/lib/i18n/ar.ts
@@ -670,6 +670,8 @@ const messages: TranslationMap = {
'الذاكرة غير متاحة: نفد رصيد حسابك. أعد الشحن لاستعادتها؛ لم يُفقد أي شيء مخزّن.',
'memory.error.unavailable':
'تعذّر الوصول إلى الذاكرة حاليًا. لم يُفقد أي شيء مخزّن؛ حاول مرة أخرى بعد قليل.',
+ 'memory.outOfCredits.title': 'نفد الرصيد',
+ 'memory.outOfCredits.action': 'اشحن الرصيد',
'memory.tab.memory': 'الذاكرة',
'memory.tab.agents': 'المكتبة',
'memory.analyzeNow': 'تحليل الآن',
diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts
index 54822b7905..fb0dfe29a2 100644
--- a/app/src/lib/i18n/bn.ts
+++ b/app/src/lib/i18n/bn.ts
@@ -683,6 +683,8 @@ const messages: TranslationMap = {
'মেমরি উপলব্ধ নয়: আপনার অ্যাকাউন্টের ক্রেডিট শেষ। ফিরিয়ে আনতে টপ আপ করুন; সংরক্ষিত কিছুই হারায়নি।',
'memory.error.unavailable':
'এই মুহূর্তে মেমরিতে পৌঁছানো যাচ্ছে না। সংরক্ষিত কিছুই হারায়নি; একটু পরে আবার চেষ্টা করুন।',
+ 'memory.outOfCredits.title': 'ক্রেডিট শেষ',
+ 'memory.outOfCredits.action': 'টপ আপ করুন',
'memory.tab.memory': 'মেমোরি',
'memory.tab.agents': 'লাইব্রেরি',
'memory.analyzeNow': 'এখনই বিশ্লেষণ করুন',
diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts
index 33c6a4e793..e7d59345fd 100644
--- a/app/src/lib/i18n/de.ts
+++ b/app/src/lib/i18n/de.ts
@@ -712,6 +712,8 @@ const messages: TranslationMap = {
'Gedächtnis nicht verfügbar: Dein Konto hat kein Guthaben mehr. Lade es auf, um es wiederherzustellen; nichts Gespeichertes ist verloren.',
'memory.error.unavailable':
'Das Gedächtnis ist gerade nicht erreichbar. Nichts Gespeichertes ist verloren; versuche es gleich noch einmal.',
+ 'memory.outOfCredits.title': 'Kein Guthaben mehr',
+ 'memory.outOfCredits.action': 'Aufladen',
'memory.tab.memory': 'Erinnerung',
'memory.tab.agents': 'Bibliothek',
'memory.analyzeNow': 'Jetzt analysieren',
diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.ts
index d698c3fd19..2c6aaa5258 100644
--- a/app/src/lib/i18n/en.ts
+++ b/app/src/lib/i18n/en.ts
@@ -639,6 +639,8 @@ const en: TranslationMap = {
'Memory is unavailable: your account is out of credits. Top up to restore it; nothing stored has been lost.',
'memory.error.unavailable':
"Memory can't be reached right now. Nothing stored has been lost; try again in a moment.",
+ 'memory.outOfCredits.title': 'Out of credits',
+ 'memory.outOfCredits.action': 'Top up',
'memory.tab.memory': 'Memory',
'memory.tab.agents': 'Library',
diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts
index 379604fc9b..cbc40f752c 100644
--- a/app/src/lib/i18n/es.ts
+++ b/app/src/lib/i18n/es.ts
@@ -704,6 +704,8 @@ const messages: TranslationMap = {
'La memoria no está disponible: tu cuenta se quedó sin créditos. Recarga para restaurarla; no se ha perdido nada guardado.',
'memory.error.unavailable':
'No se puede acceder a la memoria ahora mismo. No se ha perdido nada guardado; inténtalo de nuevo en un momento.',
+ 'memory.outOfCredits.title': 'Sin créditos',
+ 'memory.outOfCredits.action': 'Recargar',
'memory.tab.memory': 'Memoria',
'memory.tab.agents': 'Biblioteca',
'memory.analyzeNow': 'Analizar ahora',
diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts
index d22601858e..a6fc8faaa3 100644
--- a/app/src/lib/i18n/fr.ts
+++ b/app/src/lib/i18n/fr.ts
@@ -711,6 +711,8 @@ const messages: TranslationMap = {
"La mémoire est indisponible : votre compte n'a plus de crédits. Rechargez-le pour la rétablir ; rien de ce qui est stocké n'a été perdu.",
'memory.error.unavailable':
"La mémoire est injoignable pour le moment. Rien de ce qui est stocké n'a été perdu ; réessayez dans un instant.",
+ 'memory.outOfCredits.title': 'Crédits épuisés',
+ 'memory.outOfCredits.action': 'Recharger',
'memory.tab.memory': 'Mémoire',
'memory.tab.agents': 'Bibliothèque',
'memory.analyzeNow': 'Analyser maintenant',
diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts
index ee80012e54..16737a8646 100644
--- a/app/src/lib/i18n/hi.ts
+++ b/app/src/lib/i18n/hi.ts
@@ -686,6 +686,8 @@ const messages: TranslationMap = {
'मेमोरी उपलब्ध नहीं है: आपके खाते के क्रेडिट खत्म हो गए हैं। इसे बहाल करने के लिए टॉप अप करें; संग्रहीत कुछ भी खोया नहीं है।',
'memory.error.unavailable':
'अभी मेमोरी तक नहीं पहुँचा जा सकता। संग्रहीत कुछ भी खोया नहीं है; थोड़ी देर में फिर से कोशिश करें।',
+ 'memory.outOfCredits.title': 'क्रेडिट खत्म हो गए',
+ 'memory.outOfCredits.action': 'टॉप अप करें',
'memory.tab.memory': 'मेमोरी',
'memory.tab.agents': 'लाइब्रेरी',
'memory.analyzeNow': 'अभी एनालाइज़ करें',
diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts
index ab235c8380..6b643d8a22 100644
--- a/app/src/lib/i18n/id.ts
+++ b/app/src/lib/i18n/id.ts
@@ -696,6 +696,8 @@ const messages: TranslationMap = {
'Memori tidak tersedia: kredit akun Anda habis. Isi ulang untuk memulihkannya; tidak ada data tersimpan yang hilang.',
'memory.error.unavailable':
'Memori tidak dapat dijangkau saat ini. Tidak ada data tersimpan yang hilang; coba lagi sebentar lagi.',
+ 'memory.outOfCredits.title': 'Kredit habis',
+ 'memory.outOfCredits.action': 'Isi ulang',
'memory.tab.memory': 'Memori',
'memory.tab.agents': 'Perpustakaan',
'memory.analyzeNow': 'Analisis Sekarang',
diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts
index d6fbf94da8..f224dc99df 100644
--- a/app/src/lib/i18n/it.ts
+++ b/app/src/lib/i18n/it.ts
@@ -705,6 +705,8 @@ const messages: TranslationMap = {
'La memoria non è disponibile: il tuo account ha esaurito i crediti. Ricarica per ripristinarla; nulla di quanto salvato è andato perso.',
'memory.error.unavailable':
'Al momento la memoria non è raggiungibile. Nulla di quanto salvato è andato perso; riprova tra poco.',
+ 'memory.outOfCredits.title': 'Crediti esauriti',
+ 'memory.outOfCredits.action': 'Ricarica',
'memory.tab.memory': 'Memoria',
'memory.tab.agents': 'Libreria',
'memory.analyzeNow': 'Analizza ora',
diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts
index f82d1560ad..28e5212207 100644
--- a/app/src/lib/i18n/ko.ts
+++ b/app/src/lib/i18n/ko.ts
@@ -678,6 +678,8 @@ const messages: TranslationMap = {
'메모리를 사용할 수 없습니다: 계정의 크레딧이 모두 소진되었습니다. 충전하면 복구되며, 저장된 내용은 사라지지 않았습니다.',
'memory.error.unavailable':
'지금은 메모리에 연결할 수 없습니다. 저장된 내용은 사라지지 않았습니다. 잠시 후 다시 시도하세요.',
+ 'memory.outOfCredits.title': '크레딧 소진',
+ 'memory.outOfCredits.action': '충전하기',
'memory.tab.memory': '메모리',
'memory.tab.agents': '라이브러리',
'memory.analyzeNow': '지금 분석',
diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts
index 3e9ea086c8..ca3d1d984f 100644
--- a/app/src/lib/i18n/pl.ts
+++ b/app/src/lib/i18n/pl.ts
@@ -700,6 +700,8 @@ const messages: TranslationMap = {
'Pamięć jest niedostępna: na koncie skończyły się kredyty. Doładuj konto, aby ją przywrócić; nic z zapisanych danych nie zostało utracone.',
'memory.error.unavailable':
'Nie można teraz połączyć się z pamięcią. Nic z zapisanych danych nie zostało utracone; spróbuj ponownie za chwilę.',
+ 'memory.outOfCredits.title': 'Brak kredytów',
+ 'memory.outOfCredits.action': 'Doładuj',
'memory.tab.memory': 'Pamięć',
'memory.tab.agents': 'Biblioteka',
'memory.analyzeNow': 'Analizuj teraz',
diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts
index e893584277..973017f436 100644
--- a/app/src/lib/i18n/pt.ts
+++ b/app/src/lib/i18n/pt.ts
@@ -701,6 +701,8 @@ const messages: TranslationMap = {
'A memória está indisponível: sua conta ficou sem créditos. Recarregue para restaurá-la; nada do que foi guardado se perdeu.',
'memory.error.unavailable':
'Não é possível acessar a memória agora. Nada do que foi guardado se perdeu; tente novamente em instantes.',
+ 'memory.outOfCredits.title': 'Sem créditos',
+ 'memory.outOfCredits.action': 'Recarregar',
'memory.tab.memory': 'Memória',
'memory.tab.agents': 'Biblioteca',
'memory.analyzeNow': 'Analisar Agora',
diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts
index 8899a8065d..334f382644 100644
--- a/app/src/lib/i18n/ru.ts
+++ b/app/src/lib/i18n/ru.ts
@@ -695,6 +695,8 @@ const messages: TranslationMap = {
'Память недоступна: на счёте закончились кредиты. Пополните баланс, чтобы восстановить её; ничего из сохранённого не потеряно.',
'memory.error.unavailable':
'Сейчас не удаётся связаться с памятью. Ничего из сохранённого не потеряно; повторите попытку чуть позже.',
+ 'memory.outOfCredits.title': 'Кредиты закончились',
+ 'memory.outOfCredits.action': 'Пополнить',
'memory.tab.memory': 'Память',
'memory.tab.agents': 'Библиотека',
'memory.analyzeNow': 'Анализировать сейчас',
diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.ts
index a2a79e1bc9..8087a35b78 100644
--- a/app/src/lib/i18n/zh-CN.ts
+++ b/app/src/lib/i18n/zh-CN.ts
@@ -630,6 +630,8 @@ const messages: TranslationMap = {
'memory.error.insufficientCredits':
'记忆不可用:你的账户额度已用完。充值即可恢复,已存储的内容不会丢失。',
'memory.error.unavailable': '暂时无法连接记忆服务。已存储的内容不会丢失,请稍后重试。',
+ 'memory.outOfCredits.title': '额度已用完',
+ 'memory.outOfCredits.action': '充值',
'memory.tab.memory': '记忆',
'memory.tab.agents': '资料库',
'memory.analyzeNow': '立即分析',
diff --git a/app/src/services/api/memoryApi.ts b/app/src/services/api/memoryApi.ts
index 5fc7083d0f..6b2c80e36b 100644
--- a/app/src/services/api/memoryApi.ts
+++ b/app/src/services/api/memoryApi.ts
@@ -627,6 +627,20 @@ export function memoryErrorMessage(
return String(err);
}
+/**
+ * True when `message` is the out-of-credits explanation `memoryErrorMessage`
+ * produced (with `t`). That translated text is returned for
+ * `INSUFFICIENT_CREDITS` and for nothing else, so the views that keep only the
+ * message can still offer a top-up instead of an error.
+ */
+export function isOutOfCreditsMessage(
+ message: string | null,
+ t: (key: string, fallback?: string) => string
+): boolean {
+ const key = REFUSAL_KEYS.INSUFFICIENT_CREDITS;
+ return message !== null && key !== undefined && message === t(key);
+}
+
/** True when the engine state means memory is usable (an engine is set and not off). */
export function isMemoryOn(state: EngineState | null | undefined): boolean {
return Boolean(state && state.engine && state.status !== 'off');