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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: make Brain deep links and unavailable states truthful (#7859)
[._.]/ Adam Eivye483ed3d4e8c
diff --git a/client/src/components/brain/tabs/NotesTab.jsx b/client/src/components/brain/tabs/NotesTab.jsxindex fee940af97..c98c269d8c 100644--- a/client/src/components/brain/tabs/NotesTab.jsx+++ b/client/src/components/brain/tabs/NotesTab.jsx@@ -25,18 +25,42 @@ import FolderPicker from '../../FolderPicker';import { timeAgo, formatBytes, formatCount } from '../../../utils/formatters';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';import { useNoteSave } from '../../../hooks/useNoteSave.js';+import useUrlParams from '../../../hooks/useUrlParams';import { clickableProps } from '../../../lib/a11yKeyboard.js';import OfflineNotesNotice from '../../OfflineNotesNotice.jsx';import ForceSaveNoteRow from '../../ForceSaveNoteRow.jsx';+function UnavailableState({ title, message, onRetry }) {+ return (+ <div role="alert" className="rounded-lg border border-port-error/40 bg-port-error/10 p-4 text-sm text-gray-300">+ <p className="font-medium text-port-error">{title}</p>+ <p className="mt-1 text-gray-400">{message}</p>+ <button+ type="button"+ onClick={onRetry}+ className="mt-3 min-h-[44px] rounded bg-port-card px-3 text-port-accent hover:text-white"+ >+ Retry+ </button>+ </div>+ );+}+export default function NotesTab() {+ const [searchParams, updateParams] = useUrlParams();+ const selectedVaultId = searchParams.get('vault') || null;+ const folderFilter = searchParams.get('folder') || '';+ const searchQuery = searchParams.get('q') || '';+ const selectedNotePath = searchParams.get('note') || null;+// Vault stateconst [vaults, setVaults] = useState([]);- const [selectedVaultId, setSelectedVaultId] = useState(null);const [detectedVaults, setDetectedVaults] = useState([]);const [showVaultSetup, setShowVaultSetup] = useState(false);const [addingVault, setAddingVault] = useState(false);const [customPath, setCustomPath] = useState('');+ const [vaultError, setVaultError] = useState(false);+ const [detectError, setDetectError] = useState(false);// Notes stateconst [notes, setNotes] = useState([]);@@ -46,20 +70,23 @@ export default function NotesTab() {const [skippedNotes, setSkippedNotes] = useState(0);const [loading, setLoading] = useState(true);const [scanning, setScanning] = useState(false);+ const [scanError, setScanError] = useState(false);// Note viewer/editor stateconst [selectedNote, setSelectedNote] = useState(null);const [noteContent, setNoteContent] = useState('');const [editing, setEditing] = useState(false);const [loadingNote, setLoadingNote] = useState(false);+ const [noteError, setNoteError] = useState(false);+ const [noteRetry, setNoteRetry] = useState(0);// Search state- const [searchQuery, setSearchQuery] = useState('');+ const [searchInput, setSearchInput] = useState(searchQuery);const [searchResults, setSearchResults] = useState(null);- const [, setSearching] = useState(false);+ const [searching, setSearching] = useState(false);+ const [searchError, setSearchError] = useState(false);// Filter state- const [folderFilter, setFolderFilter] = useState('');const [, setFolders] = useState([]);const [expandedFolders, setExpandedFolders] = useState(new Set());const [tags, setTags] = useState([]);@@ -97,6 +124,7 @@ export default function NotesTab() {setNoteContent('');setEditing(false);setLoadingNote(false);+ setNoteError(false);dismissForce();cancelDelete();};@@ -113,14 +141,15 @@ export default function NotesTab() {setTags([]);setShowTags(false);setExpandedFolders(new Set());- setSearchQuery('');+ setSearchInput('');setSearchResults(null);- setFolderFilter('');+ setSearchError(false);setShowCreateForm(false);setNewNotePath('');setCreating(false);setScanning(false);- setSelectedVaultId(vaultId);+ setScanError(false);+ updateParams({ vault: vaultId, folder: null, q: null, note: null });};// Load vaults on mount@@ -146,11 +175,24 @@ export default function NotesTab() {const loadVaults = async (preferredVaultId) => {const scope = vaultScopeRef.current;- const data = await api.getNotesVaults().catch(() => []);+ setVaultError(false);+ const data = await api.getNotesVaults({ silent: true }).catch(() => null);if (!isCurrentScope(scope)) return;+ if (!data) {+ setVaultError(true);+ setLoading(false);+ return;+ }setVaults(data);- if (data.length > 0 && (preferredVaultId || !selectedVaultId)) {- selectVault(preferredVaultId || data[0].id);+ setVaultError(false);+ if (data.length > 0) {+ const requestedVaultId = preferredVaultId || selectedVaultId;+ const nextVaultId = data.some(vault => vault.id === requestedVaultId)+ ? requestedVaultId+ : data[0].id;+ if (nextVaultId !== selectedVaultId) {+ updateParams({ vault: nextVaultId, folder: null, q: null, note: null }, { replace: true });+ }}if (data.length === 0) {setShowVaultSetup(true);@@ -161,8 +203,11 @@ export default function NotesTab() {const detectAvailableVaults = async () => {const scope = vaultScopeRef.current;- const detected = await api.detectNotesVaults().catch(() => []);- if (isCurrentScope(scope)) setDetectedVaults(detected);+ setDetectError(false);+ const detected = await api.detectNotesVaults({ silent: true }).catch(() => null);+ if (!isCurrentScope(scope)) return;+ if (detected) setDetectedVaults(detected);+ else setDetectError(true);};const loadNotes = async () => {@@ -170,55 +215,108 @@ export default function NotesTab() {const scope = vaultScopeRef.current;const sequence = ++scanSeqRef.current;setScanning(true);- const data = await api.scanNotesVault(selectedVaultId, { folder: folderFilter, limit: 500 }).catch(() => null);+ 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);setTotalNotes(data.total);setSkippedNotes(data.skippedUnavailable || 0);- }+ } else setScanError(true);setScanning(false);};const loadFolders = async () => {if (!selectedVaultId) return;const scope = vaultScopeRef.current;- const data = await api.getNotesVaultFolders(selectedVaultId).catch(() => null);+ const data = await api.getNotesVaultFolders(selectedVaultId, { silent: true }).catch(() => null);if (isCurrentScope(scope) && data?.folders) setFolders(data.folders);};const loadTags = async () => {if (!selectedVaultId) return;const scope = vaultScopeRef.current;- const data = await api.getNotesVaultTags(selectedVaultId).catch(() => null);+ const data = await api.getNotesVaultTags(selectedVaultId, { silent: true }).catch(() => null);if (isCurrentScope(scope) && data?.tags) setTags(data.tags);};+ const loadNote = async () => {+ if (!selectedVaultId || !selectedNotePath) return;+ const scope = vaultScopeRef.current;+ const sequence = ++selectSeqRef.current;+ setSelectedNote(null);+ setNoteContent('');+ setEditing(false);+ setNoteError(false);+ setLoadingNote(true);+ dismissForce();+ cancelDelete();+ const data = await api.getNote(selectedVaultId, selectedNotePath, { silent: true }).catch(() => null);+ if (!isCurrentScope(scope) || sequence !== selectSeqRef.current) return;+ if (data) {+ setSelectedNote(data);+ setNoteContent(data.content);+ } else setNoteError(true);+ setLoadingNote(false);+ };++ useEffect(() => {+ if (!selectedVaultId || !selectedNotePath) {+ clearSelection();+ return;+ }+ loadNote();+ }, [selectedVaultId, selectedNotePath, noteRetry]);++ const loadSearch = useCallback(async (query = searchQuery) => {+ if (!query.trim() || !selectedVaultId) return;+ const scope = vaultScopeRef.current;+ const sequence = ++searchSeqRef.current;+ setSearching(true);+ setSearchError(false);+ const data = await api.searchNotes(selectedVaultId, query.trim(), undefined, { silent: true }).catch(() => null);+ if (!mountedRef.current || scope !== vaultScopeRef.current || sequence !== searchSeqRef.current) return;+ if (data) setSearchResults(data);+ else setSearchError(true);+ setSearching(false);+ }, [searchQuery, selectedVaultId]);++ useEffect(() => {+ setSearchInput(searchQuery);+ if (!searchQuery || !selectedVaultId) {+ searchSeqRef.current += 1;+ setSearchResults(null);+ setSearchError(false);+ setSearching(false);+ return;+ }+ setSearchResults(null);+ loadSearch(searchQuery);+ }, [selectedVaultId, searchQuery, loadSearch]);+const handleAddVault = async (name, path) => {const scope = vaultScopeRef.current;setAddingVault(true);- const result = await api.addNotesVault({ name, path }).catch(() => null);+ const result = await api.addNotesVault({ name, path }, { silent: true }).catch(() => null);if (!isCurrentScope(scope)) return;setAddingVault(false);if (result) {toast.success(`Added vault: ${result.name}`);setShowVaultSetup(false);+ updateParams({ vault: result.id, folder: null, q: null, note: null });await loadVaults(result.id);}};- const handleSelectNote = async (notePath) => {- const scope = vaultScopeRef.current;+ const handleSelectNote = (notePath) => {clearSelection();- const sequence = selectSeqRef.current;- setLoadingNote(true);- const data = await api.getNote(selectedVaultId, notePath).catch(() => null);- if (!isCurrentScope(scope) || sequence !== selectSeqRef.current) return;- if (data) {- setSelectedNote(data);- setNoteContent(data.content);- }- setLoadingNote(false);+ setNoteRetry(value => value + 1);+ updateParams({ note: notePath });+ };++ const closeNote = () => {+ clearSelection();+ updateParams({ note: null });};// `force` is ONLY ever passed by <ForceSaveNoteRow>'s confirm (#3717) — never@@ -239,7 +337,7 @@ export default function NotesTab() {const scope = vaultScopeRef.current;const sequence = selectSeqRef.current;setCreating(true);- const data = await api.createNote(selectedVaultId, newNotePath.trim()).catch(() => null);+ const data = await api.createNote(selectedVaultId, newNotePath.trim(), '', { silent: true }).catch(() => null);if (!isCurrentScope(scope)) return;setCreating(false);if (data) {@@ -254,33 +352,27 @@ export default function NotesTab() {const handleDeleteNote = async (notePath) => {const scope = vaultScopeRef.current;const sequence = selectSeqRef.current;- await api.deleteNote(selectedVaultId, notePath).catch(() => null);+ await api.deleteNote(selectedVaultId, notePath, { silent: true }).catch(() => null);if (!isCurrentScope(scope)) return;toast.success('Note deleted');cancelDelete();setNotes(prev => prev.filter(n => n.path !== notePath));- if (sequence === selectSeqRef.current && selectedNote?.path === notePath) {+ if (sequence === selectSeqRef.current && selectedNotePath === notePath) {clearSelection();+ updateParams({ note: null });}};- const handleSearch = useCallback(async () => {- if (!searchQuery.trim() || !selectedVaultId) return;- const scope = vaultScopeRef.current;- const sequence = ++searchSeqRef.current;- setSearching(true);- const data = await api.searchNotes(selectedVaultId, searchQuery.trim()).catch(() => null);- if (!mountedRef.current || scope !== vaultScopeRef.current || sequence !== searchSeqRef.current) return;- setSearching(false);- if (data) {- setSearchResults(data);- }- }, [searchQuery, selectedVaultId]);+ const handleSearch = useCallback((query = searchInput) => {+ updateParams({ q: query.trim() || null });+ }, [searchInput, updateParams]);const clearSearch = () => {searchSeqRef.current += 1;- setSearchQuery('');+ setSearchInput('');setSearchResults(null);+ setSearchError(false);+ updateParams({ q: null });};const toggleFolder = (folder) => {@@ -301,6 +393,18 @@ export default function NotesTab() {);}+ if (vaultError && vaults.length === 0) {+ return (+ <div className="h-full overflow-y-auto p-3 sm:p-4">+ <UnavailableState+ title="Notes vaults are unavailable"+ message="The vault list could not be read, so PortOS cannot tell whether this install has any notes."+ onRetry={loadVaults}+ />+ </div>+ );+ }+if (showVaultSetup || vaults.length === 0) {// Notes is a full-bleed tab (Brain wraps it in overflow-hidden with no// padding), so this branch must own its scroll + padding — otherwise the@@ -317,6 +421,13 @@ export default function NotesTab() {onDetect={detectAvailableVaults}onClose={() => setShowVaultSetup(false)}/>+ {detectError && (+ <UnavailableState+ title="Vault detection is unavailable"+ message="No result is shown because the iCloud scan did not complete."+ onRetry={detectAvailableVaults}+ />+ )}</div>);}@@ -330,14 +441,14 @@ export default function NotesTab() {: [...new Set(notes.filter(n => n.folder).map(n => n.folder.split('/')[0]))];// Determine what to show in list- const displayNotes = searchResults ? searchResults.results : notes;+ const displayNotes = searchQuery ? (searchResults?.results || []) : notes;return (<div className="grid grid-cols-1 md:grid-cols-[320px_1fr] grid-rows-1 h-full min-h-0 overflow-hidden">{/* Left panel: note list — on mobile it yields to the detail pane once anote is opened (the detail pane's back button restores it). On md+ bothpanels are always visible side-by-side. */}- <div className={`border-r border-port-border flex-col min-h-0 overflow-hidden ${selectedNote || loadingNote ? 'hidden md:flex' : 'flex'}`}>+ <div className={`border-r border-port-border flex-col min-h-0 overflow-hidden ${selectedNotePath || loadingNote || noteError ? 'hidden md:flex' : 'flex'}`}>{/* Vault selector and actions */}<div className="p-3 border-b border-port-border space-y-2"><div className="flex items-center gap-2">@@ -372,14 +483,14 @@ export default function NotesTab() {<Search size={14} className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-500" /><inputref={searchRef}- value={searchQuery}- onChange={e => setSearchQuery(e.target.value)}+ value={searchInput}+ onChange={e => setSearchInput(e.target.value)}onKeyDown={e => e.key === 'Enter' && handleSearch()}placeholder="Search notes..."aria-label="Search notes"className="w-full min-h-[44px] bg-port-bg border border-port-border rounded pl-7 pr-14 py-1.5 text-sm text-white placeholder-gray-500"/>- {searchQuery && (+ {searchInput && (<buttononClick={clearSearch}aria-label="Clear search"@@ -420,6 +531,14 @@ export default function NotesTab() {)}</div>+ {vaultError && (+ <UnavailableState+ title="Vault list refresh failed"+ message="Showing the last successful vault list. Retry when the server is reachable."+ onRetry={loadVaults}+ />+ )}+<OfflineNotesNotice count={skippedNotes + (searchResults?.skippedUnavailable || 0)} className="mx-3 mt-2" />{/* Stats bar */}@@ -427,7 +546,7 @@ export default function NotesTab() {<span>{formatCount(totalNotes)} notes</span>{folderFilter && (<button- onClick={() => setFolderFilter('')}+ onClick={() => updateParams({ folder: null })}className="flex items-center gap-1 text-port-accent hover:text-white"><X size={10} />@@ -460,8 +579,8 @@ export default function NotesTab() {<spankey={t.tag}className="px-1.5 py-0.5 rounded text-xs bg-port-accent/20 text-port-accent cursor-pointer hover:bg-port-accent/30"- onClick={() => { setSearchQuery(`#${t.tag}`); handleSearch(); }}- {...clickableProps(() => { setSearchQuery(`#${t.tag}`); handleSearch(); })}+ onClick={() => { setSearchInput(`#${t.tag}`); handleSearch(`#${t.tag}`); }}+ {...clickableProps(() => { setSearchInput(`#${t.tag}`); handleSearch(`#${t.tag}`); })}>#{t.tag} <span className="text-gray-500">{t.count}</span></span>@@ -469,20 +588,39 @@ export default function NotesTab() {</div>)}+ {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.'}+ onRetry={loadNotes}+ />+ )}+ {searchError && (+ <UnavailableState+ title="Search is unavailable"+ message={searchResults ? 'Showing the last successful search results. Retry when search is reachable.' : 'The search did not complete, so no-match results are not being shown.'}+ onRetry={() => loadSearch(searchQuery)}+ />+ )}+{/* Note list */}<div className="flex-1 overflow-auto">- {scanning && notes.length === 0 ? (+ {scanning && notes.length === 0 && !searchQuery ? (<div className="flex items-center justify-center h-32 text-gray-500 text-sm"><BrailleSpinner /> Scanning vault...</div>- ) : displayNotes.length === 0 ? (+ ) : searching ? (+ <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 ? (<div className="flex items-center justify-center h-32 px-4 text-center text-gray-500 text-sm">- {searchResults ? 'No matches found' : 'No notes yet — capture notes in your vault to enrich Ask Yourself and your digital twin.'}+ {searchQuery ? 'No matches found' : 'No notes yet — capture notes in your vault to enrich Ask Yourself and your digital twin.'}</div>) : (<div className="divide-y divide-port-border/50">{/* Folders first (when not searching) */}- {!searchResults && !folderFilter && folderNotes.map(folder => (+ {!searchQuery && !folderFilter && folderNotes.map(folder => (<FolderItemkey={folder}folder={folder}@@ -490,17 +628,17 @@ export default function NotesTab() {expanded={expandedFolders.has(folder)}onToggle={() => toggleFolder(folder)}onSelectNote={handleSelectNote}- onFilterFolder={() => setFolderFilter(folder)}- selectedPath={selectedNote?.path}+ onFilterFolder={() => updateParams({ folder })}+ selectedPath={selectedNotePath}/>))}{/* Root notes or filtered/search results */}- {(searchResults ? displayNotes : rootNotes).map(note => (+ {(searchQuery ? displayNotes : rootNotes).map(note => (<NoteListItemkey={note.path}note={note}- isSearch={!!searchResults}- selected={selectedNote?.path === note.path}+ isSearch={Boolean(searchQuery)}+ selected={selectedNotePath === note.path}onClick={() => handleSelectNote(note.path)}/>))}@@ -509,7 +647,7 @@ export default function NotesTab() {<NoteListItemkey={note.path}note={note}- selected={selectedNote?.path === note.path}+ selected={selectedNotePath === note.path}onClick={() => handleSelectNote(note.path)}/>))}@@ -520,17 +658,25 @@ export default function NotesTab() {{/* Right panel: note viewer/editor — hidden on mobile until a note isopened so the list owns the small-screen viewport; always shown on md+. */}- <div className={`flex-col min-w-0 min-h-0 overflow-hidden ${selectedNote || loadingNote ? 'flex' : 'hidden md:flex'}`}>+ <div className={`flex-col min-w-0 min-h-0 overflow-hidden ${selectedNotePath || loadingNote || noteError ? 'flex' : 'hidden md:flex'}`}>{loadingNote ? (<div className="flex items-center justify-center h-full"><BrailleSpinner text="Loading" /></div>+ ) : noteError ? (+ <div className="flex items-center justify-center h-full p-4">+ <UnavailableState+ title="Note is unavailable"+ message="This note could not be read, so its contents were not replaced with an empty view."+ onRetry={() => setNoteRetry(value => value + 1)}+ />+ </div>) : selectedNote ? (<>{/* Note header */}<div className="px-4 py-3 border-b border-port-border flex items-center gap-3"><button- onClick={clearSelection}+ onClick={closeNote}aria-label="Back"className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 rounded hover:bg-port-card text-gray-400 hover:text-white md:hidden">diff --git a/client/src/components/brain/tabs/NotesTab.test.jsx b/client/src/components/brain/tabs/NotesTab.test.jsxindex c2cdbf4604..6509e14cf3 100644--- a/client/src/components/brain/tabs/NotesTab.test.jsx+++ b/client/src/components/brain/tabs/NotesTab.test.jsx@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen, fireEvent, act } from '@testing-library/react';+import { MemoryRouter, useLocation, useNavigate } from 'react-router';// ── Mock toast ────────────────────────────────────────────────────────────────const mockToast = vi.hoisted(() => Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }));@@ -64,8 +65,30 @@ const expectTouchTarget = (el, { width = true } = {}) => {}};-const renderTab = async () => {- await act(async () => { render(<NotesTab />); });+function Location() {+ return <output data-testid="location">{useLocation().search}</output>;+}++function HistoryControls() {+ const navigate = useNavigate();+ return (+ <>+ <button type="button" onClick={() => navigate(-1)}>Browser back</button>+ <button type="button" onClick={() => navigate(1)}>Browser forward</button>+ </>+ );+}++const renderTab = async (entry = '/brain/notes') => {+ await act(async () => {+ render(+ <MemoryRouter initialEntries={[entry]}>+ <NotesTab />+ <Location />+ <HistoryControls />+ </MemoryRouter>,+ );+ });};describe('NotesTab header touch targets', () => {@@ -348,10 +371,156 @@ describe('NotesTab request lifetimes', () => {it('does not start follow-up work when the initial vault request finishes after unmount', async () => {const vaults = deferred();api.getNotesVaults.mockReturnValueOnce(vaults.promise);- const view = render(<NotesTab />);+ const view = render(<MemoryRouter><NotesTab /></MemoryRouter>);view.unmount();await act(async () => { vaults.resolve([]); });expect(api.detectNotesVaults).not.toHaveBeenCalled();expect(api.scanNotesVault).not.toHaveBeenCalled();});});++describe('NotesTab URL state and unavailable reads', () => {+ const note = {+ path: 'Projects/first.md',+ name: 'first',+ folder: 'Projects',+ size: 12,+ tags: [],+ modifiedAt: '2026-09-11T00:00:00Z',+ content: 'body',+ body: 'body',+ backlinks: []+ };+ const vaults = [{ id: 'vault-1', name: 'Example Vault', path: '/example/vault' }];++ beforeEach(() => {+ vi.resetAllMocks();+ api.getNotesVaults.mockResolvedValue(vaults);+ api.detectNotesVaults.mockResolvedValue([]);+ api.scanNotesVault.mockResolvedValue({ notes: [note], total: 1 });+ api.getNotesVaultFolders.mockResolvedValue({ folders: [] });+ api.getNotesVaultTags.mockResolvedValue({ tags: [] });+ api.getNote.mockResolvedValue(note);+ api.searchNotes.mockResolvedValue({ results: [note], total: 1 });+ });++ it('restores vault, folder, search, and note context from an encoded deep link, then returns to the list', async () => {+ await renderTab('/brain/notes?vault=vault-1&folder=Projects%2F2026&q=design%20notes¬e=Projects%2Ffirst.md');++ expect(await screen.findByRole('heading', { name: 'first' })).toBeInTheDocument();+ expect(screen.getByRole('combobox', { name: 'Vault' })).toHaveValue('vault-1');+ expect(screen.getByRole('textbox', { name: 'Search notes' })).toHaveValue('design notes');++ const params = new URLSearchParams(screen.getByTestId('location').textContent);+ expect(params.get('vault')).toBe('vault-1');+ expect(params.get('folder')).toBe('Projects/2026');+ expect(params.get('q')).toBe('design notes');+ expect(params.get('note')).toBe('Projects/first.md');+ expect(api.scanNotesVault).toHaveBeenCalledWith('vault-1', { folder: 'Projects/2026', limit: 500, silent: true });+ expect(api.searchNotes).toHaveBeenCalledWith('vault-1', 'design notes', undefined, { silent: true });+ expect(api.getNote).toHaveBeenCalledWith('vault-1', 'Projects/first.md', { silent: true });++ fireEvent.click(screen.getByRole('button', { name: 'Back' }));+ const afterBack = new URLSearchParams(screen.getByTestId('location').textContent);+ expect(afterBack.get('note')).toBeNull();+ expect(afterBack.get('vault')).toBe('vault-1');+ expect(screen.queryByRole('heading', { name: 'first' })).toBeNull();+ });++ it('writes folder, search, and note selection changes into the URL', async () => {+ api.scanNotesVault.mockResolvedValueOnce({+ notes: [note, ...Array.from({ length: 20 }, (_, index) => ({ ...note, path: `Projects/extra-${index}.md`, name: `extra-${index}` }))],+ total: 21,+ });+ await renderTab();+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Projects 21' })); });+ await screen.findByRole('button', { name: 'Show all 21 notes...' });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Show all 21 notes...' })); });+ expect(new URLSearchParams(screen.getByTestId('location').textContent).get('folder')).toBe('Projects');+ expect((await screen.findAllByText('first')).length).toBeGreaterThan(0);++ await act(async () => {+ fireEvent.change(screen.getByRole('textbox', { name: 'Search notes' }), { target: { value: 'needle' } });+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Search notes' }), { key: 'Enter' });+ });+ expect(new URLSearchParams(screen.getByTestId('location').textContent).get('q')).toBe('needle');++ await act(async () => { fireEvent.click((await screen.findAllByText('first'))[0]); });+ expect(new URLSearchParams(screen.getByTestId('location').textContent).get('note')).toBe('Projects/first.md');+ });++ it('replays note selection through browser back and forward', async () => {+ const rootNote = { ...note, path: 'first.md', folder: '' };+ api.scanNotesVault.mockResolvedValueOnce({ notes: [rootNote], total: 1 });+ api.getNote.mockResolvedValueOnce(rootNote);+ await renderTab();++ await act(async () => { fireEvent.click(screen.getByText('first')); });+ expect(new URLSearchParams(screen.getByTestId('location').textContent).get('note')).toBe('first.md');+ expect(await screen.findByRole('heading', { name: 'first' })).toBeInTheDocument();++ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Browser back' })); });+ expect(new URLSearchParams(screen.getByTestId('location').textContent).get('note')).toBeNull();+ expect(screen.queryByRole('heading', { name: 'first' })).toBeNull();++ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Browser forward' })); });+ expect(await screen.findByRole('heading', { name: 'first' })).toBeInTheDocument();+ });++ it('keeps vault failure distinct from an empty vault and retries it', async () => {+ api.getNotesVaults.mockRejectedValueOnce(new Error('temporary outage'));+ await renderTab();++ expect(await screen.findByText('Notes vaults are unavailable')).toBeInTheDocument();+ expect(screen.queryByText(/No notes yet/)).toBeNull();++ api.getNotesVaults.mockResolvedValueOnce(vaults);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(await screen.findByRole('combobox', { name: 'Vault' })).toHaveValue('vault-1');+ });++ it('keeps scan failure distinct from an empty list and retries the failed region', async () => {+ api.scanNotesVault.mockRejectedValueOnce(new Error('temporary outage'));+ await renderTab();++ expect(await screen.findByText('Notes are unavailable')).toBeInTheDocument();+ expect(screen.queryByText(/No notes yet/)).toBeNull();++ api.scanNotesVault.mockResolvedValueOnce({ notes: [], total: 0 });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(await screen.findByText(/No notes yet/)).toBeInTheDocument();+ expect(screen.queryByText('Notes are unavailable')).toBeNull();+ });++ 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¬e=Projects%2Ffirst.md');++ expect(await screen.findByText('Note is unavailable')).toBeInTheDocument();+ expect(screen.queryByText('Select a note to view')).toBeNull();+ expect(new URLSearchParams(screen.getByTestId('location').textContent).get('note')).toBe('Projects/first.md');++ api.getNote.mockResolvedValueOnce(note);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(await screen.findByRole('heading', { name: 'first' })).toBeInTheDocument();+ });++ it('keeps search failure distinct from a successful no-match result and retries it', async () => {+ api.searchNotes.mockRejectedValueOnce(new Error('temporary outage'));+ await renderTab();+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Projects 1' })); });+ await screen.findByText('first');++ await act(async () => {+ fireEvent.change(screen.getByRole('textbox', { name: 'Search notes' }), { target: { value: 'needle' } });+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Search notes' }), { key: 'Enter' });+ });+ expect(await screen.findByText('Search is unavailable')).toBeInTheDocument();+ expect(screen.queryByText('No matches found')).toBeNull();++ api.searchNotes.mockResolvedValueOnce({ results: [], total: 0 });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(await screen.findByText('No matches found')).toBeInTheDocument();+ expect(screen.queryByText('Search is unavailable')).toBeNull();+ });+});diff --git a/client/src/components/brain/tabs/ThreadsTab.jsx b/client/src/components/brain/tabs/ThreadsTab.jsxindex ef2840889c..f4e1ec5162 100644--- a/client/src/components/brain/tabs/ThreadsTab.jsx+++ b/client/src/components/brain/tabs/ThreadsTab.jsx@@ -9,7 +9,7 @@// drawer's section (`?threadTab=`), so the dashboard widget, unified search and// a shared link all land on the same drawer. Full-bleed: this tab owns its own// scroll region like the Daily Log.-import { useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Check, Info, Link2, ListTodo, Pin, Plus, Search, Trash2, X } from 'lucide-react';import useUrlParams from '../../../hooks/useUrlParams';import useDrawerTab from '../../../hooks/useDrawerTab';@@ -99,6 +99,22 @@ const loadRecord = (id) => api.getThread(id, { silent: true });const inputClass = 'w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent';+function UnavailableState({ title, message, onRetry }) {+ return (+ <div role="alert" className="rounded-lg border border-port-error/40 bg-port-error/10 p-4 text-sm text-gray-300">+ <p className="font-medium text-port-error">{title}</p>+ <p className="mt-1 text-gray-400">{message}</p>+ <button+ type="button"+ onClick={onRetry}+ className="mt-3 min-h-[44px] rounded bg-port-card px-3 text-port-accent hover:text-white"+ >+ Retry+ </button>+ </div>+ );+}+function ThreadRow({ thread, onOpen, onDone, onTag }) {const nextLine = threadNextLine(thread);const refCount = Array.isArray(thread.refs) ? thread.refs.length : 0;@@ -152,9 +168,13 @@ export default function ThreadsTab() {const [threads, setThreads] = useState([]);const [loading, setLoading] = useState(true);+ const [listError, setListError] = useState(false);const [newTitle, setNewTitle] = useState('');const [record, setRecord] = useState(null);const [draft, setDraft] = useState(null);+ const [recordLoading, setRecordLoading] = useState(false);+ const [recordError, setRecordError] = useState(false);+ const [recordRetry, setRecordRetry] = useState(0);const [confirmDelete, setConfirmDelete] = useState(false);const [completingSource, setCompletingSource] = useState(false);const [newRef, setNewRef] = useState({ kind: 'url', id: '', label: '' });@@ -170,26 +190,43 @@ export default function ThreadsTab() {return () => clearTimeout(timer);}, [searchInput, q, updateParams]);- // The list — one request for exactly the statuses the view shows.- useEffect(() => {+ // 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.+ const loadThreads = useCallback(() => {let active = true;setLoading(true);- api.listThreads({ q, tag, status: statusView === 'all' ? WORKING_SET : statusView })- .then((res) => { if (active) setThreads(Array.isArray(res?.threads) ? res.threads : []); })- .catch(() => { if (active) setThreads([]); })+ setListError(false);+ api.listThreads(+ { q, tag, status: statusView === 'all' ? WORKING_SET : statusView },+ { silent: true },+ )+ .then((res) => {+ if (!active) return;+ setThreads(Array.isArray(res?.threads) ? res.threads : []);+ })+ .catch(() => { if (active) setListError(true); }).finally(() => { if (active) setLoading(false); });return () => { active = false; };}, [q, tag, statusView]);+ useEffect(() => loadThreads(), [loadThreads]);+// Open record — keyed to the URL so a deep link and a row click share the path.useEffect(() => {if (!selectedId) {setRecord(null);setDraft(null);+ setRecordLoading(false);+ setRecordError(false);setConfirmDelete(false);return undefined;}let active = true;+ setRecord(null);+ setDraft(null);+ setRecordLoading(true);+ setRecordError(false);loadRecord(selectedId).then((full) => {if (!active) return;@@ -198,11 +235,13 @@ export default function ThreadsTab() {}).catch(() => {if (!active) return;- toast.error('Thread not found');- updateParams({ thread: null, threadTab: null }, { replace: true });+ setRecordError(true);+ })+ .finally(() => {+ if (active) setRecordLoading(false);});return () => { active = false; };- }, [selectedId, updateParams]);+ }, [selectedId, recordRetry]);const groups = useMemo(() => (statusView === 'all'@@ -355,12 +394,19 @@ export default function ThreadsTab() {<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 && threads.length === 0 && (+ {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.'}+ onRetry={loadThreads}+ />+ )}+ {!loading && !listError && 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>)}- {groups.map((group) => (+ {(!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>@@ -387,7 +433,15 @@ export default function ThreadsTab() {closeOnEsc={!dirty}closeOnBackdrop={!dirty}>- {record && draft && (+ {recordLoading && <p className="text-sm text-gray-500">Loading thread…</p>}+ {recordError && (+ <UnavailableState+ title="Thread unavailable"+ message="This thread could not be read, so the drawer was left open for a retry."+ onRetry={() => setRecordRetry((value) => value + 1)}+ />+ )}+ {record && draft && record.id === selectedId && (<fieldset disabled={completingSource} className="space-y-4 min-w-0"><div className="flex items-center justify-end gap-2">{dirty && <span className="text-xs text-port-warning">Unsaved changes</span>}diff --git a/client/src/components/brain/tabs/ThreadsTab.test.jsx b/client/src/components/brain/tabs/ThreadsTab.test.jsxindex 6dd3e5aded..d12b1f574c 100644--- a/client/src/components/brain/tabs/ThreadsTab.test.jsx+++ b/client/src/components/brain/tabs/ThreadsTab.test.jsx@@ -53,14 +53,14 @@ describe('ThreadsTab', () => {expect(groupTitles).toEqual(['Pinned 1', 'Overdue 1', 'Open 1', 'Waiting 1']);expect(screen.getByText('Waiting on Acme Corp')).toBeTruthy();// One request for exactly the non-terminal statuses — never the archive filtered here.- expect(api.listThreads).toHaveBeenCalledWith({ q: '', tag: '', status: 'open,waiting,someday' });+ expect(api.listThreads).toHaveBeenCalledWith({ q: '', tag: '', status: 'open,waiting,someday' }, { silent: true });});it('reads the status, tag and search filters from the URL and sends them to the server', async () => {api.listThreads.mockResolvedValue({ threads: [DONE_ROW], total: 1 });renderTab('/brain/threads?status=done&tag=ops&q=fin');await screen.findByText('Finished loop');- expect(api.listThreads).toHaveBeenCalledWith({ q: 'fin', tag: 'ops', status: 'done' });+ expect(api.listThreads).toHaveBeenCalledWith({ q: 'fin', tag: 'ops', status: 'done' }, { silent: true });expect(screen.getAllByRole('heading', { level: 3 }).map((h) => h.textContent.trim())).toEqual(['Done 1']);});@@ -152,12 +152,39 @@ describe('ThreadsTab', () => {await act(async () => { vi.advanceTimersByTime(300); });expect(screen.getByTestId('location').textContent).toBe('?q=re');expect(api.listThreads).toHaveBeenCalledTimes(2);- expect(api.listThreads).toHaveBeenLastCalledWith({ q: 're', tag: '', status: 'open,waiting,someday' });+ expect(api.listThreads).toHaveBeenLastCalledWith({ q: 're', tag: '', status: 'open,waiting,someday' }, { silent: true });} finally {vi.useRealTimers();}});+ it('distinguishes an unavailable list from a successful empty list and retries the failed read', async () => {+ api.listThreads.mockRejectedValueOnce(new Error('temporary outage'));+ renderTab();++ expect(await screen.findByText('Threads are unavailable')).toBeInTheDocument();+ expect(screen.queryByText('Nothing tracked yet — add the first open loop above.')).toBeNull();++ api.listThreads.mockResolvedValueOnce({ threads: ROWS, total: ROWS.length });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });++ expect(await screen.findByText('Pinned loop')).toBeInTheDocument();+ expect(screen.queryByText('Threads are unavailable')).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');++ expect(await screen.findByText('Thread unavailable')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Close thread' })).toBeInTheDocument();++ api.getThread.mockResolvedValueOnce({ ...ROWS[2], notes: 'body', resolvedRefs: RESOLVED });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });++ expect(await screen.findByLabelText('Title')).toHaveValue('Plain loop');+ });+it('swaps the hydrated record a ref write returns into the drawer without a second read', async () => {api.addThreadRef.mockResolvedValue({ ...ROWS[2], notes: 'body', refs: [{ kind: 'url', id: 'https://example.com/x' }], resolvedRefs: [{ kind: 'url', id: 'https://example.com/x', label: 'added', url: 'https://example.com/x', resolved: true }] });renderTab('/brain/threads?thread=op&threadTab=links');diff --git a/client/src/services/apiNotes.js b/client/src/services/apiNotes.jsindex ae4a20c738..32bdd7f4c7 100644--- a/client/src/services/apiNotes.js+++ b/client/src/services/apiNotes.js@@ -1,28 +1,30 @@import { request } from './apiCore.js';// Notes - Vault Management-export const getNotesVaults = () => request('/notes/vaults');-export const detectNotesVaults = () => request('/notes/detect');-export const addNotesVault = (data) => request('/notes/vaults', {+export const getNotesVaults = (options) => request('/notes/vaults', options);+export const detectNotesVaults = (options) => request('/notes/detect', options);+export const addNotesVault = (data, options = {}) => request('/notes/vaults', {method: 'POST',- body: JSON.stringify(data)+ body: JSON.stringify(data),+ ...options});// Notes - Scanning & Reading-export const scanNotesVault = (id, options = {}) => {+export const scanNotesVault = (id, { folder, limit, offset, ...requestOptions } = {}) => {const params = new URLSearchParams();- if (options.folder) params.set('folder', options.folder);- if (options.limit) params.set('limit', options.limit);- if (options.offset) params.set('offset', options.offset);- return request(`/notes/vaults/${id}/scan?${params}`);+ if (folder) params.set('folder', folder);+ if (limit) params.set('limit', limit);+ if (offset) params.set('offset', offset);+ return request(`/notes/vaults/${id}/scan?${params}`, requestOptions);};-export const getNote = (vaultId, path) =>- request(`/notes/vaults/${vaultId}/note?path=${encodeURIComponent(path)}`);+export const getNote = (vaultId, path, options) =>+ request(`/notes/vaults/${vaultId}/note?path=${encodeURIComponent(path)}`, options);-export const createNote = (vaultId, path, content = '') => request(`/notes/vaults/${vaultId}/note`, {+export const createNote = (vaultId, path, content = '', options = {}) => request(`/notes/vaults/${vaultId}/note`, {method: 'POST',- body: JSON.stringify({ path, content })+ body: JSON.stringify({ path, content }),+ ...options});// `force` bypasses the server's iCloud dataless screen (#3717). Only ever pass@@ -35,16 +37,16 @@ export const updateNote = (vaultId, path, content, { force = false, ...options }...options});-export const deleteNote = (vaultId, path) =>- request(`/notes/vaults/${vaultId}/note?path=${encodeURIComponent(path)}`, { method: 'DELETE' });+export const deleteNote = (vaultId, path, options = {}) =>+ request(`/notes/vaults/${vaultId}/note?path=${encodeURIComponent(path)}`, { method: 'DELETE', ...options });// Notes - Search & Discovery-export const searchNotes = (vaultId, q, limit) => {+export const searchNotes = (vaultId, q, limit, options = {}) => {const params = new URLSearchParams({ q });if (limit) params.set('limit', limit);- return request(`/notes/vaults/${vaultId}/search?${params}`);+ return request(`/notes/vaults/${vaultId}/search?${params}`, options);};-export const getNotesVaultTags = (vaultId) => request(`/notes/vaults/${vaultId}/tags`);-export const getNotesVaultFolders = (vaultId) => request(`/notes/vaults/${vaultId}/folders`);-export const getNotesVaultGraph = (vaultId) => request(`/notes/vaults/${vaultId}/graph`);+export const getNotesVaultTags = (vaultId, options) => request(`/notes/vaults/${vaultId}/tags`, options);+export const getNotesVaultFolders = (vaultId, options) => request(`/notes/vaults/${vaultId}/folders`, options);+export const getNotesVaultGraph = (vaultId, options) => request(`/notes/vaults/${vaultId}/graph`, options);