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: use a generation ref where an effect re-triggers itself (#7242)

[._.]/ Adam Eivy5ce778fee5fa
diff --git a/client/src/asyncEffectDisposalConventions.test.js b/client/src/asyncEffectDisposalConventions.test.js
index 9fa8c53dbb..6f8457dad0 100644
--- a/client/src/asyncEffectDisposalConventions.test.js
+++ b/client/src/asyncEffectDisposalConventions.test.js
@@ -50,8 +50,13 @@
* 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.
+ * - A flag must be declared, flipped, and read, but the read is not traced to
+ * the setter: a flag that gates the WRONG `set*` call still counts, and so
+ * does a flip written outside the returned cleanup.
+ * - One guarded request exempts the whole effect, so a second unguarded fetch
+ * added beside it is invisible. Pinning that needs per-statement dataflow,
+ * which a lexical scan cannot do; the allowlist rows are deliberately
+ * file-scoped for the same reason.
* - 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
@@ -233,19 +238,36 @@ const ABORT_CALL = /\.abort\s*\(/;
// 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) {
+/**
+ * A flag declared inside the effect, later assigned its opposite value, AND
+ * read at least once somewhere else.
+ *
+ * The read requirement is what stops the guard from being cosmetic. Declaring
+ * and flipping a flag that gates nothing —
+ * `let active = true; load(id).then(setValue); return () => { active = false; };`
+ * — keeps the exact race this rule exists to reject, and a declaration+flip
+ * check alone would pass it.
+ */
+function flipFlagEnd(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;
+ const end = match.index + match[0].length;
+ const rest = body.slice(end);
+ if (!flip.test(rest)) continue;
+ // Occurrences outside the declaration: the flip is one, so a flag that is
+ // never consulted has exactly one. Any more means it is read somewhere.
+ const uses = rest.match(new RegExp(`\\b${name}\\b`, 'g')) || [];
+ if (uses.length > 1) return end;
}
- return false;
+ return -1;
}
+const hasFlipFlag = (body) => flipFlagEnd(body) !== -1;
+
/** Whether `body` disposes of a superseded response by any sanctioned shape. */
export function hasDisposalGuard(body) {
return hasFlipFlag(body)
@@ -296,9 +318,70 @@ export function unguardedEffects(src) {
return found;
}
+/**
+ * The mirror-image mistake: a lifetime-scoped flip flag in an effect that
+ * SYNCHRONOUSLY writes a state value appearing in its own dependency array.
+ *
+ * useEffect(() => {
+ * let active = true;
+ * setLoadingOutput(true); // ← re-runs this effect immediately
+ * load(id).then((v) => { if (active) setValue(v); });
+ * return () => { active = false; }; // ← …whose cleanup fires here
+ * }, [id, loadingOutput]);
+ *
+ * The re-run's cleanup flips the flag before the response lands, so the update
+ * is silently dropped — the guard does not merely fail to help, it breaks the
+ * feature. That shipped four times while sweeping #7242 (it took AgentCard's
+ * transcript, the pipeline ledger/outline re-reads, and the post-download
+ * upscale re-probe offline) and only one of them had a test to catch it.
+ *
+ * The fix is a request-generation ref: the re-run early-returns without
+ * bumping, so the in-flight request stays current.
+ *
+ * Only a SYNCHRONOUS write counts. The same setter called inside `.then()` runs
+ * after the response has already been applied, so it cannot cancel itself.
+ */
+export function selfDisposingEffects(src) {
+ const blanked = blankLexical(src);
+ 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;
+ const { body, deps } = split;
+ const async = ASYNC_BOUNDARY.exec(body);
+ if (!async) continue;
+ const flagEnd = flipFlagEnd(body);
+ if (flagEnd === -1) continue;
+ const depNames = new Set(deps.split(',').map((d) => d.trim()).filter(Boolean));
+ for (const setter of body.matchAll(SETTER_CALL)) {
+ if (TIMER_SETTERS.has(setter[2])) continue;
+ const at = setter.index + setter[1].length;
+ // Only between the flag and the request. A setter ABOVE the declaration
+ // sits in an early-return branch that bails before the flag exists, so it
+ // can never be on the same path as the request it would cancel.
+ if (at < flagEnd || at > async.index) continue;
+ // `setLoadingOutput` → `loadingOutput`, the state value it writes.
+ const stateName = setter[2][3].toLowerCase() + setter[2].slice(4);
+ if (!depNames.has(stateName)) continue;
+ found.push({
+ line: blanked.slice(0, match.index).split('\n').length,
+ setter: setter[2],
+ dep: stateName,
+ });
+ break;
+ }
+ }
+ return found;
+}
+
const violationsIn = (file) => unguardedEffects(readFileSync(join(CLIENT_ROOT, file), 'utf8'))
.map((v) => `${file}:${v.line} deps=[${v.deps}] → ${v.setter}()`);
+const selfDisposingIn = (file) => selfDisposingEffects(readFileSync(join(CLIENT_ROOT, file), 'utf8'))
+ .map((v) => `${file}:${v.line} ${v.setter}() re-runs the effect via dep \`${v.dep}\``);
+
describe('identity-keyed async effects drop superseded responses', () => {
it('has no unguarded identity-keyed async effect outside the allowlist', () => {
const files = trackedSourceFiles(CLIENT_ROOT);
@@ -328,6 +411,26 @@ describe('identity-keyed async effects drop superseded responses', () => {
).toEqual([]);
});
+ it('has no lifetime flag in an effect that re-triggers itself', () => {
+ const files = trackedSourceFiles(CLIENT_ROOT);
+ expect(files.length).toBeGreaterThan(100);
+
+ const violations = files.flatMap(selfDisposingIn);
+
+ expect(
+ violations,
+ 'These effects hold a `let active`-style flag AND synchronously write a state '
+ + 'value that is in their own dependency array. The write re-runs the effect at '
+ + "once, and the re-run's cleanup flips the flag before the response lands — so "
+ + 'the update is silently dropped. The guard does not just fail to help here, it '
+ + 'breaks the feature.\n'
+ + 'Fix: use a request-generation ref instead — `const req = ++fooRef.current;` at '
+ + 'request time, `if (req === fooRef.current)` at apply time. The re-run '
+ + 'early-returns without bumping, so the in-flight request stays current.\n'
+ + `Offenders:\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', () => {
@@ -461,6 +564,18 @@ describe('identity-keyed async effects drop superseded responses', () => {
expect(unguardedEffects(src.replace('[mountedRef]', '[workId, mountedRef]'))).toHaveLength(1);
});
+ it('does not accept a flag that gates nothing', () => {
+ // Declared and flipped, but never consulted — the response is applied
+ // unconditionally, so the race is exactly the one being rejected.
+ expect(unguardedEffects(`
+ useEffect(() => {
+ let active = true;
+ load(id).then(setValue);
+ return () => { active = false; };
+ }, [id]);
+ `)).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.
@@ -505,6 +620,67 @@ describe('identity-keyed async effects drop superseded responses', () => {
`)).toEqual([]);
});
+ it('flags a lifetime flag beside a synchronous write to its own dep', () => {
+ const found = selfDisposingEffects(`
+ useEffect(() => {
+ let active = true;
+ setLoading(true);
+ load(id).then((v) => { if (active) setValue(v); });
+ return () => { active = false; };
+ }, [id, loading]);
+ `);
+ expect(found).toHaveLength(1);
+ expect(found[0].setter).toBe('setLoading');
+ expect(found[0].dep).toBe('loading');
+ });
+
+ it('does not flag a write that cannot re-trigger the effect first', () => {
+ const flagged = (src) => selfDisposingEffects(src).length;
+
+ // The setter's value is not a dependency, so the write re-runs nothing.
+ expect(flagged(`
+ useEffect(() => {
+ let active = true;
+ setLoading(true);
+ load(id).then((v) => { if (active) setValue(v); });
+ return () => { active = false; };
+ }, [id]);
+ `)).toBe(0);
+
+ // Written only inside `.then()` — the response has already been applied
+ // by the time the re-run's cleanup could fire, so it cannot self-cancel.
+ expect(flagged(`
+ useEffect(() => {
+ let active = true;
+ load(id).then((v) => { if (active) setConsents(v); });
+ return () => { active = false; };
+ }, [id, consents]);
+ `)).toBe(0);
+
+ // Written in an early-return branch ABOVE the flag: that path bails
+ // before the request exists, so it cannot cancel one.
+ expect(flagged(`
+ useEffect(() => {
+ if (!enabled) {
+ setOffset(0);
+ return;
+ }
+ let cancelled = false;
+ load(offset).then((v) => { if (!cancelled) setItems(v); });
+ return () => { cancelled = true; };
+ }, [enabled, offset]);
+ `)).toBe(0);
+
+ // A generation ref is the sanctioned fix, not a violation.
+ expect(flagged(`
+ useEffect(() => {
+ const req = ++genRef.current;
+ setLoading(true);
+ load(id).then((v) => { if (req === genRef.current) setValue(v); });
+ }, [id, loading]);
+ `)).toBe(0);
+ });
+
it('reports the line of the offending effect', () => {
const found = unguardedEffects([
'const a = 1;',
diff --git a/client/src/components/messages/InboxTab.jsx b/client/src/components/messages/InboxTab.jsx
index 8bb3c80443..7ec2bc8f3e 100644
--- a/client/src/components/messages/InboxTab.jsx
+++ b/client/src/components/messages/InboxTab.jsx
@@ -235,6 +235,9 @@ export default function InboxTab({ accounts }) {
// The URL is the source of truth for the open message. Resolve it from the
// current list when possible, then fetch it directly for a filtered-out or
// not-yet-loaded message so a copied URL still opens on a fresh load.
+ // Supersession token for the message-detail read below.
+ const detailRequestRef = useRef(0);
+
useEffect(() => {
if (!messageId) {
setLoadedMessage(null);
@@ -257,16 +260,20 @@ export default function InboxTab({ accounts }) {
return undefined;
}
- let cancelled = false;
+ // A request-generation ref, not a `let cancelled` flag: `loadedMessage` is
+ // in this effect's own dependency array, so clearing it below re-runs the
+ // effect at once and a lifetime-scoped flag would be flipped by its own
+ // cleanup before the detail arrived. The re-run bumps the token, so the
+ // newest read is the one that lands however the two resolve.
+ const req = ++detailRequestRef.current;
setLoadedMessage(null);
api.getMessageDetail(messageAccountId, messageId)
.then(message => {
- if (!cancelled) setLoadedMessage(message);
+ if (req === detailRequestRef.current) setLoadedMessage(message);
})
.catch(() => {
- if (!cancelled) closeMessage();
+ if (req === detailRequestRef.current) closeMessage();
});
- return () => { cancelled = true; };
}, [messageId, messageAccountId, messages, loading, loadedMessage, closeMessage]);
// Stream messages into the list as they arrive during sync
diff --git a/client/src/components/pipeline/SeriesReviewPanel.jsx b/client/src/components/pipeline/SeriesReviewPanel.jsx
index 43e9abcc4b..ed2f8c5e5d 100644
--- a/client/src/components/pipeline/SeriesReviewPanel.jsx
+++ b/client/src/components/pipeline/SeriesReviewPanel.jsx
@@ -169,7 +169,11 @@ export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpda
// 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;
+ const forSeries = seriesId;
+ // The counter alone advances only when another fix run ends, so it cannot
+ // invalidate a read whose series the user has since switched away from —
+ // `activeSeriesRef` (already kept for the verdict read) covers that axis.
+ const current = () => req === fixResultRequestRef.current && activeSeriesRef.current === forSeries;
setFixing(false);
if (fixLatest.type === 'complete') {
const fixed = fixLatest.fixed ?? 0;
diff --git a/client/src/pages/CreativeDirector.jsx b/client/src/pages/CreativeDirector.jsx
index 5f36bd595b..ec3d41b249 100644
--- a/client/src/pages/CreativeDirector.jsx
+++ b/client/src/pages/CreativeDirector.jsx
@@ -115,6 +115,8 @@ export default function CreativeDirector({ basePath = '/creative-director', brow
// Consume each remix handoff, then clear the history state so a
// refresh doesn't re-seed (mirrors Story Builder's prefill-consume pattern).
// Auto-open the create form so the seeded ingredient chips are visible.
+ // Supersession token for the remix-ingredient read below.
+ const remixRequestRef = useRef(0);
useEffect(() => {
if (browseOnly) {
if (searchParams.get('new') || location.state?.remix) {
@@ -122,23 +124,27 @@ 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 undefined;
+ return;
}
const ids = location.state?.remix?.ingredientIds;
- if (!Array.isArray(ids) || ids.length === 0) return undefined;
+ if (!Array.isArray(ids) || ids.length === 0) return;
const cleanIds = ids.filter(Boolean).slice(0, 50);
- if (cleanIds.length === 0) return undefined;
- let active = true;
+ if (cleanIds.length === 0) return;
+ // A request-generation ref, not a `let active` flag: the navigate() below
+ // clears the handoff state, which changes `location.key` — one of this
+ // effect's own deps — so a lifetime-scoped flag would be flipped by its own
+ // cleanup and cancel the read it just started, with no replacement fetch
+ // (the re-run sees no remix ids). Only a genuinely newer read supersedes.
+ const req = ++remixRequestRef.current;
setRemixIds(cleanIds);
if (!videoDraftOpen) setShowForm(true);
listCatalogIngredientsByIds(cleanIds, { silent: true })
- .then((res) => { if (active) setRemixIngredients(Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : [])); })
+ .then((res) => { if (req === remixRequestRef.current) 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/PipelineContinuityBible.jsx b/client/src/pages/PipelineContinuityBible.jsx
index c13d10bf2c..87a6907297 100644
--- a/client/src/pages/PipelineContinuityBible.jsx
+++ b/client/src/pages/PipelineContinuityBible.jsx
@@ -42,6 +42,11 @@ const FALLBACK_CATEGORIES = [
export default function PipelineContinuityBible() {
const { seriesId } = useParams();
+ // Live series identity for the ledger read below. Assigned during render so
+ // the comparison always sees the CURRENT series, not the one captured when
+ // the effect ran.
+ const seriesIdRef = useRef(seriesId);
+ seriesIdRef.current = seriesId;
const navigate = useNavigate();
const [series, setSeries] = useState(null);
const [ledger, setLedger] = useState(null);
@@ -92,7 +97,10 @@ export default function PipelineContinuityBible() {
activeRunIdRef.current = null;
if (latest.type === 'complete') {
const req = ++ledgerRequestRef.current;
- getContinuityBible(seriesId).then((l) => { if (req === ledgerRequestRef.current) setLedger(l); }).catch(() => {});
+ const forSeries = seriesId;
+ getContinuityBible(seriesId)
+ .then((l) => { if (req === ledgerRequestRef.current && seriesIdRef.current === forSeries) 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 fac3865471..f8b2677a46 100644
--- a/client/src/pages/PipelineIssue.jsx
+++ b/client/src/pages/PipelineIssue.jsx
@@ -6,7 +6,7 @@
* + teleplay) and streams progress via SSE.
*/
-import { useEffect, useState, useMemo } from 'react';
+import { useEffect, useRef, useState, useMemo } from 'react';
import { Link, useParams, useNavigate } from 'react-router';
import {
ArrowLeft, Sparkles, Loader2, X, Lightbulb, BookOpen, FileText, Film as FilmIcon,
@@ -87,6 +87,11 @@ const lockStageIdsForTab = (id) => {
export default function PipelineIssue() {
const { issueId, stage: stageParam } = useParams();
+ // Supersession token + live issue identity for the post-frame issue re-read.
+ // Assigned during render so the comparison always sees the CURRENT issue.
+ const issueRequestRef = useRef(0);
+ const issueIdRef = useRef(issueId);
+ issueIdRef.current = issueId;
const navigate = useNavigate();
// `comicPages` URL still routes (folded into the Comic Script tab below);
// we redirect those to `comicScript` since the merged editor lives there.
@@ -133,15 +138,22 @@ export default function PipelineIssue() {
// re-render with the freshly-persisted output. Cheaper than re-fetching on
// every frame.
useEffect(() => {
- if (!latest) return undefined;
- let active = true;
+ if (!latest) return;
if (latest.type === 'stage:complete' || latest.type === 'complete' || latest.type === 'error' || latest.type === 'canceled') {
- getPipelineIssue(issueId).then((i) => { if (active) setIssue(i); }).catch(() => null);
+ // A request-generation ref, not a `let active` flag: `latest` is in this
+ // effect's own dependency array and every progress frame changes it, so a
+ // lifetime-scoped flag would be flipped by the next frame's cleanup and
+ // drop this read — with no replacement, since an ordinary progress frame
+ // starts none. Superseded only by a newer read or a different issue.
+ const req = ++issueRequestRef.current;
+ const forIssue = issueId;
+ getPipelineIssue(issueId)
+ .then((i) => { if (req === issueRequestRef.current && issueIdRef.current === forIssue) 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 043d5b7ce5..777c1e8972 100644
--- a/client/src/pages/PipelineReverseOutline.jsx
+++ b/client/src/pages/PipelineReverseOutline.jsx
@@ -29,6 +29,11 @@ const RUN_ENDED = new Set(['complete', 'canceled', 'cancelled', 'error']);
export default function PipelineReverseOutline() {
const { seriesId } = useParams();
+ // Live series identity for the outline read below. Assigned during render so
+ // the comparison always sees the CURRENT series, not the one captured when
+ // the effect ran.
+ const seriesIdRef = useRef(seriesId);
+ seriesIdRef.current = seriesId;
const navigate = useNavigate();
const [series, setSeries] = useState(null);
const [outline, setOutline] = useState(null);
@@ -82,7 +87,10 @@ export default function PipelineReverseOutline() {
activeRunIdRef.current = null;
if (latest.type === 'complete') {
const req = ++outlineRequestRef.current;
- getReverseOutline(seriesId).then((o) => { if (req === outlineRequestRef.current) setOutline(o); }).catch(() => {});
+ const forSeries = seriesId;
+ getReverseOutline(seriesId)
+ .then((o) => { if (req === outlineRequestRef.current && seriesIdRef.current === forSeries) 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') {