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

refactor([issue-3264]): register the mounted-ref guard in CI and share its file walker

[._.]/ Adam Eivyd1367b84706e
diff --git a/client/src/a11yConventions.test.js b/client/src/a11yConventions.test.js
index 1e91739a93..d7b7a6ea2b 100644
--- a/client/src/a11yConventions.test.js
+++ b/client/src/a11yConventions.test.js
@@ -30,26 +30,19 @@
*/
import { describe, it, expect } from 'vitest';
-import { execSync } from 'child_process';
import { readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
+import { trackedJsxFiles as trackedJsx, trackedSourceFiles as trackedSources } from './test/trackedFiles.js';
const CLIENT_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
-function trackedJsxFiles() {
- const out = execSync('git ls-files src', { cwd: CLIENT_ROOT, encoding: 'utf8' });
- return out.trim().split('\n').filter(f => f.endsWith('.jsx') && !f.includes('.test.'));
-}
-
-// Same, but including plain `.js` — hooks and services hold JSX and refs too
-// (the OpenClaw composer's file-input ref lived in `hooks/useOpenClawAttachments.js`),
-// so a rule that only scans `.jsx` has a hole exactly where a shared helper
-// would reintroduce the pattern for many call sites at once.
-function trackedSourceFiles() {
- const out = execSync('git ls-files src', { cwd: CLIENT_ROOT, encoding: 'utf8' });
- return out.trim().split('\n').filter(f => /\.jsx?$/.test(f) && !f.includes('.test.'));
-}
+// Shared with the other repo-hygiene guards (see `src/test/trackedFiles.js` for
+// why `.js` is included alongside `.jsx`: the OpenClaw composer's file-input ref
+// lived in `hooks/useOpenClawAttachments.js`, exactly the hole a `.jsx`-only
+// scan leaves open).
+const trackedJsxFiles = () => trackedJsx(CLIENT_ROOT);
+const trackedSourceFiles = () => trackedSources(CLIENT_ROOT);
/**
* Slice out the full opening tag starting at `index`, tolerating `>` inside
diff --git a/client/src/components/loraTraining/CheckpointPicker.jsx b/client/src/components/loraTraining/CheckpointPicker.jsx
index bc6379aaf0..d1494ce4bd 100644
--- a/client/src/components/loraTraining/CheckpointPicker.jsx
+++ b/client/src/components/loraTraining/CheckpointPicker.jsx
@@ -25,8 +25,7 @@ export default function CheckpointPicker({ run, onPromoted }) {
const [loading, setLoading] = useState(false);
const [promotingStep, setPromotingStep] = useState(null);
// Guards the background preview-poll setTimeout chain from firing after the
- // component unmounts (deferred-work-respects-unmount rule). Not reset to true
- // so dev-mode double-mount can't re-arm a stale chain.
+ // component unmounts (deferred-work-respects-unmount rule).
const mountedRef = useMounted();
const load = useCallback(() => {
diff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsx
index c56b55a8c0..19f87dff16 100644
--- a/client/src/components/music/TracksManager.jsx
+++ b/client/src/components/music/TracksManager.jsx
@@ -471,9 +471,7 @@ export default function TracksManager() {
</div>
{!persisted ? (
<p className="text-xs text-gray-500">
- {genMode === 'chiptune'
- ? 'Save the track first, then generate a chiptune score.'
- : 'Save the track first, then generate with an audio model.'}
+ Save the track first, then generate {genMode === 'chiptune' ? 'a chiptune score' : 'with an audio model'}.
</p>
) : genMode === 'chiptune' ? (
<ChiptunePanel
@@ -581,7 +579,9 @@ export default function TracksManager() {
) : null}
</div>
) : (
- <p className="text-xs text-gray-500">Save the track first to generate, upload, or attach audio.</p>
+ /* Generation has its own hint under the mode toggle above
+ (#3264), so this covers only what the renders block offers. */
+ <p className="text-xs text-gray-500">Save the track first to upload or attach audio.</p>
)}
{/* MIDI piano-roll (#2477) — read through from the linked Music
diff --git a/client/src/components/music/TracksManager.test.jsx b/client/src/components/music/TracksManager.test.jsx
index 78a6c0d14b..737fa10487 100644
--- a/client/src/components/music/TracksManager.test.jsx
+++ b/client/src/components/music/TracksManager.test.jsx
@@ -107,6 +107,10 @@ describe('<TracksManager> generator mode toggle', () => {
expect(screen.getByText(/Save the track first, then generate with an audio model/i)).toBeInTheDocument();
expect(screen.queryByTestId('gen-panel')).toBeNull();
expect(screen.queryByTestId('chiptune-panel')).toBeNull();
+ // The renders block's own hint no longer claims to cover generation, so an
+ // unsaved track doesn't show two near-identical "save first" sentences.
+ expect(screen.getByText(/Save the track first to upload or attach audio/i)).toBeInTheDocument();
+ expect(screen.queryByText(/Save the track first to generate, upload/i)).toBeNull();
});
it('switches mode before save and names the selected mode in the hint', async () => {
@@ -125,13 +129,7 @@ describe('<TracksManager> generator mode toggle', () => {
const created = { id: 'track-new', title: 'Fresh Cut', renders: [] };
createTrack.mockResolvedValue(created);
- render(
- <MemoryRouter initialEntries={['/music/tracks/new']}>
- <Routes>
- <Route path="/music/tracks/:id" element={<TracksManager />} />
- </Routes>
- </MemoryRouter>,
- );
+ renderAt('new');
await screen.findByRole('group', { name: /generation mode/i });
fireEvent.click(modeButton('Chiptune score'));
diff --git a/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx b/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx
index f807ec6a48..9eebda5b3e 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx
@@ -50,7 +50,7 @@ export default function ManuscriptImpactPreview({ open, onClose, seriesId, secti
// The accept-all pass awaits one network round-trip per note; if the user
// closes the preview mid-batch, late callbacks must not fire into a torn-down
- // parent. Never reset to true (handles dev-mode double-mount cleanly).
+ // parent.
const mountedRef = useMounted();
const changed = useMemo(() => {
diff --git a/client/src/components/sync/SyncDetailDrawer.jsx b/client/src/components/sync/SyncDetailDrawer.jsx
index 1b812062a6..48408fabb8 100644
--- a/client/src/components/sync/SyncDetailDrawer.jsx
+++ b/client/src/components/sync/SyncDetailDrawer.jsx
@@ -261,7 +261,7 @@ export default function SyncDetailDrawer({ kind, recordId, onClose }) {
// Drop async results that resolve after the drawer unmounts (fast route
// change / close while a fetch is in flight) to avoid setState-on-unmounted
- // warnings. Never reset to true — handles dev-mode double-mount cleanly.
+ // warnings.
const mountedRef = useMounted();
// Generation counter so only the LATEST in-flight fetch commits state — a
// rapid recordId change (or switch to empty) bumps this, and an older fetch
diff --git a/client/src/hooks/mountedRefConventions.test.js b/client/src/hooks/mountedRefConventions.test.js
index 598acaf7a8..fd360faba0 100644
--- a/client/src/hooks/mountedRefConventions.test.js
+++ b/client/src/hooks/mountedRefConventions.test.js
@@ -16,35 +16,53 @@
* 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 only sanctioned form: it assigns `true`
- * in the effect setup body, so the StrictMode remount re-arms the guard.
+ * `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 below is deliberately shape-based rather than name-based — a ref called
- * `editorMountedRef` (or anything else) carries the identical bug, and one of the
- * sites this guard was written for was named exactly that. Scoped to git-tracked
- * sources under `client/src` per the repo-hygiene convention in
- * `client/src/a11yConventions.test.js`, so an untracked scratch file can't fail it.
+ * 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.
+ *
+ * ## What this guard CANNOT see
+ *
+ * It is a source grep, not a scope-aware AST pass, so these semantically identical
+ * shapes slip through. They are listed so the next person extending it knows where
+ * the floor is rather than trusting a green run too far:
+ *
+ * - `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`.
+ * - 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).
+ *
+ * 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.
*/
import { describe, it, expect } from 'vitest';
-import { execSync } from 'child_process';
import { 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)), '..', '..');
-function trackedSourceFiles() {
- const out = execSync('git ls-files src', { cwd: CLIENT_ROOT, encoding: 'utf8' });
- return out.trim().split('\n').filter((f) => /\.jsx?$/.test(f) && !f.includes('.test.'));
-}
-
// `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;
-const assignsRe = (name, value) => new RegExp(`\\b${name}\\.current\\s*=\\s*${value}\\b`);
+// `=` 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`);
/** Refs in `src` that are lowered to false but never re-raised to true. */
function findOneWayRefs(src) {
@@ -60,8 +78,13 @@ function findOneWayRefs(src) {
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);
+ // 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 = [];
- for (const file of trackedSourceFiles()) {
+ for (const file of files) {
const src = readFileSync(join(CLIENT_ROOT, file), 'utf8');
for (const name of findOneWayRefs(src)) violations.push(`${file}: ${name}`);
}
@@ -80,7 +103,7 @@ describe('mounted-guard refs re-arm on mount (StrictMode)', () => {
// Guards the guard: if the detector stops recognizing the broken shape, the test
// above goes vacuously green and the bug class walks straight back in.
- it('detects the broken shape and accepts the useMounted shape', () => {
+ it('detects the broken shape and accepts every correct re-arm', () => {
const broken = `
const mountedRef = useRef(true);
useEffect(() => () => { mountedRef.current = false; }, []);
@@ -96,14 +119,21 @@ describe('mounted-guard refs re-arm on mount (StrictMode)', () => {
return () => { mountedRef.current = false; };
}, []);
`;
+ // `||=` re-arms just as well as `=`; flagging it would be a false positive.
+ const fixedLogicalAssign = `
+ const mountedRef = useRef(true);
+ useEffect(() => {
+ mountedRef.current ||= true;
+ return () => { mountedRef.current = false; };
+ }, []);
+ `;
+ // A ref that is never lowered has nothing to re-arm.
+ const neverLowered = 'const readyRef = useRef(true);';
+
expect(findOneWayRefs(broken)).toEqual(['mountedRef']);
expect(findOneWayRefs(brokenRenamed)).toEqual(['editorMountedRef']);
expect(findOneWayRefs(fixed)).toEqual([]);
- });
-
- it('scans a non-empty set of tracked sources', () => {
- // A broken `git ls-files` (wrong cwd, detached checkout) would otherwise make
- // the whole guard pass by scanning nothing.
- expect(trackedSourceFiles().length).toBeGreaterThan(100);
+ expect(findOneWayRefs(fixedLogicalAssign)).toEqual([]);
+ expect(findOneWayRefs(neverLowered)).toEqual([]);
});
});
diff --git a/client/src/hooks/useCityPlayback.js b/client/src/hooks/useCityPlayback.js
index 544e82648e..7445bde9be 100644
--- a/client/src/hooks/useCityPlayback.js
+++ b/client/src/hooks/useCityPlayback.js
@@ -24,7 +24,7 @@ export function useCityPlayback() {
const [error, setError] = useState(false);
// Guards a deferred/interval callback against firing after unmount (CLAUDE.md
- // deferred-work rule). Never reset to true — handles dev double-mount cleanly.
+ // deferred-work rule).
const mountedRef = useMounted();
const enter = useCallback(async () => {
diff --git a/client/src/test/trackedFiles.js b/client/src/test/trackedFiles.js
new file mode 100644
index 0000000000..79b12fd91a
--- /dev/null
+++ b/client/src/test/trackedFiles.js
@@ -0,0 +1,41 @@
+/**
+ * Shared file walker for the repo-hygiene test suites.
+ *
+ * Several guards (`src/a11yConventions.test.js`, `src/hooks/mountedRefConventions.test.js`)
+ * enforce a rule across the whole client tree by grepping its sources. They all
+ * need the same answer to "which files count", and that answer has been revised
+ * before — the a11y guard originally scanned only `.jsx` and had to grow a `.js`
+ * variant once a shared hook reintroduced the pattern it was policing. Keeping
+ * one definition means the next such correction lands for every guard at once.
+ *
+ * Scoped to git-tracked files so an untracked scratch file can't fail a suite,
+ * and test files are excluded so a guard can't trip over its own fixtures.
+ *
+ * Node-only (`child_process`, `fs`) — imported by test files exclusively, never
+ * by app code, so it stays out of the browser bundle. It lives in `src/test/`
+ * rather than `src/lib/` for that reason: `lib/` carries the enforced barrel +
+ * README rule, and a node-builtin module has no business in a browser barrel.
+ */
+
+import { execSync } from 'child_process';
+
+const isTest = (f) => f.includes('.test.');
+
+function gitTracked(clientRoot) {
+ const out = execSync('git ls-files src', { cwd: clientRoot, encoding: 'utf8' });
+ return out.trim().split('\n');
+}
+
+/** Git-tracked non-test `.jsx` under `client/src`. */
+export function trackedJsxFiles(clientRoot) {
+ return gitTracked(clientRoot).filter((f) => f.endsWith('.jsx') && !isTest(f));
+}
+
+/**
+ * Git-tracked non-test `.js` AND `.jsx` under `client/src`. Hooks and services
+ * hold JSX and refs too, so a rule that only scans `.jsx` has a hole exactly
+ * where a shared helper would reintroduce the pattern for many call sites at once.
+ */
+export function trackedSourceFiles(clientRoot) {
+ return gitTracked(clientRoot).filter((f) => /\.jsx?$/.test(f) && !isTest(f));
+}
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.js
index 35b67c5432..3a12cd6103 100644
--- a/scripts/ci-test-plan.js
+++ b/scripts/ci-test-plan.js
@@ -137,6 +137,14 @@ const structuralTestsFor = (changedFiles, trackedSet) => {
if (changedFiles.some((path) => /^client\/src\/.*\.jsx$/.test(path))) {
add('client/src/a11yConventions.test.js');
}
+ // Both `.js` and `.jsx`: the StrictMode mounted-ref bug this guards against
+ // reached its widest blast radius through a plain-`.js` hook (`useAsyncAction`),
+ // so a `.jsx`-only trigger would miss the case that matters most. Nothing else
+ // selects this file — it has no source sibling and imports no app module, so
+ // without this entry it only ever runs on a full suite.
+ if (changedFiles.some((path) => /^client\/src\/.*\.jsx?$/.test(path))) {
+ add('client/src/hooks/mountedRefConventions.test.js');
+ }
return selected;
};
diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.js
index 7ef5806abc..9ecb8e58ed 100644
--- a/scripts/ci-test-plan.test.js
+++ b/scripts/ci-test-plan.test.js
@@ -13,6 +13,7 @@ const TRACKED = [
'server/services/sprites/atlasGrid.test.js',
'server/services/sprites/atlasLayout.test.js',
'client/src/a11yConventions.test.js',
+ 'client/src/hooks/mountedRefConventions.test.js',
'client/src/components/catalog/CatalogCard.jsx',
'client/src/components/catalog/CatalogCard.test.jsx',
'client/src/components/sprites/WalkWorkflow.test.jsx',
@@ -117,6 +118,7 @@ describe('CI test impact planner', () => {
expect(plan.client.mode).toBe('related');
expect(plan.client.files).toContain('client/src/lib/index.test.js');
expect(plan.client.files).toContain('client/src/a11yConventions.test.js');
+ expect(plan.client.files).toContain('client/src/hooks/mountedRefConventions.test.js');
expect(plan.lint).toEqual({
mode: 'files',
files: [
@@ -127,6 +129,16 @@ describe('CI test impact planner', () => {
expect(plan.build).toBe(true);
});
+ it('selects the mounted-ref guard for a plain-.js client change', () => {
+ // The a11y guard only triggers on `.jsx`, but the StrictMode mounted-ref bug
+ // reached 94 call sites through a `.js` hook — so this guard must be selected
+ // by a change that touches no `.jsx` at all.
+ const plan = buildCiTestPlan(['client/src/hooks/useAsyncAction.js'], { trackedFiles: TRACKED });
+
+ expect(plan.client.files).toContain('client/src/hooks/mountedRefConventions.test.js');
+ expect(plan.client.files).not.toContain('client/src/a11yConventions.test.js');
+ });
+
it('runs the DB suite when a database-backed adapter changes', () => {
const plan = buildCiTestPlan([
'server/services/catalogDB/facets.js',