Skip to content

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

fix: show a load error with Retry instead of an empty list for Brain, MeatSpace, Messages, Privacy and Tribe reads (#12784)

Adam Eivyeee738263a01
diff --git a/client/src/components/brain/IdeaLoomLists.jsx b/client/src/components/brain/IdeaLoomLists.jsx
index b53c6f6dba..86b95542cc 100644
--- a/client/src/components/brain/IdeaLoomLists.jsx
+++ b/client/src/components/brain/IdeaLoomLists.jsx
@@ -5,6 +5,11 @@ import toast from '../ui/Toast';
import InlineConfirmRow from '../ui/InlineConfirmRow';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import useUrlParams from '../../hooks/useUrlParams';
+import useListResource from '../../hooks/useListResource';
+import ListLoadError from '../ui/ListLoadError';
+
+// Module-level so useListResource sees a stable fetcher. The row owns the error UI; the route returns a bare array.
+const fetchVaults = () => api.getNotesVaults({ silent: true });
const emptyList = () => ({ title: '', prompt: '', category: '', help: '', status: 'draft', ideas: [] });
@@ -57,7 +62,7 @@ export default function IdeaLoomLists() {
const [ideaText, setIdeaText] = useState('');
const [exchangeBusy, setExchangeBusy] = useState(false);
const [exchangeResult, setExchangeResult] = useState(null);
- const [vaults, setVaults] = useState([]);
+ const vaultsResource = useListResource(fetchVaults);
const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
const select = useCallback((id) => updateParams({ list: id }), [updateParams]);
@@ -71,10 +76,6 @@ export default function IdeaLoomLists() {
toast.error(error.message || 'Failed to load IdeaLoom lists');
return [[], null];
});
- // The vault list only names existing vaults to choose between; a failure
- // here leaves the picker empty rather than blocking local list editing.
- const vaultData = await api.getNotesVaults().catch(() => ({ vaults: [] }));
- setVaults(vaultData?.vaults || []);
setLists(Array.isArray(nextLists?.lists) ? nextLists.lists : (Array.isArray(nextLists) ? nextLists : []));
setSettings(nextSettings?.settings || nextSettings);
setLoading(false);
@@ -178,10 +179,11 @@ export default function IdeaLoomLists() {
<input id="idealoom-enabled" type="checkbox" checked={Boolean(settings.enabled)} onChange={(event) => patchSettings({ enabled: event.target.checked })} />
Sync with an Obsidian vault
</label>
- {settings.enabled && <label className="block text-xs text-gray-300" htmlFor="idealoom-vault">Vault
+ {settings.enabled && vaultsResource.state === 'error' && <ListLoadError what="Obsidian vaults" error={vaultsResource.error} onRetry={vaultsResource.retry} />}
+ {settings.enabled && vaultsResource.state !== 'error' && <label className="block text-xs text-gray-300" htmlFor="idealoom-vault">Vault
<select id="idealoom-vault" value={settings.obsidianVaultId || ''} onChange={(event) => patchSettings({ obsidianVaultId: event.target.value || null })} className="mt-1 block min-h-[44px] w-full rounded border border-port-border bg-port-bg px-3 text-sm text-white">
<option value="">Choose a vault…</option>
- {vaults.map((vault) => <option key={vault.id} value={vault.id}>{vault.name}</option>)}
+ {vaultsResource.items.map((vault) => <option key={vault.id} value={vault.id}>{vault.name}</option>)}
</select>
</label>}
{settings.enabled && settings.obsidianVaultId && <label className="flex items-start gap-2 text-xs text-gray-300" htmlFor="idealoom-autosync">
diff --git a/client/src/components/brain/IdeaLoomLists.test.jsx b/client/src/components/brain/IdeaLoomLists.test.jsx
index 835a95e504..9d2e2755d6 100644
--- a/client/src/components/brain/IdeaLoomLists.test.jsx
+++ b/client/src/components/brain/IdeaLoomLists.test.jsx
@@ -43,7 +43,7 @@ beforeEach(() => {
vi.clearAllMocks();
api.getIdeaLoomLists.mockResolvedValue([]);
api.getIdeaLoomSettings.mockResolvedValue({ enabled: false, obsidianVaultId: null, autoSync: false });
- api.getNotesVaults.mockResolvedValue({ vaults: [{ id: 'vault-1', name: 'Example Vault' }] });
+ api.getNotesVaults.mockResolvedValue([{ id: 'vault-1', name: 'Example Vault' }]);
});
describe('IdeaLoomLists', () => {
@@ -67,6 +67,20 @@ describe('IdeaLoomLists', () => {
await waitFor(() => expect(api.updateIdeaLoomSettings).toHaveBeenLastCalledWith({ autoSync: true }, expect.anything()));
});
+ it('shows a retryable error instead of an empty vault picker when the vault list fails to load', async () => {
+ api.getIdeaLoomSettings.mockResolvedValue({ enabled: true, obsidianVaultId: 'vault-1', autoSync: false });
+ api.getNotesVaults.mockRejectedValueOnce(new Error('vault service down'));
+ renderPanel();
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load Obsidian vaults');
+ expect(screen.queryByLabelText('Vault')).toBeNull();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ const picker = await screen.findByLabelText('Vault');
+ expect(picker).toHaveValue('vault-1');
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+
it('offers explicit recovery only after an exchange reports a deleted note', async () => {
api.getIdeaLoomSettings.mockResolvedValue({ enabled: true, obsidianVaultId: 'vault-1', autoSync: false });
api.syncIdeaLoomToObsidian
diff --git a/client/src/components/brain/YoutubeIngestSettings.jsx b/client/src/components/brain/YoutubeIngestSettings.jsx
index 6600869a05..e0c878283d 100644
--- a/client/src/components/brain/YoutubeIngestSettings.jsx
+++ b/client/src/components/brain/YoutubeIngestSettings.jsx
@@ -7,10 +7,15 @@ import BrailleSpinner from '../BrailleSpinner';
import InfiniteScrollFooter from '../ui/InfiniteScrollFooter';
import { usePagedCollection } from '../../hooks/usePagedCollection';
import toast from '../ui/Toast';
+import ListLoadError from '../ui/ListLoadError';
+import useListResource from '../../hooks/useListResource';
const PRIORITIES = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
const INGESTS_PAGE_SIZE = 50;
+// Module-level so useListResource sees a stable fetcher; the picker owns its error UI.
+const fetchVaults = () => api.getNotesVaults({ silent: true });
+
/**
* Settings for the YouTube → Brain ingest, plus the list of what has been
* ingested so far: which Obsidian vault/folder transcripts are mirrored into,
@@ -24,18 +29,14 @@ const INGESTS_PAGE_SIZE = 50;
export default function YoutubeIngestSettings() {
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
- const [vaults, setVaults] = useState([]);
+ const vaultsResource = useListResource(fetchVaults);
const [settings, setSettings] = useState(null);
// Two-click arm rather than a confirm dialog, per the client UI conventions.
const [armedDelete, setArmedDelete] = useState(null);
useEffect(() => {
- Promise.all([
- api.getYoutubeIngestSettings({ silent: true }).catch(() => null),
- api.getNotesVaults().catch(() => ({ vaults: [] })),
- ]).then(([loaded, vaultData]) => {
+ api.getYoutubeIngestSettings({ silent: true }).catch(() => null).then((loaded) => {
setSettings(loaded);
- setVaults(vaultData?.vaults || []);
setLoading(false);
});
}, []);
@@ -117,22 +118,28 @@ export default function YoutubeIngestSettings() {
<label htmlFor="ytVault" className="block text-sm font-medium text-gray-300 mb-2">
Obsidian Vault
</label>
- <select
- id="ytVault"
- value={settings.obsidianVaultId || ''}
- onChange={(e) => patch({ obsidianVaultId: e.target.value || null })}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:outline-hidden focus:ring-2 focus:ring-port-accent"
- >
- <option value="">Same as Daily Log</option>
- {vaults.map((v) => (
- <option key={v.id} value={v.id}>{v.name}</option>
- ))}
- </select>
- <p className="mt-1 text-xs text-gray-500">
- {vaults.length === 0
- ? 'No vaults configured yet — add one under Brain → Notes.'
- : 'Leave as "Same as Daily Log" to reuse the journal\'s vault.'}
- </p>
+ {vaultsResource.state === 'error' ? (
+ <ListLoadError what="Obsidian vaults" error={vaultsResource.error} onRetry={vaultsResource.retry} />
+ ) : (
+ <>
+ <select
+ id="ytVault"
+ value={settings.obsidianVaultId || ''}
+ onChange={(e) => patch({ obsidianVaultId: e.target.value || null })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:outline-hidden focus:ring-2 focus:ring-port-accent"
+ >
+ <option value="">Same as Daily Log</option>
+ {vaultsResource.items.map((v) => (
+ <option key={v.id} value={v.id}>{v.name}</option>
+ ))}
+ </select>
+ <p className="mt-1 text-xs text-gray-500">
+ {vaultsResource.state === 'ready' && vaultsResource.items.length === 0
+ ? 'No vaults configured yet — add one under Brain → Notes.'
+ : 'Leave as "Same as Daily Log" to reuse the journal\'s vault.'}
+ </p>
+ </>
+ )}
</div>
<div>
diff --git a/client/src/components/brain/YoutubeIngestSettings.test.jsx b/client/src/components/brain/YoutubeIngestSettings.test.jsx
index cd67890567..30884c1143 100644
--- a/client/src/components/brain/YoutubeIngestSettings.test.jsx
+++ b/client/src/components/brain/YoutubeIngestSettings.test.jsx
@@ -23,7 +23,7 @@ const ingest = (videoId, ingestedAt) => ({ videoId, ingestedAt, title: `Video ${
beforeEach(() => {
vi.clearAllMocks();
api.getYoutubeIngestSettings.mockResolvedValue(SETTINGS);
- api.getNotesVaults.mockResolvedValue({ vaults: [] });
+ api.getNotesVaults.mockResolvedValue([]);
});
describe('YoutubeIngestSettings ingest history pagination (#8267)', () => {
@@ -66,6 +66,21 @@ describe('YoutubeIngestSettings ingest history pagination (#8267)', () => {
expect(screen.getByText((_, el) => el.tagName === 'H4' && /Ingested \(0/.test(el.textContent))).toBeInTheDocument();
});
+ it('shows a retryable error, not "No vaults configured", when the vault list fails to load', async () => {
+ api.getYoutubeIngests.mockResolvedValue({ ingests: [] });
+ api.getYoutubeIngestSettings.mockResolvedValue({ ...SETTINGS, obsidianVaultId: 'vault-1' });
+ api.getNotesVaults.mockRejectedValueOnce(new Error('vault service down'));
+ api.getNotesVaults.mockResolvedValue([{ id: 'vault-1', name: 'Example Vault' }]);
+
+ render(<YoutubeIngestSettings />);
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load Obsidian vaults');
+ expect(screen.queryByText(/No vaults configured yet/)).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ await waitFor(() => expect(screen.getByLabelText('Obsidian Vault')).toHaveValue('vault-1'));
+ });
+
it('removes a forgotten ingest from the loaded page without refetching', async () => {
api.getYoutubeIngests.mockResolvedValue({ ingests: [ingest('v1', '2026-01-02T00:00:00.000Z')] });
api.deleteYoutubeIngest.mockResolvedValue({ message: 'Ingest removed' });
diff --git a/client/src/components/brain/tabs/ConfigTab.jsx b/client/src/components/brain/tabs/ConfigTab.jsx
index e4060fa205..f5633eec82 100644
--- a/client/src/components/brain/tabs/ConfigTab.jsx
+++ b/client/src/components/brain/tabs/ConfigTab.jsx
@@ -16,6 +16,8 @@ import {Settings,
import BrailleSpinner from '../../BrailleSpinner';
import toast from '../../ui/Toast';
import YoutubeIngestSettings from '../YoutubeIngestSettings';
+import ListLoadError from '../../ui/ListLoadError';
+import useListResource from '../../../hooks/useListResource';
const DAYS_OF_WEEK = [
'monday',
@@ -27,11 +29,14 @@ const DAYS_OF_WEEK = [
'sunday'
];
+// Module-level so useListResource sees a stable fetcher; the pickers own the error UI.
+const fetchProviders = async () => (await api.getProviders({ silent: true }))?.providers || [];
+
export default function ConfigTab({ onRefresh }) {
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [settings, setSettings] = useState(null);
- const [providers, setProviders] = useState([]);
+ const { items: providers, state: providersState, error: providersError, retry: retryProviders } = useListResource(fetchProviders);
const [selectedProvider, setSelectedProvider] = useState('');
const [selectedModel, setSelectedModel] = useState('');
const [confidenceThreshold, setConfidenceThreshold] = useState(0.6);
@@ -55,9 +60,8 @@ export default function ConfigTab({ onRefresh }) {
}, []);
const fetchData = async () => {
- const [settingsData, providersData, cosConfig, embStatus] = await Promise.all([
+ const [settingsData, cosConfig, embStatus] = await Promise.all([
api.getBrainSettings().catch(() => null),
- api.getProviders().catch(() => ({ providers: [] })),
api.getCosConfig().catch(() => null),
api.getEmbeddingStatus().catch(() => null)
]);
@@ -73,10 +77,6 @@ export default function ConfigTab({ onRefresh }) {
setWeeklyReviewTime(settingsData.weeklyReviewTime || '16:00');
}
- if (providersData) {
- setProviders(providersData.providers || []);
- }
-
if (cosConfig) {
setEmbeddingProvider(cosConfig.embeddingProviderId || '');
setEmbeddingModel(cosConfig.embeddingModel || '');
@@ -199,7 +199,13 @@ export default function ConfigTab({ onRefresh }) {
);
};
- if (loading) {
+ // One list backs both pickers, so a failed read replaces both rather than
+ // offering a provider list that looks empty.
+ const providerLoadError = (
+ <ListLoadError what="AI providers" error={providersError} onRetry={retryProviders} />
+ );
+
+ if (loading || providersState === 'loading') {
return (
<div className="flex items-center justify-center h-64">
<BrailleSpinner text="Loading" />
@@ -247,22 +253,24 @@ export default function ConfigTab({ onRefresh }) {
<div className="space-y-4">
<div>
- <ProviderModelSelector
- id="provider"
- providers={providers}
- selectedProviderId={selectedProvider}
- selectedModel={selectedModel}
- availableModels={getAvailableModels()}
- onProviderChange={handleProviderChange}
- onModelChange={setSelectedModel}
- label="Default Provider"
- modelLabel="Default Model"
- emptyProviderOption="Select a provider..."
- emptyModelOption="Select a model..."
- alwaysShowModel
- modelDisabled={!selectedProvider || getAvailableModels().length === 0}
- layout="stacked"
- />
+ {providersState === 'error' ? providerLoadError : (
+ <ProviderModelSelector
+ id="provider"
+ providers={providers}
+ selectedProviderId={selectedProvider}
+ selectedModel={selectedModel}
+ availableModels={getAvailableModels()}
+ onProviderChange={handleProviderChange}
+ onModelChange={setSelectedModel}
+ label="Default Provider"
+ modelLabel="Default Model"
+ emptyProviderOption="Select a provider..."
+ emptyModelOption="Select a model..."
+ alwaysShowModel
+ modelDisabled={!selectedProvider || getAvailableModels().length === 0}
+ layout="stacked"
+ />
+ )}
<p className="mt-1 text-xs text-gray-500">
Used for thought classification, digests, and reviews
</p>
@@ -304,22 +312,24 @@ export default function ConfigTab({ onRefresh }) {
<div className="space-y-4">
<div>
- <ProviderModelSelector
- id="embeddingProvider"
- providers={providers}
- selectedProviderId={embeddingProvider}
- selectedModel={embeddingModel}
- availableModels={getEmbeddingModels()}
- onProviderChange={handleEmbeddingProviderChange}
- onModelChange={setEmbeddingModel}
- label="Embedding Provider"
- modelLabel="Embedding Model"
- emptyProviderOption="Select a provider..."
- emptyModelOption="Select a model..."
- alwaysShowModel
- modelDisabled={!embeddingProvider || getEmbeddingModels().length === 0}
- layout="stacked"
- />
+ {providersState === 'error' ? providerLoadError : (
+ <ProviderModelSelector
+ id="embeddingProvider"
+ providers={providers}
+ selectedProviderId={embeddingProvider}
+ selectedModel={embeddingModel}
+ availableModels={getEmbeddingModels()}
+ onProviderChange={handleEmbeddingProviderChange}
+ onModelChange={setEmbeddingModel}
+ label="Embedding Provider"
+ modelLabel="Embedding Model"
+ emptyProviderOption="Select a provider..."
+ emptyModelOption="Select a model..."
+ alwaysShowModel
+ modelDisabled={!embeddingProvider || getEmbeddingModels().length === 0}
+ layout="stacked"
+ />
+ )}
<p className="mt-1 text-xs text-gray-500">
Backend that generates vector embeddings (must serve an OpenAI-compatible <span className="font-mono">/v1/embeddings</span>).
Changing the model can change vector dimensions — reprocess after switching so all entries share one space.
diff --git a/client/src/components/brain/tabs/ConfigTab.test.jsx b/client/src/components/brain/tabs/ConfigTab.test.jsx
index def309c876..d473165395 100644
--- a/client/src/components/brain/tabs/ConfigTab.test.jsx
+++ b/client/src/components/brain/tabs/ConfigTab.test.jsx
@@ -88,3 +88,21 @@ describe('brain ConfigTab provider pickers', () => {
expect(screen.getByLabelText('Embedding Model')).toHaveValue('nomic-embed-text');
});
});
+
+describe('brain ConfigTab provider list failure', () => {
+ it('shows a retryable error instead of empty provider pickers, and recovers on retry', async () => {
+ api.getBrainSettings.mockResolvedValue({ defaultProvider: 'local', defaultModel: 'llama3.2:latest', confidenceThreshold: 0.6 });
+ api.getProviders.mockRejectedValueOnce(new Error('providers down'));
+ render(<ConfigTab />);
+
+ const alerts = await screen.findAllByRole('alert');
+ expect(alerts).toHaveLength(2);
+ expect(alerts[0]).toHaveTextContent('Could not load AI providers');
+ expect(screen.queryByLabelText('Default Provider')).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getAllByRole('button', { name: 'Retry' })[0]);
+
+ expect(await screen.findByLabelText('Default Provider')).toHaveValue('local');
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/brain/tabs/DailyLogTab.jsx b/client/src/components/brain/tabs/DailyLogTab.jsx
index 295b4f19a0..687f730656 100644
--- a/client/src/components/brain/tabs/DailyLogTab.jsx
+++ b/client/src/components/brain/tabs/DailyLogTab.jsx
@@ -5,6 +5,8 @@ import {BookOpen, ChevronLeft, ChevronRight, Mic, MicOff, Save, Volume2, Setting
import * as api from '../../../services/api';
import { getNotesVaults } from '../../../services/apiNotes';
import toast from '../../ui/Toast';
+import ListLoadError from '../../ui/ListLoadError';
+import useListResource from '../../../hooks/useListResource';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
import { FormField } from '../../ui/FormField';
import ProviderModelSelector from '../../ProviderModelSelector';
@@ -82,6 +84,9 @@ const STALE_JOURNAL_MAX_ATTEMPTS = 3;
const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
+// Module-level so useListResource sees a stable fetcher; the settings panel owns the error UI.
+const fetchVaults = () => getNotesVaults({ silent: true });
+
export default function DailyLogTab() {
// The URL is the source of truth for the open day (?date=YYYY-MM-DD) — the
// On This Day widget and shared links deep-link a specific past day; without
@@ -112,7 +117,7 @@ export default function DailyLogTab() {
const [dictation, setDictation] = useState(false);
const [showSettings, setShowSettings] = useState(false);
const [settings, setSettings] = useState(null);
- const [vaults, setVaults] = useState([]);
+ const vaultsResource = useListResource(fetchVaults);
// Activity-digest (auto-draft) config + provider list for the picker (#2155).
const [digestSettings, setDigestSettings] = useState(null);
const [providers, setProviders] = useState([]);
@@ -200,14 +205,12 @@ export default function DailyLogTab() {
}, []);
const loadSettings = useCallback(async () => {
- const [s, v, d, p] = await Promise.all([
+ const [s, d, p] = await Promise.all([
api.getDailyLogSettings().catch(() => null),
- getNotesVaults().catch(() => []),
api.getActivityDigestSettings().catch(() => null),
api.getProviders({ silent: true }).catch(() => null),
]);
if (s) setSettings(s);
- setVaults(v || []);
if (d) setDigestSettings(d);
setProviders(p?.providers || (Array.isArray(p) ? p : []));
}, []);
@@ -690,18 +693,25 @@ export default function DailyLogTab() {
{showSettings && (
<div className="p-3 border-b border-port-border space-y-3">
- <FormField label="Obsidian vault (mirror logs)" labelClassName="block text-xs text-gray-400 mb-1">
- <select
- value={settings?.obsidianVaultId || ''}
- onChange={(e) => saveSettings({ obsidianVaultId: e.target.value || null })}
- className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"
- >
- <option value="">None — PortOS only</option>
- {vaults.map((v) => (
- <option key={v.id} value={v.id}>{v.name}</option>
- ))}
- </select>
- </FormField>
+ {vaultsResource.state === 'error' ? (
+ <div>
+ <span className="block text-xs text-gray-400 mb-1">Obsidian vault (mirror logs)</span>
+ <ListLoadError what="Obsidian vaults" error={vaultsResource.error} onRetry={vaultsResource.retry} />
+ </div>
+ ) : (
+ <FormField label="Obsidian vault (mirror logs)" labelClassName="block text-xs text-gray-400 mb-1">
+ <select
+ value={settings?.obsidianVaultId || ''}
+ onChange={(e) => saveSettings({ obsidianVaultId: e.target.value || null })}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"
+ >
+ <option value="">None — PortOS only</option>
+ {vaultsResource.items.map((v) => (
+ <option key={v.id} value={v.id}>{v.name}</option>
+ ))}
+ </select>
+ </FormField>
+ )}
<FormField label="Folder inside vault" labelClassName="block text-xs text-gray-400 mb-1">
<input
type="text"
diff --git a/client/src/components/brain/tabs/DailyLogTab.test.jsx b/client/src/components/brain/tabs/DailyLogTab.test.jsx
index 9dbea75b71..87431d068a 100644
--- a/client/src/components/brain/tabs/DailyLogTab.test.jsx
+++ b/client/src/components/brain/tabs/DailyLogTab.test.jsx
@@ -44,6 +44,7 @@ vi.mock('../../../services/api', () => api);
vi.mock('../../../services/apiNotes', () => ({ getNotesVaults: vi.fn(async () => []) }));
const DailyLogTab = (await import('./DailyLogTab')).default;
+const { getNotesVaults } = await import('../../../services/apiNotes');
const TODAY = '2026-07-17';
const YESTERDAY = '2026-07-16';
@@ -166,6 +167,26 @@ describe('DailyLogTab deep linking', () => {
});
});
+describe('DailyLogTab vault picker', () => {
+ it('shows a retryable error instead of an empty vault list when the vault read fails', async () => {
+ getNotesVaults.mockRejectedValueOnce(new Error('vault service down'));
+ getNotesVaults.mockResolvedValueOnce([{ id: 'vault-1', name: 'Example Vault' }]);
+ api.getDailyLogSettings.mockResolvedValue({ obsidianVaultId: 'vault-1' });
+ await renderTab();
+
+ // Fake timers are armed (see renderTab), so flush microtasks explicitly.
+ const flush = () => act(async () => { await vi.advanceTimersByTimeAsync(0); });
+ fireEvent.click(screen.getByRole('button', { name: 'Daily log settings' }));
+ await flush();
+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load Obsidian vaults');
+ expect(screen.queryByLabelText('Obsidian vault (mirror logs)')).toBeNull();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ await flush();
+ expect(screen.getByLabelText('Obsidian vault (mirror logs)')).toHaveValue('vault-1');
+ });
+});
+
describe('DailyLogTab autosave', () => {
it('saves after the user stops typing', async () => {
await renderTab();
diff --git a/client/src/components/brain/tabs/FeedsTab.jsx b/client/src/components/brain/tabs/FeedsTab.jsx
index 5bf0413d9e..04f5400e4f 100644
--- a/client/src/components/brain/tabs/FeedsTab.jsx
+++ b/client/src/components/brain/tabs/FeedsTab.jsx
@@ -14,6 +14,7 @@ import toast from '../../ui/Toast';
import { timeAgo } from '../../../utils/formatters';
import { normalizeUrl } from '../../../utils/urlNormalize';
import LoadFailedState from '../../ui/LoadFailedState';
+import ListLoadError from '../../ui/ListLoadError';
export default function FeedsTab({ onRefresh }) {
const [inputUrl, setInputUrl] = useState('');
@@ -22,6 +23,7 @@ export default function FeedsTab({ onRefresh }) {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(true);
const [feedsFailed, setFeedsFailed] = useState(false);
+ const [itemsError, setItemsError] = useState(null);
const [refreshing, setRefreshing] = useState(false);
const [selectedFeedId, setSelectedFeedId] = useState(null);
const [unreadOnly, setUnreadOnly] = useState(false);
@@ -41,11 +43,13 @@ export default function FeedsTab({ onRefresh }) {
}, []);
const fetchItems = useCallback(async () => {
- const data = await api.getFeedItems({
- feedId: selectedFeedId,
- unreadOnly
- }).catch(() => []);
- setItems(data);
+ try {
+ const data = await api.getFeedItems({ feedId: selectedFeedId, unreadOnly });
+ setItems(data || []);
+ setItemsError(null);
+ } catch (error) {
+ setItemsError(error instanceof Error ? error : new Error('Request failed'));
+ }
}, [selectedFeedId, unreadOnly]);
useEffect(() => {
@@ -302,7 +306,9 @@ export default function FeedsTab({ onRefresh }) {
{/* Items list */}
<div className="flex-1 overflow-y-auto space-y-2 min-h-0">
- {items.length === 0 ? (
+ {itemsError ? (
+ <ListLoadError what="feed items" error={itemsError} onRetry={fetchItems} />
+ ) : items.length === 0 ? (
<div className="text-center py-8 text-gray-500 text-sm">
{unreadOnly ? 'No unread items' : 'No items yet — try refreshing your feeds'}
</div>
diff --git a/client/src/components/brain/tabs/FeedsTab.test.jsx b/client/src/components/brain/tabs/FeedsTab.test.jsx
index 2dfdd44564..520aa15453 100644
--- a/client/src/components/brain/tabs/FeedsTab.test.jsx
+++ b/client/src/components/brain/tabs/FeedsTab.test.jsx
@@ -30,4 +30,15 @@ describe('FeedsTab loading', () => {
expect(await screen.findByText('Could not load feeds.')).toBeInTheDocument();
expect(screen.queryByText('No feeds subscribed yet.')).not.toBeInTheDocument();
});
+
+ it('shows a retryable error instead of "No items yet" when the item list fails to load', async () => {
+ api.getFeeds.mockResolvedValue([{ id: 'feed-1', title: 'Example Feed', unreadCount: 0 }]);
+ api.getFeedItems.mockRejectedValueOnce(new Error('items down')).mockResolvedValueOnce([]);
+ render(<FeedsTab />);
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load feed items');
+ expect(screen.queryByText(/No items yet/)).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ expect(await screen.findByText(/No items yet/)).toBeInTheDocument();
+ });
});
diff --git a/client/src/components/brain/tabs/TrustTab.jsx b/client/src/components/brain/tabs/TrustTab.jsx
index d026eb6844..fbb3b454d0 100644
--- a/client/src/components/brain/tabs/TrustTab.jsx
+++ b/client/src/components/brain/tabs/TrustTab.jsx
@@ -10,6 +10,7 @@ import {
import BrailleSpinner from '../../BrailleSpinner';
import toast from '../../ui/Toast';
import { FormField } from '../../ui/FormField';
+import ListLoadError from '../../ui/ListLoadError';
import {
STATUS_COLORS,
@@ -22,6 +23,8 @@ export default function TrustTab({ onRefresh }) {
const [entries, setEntries] = useState([]);
const [counts, setCounts] = useState({});
const [settings, setSettings] = useState(null);
+ const [inboxError, setInboxError] = useState(null);
+ const [settingsError, setSettingsError] = useState(null);
const [loading, setLoading] = useState(true);
const [statusFilter, setStatusFilter] = useState('');
const [expandedId, setExpandedId] = useState(null);
@@ -29,15 +32,26 @@ export default function TrustTab({ onRefresh }) {
const [settingsForm, setSettingsForm] = useState({});
const fetchData = useCallback(async () => {
- const [inboxData, settingsData] = await Promise.all([
- api.getBrainInbox({ status: statusFilter || undefined, limit: 100 }).catch(() => ({ entries: [], counts: {} })),
- api.getBrainSettings().catch(() => null)
+ const asError = (error) => (error instanceof Error ? error : new Error('Request failed'));
+ // The rows own their error UI (silent), and a failure is carried as a
+ // value so it never reads as an empty log or as default settings.
+ const [inboxResult, settingsResult] = await Promise.all([
+ api.getBrainInbox({ status: statusFilter || undefined, limit: 100, silent: true })
+ .then((data) => ({ data }), (error) => ({ error: asError(error) })),
+ api.getBrainSettings({ silent: true })
+ .then((data) => ({ data }), (error) => ({ error: asError(error) })),
]);
- setEntries(inboxData.entries || []);
- setCounts(inboxData.counts || {});
- setSettings(settingsData);
- setSettingsForm(settingsData || {});
+ setInboxError(inboxResult.error || null);
+ if (inboxResult.data) {
+ setEntries(inboxResult.data.entries || []);
+ setCounts(inboxResult.data.counts || {});
+ }
+ setSettingsError(settingsResult.error || null);
+ if (settingsResult.data) {
+ setSettings(settingsResult.data);
+ setSettingsForm(settingsResult.data);
+ }
setLoading(false);
}, [statusFilter]);
@@ -90,13 +104,15 @@ export default function TrustTab({ onRefresh }) {
</div>
</div>
- <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
- <span className="text-gray-500">Total: {counts.total || 0}</span>
- <span className="text-port-success">Filed: {counts.filed || 0}</span>
- <span className="text-port-warning">Review: {counts.needs_review || 0}</span>
- <span className="text-blue-400">Corrected: {counts.corrected || 0}</span>
- <span className="text-port-error">Errors: {counts.error || 0}</span>
- </div>
+ {!inboxError && (
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
+ <span className="text-gray-500">Total: {counts.total || 0}</span>
+ <span className="text-port-success">Filed: {counts.filed || 0}</span>
+ <span className="text-port-warning">Review: {counts.needs_review || 0}</span>
+ <span className="text-blue-400">Corrected: {counts.corrected || 0}</span>
+ <span className="text-port-error">Errors: {counts.error || 0}</span>
+ </div>
+ )}
</div>
{/* Settings Section */}
@@ -106,7 +122,7 @@ export default function TrustTab({ onRefresh }) {
<Settings size={16} />
Settings
</h3>
- {!editingSettings && (
+ {!editingSettings && !settingsError && (
<button
onClick={() => setEditingSettings(true)}
className="text-sm text-port-accent hover:underline"
@@ -116,7 +132,9 @@ export default function TrustTab({ onRefresh }) {
)}
</div>
- {editingSettings ? (
+ {settingsError ? (
+ <ListLoadError what="Brain settings" error={settingsError} onRetry={fetchData} />
+ ) : editingSettings ? (
<div className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField label="Confidence Threshold">
@@ -233,7 +251,9 @@ export default function TrustTab({ onRefresh }) {
{/* Audit Log */}
<div className="space-y-2">
- {entries.length === 0 ? (
+ {inboxError ? (
+ <ListLoadError what="the audit log" error={inboxError} onRetry={fetchData} />
+ ) : entries.length === 0 ? (
<p className="text-gray-500 text-center py-8">No entries found.</p>
) : (
entries.map(entry => {
diff --git a/client/src/components/brain/tabs/TrustTab.test.jsx b/client/src/components/brain/tabs/TrustTab.test.jsx
index 80457faece..8be89478f8 100644
--- a/client/src/components/brain/tabs/TrustTab.test.jsx
+++ b/client/src/components/brain/tabs/TrustTab.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, act } from '@testing-library/react';
+import { render, screen, act, fireEvent } from '@testing-library/react';
// ── Mock toast ────────────────────────────────────────────────────────────────
const mockToast = vi.hoisted(() => Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }));
@@ -78,3 +78,23 @@ describe('TrustTab mobile header', () => {
expect(filters.className).toContain('flex-wrap');
});
});
+
+describe('TrustTab failed reads', () => {
+ it('shows retryable errors, not an empty log or default settings, and offers no Edit while settings are unknown', async () => {
+ api.getBrainInbox.mockRejectedValueOnce(new Error('inbox down'));
+ api.getBrainSettings.mockRejectedValueOnce(new Error('settings down'));
+ await renderTab();
+
+ const alerts = screen.getAllByRole('alert');
+ expect(alerts).toHaveLength(2);
+ expect(screen.queryByText('No entries found.')).not.toBeInTheDocument();
+ expect(screen.queryByText(/Confidence Threshold/)).not.toBeInTheDocument();
+ // Saving the default-seeded form would overwrite the stored settings.
+ expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument();
+
+ fireEvent.click(alerts[0].querySelector('button'));
+ await act(async () => {});
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(screen.getByText('No entries found.')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/meatspace/EpigeneticTracker.jsx b/client/src/components/meatspace/EpigeneticTracker.jsx
index 58c4696d76..10d664df44 100644
--- a/client/src/components/meatspace/EpigeneticTracker.jsx
+++ b/client/src/components/meatspace/EpigeneticTracker.jsx
@@ -4,6 +4,8 @@ import {Plus, Trash2, ChevronDown, ChevronRight,
Activity, Pill, Heart, CheckCircle, Calendar, FlameKindling} from 'lucide-react';
import BrailleSpinner from '../BrailleSpinner';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
+import ListLoadError from '../ui/ListLoadError';
+import useListResource from '../../hooks/useListResource';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import * as api from '../../services/api';
@@ -21,7 +23,6 @@ const EVIDENCE_COLORS = {
export default function EpigeneticTracker({ markerCategories = [] }) {
const [interventions, setInterventions] = useState({});
- const [recommendations, setRecommendations] = useState([]);
const [compliance, setCompliance] = useState(null);
const [loading, setLoading] = useState(true);
const [showAdd, setShowAdd] = useState(false);
@@ -37,16 +38,22 @@ export default function EpigeneticTracker({ markerCategories = [] }) {
});
const fetchData = useCallback(async () => {
- const [intData, recData, compData] = await Promise.all([
+ const [intData, compData] = await Promise.all([
api.getEpigeneticInterventions().catch(() => ({ interventions: {} })),
- api.getEpigeneticRecommendations(markerCategories).catch(() => ({ recommendations: [] })),
api.getEpigeneticCompliance(30).catch(() => null)
]);
setInterventions(intData.interventions || {});
- setRecommendations(recData.recommendations || []);
setCompliance(compData);
setLoading(false);
- }, [markerCategories]);
+ }, []);
+
+ // Recommendations are read-only suggestions; a failed read gets its own error row
+ // instead of reading as "nothing recommended".
+ const fetchRecommendations = useCallback(
+ () => api.getEpigeneticRecommendations(markerCategories, { silent: true }).then((data) => data?.recommendations || []),
+ [markerCategories]
+ );
+ const { items: recommendations, state: recState, error: recError, retry: retryRecs } = useListResource(fetchRecommendations);
useEffect(() => { fetchData(); }, [fetchData]);
@@ -343,6 +350,9 @@ export default function EpigeneticTracker({ markerCategories = [] }) {
)}
{/* Recommended Interventions (not yet tracked) */}
+ {recState === 'error' && (
+ <ListLoadError what="recommended interventions" error={recError} onRetry={retryRecs} />
+ )}
{untrackedRecs.length > 0 && (
<div className="space-y-2">
<h4 className="text-sm font-medium text-gray-400 uppercase tracking-wider">
diff --git a/client/src/components/meatspace/EpigeneticTracker.test.jsx b/client/src/components/meatspace/EpigeneticTracker.test.jsx
new file mode 100644
index 0000000000..ac5be8aea4
--- /dev/null
+++ b/client/src/components/meatspace/EpigeneticTracker.test.jsx
@@ -0,0 +1,34 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+vi.mock('../../services/api', () => ({
+ getEpigeneticInterventions: vi.fn(),
+ getEpigeneticRecommendations: vi.fn(),
+ getEpigeneticCompliance: vi.fn(),
+}));
+
+import * as api from '../../services/api';
+import EpigeneticTracker from './EpigeneticTracker';
+
+const CATEGORIES = [];
+const REC = { id: 'omega3', name: 'Omega-3', category: 'supplement', evidence: 'strong' };
+
+beforeEach(() => {
+ api.getEpigeneticInterventions.mockResolvedValue({ interventions: {} });
+ api.getEpigeneticCompliance.mockResolvedValue(null);
+});
+afterEach(cleanup);
+
+describe('EpigeneticTracker recommendations load', () => {
+ it('shows a retryable error — not an absent section — when recommendations fail, then lists them', async () => {
+ api.getEpigeneticRecommendations.mockRejectedValueOnce(new Error('boom'));
+ render(<EpigeneticTracker markerCategories={CATEGORIES} />);
+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load recommended interventions');
+ expect(screen.queryByText(/Recommended Interventions/)).toBeNull();
+
+ api.getEpigeneticRecommendations.mockResolvedValue({ recommendations: [REC] });
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ await waitFor(() => expect(screen.getByText('Recommended Interventions (1)')).toBeTruthy());
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+});
diff --git a/client/src/components/meatspace/HealthCategorySection.jsx b/client/src/components/meatspace/HealthCategorySection.jsx
index 5e5afa2118..0f43d42bf2 100644
--- a/client/src/components/meatspace/HealthCategorySection.jsx
+++ b/client/src/components/meatspace/HealthCategorySection.jsx
@@ -3,11 +3,14 @@ import { ChevronDown, ChevronRight } from 'lucide-react';
import * as api from '../../services/api';
import MetricCard from './MetricCard';
import SleepCard from './SleepCard';
+import ListLoadError from '../ui/ListLoadError';
export default function HealthCategorySection({ category, from, to, expanded, onToggle, availableMetrics }) {
const [metricData, setMetricData] = useState({});
const [latestValues, setLatestValues] = useState({});
const [loading, setLoading] = useState(false);
+ const [failedKeys, setFailedKeys] = useState([]);
+ const [attempt, setAttempt] = useState(0);
const lastRangeRef = useRef(null);
// Filter to only metrics that have data — stabilize the key list for deps
@@ -33,20 +36,24 @@ export default function HealthCategorySection({ category, from, to, expanded, on
Promise.all(
keys.map(key =>
- api.getAppleHealthMetrics(key, from, to)
+ api.getAppleHealthMetrics(key, from, to, { silent: true })
.then(data => ({ key, data: Array.isArray(data) ? data : [] }))
- .catch(() => ({ key, data: [] }))
+ .catch(error => ({ key, data: [], error }))
)
).then(results => {
if (cancelled) return;
const dataMap = {};
const emptyMetrics = [];
+ const failed = [];
for (const r of results) {
dataMap[r.key] = r.data;
- if (r.data.length === 0) emptyMetrics.push(r.key);
+ if (r.error) failed.push(r.key);
+ else if (r.data.length === 0) emptyMetrics.push(r.key);
}
setMetricData(dataMap);
- lastRangeRef.current = cacheKey;
+ setFailedKeys(failed);
+ // A range with a failed read is not cached, so Retry (and re-expanding) refetch it.
+ lastRangeRef.current = failed.length > 0 ? null : cacheKey;
setLoading(false);
// Fetch latest values for metrics with no data in this range
@@ -58,10 +65,14 @@ export default function HealthCategorySection({ category, from, to, expanded, on
});
return () => { cancelled = true; };
- }, [activeMetricKeys, cacheKey, expanded, from, to]);
+ }, [activeMetricKeys, cacheKey, expanded, from, to, attempt]);
if (activeMetrics.length === 0) return null;
+ // A metric whose read failed is not drawn, so its card never claims "no data".
+ const failedMetrics = activeMetrics.filter(m => failedKeys.includes(m.key));
+ const shownMetrics = activeMetrics.filter(m => !failedKeys.includes(m.key));
+
return (
<div className="border border-port-border rounded-xl overflow-hidden">
<button
@@ -77,7 +88,14 @@ export default function HealthCategorySection({ category, from, to, expanded, on
{expanded && (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 p-6 bg-port-bg">
- {activeMetrics.map(metric =>
+ {failedKeys.length > 0 && (
+ <ListLoadError
+ className="lg:col-span-2"
+ what={failedMetrics.map(m => m.label).join(', ')}
+ onRetry={() => setAttempt(n => n + 1)}
+ />
+ )}
+ {shownMetrics.map(metric =>
metric.key === 'sleep_analysis' ? (
<SleepCard key={metric.key} data={metricData[metric.key] ?? []} loading={loading} />
) : (
diff --git a/client/src/components/meatspace/HealthCategorySection.test.jsx b/client/src/components/meatspace/HealthCategorySection.test.jsx
new file mode 100644
index 0000000000..e4f1f520d2
--- /dev/null
+++ b/client/src/components/meatspace/HealthCategorySection.test.jsx
@@ -0,0 +1,48 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+vi.mock('../../services/api', () => ({
+ getAppleHealthMetrics: vi.fn(),
+ getLatestHealthMetrics: vi.fn(),
+}));
+vi.mock('./MetricCard', () => ({
+ default: ({ config, data }) => <div data-testid="metric-card">{config.label}:{data.length}</div>,
+}));
+vi.mock('./SleepCard', () => ({ default: () => null }));
+
+import * as api from '../../services/api';
+import HealthCategorySection from './HealthCategorySection';
+
+const category = { label: 'Activity', metrics: [{ key: 'steps', label: 'Steps' }, { key: 'flights', label: 'Flights' }] };
+const renderSection = () => render(
+ <HealthCategorySection
+ category={category}
+ from="2026-03-01"
+ to="2026-03-07"
+ expanded
+ onToggle={() => {}}
+ availableMetrics={new Set(['steps', 'flights'])}
+ />,
+);
+
+beforeEach(() => {
+ api.getLatestHealthMetrics.mockResolvedValue({});
+});
+afterEach(cleanup);
+
+describe('HealthCategorySection metric loads', () => {
+ it('names the metric whose read failed instead of drawing it as "no data", and retries it', async () => {
+ api.getAppleHealthMetrics.mockImplementation((key) => (key === 'steps'
+ ? Promise.reject(new Error('boom'))
+ : Promise.resolve([{ date: '2026-03-01', value: 3 }])));
+ renderSection();
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load Steps');
+ expect(screen.getAllByTestId('metric-card').map(n => n.textContent)).toEqual(['Flights:1']);
+
+ api.getAppleHealthMetrics.mockResolvedValue([{ date: '2026-03-01', value: 3 }]);
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
+ expect(screen.getAllByTestId('metric-card')).toHaveLength(2);
+ });
+});
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsx
index 56e5236ced..6fff5c3b3d 100644
--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx
+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx
@@ -1,9 +1,11 @@
-import { useState, useEffect, useRef } from 'react';
+import { useState, useEffect, useRef, useCallback } from 'react';
import { Link } from 'react-router';
import { Zap, Play, Brain, Dumbbell, Timer, Target, TrendingUp, TrendingDown, Minus, Compass, ArrowRight, ChevronRight, Layers } from 'lucide-react';
import { getPostReviewReps, getPostRecommendations, getMorseProgress, getPostProgress, getPostBenchmarkProtocol, getMemoryItems, updatePostConfig, getPostCognitiveProgress } from '../../../services/api';
import { FormField } from '../../ui/FormField';
import Pill from '../../ui/Pill';
+import ListLoadError from '../../ui/ListLoadError';
+import toast from '../../ui/Toast';
import { enabledApiProviderFilter } from '../../../utils/providers';
import useProviderModels from '../../../hooks/useProviderModels.js';
import { DOMAINS, DRILL_TO_DOMAIN, DRILL_LABELS, COGNITIVE_LADDER_TYPES, computeDomainAverages, computeGoalProgress, isTopicEnabled, selectMemoryItemForDrill, resolveTopicForDrillType } from './constants';
@@ -181,6 +183,9 @@ export default function PostSessionLauncher({
// until a skill is mastered and its review interval elapses; a load failure
// silently degrades to a plain Quick session.
const [reviewReps, setReviewReps] = useState([]);
+ // A failed read must not look like "no reviews due": the Quick session and the
+ // skill-review rows both depend on it.
+ const [reviewRepsError, setReviewRepsError] = useState(null);
// Ordered "what to practice next" recommendations (issue #2100). A load
// failure silently degrades to an empty list (the panel hides). The top
// recommendation also biases the Quick session's drill picks.
@@ -203,8 +208,15 @@ export default function PostSessionLauncher({
// list and fail closed until the item pool is known (issue #3254).
const [memoryItemsState, setMemoryItemsState] = useState({ status: 'loading', items: [] });
+ const loadReviewReps = useCallback(() => {
+ setReviewRepsError(null);
+ getPostReviewReps(5, { silent: true })
+ .then(r => setReviewReps(r?.reps || []))
+ .catch(err => setReviewRepsError(err instanceof Error ? err : new Error('Request failed')));
+ }, []);
+
useEffect(() => {
- getPostReviewReps(5).then(r => setReviewReps(r?.reps || [])).catch(() => setReviewReps([]));
+ loadReviewReps();
getPostRecommendations()
.then(r => {
setRecommendations(r?.recommendations || []);
@@ -218,7 +230,7 @@ export default function PostSessionLauncher({
getMemoryItems({ silent: true })
.then(items => setMemoryItemsState({ status: 'ready', items: Array.isArray(items) ? items : [] }))
.catch(() => setMemoryItemsState({ status: 'error', items: [] }));
- }, []);
+ }, [loadReviewReps]);
// Only fetch Morse progress when a Morse WPM goal exists — avoids an extra
// request on the common path. Effective WPM prefers the Farnsworth setting.
@@ -624,7 +636,11 @@ export default function PostSessionLauncher({
const skillId = rec.id.replace(/^skill-review:/, '');
let rep = allowedReviewReps.find(r => r.skillId === skillId);
if (!rep) {
- const fresh = await getPostReviewReps(5).then(r => r?.reps || []).catch(() => []);
+ const fresh = await getPostReviewReps(5, { silent: true }).then(r => r?.reps || []).catch(err => {
+ toast.error(`Could not load the review rep: ${err.message}`);
+ return null;
+ });
+ if (!fresh) return;
rep = fresh.filter(r => topicAllowed(r.type)).find(r => r.skillId === skillId);
}
if (!rep) return;
@@ -792,6 +808,10 @@ export default function PostSessionLauncher({
</nav>
</div>
+ {reviewRepsError && (
+ <ListLoadError what="due skill reviews" error={reviewRepsError} onRetry={loadReviewReps} />
+ )}
+
{/* Main + sidebar: primary session flow on the left, drill summaries + history on the right */}
<div className="grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_22rem] gap-6 items-start">
{/* Primary flow — kept above the fold */}
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
index 19477e1b9a..19d50dcff4 100644
--- a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
+++ b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
@@ -312,6 +312,29 @@ describe('PostSessionLauncher render (issue #2100)', () => {
expect(onStart).not.toHaveBeenCalled();
});
+ it('shows a retryable error — not a quiet empty list — when the due-review read fails', async () => {
+ getPostReviewReps.mockRejectedValueOnce(new Error('boom'));
+ renderLauncher();
+ await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(/Could not load due skill reviews/));
+ getPostReviewReps.mockResolvedValue({ reps: [] });
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
+ expect(getPostReviewReps).toHaveBeenCalledTimes(2);
+ });
+
+ it('starts nothing and says why when the on-demand review rep fetch fails', async () => {
+ const onStart = vi.fn();
+ getPostReviewReps.mockResolvedValueOnce({ reps: [] }).mockRejectedValue(new Error('offline'));
+ getPostRecommendations.mockResolvedValue({ recommendations: [
+ { id: 'skill-review:cognitive:n-back:L0', kind: 'skill-review', title: 'Re-verify n-back L0', deepLink: '/post/launcher', drillType: 'n-back', priority: 0 },
+ ] });
+ renderLauncher({ onStart });
+ await waitFor(() => expect(screen.getByText('Re-verify n-back L0')).toBeTruthy());
+ fireEvent.click(screen.getByText('Re-verify n-back L0').closest('button'));
+ await waitFor(() => expect(getPostReviewReps).toHaveBeenCalledTimes(2));
+ expect(onStart).not.toHaveBeenCalled();
+ });
+
it('launches a review rep (with markers) for a skill-review recommendation', async () => {
const onStart = vi.fn();
getPostReviewReps.mockResolvedValue({ reps: [
diff --git a/client/src/components/meatspace/post/PracticePlan.jsx b/client/src/components/meatspace/post/PracticePlan.jsx
index 6582e4b260..d59f9c7b9f 100644
--- a/client/src/components/meatspace/post/PracticePlan.jsx
+++ b/client/src/components/meatspace/post/PracticePlan.jsx
@@ -1,8 +1,10 @@
-import { useState, useEffect } from 'react';
+import { useState } from 'react';
import { ArrowLeft, Save, ChevronRight, ChevronDown, ListChecks, Loader } from 'lucide-react';
import BrowseCatalogLink from './BrowseCatalogLink';
import { updatePostConfig, getMemoryItems } from '../../../services/api';
import toast from '../../ui/Toast';
+import ListLoadError from '../../ui/ListLoadError';
+import useListResource from '../../../hooks/useListResource';
import {
POST_TOPICS,
TOPIC_UI,
@@ -57,6 +59,8 @@ function ToggleRow({ id, label, hint, checked, disabled, onChange, indent = fals
);
}
+const fetchMemoryItems = () => getMemoryItems({ silent: true });
+
export default function PracticePlan({ config, onSaved, onBack }) {
// Draft state seeded once from the loaded config — mirrors PostDrillConfig,
// which is why PostTab only mounts this after the config resolves.
@@ -90,15 +94,13 @@ export default function PracticePlan({ config, onSaved, onBack }) {
})
));
const [memoryItemFlags, setMemoryItemFlags] = useState(() => ({ ...(config?.memory?.items || {}) }));
- const [memoryItems, setMemoryItems] = useState(null);
const [expanded, setExpanded] = useState({});
const [saving, setSaving] = useState(false);
- useEffect(() => {
- // Silent: the plan still renders (and saves) without the item list; only the
- // per-item rows are missing, and an error toast here would be noise.
- getMemoryItems({ silent: true }).then(setMemoryItems).catch(() => setMemoryItems([]));
- }, []);
+ // Silent: the plan still renders (and saves) without the item list; the rows
+ // own the error UI. Saving never reads this list, so a failed load can't erase flags.
+ const { items: memoryItemList, state: memoryItemsState, error: memoryItemsError, retry: retryMemoryItems } = useListResource(fetchMemoryItems);
+ const memoryItems = memoryItemsState === 'loading' ? null : memoryItemList;
// Memory and Morse each have a module-level `enabled` flag on the server AND a
// topic entry. The user gets ONE control — the topic toggle — and save writes
@@ -231,7 +233,10 @@ export default function PracticePlan({ config, onSaved, onBack }) {
<Loader size={12} className="animate-spin" /> Loading your items…
</p>
)}
- {memoryItems?.length === 0 && (
+ {memoryItemsState === 'error' && (
+ <ListLoadError className="ml-7" what="your memorized texts" error={memoryItemsError} onRetry={retryMemoryItems} />
+ )}
+ {memoryItemsState === 'ready' && memoryItems.length === 0 && (
<p className="pl-7 text-xs text-gray-500">No memory items yet — add one from the Memory tab.</p>
)}
{(memoryItems || []).map(item => (
diff --git a/client/src/components/meatspace/post/PracticePlan.test.jsx b/client/src/components/meatspace/post/PracticePlan.test.jsx
index 0d2678a6d5..cfb27410d2 100644
--- a/client/src/components/meatspace/post/PracticePlan.test.jsx
+++ b/client/src/components/meatspace/post/PracticePlan.test.jsx
@@ -130,6 +130,17 @@ describe('PracticePlan summary (issue #3252)', () => {
});
describe('PracticePlan per-item memory control', () => {
+ it('shows a retryable error — not "No memory items yet" — when the item list fails to load', async () => {
+ getMemoryItems.mockRejectedValueOnce(new Error('boom'));
+ await renderPlan();
+ fireEvent.click(screen.getByLabelText('Expand Memory'));
+ expect(await screen.findByRole('alert')).toHaveTextContent(/Could not load your memorized texts/);
+ expect(screen.queryByText(/No memory items yet/)).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());
+ expect(getMemoryItems).toHaveBeenCalledTimes(2);
+ });
+
it('lists memory items under the expanded Memory topic and drops a disabled one from the count', async () => {
await renderPlan();
await waitFor(() => expect(getMemoryItems).toHaveBeenCalled());
diff --git a/client/src/components/meatspace/tabs/AlcoholTab.jsx b/client/src/components/meatspace/tabs/AlcoholTab.jsx
index e6fa8dbd49..31bb498e8a 100644
--- a/client/src/components/meatspace/tabs/AlcoholTab.jsx
+++ b/client/src/components/meatspace/tabs/AlcoholTab.jsx
@@ -3,6 +3,7 @@ import { Beer, Plus, Trash2, AlertTriangle, TrendingDown, TrendingUp, Pencil, Ch
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
import BrailleSpinner from '../../BrailleSpinner';
+import LoadFailureNotice from '../LoadFailureNotice';
import ConfirmButtonPair from '../../ui/ConfirmButtonPair';
import { FormField } from '../../ui/FormField';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
@@ -47,6 +48,7 @@ export default function AlcoholTab() {
const [summary, setSummary] = useState(null);
const [allEntries, setAllEntries] = useState(null);
const [loading, setLoading] = useState(true);
+ const [loadFailed, setLoadFailed] = useState(false);
const [logging, setLogging] = useState(false);
const [refreshKey, setRefreshKey] = useState(0);
const [visibleDays, setVisibleDays] = useState(DAYS_PER_PAGE);
@@ -86,12 +88,15 @@ export default function AlcoholTab() {
}, []);
const fetchData = useCallback(async () => {
- const [summaryData, entries] = await Promise.all([
- api.getAlcoholSummary().catch(() => null),
- api.getDailyAlcohol().catch(() => [])
+ const [summaryResult, entriesResult] = await Promise.allSettled([
+ api.getAlcoholSummary({ silent: true }),
+ api.getDailyAlcohol(undefined, undefined, { silent: true })
]);
- setSummary(summaryData);
- setAllEntries(entries);
+ // A rejected read keeps what is already shown and raises the notice, so a
+ // transient failure never renders as an empty history.
+ if (summaryResult.status === 'fulfilled') setSummary(summaryResult.value);
+ if (entriesResult.status === 'fulfilled') setAllEntries(entriesResult.value);
+ setLoadFailed(summaryResult.status === 'rejected' || entriesResult.status === 'rejected');
setLoading(false);
}, []);
@@ -257,6 +262,9 @@ export default function AlcoholTab() {
return (
<div className="space-y-4">
+ {loadFailed && (
+ <LoadFailureNotice message="Could not load drink history." onRetry={fetchData} />
+ )}
{/* Compact Summary Stats Bar */}
{summary && (
<div className="flex flex-wrap items-center gap-x-5 gap-y-1 px-4 py-2 bg-port-card border border-port-border rounded-lg">
diff --git a/client/src/components/meatspace/tabs/AlcoholTab.loadFailure.test.jsx b/client/src/components/meatspace/tabs/AlcoholTab.loadFailure.test.jsx
new file mode 100644
index 0000000000..d7a85ae277
--- /dev/null
+++ b/client/src/components/meatspace/tabs/AlcoholTab.loadFailure.test.jsx
@@ -0,0 +1,36 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+vi.mock('../../../services/api', () => ({
+ getAlcoholSummary: vi.fn(),
+ getDailyAlcohol: vi.fn(),
+ getCustomDrinks: vi.fn(),
+ getAppleHealthCorrelation: vi.fn(),
+}));
+vi.mock('../AlcoholChart', () => ({ default: () => null }));
+vi.mock('../AlcoholHrvCorrelation', () => ({ default: () => null }));
+vi.mock('../StandardDrinkCalculator', () => ({ default: () => null }));
+
+import * as api from '../../../services/api';
+import AlcoholTab from './AlcoholTab';
+
+beforeEach(() => {
+ api.getAlcoholSummary.mockResolvedValue(null);
+ api.getCustomDrinks.mockResolvedValue(null);
+ api.getAppleHealthCorrelation.mockResolvedValue(null);
+});
+afterEach(cleanup);
+
+describe('AlcoholTab history load', () => {
+ it('shows a retryable notice when the history read fails, then the history once it succeeds', async () => {
+ api.getDailyAlcohol.mockRejectedValueOnce(new Error('boom'));
+ render(<AlcoholTab />);
+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load drink history');
+ expect(screen.queryByText(/All Drink Entries/)).toBeNull();
+
+ api.getDailyAlcohol.mockResolvedValue([{ date: '2026-03-01', alcohol: { drinks: [] } }]);
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ await waitFor(() => expect(screen.getByText(/All Drink Entries \(1 days\)/)).toBeTruthy());
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+});
diff --git a/client/src/components/meatspace/tabs/NicotineTab.jsx b/client/src/components/meatspace/tabs/NicotineTab.jsx
index cce6531e61..b1d74ebab1 100644
--- a/client/src/components/meatspace/tabs/NicotineTab.jsx
+++ b/client/src/components/meatspace/tabs/NicotineTab.jsx
@@ -3,6 +3,7 @@ import { Cigarette, Plus, Trash2, Pencil, Check, X, Settings } from 'lucide-reac
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
import BrailleSpinner from '../../BrailleSpinner';
+import LoadFailureNotice from '../LoadFailureNotice';
import ConfirmButtonPair from '../../ui/ConfirmButtonPair';
import { FormField } from '../../ui/FormField';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
@@ -17,6 +18,7 @@ export default function NicotineTab() {
const [summary, setSummary] = useState(null);
const [allEntries, setAllEntries] = useState(null);
const [loading, setLoading] = useState(true);
+ const [loadFailed, setLoadFailed] = useState(false);
const [logging, setLogging] = useState(false);
const [refreshKey, setRefreshKey] = useState(0);
const [visibleDays, setVisibleDays] = useState(DAYS_PER_PAGE);
@@ -50,12 +52,15 @@ export default function NicotineTab() {
}, []);
const fetchData = useCallback(async () => {
- const [summaryData, entries] = await Promise.all([
- api.getNicotineSummary().catch(() => null),
- api.getDailyNicotine().catch(() => [])
+ const [summaryResult, entriesResult] = await Promise.allSettled([
+ api.getNicotineSummary({ silent: true }),
+ api.getDailyNicotine(undefined, undefined, { silent: true })
]);
- setSummary(summaryData);
- setAllEntries(entries);
+ // A rejected read keeps what is already shown and raises the notice, so a
+ // transient failure never renders as an empty history.
+ if (summaryResult.status === 'fulfilled') setSummary(summaryResult.value);
+ if (entriesResult.status === 'fulfilled') setAllEntries(entriesResult.value);
+ setLoadFailed(summaryResult.status === 'rejected' || entriesResult.status === 'rejected');
setLoading(false);
}, []);
@@ -204,6 +209,9 @@ export default function NicotineTab() {
return (
<div className="space-y-4">
+ {loadFailed && (
+ <LoadFailureNotice message="Could not load nicotine history." onRetry={fetchData} />
+ )}
{/* Compact Summary Stats Bar */}
{summary && (
<div className="flex flex-wrap items-center gap-x-6 gap-y-1 px-4 py-2 bg-port-card border border-port-border rounded-lg">
diff --git a/client/src/components/meatspace/tabs/NicotineTab.loadFailure.test.jsx b/client/src/components/meatspace/tabs/NicotineTab.loadFailure.test.jsx
new file mode 100644
index 0000000000..5124e9b240
--- /dev/null
+++ b/client/src/components/meatspace/tabs/NicotineTab.loadFailure.test.jsx
@@ -0,0 +1,35 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+vi.mock('../../../services/api', () => ({
+ getNicotineSummary: vi.fn(),
+ getDailyNicotine: vi.fn(),
+ getCustomNicotineProducts: vi.fn(),
+ getAppleHealthCorrelation: vi.fn(),
+}));
+vi.mock('../NicotineChart', () => ({ default: () => null }));
+vi.mock('../NicotineHealthCorrelation', () => ({ default: () => null }));
+
+import * as api from '../../../services/api';
+import NicotineTab from './NicotineTab';
+
+beforeEach(() => {
+ api.getNicotineSummary.mockResolvedValue(null);
+ api.getCustomNicotineProducts.mockResolvedValue(null);
+ api.getAppleHealthCorrelation.mockResolvedValue(null);
+});
+afterEach(cleanup);
+
+describe('NicotineTab history load', () => {
+ it('shows a retryable notice when the history read fails, then the history once it succeeds', async () => {
+ api.getDailyNicotine.mockRejectedValueOnce(new Error('boom'));
+ render(<NicotineTab />);
+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load nicotine history');
+ expect(screen.queryByText(/History \(/)).toBeNull();
+
+ api.getDailyNicotine.mockResolvedValue([{ date: '2026-03-01', nicotine: { items: [] } }]);
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ await waitFor(() => expect(screen.getByText(/History \(1 days\)/)).toBeTruthy());
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+});
diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsx
index 0126e97961..9e8d639c55 100644
--- a/client/src/components/meatspace/tabs/PostTab.jsx
+++ b/client/src/components/meatspace/tabs/PostTab.jsx
@@ -4,6 +4,7 @@ import { Loader } from 'lucide-react';
import { getPostConfig, getPostRecommendations, getPostSessions, getPostStats } from '../../../services/api';
import { usePostSession } from '../../../hooks/usePostSession';
import toast from '../../ui/Toast';
+import ListLoadError from '../../ui/ListLoadError';
import PostSessionLauncher from '../post/PostSessionLauncher';
import PostDrillRunner from '../post/PostDrillRunner';
import PostLlmDrillRunner from '../post/PostLlmDrillRunner';
@@ -56,6 +57,7 @@ export default function PostTab({ tab = 'launcher', subtab, mode }) {
const location = useLocation();
const [config, setConfig] = useState(null);
const [recentSessions, setRecentSessions] = useState([]);
+ const [sessionsError, setSessionsError] = useState(null);
const [stats, setStats] = useState(null);
const [statsWeek, setStatsWeek] = useState(null);
const session = usePostSession();
@@ -76,14 +78,18 @@ export default function PostTab({ tab = 'launcher', subtab, mode }) {
}, [tab, subtab, session.state, navigate]);
async function loadData() {
+ let sessionsFailure = null;
const [cfg, sessions, st, stWeek] = await Promise.all([
getPostConfig().catch(() => null),
- getPostSessions().catch(() => []),
+ getPostSessions(undefined, undefined, { silent: true }).catch(err => { sessionsFailure = err; return null; }),
getPostStats(30).catch(() => null),
getPostStats(7).catch(() => null)
]);
setConfig(cfg);
- setRecentSessions(sessions || []);
+ // A failed sessions read keeps the last list and raises a notice, so it never
+ // reads as "no sessions today".
+ setSessionsError(sessionsFailure);
+ if (!sessionsFailure) setRecentSessions(sessions || []);
setStats(st);
setStatsWeek(stWeek);
}
@@ -381,16 +387,21 @@ export default function PostTab({ tab = 'launcher', subtab, mode }) {
}
default:
return (
- <PostSessionLauncher
- config={config}
- recentSessions={recentSessions}
- stats={stats}
- statsWeek={statsWeek}
- onStart={handleStart}
- autoStartRecommendationId={new URLSearchParams(location.search).get('continue')}
- onAutoStartConsumed={() => navigate('/post/launcher', { replace: true })}
- onNavigate={navigate}
- />
+ <>
+ {sessionsError && (
+ <ListLoadError className="mb-4" what="recent sessions" error={sessionsError} onRetry={loadData} />
+ )}
+ <PostSessionLauncher
+ config={config}
+ recentSessions={recentSessions}
+ stats={stats}
+ statsWeek={statsWeek}
+ onStart={handleStart}
+ autoStartRecommendationId={new URLSearchParams(location.search).get('continue')}
+ onAutoStartConsumed={() => navigate('/post/launcher', { replace: true })}
+ onNavigate={navigate}
+ />
+ </>
);
}
}
diff --git a/client/src/components/meatspace/tabs/PostTab.loadFailure.test.jsx b/client/src/components/meatspace/tabs/PostTab.loadFailure.test.jsx
new file mode 100644
index 0000000000..7d4a6d20a1
--- /dev/null
+++ b/client/src/components/meatspace/tabs/PostTab.loadFailure.test.jsx
@@ -0,0 +1,31 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+const { getPostSessions } = vi.hoisted(() => ({ getPostSessions: vi.fn() }));
+vi.mock('../../../services/api', () => ({
+ getPostConfig: () => Promise.resolve(null),
+ getPostRecommendations: () => Promise.resolve({ recommendations: [] }),
+ getPostSessions,
+ getPostStats: () => Promise.resolve(null),
+}));
+vi.mock('../post/PostSessionLauncher', () => ({
+ default: ({ recentSessions }) => <div data-testid="launcher">{recentSessions.length} sessions</div>,
+}));
+
+import PostTab from './PostTab';
+
+afterEach(cleanup);
+
+describe('PostTab recent sessions load', () => {
+ it('raises a retryable notice when the sessions read fails instead of passing an empty list silently', async () => {
+ getPostSessions.mockRejectedValueOnce(new Error('boom'));
+ render(<MemoryRouter><PostTab tab="launcher" /></MemoryRouter>);
+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load recent sessions');
+
+ getPostSessions.mockResolvedValue([{ id: 's1', date: '2026-03-01' }]);
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });
+ expect(screen.queryByRole('alert')).toBeNull();
+ expect(screen.getByTestId('launcher')).toHaveTextContent('1 sessions');
+ });
+});
diff --git a/client/src/components/messages/DraftsTab.jsx b/client/src/components/messages/DraftsTab.jsx
index 9e315f812b..c0fe89088e 100644
--- a/client/src/components/messages/DraftsTab.jsx
+++ b/client/src/components/messages/DraftsTab.jsx
@@ -6,6 +6,7 @@ import InlineConfirmRow from '../ui/InlineConfirmRow';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import { copyToClipboard } from '../../lib/clipboard.js';
import BrailleSpinner from '../BrailleSpinner';
+import ListLoadError from '../ui/ListLoadError';
function DeliveryReconciliation({ draft, onReconciled }) {
const [checkedMailbox, setCheckedMailbox] = useState(false);
@@ -64,6 +65,7 @@ function DeliveryReconciliation({ draft, onReconciled }) {
export default function DraftsTab({ accounts }) {
const [drafts, setDrafts] = useState([]);
const [loading, setLoading] = useState(true);
+ const [loadError, setLoadError] = useState(null);
const sendingRef = useRef(new Set());
const [sendingIds, setSendingIds] = useState(new Set());
const [copiedId, setCopiedId] = useState(null);
@@ -80,8 +82,16 @@ export default function DraftsTab({ accounts }) {
const fetchDrafts = useCallback(async () => {
setLoading(true);
- const data = await api.getMessageDrafts().catch(() => []);
- setDrafts(data || []);
+ // A failed read keeps whatever drafts are already shown and surfaces an error row;
+ // it must not read as "No drafts".
+ const data = await api.getMessageDrafts({}, { silent: true }).catch((err) => {
+ setLoadError(err instanceof Error ? err : new Error('Request failed'));
+ return null;
+ });
+ if (data) {
+ setDrafts(data);
+ setLoadError(null);
+ }
setLoading(false);
}, []);
@@ -160,7 +170,11 @@ export default function DraftsTab({ accounts }) {
</div>
)}
- {drafts.length === 0 && !loading && (
+ {loadError && (
+ <ListLoadError what="drafts" error={loadError} onRetry={fetchDrafts} retrying={loading} />
+ )}
+
+ {drafts.length === 0 && !loading && !loadError && (
<div className="text-center py-12 text-gray-500">
<FileText size={48} className="mx-auto mb-4 opacity-50" />
<p>No drafts</p>
diff --git a/client/src/components/messages/DraftsTab.test.jsx b/client/src/components/messages/DraftsTab.test.jsx
index 0d70f2a31e..2f47d21a61 100644
--- a/client/src/components/messages/DraftsTab.test.jsx
+++ b/client/src/components/messages/DraftsTab.test.jsx
@@ -202,3 +202,21 @@ describe('DraftsTab send capabilities', () => {
expect(screen.queryByLabelText('Loading drafts…')).not.toBeInTheDocument();
});
});
+
+describe('DraftsTab — failed read', () => {
+ it('shows an error with Retry instead of "No drafts", then the drafts after Retry', async () => {
+ api.getMessageDrafts.mockRejectedValueOnce(new Error('drafts down'));
+ render(<DraftsTab accounts={[]} />);
+
+ expect(await screen.findByText(/Could not load drafts — drafts down/)).toBeTruthy();
+ expect(screen.queryByText('No drafts')).toBeNull();
+
+ api.getMessageDrafts.mockResolvedValueOnce([
+ { id: 'd1', status: 'draft', sendVia: 'api', subject: 'Recovered draft' },
+ ]);
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+
+ expect(await screen.findByText('Recovered draft')).toBeTruthy();
+ expect(screen.queryByText(/Could not load drafts/)).toBeNull();
+ });
+});
diff --git a/client/src/components/messages/IMessageTab.jsx b/client/src/components/messages/IMessageTab.jsx
index 2292d6fed5..d95b66d75b 100644
--- a/client/src/components/messages/IMessageTab.jsx
+++ b/client/src/components/messages/IMessageTab.jsx
@@ -7,6 +7,7 @@ import {
import BrailleSpinner from '../BrailleSpinner';
import Drawer from '../Drawer';
import toast from '../ui/Toast';
+import ListLoadError from '../ui/ListLoadError';
import * as api from '../../services/api';
import { formatClockTime, formatCount, timeAgo, formatDateNumeric } from '../../utils/formatters';
import useDrawerTab from '../../hooks/useDrawerTab';
@@ -391,13 +392,24 @@ function ConversationDetail({
function BlocklistPanel({ onChanged }) {
const [handles, setHandles] = useState([]);
const [loading, setLoading] = useState(true);
+ const [loadError, setLoadError] = useState(null);
+ const [attempt, setAttempt] = useState(0);
useEffect(() => {
+ let active = true;
+ setLoading(true);
api.getImessageBlocklist({ silent: true })
- .then((res) => setHandles(res?.handles || []))
- .catch(() => setHandles([]))
- .finally(() => setLoading(false));
- }, []);
+ .then((res) => {
+ if (!active) return;
+ setHandles(res?.handles || []);
+ setLoadError(null);
+ })
+ .catch((err) => {
+ if (active) setLoadError(err instanceof Error ? err : new Error('Request failed'));
+ })
+ .finally(() => { if (active) setLoading(false); });
+ return () => { active = false; };
+ }, [attempt]);
const unblock = async (handle) => {
const res = await api.removeImessageBlocklist(handle, { silent: true }).catch(() => null);
@@ -410,6 +422,10 @@ function BlocklistPanel({ onChanged }) {
onChanged?.();
};
+ // A failed read must not look like "nobody is blocked".
+ if (loadError) {
+ return <ListLoadError what="blocked handles" error={loadError} onRetry={() => setAttempt((n) => n + 1)} retrying={loading} className="shrink-0" />;
+ }
if (loading || handles.length === 0) return null;
return (
diff --git a/client/src/components/messages/IMessageTab.test.jsx b/client/src/components/messages/IMessageTab.test.jsx
index d1994da483..e7e1c58913 100644
--- a/client/src/components/messages/IMessageTab.test.jsx
+++ b/client/src/components/messages/IMessageTab.test.jsx
@@ -4,6 +4,7 @@ import { MemoryRouter, Route, Routes, useLocation } from 'react-router';
const api = vi.hoisted(() => ({
checkImessageSetup: vi.fn(),
+ getImessageBlocklist: vi.fn(),
getImessageConversationEvents: vi.fn(),
getImessageConversations: vi.fn(),
getImessageStats: vi.fn(),
@@ -36,6 +37,7 @@ function renderTab(route = '/messages/imessage') {
beforeEach(() => {
vi.clearAllMocks();
+ api.getImessageBlocklist.mockResolvedValue({ handles: [] });
api.getImessageStats.mockResolvedValue({ eventCount: 2, conversationCount: 1, blockedCount: 0 });
api.getImessageConversations.mockResolvedValue({ conversations: [] });
api.getImessageConversationEvents.mockResolvedValue({ events: [], identity: null });
@@ -87,3 +89,19 @@ describe('IMessageTab — settings drawer', () => {
});
});
});
+
+describe('IMessageTab — blocked handles read', () => {
+ it('shows an error with Retry when the blocklist read fails, then the handles after Retry', async () => {
+ api.getImessageStats.mockResolvedValue({ eventCount: 2, conversationCount: 1, blockedCount: 1 });
+ api.getImessageBlocklist.mockRejectedValueOnce(new Error('blocklist down'));
+ renderTab();
+
+ expect(await screen.findByText(/Could not load blocked handles — blocklist down/)).toBeTruthy();
+
+ api.getImessageBlocklist.mockResolvedValueOnce({ handles: ['+15550100'] });
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+
+ expect(await screen.findByRole('button', { name: 'Unblock +15550100' })).toBeTruthy();
+ expect(screen.queryByText(/Could not load blocked handles/)).toBeNull();
+ });
+});
diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsx
index 39e278e8c1..08ff4272dd 100644
--- a/client/src/pages/Tribe.jsx
+++ b/client/src/pages/Tribe.jsx
@@ -29,6 +29,7 @@ import Banner from '../components/ui/Banner';
import PageHeader from '../components/PageHeader';
import { localDateStr } from '../components/meatspace/constants';
import toast from '../components/ui/Toast';
+import ListLoadError from '../components/ui/ListLoadError';
import TabPills from '../components/ui/TabPills';
import TribeCircleMap from '../components/tribe/TribeCircleMap.jsx';
import { copyToClipboard } from '../lib/clipboard.js';
@@ -408,23 +409,32 @@ function MemoryLinksPanel({ personId }) {
const [memoryId, setMemoryId] = useState('');
const [note, setNote] = useState('');
const [loading, setLoading] = useState(false);
+ // Each read fails on its own: a failed link read must not say "No memories linked yet",
+ // nor a failed picker read render an empty picker.
+ const [linksError, setLinksError] = useState(null);
+ const [memoriesError, setMemoriesError] = useState(null);
+ const [attempt, setAttempt] = useState(0);
useEffect(() => {
if (!personId) return;
let cancelled = false;
setLoading(true);
+ setLinksError(null);
+ setMemoriesError(null);
+ const asError = (err) => (err instanceof Error ? err : new Error('Request failed'));
Promise.all([
- api.getTribeMemoryLinks(personId).catch(() => ({ links: [] })),
- api.getMemories({ limit: 25, sortBy: 'updatedAt', sortOrder: 'desc' }).catch(() => ({ memories: [] })),
- ]).then(([linkResult, memoryResult]) => {
- if (cancelled) return;
- setLinks(linkResult?.links || []);
- setMemories(memoryResult?.memories || []);
- }).finally(() => {
+ api.getTribeMemoryLinks(personId, { silent: true })
+ .then((result) => { if (!cancelled) setLinks(result?.links || []); })
+ .catch((err) => { if (!cancelled) setLinksError(asError(err)); }),
+ api.getMemories({ limit: 25, sortBy: 'updatedAt', sortOrder: 'desc' }, { silent: true })
+ .then((result) => { if (!cancelled) setMemories(result?.memories || []); })
+ .catch((err) => { if (!cancelled) setMemoriesError(asError(err)); }),
+ ]).finally(() => {
if (!cancelled) setLoading(false);
});
return () => { cancelled = true; };
- }, [personId]);
+ }, [personId, attempt]);
+ const retry = () => setAttempt((n) => n + 1);
const linkMemory = async () => {
if (!memoryId) return;
@@ -454,6 +464,7 @@ function MemoryLinksPanel({ personId }) {
{loading && <span className="text-xs text-gray-500">Loading</span>}
</div>
<div className="mt-3 grid gap-2">
+ {memoriesError && <ListLoadError what="recent memories" error={memoriesError} onRetry={retry} retrying={loading} />}
<select
aria-label="Brain memory"
value={memoryId}
@@ -484,6 +495,7 @@ function MemoryLinksPanel({ personId }) {
</div>
<div className="mt-4 grid gap-2">
+ {linksError && <ListLoadError what="linked memories" error={linksError} onRetry={retry} retrying={loading} />}
{links.length ? links.map((link) => (
<div key={link.memoryId} className="rounded border border-port-border bg-port-bg p-3">
<div className="flex items-start justify-between gap-3">
@@ -502,7 +514,7 @@ function MemoryLinksPanel({ personId }) {
</button>
</div>
</div>
- )) : (
+ )) : !linksError && !loading && (
<p className="text-sm text-gray-500">No memories linked yet.</p>
)}
</div>
diff --git a/client/src/pages/Tribe.test.jsx b/client/src/pages/Tribe.test.jsx
index 7099c6dee3..f18c2d16b6 100644
--- a/client/src/pages/Tribe.test.jsx
+++ b/client/src/pages/Tribe.test.jsx
@@ -355,3 +355,32 @@ describe('Tribe "Linked on Beeper" block (#99)', () => {
await waitFor(() => expect(screen.queryByText('Linked on Beeper')).toBeNull());
});
});
+
+describe('Tribe memory links panel — failed reads', () => {
+ beforeEach(() => {
+ api.getTribePeople.mockResolvedValue({ people: PEOPLE });
+ window.localStorage.clear();
+ });
+ afterEach(() => {
+ api.getTribeMemoryLinks.mockResolvedValue({ links: [] });
+ api.getMemories.mockResolvedValue({ memories: [] });
+ });
+
+ it('shows an error with Retry instead of "No memories linked yet" when the link read fails', async () => {
+ api.getTribeMemoryLinks.mockRejectedValueOnce(new Error('links down'));
+ api.getMemories.mockRejectedValueOnce(new Error('memories down'));
+
+ renderAt('/tribe?tab=circle');
+ fireEvent.click(await screen.findByText('Example Person'));
+
+ expect(await screen.findByText(/Could not load linked memories — links down/)).toBeTruthy();
+ expect(screen.getByText(/Could not load recent memories — memories down/)).toBeTruthy();
+ expect(screen.queryByText('No memories linked yet.')).toBeNull();
+
+ api.getTribeMemoryLinks.mockResolvedValueOnce({ links: [] });
+ api.getMemories.mockResolvedValueOnce({ memories: [] });
+ fireEvent.click(screen.getAllByRole('button', { name: 'Retry' })[0]);
+ expect(await screen.findByText('No memories linked yet.')).toBeTruthy();
+ expect(screen.queryByText(/Could not load/)).toBeNull();
+ });
+});
diff --git a/client/src/services/apiHealth.js b/client/src/services/apiHealth.js
index a8fe2b8d3c..249abebf5b 100644
--- a/client/src/services/apiHealth.js
+++ b/client/src/services/apiHealth.js
@@ -5,11 +5,11 @@ export const ingestAppleHealth = (data) => request('/health/ingest', {
method: 'POST',
body: JSON.stringify(data)
});
-export const getAppleHealthMetrics = (metricName, from, to) => {
+export const getAppleHealthMetrics = (metricName, from, to, options = {}) => {
const params = new URLSearchParams();
if (from) params.set('from', from);
if (to) params.set('to', to);
- return request(`/health/metrics/${metricName}/daily?${params}`);
+ return request(`/health/metrics/${metricName}/daily?${params}`, options);
};
export const getAvailableHealthMetrics = () => request('/health/metrics/available');
export const getLatestHealthMetrics = (metricNames, options = {}) =>
diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.js
index 96f116bb27..011a39cca8 100644
--- a/client/src/services/apiMeatspace.js
+++ b/client/src/services/apiMeatspace.js
@@ -30,8 +30,8 @@ export const scanClinvar = () => request('/meatspace/genome/clinvar/scan', { met
// MeatSpace - Epigenetic Lifestyle Tracking
export const getEpigeneticInterventions = () => request('/meatspace/genome/epigenetic');
-export const getEpigeneticRecommendations = (categories = []) =>
- request(`/meatspace/genome/epigenetic/recommendations${categories.length ? `?categories=${categories.join(',')}` : ''}`);
+export const getEpigeneticRecommendations = (categories = [], options = {}) =>
+ request(`/meatspace/genome/epigenetic/recommendations${categories.length ? `?categories=${categories.join(',')}` : ''}`, options);
export const getEpigeneticCompliance = (days = 30) =>
request(`/meatspace/genome/epigenetic/compliance?days=${days}`);
export const addEpigeneticIntervention = (data) => request('/meatspace/genome/epigenetic', {
@@ -64,7 +64,7 @@ export const setMeatspaceBirthDate = (birthDate) => request('/meatspace/birth-da
});
export const getDeathClock = () => request('/meatspace/death-clock');
export const getMeatspaceLoggingStats = (options = {}) => request('/meatspace/logging-stats', options);
-export const getAlcoholSummary = () => request('/meatspace/alcohol');
+export const getAlcoholSummary = (options = {}) => request('/meatspace/alcohol', options);
export const getDailyAlcohol = (from, to, options = {}) => {
const params = new URLSearchParams();
if (from) params.set('from', from);
@@ -96,7 +96,7 @@ export const updateCustomDrink = (index, data, options = {}) => request(`/meatsp
export const removeCustomDrink = (index) => request(`/meatspace/alcohol/custom-drinks/${index}`, {
method: 'DELETE'
});
-export const getNicotineSummary = () => request('/meatspace/nicotine');
+export const getNicotineSummary = (options = {}) => request('/meatspace/nicotine', options);
export const getDailyNicotine = (from, to, options = {}) => {
const params = new URLSearchParams();
if (from) params.set('from', from);
@@ -160,11 +160,11 @@ export const updatePostConfig = (data, options = {}) => request('/meatspace/post
body: JSON.stringify(data),
...options
});
-export const getPostSessions = (from, to) => {
+export const getPostSessions = (from, to, options = {}) => {
const params = new URLSearchParams();
if (from) params.set('from', from);
if (to) params.set('to', to);
- return request(`/meatspace/post/sessions?${params}`);
+ return request(`/meatspace/post/sessions?${params}`, options);
};
export const getPostSession = (id, options = {}) => request(`/meatspace/post/sessions/${id}`, options);
export const submitPostSession = (data, options = {}) => request('/meatspace/post/sessions', {
diff --git a/client/src/services/apiMessages.js b/client/src/services/apiMessages.js
index 89140a2d8f..93e5b45381 100644
--- a/client/src/services/apiMessages.js
+++ b/client/src/services/apiMessages.js
@@ -21,12 +21,12 @@ export const getMessageInbox = (params = {}, options = {}) => {
};
export const getMessageDetail = (accountId, messageId, options = {}) => request(`/messages/${accountId}/${messageId}`, options);
export const getMessageThread = (accountId, threadId) => request(`/messages/thread/${accountId}/${threadId}`);
-export const getMessageDrafts = (params = {}) => {
+export const getMessageDrafts = (params = {}, options = {}) => {
const qs = new URLSearchParams();
if (params.accountId) qs.set('accountId', params.accountId);
if (params.status) qs.set('status', params.status);
const str = qs.toString();
- return request(`/messages/drafts${str ? `?${str}` : ''}`);
+ return request(`/messages/drafts${str ? `?${str}` : ''}`, options);
};
export const createMessageDraft = (data) => request('/messages/drafts', { method: 'POST', body: JSON.stringify(data) });
export const generateMessageDraft = (data) => request('/messages/drafts/generate', { method: 'POST', body: JSON.stringify(data) });
diff --git a/client/src/services/apiTribe.js b/client/src/services/apiTribe.js
index cd9bff73db..008bb7aca7 100644
--- a/client/src/services/apiTribe.js
+++ b/client/src/services/apiTribe.js
@@ -51,7 +51,7 @@ export const createTribeTouchpoint = (personId, data = {}, options = {}) => requ
...options,
});
-export const getTribeMemoryLinks = (personId) => request(`/tribe/people/${personId}/memories`);
+export const getTribeMemoryLinks = (personId, options = {}) => request(`/tribe/people/${personId}/memories`, options);
export const linkTribeMemory = (personId, data, options = {}) => request(`/tribe/people/${personId}/memories`, {
method: 'POST',