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: isolate mood board edits across navigation

[._.]/ Adam Eivy99a6251c2c9a
diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsx
index 7b6f9b76f3..8cd876b407 100644
--- a/client/src/pages/MoodBoardDetail.jsx
+++ b/client/src/pages/MoodBoardDetail.jsx
@@ -35,6 +35,12 @@ import useMounted from '../hooks/useMounted';
export default function MoodBoardDetail() {
const { id } = useParams();
+ // Route changes replace the editor so every draft, modal and pending-action
+ // flag belongs to one board, including when the next board fails to load.
+ return <MoodBoardEditor key={id} id={id} />;
+}
+
+function MoodBoardEditor({ id }) {
const navigate = useNavigate();
const [board, setBoard] = useState(null);
const [loading, setLoading] = useState(true);
@@ -67,12 +73,9 @@ export default function MoodBoardDetail() {
const [syncing, setSyncing] = useState(false);
const [confirmingUnlink, setConfirmingUnlink] = useState(false);
- // Stale-response guards. `load` fires whenever the board `id` changes; because
- // the fetch is async, an older request can resolve *after* a newer one (the
- // user navigated to a different board) and clobber current state. We bump a
- // sequence counter per call and only apply the result if it's still the latest
- // — and only if the component is still mounted. The seq counter independently
- // drops StrictMode's duplicate first fetch.
+ // The keyed editor isolates board state. Also guard async continuations and
+ // delayed child callbacks so the old editor cannot toast or start a mutation
+ // after navigation. The load sequence drops StrictMode's duplicate GET.
const mountedRef = useMounted();
const loadSeqRef = useRef(0);
@@ -89,6 +92,7 @@ export default function MoodBoardDetail() {
setDescription(data.description || '');
setPinUrl(data.pinterest?.boardUrl || '');
} else {
+ setBoard(null);
toast.error('Mood board not found');
}
setLoading(false);
@@ -110,9 +114,11 @@ export default function MoodBoardDetail() {
const analyzeSource = useMemo(() => moodBoardItemAnalysisSource(analyzeItem), [analyzeItem]);
const handleSaveMeta = async () => {
+ if (!mountedRef.current) return;
if (!name.trim()) { toast.error('Board name is required'); return; }
setSavingMeta(true);
const updated = await updateMoodBoard(id, { name: name.trim(), description }, { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
setSavingMeta(false);
if (!updated) { toast.error('Failed to save board'); return; }
setBoard(updated);
@@ -124,6 +130,7 @@ export default function MoodBoardDetail() {
};
const handleAddItem = async () => {
+ if (!mountedRef.current) return;
const payload = { type: itemType, caption: caption || null, source: source || null };
if (itemType === 'image') {
if (!imageUrl.trim()) { toast.error('Enter an image URL'); return; }
@@ -134,6 +141,7 @@ export default function MoodBoardDetail() {
}
setAdding(true);
const item = await addMoodBoardItem(id, payload, { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
setAdding(false);
if (!item) { toast.error('Failed to add item'); return; }
setBoard((prev) => (prev ? { ...prev, items: [...(prev.items || []), item] } : prev));
@@ -146,7 +154,9 @@ export default function MoodBoardDetail() {
// FILENAME (`video:<file>.mp4`) so playback and peer-sync asset transfer
// both resolve without an id→filename lookup.
const addPickedItem = async (payload) => {
+ if (!mountedRef.current) return;
const item = await addMoodBoardItem(id, payload, { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
if (!item) { toast.error('Failed to add item'); return; }
setBoard((prev) => (prev ? { ...prev, items: [...(prev.items || []), item] } : prev));
};
@@ -170,7 +180,9 @@ export default function MoodBoardDetail() {
};
const handleUpdateCaption = async (itemId, nextCaption) => {
+ if (!mountedRef.current) return;
const item = await updateMoodBoardItem(id, itemId, { caption: nextCaption || null }, { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
if (!item) { toast.error('Failed to update caption'); return; }
setBoard((prev) => (prev
? { ...prev, items: (prev.items || []).map((it) => (it.id === itemId ? item : it)) }
@@ -181,6 +193,7 @@ export default function MoodBoardDetail() {
// analyzer can return an image and/or a video prompt; store the one that
// matches the item's own type, falling back to whichever was generated.
const persistAnalysis = async (item, result) => {
+ if (!mountedRef.current) return;
const preferVideo = item.type === 'video';
const primary = preferVideo ? result.videoPrompt : result.imagePrompt;
const fallback = preferVideo ? result.imagePrompt : result.videoPrompt;
@@ -198,6 +211,7 @@ export default function MoodBoardDetail() {
model: result.model || null,
};
const updated = await updateMoodBoardItem(id, item.id, { analysis }, { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
if (!updated) { toast.error('Analysis ran but could not be saved to the item'); return; }
setBoard((prev) => (prev
? { ...prev, items: (prev.items || []).map((it) => (it.id === item.id ? updated : it)) }
@@ -206,7 +220,9 @@ export default function MoodBoardDetail() {
};
const handleClearAnalysis = async (itemId) => {
+ if (!mountedRef.current) return;
const updated = await updateMoodBoardItem(id, itemId, { analysis: null }, { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
if (!updated) { toast.error('Failed to remove analysis'); return; }
setBoard((prev) => (prev
? { ...prev, items: (prev.items || []).map((it) => (it.id === itemId ? updated : it)) }
@@ -214,16 +230,20 @@ export default function MoodBoardDetail() {
};
const handleRemoveItem = async (itemId) => {
+ if (!mountedRef.current) return;
setConfirmingItemId(null);
const updated = await removeMoodBoardItem(id, itemId, { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
if (!updated) { toast.error('Failed to remove item'); return; }
setBoard((prev) => (prev ? { ...prev, items: (prev.items || []).filter((it) => it.id !== itemId) } : prev));
};
const handleLinkPinterest = async () => {
+ if (!mountedRef.current) return;
if (!pinUrl.trim()) { toast.error('Enter a Pinterest board URL'); return; }
setLinking(true);
const updated = await linkMoodBoardPinterest(id, pinUrl.trim(), { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
setLinking(false);
if (!updated) { toast.error('Could not link that Pinterest URL — is it a public board?'); return; }
setBoard(updated);
@@ -232,16 +252,20 @@ export default function MoodBoardDetail() {
};
const handleUnlinkPinterest = async () => {
+ if (!mountedRef.current) return;
setConfirmingUnlink(false);
const updated = await unlinkMoodBoardPinterest(id, { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
if (!updated) { toast.error('Failed to unlink'); return; }
setBoard(updated);
setPinUrl('');
};
const handleSyncPinterest = async () => {
+ if (!mountedRef.current) return;
setSyncing(true);
const result = await syncMoodBoardPinterest(id, { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
setSyncing(false);
if (!result?.board) { toast.error('Pinterest sync failed — the feed may be private or rate-limited'); return; }
setBoard(result.board);
diff --git a/client/src/pages/MoodBoardDetail.test.jsx b/client/src/pages/MoodBoardDetail.test.jsx
index 466a3f6458..007025fc6e 100644
--- a/client/src/pages/MoodBoardDetail.test.jsx
+++ b/client/src/pages/MoodBoardDetail.test.jsx
@@ -6,23 +6,27 @@ import { MemoryRouter } from 'react-router';
// ── Mocks must be declared before any imports that use them ──────────────────
const mockGetMoodBoard = vi.fn();
+const mockUpdateMoodBoard = vi.fn();
+const mockAddMoodBoardItem = vi.fn();
const mockUpdateMoodBoardItem = vi.fn();
+const mockSyncMoodBoardPinterest = vi.fn();
vi.mock('../services/api', () => ({
getMoodBoard: (...args) => mockGetMoodBoard(...args),
- updateMoodBoard: vi.fn(),
- addMoodBoardItem: vi.fn(),
+ updateMoodBoard: (...args) => mockUpdateMoodBoard(...args),
+ addMoodBoardItem: (...args) => mockAddMoodBoardItem(...args),
updateMoodBoardItem: (...args) => mockUpdateMoodBoardItem(...args),
removeMoodBoardItem: vi.fn(),
linkMoodBoardPinterest: vi.fn(),
unlinkMoodBoardPinterest: vi.fn(),
- syncMoodBoardPinterest: vi.fn(),
+ syncMoodBoardPinterest: (...args) => mockSyncMoodBoardPinterest(...args),
}));
const mockToastError = vi.fn();
+const mockToastSuccess = vi.fn();
vi.mock('../components/ui/Toast', () => ({
default: Object.assign(vi.fn(), {
- success: vi.fn(),
+ success: (...args) => mockToastSuccess(...args),
error: (...args) => mockToastError(...args),
warning: vi.fn(),
}),
@@ -31,19 +35,24 @@ vi.mock('../components/ui/Toast', () => ({
// Stub the prompt-from-media modal (#4188 Phase 3) — the analysis flow under
// test is the page's own wiring (open, persist via onResult, stored-analysis
// children), not the analyzer internals, which have their own suite.
+let analysisDelay = null;
vi.mock('../components/media/PromptFromMedia', () => ({
PromptFromMediaModal: ({ open, item, onResult, children }) => (open && item ? (
<div data-testid="pfm-modal">
{children}
<button
type="button"
- onClick={() => onResult?.({
- imagePrompt: 'a moody castle at dusk',
- imageNegativePrompt: 'blurry',
- rationale: 'gothic look',
- providerId: 'openai',
- model: 'gpt-4o',
- })}
+ onClick={() => {
+ const deliver = () => onResult?.({
+ imagePrompt: 'a moody castle at dusk',
+ imageNegativePrompt: 'blurry',
+ rationale: 'gothic look',
+ providerId: 'openai',
+ model: 'gpt-4o',
+ });
+ if (analysisDelay) analysisDelay.then(deliver);
+ else deliver();
+ }}
>
mock-generate
</button>
@@ -69,8 +78,9 @@ import MoodBoardDetail from './MoodBoardDetail.jsx';
// order) each fetch settles.
const deferred = () => {
let resolve;
- const promise = new Promise((res) => { resolve = res; });
- return { promise, resolve };
+ let reject;
+ const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
+ return { promise, resolve, reject };
};
// Flush pending microtasks + one macrotask so an awaited fetch continuation
@@ -89,6 +99,7 @@ const boardNameValue = () => screen.getByLabelText('Name').value;
beforeEach(() => {
vi.clearAllMocks();
currentId = 'a';
+ analysisDelay = null;
});
describe('MoodBoardDetail stale-response guards', () => {
@@ -146,6 +157,76 @@ describe('MoodBoardDetail stale-response guards', () => {
await flush();
expect(mockToastError).not.toHaveBeenCalled();
});
+
+ it('keeps the new board drafts and pending save when the old save and pin finish', async () => {
+ const oldSave = deferred();
+ const newSave = deferred();
+ const oldPin = deferred();
+ mockGetMoodBoard
+ .mockResolvedValueOnce({ id: 'a', name: 'Board A', items: [] })
+ .mockResolvedValueOnce({ id: 'b', name: 'Board B', items: [] });
+ mockUpdateMoodBoard.mockReturnValueOnce(oldSave.promise).mockReturnValueOnce(newSave.promise);
+ mockAddMoodBoardItem.mockReturnValueOnce(oldPin.promise);
+ const { rerender } = renderPage();
+ await waitFor(() => expect(boardNameValue()).toBe('Board A'));
+
+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Edited A' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save', exact: true }));
+ fireEvent.click(screen.getByRole('tab', { name: 'Note' }));
+ fireEvent.change(screen.getByLabelText('Note'), { target: { value: 'A note' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Pin to board' }));
+
+ currentId = 'b';
+ rerender(<MemoryRouter><MoodBoardDetail /></MemoryRouter>);
+ await waitFor(() => expect(boardNameValue()).toBe('Board B'));
+ expect(screen.getByLabelText('Image URL')).toHaveValue('');
+ expect(screen.getByRole('button', { name: 'Pin to board' })).not.toBeDisabled();
+ fireEvent.change(screen.getByLabelText('Image URL'), { target: { value: 'https://example.com/b.png' } });
+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Edited B' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save', exact: true }));
+
+ await act(async () => {
+ oldSave.resolve({ id: 'a', name: 'Edited A', items: [] });
+ oldPin.resolve({ id: 'a-note', type: 'text', text: 'A note' });
+ });
+ expect(boardNameValue()).toBe('Edited B');
+ expect(screen.getByLabelText('Image URL')).toHaveValue('https://example.com/b.png');
+ expect(screen.queryByText('A note')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Save', exact: true })).toBeDisabled();
+ expect(mockToastSuccess).not.toHaveBeenCalled();
+ expect(mockToastError).not.toHaveBeenCalled();
+
+ await act(async () => { newSave.resolve({ id: 'b', name: 'Edited B', items: [] }); });
+ expect(mockUpdateMoodBoard).toHaveBeenLastCalledWith('b', { name: 'Edited B', description: '' }, { silent: true });
+ expect(mockToastSuccess).toHaveBeenCalledWith('Board saved');
+ });
+
+ it('clears the old board when the next GET fails and ignores a rejected old sync', async () => {
+ const nextLoad = deferred();
+ const oldSync = deferred();
+ mockGetMoodBoard
+ .mockResolvedValueOnce({
+ id: 'a', name: 'Board A', items: [],
+ pinterest: { boardUrl: 'https://www.pinterest.com/example/board/', feedUrl: 'https://example.com/feed.rss' },
+ })
+ .mockReturnValueOnce(nextLoad.promise);
+ mockSyncMoodBoardPinterest.mockReturnValueOnce(oldSync.promise);
+ const { rerender } = renderPage();
+ await waitFor(() => expect(boardNameValue()).toBe('Board A'));
+ fireEvent.click(screen.getByRole('button', { name: 'Sync now' }));
+
+ currentId = 'missing';
+ rerender(<MemoryRouter><MoodBoardDetail /></MemoryRouter>);
+ expect(screen.queryByLabelText('Name')).not.toBeInTheDocument();
+ await act(async () => { nextLoad.reject(new Error('Not found')); });
+ expect(screen.getByText('This mood board doesn’t exist.')).toBeInTheDocument();
+ expect(screen.queryByLabelText('Name')).not.toBeInTheDocument();
+ expect(mockToastError).toHaveBeenCalledExactlyOnceWith('Mood board not found');
+
+ await act(async () => { oldSync.reject(new Error('Sync failed')); });
+ expect(mockToastError).toHaveBeenCalledExactlyOnceWith('Mood board not found');
+ expect(mockToastSuccess).not.toHaveBeenCalled();
+ });
});
describe('MoodBoardDetail video items (#4188)', () => {
@@ -205,6 +286,27 @@ describe('MoodBoardDetail item analysis (#4188 Phase 3)', () => {
id: 'i1', type: 'image', mediaKey: 'image:ref.png', imageUrl: null, caption: null, source: null,
};
+ it('does not persist an analysis callback delivered after leaving its board', async () => {
+ const pendingAnalysis = deferred();
+ analysisDelay = pendingAnalysis.promise;
+ mockGetMoodBoard
+ .mockResolvedValueOnce({ id: 'a', name: 'Board A', items: [galleryImageItem] })
+ .mockResolvedValueOnce({ id: 'b', name: 'Board B', items: [] });
+ const { rerender } = renderPage();
+ await waitFor(() => expect(boardNameValue()).toBe('Board A'));
+ fireEvent.click(screen.getByRole('button', { name: 'Analyze with AI' }));
+ fireEvent.click(screen.getByRole('button', { name: 'mock-generate' }));
+
+ currentId = 'b';
+ rerender(<MemoryRouter><MoodBoardDetail /></MemoryRouter>);
+ await waitFor(() => expect(boardNameValue()).toBe('Board B'));
+ expect(screen.queryByTestId('pfm-modal')).not.toBeInTheDocument();
+ await act(async () => { pendingAnalysis.resolve(); });
+ expect(mockUpdateMoodBoardItem).not.toHaveBeenCalled();
+ expect(mockToastSuccess).not.toHaveBeenCalled();
+ expect(mockToastError).not.toHaveBeenCalled();
+ });
+
it('offers the analyze action only on gallery-backed media items', async () => {
mockGetMoodBoard.mockResolvedValueOnce({
id: 'a',