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: ignore stale/unmounted Mood Board response updates (#2388)

Adam Eivyf2aeba11ce52
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c3b02f3f44..23c2769f67 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -65,6 +65,8 @@
- **CoS tasks with Review Loop turned off now explicitly disable saved external-review defaults when opening a PR.** Their completion prompt passes `--review-with none`, so an inherited Copilot (or other reviewer) default cannot launch a review that was not requested.
+- **[issue-2388] A slow Mood Board fetch can no longer overwrite the board you switched to (or a page you left).** `MoodBoardDetail`'s `load()` fires on every board `id` change but its fetch is async, so navigating from one board to another before the first request resolved let the older (stale) response land last and clobber the newer board's name/description/Pinterest state — and a response that resolved after the page unmounted would still fire its "not found" toast. `load()` now bumps a per-call sequence counter and captures a `mountedRef`, and drops any resolution that is no longer the latest request or arrives after unmount *before* touching state or toasting, so out-of-order completions and post-unmount updates are ignored while the current loading/error behavior is otherwise unchanged. A focused test proves the older of two overlapping loads can't overwrite the newer board and that a post-unmount not-found response fires no toast.
+
- **[issue-2387] Theme initialization and switching now survive unavailable localStorage.** The `useTheme` and `useCitySettings` hooks read/wrote `localStorage` directly (persisted theme, and the CyberCity settings that render on the same theme path), so a browser where storage access throws (Safari private mode, blocked cookies, disabled storage) or is absent would throw inside a `useState` initializer and crash the initial render, and a failing `setItem` could break theme switching. Both hooks now route every read/write/remove through a shared, guarded `safeReadStorage`/`safeWriteStorage`/`safeRemoveStorage` helper (`client/src/lib/safeStorage.js`) that swallows access failures, and corrupt stored JSON falls back to defaults instead of throwing — so init always resolves to a valid default and in-memory switching keeps working when persistence fails. `setTheme` also applies the in-memory theme (DOM + state) before any persistence/side-effect work so a later failure can never leave the UI on the stale theme. Focused hook tests cover read-throws-on-init, corrupt/invalid stored value, and write-throws-on-switch for both hooks.
- **[issue-2384] A usage-limit fallback signal now stops a direct-CLI CoS agent immediately even when an earlier transcript write is stalled, and the persisted transcript can no longer be reordered.** The direct-CLI spawn path (`spawnDirectly` in `server/services/agentCliSpawning.js`) let each stdout/stderr `data` event run its transcript-mutating body (`outputBuffer` append + `output.txt` write + batched live-tail push) as an independent async handler, so two chunks' interleaved `await`s could persist output out of order, and a blocked state/file write on an earlier chunk could sit in front of a later chunk that carried the `Now using extra usage` fallback marker. Fallback detection now runs **synchronously** in the raw listener — before any transcript work is enqueued — so the provider is killed the instant the signal arrives regardless of a stalled write, while the transcript body is serialized onto a single per-agent tail promise (mirroring `shell.js`'s `hookQueue` and `pipeline/issues.js`'s `issueWriteTail`) that the close/error/terminate paths drain before finalizing. A regression test blocks an earlier write, emits the fallback signal on a later chunk, and asserts termination stays immediate and final output stays ordered.
diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsx
index 4b20605a66..4e823a72a1 100644
--- a/client/src/pages/MoodBoardDetail.jsx
+++ b/client/src/pages/MoodBoardDetail.jsx
@@ -9,7 +9,7 @@
* `mediaKey` image item if one exists, but the in-page add form uses URL/text.
*/
-import { useEffect, useState, useCallback } from 'react';
+import { useEffect, useState, useCallback, useRef } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { ArrowLeft, ImageIcon, FileText, Trash2, Plus, Save, Link2, Unlink, RefreshCw } from 'lucide-react';
import toast from '../components/ui/Toast';
@@ -51,9 +51,31 @@ 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.
+ //
+ // `mountedRef` is set true on mount (not just left at its initial value) so
+ // that React 18 StrictMode's dev-only mount→cleanup→remount — which preserves
+ // this ref and would otherwise leave it stuck `false` after the simulated
+ // unmount — re-arms the guard for the real mount. The seq counter independently
+ // drops StrictMode's duplicate first fetch.
+ const mountedRef = useRef(true);
+ const loadSeqRef = useRef(0);
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => { mountedRef.current = false; };
+ }, []);
+
const load = useCallback(async () => {
+ const seq = ++loadSeqRef.current;
setLoading(true);
const data = await getMoodBoard(id, { silent: true }).catch(() => null);
+ // Drop stale (a newer load started) or unmounted resolutions before any
+ // setState / toast so an out-of-order response can't overwrite current state.
+ if (!mountedRef.current || seq !== loadSeqRef.current) return;
if (data) {
setBoard(data);
setName(data.name || '');
diff --git a/client/src/pages/MoodBoardDetail.test.jsx b/client/src/pages/MoodBoardDetail.test.jsx
new file mode 100644
index 0000000000..84b0ef1f2a
--- /dev/null
+++ b/client/src/pages/MoodBoardDetail.test.jsx
@@ -0,0 +1,122 @@
+import { StrictMode } from 'react';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+
+// ── Mocks must be declared before any imports that use them ──────────────────
+
+const mockGetMoodBoard = vi.fn();
+
+vi.mock('../services/api', () => ({
+ getMoodBoard: (...args) => mockGetMoodBoard(...args),
+ updateMoodBoard: vi.fn(),
+ addMoodBoardItem: vi.fn(),
+ updateMoodBoardItem: vi.fn(),
+ removeMoodBoardItem: vi.fn(),
+ linkMoodBoardPinterest: vi.fn(),
+ unlinkMoodBoardPinterest: vi.fn(),
+ syncMoodBoardPinterest: vi.fn(),
+}));
+
+const mockToastError = vi.fn();
+vi.mock('../components/ui/Toast', () => ({
+ default: Object.assign(vi.fn(), {
+ success: vi.fn(),
+ error: (...args) => mockToastError(...args),
+ warning: vi.fn(),
+ }),
+}));
+
+// Control the board id `useParams` returns so we can simulate the user
+// navigating from one board to another mid-fetch.
+let currentId = 'a';
+vi.mock('react-router-dom', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ useParams: () => ({ id: currentId }),
+ useNavigate: () => vi.fn(),
+ };
+});
+
+import MoodBoardDetail from './MoodBoardDetail.jsx';
+
+// A promise plus its resolver, so a test can control exactly when (and in what
+// order) each fetch settles.
+const deferred = () => {
+ let resolve;
+ const promise = new Promise((res) => { resolve = res; });
+ return { promise, resolve };
+};
+
+// Flush pending microtasks + one macrotask so an awaited fetch continuation
+// (including its `.catch()` link) has fully run before we assert.
+const flush = async () => {
+ await new Promise((r) => setTimeout(r, 0));
+ await Promise.resolve();
+};
+
+const renderPage = () => render(
+ <MemoryRouter><MoodBoardDetail /></MemoryRouter>,
+);
+
+const boardNameValue = () => screen.getByLabelText('Name').value;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ currentId = 'a';
+});
+
+describe('MoodBoardDetail stale-response guards', () => {
+ it('renders the loaded board', async () => {
+ mockGetMoodBoard.mockResolvedValueOnce({ id: 'a', name: 'Board A', items: [] });
+ renderPage();
+ await waitFor(() => expect(boardNameValue()).toBe('Board A'));
+ });
+
+ it('ignores an out-of-order (stale) response after the board id changes', async () => {
+ const first = deferred();
+ const second = deferred();
+ mockGetMoodBoard
+ .mockReturnValueOnce(first.promise) // board 'a'
+ .mockReturnValueOnce(second.promise); // board 'b'
+
+ const { rerender } = renderPage();
+ // The user navigates to board 'b' before board 'a' has resolved.
+ currentId = 'b';
+ rerender(<MemoryRouter><MoodBoardDetail /></MemoryRouter>);
+
+ // Newer request resolves first — its data should show.
+ second.resolve({ id: 'b', name: 'Board B', items: [] });
+ await waitFor(() => expect(boardNameValue()).toBe('Board B'));
+
+ // Older (stale) request resolves last — it must NOT overwrite current state.
+ first.resolve({ id: 'a', name: 'Board A', items: [] });
+ await flush();
+ expect(boardNameValue()).toBe('Board B');
+ });
+
+ it('still renders under StrictMode (mount guard re-arms on remount)', async () => {
+ // StrictMode double-invokes mount/effects in dev; the mount guard must be
+ // re-armed on the real mount or the board would be stuck on "Loading…".
+ mockGetMoodBoard.mockResolvedValue({ id: 'a', name: 'Board A', items: [] });
+ render(
+ <StrictMode><MemoryRouter><MoodBoardDetail /></MemoryRouter></StrictMode>,
+ );
+ await waitFor(() => expect(boardNameValue()).toBe('Board A'));
+ });
+
+ it('drops updates from a response that resolves after unmount', async () => {
+ const pending = deferred();
+ mockGetMoodBoard.mockReturnValueOnce(pending.promise);
+
+ const { unmount } = renderPage();
+ unmount();
+
+ // A not-found response after unmount must not fire its error toast — the
+ // unmounted guard returns before any setState / toast.
+ pending.resolve(null);
+ await flush();
+ expect(mockToastError).not.toHaveBeenCalled();
+ });
+});