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: address Brain refresh race and error feedback (#7859)

[._.]/ Adam Eivy9141b8857358
diff --git a/client/src/components/brain/tabs/NotesTab.jsx b/client/src/components/brain/tabs/NotesTab.jsx
index 70dafdaa90..654b202c96 100644
--- a/client/src/components/brain/tabs/NotesTab.jsx
+++ b/client/src/components/brain/tabs/NotesTab.jsx
@@ -64,6 +64,7 @@ export default function NotesTab() {
// Notes state
const [notes, setNotes] = useState([]);
+ const [notesKey, setNotesKey] = useState(null);
const [totalNotes, setTotalNotes] = useState(0);
// Notes the server skipped because iCloud hasn't downloaded them — surfaced so
// an incomplete list isn't presented as the whole vault.
@@ -135,6 +136,7 @@ export default function NotesTab() {
searchSeqRef.current += 1;
clearSelection();
setNotes([]);
+ setNotesKey(null);
setTotalNotes(0);
setSkippedNotes(0);
setFolders([]);
@@ -214,12 +216,14 @@ export default function NotesTab() {
if (!selectedVaultId) return;
const scope = vaultScopeRef.current;
const sequence = ++scanSeqRef.current;
+ const requestKey = `${selectedVaultId}\u0000${folderFilter}`;
setScanning(true);
setScanError(false);
const data = await api.scanNotesVault(selectedVaultId, { folder: folderFilter, limit: 500, silent: true }).catch(() => null);
if (!isCurrentScope(scope) || sequence !== scanSeqRef.current) return;
if (data) {
setNotes(data.notes);
+ setNotesKey(requestKey);
setTotalNotes(data.total);
setSkippedNotes(data.skippedUnavailable || 0);
} else setScanError(true);
@@ -236,7 +240,7 @@ export default function NotesTab() {
const loadTags = async () => {
if (!selectedVaultId) return;
const scope = vaultScopeRef.current;
- const data = await api.getNotesVaultTags(selectedVaultId, { silent: true }).catch(() => null);
+ const data = await api.getNotesVaultTags(selectedVaultId).catch(() => null);
if (isCurrentScope(scope) && data?.tags) setTags(data.tags);
};
@@ -297,7 +301,10 @@ export default function NotesTab() {
const handleAddVault = async (name, path) => {
const scope = vaultScopeRef.current;
setAddingVault(true);
- const result = await api.addNotesVault({ name, path }, { silent: true }).catch(() => null);
+ const result = await api.addNotesVault({ name, path }, { silent: true }).catch((error) => {
+ toast.error(error?.message || 'Failed to add vault');
+ return null;
+ });
if (!isCurrentScope(scope)) return;
setAddingVault(false);
if (result) {
@@ -337,7 +344,10 @@ export default function NotesTab() {
const scope = vaultScopeRef.current;
const sequence = selectSeqRef.current;
setCreating(true);
- const data = await api.createNote(selectedVaultId, newNotePath.trim(), '', { silent: true }).catch(() => null);
+ const data = await api.createNote(selectedVaultId, newNotePath.trim(), '', { silent: true }).catch((error) => {
+ toast.error(error?.message || 'Failed to create note');
+ return null;
+ });
if (!isCurrentScope(scope)) return;
setCreating(false);
if (data) {
@@ -352,8 +362,13 @@ export default function NotesTab() {
const handleDeleteNote = async (notePath) => {
const scope = vaultScopeRef.current;
const sequence = selectSeqRef.current;
- await api.deleteNote(selectedVaultId, notePath, { silent: true }).catch(() => null);
- if (!isCurrentScope(scope)) return;
+ const deleted = await api.deleteNote(selectedVaultId, notePath, { silent: true })
+ .then(() => true)
+ .catch((error) => {
+ toast.error(error?.message || 'Failed to delete note');
+ return false;
+ });
+ if (!deleted || !isCurrentScope(scope)) return;
toast.success('Note deleted');
cancelDelete();
setNotes(prev => prev.filter(n => n.path !== notePath));
@@ -432,16 +447,20 @@ export default function NotesTab() {
);
}
+ const notesKeyForView = `${selectedVaultId}\u0000${folderFilter}`;
+ const hasCurrentNotes = notesKey === notesKeyForView;
+ const currentNotes = hasCurrentNotes ? notes : [];
+
// Build folder tree from notes
const rootNotes = folderFilter
- ? notes
- : notes.filter(n => !n.folder);
+ ? currentNotes
+ : currentNotes.filter(n => !n.folder);
const folderNotes = folderFilter
? []
- : [...new Set(notes.filter(n => n.folder).map(n => n.folder.split('/')[0]))];
+ : [...new Set(currentNotes.filter(n => n.folder).map(n => n.folder.split('/')[0]))];
// Determine what to show in list
- const displayNotes = searchQuery ? (searchResults?.results || []) : notes;
+ const displayNotes = searchQuery ? (searchResults?.results || []) : currentNotes;
return (
<div className="grid grid-cols-1 md:grid-cols-[320px_1fr] grid-rows-1 h-full min-h-0 overflow-hidden">
@@ -539,11 +558,11 @@ export default function NotesTab() {
/>
)}
- <OfflineNotesNotice count={skippedNotes + (searchResults?.skippedUnavailable || 0)} className="mx-3 mt-2" />
+ <OfflineNotesNotice count={(hasCurrentNotes ? skippedNotes : 0) + (searchResults?.skippedUnavailable || 0)} className="mx-3 mt-2" />
{/* Stats bar */}
<div className="px-3 py-1.5 border-b border-port-border flex items-center gap-3 text-xs text-gray-500">
- <span>{formatCount(totalNotes)} notes</span>
+ <span>{formatCount(hasCurrentNotes ? totalNotes : 0)} notes</span>
{folderFilter && (
<button
onClick={() => updateParams({ folder: null })}
@@ -591,7 +610,7 @@ export default function NotesTab() {
{scanError && (
<UnavailableState
title="Notes are unavailable"
- message={notes.length > 0 ? 'Showing the last successful scan. Retry when the vault is reachable.' : 'The vault scan did not complete, so an empty list is not being shown.'}
+ message={hasCurrentNotes && notes.length > 0 ? 'Showing the last successful scan. Retry when the vault is reachable.' : 'The vault scan did not complete, so an empty list is not being shown.'}
onRetry={loadNotes}
/>
)}
@@ -605,7 +624,7 @@ export default function NotesTab() {
{/* Note list */}
<div className="flex-1 overflow-auto">
- {scanning && notes.length === 0 && !searchQuery ? (
+ {scanning && (!hasCurrentNotes || notes.length === 0) && !searchQuery ? (
<div className="flex items-center justify-center h-32 text-gray-500 text-sm">
<BrailleSpinner /> Scanning vault...
</div>
@@ -613,7 +632,7 @@ export default function NotesTab() {
<div className="flex items-center justify-center h-32 text-gray-500 text-sm">
<BrailleSpinner /> Searching notes...
</div>
- ) : (!searchQuery && scanError && notes.length === 0) || (searchQuery && searchError && !searchResults) ? null : displayNotes.length === 0 ? (
+ ) : (!searchQuery && scanError && (!hasCurrentNotes || notes.length === 0)) || (searchQuery && searchError && !searchResults) ? null : displayNotes.length === 0 ? (
<div className="flex items-center justify-center h-32 px-4 text-center text-gray-500 text-sm">
{searchQuery ? 'No matches found' : 'No notes yet — capture notes in your vault to enrich Ask Yourself and your digital twin.'}
</div>
@@ -624,7 +643,7 @@ export default function NotesTab() {
<FolderItem
key={folder}
folder={folder}
- notes={notes.filter(n => n.folder === folder || n.folder.startsWith(folder + '/'))}
+ notes={currentNotes.filter(n => n.folder === folder || n.folder.startsWith(folder + '/'))}
expanded={expandedFolders.has(folder)}
onToggle={() => toggleFolder(folder)}
onSelectNote={handleSelectNote}
@@ -643,7 +662,7 @@ export default function NotesTab() {
/>
))}
{/* Notes in filtered folder */}
- {folderFilter && notes.filter(n => n.folder).map(note => (
+ {folderFilter && currentNotes.filter(n => n.folder).map(note => (
<NoteListItem
key={note.path}
note={note}
diff --git a/client/src/components/brain/tabs/NotesTab.test.jsx b/client/src/components/brain/tabs/NotesTab.test.jsx
index 10047af972..a40b7748af 100644
--- a/client/src/components/brain/tabs/NotesTab.test.jsx
+++ b/client/src/components/brain/tabs/NotesTab.test.jsx
@@ -534,6 +534,62 @@ describe('NotesTab URL state and unavailable reads', () => {
expect(screen.queryByText('Notes are unavailable')).toBeNull();
});
+ it('does not render the previous folder when the next folder scan fails', async () => {
+ const project = { ...note, path: 'Projects/project.md', name: 'project', folder: 'Projects' };
+ const otherNotes = Array.from({ length: 21 }, (_, index) => ({
+ ...note,
+ path: `Other/other-${index}.md`,
+ name: `other-${index}`,
+ folder: 'Other',
+ }));
+ api.scanNotesVault.mockResolvedValueOnce({ notes: [project, ...otherNotes], total: 22 });
+ await renderTab();
+
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Other 21' })); });
+ await screen.findByRole('button', { name: 'Show all 21 notes...' });
+ api.scanNotesVault.mockRejectedValueOnce(new Error('temporary outage'));
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Show all 21 notes...' })); });
+
+ expect(await screen.findByText('Notes are unavailable')).toBeInTheDocument();
+ expect(screen.queryByText('project')).toBeNull();
+ });
+
+ it('surfaces vault-add, note-create, and note-delete failures without false success', async () => {
+ const rootNote = { ...note, path: 'first.md', name: 'first', folder: '' };
+ api.scanNotesVault.mockResolvedValueOnce({ notes: [rootNote], total: 1 });
+ api.addNotesVault.mockRejectedValueOnce(new Error('vault unavailable'));
+ await renderTab();
+ fireEvent.click(screen.getByRole('button', { name: 'Manage vaults' }));
+ fireEvent.change(screen.getByRole('textbox', { name: 'Custom vault path' }), { target: { value: '/new/vault' } });
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Add' })); });
+ expect(mockToast.error).toHaveBeenCalledWith('vault unavailable');
+
+ api.createNote.mockRejectedValueOnce(new Error('note unavailable'));
+ fireEvent.click(screen.getByRole('button', { name: 'Close' }));
+ fireEvent.click(screen.getByRole('button', { name: 'New note' }));
+ fireEvent.change(screen.getByRole('textbox', { name: 'New note path' }), { target: { value: 'new.md' } });
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Create' })); });
+ expect(mockToast.error).toHaveBeenCalledWith('note unavailable');
+
+ api.getNote.mockResolvedValueOnce(rootNote);
+ api.deleteNote.mockRejectedValueOnce(new Error('delete unavailable'));
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Close' })); });
+ await act(async () => { fireEvent.click(screen.getByText('first')); });
+ await screen.findByRole('heading', { name: 'first' });
+ fireEvent.click(screen.getByRole('button', { name: 'Delete note' }));
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Delete', exact: true })); });
+ expect(mockToast.error).toHaveBeenCalledWith('delete unavailable');
+ expect(mockToast.success).not.toHaveBeenCalledWith('Note deleted');
+ expect(screen.getByRole('heading', { name: 'first' })).toBeInTheDocument();
+ });
+
+ it('keeps tag-read failures visible through the normal API error feedback', async () => {
+ api.getNotesVaultTags.mockRejectedValueOnce(new Error('tags unavailable'));
+ await renderTab();
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Tags' })); });
+ expect(api.getNotesVaultTags).toHaveBeenCalledWith('vault-1');
+ });
+
it('keeps a failed note deep link open for retry instead of showing blank content', async () => {
api.getNote.mockRejectedValueOnce(new Error('temporary outage'));
await renderTab('/brain/notes?vault=vault-1&note=Projects%2Ffirst.md');
diff --git a/client/src/components/brain/tabs/ThreadsTab.jsx b/client/src/components/brain/tabs/ThreadsTab.jsx
index f4e1ec5162..079eeeb567 100644
--- a/client/src/components/brain/tabs/ThreadsTab.jsx
+++ b/client/src/components/brain/tabs/ThreadsTab.jsx
@@ -167,6 +167,7 @@ export default function ThreadsTab() {
const [drawerTab, setDrawerTab] = useDrawerTab('threadTab', 'details', DRAWER_TAB_IDS);
const [threads, setThreads] = useState([]);
+ const [threadsKey, setThreadsKey] = useState(null);
const [loading, setLoading] = useState(true);
const [listError, setListError] = useState(false);
const [newTitle, setNewTitle] = useState('');
@@ -178,6 +179,7 @@ export default function ThreadsTab() {
const [confirmDelete, setConfirmDelete] = useState(false);
const [completingSource, setCompletingSource] = useState(false);
const [newRef, setNewRef] = useState({ kind: 'url', id: '', label: '' });
+ const listRequestRef = useRef(0);
// Two-stage search (the Catalog page's pattern): `searchInput` is what the
// user is typing; `q` (the URL) drives the fetch and only moves after a
@@ -191,24 +193,34 @@ export default function ThreadsTab() {
}, [searchInput, q, updateParams]);
// The list — one request for exactly the statuses the view shows. Keep the
- // last good list when a refresh fails: an unavailable response is not an
- // empty working set.
+ // last good list when a refresh fails only when it belongs to the same filter;
+ // a failed new filter must not present another filter's records as current.
+ const listStatus = statusView === 'all' ? WORKING_SET : statusView;
+ const listKey = JSON.stringify({ q, tag, status: listStatus });
+ const hasCurrentList = threadsKey === listKey;
const loadThreads = useCallback(() => {
+ const requestId = ++listRequestRef.current;
+ const requestKey = listKey;
let active = true;
setLoading(true);
setListError(false);
api.listThreads(
- { q, tag, status: statusView === 'all' ? WORKING_SET : statusView },
+ { q, tag, status: listStatus },
{ silent: true },
)
.then((res) => {
- if (!active) return;
+ if (!active || requestId !== listRequestRef.current) return;
setThreads(Array.isArray(res?.threads) ? res.threads : []);
+ setThreadsKey(requestKey);
+ })
+ .catch(() => {
+ if (active && requestId === listRequestRef.current) setListError(true);
})
- .catch(() => { if (active) setListError(true); })
- .finally(() => { if (active) setLoading(false); });
+ .finally(() => {
+ if (active && requestId === listRequestRef.current) setLoading(false);
+ });
return () => { active = false; };
- }, [q, tag, statusView]);
+ }, [listKey, listStatus, q, tag]);
useEffect(() => loadThreads(), [loadThreads]);
@@ -393,20 +405,20 @@ export default function ThreadsTab() {
</div>
<div id={`brain-threads-${statusView}`} role="tabpanel" aria-labelledby={`tab-${statusView}`} className="flex-1 min-h-0 overflow-y-auto p-4 space-y-5">
- {loading && threads.length === 0 && <p className="text-sm text-gray-500">Loading threads…</p>}
+ {loading && (!hasCurrentList || threads.length === 0) && <p className="text-sm text-gray-500">Loading threads…</p>}
{listError && (
<UnavailableState
title="Threads are unavailable"
- message={threads.length > 0 ? 'Showing the last successful list. Retry when the server is reachable.' : 'The thread list could not be read, so the working set is unknown.'}
+ message={hasCurrentList && threads.length > 0 ? 'Showing the last successful list. Retry when the server is reachable.' : 'The thread list could not be read, so the working set is unknown.'}
onRetry={loadThreads}
/>
)}
- {!loading && !listError && threads.length === 0 && (
+ {!loading && !listError && hasCurrentList && threads.length === 0 && (
<p className="text-sm text-gray-500">
{q || tag ? 'No threads match.' : 'Nothing tracked yet — add the first open loop above.'}
</p>
)}
- {(!listError || threads.length > 0) && groups.map((group) => (
+ {hasCurrentList && (!listError || threads.length > 0) && groups.map((group) => (
<section key={group.id} aria-label={group.label}>
<h3 className="text-xs uppercase tracking-wide text-gray-500 mb-2">
{group.label} <span className="text-gray-600">{formatCount(group.items.length)}</span>
diff --git a/client/src/components/brain/tabs/ThreadsTab.test.jsx b/client/src/components/brain/tabs/ThreadsTab.test.jsx
index d12b1f574c..e04889e56c 100644
--- a/client/src/components/brain/tabs/ThreadsTab.test.jsx
+++ b/client/src/components/brain/tabs/ThreadsTab.test.jsx
@@ -30,6 +30,13 @@ const ROWS = [
];
const DONE_ROW = { id: 'done', title: 'Finished loop', status: 'done', refs: [], tags: [] };
+const deferred = () => {
+ let resolve;
+ let reject;
+ const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
+ return { promise, resolve, reject };
+};
+
const RESOLVED = [{ kind: 'url', id: 'https://example.com', label: 'example', url: 'https://example.com', resolved: true }];
function Location() {
@@ -172,6 +179,36 @@ describe('ThreadsTab', () => {
expect(screen.queryByText('Threads are unavailable')).toBeNull();
});
+ it('does not render the previous filter when the next filter fails', async () => {
+ renderTab();
+ await screen.findByText('Plain loop');
+
+ api.listThreads.mockRejectedValueOnce(new Error('temporary outage'));
+ await act(async () => { fireEvent.click(screen.getByRole('tab', { name: 'Done' })); });
+
+ expect(await screen.findByText('Threads are unavailable')).toBeInTheDocument();
+ expect(screen.queryByText('Plain loop')).toBeNull();
+ });
+
+ it('ignores a retry that resolves after a newer filter request', async () => {
+ renderTab();
+ await screen.findByText('Plain loop');
+
+ api.listThreads.mockRejectedValueOnce(new Error('temporary outage'));
+ await act(async () => { fireEvent.click(screen.getByRole('tab', { name: 'Done' })); });
+ expect(await screen.findByText('Threads are unavailable')).toBeInTheDocument();
+
+ const retry = deferred();
+ api.listThreads.mockReturnValueOnce(retry.promise).mockResolvedValueOnce({ threads: [DONE_ROW], total: 1 });
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });
+ await act(async () => { fireEvent.click(screen.getByRole('tab', { name: 'Archived' })); });
+ expect(await screen.findByText('Finished loop')).toBeInTheDocument();
+
+ await act(async () => { retry.resolve({ threads: ROWS, total: ROWS.length }); });
+ expect(screen.getByText('Finished loop')).toBeInTheDocument();
+ expect(screen.queryByText('Plain loop')).toBeNull();
+ });
+
it('keeps a selected thread deep link open when the record read fails and retries it in place', async () => {
api.getThread.mockRejectedValueOnce(new Error('temporary outage'));
renderTab('/brain/threads?thread=op');