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: stabilize long Chrome composition capture proofs (#9394)
Adam Eivybd7fa149092a
diff --git a/scripts/vitestCiPool.js b/scripts/vitestCiPool.jsindex 73c4dfe660..0e6ce02774 100644--- a/scripts/vitestCiPool.js+++ b/scripts/vitestCiPool.js@@ -14,3 +14,42 @@ export function vitestCiPool({ maxWorkers = 4 } = {}) {if (!process.env.CI) return {};return { maxWorkers };}++// Keep these public Chrome/ffmpeg contracts in the full/CI runner, but give+// their captures a quiet group after parallel unit work (#9394).+export const EXCLUSIVE_CAPTURE_TESTS = [+ 'services/htmlComposition/index.test.js',+ 'services/musicVideo/documentRender.browser.test.js',+];++export function vitestCaptureProjects(test) {+ const { include, exclude, ...shared } = test;+ // Vite concatenates inherited include arrays: extending the broad root+ // glob would also run EVERY unit file in the capture project. Copy shared+ // worker settings explicitly and leave run-wide ownership at the root.+ delete shared.coverage;+ delete shared.globalSetup;+ return [+ {+ extends: false,+ test: {+ ...shared,+ name: 'parallel',+ include,+ exclude: [...exclude, ...EXCLUSIVE_CAPTURE_TESTS],+ sequence: { groupOrder: 0 },+ },+ },+ {+ extends: false,+ test: {+ ...shared,+ name: 'capture',+ include: EXCLUSIVE_CAPTURE_TESTS,+ exclude,+ fileParallelism: false,+ sequence: { groupOrder: 1 },+ },+ },+ ];+}diff --git a/scripts/vitestCiPool.test.js b/scripts/vitestCiPool.test.jsindex ae623b4614..7b6d00ad33 100644--- a/scripts/vitestCiPool.test.js+++ b/scripts/vitestCiPool.test.js@@ -1,4 +1,9 @@import { afterEach, describe, expect, it } from 'vitest';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';import { vitestCiPool } from './vitestCiPool.js';@@ -30,3 +35,73 @@ describe('vitestCiPool', () => {expect(vitestCiPool({ maxWorkers: 2 })).toEqual({ maxWorkers: 2 });});});++// Real workers catch inheritance/array-merging mistakes that can duplicate or+// drop suites, or defeat exclusion, despite correct-looking config objects.+it('runs the full server config with parallel units and exclusive, nonduplicated captures', () => {+ const scratch = mkdtempSync(join(tmpdir(), 'portos-capture-schedule-'));+ const fixture = join(scratch, 'fixture');+ const server = fileURLToPath(new URL('../server/', import.meta.url));+ try {+ mkdirSync(fixture);+ symlinkSync(join(server, 'node_modules'), join(fixture, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir');+ const put = (name, source) => {+ const path = join(fixture, name);+ mkdirSync(join(path, '..'), { recursive: true });+ writeFileSync(path, source);+ };+ put('vitest.setup.js', "if (process.env.NODE_ENV !== 'test') throw Error('unsafe worker env');");+ put('test/runTempRoot.js', `export { setup, teardown } from ${JSON.stringify(new URL('../server/test/runTempRoot.js', import.meta.url).href)};`);+ const common = `+ import { test, expect } from 'vitest';+ import { appendFileSync, existsSync, openSync, closeSync, unlinkSync, writeFileSync } from 'node:fs';+ import { setTimeout as delay } from 'node:timers/promises';+ const root = ${JSON.stringify(fixture)};+ const marker = name => root + '/' + name;+ const record = name => appendFileSync(marker('events'), name + '\\n');+ async function waitFor(name) {+ const until = Date.now() + 5000;+ while (!existsSync(marker(name))) {+ if (Date.now() > until) throw Error('parallel unit handshake failed');+ await delay(10);+ }+ }+ `;+ for (const [name, other] of [['unit-a', 'unit-b'], ['unit-b', 'unit-a']]) {+ put(`${name}.test.js`, common + `test('${name}', async () => {+ expect(existsSync(marker('capture-lock'))).toBe(false);+ writeFileSync(marker('${name}-started'), '');+ await waitFor('${other}-started');+ writeFileSync(marker('${name}-done'), '');+ record('${name}');+ });`);+ }+ for (const [name, path] of [+ ['html', 'services/htmlComposition/index.test.js'],+ ['music', 'services/musicVideo/documentRender.browser.test.js'],+ ]) {+ put(path, common + `test('${name}', async () => {+ expect(existsSync(marker('unit-a-done')) && existsSync(marker('unit-b-done'))).toBe(true);+ const lock = openSync(marker('capture-lock'), 'wx');+ try {+ record('${name}');+ await delay(200);+ } finally { closeSync(lock); unlinkSync(marker('capture-lock')); }+ });`);+ }+ put('services/voice/profiles.db.test.js', "throw Error('DB suite must stay excluded');");+ const env = { ...process.env, NODE_ENV: 'development', TMPDIR: scratch, TMP: scratch, TEMP: scratch };+ delete env.PORTOS_TEST_TEMP_ROOT;+ delete env.VITEST_FAST;+ const result = spawnSync(process.execPath, [join(server, 'node_modules/vitest/vitest.mjs'), 'run',+ '--config', join(server, 'vitest.config.js'), '--root', fixture, '--maxWorkers', '2',+ ], { cwd: server, env, encoding: 'utf8', timeout: 30000 });+ expect(result.error).toBeUndefined();+ expect(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(['html', 'music']);+ } finally {+ rmSync(scratch, { recursive: true, force: true });+ }+}, 35000);diff --git a/server/services/htmlComposition/index.test.js b/server/services/htmlComposition/index.test.jsindex 329efe9123..b270184f49 100644--- a/server/services/htmlComposition/index.test.js+++ b/server/services/htmlComposition/index.test.js@@ -1,4 +1,4 @@-import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { existsSync } from 'node:fs';import { mkdir, writeFile, readFile, readdir, rm, symlink } from 'node:fs/promises';import { join } from 'node:path';@@ -12,7 +12,16 @@ import { loadHistory } from '../videoGen/history.js';import { videoGenEvents } from '../videoGen/events.js';import { renderComposition, cancel } from './index.js';import { installMotionKit } from './motionKit.js';-import { _cleanupTestBrowser } from './testBrowserCleanup.js';+import { _cleanupTestBrowser, _waitForTestChrome, _testChromeCaptureArgs } from './testBrowserCleanup.js';++vi.mock('./encode.js', async importOriginal => {+ const actual = await importOriginal();+ const { _withTestCaptureDiagnostics } = await import('./testBrowserCleanup.js');+ return { ...actual, encodeComposition: _withTestCaptureDiagnostics(actual.encodeComposition, { getTestSignal: () => testSignal }) };+});++let testSignal;+beforeEach(({ signal }) => { testSignal = signal; });let endpoint;vi.mock('../browserService.js', () => ({ cdpRequest: path => fetch(`${endpoint}${path}`) }));@@ -48,15 +57,8 @@ async function composition(html = fixture(), directory = `compositions/${randomUdescribe.skipIf(!chrome || !ffmpeg)('HTML composition with real Chrome and ffmpeg', () => {beforeAll(async () => {const profile = join(PATHS.data, 'chrome-test-profile');- proc = spawn(chrome, ['--headless=new', '--no-sandbox', '--no-first-run', '--disable-background-networking', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] });- const ws = await new Promise((resolve, reject) => {- const timer = setTimeout(() => reject(new Error('Test Chrome did not start')), 20000);- proc.once('error', reject);- proc.stderr.on('data', bytes => {- const match = bytes.toString().match(/DevTools listening on (ws:\/\/\S+)/);- if (match) { clearTimeout(timer); resolve(match[1]); }- });- });+ proc = spawn(chrome, _testChromeCaptureArgs(profile), { stdio: ['ignore', 'ignore', 'pipe'] });+ const ws = await _waitForTestChrome(proc);endpoint = new URL(ws).origin.replace('ws:', 'http:');browser = await chromium.connectOverCDP(endpoint);browserSession = await browser.newBrowserCDPSession();diff --git a/server/services/htmlComposition/testBrowserCleanup.js b/server/services/htmlComposition/testBrowserCleanup.jsindex 63ae610c5e..e4a0cd5eb1 100644--- a/server/services/htmlComposition/testBrowserCleanup.js+++ b/server/services/htmlComposition/testBrowserCleanup.js@@ -1,5 +1,17 @@import { killWithEscalation } from '../../lib/killWithEscalation.js';+// These owned browsers render on explicit seek(t), not wall/display time.+// Chromium's display scheduler must not pace a song-length offline capture.+// Background flags match Playwright's standard Chromium launch posture.+export function _testChromeCaptureArgs(profile) {+ return [+ '--headless=new', '--no-sandbox', '--no-first-run', '--disable-background-networking',+ '--disable-background-timer-throttling', '--disable-backgrounding-occluded-windows',+ '--disable-renderer-backgrounding', '--disable-frame-rate-limit',+ '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank',+ ];+}+// Chrome writes its CDP address to stderr. Keep only a bounded tail and report// known failure categories: raw stderr can contain the user's profile path.export function _waitForTestChrome(proc, timeoutMs = 20000) {@@ -101,3 +113,88 @@ export async function _cleanupTestBrowser({ browser, proc, cleanup }) {}if (errors.length) throw new AggregateError(errors, errors.map(error => error.message).join('; '));}++// Wrap the REAL encoder only in browser tests. Never print paths, page source,+// process stderr or job IDs: a bounded numeric snapshot suffices to separate+// steady capture from a stuck seek, screenshot, pipe write or encoder drain.+export function _withTestCaptureDiagnostics(encode, { logIntervalMs = 15000, stallMs = 30000, getTestSignal } = {}) {+ return async (page, contract, outputPath, options = {}) => {+ const started = Date.now();+ let phase = 'setup';+ let phaseStarted = started;+ let lastProgress = started;+ let lastLog = started;+ let frame = 0;+ const frames = Math.round(contract.durationSec * contract.fps);+ const timings = { setup: 0, seek: 0, capture: 0, encode: 0 };+ const controller = new AbortController();+ const signal = AbortSignal.any([options.signal, getTestSignal?.(), controller.signal].filter(Boolean));+ const enter = next => {+ const now = Date.now();+ timings[phase] += now - phaseStarted;+ phase = next;+ phaseStarted = now;+ lastProgress = now;+ };+ const snapshot = () => {+ const now = Date.now();+ const totals = { ...timings, [phase]: timings[phase] + now - phaseStarted };+ return `phase=${phase} frames=${frame}/${frames} elapsedMs=${now - started} idleMs=${now - lastProgress} `+ + Object.entries(totals).map(([name, ms]) => `${name}Ms=${ms}`).join(' ');+ };+ const timer = setInterval(() => {+ const now = Date.now();+ if (now - lastProgress >= stallMs) {+ const error = new Error(`Test Chrome capture stalled; ${snapshot()}`);+ console.error(`❌ ${error.message}`);+ // The encoder's existing abort/close boundary terminates only its own+ // ffmpeg child. Existing CDP deadlines settle pending browser commands.+ controller.abort(error);+ clearInterval(timer);+ } else if (now - lastLog >= logIntervalMs) {+ console.log(`🎞️ Test Chrome capture progress; ${snapshot()}`);+ lastLog = now;+ }+ }, Math.min(1000, logIntervalMs, stallMs));+ timer.unref?.();+ const roundTrip = async (next, action) => {+ signal.throwIfAborted();+ enter(next);+ const result = await action();+ // A late response after the test deadline must never start another+ // capture or launch an encoder with an already-aborted signal.+ signal.throwIfAborted();+ enter('encode');+ return result;+ };+ const tracedPage = {+ ...page,+ check() { signal.throwIfAborted(); page.check(); },+ evaluate(...args) {+ return roundTrip(String(args[0]).startsWith('globalThis.portosComposition.seek(') ? 'seek' : 'setup', () => page.evaluate(...args));+ },+ send(...args) {+ return roundTrip(args[0] === 'Page.captureScreenshot' ? 'capture' : 'setup', () => page.send(...args));+ },+ };+ try {+ const result = await encode(tracedPage, contract, outputPath, {+ ...options,+ signal,+ onProgress(fraction, detail) {+ frame = detail?.frame ?? Math.round(fraction * frames);+ lastProgress = Date.now();+ options.onProgress?.(fraction, detail);+ },+ });+ signal.throwIfAborted();+ console.log(`🎞️ Test Chrome capture complete; ${snapshot()}`);+ return result;+ } catch (error) {+ console.error(`❌ Test Chrome capture failed; ${snapshot()}`);+ throw error;+ } finally {+ clearInterval(timer);+ }+ };+}diff --git a/server/services/htmlComposition/testBrowserCleanup.test.js b/server/services/htmlComposition/testBrowserCleanup.test.jsindex 686619ebec..7deeb2faa5 100644--- a/server/services/htmlComposition/testBrowserCleanup.test.js+++ b/server/services/htmlComposition/testBrowserCleanup.test.js@@ -1,6 +1,6 @@import { EventEmitter } from 'node:events';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { _cleanupTestBrowser, _waitForTestChrome } from './testBrowserCleanup.js';+import { _cleanupTestBrowser, _waitForTestChrome, _withTestCaptureDiagnostics } from './testBrowserCleanup.js';function child() {const proc = new EventEmitter();@@ -75,6 +75,101 @@ describe('test Chrome startup', () => {});});+describe('real capture diagnostics boundary', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });+ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it('keeps live capture moving and forwards progress/results with bounded numeric phase timings', async () => {+ const page = { check: vi.fn(), evaluate: vi.fn(), send: vi.fn() };+ const progress = vi.fn();+ const encode = _withTestCaptureDiagnostics(async (traced, contract, path, options) => {+ expect(path).toBe('/private/example-output.mp4');+ expect(options.offsetSec).toBe(10);+ for (let n = 0; n < 3; n++) {+ page.evaluate.mockImplementationOnce(async () => { await vi.advanceTimersByTimeAsync(10000); });+ page.send.mockImplementationOnce(async () => { await vi.advanceTimersByTimeAsync(10000); });+ await traced.evaluate(`globalThis.portosComposition.seek(${10 + n})`);+ await traced.send('Page.captureScreenshot', { format: 'png' });+ options.onProgress((n + 1) / 3, { frame: n + 1, frames: 3 });+ expect(options.signal.aborted).toBe(false);+ }+ return { sampleHistogram: { 1: 3 } };+ });+ await expect(encode(page, { durationSec: 3, fps: 1 }, '/private/example-output.mp4', { onProgress: progress, offsetSec: 10 }))+ .resolves.toEqual({ sampleHistogram: { 1: 3 } });+ expect(progress.mock.calls).toEqual([[1 / 3, { frame: 1, frames: 3 }], [2 / 3, { frame: 2, frames: 3 }], [1, { frame: 3, frames: 3 }]]);+ expect(page.evaluate.mock.calls.map(([expression]) => expression)).toEqual([+ 'globalThis.portosComposition.seek(10)', 'globalThis.portosComposition.seek(11)', 'globalThis.portosComposition.seek(12)',+ ]);+ const lines = console.log.mock.calls.map(([line]) => line);+ expect(lines).toHaveLength(5);+ expect(lines.at(-1)).toContain('frames=3/3 elapsedMs=60000 idleMs=0 setupMs=0 seekMs=30000 captureMs=30000 encodeMs=0');+ expect(lines.join('\n')).not.toContain('example-output');+ expect(console.error).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });++ it('aborts a stalled encoder drain with its last completed frame and clears the watchdog', async () => {+ let ownedStopped = false;+ const encode = _withTestCaptureDiagnostics(async (page, contract, path, { signal, onProgress }) => {+ await page.evaluate('globalThis.portosComposition.seek(0)');+ await page.send('Page.captureScreenshot');+ onProgress(1, { frame: 1, frames: 1 });+ await new Promise((resolve, reject) => signal.addEventListener('abort', () => {+ ownedStopped = true;+ reject(signal.reason);+ }, { once: true }));+ });+ const result = encode({ evaluate: async () => {}, send: async () => {} }, { durationSec: 1, fps: 1 }, '/private/example-output.mp4');+ const rejected = expect(result).rejects.toThrow('Test Chrome capture stalled; phase=encode frames=1/1 elapsedMs=30000 idleMs=30000');+ await vi.advanceTimersByTimeAsync(30000);+ await rejected;+ expect(ownedStopped).toBe(true);+ expect(console.error.mock.calls.flat().join('\n')).not.toContain('example-output');+ expect(vi.getTimerCount()).toBe(0);+ });++ it('stops a late browser response after the test deadline before starting an encoder', async () => {+ const deadline = new AbortController();+ const timedOut = new Error('Test deadline');+ let reply;+ const response = new Promise(resolve => { reply = resolve; });+ const startedEncoder = vi.fn();+ const encode = _withTestCaptureDiagnostics(async page => {+ await page.send('Emulation.setDeviceMetricsOverride');+ page.check();+ startedEncoder();+ }, { getTestSignal: () => deadline.signal });+ const result = encode({ send: () => response, check() {} }, { durationSec: 1, fps: 12 }, '/private/example-output.mp4');+ const rejected = expect(result).rejects.toBe(timedOut);+ deadline.abort(timedOut);+ reply();+ await rejected;+ expect(startedEncoder).not.toHaveBeenCalled();+ expect(console.error.mock.calls.flat().join('\n')).toContain('phase=setup frames=0/12');+ expect(vi.getTimerCount()).toBe(0);+ });++ it('preserves a caller cancellation and removes diagnostics on the failure path', async () => {+ const controller = new AbortController();+ const canceled = new Error('Render canceled');+ const encode = _withTestCaptureDiagnostics(async (page, contract, path, { signal }) => {+ controller.abort(canceled);+ signal.throwIfAborted();+ });+ await expect(encode({}, { durationSec: 1, fps: 12 }, '/private/example-output.mp4', { signal: controller.signal }))+ .rejects.toBe(canceled);+ expect(vi.getTimerCount()).toBe(0);+ });+});+describe('owned test Chrome cleanup', () => {beforeEach(() => {vi.useFakeTimers();diff --git a/server/services/musicVideo/documentRender.browser.test.js b/server/services/musicVideo/documentRender.browser.test.jsindex 3f3f771959..486c4be784 100644--- a/server/services/musicVideo/documentRender.browser.test.js+++ b/server/services/musicVideo/documentRender.browser.test.js@@ -5,7 +5,7 @@* every time, and carries the master song. Skips without Chrome or ffmpeg.*/-import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { existsSync } from 'node:fs';import { copyFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';import { join } from 'node:path';@@ -26,6 +26,15 @@ vi.mock('../promptRunner.js', () => ({},}));+vi.mock('../htmlComposition/encode.js', async importOriginal => {+ const actual = await importOriginal();+ const { _withTestCaptureDiagnostics } = await import('../htmlComposition/testBrowserCleanup.js');+ return { ...actual, encodeComposition: _withTestCaptureDiagnostics(actual.encodeComposition, { getTestSignal: () => testSignal }) };+});++let testSignal;+beforeEach(({ signal }) => { testSignal = signal; });+let endpoint;vi.mock('../browserService.js', () => ({ cdpRequest: (path) => fetch(`${endpoint}${path}`) }));vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {@@ -39,7 +48,7 @@ const { importDocumentTemplate } = await import('./compositionDocument.js');const { generateMixedMediaDocument, regenerateMixedMediaSection, acceptMixedMediaDocument } = await import('./documentGeneration.js');const { buildDocumentPreview } = await import('./documentPreview.js');const projects = await import('./projects.js');-const { _cleanupTestBrowser } = await import('../htmlComposition/testBrowserCleanup.js');+const { _cleanupTestBrowser, _waitForTestChrome, _testChromeCaptureArgs } = await import('../htmlComposition/testBrowserCleanup.js');afterAll(() => cleanupTempDataRoots());@@ -54,15 +63,8 @@ describe.skipIf(!chrome || !ffmpeg)('layered template with real Chrome and ffmpelet browser;beforeAll(async () => {const profile = join(PATHS.data, 'chrome-test-profile');- proc = spawn(chrome, ['--headless=new', '--no-sandbox', '--no-first-run', '--disable-background-networking', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] });- const ws = await new Promise((resolve, reject) => {- const timer = setTimeout(() => reject(new Error('Test Chrome did not start')), 20000);- proc.once('error', reject);- proc.stderr.on('data', (bytes) => {- const match = bytes.toString().match(/DevTools listening on (ws:\/\/\S+)/);- if (match) { clearTimeout(timer); resolve(match[1]); }- });- });+ proc = spawn(chrome, _testChromeCaptureArgs(profile), { stdio: ['ignore', 'ignore', 'pipe'] });+ const ws = await _waitForTestChrome(proc);endpoint = new URL(ws).origin.replace('ws:', 'http:');browser = await chromium.connectOverCDP(endpoint);}, 30000);diff --git a/server/vitest.config.js b/server/vitest.config.jsindex f51202f445..89fe780982 100644--- a/server/vitest.config.js+++ b/server/vitest.config.js@@ -2,7 +2,7 @@ import { defineConfig } from 'vitest/config';import { mkdtempSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { vitestCiPool } from '../scripts/vitestCiPool.js';+import { vitestCaptureProjects, vitestCiPool } from '../scripts/vitestCiPool.js';import { DB_TEST_INCLUDE } from './vitest.config.db.js';import { sweepStaleRunRoots, writeOwnerFile } from './test/staleRunRoots.js';@@ -84,7 +84,7 @@ process.env.NODE_ENV = 'test';// engines), so every supported Node build respects it.process.env.NODE_DISABLE_COMPILE_CACHE = '1';-export default defineConfig({+const config = defineConfig({test: {...vitestCiPool(),// Workers get their own process.env — set it there as well as above.@@ -235,3 +235,9 @@ export default defineConfig({globalSetup: ['./test/runTempRoot.js'],}});++// Both projects share the safety env, setup files and time budgets. The+// root globalSetup owns one temp root across BOTH groups; project teardown+// must not remove it while another group still needs it.+config.test.projects = vitestCaptureProjects(config.test);+export default config;