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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: replace 13 hand-rolled mounted-ref guards with useMounted (#3266)
[._.]/ Adam Eivy000dce0ba73d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex beb598c3d4..633160ed2c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -21,6 +21,7 @@## Internal- **[issue-3264] Fixed a development-mode freeze that left panels loading and buttons stuck after one click.** Under `npm run dev`, a mount guard used across fourteen components and hooks was never re-armed after React StrictMode double-mounts a component, so anything gated on it silently stopped updating — the music generator panel sat on "Loading generators…" forever, and every button backed by the shared async-action hook stayed disabled after its first click. All fourteen now use the shared hook that re-arms correctly, and a test fails if the broken shape is reintroduced anywhere in the client.+- **[issue-3266] The mount guard behind issue 3264 now has exactly one implementation.** Thirteen more components and hooks still spelled that guard out by hand — correctly, so the new test passed them, but they were the copy source: reproducing issue 3264 took nothing more than copying one of them and dropping a line. Several also carried their own multi-line essay re-deriving the StrictMode hazard, which is the hazard being rediscovered per file instead of read off a hook name. All thirteen now call the shared hook, and the test fails on the hand-written form whether or not it happens to be correct.- **[issue-3265] Fixed a test that broke on its own once the calendar passed 2026-07-31.** An image-quota test compared against a reset timestamp baked into its fixture; once that instant passed, the code correctly ignored the stale time and the test started comparing against the wall clock, failing every run. The test now pins its own clock, and the ignore-a-past-reset path it accidentally exercised has coverage of its own.- **[issue-3267] Removed the unmount guard from the shared async-action hook, along with the test that could never fail.** The guard existed to avoid a "state update on an unmounted component" warning React stopped emitting in version 18, so its only remaining effect was to skip a no-op — while being the exact shape that froze every button backed by the hook under StrictMode. Its regression test asserted that the vanished warning never appeared, which stayed green even with the guard deleted; it now unmounts mid-request and asserts the action still resolves with its value.- **[issue-3250] Stabilize Music Video project-selection tests under CI load.** Project-selection coverage now waits for the requested project to be available before opening its board, preventing intermittent false failures.diff --git a/client/src/components/loraTraining/LiveSampleGallery.jsx b/client/src/components/loraTraining/LiveSampleGallery.jsxindex 6395ed3a03..ff2014154f 100644--- a/client/src/components/loraTraining/LiveSampleGallery.jsx+++ b/client/src/components/loraTraining/LiveSampleGallery.jsx@@ -14,12 +14,13 @@* keeps just the last step), so it builds up over the session.*/-import { useEffect, useMemo, useRef, useState } from 'react';+import { useEffect, useMemo, useState } from 'react';import { ImageOff, Radio } from 'lucide-react';import { formatDurationMs } from '../../utils/formatters';import { useTimeTick } from '../../hooks/useTimeTick';import { lossSparklineGeometry } from '../../lib/lossSparkline';import { listLoraTrainingSamples } from '../../services/api';+import useMounted from '../../hooks/useMounted';const SPARK_W = 240;const SPARK_H = 36;@@ -52,12 +53,7 @@ export default function LiveSampleGallery({ run, frames, progress, message }) {// Seconds-precision tick for the elapsed/ETA labels — shared, visibility-// aware timer (pauses when the tab is hidden) instead of a per-mount interval.const now = useTimeTick(1000);- const mountedRef = useRef(true);-- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);+ const mountedRef = useMounted();// One-shot seed of every sample persisted so far (survives a mid-run reload).useEffect(() => {diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsxindex 5d9dea63b9..484cb07b34 100644--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx@@ -2,6 +2,7 @@ import { useState, useEffect, useRef, useCallback } from 'react';import { Brain, Check, X, BookOpen, Play } from 'lucide-react';import { DRILL_LABELS, nBackBalancedAccuracy } from './constants';import { safeReadJsonStorage, safeWriteStorage } from '../../../lib/safeStorage.js';+import useMounted from '../../../hooks/useMounted';/*** Interactive runner for deterministic cognitive drills (n-back, digit-span,@@ -430,7 +431,7 @@ function NBackRunner({ drill, drillIndex, drillCount, onComplete, isTraining })const answersRef = useRef(seq.map(() => ({ answered: null, responseMs: 0 })));const stimStartRef = useRef(0);const startedAtRef = useRef(Date.now());- const mountedRef = useRef(true);+ const mountedRef = useMounted();const timeoutRef = useRef(null);const finish = useCallback(() => {@@ -442,7 +443,6 @@ function NBackRunner({ drill, drillIndex, drillCount, onComplete, isTraining })finishRef.current = finish;useEffect(() => {- mountedRef.current = true;let i = 0;const step = () => {if (!mountedRef.current) return;@@ -454,7 +454,7 @@ function NBackRunner({ drill, drillIndex, drillCount, onComplete, isTraining })timeoutRef.current = setTimeout(() => { i = cur + 1; step(); }, stimulusMs);};timeoutRef.current = setTimeout(step, 800);- return () => { mountedRef.current = false; clearTimeout(timeoutRef.current); };+ return () => clearTimeout(timeoutRef.current);}, []);const registerMatch = useCallback(() => {@@ -544,7 +544,7 @@ function DigitSpanRunner({ drill, drillIndex, drillCount, onComplete, isTrainingconst answersRef = useRef([]);const recallStartRef = useRef(0);const startedAtRef = useRef(Date.now());- const mountedRef = useRef(true);+ const mountedRef = useMounted();const inputRef = useRef(null);const finish = useCallback(() => {@@ -555,8 +555,6 @@ function DigitSpanRunner({ drill, drillIndex, drillCount, onComplete, isTrainingconst finishRef = useRef(finish);finishRef.current = finish;- useEffect(() => { mountedRef.current = true; return () => { mountedRef.current = false; }; }, []);-// Reveal the current sequence one digit at a time, then switch to recall.useEffect(() => {if (seqIdx >= sequences.length) { finishRef.current(); return; }@@ -1068,7 +1066,7 @@ function ReactionTimeRunner({ drill, drillIndex, drillCount, onComplete, isTrainconst stimulusShownRef = useRef(false);const goStartRef = useRef(0);const startedAtRef = useRef(Date.now());- const mountedRef = useRef(true);+ const mountedRef = useMounted();// Separate refs: the "reveal the stimulus" timer (armed per trial) and the// "advance to the next trial" timer (armed on response) must never share one// ref — overwriting a shared ref on response leaves the reveal timer's@@ -1078,13 +1076,9 @@ function ReactionTimeRunner({ drill, drillIndex, drillCount, onComplete, isTrainconst advanceTimeoutRef = useRef(null);const advancingRef = useRef(false);- useEffect(() => {- mountedRef.current = true;- return () => {- mountedRef.current = false;- clearTimeout(armTimeoutRef.current);- clearTimeout(advanceTimeoutRef.current);- };+ useEffect(() => () => {+ clearTimeout(armTimeoutRef.current);+ clearTimeout(advanceTimeoutRef.current);}, []);const finish = useCallback(() => {diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsxindex 82ee45c4d8..d18121a2e8 100644--- a/client/src/components/media/MediaJobsQueue.jsx+++ b/client/src/components/media/MediaJobsQueue.jsx@@ -1,4 +1,4 @@-import { useMemo, useState, useCallback, useEffect, useRef } from 'react';+import { useMemo, useState, useCallback, useEffect } from 'react';import { ListOrdered, Image as ImageIcon, Film, Cpu, X, RefreshCw, ChevronDown, ChevronRight, Trash2, RotateCw, Zap, Pencil } from 'lucide-react';import toast from '../ui/Toast';import ConfirmButtonPair from '../ui/ConfirmButtonPair';@@ -10,6 +10,7 @@ import { ANTIGRAVITY_CONFIGURED_DEFAULT, CODEX_EFFORT_LEVELS, isConfiguredDefaulimport { lossSparklineGeometry } from '../../lib/lossSparkline';import { useAutoRefetch } from '../../hooks/useAutoRefetch';import { useConfirmDelete } from '../../hooks/useConfirmDelete';+import useMounted from '../../hooks/useMounted';const STATUS_BADGE = {queued: 'bg-port-border text-port-text-muted',@@ -240,12 +241,7 @@ function trainingSummary(params) {// Re-fetches while the run is live so the curve grows as checkpoints land.function TrainingJobDetail({ runId, status }) {const [checkpoints, setCheckpoints] = useState(null); // null = loading; [] = none yet- const mountedRef = useRef(true);-- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);+ const mountedRef = useMounted();const load = useCallback(() => {listLoraTrainingCheckpoints(runId)diff --git a/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx b/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsxindex f0013a0f86..996dee69e3 100644--- a/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx+++ b/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx@@ -27,6 +27,7 @@ import { narratePipelineProse } from '../../../services/api';import { STAGE_LABEL } from './constants';import { clickableProps } from '../../../lib/a11yKeyboard';import { safeReadStorage, safeWriteStorage } from '../../../lib/safeStorage';+import useMounted from '../../../hooks/useMounted';const NARRATOR_VOICE_KEY = 'portos.manuscript.narratorVoice';const initialVoice = () => safeReadStorage(NARRATOR_VOICE_KEY) || '';@@ -42,15 +43,9 @@ export default function ManuscriptReadAloud({ open, onClose, section }) {const [elapsedMs, setElapsedMs] = useState(0);const audioRef = useRef(null);- // Set true on (re)mount, false on unmount. The body-set is required because- // the app runs under React.StrictMode, which does mount→cleanup→mount on the- // initial mount; a cleanup-only guard would be left false and freeze every- // later narration at the mounted check.- const mountedRef = useRef(true);- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);+ // Gates the post-synthesis state writes so a narration that resolves after the+ // modal is torn down doesn't apply audio/offsets into an unmounted tree.+ const mountedRef = useMounted();// Live mirror of the prose the modal is showing, so an in-flight narration// response can detect that the section's text changed (edit, reformat, accepted// fix, or a section swap) while it was synthesizing and discard itself ratherdiff --git a/client/src/components/songs/PitchTuner.jsx b/client/src/components/songs/PitchTuner.jsxindex 46039932a8..3e43a2ca1e 100644--- a/client/src/components/songs/PitchTuner.jsx+++ b/client/src/components/songs/PitchTuner.jsx@@ -21,6 +21,7 @@ import { Music2, Square } from 'lucide-react';import toast from '../ui/Toast';import { createStreamAnalyser } from '../../lib/audioRecorder.js';import { createPitchTracker, tuningQuality } from '../../lib/pitchDetect.js';+import useMounted from '../../hooks/useMounted';// Map a tuning-quality level to its readout color token + needle fill.const LEVEL_TONE = {@@ -60,12 +61,7 @@ export default function PitchTuner({ stream = null, a4 = 440 }) {const trackerRef = useRef(null); // active pitch tracker { stop }const analyserRef = useRef(null); // active { close } stream-analyser graphconst ownStreamRef = useRef(null); // standalone-mode mic stream we own + must stop- const mountedRef = useRef(true);-- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);+ const mountedRef = useMounted();// Tear down the tracker loop + analyser graph (but not the stream — see attach).const teardownTracker = useCallback(() => {diff --git a/client/src/components/writers-room/ExercisePanel.jsx b/client/src/components/writers-room/ExercisePanel.jsxindex fb51c5d56b..3261d34fa1 100644--- a/client/src/components/writers-room/ExercisePanel.jsx+++ b/client/src/components/writers-room/ExercisePanel.jsx@@ -9,6 +9,7 @@ import {} from '../../services/apiWritersRoom';import { countWords, formatCountdown } from '../../utils/formatters';import { FormField } from '../ui/FormField';+import useMounted from '../../hooks/useMounted';const DURATION_PRESETS = [{ label: '5 min', seconds: 300 },@@ -26,11 +27,7 @@ export default function ExercisePanel({ activeWork, onClose }) {const [text, setText] = useState('');const tickRef = useRef(null);- const mountedRef = useRef(true);- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);+ const mountedRef = useMounted();const refresh = useCallback(async () => {// Capture the workId we asked for so a slow response from the previousdiff --git a/client/src/hooks/mountedRefConventions.test.js b/client/src/hooks/mountedRefConventions.test.jsindex fd360faba0..41d25ffe6c 100644--- a/client/src/hooks/mountedRefConventions.test.js+++ b/client/src/hooks/mountedRefConventions.test.js@@ -1,5 +1,9 @@/**- * Repo-wide guard: a mounted-guard ref must re-arm itself on mount.+ * Repo-wide guard: `hooks/useMounted.js` is the only mounted-guard ref.+ *+ * Two rules, one bug class.+ *+ * ## 1. A mounted-guard ref must re-arm itself on mount** The broken shape is a ref seeded `useRef(true)` whose ONLY assignment is* `false` in an effect cleanup:@@ -16,15 +20,20 @@* stuck on "Loading generators…" forever, and every `useAsyncAction` button stuck* in its disabled/spinner state after one click (#3264).*- * `hooks/useMounted.js` is the fix, and the sanctioned form for new code. (A dozen- * older sites still inline the same body correctly — they DO set `true` on setup,- * so they are safe and this guard passes them; converting them is follow-up- * cleanup, not a correctness fix.)- ** The rule is deliberately shape-based rather than name-based — a ref called* `editorMountedRef` carries the identical bug, and one of the sites this guard* was written for was named exactly that.*+ * ## 2. Nothing may hand-inline `useMounted`'s body, even correctly+ *+ * `#3264` fixed fourteen sites that hand-rolled the guard *wrong*; thirteen more+ * hand-rolled it *right* and were therefore invisible to rule 1. Those thirteen+ * were the supply line: copying one of them and dropping the setup line+ * reproduces #3264 exactly, and several carried multi-line comments re-deriving+ * the StrictMode hazard from first principles — evidence the hazard was being+ * rediscovered per site instead of read off the hook name. So rule 2 rejects the+ * correct hand-roll too (#3266), leaving `useMounted()` as the only spelling.+ ** ## What this guard CANNOT see** It is a source grep, not a scope-aware AST pass, so these semantically identical@@ -33,14 +42,19 @@** - `let`/`var` declarations (the pattern hardcodes `const`).* - A non-literal seed: `const INIT = true; const r = useRef(INIT)`.- * - Two components in ONE file where A is correct and B is broken — the scan is- * file-scoped, so A's `= true` satisfies B. Live risk: three separate- * `mountedRef`s coexist in `components/meatspace/post/PostCognitiveDrillRunner.jsx`.+ * - Two components in ONE file where A is correct and B is broken — rule 1's scan+ * is file-scoped, so A's `= true` satisfies B. (Rule 2 is per-occurrence and+ * unaffected.)* - A ref created in one file and lowered in another (a hook returning its ref to* a caller that writes `ref.current = false`).* - Aliasing (`const g = mountedRef; g.current = false`), computed access* (`ref['current']`), or assignment funneled through a setter function.* - An assignment that only appears inside a comment (no comment stripping).+ * - Rule 2 matches the hook's body verbatim (modulo whitespace), so a re-spelling+ * — extra statements in either half, `||=`, a non-empty dep array, the cleanup+ * before the setup — reads as "does more than useMounted" and is left to rule 1.+ * That is the intended floor: rule 2 is aimed at the copy-paste, and a variant+ * that still re-arms correctly is not the bug this file is chasing.** Tightening any of these means moving to an AST pass; the shapes above are all* unusual enough in this codebase that the grep earns its keep as-is.@@ -54,15 +68,37 @@ import { trackedSourceFiles } from '../test/trackedFiles.js';const CLIENT_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');+// The one file allowed to contain the shape — it IS the shape.+const HOOK_FILE = 'src/hooks/useMounted.js';+// `const <name> = useRef(true)` — the seed value that marks a mounted-style guard.// A ref seeded `useRef(false)` and raised to `true` on mount is a different (and// correct) pattern, so it is intentionally out of scope.const TRUE_SEEDED_REF = /const\s+([A-Za-z_$][\w$]*)\s*=\s*useRef\(\s*true\s*\)/g;+// Ref names may legally contain `$`, which is a regex anchor — interpolating one+// raw would silently make the pattern unmatchable and pass the offender.+const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+// `=` and `||=` both count as re-arming. Matching only `=` would report a ref// re-armed with `ref.current ||= true` as broken — a false positive that would// push someone to "fix" already-correct code.-const assignsRe = (name, value) => new RegExp(`\\b${name}\\.current\\s*(?:\\|\\|)?=\\s*${value}\\b`);+const assignsRe = (name, value) => new RegExp(`\\b${escapeRe(name)}\\.current\\s*(?:\\|\\|)?=\\s*${value}\\b`);++// The body of `hooks/useMounted.js`, hand-inlined: an effect on an empty dep array+// whose setup does nothing but raise the ref and whose cleanup does nothing but+// lower it. `\s*` spans newlines, so the one-line and multi-line spellings both+// match. Anything with extra work in either half is a different effect and is left+// alone — see "What this guard CANNOT see".+const inlinedUseMountedRe = (name) => {+ const ref = `${escapeRe(name)}\\.current`;+ return new RegExp(+ `useEffect\\(\\s*\\(\\s*\\)\\s*=>\\s*\\{\\s*`+ + `${ref}\\s*=\\s*true\\s*;?\\s*`+ + `return\\s*\\(\\s*\\)\\s*=>\\s*\\{\\s*${ref}\\s*=\\s*false\\s*;?\\s*\\}\\s*;?\\s*`+ + `\\}\\s*,\\s*\\[\\s*\\]\\s*\\)`,+ );+};/** Refs in `src` that are lowered to false but never re-raised to true. */function findOneWayRefs(src) {@@ -76,6 +112,16 @@ function findOneWayRefs(src) {return offenders;}+/** Refs in `src` that re-implement `useMounted()` verbatim instead of calling it. */+function findInlinedUseMounted(src) {+ const offenders = [];+ for (const match of src.matchAll(TRUE_SEEDED_REF)) {+ const name = match[1];+ if (inlinedUseMountedRe(name).test(src)) offenders.push(name);+ }+ return offenders;+}+describe('mounted-guard refs re-arm on mount (StrictMode)', () => {it('has no ref that is only ever set to false', () => {const files = trackedSourceFiles(CLIENT_ROOT);@@ -112,7 +158,9 @@ describe('mounted-guard refs re-arm on mount (StrictMode)', () => {const editorMountedRef = useRef(true);useEffect(() => () => { editorMountedRef.current = false; }, []);`;- const fixed = `+ // Re-arms correctly, so rule 1 passes it. (Rule 2 rejects it separately —+ // it is `useMounted`'s body inlined. See the second describe block.)+ const handRolled = `const mountedRef = useRef(true);useEffect(() => {mountedRef.current = true;@@ -132,8 +180,84 @@ describe('mounted-guard refs re-arm on mount (StrictMode)', () => {expect(findOneWayRefs(broken)).toEqual(['mountedRef']);expect(findOneWayRefs(brokenRenamed)).toEqual(['editorMountedRef']);- expect(findOneWayRefs(fixed)).toEqual([]);+ expect(findOneWayRefs(handRolled)).toEqual([]);expect(findOneWayRefs(fixedLogicalAssign)).toEqual([]);expect(findOneWayRefs(neverLowered)).toEqual([]);});});++describe('mounted-guard refs call useMounted() instead of inlining it', () => {+ it('has no file re-implementing the hook', () => {+ const files = trackedSourceFiles(CLIENT_ROOT).filter((f) => f !== HOOK_FILE);+ expect(files.length).toBeGreaterThan(100);++ const violations = [];+ for (const file of files) {+ const src = readFileSync(join(CLIENT_ROOT, file), 'utf8');+ for (const name of findInlinedUseMounted(src)) violations.push(`${file}: ${name}`);+ }++ expect(+ violations,+ 'These refs inline the exact body of `useMounted` instead of calling it. They '+ + 'work today, but they are how the #3264 freezes got written: copy one, drop '+ + 'the setup line, and the ref is permanently false under StrictMode.\n'+ + 'Fix: `const mountedRef = useMounted();` — import `useMounted` from '+ + '`client/src/hooks/useMounted.js` and delete the ref + its effect. If the '+ + 'effect also does real cleanup (clearTimeout, abort), keep THAT in its own '+ + '`useEffect` and move only the ref bookkeeping to the hook.\n'+ + `Offenders:\n ${violations.join('\n ')}`,+ ).toEqual([]);+ });++ // Guards the guard: the detector must still fire on the shape it exists to ban,+ // and must not fire on refs that merely happen to be seeded `true`.+ it('detects the inlined hook body and leaves other true-seeded refs alone', () => {+ const inlinedMultiline = `+ const mountedRef = useRef(true);+ useEffect(() => {+ mountedRef.current = true;+ return () => { mountedRef.current = false; };+ }, []);+ `;+ const inlinedOneLine = 'const m = useRef(true);'+ + 'useEffect(() => { m.current = true; return () => { m.current = false; }; }, []);';+ // The sanctioned form has no effect to match.+ const usesHook = 'const mountedRef = useMounted();';+ // A ref seeded `true` that is toggled as ordinary UI state (SongBook's+ // follow-the-playhead flag) is not a mounted guard and must not be flagged.+ const unrelatedToggle = `+ const followRef = useRef(true);+ const onPlay = () => { followRef.current = true; };+ const onPan = () => { followRef.current = false; };+ `;+ // Does strictly more than the hook — rule 1 already covers whether it re-arms.+ const doesExtraCleanup = `+ const mountedRef = useRef(true);+ useEffect(() => {+ mountedRef.current = true;+ return () => { mountedRef.current = false; clearTimeout(timerRef.current); };+ }, []);+ `;+ // The broken shape has no setup half, so only rule 1 owns it.+ const broken = `+ const mountedRef = useRef(true);+ useEffect(() => () => { mountedRef.current = false; }, []);+ `;++ expect(findInlinedUseMounted(inlinedMultiline)).toEqual(['mountedRef']);+ expect(findInlinedUseMounted(inlinedOneLine)).toEqual(['m']);+ expect(findInlinedUseMounted(usesHook)).toEqual([]);+ expect(findInlinedUseMounted(unrelatedToggle)).toEqual([]);+ expect(findInlinedUseMounted(doesExtraCleanup)).toEqual([]);+ expect(findInlinedUseMounted(broken)).toEqual([]);+ });++ // The hook itself is the one sanctioned copy — if the exclusion ever stops+ // matching (file moved/renamed), this fails instead of the guard going quiet.+ it('excludes the hook itself, and the hook still matches the banned shape', () => {+ expect(trackedSourceFiles(CLIENT_ROOT)).toContain(HOOK_FILE);+ const src = readFileSync(join(CLIENT_ROOT, HOOK_FILE), 'utf8');+ expect(findInlinedUseMounted(src)).toEqual(['mountedRef']);+ });+});diff --git a/client/src/hooks/useAutoscroll.js b/client/src/hooks/useAutoscroll.jsindex b8f87c597e..ef00a6b197 100644--- a/client/src/hooks/useAutoscroll.js+++ b/client/src/hooks/useAutoscroll.js@@ -1,4 +1,5 @@import { useCallback, useEffect, useRef, useState } from 'react';+import useMounted from './useMounted';/*** Smooth autoscroll for a scrollable container (SongBook play view, or any@@ -21,16 +22,10 @@ export default function useAutoscroll(containerRef, { initialPxPerSec = 30 } = {const pxPerSecRef = useRef(pxPerSec);pxPerSecRef.current = pxPerSec;- // Reset to true in setup, not just initialized: StrictMode dev runs effects- // setup→cleanup→setup on the same instance (refs persist), so a cleanup-only- // guard would stay false forever and wheel-pause / bottom-stop would no-op.- // (The CLAUDE.md "never reset to true" rule is for deferred network emits,- // where staying false is the safe direction — here it gates live UI.)- const mountedRef = useRef(true);- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);+ // Gates the auto-stop setState so a rAF frame that lands after unmount is+ // inert. (The CLAUDE.md "never reset to true" rule is for deferred network+ // emits, where staying false is the safe direction — here it gates live UI.)+ const mountedRef = useMounted();useEffect(() => {if (!playing) return undefined;diff --git a/client/src/hooks/useMediaJobProgress.js b/client/src/hooks/useMediaJobProgress.jsindex 6278ddbefe..650789b7f8 100644--- a/client/src/hooks/useMediaJobProgress.js+++ b/client/src/hooks/useMediaJobProgress.js@@ -1,7 +1,8 @@-import { useEffect, useRef, useState } from 'react';+import { useEffect, useState } from 'react';import socket from '../services/socket';import { getMediaJob } from '../services/apiMediaJobs';import { usePreviousSync } from './usePrevious.js';+import useMounted from './useMounted';/*** Subscribe to live progress for a single mediaJobQueue job. `kind`@@ -46,18 +47,7 @@ export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {if (prevJobId !== jobId) setState(INITIAL_STATE);// Track mount so the initial fetch's setState doesn't fire after unmount// (the panel could be removed while the GET is in flight).- //- // The set-in-effect-setup pattern (NOT relying on `useRef(true)`'s initial- // value alone) is required: React 18 StrictMode in dev fires- // mount → cleanup → mount, but the ref is preserved across the simulated- // remount. Without re-setting `true` in setup, cleanup flips it to false- // and it never goes back up — the initial fetch's `.then` permanently- // no-ops for every dev render.- const mountedRef = useRef(true);- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);+ const mountedRef = useMounted();useEffect(() => {if (!jobId) return undefined;diff --git a/client/src/pages/Ask.jsx b/client/src/pages/Ask.jsxindex ae9681437d..1bb40fdf4a 100644--- a/client/src/pages/Ask.jsx+++ b/client/src/pages/Ask.jsx@@ -5,6 +5,7 @@ import * as api from '../services/api';import toast from '../components/ui/Toast';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';import { useConfirmDelete } from '../hooks/useConfirmDelete';+import useMounted from '../hooks/useMounted';// Mirrors the server-side ID_RE in askConversations.js (9-char base36 ms +// 8-char hex suffix) so this regex stays in lockstep with the production@@ -398,19 +399,16 @@ export default function Ask() {}}, [conversationId]);+ // Checked from `handleSend`'s post-stream cleanup so it can skip state writes+ // if we get there after unmount.+ const mountedRef = useMounted();+// Separately, kill any in-flight stream on real unmount so we don't leak- // a fetch + state-update closure into a torn-down tree. `mountedRef` is- // checked from `handleSend`'s post-stream cleanup so it can skip state- // writes if we get there after unmount.- const mountedRef = useRef(true);- useEffect(() => {- mountedRef.current = true;- return () => {- mountedRef.current = false;- abortRef.current?.abort();- abortRef.current = null;- streamingConvIdRef.current = null;- };+ // a fetch + state-update closure into a torn-down tree.+ useEffect(() => () => {+ abortRef.current?.abort();+ abortRef.current = null;+ streamingConvIdRef.current = null;}, []);const startNew = useCallback(() => {diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsxindex 4e823a72a1..a6102866b8 100644--- a/client/src/pages/MoodBoardDetail.jsx+++ b/client/src/pages/MoodBoardDetail.jsx@@ -26,6 +26,7 @@ import {} from '../services/api';import { moodBoardItemSrc } from '../lib/moodBoardItemSrc';import { timeAgo } from '../utils/formatters';+import useMounted from '../hooks/useMounted';export default function MoodBoardDetail() {const { id } = useParams();@@ -55,19 +56,10 @@ export default function MoodBoardDetail() {// the fetch is async, an older request can resolve *after* a newer one (the// user navigated to a different board) and clobber current state. We bump a// sequence counter per call and only apply the result if it's still the latest- // — and only if the component is still mounted.- //- // `mountedRef` is set true on mount (not just left at its initial value) so- // that React 18 StrictMode's dev-only mount→cleanup→remount — which preserves- // this ref and would otherwise leave it stuck `false` after the simulated- // unmount — re-arms the guard for the real mount. The seq counter independently+ // — and only if the component is still mounted. The seq counter independently// drops StrictMode's duplicate first fetch.- const mountedRef = useRef(true);+ const mountedRef = useMounted();const loadSeqRef = useRef(0);- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);const load = useCallback(async () => {const seq = ++loadSeqRef.current;diff --git a/client/src/pages/WritersRoom.jsx b/client/src/pages/WritersRoom.jsxindex 7a1eeb15ae..6de7a758da 100644--- a/client/src/pages/WritersRoom.jsx+++ b/client/src/pages/WritersRoom.jsx@@ -1,4 +1,4 @@-import { useEffect, useState, useCallback, useRef } from 'react';+import { useEffect, useState, useCallback } from 'react';import { useParams, useNavigate, Link } from 'react-router-dom';import { NotebookPen, PanelLeftOpen, BookOpen } from 'lucide-react';import LibraryPane from '../components/writers-room/LibraryPane';@@ -11,6 +11,7 @@ import {getWritersRoomWork,} from '../services/apiWritersRoom';import { useLocalStorageBool } from '../hooks/useLocalStorageBool';+import useMounted from '../hooks/useMounted';const LIBRARY_COLLAPSED_KEY = 'wr.libraryCollapsed';@@ -33,13 +34,8 @@ export default function WritersRoom() {}, [setLibraryCollapsed]);// Skip setState when an in-flight library or work fetch resolves after the- // page unmounts (rapid nav across pages). Reset on mount so React 18- // StrictMode's mount→cleanup→remount cycle doesn't leave the ref stuck false.- const mountedRef = useRef(true);- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);+ // page unmounts (rapid nav across pages).+ const mountedRef = useMounted();const refreshLibrary = useCallback(async () => {const [foldersList, worksList] = await Promise.all([