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: AbortController on effect fetches + lazy window guard for SpeechRecognition (#1845)

[._.]/ Adam Eivy26c6b9005174
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9888e7c0b5..923209f1c3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -25,6 +25,7 @@
## Fixed
+- **[issue-1845] Client fetch hygiene — effect fetches now abort on cleanup and `window` is read lazily** — `StagePromptModelPicker` fired two effect `fetch`es guarded only by a `cancelled` flag, so rapid `stageName` changes wasted in-flight round-trips; it now passes an `AbortController` `signal` to both and aborts on cleanup. `LocalSetupPanel`'s `/setup/check` fetch had no abort and its `setChecking(false)` `finally` could fire after unmount; it now aborts the prior/in-flight check (so a stale response can't clobber a newer one) and guards every state set behind a `mountedRef`. `VoiceCapture` read `window.SpeechRecognition` at module scope — a `ReferenceError` when the file is imported in an SSR/Node test context — now resolved lazily via a `useState` initializer that only runs in the browser. And `useArmedAction`'s `fire` is wrapped in `useCallback` so memoized children stay stable. (#1845)
- **`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)
diff --git a/client/src/components/brain/VoiceCapture.jsx b/client/src/components/brain/VoiceCapture.jsx
index d89692cbaf..b3d157b41d 100644
--- a/client/src/components/brain/VoiceCapture.jsx
+++ b/client/src/components/brain/VoiceCapture.jsx
@@ -2,12 +2,16 @@ import { useState, useRef, useCallback, useEffect } from 'react';
import { Mic, Square } from 'lucide-react';
import toast from '../ui/Toast';
-const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
-
export default function VoiceCapture({ onTranscript, disabled }) {
const [listening, setListening] = useState(false);
const [interimText, setInterimText] = useState('');
const recognitionRef = useRef(null);
+ // Resolve the Web Speech API lazily inside the component. Reading `window`
+ // at module scope throws a ReferenceError when this file is imported in an
+ // SSR/Node test context; the lazy initializer only runs in the browser.
+ const [SpeechRecognition] = useState(() => (
+ typeof window !== 'undefined' ? window.SpeechRecognition || window.webkitSpeechRecognition : undefined
+ ));
const supported = !!SpeechRecognition;
const stop = useCallback(() => {
@@ -76,7 +80,7 @@ export default function VoiceCapture({ onTranscript, disabled }) {
recognitionRef.current = recognition;
recognition.start();
setListening(true);
- }, [listening, supported, stop, onTranscript]);
+ }, [listening, supported, stop, onTranscript, SpeechRecognition]);
if (!supported) return null;
diff --git a/client/src/components/settings/LocalSetupPanel.jsx b/client/src/components/settings/LocalSetupPanel.jsx
index 7958f7cb1c..365f613e4a 100644
--- a/client/src/components/settings/LocalSetupPanel.jsx
+++ b/client/src/components/settings/LocalSetupPanel.jsx
@@ -24,6 +24,12 @@ export default function LocalSetupPanel({ pythonPath, onPythonPathChange, onPack
// directly so they take effect immediately.
const [draftPath, setDraftPath] = useState(pythonPath || '');
const commitTimerRef = useRef(null);
+ // Track mount + the latest in-flight /setup/check abort controller so a fetch
+ // that's still resolving after unmount (or superseded by a newer check)
+ // neither sets state on a dead component nor wastes the round-trip.
+ const mountedRef = useRef(true);
+ const checkAbortRef = useRef(null);
+ useEffect(() => () => { mountedRef.current = false; checkAbortRef.current?.abort(); }, []);
useEffect(() => { setDraftPath(pythonPath || ''); }, [pythonPath]);
useEffect(() => () => clearTimeout(commitTimerRef.current), []);
const commitDraft = (value) => {
@@ -38,17 +44,27 @@ export default function LocalSetupPanel({ pythonPath, onPythonPathChange, onPack
const refreshCheck = useCallback(async (path) => {
if (!path) { setCheck(null); return; }
+ // Abort any prior in-flight check so a stale response can't clobber a
+ // newer one, and so the fetch is dropped on unmount.
+ checkAbortRef.current?.abort();
+ const controller = new AbortController();
+ checkAbortRef.current = controller;
setChecking(true);
try {
- const res = await fetch(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(path)}`);
+ const res = await fetch(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(path)}`, { signal: controller.signal });
+ if (!mountedRef.current) return;
if (!res.ok) { setCheck(null); return; }
setCheck(await res.json());
- } catch {
+ } catch (err) {
+ // Aborted (unmount or superseded) — leave state alone.
+ if (err?.name === 'AbortError') return;
// Server down / offline — clear the check rather than getting stuck
// in a perpetual "Checking…" state.
- setCheck(null);
+ if (mountedRef.current) setCheck(null);
} finally {
- setChecking(false);
+ // Only settle the spinner for the current request; an aborted/superseded
+ // call must not flip a newer in-flight check's spinner off.
+ if (mountedRef.current && checkAbortRef.current === controller) setChecking(false);
}
}, []);
diff --git a/client/src/components/writers-room/StagePromptModelPicker.jsx b/client/src/components/writers-room/StagePromptModelPicker.jsx
index 523c0f1e75..91a022a07f 100644
--- a/client/src/components/writers-room/StagePromptModelPicker.jsx
+++ b/client/src/components/writers-room/StagePromptModelPicker.jsx
@@ -26,9 +26,11 @@ export default function StagePromptModelPicker({ stageName, label = 'Stage LLM',
useEffect(() => {
let cancelled = false;
+ const controller = new AbortController();
+ const { signal } = controller;
Promise.all([
- fetch(`/api/prompts/${encodeURIComponent(stageName)}`).then((r) => (r.ok ? r.json() : null)).catch(() => null),
- fetch('/api/providers').then((r) => (r.ok ? r.json() : null)).catch(() => null),
+ fetch(`/api/prompts/${encodeURIComponent(stageName)}`, { signal }).then((r) => (r.ok ? r.json() : null)).catch(() => null),
+ fetch('/api/providers', { signal }).then((r) => (r.ok ? r.json() : null)).catch(() => null),
]).then(([s, p]) => {
if (cancelled) return;
// Normalize stage.timeout through parseTimeoutMs so a legacy on-disk
@@ -43,7 +45,7 @@ export default function StagePromptModelPicker({ stageName, label = 'Stage LLM',
setActiveProviderId(p?.activeProvider || null);
setLoaded(true);
});
- return () => { cancelled = true; };
+ return () => { cancelled = true; controller.abort(); };
}, [stageName]);
const persist = async (next) => {
diff --git a/client/src/hooks/useArmedAction.js b/client/src/hooks/useArmedAction.js
index 680a80d940..8f7b4b14dd 100644
--- a/client/src/hooks/useArmedAction.js
+++ b/client/src/hooks/useArmedAction.js
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
/**
* Two-click-arm confirmation hook. Returns `[armed, fire]`:
@@ -18,7 +18,7 @@ export function useArmedAction(onConfirm, { timeoutMs = 5000 } = {}) {
if (timerRef.current) clearTimeout(timerRef.current);
}, []);
- const fire = (...args) => {
+ const fire = useCallback((...args) => {
if (!armed) {
setArmed(true);
if (timerRef.current) clearTimeout(timerRef.current);
@@ -29,7 +29,7 @@ export function useArmedAction(onConfirm, { timeoutMs = 5000 } = {}) {
timerRef.current = null;
setArmed(false);
onConfirm(...args);
- };
+ }, [armed, timeoutMs, onConfirm]);
return [armed, fire];
}