Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

test: bound Chrome teardown for HTML composition renders (#8678)

[._.]/ Adam Eivycb1f8917da2b
diff --git a/server/services/htmlComposition/index.test.js b/server/services/htmlComposition/index.test.js
index cf8dec9728..e54a30998e 100644
--- a/server/services/htmlComposition/index.test.js
+++ b/server/services/htmlComposition/index.test.js
@@ -4,8 +4,6 @@ import { mkdir, writeFile, readFile, readdir, symlink } from 'node:fs/promises';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { execFileSync, spawn } from 'node:child_process';
-import { once } from 'node:events';
-import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { chromium } from 'playwright-core';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
import { findFfmpeg } from '../../lib/ffmpeg.js';
@@ -13,6 +11,7 @@ import { PATHS } from '../../lib/fileUtils.js';
import { loadHistory } from '../videoGen/history.js';
import { videoGenEvents } from '../videoGen/events.js';
import { renderComposition, cancel } from './index.js';
+import { cleanupTestBrowser } from './testBrowserCleanup.js';
let endpoint;
vi.mock('../browserService.js', () => ({ cdpRequest: path => fetch(`${endpoint}${path}`) }));
@@ -62,33 +61,7 @@ describe.skipIf(!chrome || !ffmpeg)('HTML composition with real Chrome and ffmpe
browserSession = await browser.newBrowserCDPSession();
}, 30000);
- afterAll(async () => {
- let deadline;
- let escalation;
- try {
- // Wait for process exit, not stdio close: Chrome descendants can retain
- // stderr after the owned browser exits. Signal exits leave exitCode null.
- // Subscribe before disconnect/termination so fast exits cannot be missed.
- const running = proc && proc.exitCode === null && proc.signalCode === null;
- let processSettled = !running;
- let browserSettled = !browser;
- const exited = running ? once(proc, 'exit').then(() => { processSettled = true; }) : Promise.resolve();
- if (running) escalation = killWithEscalation(proc, {
- label: 'HTML composition test Chrome', stillRunning: () => true, delayMs: 2000,
- });
- await Promise.race([
- Promise.all([browser?.close().then(() => { browserSettled = true; }), exited]),
- new Promise((_, reject) => {
- deadline = setTimeout(() => reject(new Error(`HTML composition Chrome teardown stalled: browserSettled=${browserSettled}, processSettled=${processSettled}, exitCode=${proc?.exitCode}, signalCode=${proc?.signalCode}`)), 20000);
- }),
- ]);
- } finally {
- clearTimeout(deadline);
- clearTimeout(escalation);
- proc?.stderr?.destroy();
- cleanupTempDataRoots();
- }
- });
+ afterAll(() => cleanupTestBrowser({ browser, proc, cleanup: cleanupTempDataRoots }));
it('awaits every seek, encodes exactly 12 frames, keeps the target hidden and registers a thumbnail', async () => {
const input = await composition();
diff --git a/server/services/htmlComposition/testBrowserCleanup.js b/server/services/htmlComposition/testBrowserCleanup.js
new file mode 100644
index 0000000000..d240e22aa4
--- /dev/null
+++ b/server/services/htmlComposition/testBrowserCleanup.js
@@ -0,0 +1,52 @@
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
+
+async function withinDeadline(action, timeoutMs, stage) {
+ let timer;
+ try {
+ await Promise.race([
+ Promise.resolve().then(action),
+ new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`Test Chrome ${stage} exceeded ${timeoutMs}ms deadline`)), timeoutMs);
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+async function terminateOwnedChrome(proc) {
+ if (!proc || proc.exitCode !== null || proc.signalCode !== null) return;
+ let escalation;
+ let onClose;
+ // Subscribe before kill: even an immediate close must settle this promise.
+ const closed = new Promise(resolve => {
+ onClose = resolve;
+ proc.once('close', onClose);
+ });
+ try {
+ await withinDeadline(() => {
+ escalation = killWithEscalation(proc, {
+ label: 'HTML composition test Chrome',
+ stillRunning: () => proc.exitCode === null && proc.signalCode === null,
+ delayMs: 3000,
+ });
+ return closed;
+ }, 10000, 'child termination');
+ } finally {
+ clearTimeout(escalation);
+ proc.removeListener('close', onClose);
+ }
+}
+
+// Test-only lifecycle boundary. Disconnect failure must not strand the owned
+// child, and neither failure may prevent removal of temporary test data.
+export async function cleanupTestBrowser({ browser, proc, cleanup }) {
+ const errors = [];
+ try {
+ await withinDeadline(() => browser?.close(), 5000, 'browser disconnect').catch(error => errors.push(error));
+ await terminateOwnedChrome(proc).catch(error => errors.push(error));
+ } finally {
+ await cleanup();
+ }
+ if (errors.length) throw new AggregateError(errors, errors.map(error => error.message).join('; '));
+}
diff --git a/server/services/htmlComposition/testBrowserCleanup.test.js b/server/services/htmlComposition/testBrowserCleanup.test.js
new file mode 100644
index 0000000000..65d0723571
--- /dev/null
+++ b/server/services/htmlComposition/testBrowserCleanup.test.js
@@ -0,0 +1,104 @@
+import { EventEmitter } from 'node:events';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanupTestBrowser } from './testBrowserCleanup.js';
+
+function child() {
+ const proc = new EventEmitter();
+ proc.exitCode = null;
+ proc.signalCode = null;
+ proc.kill = vi.fn(signal => {
+ if (signal === 'SIGKILL') {
+ proc.signalCode = signal;
+ proc.emit('close', null, signal);
+ }
+ return true;
+ });
+ return proc;
+}
+
+describe('owned test Chrome cleanup', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it('does not wait for a signal-exited child whose close event already fired', async () => {
+ const proc = child();
+ proc.signalCode = 'SIGTERM';
+ proc.emit('close', null, 'SIGTERM');
+ const cleanup = vi.fn();
+ await cleanupTestBrowser({ proc, cleanup });
+ expect(proc.kill).not.toHaveBeenCalled();
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(proc.listenerCount('close')).toBe(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('observes synchronous termination and cancels escalation', async () => {
+ const proc = child();
+ proc.kill.mockImplementation(signal => {
+ proc.signalCode = signal;
+ proc.emit('close', null, signal);
+ });
+ await cleanupTestBrowser({ proc, cleanup: vi.fn() });
+ expect(proc.kill.mock.calls).toEqual([['SIGTERM']]);
+ expect(proc.listenerCount('close')).toBe(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('escalates an ignored SIGTERM and waits for delayed close', async () => {
+ const proc = child();
+ proc.kill.mockImplementation(signal => {
+ if (signal === 'SIGKILL') {
+ proc.signalCode = signal;
+ setTimeout(() => proc.emit('close', null, signal), 100);
+ }
+ });
+ const cleanup = vi.fn();
+ const result = cleanupTestBrowser({ proc, cleanup });
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(proc.kill.mock.calls).toEqual([['SIGTERM'], ['SIGKILL']]);
+ expect(cleanup).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(100);
+ await result;
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(proc.listenerCount('close')).toBe(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('still terminates the child and cleans data when disconnect rejects', async () => {
+ const proc = child();
+ const cleanup = vi.fn();
+ const result = cleanupTestBrowser({
+ browser: { close: () => Promise.reject(new Error('disconnect failed')) }, proc, cleanup,
+ });
+ const rejected = expect(result).rejects.toThrow('disconnect failed');
+ await vi.advanceTimersByTimeAsync(3000);
+ await rejected;
+ expect(proc.kill).toHaveBeenLastCalledWith('SIGKILL');
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('reports both deadlines and cleans data even if disconnect and child close never settle', async () => {
+ const proc = child();
+ proc.kill.mockImplementation(() => true);
+ const cleanup = vi.fn();
+ const result = cleanupTestBrowser({
+ browser: { close: () => new Promise(() => {}) }, proc, cleanup,
+ });
+ const rejected = expect(result).rejects.toThrow(
+ 'Test Chrome browser disconnect exceeded 5000ms deadline; Test Chrome child termination exceeded 10000ms deadline',
+ );
+ await vi.advanceTimersByTimeAsync(15000);
+ await rejected;
+ expect(proc.kill.mock.calls).toEqual([['SIGTERM'], ['SIGKILL']]);
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(proc.listenerCount('close')).toBe(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});