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: stop a slow fetch for the previous record landing on the current one (#7242)

[._.]/ Adam Eivyf85ece6c9f22
diff --git a/client/src/AGENTS.md b/client/src/AGENTS.md
index bb3fe9e35f..a0e11304d2 100644
--- a/client/src/AGENTS.md
+++ b/client/src/AGENTS.md
@@ -19,6 +19,7 @@ These apply to React/Vite client code. Universal constraints (functional program
- **Web Storage goes through `lib/safeStorage.js`** - `localStorage`/`sessionStorage` **throw** rather than returning null in Safari private browsing, with cookies disabled, in a sandboxed iframe, and at quota — and in several of those the object still exists, so `typeof sessionStorage === 'undefined'` is not a guard and neither is `?.` (it only covers a null base, not a throwing `getItem`). Use `safeReadStorage` / `safeWriteStorage` / `safeRemoveStorage` and their `Json` and `*Session` variants. This is not a lost-preference nit: a raw read in a **render body** is a render-phase exception that unmounts the whole route, and a raw write in an effect kills the flow mid-session (#5689). Enforced tree-wide by `client/src/storageConventions.test.js`.
- **Interval polling goes through `useAutoRefetch`** - a view that re-fetches on a timer uses `useAutoRefetch(fetchFn, intervalMs, { enabled, pollOnly: true })` (`hooks/useAutoRefetch.js`), never a hand-rolled `useEffect` + `setInterval`. The hook skips its tick while `document.visibilityState === 'hidden'` and re-fires once on the way back; a raw interval keeps hammering the server from a background tab, and PortOS is routinely left open on a second machine over the tailnet (#5697). Keep the site's existing gate as `enabled` rather than an early `return`, and pass `immediate: false` when another effect already owns the first fetch. Enforced tree-wide by `client/src/pollingConventions.test.js`, which allowlists the local timers that are not polls (clock ticks, frame advances, a bounded self-cancelling poll).
- **No local binding shadows a timer or `fetch`** - a `useState` pair, `useCallback`, or `const` named `setInterval` / `setTimeout` / `clearInterval` / `clearTimeout` / `requestAnimationFrame` / `cancelAnimationFrame` / `fetch` shadows that global for the whole component body, so a timer or fetch added to the same scope later silently calls the local instead — no throw, no lint error, just a state setter that stores a callback (#5728). Name the binding for what it holds (`intervalPreset`, `timeoutMinutes`, `loadRefs`). Enforced tree-wide by `client/src/globalShadowConventions.test.js`, which has no allowlist; idiomatic React state like `[open, setOpen]` / `[status, setStatus]` is deliberately out of scope because nothing here calls those globals bare.
+- **An async effect keyed to a switchable identity drops a superseded response** - an effect that fetches on a dependency and writes the answer into state needs a disposal guard: `let active = true;` at the top, every `set*` gated on it, `return () => { active = false; };`. Without it, switching the record faster than the request resolves renders the previous record's data under the current one — and it does not self-correct where the value is passed down as a controlled prop, so `WorkEditor` enriched one work's persisted storyboard images with another's characters and places (#7242, after #6996–#7000 were each fixed as a single site). **`useMounted()` does not cover this** — the component never unmounted, only its subject changed. Where the response must be matched against the newest request rather than merely dropped — notably when the effect writes a state value that is itself in its own dependency array, so a lifetime-scoped flag would be flipped by its own cleanup — bump and compare a generation ref instead (`IngredientPicker.jsx`). Enforced tree-wide by `client/src/asyncEffectDisposalConventions.test.js`, which allowlists the few deps that cannot select a different record (a drawer `open` flag, a once-only latch).
- **Reactive UI updates** - after mutations (delete, create, update), update local state directly instead of refetching the entire list from the server. Use `setState(prev => prev.filter(...))` or similar patterns for immediate feedback
## API errors and save gating
diff --git a/client/src/asyncEffectDisposalConventions.test.js b/client/src/asyncEffectDisposalConventions.test.js
new file mode 100644
index 0000000000..9fa8c53dbb
--- /dev/null
+++ b/client/src/asyncEffectDisposalConventions.test.js
@@ -0,0 +1,519 @@
+// @vitest-environment node
+
+/**
+ * Repo-wide guard: an async effect keyed to a switchable identity must drop a
+ * superseded response.
+ *
+ * The broken shape is an effect that fetches on a dependency and writes the
+ * answer straight into state:
+ *
+ * useEffect(() => {
+ * loadBible(work.id).then(setCharacters); // ← no disposal guard
+ * }, [work.id]);
+ *
+ * Switch work A → work B faster than the first request resolves and A's answer
+ * lands after B's, so B is displayed holding A's records. `useMounted()` does
+ * NOT cover this — the component never unmounted, only its subject changed —
+ * which is exactly why this guard exists alongside
+ * `hooks/mountedRefConventions.test.js` rather than inside it.
+ *
+ * It is not always a transient flicker. `WorkEditor` passed its bible lists
+ * down as controlled props, and `BibleSection` returns early rather than
+ * refetching when it receives them, so nothing re-read the server: the wrong
+ * characters and places stayed until the user manually re-ran an extraction,
+ * and in the meantime enriched the image-gen prompts behind persisted
+ * storyboard renders. Issues #6996, #6997, #6998, #6999 and #7000 were each
+ * filed and fixed as one site of this same class; #7242 swept the rest and
+ * added this test, because fixing them one at a time never stopped new ones
+ * from landing.
+ *
+ * ## The sanctioned fixes
+ *
+ * Three shapes count as a guard, matched on structure rather than on a name —
+ * the tree spells the flag `active`, `cancelled`, `canceled`, `live`, `current`
+ * and `ignore`, and a rule keyed to that list would be defeated by the next
+ * synonym:
+ *
+ * 1. **A local flip flag** — the dominant idiom, ~150 files:
+ * `let active = true;` … `if (active) setX(v);` … `return () => { active = false; };`
+ * 2. **A request-generation ref** — for an effect whose response must be
+ * matched against the LATEST request rather than merely dropped:
+ * `const gen = ++genRef.current;` … `if (gen !== genRef.current) return;`
+ * 3. **An `AbortController`** whose `.abort()` runs in the cleanup.
+ *
+ * ## What this guard CANNOT see
+ *
+ * It is a lexical scan, not a scope-aware AST pass. The boundary, so a green
+ * run is not trusted further than it earns:
+ *
+ * - It cannot tell a setter that truly runs in the async continuation from
+ * one that merely appears later in the source than the first `await` /
+ * `.then(`. A synchronous `setX()` written below an unrelated `.then()`
+ * reads as a violation; those sites are on the allowlist with that reason.
+ * - A flag declared in the effect and flipped anywhere later counts, even if
+ * the flip is not in the returned cleanup and the flag gates nothing.
+ * - The fetch/apply pair moved into a helper the effect calls is invisible,
+ * and so is a guard living in that helper.
+ * - `depsAllStable` resolves a `useRef` / `useMounted` handle only by a
+ * file-local `const` declaration, so a stable handle arriving as a prop
+ * still reads as switchable.
+ * - Regex literals are not lexed. A `(`, `)` or quote inside one skews the
+ * paren walk and can truncate the effect being read — which fails open for
+ * that effect. Strings, template literals and comments ARE blanked, and
+ * both directions are pinned by fixtures below.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { existsSync, readFileSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { trackedSourceFiles } from './test/trackedFiles.js';
+
+const CLIENT_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+/**
+ * Effects exempt from the rule, each with the reason. Adding a row is the
+ * moment to ask whether the dependency can really never select a different
+ * record — if it can, the fix is a guard, not a row here.
+ *
+ * Keyed by file: an effect's line number moves on every edit above it, so
+ * keying on one would make this list conflict on unrelated commits. The
+ * trade-off is that a file listed here is exempt for ALL of its effects, so
+ * rows are meant to stay rare.
+ */
+const ALLOWED = {
+ 'src/components/QuickBrainCapture.jsx':
+ 'seededRef latches on the first run, so the fetch fires at most once per mount',
+ 'src/components/brain/tabs/FeedsTab.jsx':
+ 'setLoading(false) is a load-finished latch, not a response written into state',
+ 'src/components/cos/tabs/MemoryTab.jsx':
+ 'embeddingConfigLoaded latches true on the first run, so the fetch fires at most once',
+ 'src/components/settings/AssessmentSweepPanel.jsx':
+ 'the setters run inside a socket handler that the cleanup severs with socket.off, '
+ + 'so none can fire for a superseded dependency',
+ 'src/components/sprites/ImportPanel.jsx':
+ 'deps are [open] only — a drawer preload with no record identity to switch',
+ 'src/components/voice/VoiceWidget.jsx':
+ 'deps are [enabled, navigate] — a session toggle, not a record identity',
+ 'src/pages/AIProviders.jsx':
+ 'deps are [fleetSetupOpen] only — a modal preload with no record identity to switch',
+ 'src/pages/Browser.jsx':
+ 'deps are [showConfig, config] — a panel toggle re-reading its own config',
+};
+
+// ---------------------------------------------------------------------------
+// Lexing
+// ---------------------------------------------------------------------------
+
+/**
+ * Blank out comments, string literals and the literal spans of template
+ * literals, preserving offsets and line breaks so reported line numbers stay
+ * true. A `(` inside a toast message would otherwise skew the paren walk below
+ * and truncate the effect it was reading; `${...}` spans are kept because they
+ * hold real code.
+ */
+export function blankLexical(src) {
+ let out = '';
+ let i = 0;
+ while (i < src.length) {
+ const c = src[i];
+ const next = src[i + 1];
+ if (c === '/' && next === '/') {
+ while (i < src.length && src[i] !== '\n') { out += ' '; i += 1; }
+ continue;
+ }
+ if (c === '/' && next === '*') {
+ out += ' '; i += 2;
+ while (i < src.length && !(src[i] === '*' && src[i + 1] === '/')) {
+ out += src[i] === '\n' ? '\n' : ' '; i += 1;
+ }
+ out += ' '; i += 2;
+ continue;
+ }
+ if (c === "'" || c === '"') {
+ out += ' '; i += 1;
+ while (i < src.length && src[i] !== c) {
+ if (src[i] === '\\') { out += ' '; i += 2; continue; }
+ out += src[i] === '\n' ? '\n' : ' '; i += 1;
+ }
+ out += ' '; i += 1;
+ continue;
+ }
+ if (c === '`') {
+ out += ' '; i += 1;
+ while (i < src.length && src[i] !== '`') {
+ if (src[i] === '\\') { out += ' '; i += 2; continue; }
+ if (src[i] === '$' && src[i + 1] === '{') {
+ out += ' '; i += 2;
+ let depth = 1;
+ while (i < src.length && depth > 0) {
+ if (src[i] === '{') depth += 1;
+ else if (src[i] === '}') {
+ depth -= 1;
+ if (depth === 0) { out += ' '; i += 1; break; }
+ }
+ out += src[i]; i += 1;
+ }
+ continue;
+ }
+ out += src[i] === '\n' ? '\n' : ' '; i += 1;
+ }
+ out += ' '; i += 1;
+ continue;
+ }
+ out += c; i += 1;
+ }
+ return out;
+}
+
+/**
+ * Text between the `(` at `open` and its matching `)`. A lazy `[^)]*` would
+ * stop at the first `)` inside the effect — every real effect has several — so
+ * the walk counts depth instead. Returns null on an unbalanced run, which
+ * reads as "nothing to inspect".
+ */
+function balancedArgs(src, open) {
+ let depth = 0;
+ for (let i = open; i < src.length; i += 1) {
+ if (src[i] === '(') depth += 1;
+ else if (src[i] === ')') {
+ depth -= 1;
+ if (depth === 0) return src.slice(open + 1, i);
+ }
+ }
+ return null;
+}
+
+/**
+ * Split a `useEffect(...)` argument list into its callback body and its
+ * dependency array, at the last top-level comma. Returns null when the call has
+ * no literal dep array — an effect that runs on every render is a different
+ * (and louder) bug that this rule does not own.
+ */
+export function splitDeps(args) {
+ let depth = 0;
+ for (let i = args.length - 1; i >= 0; i -= 1) {
+ const c = args[i];
+ if (c === ')' || c === ']' || c === '}') depth += 1;
+ else if (c === '(' || c === '[' || c === '{') depth -= 1;
+ else if (c === ',' && depth === 0) {
+ const tail = args.slice(i + 1).trim();
+ if (tail.startsWith('[') && tail.endsWith(']')) {
+ return { body: args.slice(0, i), deps: tail.slice(1, -1) };
+ }
+ return null;
+ }
+ }
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// Detection
+// ---------------------------------------------------------------------------
+
+const ASYNC_BOUNDARY = /\bawait\b|\.then\s*\(/;
+
+// `set[A-Z]` also spells the timer APIs; they set no React state.
+const TIMER_SETTERS = new Set(['setTimeout', 'setInterval', 'setImmediate']);
+
+// A bare `setFoo` reference. Deliberately not anchored to an open paren: the
+// tree writes state both as `setFoo(v)` and as `.then(setFoo)`, and the second
+// spelling is the more dangerous one — it applies the raw response. The leading
+// class keeps `obj.setFoo` out; a method on a fetched object is not this
+// component's state.
+const SETTER_CALL = /(^|[^.\w$])(set[A-Z][\w$]*)\b/g;
+
+const FLAG_DECL = /\b(?:let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(true|false)\b/g;
+const GENERATION_BUMP = /\+\+\s*[\w$.]+\.current|[\w$.]+\.current\s*\+=\s*1|[\w$.]+\.current\s*=\s*[\w$.]+\.current\s*\+\s*1/;
+const GENERATION_COMPARE = /[\w$.]+\.current\s*(?:!==|===|!=|==)|(?:!==|===|!=|==)\s*[\w$.]+\.current/;
+const ABORT_CONTROLLER = /new\s+AbortController\s*\(/;
+const ABORT_CALL = /\.abort\s*\(/;
+
+// `const x = useRef(...)` / `const x = useMounted()` — a handle whose identity
+// is fixed for the life of the component.
+const STABLE_DECL = /\bconst\s+([A-Za-z_$][\w$]*)\s*=\s*(?:useRef|useMounted)\s*\(/g;
+
+/** A flag declared inside the effect and later assigned its opposite value. */
+function hasFlipFlag(body) {
+ for (const match of body.matchAll(FLAG_DECL)) {
+ const opposite = match[2] === 'true' ? 'false' : 'true';
+ // Names may legally contain `$`, a regex anchor — escaping it keeps the
+ // pattern from silently becoming unmatchable and passing the offender.
+ const name = match[1].replace(/\$/g, '\\$');
+ const flip = new RegExp(`\\b${name}\\s*=\\s*${opposite}\\b`);
+ if (flip.test(body.slice(match.index + match[0].length))) return true;
+ }
+ return false;
+}
+
+/** Whether `body` disposes of a superseded response by any sanctioned shape. */
+export function hasDisposalGuard(body) {
+ return hasFlipFlag(body)
+ || (GENERATION_BUMP.test(body) && GENERATION_COMPARE.test(body))
+ || (ABORT_CONTROLLER.test(body) && ABORT_CALL.test(body));
+}
+
+/** The first `set*` call positioned after the effect's first async boundary. */
+function setterAfterAsync(body) {
+ const async = ASYNC_BOUNDARY.exec(body);
+ if (!async) return null;
+ for (const match of body.matchAll(SETTER_CALL)) {
+ if (TIMER_SETTERS.has(match[2])) continue;
+ if (match.index + match[1].length > async.index) return match[2];
+ }
+ return null;
+}
+
+/**
+ * Every dep is a ref handle, so the array can never select a different record —
+ * the effect is a mount-only load wearing a dep array to satisfy the lint rule.
+ */
+function depsAllStable(deps, stableNames) {
+ const entries = deps.split(',').map((d) => d.trim()).filter(Boolean);
+ return entries.length > 0 && entries.every((d) => stableNames.has(d));
+}
+
+/** Identity-keyed async effects in `src` that apply their response unguarded. */
+export function unguardedEffects(src) {
+ const blanked = blankLexical(src);
+ const stableNames = new Set([...blanked.matchAll(STABLE_DECL)].map((m) => m[1]));
+ const found = [];
+ for (const match of blanked.matchAll(/\buseEffect\s*\(/g)) {
+ const args = balancedArgs(blanked, match.index + match[0].length - 1);
+ if (args === null) continue;
+ const split = splitDeps(args);
+ if (!split || !split.deps.trim()) continue;
+ if (depsAllStable(split.deps, stableNames)) continue;
+ const setter = setterAfterAsync(split.body);
+ if (!setter) continue;
+ if (hasDisposalGuard(split.body)) continue;
+ found.push({
+ line: blanked.slice(0, match.index).split('\n').length,
+ deps: split.deps.replace(/\s+/g, ' ').trim(),
+ setter,
+ });
+ }
+ return found;
+}
+
+const violationsIn = (file) => unguardedEffects(readFileSync(join(CLIENT_ROOT, file), 'utf8'))
+ .map((v) => `${file}:${v.line} deps=[${v.deps}] → ${v.setter}()`);
+
+describe('identity-keyed async effects drop superseded responses', () => {
+ it('has no unguarded identity-keyed async effect outside the allowlist', () => {
+ const files = trackedSourceFiles(CLIENT_ROOT);
+ // A broken `git ls-files` (wrong cwd, detached checkout) would otherwise
+ // make this guard pass by scanning nothing at all.
+ expect(files.length).toBeGreaterThan(100);
+
+ const violations = files
+ .filter((file) => !(file in ALLOWED))
+ .flatMap(violationsIn);
+
+ expect(
+ violations,
+ 'These effects fetch on a dependency and write the answer into state with no '
+ + 'disposal guard. Change the dependency faster than the request resolves and the '
+ + "superseded record's data is rendered under the current one — and it does not "
+ + 'self-correct, because nothing refetches.\n'
+ + 'Fix: `let active = true;` at the top of the effect, gate every `set*` on it, and '
+ + '`return () => { active = false; };`. Match whichever spelling the file already '
+ + 'uses. Where the response must be matched against the newest request rather than '
+ + 'merely dropped, bump and compare a generation ref instead.\n'
+ + '`useMounted()` does NOT fix this — the component stays mounted; only its subject '
+ + 'changed.\n'
+ + 'If the dependency genuinely cannot select a different record (a drawer `open` '
+ + 'flag, a once-only latch), add the file to ALLOWED in this file with a one-line '
+ + `reason.\nOffenders:\n ${violations.join('\n ')}`,
+ ).toEqual([]);
+ });
+
+ // Burn-down: an allowlist entry that no longer needs to be there must go, or
+ // the list quietly becomes a list of files nobody has looked at in a year.
+ it('has no stale allowlist entry', () => {
+ const missing = Object.keys(ALLOWED).filter((file) => !existsSync(join(CLIENT_ROOT, file)));
+ expect(missing, `Allowlisted files that no longer exist:\n ${missing.join('\n ')}`).toEqual([]);
+
+ const noLongerNeeded = Object.keys(ALLOWED).filter((file) => violationsIn(file).length === 0);
+ expect(
+ noLongerNeeded,
+ 'These files are allowlisted but no longer trip the rule. Delete their rows from '
+ + `ALLOWED.\n ${noLongerNeeded.join('\n ')}`,
+ ).toEqual([]);
+ });
+
+ it('gives every allowlist entry a reason', () => {
+ const unexplained = Object.entries(ALLOWED)
+ .filter(([, reason]) => !reason || reason.trim().length < 20)
+ .map(([file]) => file);
+ expect(
+ unexplained,
+ `These rows need a one-line reason the dependency cannot switch:\n ${unexplained.join('\n ')}`,
+ ).toEqual([]);
+ });
+
+ // Guards the guard: a detector that stopped recognizing the broken shape would
+ // make the scan above vacuously green and let the bug class walk straight back in.
+ describe('detector', () => {
+ it('flags an identity-keyed fetch that applies its response unguarded', () => {
+ const found = unguardedEffects(`
+ useEffect(() => {
+ loadBible(work.id).then(setCharacters);
+ }, [work.id]);
+ `);
+ expect(found).toHaveLength(1);
+ expect(found[0].setter).toBe('setCharacters');
+ expect(found[0].deps).toBe('work.id');
+ });
+
+ it('flags an unguarded await, not just a .then', () => {
+ expect(unguardedEffects(`
+ useEffect(() => {
+ (async () => {
+ const rows = await listItems(subjectId);
+ setRows(rows);
+ })();
+ }, [subjectId]);
+ `)).toHaveLength(1);
+ });
+
+ it('accepts every sanctioned guard shape', () => {
+ // 1. The flip flag, in each spelling the tree uses.
+ for (const flag of ['active', 'cancelled', 'canceled', 'live', 'current', 'ignore']) {
+ expect(unguardedEffects(`
+ useEffect(() => {
+ let ${flag} = true;
+ load(id).then((v) => { if (${flag}) setValue(v); });
+ return () => { ${flag} = false; };
+ }, [id]);
+ `), `flag spelled \`${flag}\``).toEqual([]);
+ }
+
+ // A flag seeded false and raised in the cleanup is the same idiom inverted.
+ expect(unguardedEffects(`
+ useEffect(() => {
+ let stale = false;
+ load(id).then((v) => { if (!stale) setValue(v); });
+ return () => { stale = true; };
+ }, [id]);
+ `)).toEqual([]);
+
+ // 2. A request-generation ref.
+ expect(unguardedEffects(`
+ useEffect(() => {
+ const gen = ++genRef.current;
+ load(id).then((v) => { if (gen === genRef.current) setValue(v); });
+ }, [id]);
+ `)).toEqual([]);
+
+ // 3. An AbortController aborted in the cleanup.
+ expect(unguardedEffects(`
+ useEffect(() => {
+ const controller = new AbortController();
+ load(id, { signal: controller.signal }).then(setValue);
+ return () => controller.abort();
+ }, [id]);
+ `)).toEqual([]);
+ });
+
+ it('ignores effects that cannot strand a superseded response', () => {
+ // No dependency array at all — a different bug, not this rule's.
+ expect(unguardedEffects('useEffect(() => { load().then(setValue); });')).toEqual([]);
+
+ // Mount-only.
+ expect(unguardedEffects('useEffect(() => { load().then(setValue); }, []);')).toEqual([]);
+
+ // Nothing async.
+ expect(unguardedEffects('useEffect(() => { setValue(id); }, [id]);')).toEqual([]);
+
+ // Async, but nothing written into state.
+ expect(unguardedEffects('useEffect(() => { track(id).then(() => log(id)); }, [id]);')).toEqual([]);
+
+ // A setter that runs BEFORE the async boundary is not a stranded response.
+ expect(unguardedEffects(`
+ useEffect(() => {
+ setLoading(true);
+ void refresh(id);
+ }, [id]);
+ `)).toEqual([]);
+
+ // Timer APIs spell `set[A-Z]` but set no React state.
+ expect(unguardedEffects(`
+ useEffect(() => {
+ load(id).then(() => setTimeout(done, 10));
+ }, [id]);
+ `)).toEqual([]);
+
+ // A method on the fetched value is not this component's state.
+ expect(unguardedEffects('useEffect(() => { load(id).then((r) => r.setName(x)); }, [id]);')).toEqual([]);
+ });
+
+ it('treats a dep array of only ref handles as mount-only', () => {
+ const src = `
+ const mountedRef = useMounted();
+ useEffect(() => {
+ load().then((v) => { if (mountedRef.current) setValue(v); });
+ }, [mountedRef]);
+ `;
+ expect(unguardedEffects(src)).toEqual([]);
+
+ // …but one switchable dep alongside it still counts.
+ expect(unguardedEffects(src.replace('[mountedRef]', '[workId, mountedRef]'))).toHaveLength(1);
+ });
+
+ it('does not accept a mounted guard as an identity guard', () => {
+ // The component never unmounted — `mountedRef.current` is true the whole
+ // time — so this is the exact shape the rule exists to reject.
+ expect(unguardedEffects(`
+ useEffect(() => {
+ load(workId).then((v) => { if (mountedRef.current) setValue(v); });
+ }, [workId]);
+ `)).toHaveLength(1);
+ });
+
+ it('reads through parens and braces inside strings, templates and comments', () => {
+ // Each of these would truncate the effect (or fake a guard) without lexing.
+ expect(unguardedEffects(`
+ useEffect(() => {
+ toast.error('could not load :( ');
+ load(id).then(setValue);
+ }, [id]);
+ `)).toHaveLength(1);
+
+ expect(unguardedEffects(`
+ useEffect(() => {
+ const label = \`item (\${id}\`;
+ load(label).then(setValue);
+ }, [id]);
+ `)).toHaveLength(1);
+
+ // A guard written only inside a comment is not a guard.
+ expect(unguardedEffects(`
+ useEffect(() => {
+ // let active = true; return () => { active = false; };
+ load(id).then(setValue);
+ }, [id]);
+ `)).toHaveLength(1);
+
+ // …and a real guard is still seen when a comment sits next to it.
+ expect(unguardedEffects(`
+ useEffect(() => {
+ let active = true; // dropped if \`id\` changes first
+ load(id).then((v) => { if (active) setValue(v); });
+ return () => { active = false; };
+ }, [id]);
+ `)).toEqual([]);
+ });
+
+ it('reports the line of the offending effect', () => {
+ const found = unguardedEffects([
+ 'const a = 1;',
+ 'const b = 2;',
+ 'useEffect(() => {',
+ ' load(id).then(setValue);',
+ '}, [id]);',
+ ].join('\n'));
+ expect(found[0].line).toBe(3);
+ });
+ });
+});
diff --git a/client/src/components/agents/tabs/ToolsTab.jsx b/client/src/components/agents/tabs/ToolsTab.jsx
index e8808e8ade..7ada3f9e97 100644
--- a/client/src/components/agents/tabs/ToolsTab.jsx
+++ b/client/src/components/agents/tabs/ToolsTab.jsx
@@ -50,27 +50,37 @@ export default function ToolsTab({ agentId, agent }) {
// Auto-resolve the moltbook account for this agent
useEffect(() => {
+ let live = true;
api.getPlatformAccounts(agentId, 'moltbook').then(data => {
+ if (!live) return;
const active = data.filter(a => a.status === 'active');
if (active.length > 0) {
setSelectedAccountId(active[0].id);
setAccountName(active[0].credentials?.username || '');
}
setLoading(false);
- }).catch(err => { console.warn('⚠️ Failed to resolve moltbook account: ' + err.message); setLoading(false); });
+ }).catch(err => {
+ if (!live) return;
+ console.warn('⚠️ Failed to resolve moltbook account: ' + err.message);
+ setLoading(false);
+ });
+ return () => { live = false; };
}, [agentId]);
// Load rate limits + submolts when account resolves
useEffect(() => {
if (!selectedAccountId) {
setRateLimits(null);
- return;
+ return undefined;
}
- api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(err => console.warn('⚠️ Failed to refresh rate limits: ' + err.message));
+ let live = true;
+ api.getAgentRateLimits(selectedAccountId).then(data => { if (live) setRateLimits(data); }).catch(err => console.warn('⚠️ Failed to refresh rate limits: ' + err.message));
api.getAgentSubmolts(selectedAccountId).then(data => {
+ if (!live) return;
const list = data.submolts || data || [];
setSubmolts(Array.isArray(list) ? list : []);
}).catch(err => console.warn('⚠️ Failed to load submolts: ' + err.message));
+ return () => { live = false; };
}, [selectedAccountId]);
// Calculate cooldown end timestamps from rate limit data
diff --git a/client/src/components/agents/tabs/WorldTab.jsx b/client/src/components/agents/tabs/WorldTab.jsx
index 98b6094578..7029f9d834 100644
--- a/client/src/components/agents/tabs/WorldTab.jsx
+++ b/client/src/components/agents/tabs/WorldTab.jsx
@@ -143,14 +143,17 @@ export default function WorldTab({ agentId }) {
// Auto-resolve the moltworld account for this agent
useEffect(() => {
+ let live = true;
api.getPlatformAccounts(agentId, 'moltworld').then(data => {
+ if (!live) return;
const active = data.filter(a => a.status === 'active');
if (active.length > 0) {
setAccountId(active[0].id);
setAccountName(active[0].credentials?.username || '');
}
setLoading(false);
- }).catch(() => setLoading(false));
+ }).catch(() => { if (live) setLoading(false); });
+ return () => { live = false; };
}, [agentId]);
const fetchStatus = useCallback(async () => {
diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsx
index 16cc7880fd..8695d08fa0 100644
--- a/client/src/components/apps/EditAppDrawer.jsx
+++ b/client/src/components/apps/EditAppDrawer.jsx
@@ -137,9 +137,11 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
}, []);
useEffect(() => {
+ let cancelled = false;
api.getAppWorkTracker(app.id)
- .then(setWorkTrackerInfo)
- .catch(() => setWorkTrackerInfo(null));
+ .then(info => { if (!cancelled) setWorkTrackerInfo(info); })
+ .catch(() => { if (!cancelled) setWorkTrackerInfo(null); });
+ return () => { cancelled = true; };
}, [app.id]);
// Load the app's effective Layered Intelligence config + the CLI provider list
diff --git a/client/src/components/apps/tabs/CustomTasksSection.jsx b/client/src/components/apps/tabs/CustomTasksSection.jsx
index 9a31318b86..774179b1f5 100644
--- a/client/src/components/apps/tabs/CustomTasksSection.jsx
+++ b/client/src/components/apps/tabs/CustomTasksSection.jsx
@@ -190,12 +190,15 @@ export default function CustomTasksSection({ appId, appName, providerCatalog, ac
if (providerCatalog) {
setRawProviders(providerCatalog);
setActiveProviderId(inheritedActiveProviderId || '');
- return;
+ return undefined;
}
+ let active = true;
api.getProviders({ silent: true }).then(data => {
+ if (!active) return;
setRawProviders(data?.providers || []);
setActiveProviderId(data?.activeProvider || '');
}).catch(() => {});
+ return () => { active = false; };
}, [providerCatalog, inheritedActiveProviderId]);
const validate = (form) => {
diff --git a/client/src/components/apps/tabs/TasksTab.jsx b/client/src/components/apps/tabs/TasksTab.jsx
index 7436583a50..904681b9ee 100644
--- a/client/src/components/apps/tabs/TasksTab.jsx
+++ b/client/src/components/apps/tabs/TasksTab.jsx
@@ -30,12 +30,14 @@ export default function TasksTab({ appId }) {
}, [appId]);
useEffect(() => {
+ let active = true;
fetchAgents();
// Fetch providers and apps for the task add form
api.getProviders().catch(() => ({ providers: [] }))
- .then(d => setProviders(d.providers || []));
+ .then(d => { if (active) setProviders(d.providers || []); });
api.getApps().catch(() => [])
- .then(a => setApps((a || []).filter(app => app.id !== 'portos-autofixer')));
+ .then(a => { if (active) setApps((a || []).filter(app => app.id !== 'portos-autofixer')); });
+ return () => { active = false; };
}, [appId, fetchAgents]);
if (loading) {
diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsx
index ca7ccaf06a..ca2988627e 100644
--- a/client/src/components/brain/tabs/LinksTab.jsx
+++ b/client/src/components/brain/tabs/LinksTab.jsx
@@ -151,10 +151,12 @@ export default function LinksTab({ onRefresh }) {
}, []);
useEffect(() => {
+ let active = true;
fetchLinks();
api.getBrainBuckets({ silent: true })
- .then(data => setBuckets(data.buckets || []))
- .catch(() => setBuckets([]));
+ .then(data => { if (active) setBuckets(data.buckets || []); })
+ .catch(() => { if (active) setBuckets([]); });
+ return () => { active = false; };
}, [fetchLinks]);
// Poll ONLY the links whose clone is in flight, patching each fresh record
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index bdf3d18b73..bad8bc2dfb 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useMemo, useCallback } from 'react';
+import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { Link } from 'react-router';
import {
Cpu,
@@ -356,20 +356,30 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
}
};
+ // Supersession token for the full-output read below.
+ const outputRequestRef = useRef(0);
+
// Fetch full output when expanded for completed agents (skip for remote)
useEffect(() => {
- if (expanded && inactive && !fullOutput && !loadingOutput && !remote) {
- setLoadingOutput(true);
- api.getCosAgent(agent.id)
- .then(data => {
- setFullOutput(toTranscript(data));
- })
- .catch(() => {
- // Fall back to agent's stored output
- setFullOutput(toTranscript(agent));
- })
- .finally(() => setLoadingOutput(false));
- }
+ if (!(expanded && inactive && !fullOutput && !loadingOutput && !remote)) return;
+ // A request-generation ref, not a `let active` flag: `loadingOutput` is in this
+ // effect's own dependency array, so the write below re-runs the effect
+ // immediately and a lifetime-scoped flag would be flipped by its own
+ // cleanup before the response landed. The re-run early-returns without
+ // bumping, so the in-flight request stays current and only a genuinely
+ // newer one supersedes it.
+ const req = ++outputRequestRef.current;
+ const current = () => req === outputRequestRef.current;
+ setLoadingOutput(true);
+ api.getCosAgent(agent.id)
+ .then(data => {
+ if (current()) setFullOutput(toTranscript(data));
+ })
+ .catch(() => {
+ // Fall back to agent's stored output
+ if (current()) setFullOutput(toTranscript(agent));
+ })
+ .finally(() => { if (current()) setLoadingOutput(false); });
}, [expanded, inactive, agent.id, fullOutput, loadingOutput, remote, agent.output]);
const duration = agent.completedAt
diff --git a/client/src/components/cos/tabs/MemoryEditModal.jsx b/client/src/components/cos/tabs/MemoryEditModal.jsx
index c6ca333850..1abe23c03a 100644
--- a/client/src/components/cos/tabs/MemoryEditModal.jsx
+++ b/client/src/components/cos/tabs/MemoryEditModal.jsx
@@ -24,10 +24,11 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {
// Fetch full memory data if we only have index data
useEffect(() => {
+ let active = true;
const fetchFullMemory = async () => {
if (!memory.content && memory.id) {
const full = await api.getMemory(memory.id).catch(() => null);
- if (full) {
+ if (full && active) {
setFullMemory(full);
setFormData({
content: full.content || '',
@@ -43,6 +44,7 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {
}
};
fetchFullMemory();
+ return () => { active = false; };
}, [memory]);
const handleSubmit = async (e) => {
diff --git a/client/src/components/creative-director/VideoDraftDrawer.jsx b/client/src/components/creative-director/VideoDraftDrawer.jsx
index f0712ae137..5a6f63fa3f 100644
--- a/client/src/components/creative-director/VideoDraftDrawer.jsx
+++ b/client/src/components/creative-director/VideoDraftDrawer.jsx
@@ -27,7 +27,8 @@ export default function VideoDraftDrawer({ open, onClose, project, onSaved, cata
const [sourceQuery, setSourceQuery] = useState('');
const [saving, setSaving] = useState(false);
useEffect(() => {
- if (!open) return;
+ if (!open) return undefined;
+ let active = true;
setSourceId('');
setSourceQuery('');
const draft = project?.videoDraft;
@@ -37,11 +38,12 @@ export default function VideoDraftDrawer({ open, onClose, project, onSaved, cata
min: draft?.durationRange?.min || 30, max: draft?.durationRange?.max || 60,
reviewPolicy: draft?.reviewPolicy || 'review', transition: draft?.transition || 'cut', audioMode: draft?.audio?.mode || 'native', trackId: draft?.audio?.trackId || '', audioPrompt: draft?.audio?.prompt || '', audioProvider: draft?.audio?.providerId || '', audioModel: draft?.audio?.model || '',
sources: draft?.sources || catalogIngredientIds.map(id => ({ kind: 'catalog', id })) });
- listTracks({ silent: true }).then(data => setTracks(Array.isArray(data) ? data : data?.tracks || [])).catch(() => {});
- listMusicEngines({ silent: true }).then(data => setEngines(data?.engines || [])).catch(() => {});
+ listTracks({ silent: true }).then(data => { if (active) setTracks(Array.isArray(data) ? data : data?.tracks || []); }).catch(() => {});
+ listMusicEngines({ silent: true }).then(data => { if (active) setEngines(data?.engines || []); }).catch(() => {});
const rows = data => Array.isArray(data) ? data : data?.items || data?.series || data?.universes || [];
- Promise.all([listUniverseNames({ silent: true }), listPipelineSeriesNames({ silent: true }), listCatalogIngredients({ limit: 100, silent: true })]).then(([u, s, c]) => setSourceOptions({ universe: rows(u), series: rows(s), catalog: rows(c) })).catch(() => toast.error('Unable to load source choices. Close and reopen to retry.'));
- listVideoModels({ silent: true }).then(m => setModels(m || [])).catch(() => {});
+ Promise.all([listUniverseNames({ silent: true }), listPipelineSeriesNames({ silent: true }), listCatalogIngredients({ limit: 100, silent: true })]).then(([u, s, c]) => { if (active) setSourceOptions({ universe: rows(u), series: rows(s), catalog: rows(c) }); }).catch(() => { if (active) toast.error('Unable to load source choices. Close and reopen to retry.'); });
+ listVideoModels({ silent: true }).then(m => { if (active) setModels(m || []); }).catch(() => {});
+ return () => { active = false; };
}, [open, project?.id]);
const change = (key, value) => setForm(prev => ({ ...prev, [key]: value }));
const input = (key, label, options = {}) => <label htmlFor={`video-draft-${key}`} className="block text-sm">{label}<input id={`video-draft-${key}`} className={fieldClass} value={form[key] ?? ''} onChange={e => change(key, e.target.value)} {...options} /></label>;
diff --git a/client/src/components/loraTraining/CharacterLoraChip.jsx b/client/src/components/loraTraining/CharacterLoraChip.jsx
index 2c3f95542f..48c4d79b41 100644
--- a/client/src/components/loraTraining/CharacterLoraChip.jsx
+++ b/client/src/components/loraTraining/CharacterLoraChip.jsx
@@ -20,18 +20,25 @@ export default function CharacterLoraChip({ entryId, ingredientId, universeId, s
const [opening, setOpening] = useState(false);
useEffect(() => {
- if (!entryId && !ingredientId) return;
+ if (!entryId && !ingredientId) return undefined;
+ let active = true;
getCharacterLoras({ entryId, ingredientId }, { silent: true })
- .then((list) => setLoras(Array.isArray(list) ? list : []))
- .catch(err => { console.warn('⚠️ Failed to load character LoRAs: ' + err.message); setLoras([]); });
+ .then((list) => { if (active) setLoras(Array.isArray(list) ? list : []); })
+ .catch(err => {
+ console.warn('⚠️ Failed to load character LoRAs: ' + err.message);
+ if (active) setLoras([]);
+ });
+ return () => { active = false; };
}, [entryId, ingredientId]);
const canCreate = !!(universeId && entryId);
useEffect(() => {
- if (canCreate || (!entryId && !ingredientId)) return;
+ if (canCreate || (!entryId && !ingredientId)) return undefined;
+ let active = true;
listLoraDatasets(entryId ? { entryKind: 'characters', entryId } : { entryKind: 'characters', ingredientId })
- .then((list) => setExistingDataset(list?.[0] || null))
+ .then((list) => { if (active) setExistingDataset(list?.[0] || null); })
.catch(err => console.warn('⚠️ Failed to load LoRA datasets: ' + err.message));
+ return () => { active = false; };
}, [canCreate, entryId, ingredientId]);
const openDataset = async () => {
diff --git a/client/src/components/loraTraining/LiveSampleGallery.jsx b/client/src/components/loraTraining/LiveSampleGallery.jsx
index ff2014154f..c7135b1861 100644
--- a/client/src/components/loraTraining/LiveSampleGallery.jsx
+++ b/client/src/components/loraTraining/LiveSampleGallery.jsx
@@ -57,10 +57,12 @@ export default function LiveSampleGallery({ run, frames, progress, message }) {
// One-shot seed of every sample persisted so far (survives a mid-run reload).
useEffect(() => {
- if (!run?.id) return;
+ if (!run?.id) return undefined;
+ let active = true;
listLoraTrainingSamples(run.id)
- .then((res) => { if (mountedRef.current) setSeed(Array.isArray(res?.samples) ? res.samples : []); })
+ .then((res) => { if (active && mountedRef.current) setSeed(Array.isArray(res?.samples) ? res.samples : []); })
.catch(err => console.warn('⚠️ Failed to load training samples: ' + err.message));
+ return () => { active = false; };
}, [run?.id]);
// Merge seed + live frames into a step-sorted, dedup'd sample list.
diff --git a/client/src/components/loraTraining/UniverseCharacterPicker.jsx b/client/src/components/loraTraining/UniverseCharacterPicker.jsx
index 3a8aa94c46..2e63236773 100644
--- a/client/src/components/loraTraining/UniverseCharacterPicker.jsx
+++ b/client/src/components/loraTraining/UniverseCharacterPicker.jsx
@@ -39,12 +39,17 @@ export default function UniverseCharacterPicker({
}, []);
useEffect(() => {
- if (!universeId) { setUniverse(null); setEntries(null); return; }
+ if (!universeId) { setUniverse(null); setEntries(null); return undefined; }
+ let active = true;
setUniverse(null);
setEntries(null);
getUniverse(universeId, { silent: true })
- .then((u) => setUniverse(u || {}))
- .catch(err => { console.warn('⚠️ Failed to load universe: ' + err.message); setUniverse({}); });
+ .then((u) => { if (active) setUniverse(u || {}); })
+ .catch(err => {
+ console.warn('⚠️ Failed to load universe: ' + err.message);
+ if (active) setUniverse({});
+ });
+ return () => { active = false; };
}, [universeId]);
useEffect(() => {
diff --git a/client/src/components/meatspace/post/ElementsSong.jsx b/client/src/components/meatspace/post/ElementsSong.jsx
index 25a0656b68..1052b44a9e 100644
--- a/client/src/components/meatspace/post/ElementsSong.jsx
+++ b/client/src/components/meatspace/post/ElementsSong.jsx
@@ -66,16 +66,19 @@ export default function ElementsSong({ item: itemProp, onBack, loadItemOnMount,
const [mastery, setMastery] = useState(item?.mastery || { overallPct: 0, chunks: {}, elements: {} });
useEffect(() => {
- if (!itemProp && loadItemOnMount) {
- getMemoryItem('elements-song').then(data => {
- if (data) { setLoadedItem(data); setMastery(data.mastery || { overallPct: 0, chunks: {}, elements: {} }); }
- }).catch(err => console.warn('⚠️ Failed to load elements song: ' + err.message));
- }
+ if (itemProp || !loadItemOnMount) return undefined;
+ let active = true;
+ getMemoryItem('elements-song').then(data => {
+ if (data && active) { setLoadedItem(data); setMastery(data.mastery || { overallPct: 0, chunks: {}, elements: {} }); }
+ }).catch(err => console.warn('⚠️ Failed to load elements song: ' + err.message));
+ return () => { active = false; };
}, [itemProp, loadItemOnMount]);
useEffect(() => {
- if (!item?.id) return;
- getMemoryMastery(item.id).then(m => { if (m) setMastery(m); }).catch(err => console.warn('⚠️ Failed to load mastery: ' + err.message));
+ if (!item?.id) return undefined;
+ let active = true;
+ getMemoryMastery(item.id).then(m => { if (m && active) setMastery(m); }).catch(err => console.warn('⚠️ Failed to load mastery: ' + err.message));
+ return () => { active = false; };
}, [item?.id]);
function handlePracticeComplete(newMastery, continueDaily = false) {
diff --git a/client/src/components/meatspace/post/MemoryPractice.jsx b/client/src/components/meatspace/post/MemoryPractice.jsx
index 1fb1ea4cc0..1657419d89 100644
--- a/client/src/components/meatspace/post/MemoryPractice.jsx
+++ b/client/src/components/meatspace/post/MemoryPractice.jsx
@@ -170,11 +170,15 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, on
// Load chunk mastery when entering spaced mode
useEffect(() => {
- if (mode === 'spaced') {
- getChunkMastery(item.id).then(data => {
- setChunkMastery(data || []);
- }).catch(err => { console.warn('⚠️ Failed to load chunk mastery: ' + err.message); setChunkMastery([]); });
- }
+ if (mode !== 'spaced') return undefined;
+ let active = true;
+ getChunkMastery(item.id).then(data => {
+ if (active) setChunkMastery(data || []);
+ }).catch(err => {
+ console.warn('⚠️ Failed to load chunk mastery: ' + err.message);
+ if (active) setChunkMastery([]);
+ });
+ return () => { active = false; };
}, [mode, item.id]);
// Drive terminal transitions from an effect, never during render. The render
diff --git a/client/src/components/meatspace/tabs/AlcoholTab.jsx b/client/src/components/meatspace/tabs/AlcoholTab.jsx
index 987d42b163..e6fa8dbd49 100644
--- a/client/src/components/meatspace/tabs/AlcoholTab.jsx
+++ b/client/src/components/meatspace/tabs/AlcoholTab.jsx
@@ -112,9 +112,11 @@ export default function AlcoholTab() {
}, [chartView]);
useEffect(() => {
+ let active = true;
api.getAppleHealthCorrelation(correlationFrom, correlationTo)
- .then(setCorrelationData)
- .catch(() => setCorrelationData(null));
+ .then(data => { if (active) setCorrelationData(data); })
+ .catch(() => { if (active) setCorrelationData(null); });
+ return () => { active = false; };
}, [correlationFrom, correlationTo]);
const handleQuickAdd = async (drink) => {
diff --git a/client/src/components/meatspace/tabs/HealthTab.jsx b/client/src/components/meatspace/tabs/HealthTab.jsx
index 1eed105324..73a03372c7 100644
--- a/client/src/components/meatspace/tabs/HealthTab.jsx
+++ b/client/src/components/meatspace/tabs/HealthTab.jsx
@@ -65,9 +65,11 @@ export default function HealthTab() {
const to = new Date().toISOString().split('T')[0];
useEffect(() => {
+ let active = true;
api.getAppleHealthCorrelation(from, to)
- .then(setCorrelationData)
- .catch(() => setCorrelationData(null));
+ .then(data => { if (active) setCorrelationData(data); })
+ .catch(() => { if (active) setCorrelationData(null); });
+ return () => { active = false; };
}, [from, to]);
useEffect(() => {
diff --git a/client/src/components/meatspace/tabs/NicotineTab.jsx b/client/src/components/meatspace/tabs/NicotineTab.jsx
index 8ec3e6c45d..cce6531e61 100644
--- a/client/src/components/meatspace/tabs/NicotineTab.jsx
+++ b/client/src/components/meatspace/tabs/NicotineTab.jsx
@@ -76,9 +76,11 @@ export default function NicotineTab() {
}, [chartView]);
useEffect(() => {
+ let active = true;
api.getAppleHealthCorrelation(correlationFrom, correlationTo)
- .then(setCorrelationData)
- .catch(() => setCorrelationData(null));
+ .then(data => { if (active) setCorrelationData(data); })
+ .catch(() => { if (active) setCorrelationData(null); });
+ return () => { active = false; };
}, [correlationFrom, correlationTo]);
const handleQuickAdd = async (prod) => {
diff --git a/client/src/components/media/VideoUpscaleDrawer.jsx b/client/src/components/media/VideoUpscaleDrawer.jsx
index 1729a6228d..d6a08dad53 100644
--- a/client/src/components/media/VideoUpscaleDrawer.jsx
+++ b/client/src/components/media/VideoUpscaleDrawer.jsx
@@ -12,7 +12,7 @@
* opens the drawer and get the finished entry back via `onUpscaled` for their
* existing reactive local-state update (no refetch).
*/
-import { useState, useEffect, useCallback } from 'react';
+import { useState, useEffect, useCallback, useRef } from 'react';
import { Loader2 } from 'lucide-react';
import Drawer from '../Drawer';
import toast from '../ui/Toast';
@@ -98,12 +98,21 @@ export default function VideoUpscaleDrawer({ item, onClose, onUpscaled }) {
const downloadUrl = downloading ? upscaleAdapterDownloadUrl(adapterKey) : null;
const dl = useSseProgress(downloadUrl, { enabled: !!downloadUrl });
+ // Supersession token for the post-download plan re-probe below.
+ const planRequestRef = useRef(0);
useEffect(() => {
if (!downloading || !dl.latest) return;
+ // A request-generation ref, not a `let active` flag: `downloading` is in this
+ // effect's own dependency array, so the write below re-runs the effect
+ // immediately and a lifetime-scoped flag would be flipped by its own
+ // cleanup before the response landed. The re-run early-returns without
+ // bumping, so the in-flight request stays current and only a genuinely
+ // newer one supersedes it.
if (dl.latest.type === 'complete') {
+ const req = ++planRequestRef.current;
setDownloading(false);
// Re-probe so `adapter.cached` flips and the option re-enables.
- getUpscalePlan(itemId, 'ltx').then((res) => setPlan(res?.plan || null)).catch(() => {});
+ getUpscalePlan(itemId, 'ltx').then((res) => { if (req === planRequestRef.current) setPlan(res?.plan || null); }).catch(() => {});
} else if (dl.latest.type === 'error') {
setDownloading(false);
toast.error(dl.latest.message || 'Adapter download failed');
diff --git a/client/src/components/persona/PersonaMasterDetail.jsx b/client/src/components/persona/PersonaMasterDetail.jsx
index 830b31b2d8..b078c8ac3d 100644
--- a/client/src/components/persona/PersonaMasterDetail.jsx
+++ b/client/src/components/persona/PersonaMasterDetail.jsx
@@ -51,10 +51,12 @@ export default function PersonaMasterDetail({
};
useEffect(() => {
+ let active = true;
listRecords({ silent: true })
- .then((list) => setRecords(Array.isArray(list) ? list : []))
- .catch((err) => toast.error(err.message || `Failed to load ${plural.toLowerCase()}`))
- .finally(() => setLoading(false));
+ .then((list) => { if (active) setRecords(Array.isArray(list) ? list : []); })
+ .catch((err) => { if (active) toast.error(err.message || `Failed to load ${plural.toLowerCase()}`); })
+ .finally(() => { if (active) setLoading(false); });
+ return () => { active = false; };
}, [listRecords, plural]);
useEffect(() => {
diff --git a/client/src/components/pipeline/SeriesReviewPanel.jsx b/client/src/components/pipeline/SeriesReviewPanel.jsx
index 471dc39927..43e9abcc4b 100644
--- a/client/src/components/pipeline/SeriesReviewPanel.jsx
+++ b/client/src/components/pipeline/SeriesReviewPanel.jsx
@@ -86,6 +86,8 @@ export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpda
const reviewRunIdRef = useRef(null);
const fixRunIdRef = useRef(null);
+ // Supersession token for the post-fix series/issues re-read below.
+ const fixResultRequestRef = useRef(0);
// The series this panel currently represents — used to drop a late-resolving
// verdict response from a series the user has already switched away from.
const activeSeriesRef = useRef(seriesId);
@@ -160,14 +162,22 @@ export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpda
useEffect(() => {
if (!fixing || !fixLatest || !FIX_RUN_ENDED.has(fixLatest.type)) return;
if (fixRunIdRef.current && fixLatest.runId && fixLatest.runId !== fixRunIdRef.current) return;
+ // A request-generation ref, not a `let active` flag: `fixing` is in this
+ // effect's own dependency array, so the write below re-runs the effect
+ // immediately and a lifetime-scoped flag would be flipped by its own
+ // cleanup before the response landed. The re-run early-returns without
+ // bumping, so the in-flight request stays current and only a genuinely
+ // newer one supersedes it.
+ const req = ++fixResultRequestRef.current;
+ const current = () => req === fixResultRequestRef.current;
setFixing(false);
if (fixLatest.type === 'complete') {
const fixed = fixLatest.fixed ?? 0;
if (fixed > 0) {
// Fixes landed — the manuscript + findings changed, so the verdict is
// stale; clear it and prompt a re-review to confirm.
- getPipelineSeries(seriesId, { silent: true }).then((s) => { if (s) onSeriesUpdateRef.current?.(s); }).catch(() => null);
- listPipelineIssues(seriesId, { silent: true }).then((is) => onIssuesUpdateRef.current?.(Array.isArray(is) ? is : [])).catch(() => null);
+ getPipelineSeries(seriesId, { silent: true }).then((s) => { if (s && current()) onSeriesUpdateRef.current?.(s); }).catch(() => null);
+ listPipelineIssues(seriesId, { silent: true }).then((is) => { if (current()) onIssuesUpdateRef.current?.(Array.isArray(is) ? is : []); }).catch(() => null);
setReview(null);
setConfirmDismissed(false);
toast.success(`Fixed ${fixed} of ${fixLatest.total ?? 0} — re-review to confirm${fixLatest.budgetStopped ? ' (stopped: daily budget reached)' : ''}`);
diff --git a/client/src/components/privacy/OrgDrawer.jsx b/client/src/components/privacy/OrgDrawer.jsx
index e87617ef34..b61cb2d6c6 100644
--- a/client/src/components/privacy/OrgDrawer.jsx
+++ b/client/src/components/privacy/OrgDrawer.jsx
@@ -31,7 +31,8 @@ export default function OrgDrawer({ open, org, subjectId, vaultRecords, onClose,
const [socialAccounts, setSocialAccounts] = useState([]); // Digital Twin accounts for the cross-link picker
useEffect(() => {
- if (!open) return;
+ if (!open) return undefined;
+ let active = true;
setForm(org
? {
name: org.name ?? '',
@@ -49,14 +50,15 @@ export default function OrgDrawer({ open, org, subjectId, vaultRecords, onClose,
// Load existing holdings for an org being edited.
if (org?.id) {
getOrgHoldings(org.id, { silent: true })
- .then((h) => setSelected(new Set((h || []).map((x) => x.vaultRecordId))))
+ .then((h) => { if (active) setSelected(new Set((h || []).map((x) => x.vaultRecordId))); })
.catch(() => {});
}
// Load Digital Twin social accounts for the cross-link picker (#2147). Degrades
// to no picker options if the twin has none — never blocks org editing.
getSocialAccounts()
- .then((res) => setSocialAccounts(res?.accounts || []))
- .catch(() => setSocialAccounts([]));
+ .then((res) => { if (active) setSocialAccounts(res?.accounts || []); })
+ .catch(() => { if (active) setSocialAccounts([]); });
+ return () => { active = false; };
}, [open, org]);
const set = (k, v) => setForm((prev) => ({ ...prev, [k]: v }));
diff --git a/client/src/components/privacy/PrivacyOverviewTab.jsx b/client/src/components/privacy/PrivacyOverviewTab.jsx
index fef20c6b01..dbbf4dce7b 100644
--- a/client/src/components/privacy/PrivacyOverviewTab.jsx
+++ b/client/src/components/privacy/PrivacyOverviewTab.jsx
@@ -18,16 +18,19 @@ export default function PrivacyOverviewTab({ subjectId }) {
const [loading, setLoading] = useState(true);
useEffect(() => {
+ let active = true;
setLoading(true);
Promise.allSettled([
getPrivacyStatus({ subjectId }), getPrivacyOrgs({}, { subjectId }),
getPrivacyScanStatus({ subjectId }),
]).then(([s, o, b]) => {
+ if (!active) return;
setStatus(s.status === 'fulfilled' ? s.value : { keyConfigured: false, recordCounts: {} });
setOrgs(o.status === 'fulfilled' ? o.value : []);
setScanStatus(b.status === 'fulfilled' ? b.value : { caseCounts: {}, enabledBrokers: 0 });
setLoading(false);
});
+ return () => { active = false; };
}, [subjectId]);
// Cross-tab links carry the active subject so a drill-down never silently
diff --git a/client/src/components/privacy/SubjectsDrawer.jsx b/client/src/components/privacy/SubjectsDrawer.jsx
index 799c10d78e..e8b27eb2f6 100644
--- a/client/src/components/privacy/SubjectsDrawer.jsx
+++ b/client/src/components/privacy/SubjectsDrawer.jsx
@@ -31,10 +31,12 @@ function ConsentTrail({ subjectId }) {
const [open, setOpen] = useState(false);
useEffect(() => {
- if (!open || consents !== null) return;
+ if (!open || consents !== null) return undefined;
+ let active = true;
getPrivacySubjectConsents(subjectId, { silent: true })
- .then((rows) => setConsents(rows || []))
- .catch(() => setConsents('error'));
+ .then((rows) => { if (active) setConsents(rows || []); })
+ .catch(() => { if (active) setConsents('error'); });
+ return () => { active = false; };
}, [open, consents, subjectId]);
// Collapsing clears a failed read so re-expanding retries. Without this the
diff --git a/client/src/components/settings/ApiAccessTab.jsx b/client/src/components/settings/ApiAccessTab.jsx
index 0a00b240b3..76b15b8e7b 100644
--- a/client/src/components/settings/ApiAccessTab.jsx
+++ b/client/src/components/settings/ApiAccessTab.jsx
@@ -76,8 +76,10 @@ export function ApiAccessTab() {
}, []);
useEffect(() => {
+ let active = true;
getSettings({ silent: true })
.then((s) => {
+ if (!active) return;
setAccess(s?.apiAccess || {});
setAgentContext({
...DEFAULT_AGENT_CONTEXT,
@@ -86,10 +88,11 @@ export function ApiAccessTab() {
actions: { ...DEFAULT_AGENT_CONTEXT.actions, ...(s?.agentContext?.actions || {}) },
});
})
- .catch(() => toast.error('Failed to load API access settings'))
- .finally(() => setLoading(false));
+ .catch(() => { if (active) toast.error('Failed to load API access settings'); })
+ .finally(() => { if (active) setLoading(false); });
loadApiCards();
loadSpec();
+ return () => { active = false; };
}, [loadApiCards, loadSpec]);
const entryFor = (id) => ({ ...DEFAULT_ACCESS, ...(access[id] || {}) });
diff --git a/client/src/components/settings/VoiceTab.jsx b/client/src/components/settings/VoiceTab.jsx
index 9e14c4f7f4..cc98d86add 100644
--- a/client/src/components/settings/VoiceTab.jsx
+++ b/client/src/components/settings/VoiceTab.jsx
@@ -143,10 +143,12 @@ export function VoiceTab() {
// Refetch the voice catalog whenever the user flips TTS engine so the picker
// reflects the selected engine's voices (without requiring a save first).
useEffect(() => {
- if (!currentEngine) return;
+ if (!currentEngine) return undefined;
+ let active = true;
listVoices(currentEngine)
- .then((v) => setVoiceList(v))
- .catch(() => setVoiceList({ engine: currentEngine, voices: [] }));
+ .then((v) => { if (active) setVoiceList(v); })
+ .catch(() => { if (active) setVoiceList({ engine: currentEngine, voices: [] }); });
+ return () => { active = false; };
}, [currentEngine]);
// Functional setState form so sequential patch() calls in one event handler
diff --git a/client/src/components/writers-room/BibleSection.jsx b/client/src/components/writers-room/BibleSection.jsx
index 1ff7c4a321..ffd52b9f60 100644
--- a/client/src/components/writers-room/BibleSection.jsx
+++ b/client/src/components/writers-room/BibleSection.jsx
@@ -70,13 +70,18 @@ export default function BibleSection({
const mountedRef = useMounted();
useEffect(() => {
- if (itemsProp) return;
- if (!workId) return;
+ if (itemsProp) return undefined;
+ if (!workId) return undefined;
+ // `active` is the WORK-switch guard and `mountedRef` the unmount one; they
+ // are not interchangeable. The component stays mounted across a work swap,
+ // so only `active` keeps the previous work's bible out of this one.
+ let active = true;
setLoading(true);
config.api.list(workId)
- .then((list) => { if (mountedRef.current) setInternalItems(list); })
- .catch(() => { if (mountedRef.current) setInternalItems([]); })
- .finally(() => { if (mountedRef.current) setLoading(false); });
+ .then((list) => { if (active && mountedRef.current) setInternalItems(list); })
+ .catch(() => { if (active && mountedRef.current) setInternalItems([]); })
+ .finally(() => { if (active && mountedRef.current) setLoading(false); });
+ return () => { active = false; };
}, [workId, itemsProp, mountedRef]);
// Internal state uses a functional updater so back-to-back saves (the add
diff --git a/client/src/components/writers-room/PolishPanel.jsx b/client/src/components/writers-room/PolishPanel.jsx
index acc7e41004..e83e695b06 100644
--- a/client/src/components/writers-room/PolishPanel.jsx
+++ b/client/src/components/writers-room/PolishPanel.jsx
@@ -52,12 +52,14 @@ export default function PolishPanel({ work, dirty, onBodyChanged }) {
// On mount / work switch: reset stream state and load existing snapshots. If a
// run is already active on the server (e.g. this panel was reopened), re-attach.
useEffect(() => {
+ let live = true;
setSseUrl(null);
setSnapshots([]);
refreshSnapshots();
getWritersRoomPolishStatus(work.id)
- .then((s) => { if (s?.active && mountedRef.current) setSseUrl(`/api/writers-room/works/${encodeURIComponent(work.id)}/polish/progress`); })
+ .then((s) => { if (s?.active && live && mountedRef.current) setSseUrl(`/api/writers-room/works/${encodeURIComponent(work.id)}/polish/progress`); })
.catch(() => {});
+ return () => { live = false; };
}, [work.id, refreshSnapshots, mountedRef]);
// When the stream closes on a terminal frame, refresh snapshots and pull the
diff --git a/client/src/components/writers-room/WorkEditor.bibleDisposal.test.jsx b/client/src/components/writers-room/WorkEditor.bibleDisposal.test.jsx
new file mode 100644
index 0000000000..cb75a83d46
--- /dev/null
+++ b/client/src/components/writers-room/WorkEditor.bibleDisposal.test.jsx
@@ -0,0 +1,168 @@
+/**
+ * Regression: a bible read for the PREVIOUS work must not land on the current one.
+ *
+ * `WorkEditor` is rendered without a `key` (`pages/WritersRoom.jsx`), so it
+ * stays mounted when the user switches works and its `[work.id]` bible effect
+ * merely re-fires. Before #7242 that effect had no disposal guard, so a slow
+ * read for work A resolved after work B was already on screen and overwrote
+ * `characters` / `places` / `objects` with A's records.
+ *
+ * It did not self-correct: `WorkEditor` hands those lists down as controlled
+ * props and `BibleSection` returns early rather than refetching when it gets
+ * them, so nothing re-read the server until the user manually re-ran an
+ * extraction. In the meantime `StoryboardPanel` — "Persisted across runs ·
+ * feeds image-gen prompts" — enriched work B's image prompts with work A's
+ * characters and places, and those renders were persisted.
+ *
+ * The assertion is therefore on what `StoryboardPanel` is handed, not on
+ * internal state: that prop is the path by which the wrong data reached
+ * generated output.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { act, render } from '@testing-library/react';
+import { createMemoryRouter, RouterProvider } from 'react-router';
+
+// Records the bible lists the panel is rendered with, so the test asserts on
+// what actually reaches image-prompt enrichment.
+const storyboardProps = [];
+vi.mock('./StoryboardPanel', () => ({
+ default: function StoryboardPanelStub(props) {
+ storyboardProps.push({ characters: props.characters, places: props.places, objects: props.objects });
+ return <div data-testid="storyboard-panel" />;
+ },
+ STORYBOARD_TAB: {
+ CHARACTERS: 'characters', WORLD: 'world', OBJECTS: 'objects',
+ SCENES: 'scenes', BOARDS: 'boards', CONFIG: 'config',
+ },
+ STORYBOARD_TAB_VALUES: ['characters', 'world', 'objects', 'scenes', 'boards', 'config'],
+}));
+
+// Socket.IO auto-connects on import (useImageGenQueue / LiveRenderPanel).
+vi.mock('../../services/socket', () => ({
+ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn(), connected: false },
+}));
+
+vi.mock('../../services/apiWritersRoom', async (importOriginal) => ({
+ ...(await importOriginal()),
+ listWritersRoomFolders: vi.fn(async () => []),
+ listWritersRoomWorks: vi.fn(async () => []),
+ getWritersRoomWork: vi.fn(),
+ saveWritersRoomDraft: vi.fn(),
+ listWritersRoomCharacters: vi.fn(async () => []),
+ listWritersRoomPlaces: vi.fn(async () => []),
+ listWritersRoomObjects: vi.fn(async () => []),
+}));
+
+vi.mock('../CatalogCastPanel', () => ({ default: () => <div>Catalog cast controls</div> }));
+vi.mock('./LibraryPane', () => ({ default: () => <div>Library controls</div> }));
+
+import WorkEditor from './WorkEditor';
+import {
+ listWritersRoomCharacters,
+ listWritersRoomPlaces,
+ listWritersRoomObjects,
+} from '../../services/apiWritersRoom';
+
+const workNamed = (id, title) => ({
+ id,
+ title,
+ status: 'drafting',
+ kind: 'novel',
+ activeDraftBody: `${title} opens.`,
+ activeDraftVersionId: `${id}-draft-1`,
+ drafts: [{ id: `${id}-draft-1`, label: 'v1', wordCount: 2 }],
+});
+
+const WORK_A = workNamed('wr-work-a', 'Work A');
+const WORK_B = workNamed('wr-work-b', 'Work B');
+
+const A_CHARACTERS = [{ id: 'char-a', name: 'Ada from Work A' }];
+const A_PLACES = [{ id: 'place-a', name: 'Harbour in Work A' }];
+const A_OBJECTS = [{ id: 'obj-a', name: 'Lantern from Work A' }];
+
+/**
+ * A deferred list reader: the first call (work A) hangs until released, every
+ * later call (work B) resolves empty straight away. That is the exact ordering
+ * the bug needs — A's response arriving after B is on screen.
+ */
+function deferredReader(lateValue) {
+ let release;
+ const pending = new Promise((resolve) => { release = resolve; });
+ let first = true;
+ const read = vi.fn(() => {
+ if (!first) return Promise.resolve([]);
+ first = false;
+ return pending;
+ });
+ return { read, release: () => release(lateValue) };
+}
+
+// A DATA router: WorkEditor's unsaved-changes guard uses `useBlocker`, which
+// throws under a plain <MemoryRouter> (#3995).
+const routerFor = (work) => createMemoryRouter(
+ [{ path: '/writers-room', element: <WorkEditor work={work} onChange={() => {}} /> }],
+ { initialEntries: ['/writers-room'] },
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ storyboardProps.length = 0;
+});
+
+describe('WorkEditor bible load disposal (#7242)', () => {
+ it('drops a bible response for the previous work', async () => {
+ const characters = deferredReader(A_CHARACTERS);
+ const places = deferredReader(A_PLACES);
+ const objects = deferredReader(A_OBJECTS);
+ listWritersRoomCharacters.mockImplementation(characters.read);
+ listWritersRoomPlaces.mockImplementation(places.read);
+ listWritersRoomObjects.mockImplementation(objects.read);
+
+ // Work A mounts; its bible read is in flight and has not resolved.
+ const view = render(<RouterProvider router={routerFor(WORK_A)} />);
+ await act(async () => {});
+ expect(listWritersRoomCharacters).toHaveBeenCalledWith(WORK_A.id);
+
+ // The user switches to work B before that read comes back. WorkEditor has
+ // no `key`, so this is a re-render of the SAME instance, not a remount.
+ view.rerender(<RouterProvider router={routerFor(WORK_B)} />);
+ await act(async () => {});
+ expect(listWritersRoomCharacters).toHaveBeenLastCalledWith(WORK_B.id);
+
+ // Now work A's answer lands.
+ characters.release();
+ places.release();
+ objects.release();
+ await act(async () => {});
+
+ const latest = storyboardProps.at(-1);
+ expect(latest.characters).toEqual([]);
+ expect(latest.places).toEqual([]);
+ expect(latest.objects).toEqual([]);
+
+ // Nothing work A owned may appear in ANY render after the switch — the
+ // storyboard reads these on every frame, so a single frame holding them is
+ // enough to enrich a prompt.
+ const afterSwitch = storyboardProps.slice(storyboardProps.indexOf(latest) - 1);
+ for (const frame of afterSwitch) {
+ expect(frame.characters).not.toContainEqual(A_CHARACTERS[0]);
+ expect(frame.places).not.toContainEqual(A_PLACES[0]);
+ expect(frame.objects).not.toContainEqual(A_OBJECTS[0]);
+ }
+ });
+
+ it('still applies the response for the work that is current', async () => {
+ listWritersRoomCharacters.mockResolvedValue(A_CHARACTERS);
+ listWritersRoomPlaces.mockResolvedValue(A_PLACES);
+ listWritersRoomObjects.mockResolvedValue(A_OBJECTS);
+
+ render(<RouterProvider router={routerFor(WORK_A)} />);
+ await act(async () => {});
+
+ const latest = storyboardProps.at(-1);
+ expect(latest.characters).toEqual(A_CHARACTERS);
+ expect(latest.places).toEqual(A_PLACES);
+ expect(latest.objects).toEqual(A_OBJECTS);
+ });
+});
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index cbbba907b5..52ef27d07e 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -272,16 +272,28 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
// The CharactersBible / PlacesBible drawers are the canonical editors;
// mirror their lists here so the storyboard's image-prompt enrichment picks
// up edits immediately.
+ //
+ // `active` is load-bearing, not hygiene. WorkEditor is rendered without a
+ // `key` (WritersRoom.jsx), so it stays mounted across a work swap and this
+ // effect merely re-fires. Without the guard, a slow bible read for work A
+ // lands after the swap and sticks: these lists are passed down as controlled
+ // props, and BibleSection returns early rather than refetching when it gets
+ // them, so nothing re-reads the server until the user re-runs an extraction.
+ // In the meantime StoryboardPanel enriches work B's image-gen prompts with
+ // work A's characters and places, and those renders are persisted.
useEffect(() => {
+ let active = true;
Promise.all([
listWritersRoomCharacters(work.id).catch(() => []),
listWritersRoomPlaces(work.id).catch(() => []),
listWritersRoomObjects(work.id).catch(() => []),
]).then(([chars, plcs, objs]) => {
+ if (!active) return;
setCharacters(chars || []);
setPlaces(plcs || []);
setObjects(objs || []);
});
+ return () => { active = false; };
}, [work.id]);
useEffect(() => { onDirtyChange?.(dirty); }, [dirty, onDirtyChange]);
diff --git a/client/src/hooks/useAgentFeedbackToast.jsx b/client/src/hooks/useAgentFeedbackToast.jsx
index 01a79702c6..cf7f9fca23 100644
--- a/client/src/hooks/useAgentFeedbackToast.jsx
+++ b/client/src/hooks/useAgentFeedbackToast.jsx
@@ -17,6 +17,8 @@ function AgentFeedbackToast({ t, agentData, onFeedback }) {
const [output, setOutput] = useState(agentData?.output || []);
const [loadingOutput, setLoadingOutput] = useState(false);
const dismissTimer = useRef(null);
+ // Supersession token for the agent-output read below.
+ const outputRequestRef = useRef(0);
const agentId = agentData?.id || agentData?.agentId;
const taskDesc = agentData?.metadata?.taskDescription || agentData?.taskId || 'Task';
@@ -37,13 +39,20 @@ function AgentFeedbackToast({ t, agentData, onFeedback }) {
// Fetch output on expand if not already loaded
useEffect(() => {
- if (expanded && output.length === 0 && !loadingOutput && agentId) {
- setLoadingOutput(true);
- api.getCosAgent(agentId)
- .then(data => setOutput(data?.output || []))
- .catch(err => console.warn('fetch agent output:', err?.message ?? String(err)))
- .finally(() => setLoadingOutput(false));
- }
+ if (!(expanded && output.length === 0 && !loadingOutput && agentId)) return;
+ // A request-generation ref, not a `let active` flag: `loadingOutput` is in this
+ // effect's own dependency array, so the write below re-runs the effect
+ // immediately and a lifetime-scoped flag would be flipped by its own
+ // cleanup before the response landed. The re-run early-returns without
+ // bumping, so the in-flight request stays current and only a genuinely
+ // newer one supersedes it.
+ const req = ++outputRequestRef.current;
+ const current = () => req === outputRequestRef.current;
+ setLoadingOutput(true);
+ api.getCosAgent(agentId)
+ .then(data => { if (current()) setOutput(data?.output || []); })
+ .catch(err => console.warn('fetch agent output:', err?.message ?? String(err)))
+ .finally(() => { if (current()) setLoadingOutput(false); });
}, [expanded, output.length, loadingOutput, agentId]);
return (
diff --git a/client/src/hooks/useRepoStudyConfig.js b/client/src/hooks/useRepoStudyConfig.js
index 161a71b19b..f8825c684b 100644
--- a/client/src/hooks/useRepoStudyConfig.js
+++ b/client/src/hooks/useRepoStudyConfig.js
@@ -43,8 +43,10 @@ export function useRepoStudyConfig({ enabled = true, resetKey = null, initialStu
}, [resetKey]);
useEffect(() => {
- if (!enabled || typeof api.getApps !== 'function') return;
+ if (!enabled || typeof api.getApps !== 'function') return undefined;
+ let active = true;
api.getApps({ silent: true }).then((apps) => {
+ if (!active) return;
const eligible = (Array.isArray(apps) ? apps : [])
.filter(app => app?.id && app.repoPath && !app.archived)
.sort((a, b) => (a.id === PORTOS_APP_ID ? -1 : b.id === PORTOS_APP_ID ? 1 : a.name.localeCompare(b.name)));
@@ -53,6 +55,7 @@ export function useRepoStudyConfig({ enabled = true, resetKey = null, initialStu
setTargetAppId(current => eligible.some(app => app.id === current) ? current : eligible[0].id);
}
}).catch(() => {});
+ return () => { active = false; };
}, [enabled]);
return {
diff --git a/client/src/hooks/useSyncSourceSettings.js b/client/src/hooks/useSyncSourceSettings.js
index e059c63ac9..306194fb72 100644
--- a/client/src/hooks/useSyncSourceSettings.js
+++ b/client/src/hooks/useSyncSourceSettings.js
@@ -13,11 +13,13 @@ export function useSyncSourceSettings({ domain, defaultInterval, getStatus }) {
const [status, setStatus] = useState(null);
useEffect(() => {
+ let active = true;
Promise.all([
getSettings({ silent: true }).catch(() => ({})),
getStatus({ silent: true }).catch(() => null),
])
.then(([settings, sourceStatus]) => {
+ if (!active) return;
const config = settings?.[domain] || {};
const nextEnabled = typeof config.enabled === 'boolean' ? config.enabled : false;
const nextInterval = Number.isFinite(config.intervalMinutes) ? config.intervalMinutes : defaultInterval;
@@ -27,7 +29,8 @@ export function useSyncSourceSettings({ domain, defaultInterval, getStatus }) {
setSavedInterval(nextInterval);
setStatus(sourceStatus);
})
- .finally(() => setLoading(false));
+ .finally(() => { if (active) setLoading(false); });
+ return () => { active = false; };
}, [defaultInterval, domain, getStatus]);
const dirty = enabled !== savedEnabled || Number(intervalMinutes) !== Number(savedInterval);
diff --git a/client/src/pages/CreativeDirector.jsx b/client/src/pages/CreativeDirector.jsx
index 908a960af7..5f36bd595b 100644
--- a/client/src/pages/CreativeDirector.jsx
+++ b/client/src/pages/CreativeDirector.jsx
@@ -99,14 +99,17 @@ export default function CreativeDirector({ basePath = '/creative-director', brow
}, []);
useEffect(() => {
+ let active = true;
fetchProjects();
listVideoModels().then((m) => {
+ if (!active) return;
setModels(m || []);
// Prefer the first non-deprecated model as the default so new projects
// don't start on a legacy backend.
const preferred = (m || []).find((entry) => !entry.deprecated) || (m || [])[0];
if (preferred && !form.modelId) setForm((f) => ({ ...f, modelId: preferred.id }));
}).catch(() => {});
+ return () => { active = false; };
}, [fetchProjects]);
// Consume each remix handoff, then clear the history state so a
@@ -119,21 +122,23 @@ export default function CreativeDirector({ basePath = '/creative-director', brow
if (!next.has('new')) next.set('new', 'video');
navigate({ pathname: '/creative-director', search: next.toString(), hash: location.hash }, { replace: true, state: location.state });
}
- return;
+ return undefined;
}
const ids = location.state?.remix?.ingredientIds;
- if (!Array.isArray(ids) || ids.length === 0) return;
+ if (!Array.isArray(ids) || ids.length === 0) return undefined;
const cleanIds = ids.filter(Boolean).slice(0, 50);
- if (cleanIds.length === 0) return;
+ if (cleanIds.length === 0) return undefined;
+ let active = true;
setRemixIds(cleanIds);
if (!videoDraftOpen) setShowForm(true);
listCatalogIngredientsByIds(cleanIds, { silent: true })
- .then((res) => setRemixIngredients(Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : [])))
+ .then((res) => { if (active) setRemixIngredients(Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : [])); })
.catch(() => {});
// Clear the handoff state so a refresh doesn't re-seed (ids already captured).
const nextSearch = new URLSearchParams(location.search);
if (videoDraftOpen) nextSearch.set('new', 'video');
navigate({ pathname: location.pathname, search: nextSearch.toString(), hash: location.hash }, { replace: true, state: {} });
+ return () => { active = false; };
}, [browseOnly, location.key]);
// Drop any pending remix handoff so abandoned ingredient ids can't leak into
diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsx
index 8efffc723a..9ab38b6246 100644
--- a/client/src/pages/FableLoomStory.jsx
+++ b/client/src/pages/FableLoomStory.jsx
@@ -98,9 +98,13 @@ export default function FableLoomStory({ view = 'graph' }) {
: undefined;
useEffect(() => {
+ let canceled = false;
setNotFound(false);
setMediaJobs({});
- getLoom(loomId).then(setLoom).catch(() => setNotFound(true));
+ getLoom(loomId)
+ .then((l) => { if (!canceled) setLoom(l); })
+ .catch(() => { if (!canceled) setNotFound(true); });
+ return () => { canceled = true; };
}, [loomId]);
const linkedSeriesId = loom?.seriesId || null;
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 55ee74a8d6..09902b1942 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -1515,15 +1515,16 @@ function InstancesContent() {
// are independent of peer state, and fetching them sequentially added
// ~100-500ms to first paint on machines where `tailscale status --json`
// is slow to respond.
+ let active = true;
Promise.all([
fetchData(),
- getTailnetInfo().then(setTailnetInfo).catch(() => setTailnetInfo(null)),
- getNetworkExposure({ silent: true }).then(setNetworkExposure).catch(() => setNetworkExposure(null)),
+ getTailnetInfo().then((info) => { if (active) setTailnetInfo(info); }).catch(() => { if (active) setTailnetInfo(null); }),
+ getNetworkExposure({ silent: true }).then((e) => { if (active) setNetworkExposure(e); }).catch(() => { if (active) setNetworkExposure(null); }),
// Stored results only — the audit itself never runs on page load.
getBrainParityReports({ silent: true })
- .then((data) => setParityReports(data?.reports ?? {}))
- .catch(() => setParityReports({}))
- ]).finally(() => setLoading(false));
+ .then((data) => { if (active) setParityReports(data?.reports ?? {}); })
+ .catch(() => { if (active) setParityReports({}); })
+ ]).finally(() => { if (active) setLoading(false); });
socket.emit('instances:subscribe');
const handlePeersUpdated = (updatedPeers) => {
@@ -1537,6 +1538,7 @@ function InstancesContent() {
// refetch all peers + syncStatus for a change that touches only one card.
return () => {
+ active = false;
socket.emit('instances:unsubscribe');
socket.off('instances:peers:updated', handlePeersUpdated);
};
diff --git a/client/src/pages/LoraDatasetDetail.jsx b/client/src/pages/LoraDatasetDetail.jsx
index cb8bed8a12..287e9f9d80 100644
--- a/client/src/pages/LoraDatasetDetail.jsx
+++ b/client/src/pages/LoraDatasetDetail.jsx
@@ -310,13 +310,16 @@ export default function LoraDatasetDetail({ recordId }) {
// Pull the live canon subject once for variation-axis options + sheet link.
useEffect(() => {
- if (!dataset?.character?.universeId) return;
+ if (!dataset?.character?.universeId) return undefined;
+ let cancelled = false;
getUniverse(dataset.character.universeId, { silent: true })
.then((u) => {
+ if (cancelled) return;
const entries = Array.isArray(u?.[subjectKind(dataset)]) ? u[subjectKind(dataset)] : [];
setSubject(entries.find((entry) => entry.id === dataset.character.entryId) || null);
})
.catch(() => {});
+ return () => { cancelled = true; };
}, [dataset?.character?.universeId, dataset?.character?.entryKind, dataset?.character?.entryId]);
// Object/place variation axes (Lighting/Settings) live as server-side
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index 335211cd6d..1e5847ea41 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -199,8 +199,10 @@ export default function Loras() {
}, []);
useEffect(() => {
+ let active = true;
refresh();
- getCivitaiAuth().then(setAuth).catch(() => {});
+ getCivitaiAuth().then((a) => { if (active) setAuth(a); }).catch(() => {});
+ return () => { active = false; };
}, [refresh]);
// Discovery is fetched the first time its view is opened, not on mount —
diff --git a/client/src/pages/MediaModels.jsx b/client/src/pages/MediaModels.jsx
index a780dca9c0..88fc8ffa1a 100644
--- a/client/src/pages/MediaModels.jsx
+++ b/client/src/pages/MediaModels.jsx
@@ -138,11 +138,13 @@ export default function MediaModels() {
useEffect(() => {
if (textEncoderDownloads.downloading) {
wasDownloadingTextEncoder.current = true;
- return;
+ return undefined;
}
- if (!wasDownloadingTextEncoder.current) return;
+ if (!wasDownloadingTextEncoder.current) return undefined;
wasDownloadingTextEncoder.current = false;
- listCachedModels({ silent: true }).then(setData).catch(() => {});
+ let active = true;
+ listCachedModels({ silent: true }).then((d) => { if (active) setData(d); }).catch(() => {});
+ return () => { active = false; };
}, [textEncoderDownloads.downloading]);
const handleDeleteModel = async (id) => {
diff --git a/client/src/pages/OpenClaw.jsx b/client/src/pages/OpenClaw.jsx
index ceb2f686d4..29e4d7a83f 100644
--- a/client/src/pages/OpenClaw.jsx
+++ b/client/src/pages/OpenClaw.jsx
@@ -276,9 +276,13 @@ export default function OpenClaw() {
loadRuntime();
if (!featureEnabled) {
setApps([]);
- return;
+ return undefined;
}
- coreApi.getApps().then(data => setApps((data || []).filter(app => !app.archived))).catch(() => setApps([]));
+ let active = true;
+ coreApi.getApps()
+ .then(data => { if (active) setApps((data || []).filter(app => !app.archived)); })
+ .catch(() => { if (active) setApps([]); });
+ return () => { active = false; };
}, [featureEnabled, loadRuntime]);
useEffect(() => {
diff --git a/client/src/pages/PipelineContinuityBible.jsx b/client/src/pages/PipelineContinuityBible.jsx
index 6dfee6980d..c13d10bf2c 100644
--- a/client/src/pages/PipelineContinuityBible.jsx
+++ b/client/src/pages/PipelineContinuityBible.jsx
@@ -49,6 +49,8 @@ export default function PipelineContinuityBible() {
const [active, setActive] = useState(false);
const [starting, setStarting] = useState(false);
const activeRunIdRef = useRef(null);
+ // Supersession token for the ledger re-read below.
+ const ledgerRequestRef = useRef(0);
// Load series + ledger, and re-attach to an in-flight run on (re)mount.
useEffect(() => {
@@ -80,10 +82,17 @@ export default function PipelineContinuityBible() {
useEffect(() => {
if (!active || !latest || !RUN_ENDED.has(latest.type)) return;
if (activeRunIdRef.current && latest.runId && latest.runId !== activeRunIdRef.current) return;
+ // A request-generation ref, not a `let active` flag: `active` is in this
+ // effect's own dependency array, so the write below re-runs the effect
+ // immediately and a lifetime-scoped flag would be flipped by its own
+ // cleanup before the response landed. The re-run early-returns without
+ // bumping, so the in-flight request stays current and only a genuinely
+ // newer one supersedes it.
setActive(false);
activeRunIdRef.current = null;
if (latest.type === 'complete') {
- getContinuityBible(seriesId).then((l) => setLedger(l)).catch(() => {});
+ const req = ++ledgerRequestRef.current;
+ getContinuityBible(seriesId).then((l) => { if (req === ledgerRequestRef.current) setLedger(l); }).catch(() => {});
if (latest.status === 'no-content') toast.warning('Nothing to build a ledger from — add canon or draft a manuscript first');
else toast.success(`Continuity bible ready — ${latest.factCount || 0} facts`);
} else if (latest.type === 'canceled') {
diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsx
index a56a687313..fac3865471 100644
--- a/client/src/pages/PipelineIssue.jsx
+++ b/client/src/pages/PipelineIssue.jsx
@@ -133,13 +133,15 @@ export default function PipelineIssue() {
// re-render with the freshly-persisted output. Cheaper than re-fetching on
// every frame.
useEffect(() => {
- if (!latest) return;
+ if (!latest) return undefined;
+ let active = true;
if (latest.type === 'stage:complete' || latest.type === 'complete' || latest.type === 'error' || latest.type === 'canceled') {
- getPipelineIssue(issueId).then(setIssue).catch(() => null);
+ getPipelineIssue(issueId).then((i) => { if (active) setIssue(i); }).catch(() => null);
}
if (latest.type === 'complete' || latest.type === 'canceled' || latest.type === 'error') {
setAutoRunActive(false);
}
+ return () => { active = false; };
}, [latest, issueId]);
const handleAutoRun = async (opts = {}) => {
diff --git a/client/src/pages/PipelineReverseOutline.jsx b/client/src/pages/PipelineReverseOutline.jsx
index 8234a68c85..043d5b7ce5 100644
--- a/client/src/pages/PipelineReverseOutline.jsx
+++ b/client/src/pages/PipelineReverseOutline.jsx
@@ -39,6 +39,8 @@ export default function PipelineReverseOutline() {
// panel is shareable, bookmarkable, and survives a reload.
const [searchParams, updateParams] = useUrlParams();
const activeRunIdRef = useRef(null);
+ // Supersession token for the outline re-read below.
+ const outlineRequestRef = useRef(0);
// Load series + outline, and re-attach to an in-flight run on (re)mount.
useEffect(() => {
@@ -70,10 +72,17 @@ export default function PipelineReverseOutline() {
useEffect(() => {
if (!active || !latest || !RUN_ENDED.has(latest.type)) return;
if (activeRunIdRef.current && latest.runId && latest.runId !== activeRunIdRef.current) return;
+ // A request-generation ref, not a `let active` flag: `active` is in this
+ // effect's own dependency array, so the write below re-runs the effect
+ // immediately and a lifetime-scoped flag would be flipped by its own
+ // cleanup before the response landed. The re-run early-returns without
+ // bumping, so the in-flight request stays current and only a genuinely
+ // newer one supersedes it.
setActive(false);
activeRunIdRef.current = null;
if (latest.type === 'complete') {
- getReverseOutline(seriesId).then((o) => setOutline(o)).catch(() => {});
+ const req = ++outlineRequestRef.current;
+ getReverseOutline(seriesId).then((o) => { if (req === outlineRequestRef.current) setOutline(o); }).catch(() => {});
if (latest.status === 'no-content') toast.warning('Nothing drafted yet — write or import a manuscript first');
else toast.success(`Reverse outline ready — ${latest.sceneCount || 0} scenes`);
} else if (latest.type === 'canceled') {
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index 0881bf3adb..728907fe1e 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -1110,11 +1110,13 @@ function StoryBuilderDetail({ storyId, stepParam }) {
// Load the step manifest first; gate the loading spinner on BOTH it and the
// session so the detail view never renders with an empty step rail.
useEffect(() => {
+ let active = true;
setLoading(true);
getStoryBuilderSteps({ silent: true })
- .then((r) => setSteps(r.steps || []))
+ .then((r) => { if (active) setSteps(r.steps || []); })
.catch(() => {})
- .finally(reload);
+ .finally(() => { if (active) reload(); });
+ return () => { active = false; };
}, [reload]);
const stepIds = steps.map((s) => s.id);
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 424dde8218..9efa6ec357 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -148,12 +148,15 @@ export default function VideoGen() {
};
const [episodeImportScenes, setEpisodeImportScenes] = useState(null);
useEffect(() => {
- if (!episodeOpen || !episodeLoomId || !episodeEpisodeId) return;
+ if (!episodeOpen || !episodeLoomId || !episodeEpisodeId) return undefined;
+ let active = true;
getLoom(episodeLoomId, { silent: true }).then((loom) => {
+ if (!active) return;
const episode = loom?.episodes?.find((e) => e.id === episodeEpisodeId);
const draftScenes = loomEpisodeToDraftScenes(episode, { format: loom?.format });
if (draftScenes.length) setEpisodeImportScenes(draftScenes);
}).catch(() => {});
+ return () => { active = false; };
// Only re-run when a fresh loom/episode is targeted, not on every render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [episodeOpen, episodeLoomId, episodeEpisodeId]);