Personal AI, On Personal Devices
Python
fix(desktop): surface memory status errors and allow retry (#1049)
Elliot Sluskyf77070f4522f
diff --git a/frontend/src/lib/api.memory.test.ts b/frontend/src/lib/api.memory.test.tsnew file mode 100644index 00000000..8fe3ef34--- /dev/null+++ b/frontend/src/lib/api.memory.test.ts@@ -0,0 +1,65 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const fetchMock = vi.fn<typeof fetch>();++class MemoryStorage {+ private store = new Map<string, string>();+ getItem(key: string): string | null {+ return this.store.get(key) ?? null;+ }+ setItem(key: string, value: string): void {+ this.store.set(key, value);+ }+}++beforeEach(() => {+ vi.resetModules();+ vi.stubEnv('VITE_API_URL', '');+ fetchMock.mockReset();+ globalThis.fetch = fetchMock;+ (globalThis as unknown as { localStorage: MemoryStorage }).localStorage = new MemoryStorage();+});++afterEach(() => {+ vi.unstubAllEnvs();+ (globalThis as unknown as { localStorage?: MemoryStorage }).localStorage = undefined;+});++describe('getMemoryStats', () => {+ it('shows the server detail and HTTP status for a backend failure', async () => {+ fetchMock.mockResolvedValue(new Response(+ JSON.stringify({ detail: 'openjarvis_rust is missing from the serving environment' }),+ { status: 503, headers: { 'Content-Type': 'application/json' } },+ ));+ const { getMemoryStats } = await import('./api');++ await expect(getMemoryStats()).rejects.toThrow(+ 'openjarvis_rust is missing from the serving environment (HTTP 503)',+ );+ });++ it('keeps the HTTP status when a failed response has no JSON detail', async () => {+ fetchMock.mockResolvedValue(new Response('Internal Server Error', { status: 500 }));+ const { getMemoryStats } = await import('./api');++ await expect(getMemoryStats()).rejects.toThrow('Memory status request failed (HTTP 500)');+ });++ it('retries successfully against the updated API URL after a connection failure', async () => {+ localStorage.setItem('openjarvis-settings', JSON.stringify({ apiUrl: 'http://localhost:8000' }));+ fetchMock.mockRejectedValueOnce(new TypeError('Failed to fetch'));+ fetchMock.mockResolvedValueOnce(new Response(+ JSON.stringify({ backend: 'sqlite', entries: 3 }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ ));+ const { getMemoryStats } = await import('./api');++ await expect(getMemoryStats()).rejects.toThrow(/Check the server status and API URL/);+ localStorage.setItem('openjarvis-settings', JSON.stringify({ apiUrl: 'http://localhost:8010' }));+ await expect(getMemoryStats()).resolves.toEqual({ backend: 'sqlite', entries: 3 });+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([+ 'http://localhost:8000/v1/memory/stats',+ 'http://localhost:8010/v1/memory/stats',+ ]);+ });+});diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex dc8f09c1..742b6bc8 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1095,8 +1095,16 @@ async function memoryErrorDetail(res: Response, fallback: string): Promise<strin}export async function getMemoryStats(): Promise<MemoryStats> {- const res = await apiFetch(`/v1/memory/stats`);- if (!res.ok) throw new Error('Failed to fetch memory stats');+ let res: Response;+ try {+ res = await apiFetch(`/v1/memory/stats`);+ } catch {+ throw new Error('Could not reach the OpenJarvis API. Check the server status and API URL, then retry.');+ }+ if (!res.ok) {+ const detail = await memoryErrorDetail(res, 'Memory status request failed');+ throw new Error(`${detail} (HTTP ${res.status})`);+ }return res.json();}diff --git a/frontend/src/pages/SettingsPage.memory.test.tsx b/frontend/src/pages/SettingsPage.memory.test.tsxnew file mode 100644index 00000000..22f12ff2--- /dev/null+++ b/frontend/src/pages/SettingsPage.memory.test.tsx@@ -0,0 +1,45 @@+import { renderToStaticMarkup } from 'react-dom/server';+import { describe, expect, it, vi } from 'vitest';++vi.mock('../lib/store', () => ({ useAppStore: vi.fn() }));++import { MemoryStatusRow } from './SettingsPage';++describe('Settings memory status', () => {+ it('shows the failure detail and a Retry action, then the recovered count', () => {+ const onRetry = vi.fn();+ const failed = renderToStaticMarkup(+ <MemoryStatusRow+ status={{ kind: 'error', message: 'Missing Authorization header (HTTP 401)' }}+ onRetry={onRetry}+ />,+ );+ const recovered = renderToStaticMarkup(+ <MemoryStatusRow+ status={{ kind: 'ready', stats: { backend: 'sqlite', entries: 3 } }}+ onRetry={onRetry}+ />,+ );++ expect(failed).toContain('Missing Authorization header (HTTP 401)');+ expect(failed).toContain('Retry');+ expect(failed).toContain('Unavailable');+ expect(failed).not.toContain('Unable to reach memory service');+ expect(recovered).toContain('sqlite backend — 3 entries');+ expect(recovered).not.toContain('Retry');+ expect(recovered).not.toContain('Missing Authorization header');+ });++ it('does not present an unconfigured backend as connected', () => {+ const html = renderToStaticMarkup(+ <MemoryStatusRow+ status={{ kind: 'ready', stats: { backend: 'none', entries: 0, status: 'not_configured' } }}+ onRetry={vi.fn()}+ />,+ );++ expect(html).toContain('Memory is not configured');+ expect(html).toContain('Not configured');+ expect(html).not.toContain('0 entries');+ });+});diff --git a/frontend/src/pages/SettingsPage.tsx b/frontend/src/pages/SettingsPage.tsxindex b730b1a9..6b8bdc1d 100644--- a/frontend/src/pages/SettingsPage.tsx+++ b/frontend/src/pages/SettingsPage.tsx@@ -1,4 +1,4 @@-import { useState, useEffect, useCallback } from 'react';+import { useState, useEffect, useCallback, useRef } from 'react';import {Palette,Globe,@@ -33,6 +33,7 @@ import {deleteToolCredential,isTauri,type InferenceSource,+ type MemoryStats,} from '../lib/api';import { isAutoUpdateDisabled, setAutoUpdateDisabled } from '../components/Desktop/UpdateChecker';@@ -217,10 +218,10 @@ function Section({ title, children }: { title: string; children: React.ReactNodefunction SettingRow({ label, description, children }: { label: string; description?: string; children: React.ReactNode }) {return (<div className="flex items-center justify-between py-3" style={{ borderBottom: '1px solid var(--color-border-subtle)' }}>- <div>+ <div className="min-w-0"><div className="text-sm" style={{ color: 'var(--color-text)' }}>{label}</div>{description && (- <div className="text-xs mt-0.5" style={{ color: 'var(--color-text-tertiary)' }}>{description}</div>+ <div className="text-xs mt-0.5 break-words" style={{ color: 'var(--color-text-tertiary)' }}>{description}</div>)}</div><div>{children}</div>@@ -228,6 +229,56 @@ function SettingRow({ label, description, children }: { label: string; descripti);}+type MemoryStatus =+ | { kind: 'loading' }+ | { kind: 'ready'; stats: MemoryStats }+ | { kind: 'error'; message: string };++export function MemoryStatusRow({+ status,+ onRetry,+}: {+ status: MemoryStatus;+ onRetry: () => void;+}) {+ const stats = status.kind === 'ready' ? status.stats : null;+ const description = status.kind === 'error'+ ? status.message+ : status.kind === 'loading'+ ? 'Checking memory backend...'+ : stats?.backend === 'none'+ ? 'Memory is not configured'+ : `${stats?.backend} backend — ${stats?.entries} entries`;+ const label = status.kind === 'loading'+ ? 'Checking...'+ : stats?.backend === 'none'+ ? 'Not configured'+ : stats+ ? `${stats.entries} entries`+ : 'Unavailable';++ return (+ <SettingRow label="Memory status" description={description}>+ <div className="flex items-center gap-2">+ <Brain size={14} style={{ color: stats && stats.backend !== 'none' ? 'var(--color-accent)' : 'var(--color-text-tertiary)' }} />+ <span className="text-xs whitespace-nowrap" style={{ color: 'var(--color-text-secondary)' }}>+ {label}+ </span>+ {status.kind === 'error' && (+ <button+ type="button"+ onClick={onRetry}+ className="text-xs underline cursor-pointer whitespace-nowrap"+ style={{ color: 'var(--color-accent)' }}+ >+ Retry+ </button>+ )}+ </div>+ </SettingRow>+ );+}+const themeOptions: { value: ThemeMode; label: string; icon: typeof Sun }[] = [{ value: 'light', label: 'Light', icon: Sun },{ value: 'dark', label: 'Dark', icon: Moon },@@ -265,7 +316,8 @@ export function SettingsPage() {}}, []);- const [memoryStats, setMemoryStats] = useState<{ entries: number; backend: string } | null>(null);+ const [memoryStatus, setMemoryStatus] = useState<MemoryStatus>({ kind: 'loading' });+ const memoryRequestId = useRef(0);const [memoryEnabled, setMemoryEnabled] = useState(() => {try { return localStorage.getItem('openjarvis-memory-enabled') !== 'false'; } catch { return true; }});@@ -311,6 +363,34 @@ export function SettingsPage() {}}, [srcKind, customHost, customModel, customEngine, customKey]);+ const refreshMemoryStatus = useCallback(async () => {+ const requestId = ++memoryRequestId.current;+ setMemoryStatus({ kind: 'loading' });+ try {+ const stats = await getMemoryStats();+ if (requestId === memoryRequestId.current) {+ setMemoryStatus({ kind: 'ready', stats });+ }+ } catch (error) {+ if (requestId === memoryRequestId.current) {+ setMemoryStatus({+ kind: 'error',+ message: error instanceof Error ? error.message : String(error),+ });+ }+ }+ }, []);++ useEffect(() => {+ void refreshMemoryStatus();+ const onFocus = () => { void refreshMemoryStatus(); };+ window.addEventListener('focus', onFocus);+ return () => {+ window.removeEventListener('focus', onFocus);+ ++memoryRequestId.current;+ };+ }, [refreshMemoryStatus, settings.apiUrl]);+useEffect(() => {checkHealth().then(setHealthy);fetchSpeechHealth()@@ -319,9 +399,6 @@ export function SettingsPage() {fetchTtsHealth().then((h) => setTtsBackend(h)).catch(() => setTtsBackend({ available: false }));- getMemoryStats()- .then(setMemoryStats)- .catch(() => setMemoryStats(null));}, []);const showSaved = () => {@@ -584,14 +661,7 @@ export function SettingsPage() {{/* Memory */}<Section title="Memory">- <SettingRow label="Memory status" description={memoryStats ? `${memoryStats.backend} backend — ${memoryStats.entries} entries` : 'Unable to reach memory service'}>- <div className="flex items-center gap-2">- <Brain size={14} style={{ color: memoryStats ? 'var(--color-accent)' : 'var(--color-text-tertiary)' }} />- <span className="text-xs" style={{ color: 'var(--color-text-secondary)' }}>- {memoryStats ? `${memoryStats.entries} entries` : 'Unavailable'}- </span>- </div>- </SettingRow>+ <MemoryStatusRow status={memoryStatus} onRetry={() => { void refreshMemoryStatus(); }} /><SettingRow label="Use memory context" description="Automatically inject relevant memories into conversations"><buttononClick={() => {