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: keep Brain Notes requests scoped to the latest selection (#6997)
[._.]/ Adam Eivyc604f1362af9
diff --git a/client/src/components/brain/tabs/NotesTab.jsx b/client/src/components/brain/tabs/NotesTab.jsxindex e4446ccbdd..ee2c188f46 100644--- a/client/src/components/brain/tabs/NotesTab.jsx+++ b/client/src/components/brain/tabs/NotesTab.jsx@@ -83,9 +83,57 @@ export default function NotesTab() {const searchRef = useRef(null);const editorRef = useRef(null);+ // Invalidate work at the interaction boundary, including A → B → A switches.+ const vaultScopeRef = useRef(0);+ const selectSeqRef = useRef(0);+ const scanSeqRef = useRef(0);+ const searchSeqRef = useRef(0);+ const mountedRef = useRef(false);+ const isCurrentScope = scope => mountedRef.current && vaultScopeRef.current === scope;++ const clearSelection = () => {+ selectSeqRef.current += 1;+ setSelectedNote(null);+ setNoteContent('');+ setEditing(false);+ setLoadingNote(false);+ dismissForce();+ cancelDelete();+ };++ const selectVault = vaultId => {+ vaultScopeRef.current += 1;+ scanSeqRef.current += 1;+ searchSeqRef.current += 1;+ clearSelection();+ setNotes([]);+ setTotalNotes(0);+ setSkippedNotes(0);+ setFolders([]);+ setTags([]);+ setShowTags(false);+ setExpandedFolders(new Set());+ setSearchQuery('');+ setSearchResults(null);+ setFolderFilter('');+ setShowCreateForm(false);+ setNewNotePath('');+ setCreating(false);+ setScanning(false);+ setSelectedVaultId(vaultId);+ };+// Load vaults on mountuseEffect(() => {+ mountedRef.current = true;loadVaults();+ return () => {+ mountedRef.current = false;+ vaultScopeRef.current += 1;+ selectSeqRef.current += 1;+ scanSeqRef.current += 1;+ searchSeqRef.current += 1;+ };}, []);// Load notes when vault changes@@ -96,11 +144,13 @@ export default function NotesTab() {}}, [selectedVaultId, folderFilter]);- const loadVaults = async () => {+ const loadVaults = async (preferredVaultId) => {+ const scope = vaultScopeRef.current;const data = await api.getNotesVaults().catch(() => []);+ if (!isCurrentScope(scope)) return;setVaults(data);- if (data.length > 0 && !selectedVaultId) {- setSelectedVaultId(data[0].id);+ if (data.length > 0 && (preferredVaultId || !selectedVaultId)) {+ selectVault(preferredVaultId || data[0].id);}if (data.length === 0) {setShowVaultSetup(true);@@ -110,14 +160,18 @@ export default function NotesTab() {};const detectAvailableVaults = async () => {+ const scope = vaultScopeRef.current;const detected = await api.detectNotesVaults().catch(() => []);- setDetectedVaults(detected);+ if (isCurrentScope(scope)) setDetectedVaults(detected);};const loadNotes = async () => {if (!selectedVaultId) return;+ const scope = vaultScopeRef.current;+ const sequence = ++scanSeqRef.current;setScanning(true);const data = await api.scanNotesVault(selectedVaultId, { folder: folderFilter, limit: 500 }).catch(() => null);+ if (!isCurrentScope(scope) || sequence !== scanSeqRef.current) return;if (data) {setNotes(data.notes);setTotalNotes(data.total);@@ -128,32 +182,38 @@ export default function NotesTab() {const loadFolders = async () => {if (!selectedVaultId) return;+ const scope = vaultScopeRef.current;const data = await api.getNotesVaultFolders(selectedVaultId).catch(() => null);- if (data?.folders) setFolders(data.folders);+ 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);- if (data?.tags) setTags(data.tags);+ if (isCurrentScope(scope) && data?.tags) setTags(data.tags);};const handleAddVault = async (name, path) => {+ const scope = vaultScopeRef.current;setAddingVault(true);const result = await api.addNotesVault({ name, path }).catch(() => null);+ if (!isCurrentScope(scope)) return;setAddingVault(false);if (result) {toast.success(`Added vault: ${result.name}`);setShowVaultSetup(false);- await loadVaults();- setSelectedVaultId(result.id);+ await loadVaults(result.id);}};const handleSelectNote = async (notePath) => {+ const scope = vaultScopeRef.current;+ clearSelection();+ const sequence = selectSeqRef.current;setLoadingNote(true);- setEditing(false);const data = await api.getNote(selectedVaultId, notePath).catch(() => null);+ if (!isCurrentScope(scope) || sequence !== selectSeqRef.current) return;if (data) {setSelectedNote(data);setNoteContent(data.content);@@ -164,8 +224,10 @@ export default function NotesTab() {// `force` is ONLY ever passed by <ForceSaveNoteRow>'s confirm (#3717) — never// by the Save button or ⌘S.const handleSaveNote = async (options) => {+ const scope = vaultScopeRef.current;+ const sequence = selectSeqRef.current;const data = await save(options);- if (!data) return;+ if (!data || !isCurrentScope(scope) || sequence !== selectSeqRef.current) return;setSelectedNote(data);setEditing(false);toast.success('Note saved');@@ -174,32 +236,41 @@ export default function NotesTab() {const handleCreateNote = async () => {if (!newNotePath.trim()) return;+ const scope = vaultScopeRef.current;+ const sequence = selectSeqRef.current;setCreating(true);const data = await api.createNote(selectedVaultId, newNotePath.trim()).catch(() => null);+ if (!isCurrentScope(scope)) return;setCreating(false);if (data) {toast.success(`Created: ${data.name}`);setShowCreateForm(false);setNewNotePath('');loadNotes();- handleSelectNote(data.path);+ if (sequence === selectSeqRef.current) handleSelectNote(data.path);}};const handleDeleteNote = async (notePath) => {+ const scope = vaultScopeRef.current;+ const sequence = selectSeqRef.current;await api.deleteNote(selectedVaultId, notePath).catch(() => null);+ if (!isCurrentScope(scope)) return;toast.success('Note deleted');cancelDelete();setNotes(prev => prev.filter(n => n.path !== notePath));- if (selectedNote?.path === notePath) {- setSelectedNote(null);+ if (sequence === selectSeqRef.current && selectedNote?.path === notePath) {+ clearSelection();}};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);@@ -207,6 +278,7 @@ export default function NotesTab() {}, [searchQuery, selectedVaultId]);const clearSearch = () => {+ searchSeqRef.current += 1;setSearchQuery('');setSearchResults(null);};@@ -272,12 +344,7 @@ export default function NotesTab() {<selectaria-label="Vault"value={selectedVaultId || ''}- onChange={e => {- setSelectedVaultId(e.target.value);- setSelectedNote(null);- setSearchResults(null);- setFolderFilter('');- }}+ onChange={e => selectVault(e.target.value)}className="flex-1 min-w-0 min-h-[44px] bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white">{vaults.map(v => (@@ -463,7 +530,7 @@ export default function NotesTab() {{/* Note header */}<div className="px-4 py-3 border-b border-port-border flex items-center gap-3"><button- onClick={() => setSelectedNote(null)}+ onClick={clearSelection}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 eb9e1ef07c..c2cdbf4604 100644--- a/client/src/components/brain/tabs/NotesTab.test.jsx+++ b/client/src/components/brain/tabs/NotesTab.test.jsx@@ -238,3 +238,120 @@ describe('NotesTab iCloud force save', () => {expect(screen.queryByRole('button', { name: 'Save anyway' })).toBeNull();});});++describe('NotesTab request lifetimes', () => {+ const note = (name, content = name) => ({+ path: `${name}.md`, name, folder: '', size: 12, tags: [],+ modifiedAt: '2026-09-11T00:00:00Z', content, body: content, backlinks: []+ });+ const deferred = () => {+ let resolve;+ let reject;+ const promise = new Promise((yes, no) => { resolve = yes; reject = no; });+ return { promise, resolve, reject };+ };+ const switchVault = value => fireEvent.change(screen.getByRole('combobox', { name: 'Vault' }), { target: { value } });++ beforeEach(() => {+ vi.resetAllMocks();+ api.getNotesVaults.mockResolvedValue([+ { id: 'a', name: 'Vault A' }, { id: 'b', name: 'Vault B' }+ ]);+ api.scanNotesVault.mockResolvedValue({ notes: [note('first'), note('second')], total: 2 });+ api.getNotesVaultFolders.mockResolvedValue({ folders: [] });+ api.getNotesVaultTags.mockResolvedValue({ tags: [] });+ api.getNote.mockImplementation((_vault, path) => Promise.resolve(note(path.replace('.md', ''))));+ });++ it('keeps the newest selected note and saves its buffer after an older fetch resolves', async () => {+ const first = deferred();+ api.getNote.mockImplementation((_vault, path) => path === 'first.md' ? first.promise : Promise.resolve(note('second')));+ await renderTab();+ fireEvent.click(screen.getByText('first'));+ await act(async () => { fireEvent.click(screen.getByText('second')); });+ await act(async () => { first.resolve(note('first', 'stale body')); });+ expect(screen.getByRole('heading', { name: 'second' })).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));+ expect(screen.getByRole('textbox', { name: 'Note content' })).toHaveValue('second');+ api.updateNote.mockResolvedValue(note('second'));+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Save' })); });+ expect(api.updateNote).toHaveBeenCalledWith('a', 'second.md', 'second', { force: false });+ });++ it('does not let an old failed selection stop the newest note loading', async () => {+ const first = deferred();+ const second = deferred();+ api.getNote.mockImplementation((_vault, path) => path === 'first.md' ? first.promise : second.promise);+ await renderTab();+ fireEvent.click(screen.getByText('first'));+ fireEvent.click(screen.getByText('second'));+ await act(async () => { first.reject(new Error('old failure')); });+ expect(screen.queryByRole('button', { name: 'Edit' })).toBeNull();+ await act(async () => { second.resolve(note('second')); });+ expect(screen.getByRole('heading', { name: 'second' })).toBeInTheDocument();+ });++ it('clears the old vault immediately and ignores old scans, note reads, and search results after switching back', async () => {+ const oldScan = deferred();+ const newScan = deferred();+ const oldNote = deferred();+ const oldSearch = deferred();+ await renderTab();+ api.scanNotesVault.mockReturnValueOnce(oldScan.promise).mockReturnValueOnce(newScan.promise);+ api.getNote.mockReturnValueOnce(oldNote.promise);+ api.searchNotes.mockReturnValueOnce(oldSearch.promise);+ fireEvent.click(screen.getByText('first'));+ fireEvent.change(screen.getByRole('textbox', { name: 'Search notes' }), { target: { value: 'old' } });+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Search notes' }), { key: 'Enter' });+ fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));+ switchVault('b');+ expect(screen.queryByText('first')).toBeNull();+ expect(screen.queryByRole('button', { name: 'Edit' })).toBeNull();+ await act(async () => { switchVault('a'); });+ await act(async () => {+ oldScan.resolve({ notes: [note('stale scan')], total: 1 });+ newScan.resolve({ notes: [note('wrong vault')], total: 1 });+ oldNote.resolve(note('stale editor'));+ oldSearch.resolve({ results: [note('stale search')], total: 1 });+ });+ expect(screen.getByText('first')).toBeInTheDocument();+ expect(screen.queryByText(/stale|wrong vault/)).toBeNull();+ expect(screen.queryByRole('button', { name: 'Edit' })).toBeNull();+ });++ it('keeps the newest refresh when same-vault scans finish out of order', async () => {+ const older = deferred();+ const newer = deferred();+ await renderTab();+ api.scanNotesVault.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise);+ fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));+ fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));+ await act(async () => { newer.resolve({ notes: [note('current')], total: 1 }); });+ await act(async () => { older.resolve({ notes: [note('stale')], total: 1 }); });+ expect(screen.getByText('current')).toBeInTheDocument();+ expect(screen.queryByText('stale')).toBeNull();+ });++ it('does not restore a saved note after the user selects another note', async () => {+ const saved = deferred();+ api.updateNote.mockReturnValueOnce(saved.promise);+ await renderTab();+ await act(async () => { fireEvent.click(screen.getByText('first')); });+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await act(async () => { fireEvent.click(screen.getByText('second')); });+ await act(async () => { saved.resolve(note('first')); });+ expect(screen.getByRole('heading', { name: 'second' })).toBeInTheDocument();+ expect(mockToast.success).not.toHaveBeenCalledWith('Note saved');+ });++ 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 />);+ view.unmount();+ await act(async () => { vaults.resolve([]); });+ expect(api.detectNotesVaults).not.toHaveBeenCalled();+ expect(api.scanNotesVault).not.toHaveBeenCalled();+ });+});