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: own the cover filename hooks' completion so tests can't race teardown (#9634)

Adam Eivy41237408df1b
diff --git a/server/services/pipeline/comicPagesFilenameHook.js b/server/services/pipeline/comicPagesFilenameHook.js
index a3147936c2..482b623a2d 100644
--- a/server/services/pipeline/comicPagesFilenameHook.js
+++ b/server/services/pipeline/comicPagesFilenameHook.js
@@ -127,8 +127,4 @@ export function initComicPagesFilenameHook() {
hook.init();
}
-export const __testing = {
- reset() {
- hook.__testing.reset();
- },
-};
+export const __testing = hook.__testing;
diff --git a/server/services/pipeline/coverFilenameHooks.integration.test.js b/server/services/pipeline/coverFilenameHooks.integration.test.js
index 7a6c761b35..4096834673 100644
--- a/server/services/pipeline/coverFilenameHooks.integration.test.js
+++ b/server/services/pipeline/coverFilenameHooks.integration.test.js
@@ -75,20 +75,21 @@ vi.mock('../universeBuilder.js', () => ({
// Real imports below — these read through the mocks above.
const { mediaJobEvents } = await import('../mediaJobQueue/index.js');
const collections = await import('../mediaCollections.js');
+const universeSvc = await import('../universeBuilder.js');
const seasonHook = await import('./seasonCoverFilenameHook.js');
const comicHook = await import('./comicPagesFilenameHook.js');
const { buildSeasonCoverOwner, buildComicPagesOwner } = await import('./owners.js');
-async function waitFor(predicate, { timeoutMs = 1000, intervalMs = 5 } = {}) {
- const deadline = Date.now() + timeoutMs;
- while (Date.now() < deadline) {
- if (await predicate()) return;
- await new Promise((r) => setTimeout(r, intervalMs));
- }
- throw new Error('waitFor: predicate never became true');
-}
+// Settle every hook run the emit started, including its collection write.
+const drainHooks = () => Promise.all([seasonHook.__testing.drain(), comicHook.__testing.drain()]);
+const resetHooks = () => Promise.all([seasonHook.__testing.reset(), comicHook.__testing.reset()]);
+const refsIn = async (universeId) => {
+ const linked = await collections.findCollectionByUniverseId(universeId);
+ return linked ? linked.items.map((it) => it.ref) : null;
+};
-beforeEach(() => {
+beforeEach(async () => {
+ await resetHooks();
rmSync(tempData, { recursive: true, force: true });
mkdirSync(tempData, { recursive: true });
seriesStore.clear();
@@ -97,15 +98,12 @@ beforeEach(() => {
seasonStore.clear();
updateSeasonOnSeriesMock.mockClear();
updateStageWithLatestMock.mockClear();
- seasonHook.__testing.reset();
- comicHook.__testing.reset();
seasonHook.initSeasonCoverFilenameHook();
comicHook.initComicPagesFilenameHook();
});
-afterEach(() => {
- seasonHook.__testing.reset();
- comicHook.__testing.reset();
+afterEach(async () => {
+ await resetHooks();
});
// tempData is minted once (module scope) and reused across every test in
@@ -134,12 +132,8 @@ describe('seasonCoverFilenameHook — universe collection auto-file', () => {
owner: buildSeasonCoverOwner({ seriesId, seasonId, target: 'cover', variant: 'proof' }),
});
- await waitFor(async () => {
- const linked = await collections.findCollectionByUniverseId(universeId);
- return linked?.items?.some((it) => it.ref === 'cover-final.png');
- });
- const linked = await collections.findCollectionByUniverseId(universeId);
- expect(linked.items.map((it) => it.ref)).toEqual(['cover-final.png']);
+ await drainHooks();
+ expect(await refsIn(universeId)).toEqual(['cover-final.png']);
});
it('does NOT file when the slot jobId no longer matches (stale render lands after a re-render)', async () => {
@@ -160,10 +154,7 @@ describe('seasonCoverFilenameHook — universe collection auto-file', () => {
owner: buildSeasonCoverOwner({ seriesId, seasonId, target: 'cover', variant: 'proof' }),
});
- // Give the IIFE time to run; verify the universe collection never gets
- // the stale filename. A small wait is enough — the handler's path is
- // synchronous through await microtasks once the mocks resolve.
- await new Promise((r) => setTimeout(r, 60));
+ await drainHooks();
const linked = await collections.findCollectionByUniverseId(universeId);
expect(linked).toBeNull();
});
@@ -190,7 +181,7 @@ describe('seasonCoverFilenameHook — universe collection auto-file', () => {
owner: buildSeasonCoverOwner({ seriesId, seasonId, target: 'cover', variant: 'proof' }),
});
- await new Promise((r) => setTimeout(r, 60));
+ await drainHooks();
const linked = await collections.findCollectionByUniverseId(universeId);
expect(linked).toBeNull();
});
@@ -209,7 +200,7 @@ describe('seasonCoverFilenameHook — universe collection auto-file', () => {
owner: 'pipeline:other:not-a-season-cover',
});
- await new Promise((r) => setTimeout(r, 60));
+ await drainHooks();
const linked = await collections.findCollectionByUniverseId(universeId);
expect(linked).toBeNull();
});
@@ -239,10 +230,8 @@ describe('comicPagesFilenameHook — universe collection auto-file', () => {
owner: buildComicPagesOwner({ issueId, target: 'cover', variant: 'proof' }),
});
- await waitFor(async () => {
- const linked = await collections.findCollectionByUniverseId(universeId);
- return linked?.items?.some((it) => it.ref === 'issue-cover.png');
- });
+ await drainHooks();
+ expect(await refsIn(universeId)).toEqual(['issue-cover.png']);
});
it('files the issue back-cover on completion (separate target from cover)', async () => {
@@ -268,10 +257,58 @@ describe('comicPagesFilenameHook — universe collection auto-file', () => {
owner: buildComicPagesOwner({ issueId, target: 'backCover', variant: 'proof' }),
});
- await waitFor(async () => {
- const linked = await collections.findCollectionByUniverseId(universeId);
- return linked?.items?.some((it) => it.ref === 'issue-back.png');
+ await drainHooks();
+ expect(await refsIn(universeId)).toEqual(['issue-back.png']);
+ });
+
+ it('reset waits for a held post-stamp collection filing before teardown can proceed', async () => {
+ const universeId = 'u-comic-held';
+ const seriesId = 'ser-comic-held';
+ const issueId = 'iss-held';
+ universeStore.set(universeId, { id: universeId, name: 'Held' });
+ seriesStore.set(seriesId, { id: seriesId, universeId });
+ issuesStore.set(issueId, {
+ id: issueId,
+ seriesId,
+ stages: { comicPages: { backCover: { proofImage: { jobId: 'job-back-held' } } } },
+ });
+
+ // Hold the filer's universe lookup — reached only after the stage write
+ // committed and onStamped began — until the test releases it.
+ let release;
+ const gate = new Promise((r) => { release = r; });
+ let entered;
+ const reachedHold = new Promise((r) => { entered = r; });
+ vi.mocked(universeSvc.getUniverse).mockImplementationOnce(async (id) => {
+ entered();
+ await gate;
+ return universeStore.get(id) || null;
+ });
+
+ mediaJobEvents.emit('completed', {
+ id: 'job-back-held',
+ kind: 'image',
+ result: { filename: 'issue-back-held.png' },
+ owner: buildComicPagesOwner({ issueId, target: 'backCover', variant: 'proof' }),
});
+ await reachedHold;
+ expect(issuesStore.get(issueId).stages.comicPages.backCover.proofImage.filename).toBe('issue-back-held.png');
+
+ let resetSettled = false;
+ const resetDone = comicHook.__testing.reset().then(() => { resetSettled = true; });
+ try {
+ // A full event-loop turn: a reset that doesn't own the in-flight run
+ // would have settled by now; one that does stays parked on the gate.
+ await new Promise((r) => setImmediate(r));
+ expect(resetSettled).toBe(false);
+ expect(await refsIn(universeId)).toBeNull();
+ } finally {
+ // Always release so a failed assertion can't wedge later teardown.
+ release();
+ }
+ await resetDone;
+ // Teardown proceeds only after the filing landed — nothing left to race.
+ expect(await refsIn(universeId)).toEqual(['issue-back-held.png']);
});
it('does NOT file an interior PAGE render — only cover/backCover get universe-bucketed', async () => {
@@ -297,7 +334,7 @@ describe('comicPagesFilenameHook — universe collection auto-file', () => {
owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex: 0, variant: 'proof' }),
});
- await new Promise((r) => setTimeout(r, 60));
+ await drainHooks();
const linked = await collections.findCollectionByUniverseId(universeId);
expect(linked).toBeNull();
});
@@ -325,7 +362,7 @@ describe('comicPagesFilenameHook — universe collection auto-file', () => {
owner: buildComicPagesOwner({ issueId, target: 'cover', variant: 'proof' }),
});
- await new Promise((r) => setTimeout(r, 60));
+ await drainHooks();
const linked = await collections.findCollectionByUniverseId(universeId);
expect(linked).toBeNull();
});
diff --git a/server/services/pipeline/filenameHookFactory.js b/server/services/pipeline/filenameHookFactory.js
index 521af8dbd2..0e2a993b1a 100644
--- a/server/services/pipeline/filenameHookFactory.js
+++ b/server/services/pipeline/filenameHookFactory.js
@@ -21,16 +21,46 @@
* universe bucket. The callback is awaited inside the same outer
* try/catch frame as the hook, so a thrown error is logged and swallowed
* the same way as other hook failures (bookkeeping must not fail renders).
+ *
+ * **Completion ownership.** The mediaJobEvents listener can't return the
+ * handler's promise to anyone, so each run — stage write AND `onStamped`
+ * side effect — is registered with a run tracker. `__testing.drain()`
+ * resolves once every run in flight (including runs started while draining)
+ * has settled, and `__testing.reset()` detaches the listener and THEN
+ * drains, so a test fixture can't wipe shared stores underneath a prior
+ * test's still-running write (#9634).
*/
import { mediaJobEvents } from '../mediaJobQueue/index.js';
import { updateStageWithLatest } from './issues.js';
+/**
+ * Owned completion boundary for fire-and-forget hook runs. `track(promise)`
+ * registers a run (the promise must never reject — hook runs end in their
+ * own `.catch`); `drain()` resolves when no tracked run is in flight,
+ * looping so a run that starts mid-drain is awaited too. Shared with
+ * `seasonCoverFilenameHook.js`, which can't use the issue-scoped factory.
+ */
+export function createHookRunTracker() {
+ const inFlight = new Set();
+ const track = (promise) => {
+ inFlight.add(promise);
+ const settle = () => { inFlight.delete(promise); };
+ promise.then(settle, settle);
+ return promise;
+ };
+ const drain = async () => {
+ while (inFlight.size > 0) await Promise.allSettled([...inFlight]);
+ };
+ return { track, drain };
+}
+
export function createFilenameHook({ name, stageId, kind = 'image', parseOwner, applyFilename, onStamped = null }) {
let registeredHandler = null;
+ const runs = createHookRunTracker();
const handler = (job) => {
- void (async () => {
+ void runs.track((async () => {
if (!job || job.kind !== kind) return;
const filename = job.result?.filename;
if (typeof filename !== 'string' || !filename) return;
@@ -68,7 +98,7 @@ export function createFilenameHook({ name, stageId, kind = 'image', parseOwner,
}
})().catch((err) => {
console.error(`❌ ${name} filename hook crashed: ${err?.message || err}`);
- });
+ }));
};
function init() {
@@ -78,12 +108,15 @@ export function createFilenameHook({ name, stageId, kind = 'image', parseOwner,
console.log(`📎 ${name} filename hook initialized`);
}
- function reset() {
+ // Detach first so no new run can start, then wait out the runs already in
+ // flight — callers reset shared fixture state right after this resolves.
+ async function reset() {
if (registeredHandler) {
mediaJobEvents.off('completed', registeredHandler);
registeredHandler = null;
}
+ await runs.drain();
}
- return { init, __testing: { reset } };
+ return { init, __testing: { reset, drain: runs.drain } };
}
diff --git a/server/services/pipeline/seasonCoverFilenameHook.js b/server/services/pipeline/seasonCoverFilenameHook.js
index a59c2df6c2..25166e65c6 100644
--- a/server/services/pipeline/seasonCoverFilenameHook.js
+++ b/server/services/pipeline/seasonCoverFilenameHook.js
@@ -23,11 +23,15 @@ import { parseSeasonCoverOwner, slotKeyForVariant } from './owners.js';
import * as seriesSvc from './series.js';
import { fileCoverIntoAutoCollection } from './coverUniverseFiler.js';
import { refreshSeriesCoverImage } from './seriesCoverImage.js';
+import { createHookRunTracker } from './filenameHookFactory.js';
let registeredHandler = null;
+// Owned completion boundary for the fire-and-forget handler runs, including
+// the post-stamp collection filing — see `createHookRunTracker` (#9634).
+const runs = createHookRunTracker();
const handler = (job) => {
- void (async () => {
+ void runs.track((async () => {
if (!job || job.kind !== 'image') return;
const filename = job.result?.filename;
if (typeof filename !== 'string' || !filename) return;
@@ -72,7 +76,7 @@ const handler = (job) => {
}
})().catch((err) => {
console.error(`❌ seasonCover filename hook crashed: ${err?.message || err}`);
- });
+ }));
};
export function initSeasonCoverFilenameHook() {
@@ -83,10 +87,13 @@ export function initSeasonCoverFilenameHook() {
}
export const __testing = {
- reset() {
+ // Detach, then wait out in-flight runs so fixture teardown can't race them.
+ async reset() {
if (registeredHandler) {
mediaJobEvents.off('completed', registeredHandler);
registeredHandler = null;
}
+ await runs.drain();
},
+ drain: runs.drain,
};
diff --git a/server/services/pipeline/storyboardsFilenameHook.test.js b/server/services/pipeline/storyboardsFilenameHook.test.js
index a4b0565647..8676020f14 100644
--- a/server/services/pipeline/storyboardsFilenameHook.test.js
+++ b/server/services/pipeline/storyboardsFilenameHook.test.js
@@ -6,8 +6,8 @@
* queue, and must still attach jobs queued under the LEGACY index-only owner
* format (no ids) so an upgrade doesn't strand in-flight renders.
*
- * The hook's handler runs inside a `void (async () => {})` IIFE, so each test
- * waits for the side effect rather than awaiting the emit.
+ * The hook's handler runs fire-and-forget, so each test awaits the hook's
+ * owned completion boundary (`__testing.drain()`) before asserting (#9634).
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
@@ -31,29 +31,20 @@ const { mediaJobEvents } = await import('../mediaJobQueue/index.js');
const hook = await import('./storyboardsFilenameHook.js');
const { buildStoryboardsShotOwner } = await import('./owners.js');
-async function waitFor(predicate, { timeoutMs = 1000, intervalMs = 5 } = {}) {
- const deadline = Date.now() + timeoutMs;
- while (Date.now() < deadline) {
- if (predicate()) return;
- await new Promise((r) => setTimeout(r, intervalMs));
- }
- throw new Error('waitFor: predicate never became true');
-}
-
const seedIssue = (scenes) => {
issuesStore.set('iss-1', { id: 'iss-1', stages: { storyboards: { scenes } } });
};
const shotsOf = (sceneIndex) => issuesStore.get('iss-1').stages.storyboards.scenes[sceneIndex].shots;
-beforeEach(() => {
+beforeEach(async () => {
+ await hook.__testing.reset();
issuesStore.clear();
updateStageWithLatestMock.mockClear();
- hook.__testing.reset();
hook.initStoryboardsFilenameHook();
});
-afterEach(() => {
- hook.__testing.reset();
+afterEach(async () => {
+ await hook.__testing.reset();
});
describe('storyboardsFilenameHook', () => {
@@ -74,7 +65,8 @@ describe('storyboardsFilenameHook', () => {
}),
});
- await waitFor(() => shotsOf(1)[0].startFrameFilename === 'shot.png');
+ await hook.__testing.drain();
+ expect(shotsOf(1)[0].startFrameFilename).toBe('shot.png');
expect(shotsOf(0)[0].startFrameFilename).toBeUndefined();
});
@@ -90,7 +82,8 @@ describe('storyboardsFilenameHook', () => {
owner: 'pipeline:iss-1:storyboards:scene0:shot0',
});
- await waitFor(() => shotsOf(0)[0].startFrameFilename === 'legacy.png');
+ await hook.__testing.drain();
+ expect(shotsOf(0)[0].startFrameFilename).toBe('legacy.png');
});
it('skips when the shot is no longer pointing at this job (stale re-render)', async () => {
@@ -105,7 +98,8 @@ describe('storyboardsFilenameHook', () => {
}),
});
- await waitFor(() => updateStageWithLatestMock.mock.calls.length > 0);
+ await hook.__testing.drain();
+ expect(updateStageWithLatestMock).toHaveBeenCalledTimes(1);
expect(shotsOf(0)[0].startFrameFilename).toBeUndefined();
});
@@ -121,7 +115,8 @@ describe('storyboardsFilenameHook', () => {
}),
});
- await waitFor(() => updateStageWithLatestMock.mock.calls.length > 0);
+ await hook.__testing.drain();
+ expect(updateStageWithLatestMock).toHaveBeenCalledTimes(1);
expect(shotsOf(0)[0].startFrameFilename).toBeUndefined();
});
});