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: read handler through a ref in useEscapeKey/useClickOutside to stop listener thrash (#1844)

[._.]/ Adam Eivy9ff570da80dd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index cb7bf8df96..146c097d16 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -23,6 +23,7 @@
## Fixed
+- **`useEscapeKey`/`useClickOutside` no longer thrash their global listener on every render** — both hooks kept the caller's `handler`/`onOutside` in the effect dep array, so the `window` keydown/mousedown listener was removed and re-added on every parent render while open. Since most call sites pass a fresh inline arrow (`() => setOpenCommentId(null)`), that meant a full detach+reattach on *every keystroke* in editors like `PipelineManuscriptEditor`/`AnnotatedManuscriptSection` and on every render of `SceneCard`/`WorkEditor`/`UniverseBuilder`. Both hooks now read the handler through a ref (the same pattern `useKeyboardShortcuts` already uses), so the listener subscribes only when `active` (and, for `useClickOutside`, `ref`) changes while still always invoking the latest handler. Behavior-preserving; covered by new hook tests. (#1844)
- **Blocking sync I/O removed from request/completion hot paths** — several syscalls ran synchronously on paths that serve live SSE/socket traffic, freezing the event loop for their duration. `checkForTaskCommit` (`agentRunTracking.js`) ran a `spawnSync('git', ['log', …])` on the completion path of every failed CoS run (100ms–2s on a large repo); it now uses the async, hard-timeout `bufferedSpawn`. `buildId.js` `statSync`'d `client/dist/index.html` on every SPA navigation; the freshness check is now throttled to at most once per second (the hot path between checks is a clock comparison, no syscall), so a rebuild re-syncs the served HTML with the on-disk chunks within the throttle window instead of paying a stat per navigation. The avatar (`routes/avatar.js`) and attachment (`routes/attachments.js`) routes swapped `existsSync`/`statSync` for async `fs.access`/`fs.stat` (via a new canonical `pathExists` helper in `fileUtils.js`), and uploads now call the idempotent `ensureDir` directly. Separately, the tombstone-prune paths for authors/tracks/creative-director projects (DB + file backends) wrapped their per-record `deleteSyncBaseHash` loops in `withBaseHashFlushBatch`, collapsing N `sync_base_hashes.json` rewrites into one. (#1828)
- **External API model/metadata fetches now time out instead of stalling callers indefinitely** — `_fetchGeminiModels` (Gemini model refresh in `aiToolkit/providers.js`) made a `fetch` with no `AbortSignal`, unlike every other provider model-fetch in that file, so a hung Google endpoint could block a model-refresh request forever; it now uses the same `AbortSignal.timeout(8000)`. `fetchCivitaiModel` and `searchCivitaiLoras` (`server/lib/civitai.js`) likewise passed no signal, so a Civitai hang stalled LoRA metadata/search callers; both now default to `AbortSignal.timeout(10000)` and accept a caller-provided `signal` override. (#1827)
- **Absent-vs-cleared merge bugs that silently restored values the user just cleared** — three spots conflated "field absent" with "field intentionally cleared to empty". A memory content edit now regenerates the summary and (file backend) reindexes BM25 via a shape-based gate (`typeof content === 'string'` / `Array.isArray(tags)`) instead of a falsy one that skipped both on an empty value and could crash `generateSummary` on a null/undefined content — fixed in both the file backend (`memory.js`) and the production Postgres backend (`memoryDB.js`) so they stay mirrored. (Empty memory content stays blocked at the API by `memoryUpdateSchema`'s `min(1)`, consistent with create.) A genuinely empty-body email refresh now overwrites the cached body instead of `||` collapsing back to the stale text (`messageSync.js`, both the thread-match and original-message paths). And clearing a CoS task's legacy direct field (`context`/`model`/`provider`/`app`) to `""` now persists as `""` rather than `|| undefined` deleting the key — `null` still drops it (`cosTaskStore.js`). (#1826)
diff --git a/client/src/hooks/useClickOutside.js b/client/src/hooks/useClickOutside.js
index 3f133fc869..3d151a644d 100644
--- a/client/src/hooks/useClickOutside.js
+++ b/client/src/hooks/useClickOutside.js
@@ -1,15 +1,21 @@
-import { useEffect } from 'react';
+import { useEffect, useRef } from 'react';
// Calls onOutside when a mousedown lands outside the ref'd element.
// Listener only attaches while `active` is true so closed menus don't pay
// the per-click cost.
+//
+// `onOutside` is read through a ref, so an inline arrow recreated every parent
+// render (the common call-site shape) doesn't tear down + re-add the global
+// mousedown listener on each render — only `active`/`ref` flip the subscription.
export default function useClickOutside(ref, active, onOutside) {
+ const onOutsideRef = useRef(onOutside);
+ onOutsideRef.current = onOutside;
useEffect(() => {
- if (!active) return;
+ if (!active) return undefined;
const onDown = (e) => {
- if (!ref.current?.contains(e.target)) onOutside();
+ if (!ref.current?.contains(e.target)) onOutsideRef.current();
};
window.addEventListener('mousedown', onDown);
return () => window.removeEventListener('mousedown', onDown);
- }, [active, ref, onOutside]);
+ }, [active, ref]);
}
diff --git a/client/src/hooks/useClickOutside.test.jsx b/client/src/hooks/useClickOutside.test.jsx
new file mode 100644
index 0000000000..89dbe0d5d4
--- /dev/null
+++ b/client/src/hooks/useClickOutside.test.jsx
@@ -0,0 +1,76 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { renderHook, fireEvent } from '@testing-library/react';
+import { useRef } from 'react';
+import useClickOutside from './useClickOutside';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.innerHTML = '';
+});
+
+// Mount an inside element attached to the ref and an outside sibling, so a
+// mousedown on either lands inside vs outside the ref'd element.
+function setupDom() {
+ const inside = document.createElement('div');
+ const outside = document.createElement('div');
+ document.body.append(inside, outside);
+ return { inside, outside };
+}
+
+describe('useClickOutside', () => {
+ it('fires onOutside for a mousedown outside the ref, not inside it', () => {
+ const { inside, outside } = setupDom();
+ const onOutside = vi.fn();
+ renderHook(() => {
+ const ref = useRef(inside);
+ useClickOutside(ref, true, onOutside);
+ });
+ fireEvent.mouseDown(inside);
+ expect(onOutside).not.toHaveBeenCalled();
+ fireEvent.mouseDown(outside);
+ expect(onOutside).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not bind while inactive', () => {
+ const { outside } = setupDom();
+ const onOutside = vi.fn();
+ renderHook(() => {
+ const ref = useRef(document.createElement('div'));
+ useClickOutside(ref, false, onOutside);
+ });
+ fireEvent.mouseDown(outside);
+ expect(onOutside).not.toHaveBeenCalled();
+ });
+
+ it('calls the latest onOutside without re-subscribing when the handler identity changes', () => {
+ const { inside, outside } = setupDom();
+ const first = vi.fn();
+ const second = vi.fn();
+ const addSpy = vi.spyOn(window, 'addEventListener');
+ const { rerender } = renderHook(
+ ({ fn }) => {
+ const ref = useRef(inside);
+ useClickOutside(ref, true, fn);
+ },
+ { initialProps: { fn: first } },
+ );
+ const subs = addSpy.mock.calls.filter(([type]) => type === 'mousedown').length;
+ rerender({ fn: second });
+ fireEvent.mouseDown(outside);
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledTimes(1);
+ expect(addSpy.mock.calls.filter(([type]) => type === 'mousedown').length).toBe(subs);
+ });
+
+ it('detaches the listener on unmount', () => {
+ const { outside } = setupDom();
+ const onOutside = vi.fn();
+ const { unmount } = renderHook(() => {
+ const ref = useRef(document.createElement('div'));
+ useClickOutside(ref, true, onOutside);
+ });
+ unmount();
+ fireEvent.mouseDown(outside);
+ expect(onOutside).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/hooks/useEscapeKey.js b/client/src/hooks/useEscapeKey.js
index 82206d2959..efcf5fe115 100644
--- a/client/src/hooks/useEscapeKey.js
+++ b/client/src/hooks/useEscapeKey.js
@@ -1,16 +1,22 @@
-import { useEffect } from 'react';
+import { useEffect, useRef } from 'react';
/**
* Call `handler` when Escape is pressed, but only while `active` is truthy.
* Listener is attached/removed with `active`, so a closed popover/card doesn't
* keep a global keydown handler around. Use for non-modal dismissables (the
* Modal component already owns Esc for true modals).
+ *
+ * `handler` is read through a ref, so an inline arrow recreated every parent
+ * render (the common call-site shape) doesn't tear down + re-add the global
+ * keydown listener on each render — only `active` flips the subscription.
*/
export default function useEscapeKey(active, handler) {
+ const handlerRef = useRef(handler);
+ handlerRef.current = handler;
useEffect(() => {
if (!active) return undefined;
- const onKey = (e) => { if (e.key === 'Escape') handler(); };
+ const onKey = (e) => { if (e.key === 'Escape') handlerRef.current(); };
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
- }, [active, handler]);
+ }, [active]);
}
diff --git a/client/src/hooks/useEscapeKey.test.jsx b/client/src/hooks/useEscapeKey.test.jsx
new file mode 100644
index 0000000000..0d07a2c1db
--- /dev/null
+++ b/client/src/hooks/useEscapeKey.test.jsx
@@ -0,0 +1,62 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { renderHook, fireEvent } from '@testing-library/react';
+import useEscapeKey from './useEscapeKey';
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('useEscapeKey', () => {
+ it('calls the handler on Escape while active', () => {
+ const handler = vi.fn();
+ renderHook(() => useEscapeKey(true, handler));
+ fireEvent.keyDown(window, { key: 'Escape' });
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores non-Escape keys', () => {
+ const handler = vi.fn();
+ renderHook(() => useEscapeKey(true, handler));
+ fireEvent.keyDown(window, { key: 'Enter' });
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it('does not bind while inactive', () => {
+ const handler = vi.fn();
+ renderHook(() => useEscapeKey(false, handler));
+ fireEvent.keyDown(window, { key: 'Escape' });
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it('calls the latest handler without re-subscribing when the handler identity changes', () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ const addSpy = vi.spyOn(window, 'addEventListener');
+ const { rerender } = renderHook(({ fn }) => useEscapeKey(true, fn), {
+ initialProps: { fn: first },
+ });
+ const subs = addSpy.mock.calls.filter(([type]) => type === 'keydown').length;
+ // A new inline arrow every render (the common call-site shape) must not thrash the listener.
+ rerender({ fn: second });
+ fireEvent.keyDown(window, { key: 'Escape' });
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledTimes(1);
+ expect(addSpy.mock.calls.filter(([type]) => type === 'keydown').length).toBe(subs);
+ });
+
+ it('detaches the listener on unmount', () => {
+ const handler = vi.fn();
+ const { unmount } = renderHook(() => useEscapeKey(true, handler));
+ unmount();
+ fireEvent.keyDown(window, { key: 'Escape' });
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it('detaches the listener when active flips to false', () => {
+ const handler = vi.fn();
+ const { rerender } = renderHook(({ active }) => useEscapeKey(active, handler), {
+ initialProps: { active: true },
+ });
+ rerender({ active: false });
+ fireEvent.keyDown(window, { key: 'Escape' });
+ expect(handler).not.toHaveBeenCalled();
+ });
+});