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: keep Brain edits bound to complete records and editing sessions

[._.]/ Adam Eivy20a1938c2123
diff --git a/client/src/components/brain/tabs/MemoryTab.editing.test.jsx b/client/src/components/brain/tabs/MemoryTab.editing.test.jsx
new file mode 100644
index 0000000000..82c79a0c8b
--- /dev/null
+++ b/client/src/components/brain/tabs/MemoryTab.editing.test.jsx
@@ -0,0 +1,132 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';
+import { MemoryRouter, Route, Routes } from 'react-router';
+import MemoryTab from './MemoryTab';
+
+const api = vi.hoisted(() => ({
+ getBrainMemories: vi.fn(), getBrainMemory: vi.fn(), updateBrainMemory: vi.fn(),
+ getBrainPeople: vi.fn(), updateBrainPerson: vi.fn(),
+ getMemoryBackendStatus: vi.fn(),
+}));
+vi.mock('../../../services/api', () => api);
+vi.mock('../../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));
+vi.mock('../../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+
+const memory = (id, extra = {}) => ({ id, title: `Example ${id}`, content: `Full body ${id}`, tags: [], ...extra });
+const deferred = () => {
+ let resolve;
+ let reject;
+ const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
+ return { promise, resolve, reject };
+};
+async function mount(rows) {
+ api.getBrainMemories.mockResolvedValue(rows);
+ render(<MemoryRouter initialEntries={['/brain/memory']}><Routes>
+ <Route path="/brain/:tab/:recordType?/:recordId?" element={<MemoryTab />} />
+ </Routes></MemoryRouter>);
+ await screen.findByRole('button', { name: `Read ${rows[0].title}` });
+}
+function edit(title) {
+ const row = screen.getByRole('button', { name: `Read ${title}` }).closest('.p-4');
+ fireEvent.click(within(row).getByRole('button', { name: 'Edit', exact: true }));
+}
+beforeEach(() => {
+ vi.resetAllMocks();
+ api.getMemoryBackendStatus.mockResolvedValue({ backend: 'postgres' });
+});
+afterEach(() => cleanup());
+
+describe('Brain record editor ownership', () => {
+ it('cannot save a truncated preview, and offers retry before editing after a failed full read', async () => {
+ const full = deferred();
+ api.getBrainMemory.mockReturnValueOnce(full.promise).mockResolvedValueOnce(memory('a'));
+ await mount([memory('a', { content: 'Preview only', contentTruncated: true })]);
+ edit('Example a');
+ expect(screen.getByRole('button', { name: 'Save', exact: true })).toBeDisabled();
+ expect(screen.queryByRole('textbox', { name: 'What happened' })).toBeNull();
+ await act(async () => { full.reject(new Error('Read failed')); });
+ expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load this entry for editing");
+ fireEvent.click(screen.getByRole('button', { name: 'Save', exact: true }));
+ expect(api.updateBrainMemory).not.toHaveBeenCalled();
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });
+ expect(screen.getByRole('textbox', { name: 'What happened' })).toHaveValue('Full body a');
+ api.updateBrainMemory.mockResolvedValue(memory('a', { content: 'Complete edited body' }));
+ fireEvent.change(screen.getByRole('textbox', { name: 'What happened' }), { target: { value: 'Complete edited body' } });
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Save', exact: true })); });
+ expect(api.updateBrainMemory).toHaveBeenCalledWith('a', expect.objectContaining({ content: 'Complete edited body' }), { silent: true });
+ expect(screen.getByRole('button', { name: 'Read Example a' })).toHaveTextContent('Complete edited body');
+ });
+
+ it('ignores an older hydration response after another record is edited', async () => {
+ const full = deferred();
+ api.getBrainMemory.mockReturnValueOnce(full.promise);
+ await mount([memory('a', { content: 'Preview only', contentTruncated: true }), memory('b')]);
+ edit('Example a');
+ edit('Example b');
+ fireEvent.change(screen.getByRole('textbox', { name: 'What happened' }), { target: { value: 'New body b' } });
+ await act(async () => { full.resolve(memory('a')); });
+ expect(screen.getByRole('textbox', { name: 'Title' })).toHaveValue('Example b');
+ expect(screen.getByRole('textbox', { name: 'What happened' })).toHaveValue('New body b');
+ api.updateBrainMemory.mockResolvedValue(memory('b', { content: 'New body b' }));
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Save', exact: true })); });
+ expect(api.updateBrainMemory).toHaveBeenCalledWith('b', expect.objectContaining({ content: 'New body b' }), { silent: true });
+ });
+
+ it('keeps a newer editing session when an older save finishes', async () => {
+ const saved = deferred();
+ api.updateBrainMemory.mockReturnValueOnce(saved.promise).mockResolvedValueOnce(memory('b', { content: 'New body b' }));
+ await mount([memory('a'), memory('b')]);
+ edit('Example a');
+ fireEvent.click(screen.getByRole('button', { name: 'Save', exact: true }));
+ edit('Example b');
+ fireEvent.change(screen.getByRole('textbox', { name: 'What happened' }), { target: { value: 'New body b' } });
+ expect(screen.getByRole('button', { name: 'Save', exact: true })).toBeDisabled();
+ await act(async () => { saved.resolve(memory('a')); });
+ expect(screen.getByRole('textbox', { name: 'What happened' })).toHaveValue('New body b');
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Save', exact: true })); });
+ expect(api.updateBrainMemory).toHaveBeenLastCalledWith('b', expect.objectContaining({ content: 'New body b' }), { silent: true });
+ });
+
+ it('does not restore a canceled hydration after reopening the same record', async () => {
+ const older = deferred();
+ const newer = deferred();
+ api.getBrainMemory.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise);
+ await mount([memory('a', { contentTruncated: true })]);
+ edit('Example a');
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel', exact: true }));
+ edit('Example a');
+ await act(async () => { newer.resolve(memory('a', { content: 'Current body' })); });
+ fireEvent.change(screen.getByRole('textbox', { name: 'What happened' }), { target: { value: 'New unsaved body' } });
+ await act(async () => { older.resolve(memory('a')); });
+ expect(screen.getByRole('textbox', { name: 'What happened' })).toHaveValue('New unsaved body');
+ });
+
+ it('disables the submitted form while saving and preserves it after failure', async () => {
+ const saved = deferred();
+ api.updateBrainMemory.mockReturnValueOnce(saved.promise);
+ await mount([memory('a')]);
+ edit('Example a');
+ fireEvent.change(screen.getByRole('textbox', { name: 'What happened' }), { target: { value: 'Unsaved body' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save', exact: true }));
+ expect(screen.getByRole('textbox', { name: 'What happened' })).toBeDisabled();
+ fireEvent.click(screen.getByRole('button', { name: 'Save', exact: true }));
+ expect(api.updateBrainMemory).toHaveBeenCalledTimes(1);
+ await act(async () => { saved.reject(new Error('Write failed')); });
+ expect(screen.getByRole('textbox', { name: 'What happened' })).toBeEnabled();
+ expect(screen.getByRole('textbox', { name: 'What happened' })).toHaveValue('Unsaved body');
+ expect(screen.getByRole('button', { name: 'Save', exact: true })).toBeEnabled();
+ });
+
+ it('invalidates a hydration across a type change even when record IDs coincide', async () => {
+ const full = deferred();
+ api.getBrainMemory.mockReturnValueOnce(full.promise);
+ api.getBrainPeople.mockResolvedValue([{ id: 'a', name: 'Example person', context: 'Person context' }]);
+ await mount([memory('a', { contentTruncated: true })]);
+ edit('Example a');
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'People' })); });
+ fireEvent.click(screen.getByRole('button', { name: 'Edit', exact: true }));
+ await act(async () => { full.resolve(memory('a')); });
+ expect(screen.getByRole('textbox', { name: 'Name' })).toHaveValue('Example person');
+ expect(screen.getByRole('textbox', { name: /Context/ })).toHaveValue('Person context');
+ });
+});
diff --git a/client/src/components/brain/tabs/MemoryTab.jsx b/client/src/components/brain/tabs/MemoryTab.jsx
index 1e033fac9f..3adab82f17 100644
--- a/client/src/components/brain/tabs/MemoryTab.jsx
+++ b/client/src/components/brain/tabs/MemoryTab.jsx
@@ -32,6 +32,7 @@ import CollapsibleListItem from '../../ui/CollapsibleListItem';
import InfiniteScrollFooter from '../../ui/InfiniteScrollFooter';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
import { usePagedCollection } from '../../../hooks/usePagedCollection';
+import useMounted from '../../../hooks/useMounted';
import socket from '../../../services/socket';
// Plain-text teaser for imported transcripts — avoids mounting full markdown
@@ -66,6 +67,23 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {
currentType.current = activeType;
const [editingId, setEditingId] = useState(null);
const [editForm, setEditForm] = useState({});
+ const [editStatus, setEditStatus] = useState('ready');
+ const [savingEdit, setSavingEdit] = useState(false);
+ const pendingSave = useRef(false);
+ const editSession = useRef(null);
+ const selectedRecordId = useRef(recordId);
+ selectedRecordId.current = recordId;
+ const mounted = useMounted();
+ const cancelEdit = useCallback(() => {
+ editSession.current = null;
+ setEditingId(null);
+ setEditForm({});
+ setEditStatus('ready');
+ }, []);
+ useEffect(() => {
+ cancelEdit();
+ return () => { editSession.current = null; };
+ }, [activeType, cancelEdit]);
const [showAdd, setShowAdd] = useState(false);
const [addForm, setAddForm] = useState({});
const [statusFilter, setStatusFilter] = useState('');
@@ -217,28 +235,33 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {
}, [records, searchQuery, removingIds, activeType]);
const handleSave = async () => {
+ const session = editSession.current;
+ if (!session || pendingSave.current || editStatus !== 'ready' || session.type !== activeType) return;
+ pendingSave.current = true;
+ setSavingEdit(true);
+ setEditStatus('saving');
let result;
- switch (activeType) {
+ switch (session.type) {
case 'people':
- result = await api.updateBrainPerson(editingId, editForm, { silent: true }).catch(err => {
+ result = await api.updateBrainPerson(session.id, editForm, { silent: true }).catch(err => {
toast.error(err.message);
return null;
});
break;
case 'projects':
- result = await api.updateBrainProject(editingId, editForm, { silent: true }).catch(err => {
+ result = await api.updateBrainProject(session.id, editForm, { silent: true }).catch(err => {
toast.error(err.message);
return null;
});
break;
case 'ideas':
- result = await api.updateBrainIdea(editingId, editForm, { silent: true }).catch(err => {
+ result = await api.updateBrainIdea(session.id, editForm, { silent: true }).catch(err => {
toast.error(err.message);
return null;
});
break;
case 'admin':
- result = await api.updateBrainAdminItem(editingId, editForm, { silent: true }).catch(err => {
+ result = await api.updateBrainAdminItem(session.id, editForm, { silent: true }).catch(err => {
toast.error(err.message);
return null;
});
@@ -246,7 +269,7 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {
case 'memories': {
const { tagInput, ...memData } = editForm;
if (tagInput != null) memData.tags = tagInput.split(',').map(s => s.trim()).filter(Boolean);
- result = await api.updateBrainMemory(editingId, memData, { silent: true }).catch(err => {
+ result = await api.updateBrainMemory(session.id, memData, { silent: true }).catch(err => {
toast.error(err.message);
return null;
});
@@ -254,12 +277,14 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {
}
}
- if (result) {
+ pendingSave.current = false;
+ if (mounted.current) setSavingEdit(false);
+ if (editSession.current === session) setEditStatus('ready');
+ if (result && mounted.current && currentType.current === session.type) {
toast.success('Saved');
- if (editingId === recordId) setDetailResult({ id: recordId, type: activeType, record: result });
- setEditingId(null);
- setEditForm({});
- paged.refreshFirst();
+ if (session.id === selectedRecordId.current) setDetailResult({ id: session.id, type: session.type, record: result });
+ if (editSession.current === session) cancelEdit();
+ paged.setItems(items => items.map(item => item.id === session.id ? result : item));
onRefresh?.();
}
};
@@ -401,15 +426,23 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {
};
const startEdit = async (record) => {
+ // The token distinguishes separate visits to the same record as well as
+ // different records. A canceled load/save cannot acquire the next editor.
+ const session = { id: record.id, type: activeType };
+ editSession.current = session;
setEditingId(record.id);
if (activeType === 'memories' && record.contentTruncated) {
- setEditForm({ ...record, tagInput: (record.tags || []).join(', ') });
- const full = await api.getBrainMemory(record.id).catch(() => null);
- if (full) {
+ setEditForm({});
+ setEditStatus('loading');
+ const full = await api.getBrainMemory(record.id, { silent: true }).catch(() => null);
+ if (editSession.current !== session) return;
+ if (full?.id === record.id && !full.contentTruncated) {
setEditForm({ ...full, tagInput: (full.tags || []).join(', ') });
- }
+ setEditStatus('ready');
+ } else setEditStatus('error');
} else {
setEditForm({ ...record, tagInput: (record.tags || []).join(', ') });
+ setEditStatus('ready');
}
};
@@ -629,17 +662,25 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {
if (editingId === record.id && (recordId !== record.id || inReader)) {
return (
<div key={record.id} className="p-4 bg-port-card border border-port-accent/50 rounded-lg">
- {renderForm(editForm, setEditForm, true)}
+ {editStatus === 'loading' ? <BrailleSpinner text="Loading entry for editing" /> : editStatus === 'error' ? (
+ <Banner tone="error" title="Couldn't load this entry for editing">
+ The full record must load before changes can be saved.
+ <button onClick={() => startEdit(record)} className="block min-h-[44px] text-port-accent hover:underline">Retry</button>
+ </Banner>
+ ) : (
+ <fieldset disabled={editStatus === 'saving'}>{renderForm(editForm, setEditForm, true)}</fieldset>
+ )}
<div className="flex items-center gap-2 mt-3">
<button
onClick={handleSave}
- className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 text-port-accent rounded hover:bg-port-accent/30"
+ disabled={editStatus !== 'ready' || savingEdit}
+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 text-port-accent rounded hover:bg-port-accent/30 disabled:opacity-50"
>
<Save size={14} />
Save
</button>
<button
- onClick={() => { setEditingId(null); setEditForm({}); }}
+ onClick={cancelEdit}
className="px-3 py-1.5 text-gray-400 hover:text-white"
>
Cancel