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: cancel pending query-mirror writes before navigating away (#8187)

[._.]/ Adam Eivy90c069935532
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index f014dcfd5b..757662c803 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -114,6 +114,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useAutoSizeTextarea` | `[ref, resize]` — grows a `<textarea>` to fit its content (no scroll / hand-resize); recomputes before paint on value change. | A textarea that should auto-fit content. Prefer the `AutoSizeTextarea` UI component, which wraps this. |
| `useChartColors` | Resolves the `--port-*` theme tokens (accent/success/warning/error, `chart-1..4`, grid, axis, tooltip surfaces) to concrete `rgb()` strings via `getComputedStyle`, re-resolving on theme switch. | A recharts card needs theme-following colors — SVG `fill`/`stroke` props can't read CSS vars, so pass these resolved strings instead of hardcoded hex. |
| `useClickOutside` | Fire `onOutside` on mousedown outside a ref — or outside *every* ref in an array. | Popovers, menus, drawers. Pass `[triggerRef, panelRef]` for a portaled panel, which is outside the trigger's subtree. |
+| `useCancelableDebounce` | `[schedule, cancel]` — `schedule(fn, delay)` arms a cancelable `setTimeout`, replacing any pending call; `cancel()` drops it with no replacement. Call `cancel()` synchronously right before a navigation that a stale debounced write must not be able to race (React's own unmount cleanup runs asynchronously relative to `navigate()`, leaving a window under load). | Any debounced state→URL mirror sitting in front of a route that can change out from under it (Catalog, MediaCollections search-query mirrors) — don't re-roll a bare `setTimeout`/`clearTimeout` pair. |
| `useConfirmDelete` | Single-at-a-time `{ confirmingId, isConfirming, requestDelete, cancelDelete, confirmDelete }` for arming one list/card row at a time. | New destructive list action — pair with `<InlineConfirmRow>` / `<ConfirmButtonPair>` instead of deleting on the raw trash click. |
| `useEscapeKey` | `useEscapeKey(active, handler)` — call `handler` on Escape while `active`. | Non-modal dismissables (in-context popovers/cards); Modal owns Esc for true modals. |
| `useHoverTooltip` | `{ hoveredNode, tooltipPos, handleHover, handlePointerMove }` for a canvas hover tooltip. `handlePointerMove` drops any move that cannot paint a tooltip (nothing hovered, or a touch pointer, where the tooltip is `pointer-coarse:hidden`), so idle cursor motion stops re-rendering the page. The gate reads a ref, not the hovered state — r3f raycasts on the Canvas' inner div while React delegates the container's move handler, so the enter event's own move still sees the pre-flush `null`. | Any 3D graph/canvas view with a cursor-following hover tooltip (BrainGraph) — pass `{ x: e.clientX, y: e.clientY }` to `handleHover` from the mesh's `onPointerOver` so the first frame is placed. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 05a2764934..abb567870b 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -19,6 +19,7 @@ export { default as useAutoSizeTextarea } from './useAutoSizeTextarea.js';
export { default as useChartColors } from './useChartColors.js';
export * from './useChartColors.js';
export { default as useClickOutside } from './useClickOutside.js';
+export { default as useCancelableDebounce } from './useCancelableDebounce.js';
export { default as useConfirmDelete } from './useConfirmDelete.js';
export { default as useColorMatch } from './useColorMatch.js';
export { default as useContainerWidth } from './useContainerWidth.js';
diff --git a/client/src/hooks/useCancelableDebounce.js b/client/src/hooks/useCancelableDebounce.js
new file mode 100644
index 0000000000..9e3feae121
--- /dev/null
+++ b/client/src/hooks/useCancelableDebounce.js
@@ -0,0 +1,41 @@
+import { useCallback, useEffect, useRef } from 'react';
+
+// A setTimeout-backed debounce whose pending callback can be cancelled
+// synchronously by the caller — not only via the arming effect's own unmount
+// cleanup. React's unmount runs asynchronously relative to a `navigate()`
+// call made in the same tick (it waits for the router to re-render and
+// commit), so a debounce timer armed well before that `navigate()` can still
+// fire in the gap under load, landing a stale write after a route change is
+// already in flight and clobbering it (#8187 — MediaCollections' query→URL
+// mirror overwrote a just-opened collection's detail route). Storing the
+// timer id in a ref that outlives a single render lets both the effect's own
+// cleanup AND an imperative call site (e.g. right before `navigate()`) cancel
+// the exact same pending write.
+//
+// `[schedule, cancel]`: `schedule(fn, delay)` replaces any pending call with
+// a new one; `cancel()` drops a pending call with no replacement. Call
+// `cancel()` immediately before any navigation that a stale debounced write
+// must not be allowed to race.
+export default function useCancelableDebounce() {
+ const timerRef = useRef(null);
+
+ const cancel = useCallback(() => {
+ if (timerRef.current != null) {
+ clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }
+ }, []);
+
+ const schedule = useCallback((fn, delay) => {
+ cancel();
+ timerRef.current = setTimeout(() => {
+ timerRef.current = null;
+ fn();
+ }, delay);
+ }, [cancel]);
+
+ // Unmount safety net for the normal (non-racing) case.
+ useEffect(() => cancel, [cancel]);
+
+ return [schedule, cancel];
+}
diff --git a/client/src/hooks/useCancelableDebounce.test.js b/client/src/hooks/useCancelableDebounce.test.js
new file mode 100644
index 0000000000..099b2c8169
--- /dev/null
+++ b/client/src/hooks/useCancelableDebounce.test.js
@@ -0,0 +1,66 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import useCancelableDebounce from './useCancelableDebounce.js';
+
+// The mechanism behind #8187: a debounced state→URL mirror armed well before
+// a navigation must not be free to fire AFTER that navigation and clobber
+// it. React's own effect-cleanup-on-unmount is not sufficient — it runs
+// asynchronously relative to a synchronous `navigate()` call, leaving a
+// window under load. `cancel()` closes that window by letting a call site
+// drop the pending callback synchronously, in the same tick as the
+// navigation, rather than waiting on unmount.
+describe('useCancelableDebounce', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('fires the scheduled callback after the delay elapses', () => {
+ const fn = vi.fn();
+ const { result } = renderHook(() => useCancelableDebounce());
+ const [schedule] = result.current;
+
+ act(() => { schedule(fn, 300); });
+ expect(fn).not.toHaveBeenCalled();
+
+ act(() => { vi.advanceTimersByTime(300); });
+ expect(fn).toHaveBeenCalledOnce();
+ });
+
+ it('never fires a callback cancelled before its delay elapses, even after the delay passes', () => {
+ const fn = vi.fn();
+ const { result } = renderHook(() => useCancelableDebounce());
+ const [schedule, cancel] = result.current;
+
+ act(() => { schedule(fn, 300); });
+ act(() => { cancel(); });
+ act(() => { vi.advanceTimersByTime(1000); });
+
+ expect(fn).not.toHaveBeenCalled();
+ });
+
+ it('replaces a still-pending call when scheduled again, running only the latest', () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ const { result } = renderHook(() => useCancelableDebounce());
+ const [schedule] = result.current;
+
+ act(() => { schedule(first, 300); });
+ act(() => { vi.advanceTimersByTime(150); });
+ act(() => { schedule(second, 300); });
+ act(() => { vi.advanceTimersByTime(300); });
+
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledOnce();
+ });
+
+ it('cancels a pending call on unmount as a safety net for the ordinary case', () => {
+ const fn = vi.fn();
+ const { result, unmount } = renderHook(() => useCancelableDebounce());
+ const [schedule] = result.current;
+
+ act(() => { schedule(fn, 300); });
+ unmount();
+ act(() => { vi.advanceTimersByTime(1000); });
+
+ expect(fn).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/pages/Catalog.jsx b/client/src/pages/Catalog.jsx
index de8ad7c882..59fe2a78c1 100644
--- a/client/src/pages/Catalog.jsx
+++ b/client/src/pages/Catalog.jsx
@@ -39,6 +39,7 @@ import { catalogRefRoleForType } from '../lib/catalogTypes';
import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';
import useDrawerTab from '../hooks/useDrawerTab';
import useUrlParams from '../hooks/useUrlParams';
+import useCancelableDebounce from '../hooks/useCancelableDebounce';
// All type-derived UI (chips, badge color, inline-form primary content
// key/label, snippet fallback) flows from the merged registry (system +
@@ -132,14 +133,17 @@ export default function Catalog() {
// Debounce typing → q, and mirror q to the URL (replace, to avoid history
// spam). The fetch keys on the local `q`; the URL copy is for shareability.
+ // Cancelable at the same shared boundary MediaCollections uses (#8187):
+ // a page that later navigates away can drop a still-pending mirror write
+ // instead of letting it fire after the fact and clobber the new route.
+ const [scheduleQMirror] = useCancelableDebounce();
useEffect(() => {
- const t = setTimeout(() => {
+ scheduleQMirror(() => {
const trimmed = searchInput.trim();
setQ(trimmed);
updateParams({ q: trimmed }, { replace: true });
}, 300);
- return () => clearTimeout(t);
- }, [searchInput, updateParams]);
+ }, [searchInput, updateParams, scheduleQMirror]);
// Adopt an externally-changed `?q=` (Back/Forward, or an in-app link to a
// different query while this page stays mounted) so the box + fetch never lag
diff --git a/client/src/pages/MediaCollections.jsx b/client/src/pages/MediaCollections.jsx
index bc1ad87145..0067ed2a56 100644
--- a/client/src/pages/MediaCollections.jsx
+++ b/client/src/pages/MediaCollections.jsx
@@ -19,6 +19,7 @@ import MediaImage from '../components/MediaImage';
import SyncBadge from '../components/sync/SyncBadge';
import { useSyncIntegrity, syncBadgeStatus } from '../hooks/useSyncIntegrity';
import useUrlParams from '../hooks/useUrlParams';
+import useCancelableDebounce from '../hooks/useCancelableDebounce';
// Cap for the card title AFTER the auto-creator prefix moves to its badge.
// Middle-truncating at this length keeps the trailing date/qualifier — the only
@@ -100,6 +101,10 @@ export default function MediaCollections() {
// make the create read as broken. Navigating is the one feedback that
// holds regardless of the filter row, and an empty bucket exists to be
// filled anyway.
+ // Drop any pending query→URL mirror write first — it would otherwise be
+ // free to fire after this navigation and clobber the detail route back
+ // to the list route (#8187).
+ cancelQueryMirror();
navigate(`/media/collections/${encodeURIComponent(created.id)}`);
}
};
@@ -159,14 +164,20 @@ export default function MediaCollections() {
// history write + full route re-render per keystroke.
const [query, setQuery] = useState(() => searchParams.get('q') || '');
const [mirroredQuery, setMirroredQuery] = useState(() => searchParams.get('q') || '');
+ // Cancelable so a route change (opening the just-created collection) can
+ // drop a still-pending mirror write before it fires — otherwise the stale
+ // write can land after the navigation and clobber it back to the list
+ // route (#8187). React's own unmount cleanup isn't enough: it runs
+ // asynchronously relative to the `navigate()` call in `handleCreate`, and
+ // under load the gap can outlast the 300ms debounce.
+ const [scheduleQueryMirror, cancelQueryMirror] = useCancelableDebounce();
useEffect(() => {
- const t = setTimeout(() => {
+ scheduleQueryMirror(() => {
const trimmed = query.trim();
setMirroredQuery(trimmed);
updateParams({ q: trimmed }, { replace: true });
}, 300);
- return () => clearTimeout(t);
- }, [query, updateParams]);
+ }, [query, updateParams, scheduleQueryMirror]);
// Adopt an externally-changed `?q=` (Back/Forward, or a ⌘K/voice link while
// this page stays mounted). Our own debounced write lands `urlQuery ===
diff --git a/client/src/pages/MediaCollections.test.jsx b/client/src/pages/MediaCollections.test.jsx
index b1d64974ea..8d2962ff97 100644
--- a/client/src/pages/MediaCollections.test.jsx
+++ b/client/src/pages/MediaCollections.test.jsx
@@ -4,6 +4,18 @@ import userEvent from '@testing-library/user-event';
import { MemoryRouter, Routes, Route, useLocation, useNavigate } from 'react-router';
import { typeSettled } from '../test/settledInput';
+// ── Spy on the shared cancelable-debounce boundary ───────────────────────────
+// `schedule` still delegates to a REAL setTimeout so the existing
+// mirror-to-URL tests keep their real timing behavior; only `cancel` is a
+// spy, so a rendered test can assert MediaCollections actually cancels the
+// pending query→URL mirror before navigating to a newly-created collection
+// (#8187) — a stale mirror write left free to fire after that navigation can
+// land later and clobber the detail route back to the list route.
+const { cancelQueryMirrorSpy } = vi.hoisted(() => ({ cancelQueryMirrorSpy: vi.fn() }));
+vi.mock('../hooks/useCancelableDebounce', () => ({
+ default: () => [(fn, delay) => setTimeout(fn, delay), cancelQueryMirrorSpy],
+}));
+
// ── Mock API calls ───────────────────────────────────────────────────────────
vi.mock('../services/api', () => ({
listMediaCollections: vi.fn().mockResolvedValue([
@@ -88,6 +100,7 @@ function renderPage(entry = '/media/collections') {
describe('MediaCollections', () => {
beforeEach(() => {
vi.clearAllMocks();
+ cancelQueryMirrorSpy.mockClear();
// clearAllMocks resets calls, not implementations — restore the shared
// fixture so a test that emptied it can't leak into the next one.
mockUnsortedItems = [{ kind: 'image', ref: 'loose.png', addedAt: '2024-01-02' }];
@@ -227,6 +240,30 @@ describe('MediaCollections', () => {
await waitFor(() => expect(screen.getByTestId('pathname')).toHaveTextContent('/media/collections/col-4'));
});
+ it('cancels the pending query-mirror write before navigating to a new collection', async () => {
+ // #8187 regression: the 300ms query→URL mirror is armed on mount (and
+ // re-armed on every keystroke) and is still pending — not yet fired —
+ // when create resolves. React's own unmount cleanup for that timer runs
+ // asynchronously relative to the `navigate()` call in `handleCreate`
+ // (it waits for the router to re-render and commit), so under load the
+ // stale write can still land AFTER the navigation and clobber the
+ // detail route back to the list route. Creating a collection must
+ // cancel the pending mirror synchronously, before navigating, rather
+ // than relying on that unmount race to resolve in its favor.
+ const { createMediaCollection } = await import('../services/api');
+ createMediaCollection.mockResolvedValueOnce({ id: 'col-4', name: 'Fresh Bucket', items: [] });
+ const user = userEvent.setup();
+ // An active search keeps the mirror's debounce genuinely armed (a
+ // change from the mounted `?q=alpha`) at the moment create fires.
+ renderPage('/media/collections?q=alpha');
+ await waitFor(() => screen.getByText('Alpha'));
+ expect(cancelQueryMirrorSpy).not.toHaveBeenCalled();
+ await typeSettled(user, screen.getByLabelText('New collection name'), 'Fresh Bucket');
+ await user.click(screen.getByRole('button', { name: /create/i }));
+ await waitFor(() => expect(screen.getByTestId('pathname')).toHaveTextContent('/media/collections/col-4'));
+ expect(cancelQueryMirrorSpy).toHaveBeenCalled();
+ });
+
it('preserves sibling URL params when one filter changes', async () => {
const user = userEvent.setup();
renderPage('/media/collections?q=beta&sort=name&empty=1');