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: drain owned browser groups before profile cleanup (#11639)
[._.]/078ed9b8e3e5
diff --git a/server/services/htmlComposition/browserProcessGroup.js b/server/services/htmlComposition/browserProcessGroup.jsnew file mode 100644index 0000000000..b29fbdd592--- /dev/null+++ b/server/services/htmlComposition/browserProcessGroup.js@@ -0,0 +1,78 @@+import { promisify } from 'node:util';+import { execFile } from '../../lib/childProcess.js';++const execFileAsync = promisify(execFile);++// Only numeric identity/state are read: command lines can contain private data.+async function liveMembers(pgid, timeout) {+ const { stdout } = await execFileAsync('ps', ['-A', '-o', 'pid=', '-o', 'pgid=', '-o', 'stat='], {+ timeout, maxBuffer: 4 * 1024 * 1024,+ });+ const rows = stdout.trim().split('\n').map(line => {+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s*$/.exec(line);+ if (!match) throw new Error('Composition browser group observation failed');+ return { pid: Number(match[1]), group: Number(match[2]), state: match[3] };+ });+ if (!rows.some(row => row.pid === process.pid)) throw new Error('Composition browser group observation incomplete');+ return rows.filter(row => row.group === pgid && !row.state.startsWith('Z'));+}++const safeSignal = signal => ['SIGTERM', 'SIGKILL'].includes(signal) ? signal : 'other';+const safePhase = phase => ['shutdown', 'drain'].includes(phase) ? phase : 'other';+const safeCode = code => ['EPERM', 'EACCES', 'EINVAL', 'ENOSYS'].includes(code) ? code : 'other';++export function signalBrowserProcessGroup(pgid, signal, state, phase) {+ if (state.error !== 'none') return;+ const key = signal === 'SIGTERM' ? 'term' : 'kill';+ try {+ process.kill(-pgid, signal);+ state[key] = 'accepted';+ } catch (error) {+ state[key] = error?.code === 'ESRCH' ? 'absent' : 'threw';+ if (error?.code !== 'ESRCH') {+ state.error = safeCode(error?.code);+ state.failedSignal = signal;+ state.failedPhase = phase;+ }+ }+}++// Only the retained, closed child's detached group is eligible. Zombies cannot+// write; a live leader at the departed PID means reuse and must not be signaled.+export async function drainBrowserProcessGroup(pgid, deadline, graceMs, state = { error: 'none' }) {+ const failure = message => {+ const code = state.error === 'none' ? 'none' : safeCode(state.error);+ const signal = state.error === 'none' ? 'none' : safeSignal(state.failedSignal);+ const phase = state.error === 'none' ? 'none' : safePhase(state.failedPhase);+ return Object.assign(new Error(`${message} (groupSignalError=${code}, groupFailedSignal=${signal}, groupFailedPhase=${phase})`), { code });+ };+ if (!Number.isSafeInteger(pgid) || pgid <= 1 || pgid === process.pid) {+ throw failure('Composition browser group identity unavailable');+ }+ let termAt;+ let killed = false;+ while (true) {+ const remaining = Math.floor(deadline - performance.now());+ if (remaining <= 0) throw failure('Composition browser group cleanup exceeded its deadline');+ let members;+ try { members = await liveMembers(pgid, remaining); }+ catch { throw failure('Composition browser group observation failed'); }+ if (!members.length) {+ if (state.error !== 'none') {+ const signal = safeSignal(state.failedSignal);+ const phase = safePhase(state.failedPhase);+ console.warn(`⚠️ Composition browser group quiesced after signal failure (code=${safeCode(state.error)}, signal=${signal}, phase=${phase})`);+ }+ return;+ }+ if (members.some(row => row.pid === pgid)) throw failure('Composition browser group identity changed');+ const signal = termAt === undefined ? 'SIGTERM'+ : !killed && performance.now() - termAt >= graceMs ? 'SIGKILL' : null;+ if (signal && state.error === 'none') {+ signalBrowserProcessGroup(pgid, signal, state, 'drain');+ if (termAt === undefined) termAt = performance.now();+ else killed = true;+ }+ await new Promise(resolve => setTimeout(resolve, Math.min(25, Math.max(1, deadline - performance.now()))));+ }+}diff --git a/server/services/htmlComposition/browserProcessGroup.test.js b/server/services/htmlComposition/browserProcessGroup.test.jsnew file mode 100644index 0000000000..5eb4c6f8eb--- /dev/null+++ b/server/services/htmlComposition/browserProcessGroup.test.js@@ -0,0 +1,126 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const observation = vi.hoisted(() => ({ read: vi.fn() }));+vi.mock('../../lib/childProcess.js', async () => {+ const { promisify } = await import('node:util');+ return { execFile: Object.assign(vi.fn(), { [promisify.custom]: observation.read }) };+});+const { drainBrowserProcessGroup, signalBrowserProcessGroup } = await import('./browserProcessGroup.js');+const group = 12345;+const snapshot = (...rows) => ({ stdout: [`${process.pid} 1 S`, ...rows].join('\n') });+let signal;+beforeEach(() => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });+ signal = vi.spyOn(process, 'kill').mockReturnValue(true);+ observation.read.mockReset().mockResolvedValue(snapshot());+});+afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });++it('does not signal an empty or zombie-only owned group', async () => {+ observation.read.mockResolvedValue(snapshot(`23456 ${group} Z`));+ await drainBrowserProcessGroup(group, 500, 100);+ expect(signal).not.toHaveBeenCalled();+ expect(observation.read).toHaveBeenCalledWith('ps', ['-A', '-o', 'pid=', '-o', 'pgid=', '-o', 'stat='], expect.objectContaining({ timeout: 500 }));+});++it('requires observed quiescence after accepted signals and escalates surviving descendants', async () => {+ observation.read.mockResolvedValue(snapshot(`23456 ${group} S`));+ let settled = false;+ const drain = drainBrowserProcessGroup(group, 500, 100).then(() => { settled = true; });+ await vi.advanceTimersByTimeAsync(100);+ expect(signal.mock.calls).toEqual([[-group, 'SIGTERM'], [-group, 'SIGKILL']]);+ expect(settled).toBe(false);+ observation.read.mockResolvedValue(snapshot(`23456 ${group} Z`));+ await vi.advanceTimersByTimeAsync(25);+ await drain;+ expect(settled).toBe(true);+});++it.each([+ ['reused leader', () => snapshot(`${group} ${group} S`), /identity changed/],+ ['malformed output', () => ({ stdout: 'invalid' }), /observation failed/],+ ['incomplete output', () => ({ stdout: '23456 1 S' }), /observation failed/],+])('refuses to signal on %s', async (_, result, error) => {+ observation.read.mockResolvedValue(result());+ await expect(drainBrowserProcessGroup(group, 500, 100)).rejects.toThrow(error);+ expect(signal).not.toHaveBeenCalled();+});++it('fails closed when process observation is unavailable without exposing output', async () => {+ observation.read.mockRejectedValue(new Error('/private/command'));+ await expect(drainBrowserProcessGroup(group, 500, 100)).rejects.toThrow(/^Composition browser group observation failed \(groupSignalError=none, groupFailedSignal=none, groupFailedPhase=none\)$/);+ expect(signal).not.toHaveBeenCalled();+});++it('rejects within the retained deadline if accepted signals do not stop writers', async () => {+ observation.read.mockResolvedValue(snapshot(`23456 ${group} S`));+ const verdict = expect(drainBrowserProcessGroup(group, 100, 25)).rejects.toThrow(/exceeded its deadline/);+ await vi.advanceTimersByTimeAsync(100);+ await verdict;+ expect(signal.mock.calls).toEqual([[-group, 'SIGTERM'], [-group, 'SIGKILL']]);+});++it.each(['EPERM', '/private/code'])('retains signal failure %s until the deadline without signaling again', async code => {+ observation.read.mockResolvedValue(snapshot(`23456 ${group} S`));+ signal.mockImplementation(() => { throw Object.assign(new Error('/private/path'), { code }); });+ const expected = code === 'EPERM' ? 'EPERM' : 'other';+ const verdict = expect(drainBrowserProcessGroup(group, 100, 25)).rejects.toThrow(`Composition browser group cleanup exceeded its deadline (groupSignalError=${expected}, groupFailedSignal=SIGTERM, groupFailedPhase=drain)`);+ await vi.advanceTimersByTimeAsync(100);+ await verdict;+ expect(signal).toHaveBeenCalledExactlyOnceWith(-group, 'SIGTERM');+});++it.each(['SIGTERM', 'SIGKILL'])('requires observed quiescence after failed %s, preserving one safe diagnostic', async failedSignal => {+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});+ observation.read.mockResolvedValue(snapshot(`23456 ${group} S`));+ signal.mockImplementation((_, name) => {+ if (name === failedSignal) throw Object.assign(new Error('/private'), { code: 'EPERM' });+ return true;+ });+ let settled = false;+ const drain = drainBrowserProcessGroup(group, 500, 25).then(() => { settled = true; });+ await vi.advanceTimersByTimeAsync(75);+ expect(settled).toBe(false);+ expect(signal).toHaveBeenCalledTimes(failedSignal === 'SIGTERM' ? 1 : 2);+ observation.read.mockResolvedValue(snapshot(`23456 ${group} Z`));+ await vi.advanceTimersByTimeAsync(25);+ await drain;+ expect(warning).toHaveBeenCalledExactlyOnceWith(`⚠️ Composition browser group quiesced after signal failure (code=EPERM, signal=${failedSignal}, phase=drain)`);+});++it('carries a shutdown failure into draining without another group signal', async () => {+ const state = { error: 'none' };+ signal.mockImplementation(() => { throw Object.assign(new Error('/private'), { code: 'EPERM' }); });+ signalBrowserProcessGroup(group, 'SIGTERM', state, 'shutdown');+ signalBrowserProcessGroup(group, 'SIGKILL', state, 'shutdown');+ observation.read.mockResolvedValueOnce(snapshot(`23456 ${group} S`)).mockResolvedValue(snapshot());+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const drain = drainBrowserProcessGroup(group, 500, 25, state);+ await vi.advanceTimersByTimeAsync(25);+ await drain;+ expect(signal).toHaveBeenCalledTimes(1);+ expect(state).toMatchObject({ error: 'EPERM', failedSignal: 'SIGTERM', failedPhase: 'shutdown' });+});++it.each(['observation', 'reuse'])('retains inherited failure when %s becomes unsafe', async kind => {+ if (kind === 'observation') observation.read.mockRejectedValue(new Error('/private'));+ else observation.read.mockResolvedValue(snapshot(`${group} ${group} S`));+ await expect(drainBrowserProcessGroup(group, 500, 25, { error: '/private/code' })).rejects.toThrow('(groupSignalError=other, groupFailedSignal=other, groupFailedPhase=other)');+ expect(signal).not.toHaveBeenCalled();+});++it('reobserves after ESRCH instead of treating a signal result as quiescence', async () => {+ signal.mockImplementation(() => { throw Object.assign(new Error('gone'), { code: 'ESRCH' }); });+ observation.read.mockResolvedValueOnce(snapshot(`23456 ${group} S`)).mockResolvedValue(snapshot());+ const drain = drainBrowserProcessGroup(group, 500, 100);+ await vi.advanceTimersByTimeAsync(25);+ await drain;+ expect(observation.read).toHaveBeenCalledTimes(2);+});+++it('redacts inherited fields in the successful-quiescence diagnostic', async () => {+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});+ await drainBrowserProcessGroup(group, 500, 25, { error: '/private/code', failedSignal: '/private/signal', failedPhase: '/private/phase' });+ expect(warning).toHaveBeenCalledExactlyOnceWith('⚠️ Composition browser group quiesced after signal failure (code=other, signal=other, phase=other)');+});diff --git a/server/services/htmlComposition/ownedBrowser.descendant.test.js b/server/services/htmlComposition/ownedBrowser.descendant.test.jsnew file mode 100644index 0000000000..93822a90f7--- /dev/null+++ b/server/services/htmlComposition/ownedBrowser.descendant.test.js@@ -0,0 +1,65 @@+import { it, expect, vi } from 'vitest';+import { spawn } from 'node:child_process';+import { mkdtemp, writeFile, rm } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++const fixture = vi.hoisted(() => ({ control: '', profile: '', child: null }));+vi.mock('../browserService.js', () => ({ loadConfig: async () => ({ chromePath: '/synthetic/chrome' }) }));+vi.mock('../../lib/childProcess.js', async original => ({+ ...await original(),+ spawn: (_command, args, options) => {+ fixture.profile = args.find(arg => arg.startsWith('--user-data-dir=')).slice('--user-data-dir='.length);+ const helper = `+ const fs = require('node:fs');+ const [profile, control] = process.argv.slice(1);+ const limit = setTimeout(() => process.exit(0), 5000);+ let terms = 0;+ process.on('SIGTERM', () => {+ if (++terms === 1) return;+ fs.writeFileSync(control + '/stopped', 'stopped');+ process.exit(0);+ });+ setInterval(() => {+ if (!fs.existsSync(control + '/write')) return;+ fs.mkdirSync(profile, { recursive: true });+ fs.writeFileSync(profile + '/late-write', 'synthetic');+ fs.writeFileSync(control + '/done', 'done');+ clearTimeout(limit);+ process.exit(0);+ }, 10);+ process.send('ready');+ `;+ const parent = `+ const { spawn } = require('node:child_process');+ const [helper, profile, control] = process.argv.slice(1);+ const child = spawn(process.execPath, ['-e', helper, profile, control], { stdio: ['ignore', 'ignore', 'inherit', 'ipc'] });+ child.once('message', () => process.stderr.write('DevTools listening on ws://127.0.0.1:12345/devtools/browser/synthetic\\n'));+ process.on('SIGTERM', () => process.exit(0));+ `;+ fixture.child = spawn(process.execPath, ['-e', parent, helper, fixture.profile, fixture.control], options);+ return fixture.child;+ },+}));++const { launchCompositionBrowser } = await import('./ownedBrowser.js');++it.skipIf(process.platform === 'win32')('does not let an owned descendant recreate the profile after browser close', async () => {+ fixture.control = await mkdtemp(join(tmpdir(), 'owned-descendant-control-'));+ let owner;+ try {+ owner = await launchCompositionBrowser();+ await owner.close();+ expect(fixture.child.exitCode).toBe(0);+ expect(existsSync(fixture.profile)).toBe(false);+ expect(existsSync(join(fixture.control, 'stopped'))).toBe(true);+ await writeFile(join(fixture.control, 'write'), 'write');+ expect(existsSync(join(fixture.control, 'done'))).toBe(false);+ expect(existsSync(fixture.profile)).toBe(false);+ } finally {+ await owner?.close().catch(() => {});+ if (fixture.profile) await rm(fixture.profile, { recursive: true, force: true });+ await rm(fixture.control, { recursive: true, force: true });+ }+});diff --git a/server/services/htmlComposition/ownedBrowser.js b/server/services/htmlComposition/ownedBrowser.jsindex c331b089d9..e7e1d2f3a9 100644--- a/server/services/htmlComposition/ownedBrowser.js+++ b/server/services/htmlComposition/ownedBrowser.js@@ -10,6 +10,7 @@ import { browserExecutablePath } from '../../lib/browserConfig.js';import { isVitestRunner } from '../../lib/runtimeEnv.js';import { PREVIEW_HOST_RESOLVER_SOCKETS, previewIsolationPlan } from '../../lib/generatedPreviewSandbox.js';import { createCdpPipeTransport } from './cdpPipe.js';+import { drainBrowserProcessGroup, signalBrowserProcessGroup } from './browserProcessGroup.js';// Chrome refuses to run as root with its sandbox on. Only a Vitest worker// running as root (a root dev/CI container) drops it, matching the test-owned@@ -79,6 +80,7 @@ export async function launchCompositionBrowser({} = {}) {signal?.throwIfAborted();const piped = isolation !== 'legacy';+ const ownsProcessGroup = process.platform !== 'win32';const { loadConfig } = await import('../browserService.js');const executable = browserExecutablePath(await loadConfig());signal?.throwIfAborted();@@ -104,17 +106,26 @@ export async function launchCompositionBrowser({let closing;let profileCleanup;let terminationStarted;+ let closeDeadlineExpired = false;// Fixed-size observations from this retained child only. Observation// timestamps are monotonic milliseconds since ownership began.const observedSince = performance.now();const observed = { spawnMs: null, exitMs: null, closeMs: null, termMs: null, killMs: null };const observedMs = () => Math.round(performance.now() - observedSince);+ const groupTermination = { term: 'not-attempted', kill: 'not-attempted', error: 'none', failedSignal: 'none', failedPhase: 'none' };const termination = { term: 'not-attempted', kill: 'not-attempted', error: 'none' };const safeSignalError = error => ['EPERM', 'ESRCH', 'EINVAL', 'ENOSYS'].includes(error?.code) ? error.code : 'other';const cleanupProfile = () => {if (!profileCleanup) {- observe('remove-start', profile);- profileCleanup = removeProfile(profile);+ profileCleanup = (async () => {+ if (ownsProcessGroup && proc?.pid && closed) {+ // Late child close still owns cleanup, without changing the rejected close verdict.+ const deadline = (closeDeadlineExpired ? performance.now() : terminationStarted ?? performance.now()) + shutdownMs;+ await drainBrowserProcessGroup(proc.pid, deadline, Math.min(1000, shutdownMs / 2), groupTermination);+ }+ observe('remove-start', profile);+ await removeProfile(profile);+ })();// Observe settlement without replacing the cached promise or its verdict.if (lifecycle.hasSubscribers) profileCleanup.then(() => observe('remove-resolved', profile),@@ -153,8 +164,8 @@ export async function launchCompositionBrowser({const signalChild = (name) => {// sandbox-exec / bwrap wait on Chrome. Signal the group, then the wrapper,// so a helper cannot keep the profile open after close.- if (piped && proc?.pid) {- try { process.kill(-proc.pid, name); } catch { /* the wrapper kill below still runs */ }+ if (ownsProcessGroup && proc?.pid) {+ signalBrowserProcessGroup(proc.pid, name, groupTermination, 'shutdown');}return proc.kill(name);};@@ -192,6 +203,7 @@ export async function launchCompositionBrowser({});await Promise.race([childClosed, new Promise((_, reject) => {deadline = setTimeout(() => {+ closeDeadlineExpired = true;// Never interpolate arbitrary child properties, errors or output.// Public status and observed events are separate evidence: accepted// signals alone do not establish that the child has exited.@@ -201,6 +213,8 @@ export async function launchCompositionBrowser({const facts = {exit: exited, stdioClosed: Boolean(proc.stderr?.destroyed),term: termination.term, kill: termination.kill, signalError: termination.error,+ groupTerm: groupTermination.term, groupKill: groupTermination.kill, groupSignalError: groupTermination.error,+ groupFailedSignal: groupTermination.failedSignal, groupFailedPhase: groupTermination.failedPhase,elapsedMs: Math.round(performance.now() - terminationStarted),spawned, closed, exitCode, signalCode,exitListener: proc.listeners('exit').includes(onExit),@@ -243,7 +257,7 @@ export async function launchCompositionBrowser({];proc = spawn(command, args, piped? { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'], env: previewBrowserEnv(), detached: true }- : safeChildProcessOptions({ stdio: ['ignore', 'ignore', 'pipe'] }));+ : safeChildProcessOptions({ stdio: ['ignore', 'ignore', 'pipe'], detached: ownsProcessGroup }));proc.once('spawn', () => { spawned = true; observed.spawnMs = observedMs(); });proc.once('exit', onExit);proc.once('close', onClose);diff --git a/server/services/htmlComposition/ownedBrowser.test.js b/server/services/htmlComposition/ownedBrowser.test.jsindex c363579ad9..70a2d1ffa9 100644--- a/server/services/htmlComposition/ownedBrowser.test.js+++ b/server/services/htmlComposition/ownedBrowser.test.js@@ -2,10 +2,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { EventEmitter, getEventListeners } from 'node:events';import { PassThrough } from 'node:stream';import { basename } from 'node:path';+import { pinPlatform } from '../../lib/testHelper.js';import { access, mkdir, rm } from 'node:fs/promises';import { createOwnedBrowserDiagnostics, readOwnedBrowserObservations } from '../../test/ownedBrowserDiagnostics.js';const launch = vi.hoisted(() => ({ spawn: vi.fn() }));+vi.mock('./browserProcessGroup.js', async original => ({ ...await original(), drainBrowserProcessGroup: vi.fn(async () => {}) }));vi.mock('node:fs/promises', async original => {const actual = await original();return { ...actual, rm: vi.fn(actual.rm) };@@ -13,6 +15,7 @@ vi.mock('node:fs/promises', async original => {vi.mock('../../lib/childProcess.js', async original => ({ ...await original(), spawn: launch.spawn }));vi.mock('../browserService.js', () => ({ loadConfig: async () => ({ chromePath: '/synthetic/chrome' }) }));const { launchCompositionBrowser } = await import('./ownedBrowser.js');+const { drainBrowserProcessGroup } = await import('./browserProcessGroup.js');let child;let profile;@@ -20,6 +23,8 @@ let startup;let diagnostics;const endpoint = 'ws://127.0.0.1:12345/devtools/browser/synthetic-browser';beforeEach(() => {+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ vi.mocked(drainBrowserProcessGroup).mockReset().mockResolvedValue();diagnostics = createOwnedBrowserDiagnostics();child = new EventEmitter();Object.assign(child, { pid: 12345, exitCode: null, signalCode: null, stderr: new PassThrough() });@@ -369,6 +374,8 @@ it.each([expect(facts).toEqual({exit: String(emitExit), stdioClosed: String(emitExit),term: 'accepted', kill: 'accepted', signalError: malformed ? 'other' : 'none', elapsedMs: '5000',+ groupTerm: process.platform === 'win32' ? 'not-attempted' : 'accepted', groupKill: process.platform === 'win32' ? 'not-attempted' : 'accepted',+ groupSignalError: 'none', groupFailedSignal: 'none', groupFailedPhase: 'none',spawned: 'true', closed: 'false', exitCode: malformed ? 'other' : exitCode === null ? 'none' : String(exitCode),signalCode: malformed ? 'other' : signalCode ?? 'none',exitListener: String(!emitExit), closeListener: 'true', errorListener: 'true',@@ -380,7 +387,7 @@ it.each([expect(result.message).not.toContain(privateValue);}expect(vi.getTimerCount()).toBe(timersBeforeClose);- expect(signalProcess).not.toHaveBeenCalled();+ expect(signalProcess.mock.calls).toEqual(process.platform === 'win32' ? [] : [[-child.pid, 'SIGTERM'], [-child.pid, 'SIGKILL']]);expect(child.listenerCount('error')).toBe(1);expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);controller.abort();@@ -401,6 +408,7 @@ it.each([removalFinished();});child.emit('close', null, 'SIGKILL');+ if (process.platform !== 'win32') expect(drainBrowserProcessGroup).toHaveBeenCalledWith(child.pid, performance.now() + 5000, 1000, expect.objectContaining({ error: 'none' }));await removed;await expect(access(profile)).rejects.toThrow();expect(rm).toHaveBeenCalledExactlyOnceWith(profile, { recursive: true, force: true });@@ -412,3 +420,63 @@ it.each([await expect(owner.close()).rejects.toBe(result);expect(result.message).toContain('closeMs=unobserved');});++it.skipIf(process.platform === 'win32')('waits for the retained group to stop before removing its profile', async () => {+ let drained;+ vi.mocked(drainBrowserProcessGroup).mockImplementationOnce(() => new Promise(resolve => { drained = resolve; }));+ const owner = await launchCompositionBrowser();+ expect(launch.spawn.mock.calls[0][2].detached).toBe(true);+ const closing = owner.close();+ expect(rm).not.toHaveBeenCalled();+ await expect(access(profile)).resolves.toBeUndefined();+ drained();+ await closing;+ await expect(access(profile)).rejects.toThrow();+});++it.skipIf(process.platform === 'win32')('preserves the profile when group quiescence cannot be established', async () => {+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(drainBrowserProcessGroup).mockRejectedValueOnce(new Error('Composition browser group observation failed'));+ const owner = await launchCompositionBrowser();+ await expect(owner.close()).rejects.toThrow('Composition browser group observation failed');+ expect(rm).not.toHaveBeenCalled();+ await expect(access(profile)).resolves.toBeUndefined();+ expect(log).toHaveBeenCalled();+ await rm(profile, { recursive: true, force: true });+});++it('keeps Windows legacy ownership on the retained direct child', async () => {+ const restorePlatform = pinPlatform('win32');+ try {+ const owner = await launchCompositionBrowser();+ expect(launch.spawn.mock.calls[0][2].detached).toBe(false);+ await owner.close();+ expect(child.kill).toHaveBeenCalledExactlyOnceWith('SIGTERM');+ expect(process.kill).not.toHaveBeenCalled();+ expect(drainBrowserProcessGroup).not.toHaveBeenCalled();+ await expect(access(profile)).rejects.toThrow();+ } finally {+ restorePlatform();+ }+});++it.skipIf(process.platform === 'win32')('latches the first group failure across direct-child escalation and late cleanup', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });+ child.kill = vi.fn(() => true);+ vi.mocked(process.kill).mockImplementation(() => { throw Object.assign(new Error('/private/error'), { code: 'EPERM' }); });+ const owner = await launchCompositionBrowser();+ const result = owner.close().catch(error => error);+ await vi.advanceTimersByTimeAsync(5000);+ const error = await result;+ expect(error.message).toContain('groupTerm=threw, groupKill=not-attempted, groupSignalError=EPERM');+ expect(error.message).toContain('groupFailedSignal=SIGTERM, groupFailedPhase=shutdown');+ expect(error.message).toContain('term=accepted, kill=accepted, signalError=none');+ expect(error.message).not.toContain('/private');+ expect(process.kill).toHaveBeenCalledExactlyOnceWith(-child.pid, 'SIGTERM');+ expect(child.kill.mock.calls).toEqual([['SIGTERM'], ['SIGKILL']]);+ child.emit('exit', 0, null);+ child.emit('close', 0, null);+ await vi.waitFor(() => expect(drainBrowserProcessGroup).toHaveBeenCalledWith(child.pid, 10000, 1000,+ expect.objectContaining({ error: 'EPERM', failedSignal: 'SIGTERM', failedPhase: 'shutdown' })));+ await vi.waitFor(() => expect(rm).toHaveBeenCalled());+});