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
test: make slow suites deterministic
[._.]/ Adam Eivye450484c39ea
diff --git a/lib/portosAuthCore.js b/lib/portosAuthCore.jsindex 175b170bd3..821a140ec6 100644--- a/lib/portosAuthCore.js+++ b/lib/portosAuthCore.js@@ -30,11 +30,21 @@ export const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days// here), so 256 MiB is allocated.export const SCRYPT_PARAMS = { N: 131072, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };-export const hashPassword = async (password, salt) => {- const buf = await scryptAsync(password, salt, HASH_BYTES, SCRYPT_PARAMS);+const derivePasswordHash = async (password, salt, scryptParams) => {+ const buf = await scryptAsync(password, salt, HASH_BYTES, scryptParams);return buf.toString('hex');};+export const hashPassword = (password, salt) =>+ derivePasswordHash(password, salt, SCRYPT_PARAMS);++// Test-only: high-level auth suites verify service/middleware behavior with a+// cheap real-scrypt profile. The production hashPassword contract above stays+// pinned to SCRYPT_PARAMS so callers cannot accidentally create an incompatible+// stored credential.+export const __hashPasswordWithParamsForTests = (password, salt, scryptParams) =>+ derivePasswordHash(password, salt, scryptParams);+export const constantEqual = (aHex, bHex) => {const a = Buffer.from(aHex, 'hex');const b = Buffer.from(bHex, 'hex');diff --git a/server/lib/authGate.test.js b/server/lib/authGate.test.jsindex a516b17eff..33cf0a229c 100644--- a/server/lib/authGate.test.js+++ b/server/lib/authGate.test.js@@ -11,6 +11,21 @@ vi.mock('../lib/fileUtils.js', async () => {return makeProxy(actual);});+vi.mock('../../lib/portosAuthCore.js', async () => {+ const actual = await vi.importActual('../../lib/portosAuthCore.js');+ const testParams = { N: 1024, r: 8, p: 1, maxmem: 8 * 1024 * 1024 };+ const hashPassword = (password, salt) =>+ actual.__hashPasswordWithParamsForTests(password, salt, testParams);+ return {+ ...actual,+ hashPassword,+ verifyPasswordAgainst: async (auth, password) => {+ if (!auth?.enabled || !auth.passwordHash || !auth.salt || typeof password !== 'string' || password.length === 0) return false;+ return actual.constantEqual(await hashPassword(password, auth.salt), auth.passwordHash);+ },+ };+});+// Direct settings.json writes that also drop the getSettings() read cache —// see server/lib/settingsTestUtil.js for why the reset is required here// (a prior setPassword() warms the cache; a bypass-save() write leaves it stale).diff --git a/server/routes/auth.test.js b/server/routes/auth.test.jsindex 60682b1209..79c8030599 100644--- a/server/routes/auth.test.js+++ b/server/routes/auth.test.js@@ -13,6 +13,21 @@ vi.mock('../lib/fileUtils.js', async () => {return makeProxy(actual);});+vi.mock('../../lib/portosAuthCore.js', async () => {+ const actual = await vi.importActual('../../lib/portosAuthCore.js');+ const testParams = { N: 1024, r: 8, p: 1, maxmem: 8 * 1024 * 1024 };+ const hashPassword = (password, salt) =>+ actual.__hashPasswordWithParamsForTests(password, salt, testParams);+ return {+ ...actual,+ hashPassword,+ verifyPasswordAgainst: async (auth, password) => {+ if (!auth?.enabled || !auth.passwordHash || !auth.salt || typeof password !== 'string' || password.length === 0) return false;+ return actual.constantEqual(await hashPassword(password, auth.salt), auth.passwordHash);+ },+ };+});+// Reset settings.json through the shared helper so the getSettings() read cache// is dropped on every reset — see server/lib/settingsTestUtil.js. This suite// passes today only because buildApp()'s vi.resetModules() incidentally discardsdiff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 83f85aeedb..88dd816b0e 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -464,6 +464,7 @@ describe('stream error containment', () => {});afterEach(() => {+ vi.useRealTimers();vi.restoreAllMocks();});@@ -682,19 +683,19 @@ describe('stream error containment', () => {describe('initialization timeout — 3-second phase transition', () => {it('calls updateAgent with working phase after 3s when agent has not started working', async () => {+ vi.useFakeTimers();const { activeAgents } = await import('./agentState.js');const agents = cosAgentsMocks;const spawnPromise = spawnDirectly(minimalArgs);// Yield two microtask rounds so the getClaudeSettingsEnv await resolves and// the setTimeout is registered before we seed activeAgents.- await new Promise((r) => setTimeout(r, 10));+ await vi.advanceTimersByTimeAsync(10);// Manually seed the activeAgents map so the guard inside the timeout passes.activeAgents.set(minimalArgs.agentId, { process: fakeProcess });- // Wait past the 3-second threshold using real timers.- await new Promise((r) => setTimeout(r, 3100));+ await vi.advanceTimersByTimeAsync(3000);expect(agents.updateAgent).toHaveBeenCalledWith(minimalArgs.agentId,@@ -705,9 +706,10 @@ describe('stream error containment', () => {activeAgents.delete(minimalArgs.agentId);fakeProcess.emit('close', 0);await spawnPromise.catch(() => {});- }, 10000);+ });it('does NOT crash when updateAgent rejects inside the timeout callback', async () => {+ vi.useFakeTimers();const { activeAgents } = await import('./agentState.js');// spawnDirectly calls updateAgent once synchronously (PID update at line ~406)// before the 3-second setTimeout fires. Allow that first call to resolve@@ -723,12 +725,13 @@ describe('stream error containment', () => {process.on('unhandledRejection', onUnhandled);const spawnPromise = spawnDirectly(minimalArgs);- await new Promise((r) => setTimeout(r, 10));+ await vi.advanceTimersByTimeAsync(10);activeAgents.set(minimalArgs.agentId, { process: fakeProcess });- // Wait for the timeout to fire and its async body to finish.- await new Promise((r) => setTimeout(r, 3100));+ // Advance the initialization threshold and let the callback's rejected+ // update settle without burning three seconds of wall clock.+ await vi.advanceTimersByTimeAsync(3000);process.off('unhandledRejection', onUnhandled);@@ -742,7 +745,7 @@ describe('stream error containment', () => {fakeProcess.emit('close', 0);await spawnPromise.catch(() => {});consoleSpy.mockRestore();- }, 10000);+ });});it('threads the ordered reviewers list (not a stale singular `reviewer`) into worktree cleanup', async () => {diff --git a/server/services/auth.test.js b/server/services/auth.test.jsindex 21f6ff5692..302a00801b 100644--- a/server/services/auth.test.js+++ b/server/services/auth.test.js@@ -1,4 +1,4 @@-import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { rmSync } from 'fs';import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';@@ -9,6 +9,25 @@ vi.mock('../lib/fileUtils.js', async () => {return makeProxy(actual);});+// High-level auth tests exercise state/session behavior, not production KDF+// throughput. Keep the real scrypt implementation with a small test cost;+// lib/sidecarAuthGate.test.js retains the production-parameter compatibility+// path shared by the main server and sidecars.+vi.mock('../../lib/portosAuthCore.js', async () => {+ const actual = await vi.importActual('../../lib/portosAuthCore.js');+ const testParams = { N: 1024, r: 8, p: 1, maxmem: 8 * 1024 * 1024 };+ const hashPassword = (password, salt) =>+ actual.__hashPasswordWithParamsForTests(password, salt, testParams);+ return {+ ...actual,+ hashPassword,+ verifyPasswordAgainst: async (auth, password) => {+ if (!auth?.enabled || !auth.passwordHash || !auth.salt || typeof password !== 'string' || password.length === 0) return false;+ return actual.constantEqual(await hashPassword(password, auth.salt), auth.passwordHash);+ },+ };+});+// Reset settings.json between tests so a password-set in one test doesn't bleed// into the next. The auth service uses the real settings.js, which writes to// PATHS.data → tempRoot.@@ -31,6 +50,10 @@ afterAll(() => {cleanup();});+afterEach(() => {+ vi.useRealTimers();+});+describe('auth service', () => {it('starts disabled when no password has been set', async () => {const auth = await import('./auth.js');@@ -162,16 +185,14 @@ describe('auth service', () => {});it('emits sessions:revoked-all on every auth-state change so the socket layer can kick connections', async () => {+ vi.useFakeTimers();const auth = await import('./auth.js');const events = [];auth.authEvents.on('sessions:revoked-all', () => events.push('event'));await auth.setPassword({ newPassword: 'correct-horse' }); // first-time enableawait auth.setPassword({ newPassword: 'new-horse', currentPassword: 'correct-horse' }); // rotateawait auth.clearPassword({ currentPassword: 'new-horse' }); // disable- // The emit is deferred via setImmediate so the response cookie can- // flush first — let the event loop tick before asserting.- // Kick event is deferred ~500ms so the response cookie can flush first.- await new Promise((resolve) => setTimeout(resolve, 600));+ await vi.advanceTimersByTimeAsync(500);expect(events.length).toBe(3);});@@ -221,22 +242,23 @@ describe('auth service', () => {});it('emits sessions:revoked-all on single-token logout too (kicks the tab\'s sockets)', async () => {+ vi.useFakeTimers();const auth = await import('./auth.js');await auth.setPassword({ newPassword: 'correct-horse' });const { token } = await auth.createSession();// Drain the setPassword's deferred-kick timer before we attach the// listener so it doesn't get counted against this test's expectation.- await new Promise((resolve) => setTimeout(resolve, 600));+ await vi.advanceTimersByTimeAsync(500);const events = [];auth.authEvents.on('sessions:revoked-all', () => events.push('event'));await auth.revokeSession(token);// Kick event is deferred ~500ms so the response cookie can flush first.- await new Promise((resolve) => setTimeout(resolve, 600));+ await vi.advanceTimersByTimeAsync(500);expect(events.length).toBe(1);// Revoking an unknown token must NOT fire — no state changed.await auth.revokeSession('not-a-real-token');// Kick event is deferred ~500ms so the response cookie can flush first.- await new Promise((resolve) => setTimeout(resolve, 600));+ await vi.advanceTimersByTimeAsync(500);expect(events.length).toBe(1);});});diff --git a/server/services/creativeDirector/orchestrator.test.js b/server/services/creativeDirector/orchestrator.test.jsindex 4717e85b44..3f060148a9 100644--- a/server/services/creativeDirector/orchestrator.test.js+++ b/server/services/creativeDirector/orchestrator.test.js@@ -1,4 +1,4 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { nextPendingScene, nextTaskKind, buildTimelineClips } from './orchestrator.js';import { presetToRenderParams } from '../../lib/creativeDirectorPresets.js';@@ -275,6 +275,11 @@ describe('advanceAfterSceneSettled', () => {__resetInflightState();});+ afterEach(() => {+ vi.useRealTimers();+ __resetInflightState();+ });+it('picks scene-2 (lowest-order pending) when scene-1 is accepted and scenes 2-6 are pending', async () => {const project = makeProject();// getProject called twice: initial fetch + fresh fetch before runSceneRender.@@ -662,6 +667,7 @@ describe('advanceAfterSceneSettled', () => {});it('renders after the seed frame job completes and sourceImageFile lands', async () => {+ vi.useFakeTimers();const project = seedProject('cd-seed-completes');const projectWithFrame = seedProject('cd-seed-completes', {treatment: {@@ -686,8 +692,7 @@ describe('advanceAfterSceneSettled', () => {// Fire the completion event — the defer listener re-advances.mockMediaJobEvents.emit('completed', seedJob(project.id, 'scene-1', 'completed'));- // Let the async poll + re-advance settle.- await new Promise((r) => setTimeout(r, 400));+ await vi.advanceTimersByTimeAsync(400);expect(mockRunSceneRender).toHaveBeenCalledTimes(1);const [, sceneArg] = mockRunSceneRender.mock.calls[0];@@ -696,6 +701,7 @@ describe('advanceAfterSceneSettled', () => {});it('renders text-to-video when the seed frame job fails (frame never lands)', async () => {+ vi.useFakeTimers();const project = seedProject('cd-seed-fails');localMod.getProject.mockResolvedValue(project);mockListJobs.mockReturnValue([seedJob(project.id, 'scene-1')]);@@ -707,8 +713,8 @@ describe('advanceAfterSceneSettled', () => {// queued/running, so the re-advance won't re-defer.mockListJobs.mockReturnValue([seedJob(project.id, 'scene-1', 'failed')]);mockMediaJobEvents.emit('failed', seedJob(project.id, 'scene-1', 'failed'));- // Poll runs to the deadline (no sourceImageFile ever) then renders.- await new Promise((r) => setTimeout(r, 3200));+ // Advance the bounded attach schedule without waiting on real time.+ await vi.advanceTimersByTimeAsync(2000);expect(mockRunSceneRender).toHaveBeenCalledTimes(1);expect(mockRunSceneRender.mock.calls[0][1].sceneId).toBe('scene-1');diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex 5f0a4304a8..548be147f0 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -50,6 +50,8 @@ const CODEX_TIMEOUT_MS = (() => {})();const DEFAULT_BIN = 'codex';+const DEFAULT_HARVEST_TIMEOUT_MS = 5000;+let harvestTimeoutMs = DEFAULT_HARVEST_TIMEOUT_MS;const codexImagesDir = (sessionId) =>join(homedir(), '.codex', 'generated_images', sessionId);@@ -354,7 +356,7 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle// Codex writes the PNG asynchronously while it's wrapping up the turn.// Empirically the file is on disk by the time `codex exec` exits, but// poll for a few seconds in case there's a flush lag on slow disks.- const harvested = await harvestGeneratedImage(sessionId, 5000);+ const harvested = await harvestGeneratedImage(sessionId, harvestTimeoutMs);if (!harvested) {return finalizeError(job, jobId, proc, noImageReason(stdoutTail));}@@ -430,7 +432,8 @@ async function harvestLatestImage(sessionId, timeoutMs) {while (Date.now() < deadline) {const latest = await latestGeneratedImageFile(sessionId);if (latest) return latest;- await new Promise((r) => setTimeout(r, 250));+ const remainingMs = Math.max(1, deadline - Date.now());+ await new Promise((r) => setTimeout(r, Math.min(250, remainingMs)));}return null;}@@ -510,4 +513,9 @@ export const _internals = {harvestLatestImage,harvestSessionLogImage,harvestGeneratedImage,+ setHarvestTimeoutForTests: (timeoutMs = DEFAULT_HARVEST_TIMEOUT_MS) => {+ harvestTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0+ ? timeoutMs+ : DEFAULT_HARVEST_TIMEOUT_MS;+ },};diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.jsindex c9f664db92..4f3e18b9e9 100644--- a/server/services/imageGen/codex.test.js+++ b/server/services/imageGen/codex.test.js@@ -67,11 +67,14 @@ const flush = () => new Promise((r) => setImmediate(r));beforeEach(async () => {spawnCalls.length = 0;imageGenEvents.removeAllListeners();+ codex._internals.setHarvestTimeoutForTests(10);await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});await mkdir(TEST_HOME, { recursive: true });});afterEach(async () => {+ vi.useRealTimers();+ codex._internals.setHarvestTimeoutForTests();await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});});@@ -382,14 +385,9 @@ describe('codex provider — image harvest', () => {child.exitCode = 0;child.emit('close', 0, null);- // Wait out the harvest poll window (5s) plus a buffer.- const deadline = Date.now() + 6000;- while (Date.now() < deadline && failedListener.mock.calls.length === 0) {- await new Promise((r) => setTimeout(r, 100));- }- expect(failedListener).toHaveBeenCalledTimes(1);+ await vi.waitFor(() => expect(failedListener).toHaveBeenCalledTimes(1));expect(failedListener.mock.calls[0][0].error).toMatch(/no image|account may not allow/i);- }, 10000);+ });it('captures the session id even when banner + long prompt echo arrive in a single >4KB stderr chunk', async () => {// Regression: with multi-KB comic-pipeline prompts, codex flushes thediff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.jsindex e3617f980a..f29cb69ff7 100644--- a/server/services/imageGen/grok.js+++ b/server/services/imageGen/grok.js@@ -60,6 +60,8 @@ const GROK_TIMEOUT_MS = (() => {})();const DEFAULT_BIN = 'grok';+const DEFAULT_HARVEST_TIMEOUT_MS = 5000;+let harvestTimeoutMs = DEFAULT_HARVEST_TIMEOUT_MS;// Aspect ratios grok's image_gen/image_edit tools accept. Width/height from// PortOS callers are mapped to the closest of these; a configured default@@ -340,7 +342,7 @@ async function runGrok(job, jobId, bin, args, {// exit, but poll a few seconds in case of flush lag on slow disks. The// harvest signature-sniffs the bytes so a text error, truncated file,// or non-image payload is never accepted into the gallery as a PNG.- const harvested = await harvestStagedImage(stagingPath, 5000);+ const harvested = await harvestStagedImage(stagingPath, harvestTimeoutMs);if (!harvested.found) {removeScratch();const prefix = harvested.invalid ? 'Grok wrote a non-image file at the directed path. ' : '';@@ -421,7 +423,8 @@ async function harvestStagedImage(stagingPath, timeoutMs) {sawInvalid = true;}}- await new Promise((r) => setTimeout(r, 250));+ const remainingMs = Math.max(1, deadline - Date.now());+ await new Promise((r) => setTimeout(r, Math.min(250, remainingMs)));}return { found: false, invalid: sawInvalid };}@@ -431,4 +434,9 @@ export const _internals = {harvestStagedImage,deriveAspectRatio,buildGrokPrompt,+ setHarvestTimeoutForTests: (timeoutMs = DEFAULT_HARVEST_TIMEOUT_MS) => {+ harvestTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0+ ? timeoutMs+ : DEFAULT_HARVEST_TIMEOUT_MS;+ },};diff --git a/server/services/imageGen/grok.test.js b/server/services/imageGen/grok.test.jsindex 2a1e7f2180..654323316e 100644--- a/server/services/imageGen/grok.test.js+++ b/server/services/imageGen/grok.test.js@@ -61,11 +61,14 @@ const closeChild = async (i = 0, code = 1) => {beforeEach(async () => {spawnCalls.length = 0;imageGenEvents.removeAllListeners();+ grok._internals.setHarvestTimeoutForTests(10);await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});await mkdir(TEST_ROOT, { recursive: true });});afterEach(async () => {+ vi.useRealTimers();+ grok._internals.setHarvestTimeoutForTests();await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});});@@ -245,25 +248,18 @@ describe('grok provider — directed-path harvest', () => {// Grok wrote a text error where the PNG should be.await mkdir(join(tmpdir(), `portos-grok-${job.jobId}`), { recursive: true });await writeFile(stagingPathFor(job.jobId), 'Error: could not generate');- await closeChild(0, 0);-- const deadline = Date.now() + 8000;- while (Date.now() < deadline && failedListener.mock.calls.length === 0) {- await new Promise((r) => setTimeout(r, 100));- }- expect(failedListener).toHaveBeenCalledTimes(1);+ spawnCalls[0].child.exitCode = 0;+ spawnCalls[0].child.emit('close', 0, null);+ await vi.waitFor(() => expect(failedListener).toHaveBeenCalledTimes(1));expect(failedListener.mock.calls[0][0].error).toMatch(/non-image file/);// The rejected junk never reaches the gallery. Scratch-dir removal is// fire-and-forget alongside the 'failed' event (not awaited before it),// so give it a moment to land on disk rather than racing it.expect(existsSync(join(FAKE_IMAGES_DIR, job.filename))).toBe(false);const scratchDir = join(tmpdir(), `portos-grok-${job.jobId}`);- const scratchDeadline = Date.now() + 3000;- while (Date.now() < scratchDeadline && existsSync(scratchDir)) {- await new Promise((r) => setTimeout(r, 50));- }+ await vi.waitFor(() => expect(existsSync(scratchDir)).toBe(false));expect(existsSync(scratchDir)).toBe(false);- }, 12000);+ });it('fails with the stdout narration when grok exits 0 but wrote no file', async () => {const failedListener = vi.fn();@@ -272,16 +268,11 @@ describe('grok provider — directed-path harvest', () => {await grok.generateImage({ prompt: 'a fox' });const child = spawnCalls[0].child;child.stdout.emit('data', Buffer.from('I cannot generate that image.\n'));- await closeChild(0, 0);-- // Wait out the harvest poll window (5s) plus a buffer.- const deadline = Date.now() + 8000;- while (Date.now() < deadline && failedListener.mock.calls.length === 0) {- await new Promise((r) => setTimeout(r, 100));- }- expect(failedListener).toHaveBeenCalledTimes(1);+ child.exitCode = 0;+ child.emit('close', 0, null);+ await vi.waitFor(() => expect(failedListener).toHaveBeenCalledTimes(1));expect(failedListener.mock.calls[0][0].error).toMatch(/I cannot generate that image/);- }, 12000);+ });it('fails with the stderr tail on a non-zero exit', async () => {const failedListener = vi.fn();diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex 3ef7a7d620..88706be24c 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -216,6 +216,14 @@ const sseJobs = new Map();let workerStarted = false;let initPromise = null;+const terminalOperations = new Set();++function trackTerminalOperation(operation) {+ const tracked = Promise.resolve(operation);+ terminalOperations.add(tracked);+ tracked.finally(() => terminalOperations.delete(tracked)).catch(() => {});+ return tracked;+}function findJob(jobId) {if (running && running.id === jobId) return running;@@ -635,6 +643,8 @@ function makeGenDispatcher(emitter, job, handlers) {async function runJob(job) {const sseEntry = ensureSseEntry(job.id);+ let resolveTerminalState;+ const terminalState = new Promise((resolve) => { resolveTerminalState = resolve; });let progressPersistDirty = false;let progressPersistTimer = null;let progressPersisting = null;@@ -699,6 +709,10 @@ async function runJob(job) {// (how far it got) — consumers gate the progress UI on status === 'running',// so the residual values are not displayed for terminal jobs.job.completedAt = new Date().toISOString();+ // Wake the lane finalizer without polling. Some providers emit their+ // terminal event just before their kickoff promise resolves; the promise+ // retains that signal until runJob reaches the await below.+ resolveTerminalState();const logPrefix = state === 'completed' ? '✅' : state === 'canceled' ? '🛑' : '❌';const logSuffix = state === 'failed' ? `: ${job.error}` : state === 'canceled' ? ' (was running)' : '';console.log(`${logPrefix} media-job [${job.id.slice(0, 8)}] ${state}${logSuffix}`);@@ -727,24 +741,30 @@ async function runJob(job) {broadcastSse(sseEntry, payload);},completed: (payload) => {- terminate('completed', (j) => { j.result = payload; })- .catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`));+ trackTerminalOperation(+ terminate('completed', (j) => { j.result = payload; })+ .catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`)),+ );},failed: (payload) => {// If cancelJob() flagged this job before the underlying gen reported// failure, treat the SIGTERM-induced failure as a clean cancel rather// than an error so /api/media-jobs?status=canceled works.if (job.cancelRequested) {- terminate('canceled', (j) => {- // Persist the reason so a late SSE reconnect after the live entry- // is cleaned up still gets a meaningful terminal frame from the- // archived state, rather than the generic "Canceled" fallback.- j.error = 'Canceled while running';- }).catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`));+ trackTerminalOperation(+ terminate('canceled', (j) => {+ // Persist the reason so a late SSE reconnect after the live entry+ // is cleaned up still gets a meaningful terminal frame from the+ // archived state, rather than the generic "Canceled" fallback.+ j.error = 'Canceled while running';+ }).catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`)),+ );return;}- terminate('failed', (j) => { j.error = payload.error || 'unknown error'; })- .catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`));+ trackTerminalOperation(+ terminate('failed', (j) => { j.error = payload.error || 'unknown error'; })+ .catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`)),+ );},};@@ -882,11 +902,10 @@ async function runJob(job) {handlers.failed({ error: err.message });}- // Wait for the underlying gen to settle (the gen modules emit completed/- // failed asynchronously after the proc closes — runJob's await above only- // gates the spawn, not the render finish). Handlers flip job.status to a- // terminal state; short-sleep poll so we don't busy-spin.- while (job.status === 'running') await sleep(100);+ // The gen modules emit completed/failed asynchronously after kickoff. Await+ // the explicit terminal signal rather than polling every 100ms; this makes+ // lane release immediate and gives tests a deterministic lifecycle to drain.+ await terminalState;dispatcher.detach();}@@ -1078,3 +1097,18 @@ export function __resetForTests() {// ENOENT writes doesn't poison subsequent persist() calls.persistChain = Promise.resolve();}++// Test-only deterministic settle hook. EventEmitter terminal handlers and+// persistence are intentionally fire-and-forget in production; tests use this+// instead of sleeping for an arbitrary wall-clock window before inspecting or+// removing their temporary data directory.+export async function __drainForTests() {+ while (terminalOperations.size > 0) {+ await Promise.allSettled([...terminalOperations]);+ }+ await persistChain.catch(() => {});+ // A settled terminal operation can schedule the archive snapshot in the+ // lane-finalizer microtask. Yield once and capture that tail as well.+ await Promise.resolve();+ await persistChain.catch(() => {});+}diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex a92caac16e..edb0e7f4b4 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -97,7 +97,10 @@ async function importFresh() {audioGenEvents = (await import('../audioGen/events.js')).audioGenEvents;}-const flush = () => new Promise((r) => setTimeout(r, 250));+const flush = async () => {+ await Promise.resolve();+ await mediaJobQueue?.__drainForTests();+};beforeEach(async () => {tempDataDir = mkdtempSync(join(tmpdir(), 'mediaJobQueue-test-'));@@ -115,6 +118,7 @@ beforeEach(async () => {afterEach(async () => {await flush();+ mediaJobQueue?.__resetForTests();if (tempDataDir && existsSync(tempDataDir)) {rmSync(tempDataDir, { recursive: true, force: true });}diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 823dc416e8..28862987b8 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -23,7 +23,7 @@import { peerBaseUrl } from '../../lib/peerUrl.js';import { peerFetch } from '../../lib/peerHttpClient.js';import { withAbortTimeout } from '../../lib/abortTimeout.js';-import { withBaseHashFlushBatch } from '../../lib/conflictJournal.js';+import { flushBaseHashes, withBaseHashFlushBatch } from '../../lib/conflictJournal.js';import { recordEvents, registerSubscriptionAdapter } from './recordEvents.js';import { getInstanceId, getPeers, enqueueReciprocalSync, UNKNOWN_INSTANCE_ID } from '../instances.js';import { peerSyncPushSchema } from '../../lib/validation.js';@@ -98,6 +98,25 @@ export {syncCosTasksWithAllPeers,} from './peerCosSync.js';+// Fire-and-forget work must remain non-blocking in production, but it still+// needs an explicit lifecycle so shutdown/tests can wait for it. Without this+// registry, an initial push can enqueue subscription/cursor writes after a+// test has started removing its temporary PATHS.data tree, producing an+// intermittent ENOTEMPTY teardown failure.+const backgroundOperations = new Set();++function trackBackgroundOperation(operation) {+ const tracked = Promise.resolve(operation);+ backgroundOperations.add(tracked);+ tracked.finally(() => backgroundOperations.delete(tracked)).catch(() => {});+ return tracked;+}++async function drainBackgroundOperations() {+ while (backgroundOperations.size > 0) {+ await Promise.allSettled([...backgroundOperations]);+ }+}// --- Subscription CRUD --------------------------------------------------@@ -254,9 +273,9 @@ export async function subscribePeer({ peerId, recordKind, recordId }, opts = {})// result lastPushedHash will short-circuit anyway. Callers that need a// forced re-push can call pushRecordToPeer(sub) directly.if (created && !opts.adoptedFromReverse) {- const initialPush = pushRecordToPeer(sub).catch((err) => {+ const initialPush = trackBackgroundOperation(pushRecordToPeer(sub).catch((err) => {console.log(`⚠️ peerSync: initial push failed for ${sub.id}: ${err.message}`);- });+ }));// Fan-out callers await the push inside a flush batch so its base-hash// stamps land before the batch's terminal flush; the default path leaves it// fire-and-forget so a single subscribe never blocks on a slow peer.@@ -637,9 +656,9 @@ export async function triggerPushForRecord(recordKind, recordId) {// (we'd be pushing for nothing), (3) a subsequent edit landed under a// newer hash. Reading the live record by id makes the debounced fire// safe against all three.- pushFromFreshSubscription(subId).catch((err) => {+ trackBackgroundOperation(pushFromFreshSubscription(subId).catch((err) => {console.log(`⚠️ peerSync: scheduled push failed for ${subId}: ${err.message}`);- });+ }));}, DEBOUNCE_MS);if (typeof t.unref === 'function') t.unref();pendingTimers.set(sub.id, t);@@ -903,9 +922,9 @@ let onPeerOnline = null;export function installPeerSyncListener() {if (onUpdated) return;onUpdated = ({ recordKind, recordId }) => {- triggerPushForRecord(recordKind, recordId).catch((err) => {+ trackBackgroundOperation(triggerPushForRecord(recordKind, recordId).catch((err) => {console.log(`⚠️ peerSync: listener error for ${recordKind}/${recordId}: ${err.message}`);- });+ }));};recordEvents.on('updated', onUpdated);// ALSO listen for `deleted` events so soft-deletes propagate immediately via@@ -922,9 +941,9 @@ export function installPeerSyncListener() {// excludes them once their sub is gone. See dataSync.getSnapshot's// `forPeerId` scoping.)onDeleted = ({ recordKind, recordId }) => {- triggerPushForRecord(recordKind, recordId).catch((err) => {+ trackBackgroundOperation(triggerPushForRecord(recordKind, recordId).catch((err) => {console.log(`⚠️ peerSync: delete listener error for ${recordKind}/${recordId}: ${err.message}`);- });+ }));};recordEvents.on('deleted', onDeleted);// On peer:online, drive the local subscription state to convergence with@@ -948,7 +967,7 @@ export function installPeerSyncListener() {// both unconditionally per peer:online.onPeerOnline = (peer) => {if (!peer?.instanceId) return;- (async () => {+ trackBackgroundOperation((async () => {// peerHasCategory owns the (kind → category) mapping and the fullSync// short-circuit, so iterate the kinds and let it decide.for (const kind of PEER_SUBSCRIBABLE_KINDS) {@@ -970,7 +989,7 @@ export function installPeerSyncListener() {if (peer.fullSync === true && peer.id) {await enqueueReciprocalSync(peer.id).catch(() => {});}- })().catch(() => {});+ })().catch(() => {}));};instanceEvents.on('peer:online', onPeerOnline);}@@ -1000,20 +1019,27 @@ export function uninstallPeerSyncListener() {*/export async function __resetForTests() {uninstallPeerSyncListener();+ await drainBackgroundOperations();+ // A record-event handler that was already running when the first uninstall+ // happened may have scheduled a debounce before it settled. Clear that late+ // timer too, then wait for any timer callback that already started.+ uninstallPeerSyncListener();+ await drainBackgroundOperations();await drainWriteTail();+ await flushBaseHashes();}/*** Test-only: await the in-flight write/push tail WITHOUT resetting state or* detaching listeners, so a test can deterministically settle the fire-and-forget- * pushes a `subscribePeer` kicks off before asserting on the network mock. Awaits- * twice because a push's `persistPushSuccess` only enqueues on `writeTail` after- * its `peerFetch` resolves — i.e. a tick after the subscribe returned.+ * pushes a `subscribePeer` kicks off before asserting on the network mock.*/export async function __drainForTests() {+ await drainBackgroundOperations();await drainWriteTail();- await new Promise((r) => setTimeout(r, 0));- await drainWriteTail();+ // pushRecordToPeer deliberately keeps this disk write off the request path;+ // tests that redirect PATHS.data must still wait for it before rm.+ await flushBaseHashes();}// Register the subscription-lifecycle implementation with the import-lightdiff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex c776a35492..e63ccd4768 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -371,28 +371,23 @@ beforeEach(async () => {});afterEach(async () => {- // Drain in-flight fire-and-forget pushes before tearing down the tmpdir —- // otherwise persistPushSuccess can race the rm and leave ENOTEMPTY.- // Drain BOTH writeTails (peerSync's subscription state AND the tombstone- // cursor module's separate writeTail, since initCursor writes happen- // outside peerSync's lock). Three drain cycles with a 5ms macrotask- // delay between them — pushes scheduled by an earlier drain (e.g.- // ackDeletesUpTo from a settled push) only enqueue on the next tick, so- // we need more than one pass to fully quiesce the writeTail chains.- // __drainForTests double-awaits writeTail (one tick apart) so the- // persistPushSuccess that enqueues after peerFetch resolves is captured.- for (let i = 0; i < 3; i++) {+ try {+ // The peer-sync drain owns every fire-and-forget push/listener promise;+ // cursor writes are serialized on a separate tail. One deterministic pass+ // replaces the former fixed sleeps and prevents late writes racing rm.await __drainForTests();await __drainCursors();- await new Promise((r) => setTimeout(r, 5));+ await __resetForTests();+ await rm(tmp, { recursive: true, force: true });+ } finally {+ // Restore shared PATHS even when teardown itself fails so one test cannot+ // leak its temporary data root into the rest of the suite.+ PATHS.data = originalDataPath;+ PATHS.images = originalImagesPath;+ PATHS.imageRefs = originalImageRefsPath;+ PATHS.videos = originalVideosPath;+ PATHS.music = originalMusicPath;}- await __resetForTests();- await rm(tmp, { recursive: true, force: true });- PATHS.data = originalDataPath;- PATHS.images = originalImagesPath;- PATHS.imageRefs = originalImageRefsPath;- PATHS.videos = originalVideosPath;- PATHS.music = originalMusicPath;});describe('peerSync', () => {@@ -434,6 +429,28 @@ describe('peerSync', () => {expect(all).toHaveLength(1);});+ it('drains a non-blocking initial push before teardown', async () => {+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo', updatedAt: '2026-01-01T00:00:00Z' });+ let resolveFetch;+ vi.mocked(peerFetch).mockImplementation(() => new Promise((resolve) => {+ resolveFetch = resolve;+ }));++ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });+ await vi.waitFor(() => expect(peerFetch).toHaveBeenCalledTimes(1));++ let drained = false;+ const drain = __drainForTests().then(() => { drained = true; });+ await Promise.resolve();+ expect(drained).toBe(false);++ resolveFetch({ ok: true, json: async () => ({ missingAssets: [] }) });+ await drain;++ const persisted = await findPeerSubscription('peer-a', 'universe', 'u1');+ expect(persisted.lastPushedAt).toBeTruthy();+ });+it('does NOT re-push on idempotent re-subscribe (existing sub keeps its lastPushedAt)', async () => {// Regression: subscribePeer used to fire pushRecordToPeer fire-and-// forget on every call, even when the sub already existed. For thediff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.jsindex 5a5357ba62..f536ec255c 100644--- a/server/services/videoGen/grok.js+++ b/server/services/videoGen/grok.js@@ -50,6 +50,8 @@ const GROK_VIDEO_TIMEOUT_MS = (() => {})();const DEFAULT_BIN = 'grok';+const DEFAULT_HARVEST_TIMEOUT_MS = 10000;+let harvestTimeoutMs = DEFAULT_HARVEST_TIMEOUT_MS;// The clip lengths this module gates on live in lib/grokVideoClip.js — the one// list the Zod schemas and the client picker also derive from (#3022).@@ -256,7 +258,7 @@ async function runGrokVideo(job, jobId, bin, args, {removeUpload();return finalizeError(job, jobId, proc, `Grok video generation failed: ${reason}\n${tail}`);}- const harvested = await harvestStagedVideo(stagingPath, 10000);+ const harvested = await harvestStagedVideo(stagingPath, harvestTimeoutMs);if (!harvested.found) {removeScratch();removeUpload();@@ -332,7 +334,8 @@ async function harvestStagedVideo(stagingPath, timeoutMs) {sawInvalid = true;}}- await new Promise((r) => setTimeout(r, 250));+ const remainingMs = Math.max(1, deadline - Date.now());+ await new Promise((r) => setTimeout(r, Math.min(250, remainingMs)));}return { found: false, invalid: sawInvalid };}@@ -342,4 +345,9 @@ export const _internals = {harvestStagedVideo,buildGrokVideoPrompt,isMp4Header,+ setHarvestTimeoutForTests: (timeoutMs = DEFAULT_HARVEST_TIMEOUT_MS) => {+ harvestTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0+ ? timeoutMs+ : DEFAULT_HARVEST_TIMEOUT_MS;+ },};diff --git a/server/services/videoGen/grok.test.js b/server/services/videoGen/grok.test.jsindex 83ba92dc54..150e5ef19f 100644--- a/server/services/videoGen/grok.test.js+++ b/server/services/videoGen/grok.test.js@@ -79,11 +79,14 @@ const MP4_BYTES = Buffer.concat([beforeEach(async () => {spawnCalls.length = 0;videoGenEvents.removeAllListeners();+ grok._internals.setHarvestTimeoutForTests(10);await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});await mkdir(FAKE_DATA_DIR, { recursive: true });});afterEach(async () => {+ vi.useRealTimers();+ grok._internals.setHarvestTimeoutForTests();await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});});@@ -186,25 +189,18 @@ describe('videoGen/grok — harvest and finalize', () => {const job = await grok.generateVideo({ prompt: 'a fox' });await mkdir(scratchDirFor(job.jobId), { recursive: true });await writeFile(stagingPathFor(job.jobId), 'Error: render failed');- await closeChild(0, 0);-- const deadline = Date.now() + 13000;- while (Date.now() < deadline && failed.mock.calls.length === 0) {- await new Promise((r) => setTimeout(r, 100));- }- expect(failed).toHaveBeenCalledTimes(1);+ spawnCalls[0].child.exitCode = 0;+ spawnCalls[0].child.emit('close', 0, null);+ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));expect(failed.mock.calls[0][0].error).toMatch(/non-MP4 file/);expect(existsSync(join(FAKE_VIDEOS_DIR, job.filename))).toBe(false);// Scratch-dir removal is fire-and-forget alongside the 'failed' event// (not awaited before it), so give it a moment to land on disk rather// than racing it.const scratchDir = scratchDirFor(job.jobId);- const scratchDeadline = Date.now() + 3000;- while (Date.now() < scratchDeadline && existsSync(scratchDir)) {- await new Promise((r) => setTimeout(r, 50));- }+ await vi.waitFor(() => expect(existsSync(scratchDir)).toBe(false));expect(existsSync(scratchDir)).toBe(false);- }, 16000);+ });it('fails with the narration tail when grok exits 0 with no file', async () => {const failed = vi.fn();@@ -212,17 +208,13 @@ describe('videoGen/grok — harvest and finalize', () => {await grok.generateVideo({ prompt: 'a fox' });spawnCalls[0].child.stdout.emit('data', Buffer.from('I cannot animate that.\n'));- await closeChild(0, 0);-- const deadline = Date.now() + 13000;- while (Date.now() < deadline && failed.mock.calls.length === 0) {- await new Promise((r) => setTimeout(r, 100));- }- expect(failed).toHaveBeenCalledTimes(1);+ spawnCalls[0].child.exitCode = 0;+ spawnCalls[0].child.emit('close', 0, null);+ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));expect(failed.mock.calls[0][0].error).toMatch(/I cannot animate that/);// Video-flavored wording, not the image provider's.expect(failed.mock.calls[0][0].error).toMatch(/video/i);- }, 16000);+ });it('fails with the stderr tail on non-zero exit', async () => {const failed = vi.fn();