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
fix: keep full local validation inside existing test budgets (#10356)
Adam Eivy4055ece3b0ac
diff --git a/AGENTS.md b/AGENTS.mdindex c89dbbee18..3b699595fd 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -24,6 +24,10 @@ npm run install:all # includes git submodule update --init --recursive# per workspace from the repository root to scope to one — both are Vitest:npm test --prefix server # Vitest (node) — ALSO globs ../scripts, ../lib, ../autofixernpm test --prefix client # Vitest (happy-dom) — component/unit tests+# Supported FULL local validation (same worker cap as CI). A focused file run+# is not a full-suite result; unbounded npm test can time out heavy cases on a+# loaded machine. See docs/CONTRIBUTING.md.+# PORTOS_PREGATE_MAX_WORKERS=4 npm test# No NODE_ENV prefix needed: server/vitest.config.js FORCES NODE_ENV=test (#4554),# because PortOS runs under PM2 with NODE_ENV=development and a suite that# inherits it aims at the real Postgres.diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.mdindex d4dec67ba4..2d9823e890 100644--- a/docs/CONTRIBUTING.md+++ b/docs/CONTRIBUTING.md@@ -149,6 +149,19 @@ npm run setup:db:testnpm run test:db```+Supported full local validation uses the CI worker budget. An unbounded+`npm test` can oversubscribe a loaded machine: real media, prompt-catalog,+and nested-worker cases then hit their existing budgets. A green focused+file run is evidence for that file only, not a full-suite result.++```bash+# Server, then client. The value only lowers each workspace cap (client stays at 2).+PORTOS_PREGATE_MAX_WORKERS=4 npm test++# Focused evidence for one file:+npm test --prefix server -- services/creativeDirector/videoAssembly.test.js+```+For release validation, run `npm run test:db` after the server and clientsuites finish rather than alongside them. A concurrent run is supported —the database restore suite drains a timed-out case before the next one touchesdiff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.mdindex f59e720d85..5cb4317a70 100644--- a/docs/GITHUB_ACTIONS.md+++ b/docs/GITHUB_ACTIONS.md@@ -139,7 +139,9 @@ On GitHub Actions, `CI=true` caps the server Vitest runner at `maxWorkers: 4``client/vitest.config.js`). Standard Linux runners for public repositories are[4 vCPU / 16GB](https://docs.github.com/en/actions/reference/runners/github-hosted-runners);uncapped forks oversubscribe those cores during transform. Local `npm test`-is unbounded. `npm run pregate` exports `PORTOS_PREGATE_MAX_WORKERS` (default 4,+is unbounded so a developer machine can use every core. The supported full+local validation is `PORTOS_PREGATE_MAX_WORKERS=4 npm test` (see+`docs/CONTRIBUTING.md`); a focused file run is not that result. `npm run pregate` exports `PORTOS_PREGATE_MAX_WORKERS` (default 4,overridable) so concurrent worktree gates on one host bound their Vitestworkers; it can only lower a workspace's cap (client stays at 2), and directtest runs ignore it unless you set it. Divide the host between simultaneousdiff --git a/scripts/duplicateDetectionCleanup.test.js b/scripts/duplicateDetectionCleanup.test.jsindex 6d08ab4dc5..5689631c48 100644--- a/scripts/duplicateDetectionCleanup.test.js+++ b/scripts/duplicateDetectionCleanup.test.js@@ -4,7 +4,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'noimport { tmpdir } from 'node:os';import { join, dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';-import { createVitestTempFixture } from './lib/vitestTempRootFixture.js';+import { createVitestTempFixture, fixtureReadyFailureSource } from './lib/vitestTempRootFixture.js';// Pins the regression uniquely: a different worker's --bail=1 failure cancels a// duplicate-detection test while its body still owns store writes into the@@ -31,14 +31,7 @@ it('drains duplicate-detection fixture writes after another worker triggers failreturn;`);expect(source).toContain('await cancelled;');writeFileSync(join(fixture, 'lifecycle.test.js'), source);- writeFileSync(join(fixture, 'failure.test.js'), `- import { it, expect } from 'vitest';- import { existsSync } from 'node:fs';- it('controlled sibling failure', async () => {- await expect.poll(() => existsSync(${JSON.stringify(ready)}), { timeout: 10000 }).toBe(true);- throw new Error('controlled sibling failure');- });- `);+ writeFileSync(join(fixture, 'failure.test.js'), fixtureReadyFailureSource(ready));const workerIndex = args.indexOf('--maxWorkers');args[workerIndex + 1] = '2';args.push('--bail=1');diff --git a/scripts/lib/vitestTempRootFixture.js b/scripts/lib/vitestTempRootFixture.jsindex 65908e861d..e8689136e2 100644--- a/scripts/lib/vitestTempRootFixture.js+++ b/scripts/lib/vitestTempRootFixture.js@@ -1,6 +1,6 @@// Dependency-free subprocess fixtures: each workspace runs its own lifecycle cases.-import { mkdirSync, symlinkSync, writeFileSync } from 'node:fs';-import { join } from 'node:path';+import { existsSync, mkdirSync, symlinkSync, watch, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';const repo = fileURLToPath(new URL('../../', import.meta.url));@@ -40,3 +40,60 @@ export function createVitestTempFixture(host, workspace, body) {options: { cwd: join(repo, workspace), env, encoding: 'utf8', timeout: 20000 },};}++const READY_POLL_MS = 15;++function readinessAborted(signal) {+ const error = new Error('fixture readiness wait aborted');+ error.name = 'AbortError';+ if (signal?.reason) error.cause = signal.reason;+ return error;+}++/**+ * Resolve when `file` exists. `signal` is the only failure boundary — the+ * caller's test or process completion — so a sibling that is still importing+ * can still publish readiness. A shorter inner clock expires first and skips+ * the scenario the wait exists to run.+ */+export function waitForFixtureReady(file, { signal } = {}) {+ if (existsSync(file)) return Promise.resolve();+ if (signal?.aborted) return Promise.reject(readinessAborted(signal));+ return new Promise((resolve, reject) => {+ let settled = false;+ let watcher;+ let timer;+ const finish = (error) => {+ if (settled) return;+ settled = true;+ clearInterval(timer);+ watcher?.close();+ signal?.removeEventListener('abort', onAbort);+ if (error) reject(error);+ else resolve();+ };+ const onAbort = () => finish(readinessAborted(signal));+ const seen = () => { if (existsSync(file)) finish(); };+ signal?.addEventListener('abort', onAbort, { once: true });+ try {+ watcher = watch(dirname(file), seen);+ } catch (error) {+ finish(error);+ return;+ }+ timer = setInterval(seen, READY_POLL_MS);+ if (signal?.aborted) finish(readinessAborted(signal));+ else seen();+ });+}++/** Sibling worker source: fail only after the lifecycle worker publishes readiness. */+export function fixtureReadyFailureSource(readyFile) {+ return `import { it } from 'vitest';+import { waitForFixtureReady } from ${JSON.stringify(fileURLToPath(import.meta.url))};+it('controlled sibling failure', async ({ signal }) => {+ await waitForFixtureReady(${JSON.stringify(readyFile)}, { signal });+ throw new Error('controlled sibling failure');+});+`;+}diff --git a/scripts/lib/vitestTempRootFixture.test.js b/scripts/lib/vitestTempRootFixture.test.jsnew file mode 100644index 0000000000..d86c496562--- /dev/null+++ b/scripts/lib/vitestTempRootFixture.test.js@@ -0,0 +1,42 @@+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { describe, expect, it } from 'vitest';+import { waitForFixtureReady } from './vitestTempRootFixture.js';++describe('waitForFixtureReady', () => {+ it('resolves for a file that is already present and for one that appears later', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'fixture-ready-'));+ try {+ const present = join(dir, 'present');+ writeFileSync(present, 'ready');+ await expect(waitForFixtureReady(present)).resolves.toBeUndefined();++ const later = join(dir, 'later');+ const pending = waitForFixtureReady(later);+ writeFileSync(later, 'ready');+ await expect(pending).resolves.toBeUndefined();+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it('rejects on the caller signal and ignores a file created after that abort', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'fixture-abort-'));+ try {+ const file = join(dir, 'ready');+ const controller = new AbortController();+ const pending = waitForFixtureReady(file, { signal: controller.signal });+ controller.abort();+ await expect(pending).rejects.toMatchObject({ name: 'AbortError' });+ writeFileSync(file, 'late');+ await new Promise(resolve => setTimeout(resolve, 40));+ await expect(Promise.race([+ pending.then(() => 'resolved', () => 'rejected'),+ new Promise(resolve => setTimeout(() => resolve('quiet'), 20)),+ ])).resolves.toBe('rejected');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/scripts/persistentMindProcessAuditCleanup.test.js b/scripts/persistentMindProcessAuditCleanup.test.jsindex 76106640d6..f6f6f273ff 100644--- a/scripts/persistentMindProcessAuditCleanup.test.js+++ b/scripts/persistentMindProcessAuditCleanup.test.js@@ -4,7 +4,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'noimport { tmpdir } from 'node:os';import { join, dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';-import { createVitestTempFixture } from './lib/vitestTempRootFixture.js';+import { createVitestTempFixture, fixtureReadyFailureSource } from './lib/vitestTempRootFixture.js';// Pins the regression uniquely: a different worker's --bail=1 failure cancels a// process-audit test while its body still owns fixture writes (an archived job@@ -31,14 +31,7 @@ it('drains process-audit fixture writes after another worker triggers fail-fast'return;`);expect(source).toContain('await cancelled;');writeFileSync(join(fixture, 'lifecycle.test.js'), source);- writeFileSync(join(fixture, 'failure.test.js'), `- import { it, expect } from 'vitest';- import { existsSync } from 'node:fs';- it('controlled sibling failure', async () => {- await expect.poll(() => existsSync(${JSON.stringify(ready)}), { timeout: 10000 }).toBe(true);- throw new Error('controlled sibling failure');- });- `);+ writeFileSync(join(fixture, 'failure.test.js'), fixtureReadyFailureSource(ready));const workerIndex = args.indexOf('--maxWorkers');args[workerIndex + 1] = '2';args.push('--bail=1');diff --git a/scripts/vitestCiPool.js b/scripts/vitestCiPool.jsindex 924f81c2fe..d1a4570b03 100644--- a/scripts/vitestCiPool.js+++ b/scripts/vitestCiPool.js@@ -3,9 +3,14 @@* repositories are 4 vCPU / 16GB; uncapped forks oversubscribe those cores* during transform and swap.* Local `npm test` stays unbounded so a developer machine can use every core.- * `npm run pregate` is the exception: it exports PORTOS_PREGATE_MAX_WORKERS so- * several concurrent worktree gates share one host budget (#9773). The value- * can only LOWER a workspace's cap, never raise it past the proven one.+ * That is not the supported full-suite result: an unbounded run oversubscribes+ * a loaded machine and resource-heavy cases hit their existing budgets.+ * `PORTOS_PREGATE_MAX_WORKERS=4 npm test` is the supported full local+ * validation (same cap as CI). A focused file run is evidence for that file+ * only. See docs/CONTRIBUTING.md.+ * `npm run pregate` exports PORTOS_PREGATE_MAX_WORKERS so several concurrent+ * worktree gates share one host budget (#9773). The value can only LOWER a+ * workspace's cap, never raise it past the proven one.** fileParallelism stays at Vitest's default (true): four workers stay busy on* independent files. The DB suite already serializes files because those@@ -42,9 +47,20 @@ export const EXCLUSIVE_CAPTURE_TESTS = [// concurrent-run failure spent 3.746 seconds on startup/module import alone// (#9368). Isolate that resource-sensitive contract without changing its// deadline, process-incarnation checks, or fail-closed negative controls.+// Resource-heavy contracts that pass on a quiet worker and time out when an+// unbounded local run spends their budget on CPU contention (#10356). They run+// one at a time after the parallel group. Isolation does not raise their+// timeouts or drop their assertions.const EXCLUSIVE_TESTS = [...EXCLUSIVE_CAPTURE_TESTS,'services/databaseMaintenanceCutover.test.js',+ 'services/creativeDirector/videoAssembly.test.js',+ 'services/musicVideo/publishKit.test.js',+ 'services/musicVideo/sharingCopy.test.js',+ 'scripts/run-local-code-review.test.js',+ 'lib/workTracker.trackerInstructions.test.js',+ '../scripts/ci-test-plan.test.js',+ '../scripts/writersRoomPromotionCleanup.test.js',];export function vitestCaptureProjects(test) {diff --git a/scripts/vitestCiPool.test.js b/scripts/vitestCiPool.test.jsindex 53fe2bdfa5..c9915e736d 100644--- a/scripts/vitestCiPool.test.js+++ b/scripts/vitestCiPool.test.js@@ -125,6 +125,7 @@ it('runs parallel units before exclusive, nonduplicated captures and cutover pro['html', 'services/htmlComposition/index.test.js'],['music', 'services/musicVideo/documentRender.browser.test.js'],['cutover', 'services/databaseMaintenanceCutover.test.js'],+ ['assembly', 'services/creativeDirector/videoAssembly.test.js'],]) {put(path, common + `test('${name}', async () => {expect(existsSync(marker('unit-a-done')) && existsSync(marker('unit-b-done'))).toBe(true);@@ -146,7 +147,7 @@ it('runs parallel units before exclusive, nonduplicated captures and cutover proexpect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);const events = readFileSync(join(fixture, 'events'), 'utf8').trim().split('\n');expect(events.slice(0, 2).sort()).toEqual(['unit-a', 'unit-b']);- expect(events.slice(2).sort()).toEqual(['cutover', 'html', 'music']);+ expect(events.slice(2).sort()).toEqual(['assembly', 'cutover', 'html', 'music']);} finally {rmSync(scratch, { recursive: true, force: true });}diff --git a/scripts/writersRoomPromotionCleanup.test.js b/scripts/writersRoomPromotionCleanup.test.jsindex 78ef8fc54b..3bff594f59 100644--- a/scripts/writersRoomPromotionCleanup.test.js+++ b/scripts/writersRoomPromotionCleanup.test.js@@ -4,7 +4,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'noimport { tmpdir } from 'node:os';import { join, dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';-import { createVitestTempFixture } from './lib/vitestTempRootFixture.js';+import { createVitestTempFixture, fixtureReadyFailureSource } from './lib/vitestTempRootFixture.js';// Pins the regression uniquely: a different worker's --bail=1 failure cancels// the promotion test while its body still owns an asynchronous persistence call.@@ -34,14 +34,7 @@ it('drains promotion fixture writes after another worker triggers fail-fast', ()await vi.waitFor(() => expect(existsSync(${JSON.stringify(finished)})).toBe(true), { timeout: 1000 });});`);- writeFileSync(join(fixture, 'failure.test.js'), `- import { it, expect } from 'vitest';- import { existsSync } from 'node:fs';- it('controlled sibling failure', async () => {- await expect.poll(() => existsSync(${JSON.stringify(ready)}), { timeout: 10000 }).toBe(true);- throw new Error('controlled sibling failure');- });- `);+ writeFileSync(join(fixture, 'failure.test.js'), fixtureReadyFailureSource(ready));const workerIndex = args.indexOf('--maxWorkers');args[workerIndex + 1] = '2';args.push('--bail=1');diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex fa694e52c6..8840c81ff4 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -366,6 +366,10 @@ const HOISTED = ['warms the peer-sync route graph once, for the same vi.resetModules() reason'],['routes/peerSyncAuthIntegration.test.js', '../services/auth.js','warms the auth service the first test reaches before it can build an app'],+ ['lib/workTracker.trackerInstructions.test.js', '../services/taskPromptDefaults.js',+ 'the shipped prompt catalog cold-transforms past the expansion test budget under full-run contention'],+ ['lib/workTracker.trackerInstructions.test.js', './auditCatalog.js',+ 'the audit catalog loads with that same expansion and must stay outside the test budget'],];// Everything up to the first test/hook registration is module-collection scope.diff --git a/server/lib/workTracker.trackerInstructions.test.js b/server/lib/workTracker.trackerInstructions.test.jsindex 19743b4a20..2204a4aea3 100644--- a/server/lib/workTracker.trackerInstructions.test.js+++ b/server/lib/workTracker.trackerInstructions.test.js@@ -18,9 +18,15 @@ import {REPO_STUDY_LABEL_CONTRACT,formatOptionalIssueLabelFlags,} from './dispatchLabels.js';-import { formatTrackerInstructions, TRACKER_FILING_PRESETS, formatForgeCategoryLabelFlags } from './workTracker.js';+import { formatTrackerInstructions, TRACKER_FILING_PRESETS, formatForgeCategoryLabelFlags, resolveTrackerFilingBlock } from './workTracker.js';import { getAuditFilingPreset } from './auditCatalog.js';+// The shipped prompt catalog's cold transform exceeds the expansion test's+// budget when a full run is contending for CPU. File scope is unbudgeted+// (#7951, #10356).+const { DEFAULT_TASK_PROMPTS } = await import('../services/taskPromptDefaults.js');+const { AUDIT_TASK_TYPES, modeContractFor } = await import('./auditCatalog.js');+const REF_WATCH = { slugPrefix: 'ref-watch-', label: 'reference-watch', issueLabel: 'reference-watch' };const EXPECTED_PLAN = `This app records autonomous work in **PLAN.md** at the repo root ({repoPath}).@@ -248,10 +254,6 @@ describe('formatTrackerInstructions — ux preset (#3273)', () => {// If an audit prompt later adopts a placeholder the generator substitutes but// this chain does not, this test fails and names the token — add it here.it('leaves no unexpanded {token} in ANY shipped audit prompt, in either mode', async () => {- const { DEFAULT_TASK_PROMPTS } = await import('../services/taskPromptDefaults.js');- const { AUDIT_TASK_TYPES, modeContractFor } = await import('./auditCatalog.js');- const { resolveTrackerFilingBlock } = await import('./workTracker.js');-expect(AUDIT_TASK_TYPES.size).toBeGreaterThan(1);for (const taskType of AUDIT_TASK_TYPES) {const template = DEFAULT_TASK_PROMPTS[taskType];@@ -292,7 +294,6 @@ describe('formatTrackerInstructions — ux preset (#3273)', () => {// ux keeps one assertion of its own: it is the audit whose body most recently// hardcoded its posture instead of deferring to the injected banner.it('keeps the ux prompt on the injected tracker and mode seams', async () => {- const { DEFAULT_TASK_PROMPTS } = await import('../services/taskPromptDefaults.js');const template = DEFAULT_TASK_PROMPTS['ux'];expect(template).toContain('{trackerInstructions}');expect(template).toContain('{modeInstructions}');@@ -301,7 +302,6 @@ describe('formatTrackerInstructions — ux preset (#3273)', () => {describe('resolveTrackerFilingBlock — fileIssues audit types', () => {it('files for an audit type only when fileIssues is on', async () => {- const { resolveTrackerFilingBlock } = await import('./workTracker.js');const app = { repoPath: '/tmp/example-repo', workTracker: 'plan' };const off = await resolveTrackerFilingBlock(app, 'security', { fileIssues: false });expect(off.trackerInstructions).toBe('');@@ -314,7 +314,6 @@ describe('resolveTrackerFilingBlock — fileIssues audit types', () => {});it('still files always-filing types (reference-watch) without fileIssues', async () => {- const { resolveTrackerFilingBlock } = await import('./workTracker.js');const app = { repoPath: '/tmp/example-repo', workTracker: 'plan' };const block = await resolveTrackerFilingBlock(app, 'reference-watch');expect(block.workTracker).toBe('plan');@@ -361,7 +360,6 @@ describe('formatTrackerInstructions — plan-feature preset', () => {});it('is an always-filing type: files without a fileIssues flag (unlike audit types)', async () => {- const { resolveTrackerFilingBlock } = await import('./workTracker.js');const app = { repoPath: '/tmp/example-repo', workTracker: 'plan' };const block = await resolveTrackerFilingBlock(app, 'plan-feature', { fileIssues: false });expect(block.workTracker).toBe('plan');@@ -401,7 +399,6 @@ describe('formatTrackerInstructions — repo-study complete labels', () => {// provenance requirements (there is no source repository or license to inspect).describe('YouTube analysis tracker dispatch', () => {it('keeps external filing and local PLAN work aligned with completion metadata', async () => {- const { resolveTrackerFilingBlock } = await import('./workTracker.js');for (const tracker of ['github', 'gitlab', 'jira', 'plan']) {const block = await resolveTrackerFilingBlock({ repoPath: '/example', workTracker: tracker }, 'youtube-analysis');expect(block.workTracker).toBe(tracker);diff --git a/server/services/creativeDirector/videoAssembly.js b/server/services/creativeDirector/videoAssembly.jsindex 28d415a348..aa41417ff4 100644--- a/server/services/creativeDirector/videoAssembly.js+++ b/server/services/creativeDirector/videoAssembly.js@@ -58,6 +58,18 @@ async function prepareClips(project, history) {return segments;}+async function stopRender(timeline, jobId) {+ if (!jobId) return;+ // cancelRender is a no-op until the child handle exists. Retry only until+ // that first successful signal, then wait for the job to leave the active+ // set so a caller can reuse the project without overlapping ffmpeg.+ let signalled = false;+ while (['running', 'pending'].includes(timeline.getRenderJobStatus(jobId)?.status)) {+ if (!signalled) signalled = timeline.cancelRender(jobId) === true;+ await new Promise(resolve => setTimeout(resolve, 20));+ }+}+export async function runVideoAssembly(projectId) {if (inFlight.has(projectId)) return;inFlight.add(projectId);@@ -134,13 +146,13 @@ export async function runVideoAssembly(projectId) {}const deadline = Date.now() + 30 * 60 * 1000;while (!entry && Date.now() < deadline) {- if (!await isCurrent()) { timeline.cancelRender(jobId); return; }+ if (!await isCurrent()) { await stopRender(timeline, jobId); return; }const status = timeline.getRenderJobStatus(jobId);if (['error', 'canceled'].includes(status?.status)) throw fail(`Timeline assembly ${status.status}: ${status.error || 'Open Timeline to inspect the cut.'}`);entry = (await loadHistory()).find(row => row.id === jobId);if (!entry) await sleep(1000);}- if (!entry) { timeline.cancelRender(jobId); throw fail('Timeline assembly timed out. Partial clips remain available; inspect Timeline and Resume.'); }+ if (!entry) { await stopRender(timeline, jobId); throw fail('Timeline assembly timed out. Partial clips remain available; inspect Timeline and Resume.'); }if (!await isCurrent()) return;const path = safeUnder(PATHS.videos, entry.filename) ? join(PATHS.videos, entry.filename) : null;if (!path) throw fail('Timeline returned an invalid output path.');diff --git a/server/services/creativeDirector/videoAssembly.test.js b/server/services/creativeDirector/videoAssembly.test.jsindex 27674a4a20..2b1e59de13 100644--- a/server/services/creativeDirector/videoAssembly.test.js+++ b/server/services/creativeDirector/videoAssembly.test.js@@ -29,6 +29,37 @@ import { videoReviewStages, applyVideoReviewAction } from '../../lib/creativeDirimport { runVideoAssembly, validateVideoCut } from './videoAssembly.js';const exec = promisify(execFile);let ffmpeg;++// A timed-out assembly keeps the shared project id in flight and writes through+// the same mocks the next case resets. Invalidate the superseded project, wait+// until that run and its ffmpeg child have stopped, then install the next fixture.+function ownAssembly(promise) {+ const tracked = promise.finally(() => { if (state.owned === tracked) state.owned = null; });+ state.owned = tracked;+ return promise;+}++async function drainOwnedAssembly() {+ const jobId = state.project?.videoExecution?.assembly?.jobId ?? null;+ if (state.project?.videoExecution) {+ state.project = {+ ...state.project,+ status: 'paused',+ videoExecution: { ...state.project.videoExecution, authorized: false },+ };+ }+ const owned = state.owned;+ state.owned = null;+ if (owned) await owned.catch(() => {});+ if (!jobId) return;+ const { cancelRender, getRenderJobStatus } = await import('../videoTimeline/local.js');+ let signalled = false;+ while (['running', 'pending'].includes(getRenderJobStatus(jobId)?.status)) {+ if (!signalled) signalled = cancelRender(jobId) === true;+ await new Promise(resolve => setTimeout(resolve, 20));+ }+}+beforeAll(async () => {ffmpeg = await findFfmpeg();if (!ffmpeg || !await findFfprobe()) { ffmpeg = null; return; }@@ -36,8 +67,12 @@ beforeAll(async () => {for (const [index, color] of ['red', 'blue'].entries()) await exec(ffmpeg, ['-y', '-f', 'lavfi', '-i', `color=c=${color}:s=64x64:r=24:d=3`, '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-an', join(state.root, 'videos', `reactor-${index}.mp4`)]);await exec(ffmpeg, ['-y', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=2', join(state.root, 'music', 'example-bed.wav')]);}, 30000);-afterAll(async () => { await rm(state.root, { recursive: true, force: true }); });-beforeEach(() => {+afterAll(async () => {+ await drainOwnedAssembly();+ await rm(state.root, { recursive: true, force: true });+});+beforeEach(async () => {+ await drainOwnedAssembly();state.collection = [];state.tracks = [{ id: 'example-track', audioFilename: 'example-bed.wav' }];state.history = [0, 1].map(i => ({ id: `00000000-0000-4000-8000-00000000000${i}`, filename: `reactor-${i}.mp4`, width: 64, height: 64, fps: 24, numFrames: 72, modelId: 'reactor' }));@@ -55,7 +90,7 @@ it('assembles a one-minute standalone cut from fake Reactor clips through real Tstate.project.videoDraft.durationRange = { min: 60, max: 180 };state.project.treatment.scenes = Array.from({ length: 20 }, (_, order) => ({ ...state.project.treatment.scenes[order % 2], sceneId: `shot-${order}`, order }));state.project.videoExecution.inputRevision = videoConfigurationRevision(state.project);- await runVideoAssembly('example-video');+ await ownAssembly(runVideoAssembly('example-video'));expect(state.project.failureReason).toBeNull();expect(state.project.status).toBe('complete');expect(state.project.finalVideoId).not.toBe('00000000-0000-4000-8000-000000000001');@@ -78,17 +113,17 @@ it('holds real rough/final artifacts for distinct approvals and reuses the rendestate.project = applyVideoReviewAction(state.project, { action: 'approve', stage, revision: row.revision }, 'example-owner').project;};approve('script-shot-plan');- await runVideoAssembly('example-video');+ await ownAssembly(runVideoAssembly('example-video'));expect(state.project.status).toBe('stitching');expect(state.project.videoRoughCut.videoId).toBeTruthy();expect(state.project.videoFinalCut).toBeUndefined();const rendered = state.history.length;approve('rough-cut');- await runVideoAssembly('example-video');+ await ownAssembly(runVideoAssembly('example-video'));expect(state.project.videoFinalCut.videoId).toBe(state.project.videoRoughCut.videoId);expect(state.project.finalVideoId).toBeUndefined();approve('final-cut');- await runVideoAssembly('example-video');+ await ownAssembly(runVideoAssembly('example-video'));expect(state.project.status).toBe('complete');expect(state.history.length).toBe(rendered);}, 30000);@@ -100,7 +135,7 @@ it('assembles directive clips and repeats an imported standalone soundtrack in tstate.project.videoDraft.audio = { mode: 'imported', trackId: 'example-track' };state.project.videoExecution.choices.audio = { ...state.project.videoDraft.audio, filename: 'example-bed.wav' };state.project.videoExecution.inputRevision = videoConfigurationRevision(state.project);- await runVideoAssembly('example-video');+ await ownAssembly(runVideoAssembly('example-video'));expect(state.project.failureReason).toBeNull();expect(state.project.status).toBe('complete');const { getProject } = await import('../videoTimeline/local.js');@@ -134,7 +169,7 @@ it('mutes a selected shot in the real cut while retaining the next shot audio',state.project.videoExecution.choices.audio = { mode: 'native' };state.project.treatment.scenes[0].muteAudio = true;state.project.videoExecution.inputRevision = videoConfigurationRevision(state.project);- await runVideoAssembly('example-video');+ await ownAssembly(runVideoAssembly('example-video'));expect(state.project.failureReason).toBeNull();expect(state.project.status).toBe('complete');const output = join(state.root, 'videos', state.project.videoFinalCut.filename);@@ -158,10 +193,36 @@ it('uses the highest-scoring accepted scene midpoint on a three-scene timeline',evaluation: { score: [0.2, 0.9, 0.3][order] },}));state.project.videoExecution.inputRevision = videoConfigurationRevision(state.project);- await runVideoAssembly('example-video');+ await ownAssembly(runVideoAssembly('example-video'));expect(state.project.failureReason).toBeNull();const final = state.history.find(item => item.id === state.project.finalVideoId);const { stdout } = await exec(ffmpeg, ['-v', 'error', '-i', join(state.root, 'thumbnails', final.thumbnail), '-vf', 'scale=1:1', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], { encoding: 'buffer' });expect(stdout[2]).toBeGreaterThan(200);expect(stdout[0]).toBeLessThan(30);}, 30000);++it('drains a superseded assembly before the next case reuses the project and files', async context => {+ requireFfmpeg(context);+ state.project.targetDurationSeconds = 60;+ state.project.videoDraft.durationRange = { min: 60, max: 180 };+ state.project.treatment.scenes = Array.from({ length: 20 }, (_, order) => ({ ...state.project.treatment.scenes[order % 2], sceneId: `shot-${order}`, order }));+ state.project.videoExecution.inputRevision = videoConfigurationRevision(state.project);+ const owned = ownAssembly(runVideoAssembly('example-video'));+ const { getRenderJobStatus } = await import('../videoTimeline/local.js');+ await vi.waitFor(() => {+ const jobId = state.project.videoExecution?.assembly?.jobId;+ expect(['running', 'pending'].includes(getRenderJobStatus(jobId)?.status)).toBe(true);+ }, { timeout: 20000, interval: 20 });+ await drainOwnedAssembly();+ const sentinel = { id: 'next-case', marker: 'stable-next-case' };+ state.project = sentinel;+ state.history = [{ id: 'next-history' }];+ const sentinelFile = join(state.root, 'videos', 'next-case-owned.txt');+ await writeFile(sentinelFile, 'owned by the next case');+ await new Promise(resolve => setTimeout(resolve, 100));+ expect(state.project).toBe(sentinel);+ expect(state.history).toEqual([{ id: 'next-history' }]);+ const { readFile } = await import('node:fs/promises');+ expect(await readFile(sentinelFile, 'utf8')).toBe('owned by the next case');+ await expect(owned).resolves.toBeUndefined();+}, 30000);diff --git a/server/services/musicVideo/publishKit.test.js b/server/services/musicVideo/publishKit.test.jsindex eafee1f5b2..188aaa68f8 100644--- a/server/services/musicVideo/publishKit.test.js+++ b/server/services/musicVideo/publishKit.test.js@@ -5,7 +5,7 @@* record, and a rebuild frees the files the previous kit made. The copy is* one provider call (injected here) whose JSON lands editable on the kit.*/-import { describe, expect, it, vi, afterAll } from 'vitest';+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';import { existsSync } from 'node:fs';import { mkdir, readFile, writeFile } from 'node:fs/promises';import { join } from 'node:path';@@ -22,7 +22,28 @@ const projects = await import('./projects.js');const { saveHistory } = await import('../videoGen/history.js');const kit = await import('./publishKit.js');const ffmpeg = await findFfmpeg();+const watchedBuilds = new Set();+const startPublishKitBuild = kit.startPublishKitBuild.bind(kit);+vi.spyOn(kit, 'startPublishKitBuild').mockImplementation(async (id, ...rest) => {+ watchedBuilds.add(id);+ return startPublishKitBuild(id, ...rest);+});++// A timed-out encode keeps writing this file's shared video directory. Cancel+// the job and wait until it has left the active set before the next case runs.+async function drainPublishKitBuilds() {+ for (const id of watchedBuilds) {+ const active = kit.getActivePublishKitBuild(id);+ if (active) kit.cancelPublishKitBuild(active.jobId);+ }+ const pending = [...watchedBuilds].some(id => kit.getActivePublishKitBuild(id));+ if (!pending) return;+ await vi.waitFor(() => {+ expect([...watchedBuilds].every(id => kit.getActivePublishKitBuild(id) === null)).toBe(true);+ }, { timeout: 15000, interval: 20 });+}+afterEach(drainPublishKitBuilds);afterAll(() => cleanupTempDataRoots());const cue = (text, startSec, endSec) => ({ id: `lc-${startSec}`, text, startSec, endSec });@@ -109,6 +130,32 @@ describe('publishing kit build (#9281)', () => {}});+ it('stops a superseded kit build before the next case reuses the project', async () => {+ const { id } = await projects.createProject({ name: 'Example Held Build' });+ await mkdir(PATHS.videos, { recursive: true });+ await writeFile(join(PATHS.videos, 'held-master.mp4'), 'placeholder; encoding is held');+ await saveHistory([{ id: 'held-render', filename: 'held-master.mp4', durationSec: 36 }]);+ await projects.mutateProjectRecord(id, current => ({ project: { ...current, renderHistoryId: 'held-render' } }));+ const probe = vi.spyOn(ffmpegService, 'findFfmpeg').mockResolvedValue('example-ffmpeg');+ const encode = vi.spyOn(ffmpegService, 'runFfmpegProcess').mockImplementation(({ signal }) => new Promise(resolve => {+ if (signal?.aborted) resolve({ ok: false, reason: 'cancelled' });+ else signal?.addEventListener('abort', () => resolve({ ok: false, reason: 'cancelled' }), { once: true });+ }));+ try {+ await kit.startPublishKitBuild(id);+ await vi.waitFor(() => expect(kit.getActivePublishKitBuild(id)?.jobId).toBeTruthy());+ await drainPublishKitBuilds();+ await projects.mutateProjectRecord(id, current => ({ project: { ...current, marker: 'next-case' } }));+ await new Promise(resolve => setTimeout(resolve, 30));+ const project = await projects.getProject(id);+ expect(project.marker).toBe('next-case');+ expect(project.publishKit?.builtAt).toBeFalsy();+ } finally {+ probe.mockRestore();+ encode.mockRestore();+ }+ });+it.skipIf(!ffmpeg)('turns the final render into encodes, thumbnails, captions and chapters, and frees a rebuilt kit\'s old files', { timeout: 120000 }, async () => {const id = await renderedProject();await kit.startPublishKitBuild(id);diff --git a/server/services/musicVideo/sharingCopy.test.js b/server/services/musicVideo/sharingCopy.test.jsindex 3becb1e5f4..6862a64899 100644--- a/server/services/musicVideo/sharingCopy.test.js+++ b/server/services/musicVideo/sharingCopy.test.js@@ -70,6 +70,7 @@ const { videoGenEvents } = await import('../videoGen/events.js');const { enqueueJob } = await import('../mediaJobQueue/index.js');beforeEach(async () => {+ await drainOwnedExport();state.project = { id: 'mv-example', renderHistoryId: 'final-example' };state.jobs = []; state.spawns = []; state.outputSizes = []; state.duringPass = null; state.failPass = null; state.realEncode = false; state.saveError = null; state.missingFfmpeg = false; state.cleanupError = false; state.observerError = null; state.openedFiles = [];vi.clearAllMocks();@@ -80,12 +81,31 @@ beforeEach(async () => {});afterAll(cleanupTempDataRoots);+let ownedRun = null;+let ownedJobId = null;++async function drainOwnedExport() {+ if (ownedJobId) sharing.cancel(ownedJobId);+ const owned = ownedRun;+ ownedRun = null;+ ownedJobId = null;+ if (owned) await owned.catch(() => {});+}+async function runExport(jobId = '00000000-0000-4000-8000-000000000001') {+ await drainOwnedExport();+ ownedJobId = jobId;const queued = await sharing.prepareSharingCopy('mv-example');const params = state.jobs.find(j => j.id === queued.jobId).params;const completed = vi.fn(); const failed = vi.fn();videoGenEvents.once('completed', completed); videoGenEvents.once('failed', failed);- await sharing.runSharingCopy({ ...params, jobId });+ const run = sharing.runSharingCopy({ ...params, jobId });+ ownedRun = run;+ try {+ await run;+ } finally {+ if (ownedRun === run) ownedRun = null;+ }videoGenEvents.removeListener('completed', completed); videoGenEvents.removeListener('failed', failed);return { completed, failed };}@@ -258,6 +278,22 @@ describe('private sharing export workflow', () => {} finally { await file.close(); }});+ it('a cancelled export cannot write the next case project', async () => {+ let releasePass;+ state.duringPass = () => new Promise(resolve => { releasePass = resolve; });+ const pending = runExport('00000000-0000-4000-8000-000000000098');+ await vi.waitFor(() => expect(state.spawns.length).toBeGreaterThan(0));+ await new Promise(resolve => setImmediate(resolve));+ await drainOwnedExport();+ const sentinel = { id: 'mv-example', renderHistoryId: 'final-example', marker: 'next-case' };+ state.project = sentinel;+ releasePass();+ await pending;+ await new Promise(resolve => setTimeout(resolve, 30));+ expect(state.project).toBe(sentinel);+ expect(state.project.publishKit?.sharingCopy).toBeUndefined();+ });+it('closes the retained descriptor when source validation refuses delivery', async () => {await runExport('00000000-0000-4000-8000-000000000073');const { getProject } = await import('./projects.js');