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([issue-9641]): capture bounded Chrome lifecycle process facts (#10292)
[._.]/754d653dd834
diff --git a/server/services/htmlComposition/testBrowserCleanup.js b/server/services/htmlComposition/testBrowserCleanup.jsindex fd29721f3e..9c6989e689 100644--- a/server/services/htmlComposition/testBrowserCleanup.js+++ b/server/services/htmlComposition/testBrowserCleanup.js@@ -1,5 +1,5 @@import { execFileSync } from '../../lib/childProcess.js';-import { existsSync } from 'node:fs';+import { closeSync, existsSync, openSync, opendirSync, readSync } from 'node:fs';import { basename, join } from 'node:path';import { killWithEscalation } from '../../lib/killWithEscalation.js';@@ -23,6 +23,82 @@ export function _selectTestChrome(candidates) {return candidates.find(({ path }) => path && existsSync(path));}+// Failure-only Linux observations of this owned child and its current worker.+// Never read cmdline, environ, links, stacks, or arbitrary process output. A+// fixed prefix per file and at most 16 threads bound both capture and output.+function readProcPrefix(path) {+ const fd = openSync(path, 'r');+ try {+ const bytes = Buffer.alloc(4096);+ return bytes.subarray(0, readSync(fd, bytes, 0, bytes.length, 0)).toString();+ } finally { closeSync(fd); }+}++function readThreadIds(path) {+ const dir = opendirSync(path);+ const ids = [];+ try {+ let entry;+ while (ids.length < 17 && (entry = dir.readSync())) {+ if (/^[1-9]\d*$/.test(entry.name)) ids.push(entry.name);+ }+ } finally { dir.closeSync(); }+ return ids;+}++const PROCESS_STATES = { R: 'runnable', S: 'sleeping', D: 'uninterruptible', Z: 'zombie', T: 'stopped', t: 'traced', X: 'dead', I: 'idle' };++export function _testChromeProcessFacts(proc, {+ platform = process.platform, workerPid = process.pid, read = readProcPrefix, threads = readThreadIds,+} = {}) {+ if (platform !== 'linux') return 'os=unsupported';+ if (!Number.isSafeInteger(proc?.pid) || proc.pid <= 0) return 'os=linux child=unavailable';+ // Once Node has reaped it, the numeric PID may belong to somebody else.+ if (proc.exitCode != null || proc.signalCode != null) return 'os=linux child=settled';+ const stat = pid => {+ try {+ const text = read(`/proc/${pid}/stat`).slice(0, 4096);+ // comm is parenthesized and may contain spaces/parentheses; discard it.+ const end = text.lastIndexOf(')');+ if (end < 0) return null;+ const fields = text.slice(end + 2).trim().split(/\s+/);+ if (fields.length < 4 || !Object.hasOwn(PROCESS_STATES, fields[0]) || !fields.slice(1, 4).every(x => /^\d+$/.test(x))) return null;+ return { state: PROCESS_STATES[fields[0]], parent: fields[1], group: fields[2], session: fields[3] };+ } catch { return null; }+ };+ const child = stat(proc.pid);+ const worker = stat(workerPid);+ const same = (a, b) => a && b ? (a === b ? 'worker' : 'other') : 'unavailable';+ const waits = { none: 0, futex: 0, poll: 0, pipe: 0, child: 0, io: 0, other: 0, unavailable: 0 };+ let ids;+ try { ids = threads(`/proc/${proc.pid}/task`).filter(x => /^[1-9]\d*$/.test(x)).slice(0, 17); }+ catch { ids = null; }+ for (const id of ids?.slice(0, 16) ?? []) {+ let category = 'unavailable';+ try {+ const wait = read(`/proc/${proc.pid}/task/${id}/wchan`).slice(0, 4096).trim();+ // Exact kernel names only: unfamiliar text never becomes log content.+ // Zero also occurs when the kernel hides a wait; it doesn't prove runnable.+ category = wait === '0' ? 'none'+ : ['futex_wait_queue', 'futex_wait_queue_me', 'futex_wait'].includes(wait) ? 'futex'+ : ['ep_poll', 'do_epoll_wait', 'do_poll', 'poll_schedule_timeout', 'poll_schedule_timeout.constprop.0'].includes(wait) ? 'poll'+ : wait === 'pipe_read' ? 'pipe'+ : ['do_wait', 'kernel_wait4'].includes(wait) ? 'child'+ : ['io_schedule', 'io_schedule_timeout', 'wait_on_page_bit_common'].includes(wait) ? 'io' : 'other';+ } catch { /* exited, permissions, or unavailable procfs */ }+ waits[category]++;+ }+ return `os=linux child=${child?.state ?? 'unavailable'} worker=${worker?.state ?? 'unavailable'}`+ + ` parent=${same(child?.parent, String(workerPid))} group=${same(child?.group, worker?.group)} session=${same(child?.session, worker?.session)}`+ + ` threads=${ids ? Math.min(ids.length, 16) : 'unavailable'} threadLimit=${ids ? ids.length > 16 : 'unavailable'}`+ + ` waits=${Object.entries(waits).map(([name, count]) => `${name}:${count}`).join(',')}`;+}++function describeProcess(proc, observeProcess) {+ try { return observeProcess(proc); }+ catch { return 'os=unavailable'; } // Observation must never replace a lifecycle failure.+}+function executableKind(executable) {const name = basename(executable).toLowerCase();if (name.includes('headless_shell') || name.includes('headless-shell')) return 'headless-shell';@@ -52,7 +128,7 @@ export function _describeTestChromeStartup(proc, { source = 'unknown', executabl// 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, startup) {+export function _waitForTestChrome(proc, timeoutMs = 20000, startup, { observeProcess = _testChromeProcessFacts } = {}) {return new Promise((resolve, reject) => {let stderr = '';let timer;@@ -68,9 +144,10 @@ export function _waitForTestChrome(proc, timeoutMs = 20000, startup) {['crashpad', /crashpad/i],].filter(([, pattern]) => pattern.test(stderr)).map(([name]) => name);const base = categories.length ? `; stderr: ${categories.join(', ')}` : stderr ? '; Chrome emitted stderr' : '; no stderr';- if (!startup) return base;+ const processFacts = `; process: ${describeProcess(proc, observeProcess)}`;+ if (!startup) return base + processFacts;proc.spawnedSeen = spawned;- return `${base}; startup: ${_describeTestChromeStartup(proc, startup)}`;+ return `${base}; startup: ${_describeTestChromeStartup(proc, startup)}${processFacts}`;};const cleanup = () => {clearTimeout(timer);@@ -120,7 +197,7 @@ async function withinDeadline(action, timeoutMs, stage, facts = () => '') {}}-async function terminateOwnedChrome(proc) {+async function terminateOwnedChrome(proc, observeProcess) {if (!proc || proc.exitCode !== null || proc.signalCode !== null) return;let escalation;let exitObserved = false;@@ -166,7 +243,7 @@ async function terminateOwnedChrome(proc) {delayMs: 3000,});return exited;- }, 10000, 'child termination', facts);+ }, 10000, 'child termination', () => `${facts()}; process: ${describeProcess(proc, observeProcess)}`);if (signalError !== 'none') throw new Error(`Test Chrome signal delivery error${facts()}`);} finally {clearTimeout(escalation);@@ -179,11 +256,12 @@ async function terminateOwnedChrome(proc) {// 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 }) {+export async function _cleanupTestBrowser({ browser, proc, cleanup, observeProcess = _testChromeProcessFacts }) {const errors = [];try {- await withinDeadline(() => browser?.close(), 5000, 'browser disconnect').catch(error => errors.push(error));- await terminateOwnedChrome(proc).catch(error => errors.push(error));+ await withinDeadline(() => browser?.close(), 5000, 'browser disconnect',+ () => `; process: ${describeProcess(proc, observeProcess)}`).catch(error => errors.push(error));+ await terminateOwnedChrome(proc, observeProcess).catch(error => errors.push(error));} finally {proc?.stderr?.destroy();await cleanup();diff --git a/server/services/htmlComposition/testBrowserCleanup.test.js b/server/services/htmlComposition/testBrowserCleanup.test.jsindex 0f9aa4cad0..56d7f60c1f 100644--- a/server/services/htmlComposition/testBrowserCleanup.test.js+++ b/server/services/htmlComposition/testBrowserCleanup.test.js@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { EventEmitter } from 'node:events';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { _cleanupTestBrowser, _waitForTestChrome, _withTestCaptureDiagnostics } from './testBrowserCleanup.js';+import { _cleanupTestBrowser, _testChromeProcessFacts, _waitForTestChrome, _withTestCaptureDiagnostics } from './testBrowserCleanup.js';function child() {const proc = new EventEmitter();@@ -34,18 +34,76 @@ function expectStartupClean(proc) {expect(vi.getTimerCount()).toBe(0);}+describe('failure process observations', () => {+ // Synthetic procfs only: no host process, command, environment or profile.+ const stat = (state, parent, group = 777, session = 888) => `123 (example-secret (wrapper)) ${state} ${parent} ${group} ${session} 0 0 0`;+ it('classifies owned-child waits and worker ancestry with bounded, allowlisted output', () => {+ const read = vi.fn(path => {+ if (path === '/proc/123/stat') return stat('D', 456);+ if (path === '/proc/456/stat') return stat('R', 999);+ const id = path.split('/').at(-2);+ return { 1: 'futex_wait_queue', 2: 'ep_poll', 3: 'do_wait', 4: 'io_schedule', 5: 'pipe_read', 6: '0' }[id]+ ?? '/private/example-secret --password=example-secret';+ });+ const threads = vi.fn(() => Array.from({ length: 200 }, (_, i) => String(i + 1)));+ const result = _testChromeProcessFacts({ pid: 123 }, { platform: 'linux', workerPid: 456, read, threads });+ expect(result).toBe('os=linux child=uninterruptible worker=runnable parent=worker group=worker session=worker threads=16 threadLimit=true waits=none:1,futex:1,poll:1,pipe:1,child:1,io:1,other:10,unavailable:0');+ expect(read).toHaveBeenCalledTimes(18);+ expect(read.mock.calls.every(([path]) => /^\/proc\/(123|456)\/(stat|task\/\d+\/wchan)$/.test(path))).toBe(true);+ expect(result).not.toMatch(/123|456|777|888|999|example-secret|password|private/);+ });++ it('keeps absent, malformed and denied observations distinct from successful capture', () => {+ const denied = () => { throw new Error('/private/example-secret'); };+ expect(_testChromeProcessFacts({ pid: 123 }, { platform: 'linux', read: denied, threads: denied }))+ .toContain('child=unavailable worker=unavailable parent=unavailable group=unavailable session=unavailable threads=unavailable threadLimit=unavailable');+ for (const malformed of ['malformed example-secret', '123 (example-secret) R', '123 (example-secret) toString 1 2 3']) {+ const read = path => path.endsWith('/stat') ? malformed : '0';+ const result = _testChromeProcessFacts({ pid: 123 }, { platform: 'linux', read, threads: () => [] });+ expect(result).toContain('child=unavailable');+ expect(result).toContain('threads=0 threadLimit=false');+ expect(result).not.toContain('example-secret');+ }+ });++ it('separates a reparented child outside the worker group and unavailable thread waits', () => {+ const read = path => {+ if (path === '/proc/123/stat') return stat('Z', 1, 2, 3);+ if (path === '/proc/456/stat') return stat('S', 999);+ if (path.endsWith('/1/wchan')) throw new Error('denied example-secret');+ // The permitted prefix is complete, but the excess must be discarded.+ return '0'.padEnd(4096, ' ') + 'example-secret';+ };+ const result = _testChromeProcessFacts({ pid: 123 }, { platform: 'linux', workerPid: 456, read, threads: () => ['1', '2', '../example-secret'] });+ expect(result).toBe('os=linux child=zombie worker=sleeping parent=other group=other session=other threads=2 threadLimit=false waits=none:1,futex:0,poll:0,pipe:0,child:0,io:0,other:0,unavailable:1');+ });++ it('does no reads on unsupported platforms or missing/settled child identity', () => {+ const read = vi.fn();+ const threads = vi.fn();+ expect(_testChromeProcessFacts({ pid: 123 }, { platform: 'darwin', read, threads })).toBe('os=unsupported');+ expect(_testChromeProcessFacts({}, { platform: 'linux', read, threads })).toBe('os=linux child=unavailable');+ expect(_testChromeProcessFacts({ pid: 123, exitCode: 0 }, { platform: 'linux', read, threads })).toBe('os=linux child=settled');+ expect(_testChromeProcessFacts({ pid: 123, signalCode: 'SIGTERM' }, { platform: 'linux', read, threads })).toBe('os=linux child=settled');+ expect(read).not.toHaveBeenCalled();+ expect(threads).not.toHaveBeenCalled();+ });+});+describe('test Chrome startup', () => {beforeEach(() => vi.useFakeTimers());afterEach(() => vi.useRealTimers());it('waits for a complete DevTools address across stderr chunks', async () => {const proc = startingChild();- const ready = _waitForTestChrome(proc);+ const observeProcess = vi.fn();+ const ready = _waitForTestChrome(proc, 20000, undefined, { observeProcess });proc.stderr.emit('data', Buffer.from('noise\nDevTools listening on ws://127.0.0.1:4'));proc.stderr.emit('data', Buffer.from('321/devtools/browser/example'));expect(proc.listenerCount('exit')).toBe(1);proc.stderr.emit('data', Buffer.from('\n'));await expect(ready).resolves.toBe('ws://127.0.0.1:4321/devtools/browser/example');+ expect(observeProcess).not.toHaveBeenCalled();expectStartupClean(proc);});@@ -62,9 +120,9 @@ describe('test Chrome startup', () => {it('reports a spawn error without exposing its raw message', async () => {const proc = startingChild();- const ready = _waitForTestChrome(proc);+ const ready = _waitForTestChrome(proc, 20000, undefined, { observeProcess: () => { throw new Error('example-secret'); } });proc.emit('error', Object.assign(new Error('/private/example-secret/chrome'), { code: 'ENOENT' }));- await expect(ready).rejects.toThrow('failed to spawn (ENOENT; no stderr)');+ await expect(ready).rejects.toThrow('failed to spawn (ENOENT; no stderr; process: os=unavailable)');await expect(ready).rejects.not.toThrow('example-secret');expectStartupClean(proc);});@@ -73,7 +131,8 @@ describe('test Chrome startup', () => {const root = mkdtempSync(join(tmpdir(), 'example-secret-'));const proc = startingChild();proc.pid = 123;- const ready = _waitForTestChrome(proc, 20000, { source: 'playwright', executable: join(root, 'missing', 'chrome-headless-shell'), profile: join(root, 'profile') });+ const ready = _waitForTestChrome(proc, 20000, { source: 'playwright', executable: join(root, 'missing', 'chrome-headless-shell'), profile: join(root, 'profile') },+ { observeProcess: () => 'os=unavailable' });const rejected = expect(ready).rejects.toThrow('no stderr; startup: source=playwright kind=headless-shell version=unavailable spawned=yes pid=yes state=running profile=missing devToolsActivePort=false',);@@ -87,10 +146,14 @@ describe('test Chrome startup', () => {it('keeps the startup deadline and clears listeners on timeout', async () => {const proc = startingChild();- const ready = _waitForTestChrome(proc);- const rejected = expect(ready).rejects.toThrow('did not start within 20000ms; no stderr');- await vi.advanceTimersByTimeAsync(20000);+ const observeProcess = vi.fn(() => 'os=linux child=sleeping');+ const ready = _waitForTestChrome(proc, 20000, undefined, { observeProcess });+ const rejected = expect(ready).rejects.toThrow('did not start within 20000ms; no stderr; process: os=linux child=sleeping');+ await vi.advanceTimersByTimeAsync(19999);+ expect(observeProcess).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);await rejected;+ expect(observeProcess).toHaveBeenCalledExactlyOnceWith(proc);expectStartupClean(proc);});});@@ -220,7 +283,9 @@ describe('owned test Chrome cleanup', () => {proc.signalCode = signal;proc.emit('exit', null, signal);});- await _cleanupTestBrowser({ proc, cleanup: vi.fn() });+ const observeProcess = vi.fn();+ await _cleanupTestBrowser({ proc, cleanup: vi.fn(), observeProcess });+ expect(observeProcess).not.toHaveBeenCalled();expect(proc.kill.mock.calls).toEqual([['SIGTERM']]);expect(proc.listenerCount('exit')).toBe(0);expect(vi.getTimerCount()).toBe(0);@@ -275,13 +340,17 @@ describe('owned test Chrome cleanup', () => {return accepted;});const cleanup = vi.fn();- const pending = _cleanupTestBrowser({ proc, cleanup });+ const observeProcess = vi.fn(() => 'os=linux child=zombie worker=runnable parent=worker');+ const pending = _cleanupTestBrowser({ proc, cleanup, observeProcess });const rejected = expect(pending).rejects.toThrow(`child termination exceeded 10000ms deadline; teardown: stage=child-termination term=${result} kill=${result}`- + ` exitCode=none signal=${signalCode ?? 'none'} exitObserved=false signalError=${errorCode}`,+ + ` exitCode=none signal=${signalCode ?? 'none'} exitObserved=false signalError=${errorCode}; process: os=linux child=zombie worker=runnable parent=worker`,);- await vi.advanceTimersByTimeAsync(10000);+ await vi.advanceTimersByTimeAsync(9999);+ expect(observeProcess).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);await rejected;+ expect(observeProcess).toHaveBeenCalledExactlyOnceWith(proc);expect(cleanup).toHaveBeenCalledOnce();expect(proc.stderr.destroy).toHaveBeenCalledOnce();expect(proc.listenerCount('exit')).toBe(0);@@ -298,12 +367,15 @@ describe('owned test Chrome cleanup', () => {const cleanup = vi.fn();const result = _cleanupTestBrowser({browser: { close: () => new Promise(() => {}) }, proc, cleanup,+ observeProcess: () => { throw new Error('example-secret'); },});const rejected = expect(result).rejects.toThrow(- 'Test Chrome browser disconnect exceeded 5000ms deadline; Test Chrome child termination exceeded 10000ms deadline',+ 'Test Chrome browser disconnect exceeded 5000ms deadline; process: os=unavailable; Test Chrome child termination exceeded 10000ms deadline',);await vi.advanceTimersByTimeAsync(15000);await rejected;+ await expect(result).rejects.toThrow('process: os=unavailable');+ await expect(result).rejects.not.toThrow('example-secret');expect(proc.kill.mock.calls).toEqual([['SIGTERM'], ['SIGKILL']]);expect(cleanup).toHaveBeenCalledOnce();expect(proc.stderr.destroy).toHaveBeenCalledOnce();