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

fix(autofixer): bound CLI commands and clean up log children (#11787)

[._.]/447abcdf92a7
diff --git a/autofixer/childProcess.js b/autofixer/childProcess.js
new file mode 100644
index 0000000000..8246fe5a91
--- /dev/null
+++ b/autofixer/childProcess.js
@@ -0,0 +1,63 @@
+// Autofixer stays independent of the server's process/dependency graph.
+export const COMMAND_TIMEOUT_MS = 60_000;
+const KILL_GRACE_MS = 1_000;
+
+/** Observe one direct CLI child. Abort/timeout never implies its daemon stopped. */
+export function waitForChild(child, { timeoutMs = COMMAND_TIMEOUT_MS, signal, capture = true } = {}) {
+ return new Promise(resolve => {
+ let stdout = '';
+ let stderr = '';
+ let settled = false;
+ let stopping = false;
+ let timedOut = false;
+ let timer;
+ let cleanupTimer;
+ const onStdout = data => { stdout += data.toString(); };
+ const onStderr = data => { stderr += data.toString(); };
+ const onError = error => { if (!stopping) finish(-1, error); };
+ const onClose = code => finish(code);
+ const finish = (code, error, cleanupConfirmed = true) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ clearTimeout(cleanupTimer);
+ signal?.removeEventListener('abort', stop);
+ child.removeListener('close', onClose);
+ // Retain the error sink if an unconfirmed child emits a late error.
+ if (cleanupConfirmed) child.removeListener('error', onError);
+ child.stdout?.removeListener('data', onStdout);
+ child.stderr?.removeListener('data', onStderr);
+ if (!cleanupConfirmed) {
+ child.stdin?.destroy();
+ child.stdout?.destroy();
+ child.stderr?.destroy();
+ child.unref?.();
+ }
+ resolve({ code: stopping ? -1 : code, stdout, stderr, error, timedOut, aborted: signal?.aborted === true, cleanupConfirmed });
+ };
+ const kill = value => {
+ try { child.kill(value); }
+ catch (error) { console.error(`❌ Autofixer CLI ${value} failed: ${error.message}`); }
+ };
+ const stop = () => {
+ if (settled || stopping) return;
+ stopping = true;
+ clearTimeout(timer);
+ cleanupTimer = setTimeout(() => {
+ cleanupTimer = setTimeout(() => finish(-1, undefined, false), KILL_GRACE_MS);
+ kill('SIGKILL');
+ }, KILL_GRACE_MS);
+ // These are direct CLI children, never a shell or the managed service.
+ kill('SIGTERM');
+ };
+ if (capture) {
+ child.stdout?.on('data', onStdout);
+ child.stderr?.on('data', onStderr);
+ }
+ child.on('close', onClose);
+ child.on('error', onError);
+ if (timeoutMs !== null) timer = setTimeout(() => { timedOut = true; stop(); }, timeoutMs);
+ signal?.addEventListener('abort', stop, { once: true });
+ if (signal?.aborted) stop();
+ });
+}
diff --git a/autofixer/sandbox.js b/autofixer/sandbox.js
index 674e270e4a..a425294741 100644
--- a/autofixer/sandbox.js
+++ b/autofixer/sandbox.js
@@ -24,6 +24,7 @@
*/
import { spawn } from 'child_process';
+import { waitForChild, COMMAND_TIMEOUT_MS } from './childProcess.js';
import { writeFile, rm, mkdir } from 'fs/promises';
import { join, isAbsolute, normalize } from 'path';
import { randomBytes } from 'crypto';
@@ -347,25 +348,25 @@ export function validateProposedDiff(diff, opts = {}) {
* request lifecycle a thrown spawn error would crash the process, so we resolve
* an error shape instead.
*/
-export function execGit(gitArgs, cwd) {
- return new Promise((resolve, reject) => {
- // A missing cwd makes `spawn` fall back to `process.cwd()` — which for the
- // autofixer suite is the PortOS checkout itself, so a fixture that lost its
- // temp dir would `git init` / `git config` the developer's real repo.
- // This is a caller bug, not a git failure, so it rejects rather than
- // resolving with the `{ code: -1 }` shape reserved for spawn errors (#4554).
- if (typeof cwd !== 'string' || cwd.trim() === '') {
- reject(new Error(`execGit requires a working directory: git ${gitArgs.join(' ')}`));
- return;
- }
- const child = spawn('git', gitArgs, { cwd, windowsHide: true });
- let stdout = '';
- let stderr = '';
- child.stdout.on('data', (d) => { stdout += d.toString(); });
- child.stderr.on('data', (d) => { stderr += d.toString(); });
- child.on('error', (err) => resolve({ code: -1, stdout, stderr: err.message }));
- child.on('close', (code) => resolve({ code, stdout, stderr }));
- });
+export async function execGit(gitArgs, cwd, { timeoutMs = COMMAND_TIMEOUT_MS } = {}) {
+ // Reject caller bugs before git can fall back to the autofixer checkout.
+ if (typeof cwd !== 'string' || cwd.trim() === '') {
+ throw new Error(`execGit requires a working directory: git ${gitArgs.join(' ')}`);
+ }
+ let child;
+ try {
+ child = spawn('git', gitArgs, {
+ cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
+ });
+ } catch (error) {
+ return { code: -1, stdout: '', stderr: error.message };
+ }
+ const result = await waitForChild(child, { timeoutMs });
+ const failure = result.timedOut
+ ? `git timed out after ${timeoutMs / 1000}s; CLI cleanup ${result.cleanupConfirmed ? 'confirmed' : 'unconfirmed'}, command outcome unknown`
+ : result.error?.message;
+ return { code: result.code, stdout: result.stdout, stderr: failure ? [result.stderr, failure].filter(Boolean).join('\n') : result.stderr };
}
/** True when repoPath is inside a git work tree. A missing path is a definite
diff --git a/autofixer/sandbox.test.js b/autofixer/sandbox.test.js
index df031e625e..2f8335292b 100644
--- a/autofixer/sandbox.test.js
+++ b/autofixer/sandbox.test.js
@@ -1,5 +1,9 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { EventEmitter } from 'node:events';
+const spawnMock = vi.hoisted(() => vi.fn());
+vi.mock('child_process', () => ({ spawn: spawnMock }));
import {
+ execGit,
sanitizeChildEnv,
collectSecretEnvValues,
buildFixPrompt,
@@ -284,3 +288,47 @@ new file mode 100644
expect(paths).not.toContain('/dev/null');
});
});
+
+
+describe('execGit command lifecycle', () => {
+ afterEach(() => vi.useRealTimers());
+
+ it('settles a hung git command with partial output and the existing failure shape', async () => {
+ vi.useFakeTimers();
+ const child = new EventEmitter();
+ child.stdout = Object.assign(new EventEmitter(), { destroy: vi.fn() });
+ child.stderr = Object.assign(new EventEmitter(), { destroy: vi.fn() });
+ child.kill = vi.fn(() => { throw new Error('example signal failure'); });
+ child.unref = vi.fn();
+ spawnMock.mockReturnValue(child);
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ const result = execGit(['status'], '/example/repo', { timeoutMs: 10 });
+ child.stdout.emit('data', 'partial status');
+ await vi.advanceTimersByTimeAsync(2010);
+ expect(await result).toEqual({ code: -1, stdout: 'partial status', stderr: expect.stringContaining('command outcome unknown') });
+ expect(spawnMock).toHaveBeenCalledWith('git', ['status'], expect.objectContaining({
+ stdio: ['ignore', 'pipe', 'pipe'], env: expect.objectContaining({ GIT_TERMINAL_PROMPT: '0' }),
+ }));
+ expect(child.kill.mock.calls).toEqual([['SIGTERM'], ['SIGKILL']]);
+ expect(child.unref).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ } finally { log.mockRestore(); }
+ });
+
+ it('preserves nonzero exit output and settles spawn errors without rejection', async () => {
+ for (const spawnError of [false, true]) {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ spawnMock.mockReturnValue(child);
+ const result = execGit(['status'], '/example/repo');
+ child.stdout.emit('data', 'partial');
+ if (spawnError) child.emit('error', new Error('missing git'));
+ else { child.stderr.emit('data', 'failed'); child.emit('close', 2); }
+ expect(await result).toEqual({ code: spawnError ? -1 : 2, stdout: 'partial', stderr: spawnError ? 'missing git' : 'failed' });
+ child.emit('close', 0);
+ expect(child.stdout.listenerCount('data')).toBe(0);
+ }
+ });
+});
diff --git a/autofixer/shared.js b/autofixer/shared.js
index 27a9fdaa92..a98a35fce0 100644
--- a/autofixer/shared.js
+++ b/autofixer/shared.js
@@ -6,6 +6,7 @@
// express. `server/lib/pm2Jlist.js` is the one exception: a pure, zero-import
// leaf, so importing it costs nothing this package needs to stay light about.
import { spawn } from 'child_process';
+import { waitForChild, COMMAND_TIMEOUT_MS } from './childProcess.js';
import { existsSync } from 'fs';
import { readFile } from 'fs/promises';
import { join, dirname } from 'path';
@@ -20,28 +21,21 @@ const require = createRequire(import.meta.url);
export const PM2_BIN = join(dirname(require.resolve('pm2/package.json')), 'bin', 'pm2');
/** Execute a PM2 CLI command via node (bypasses pm2.cmd) */
-export function execPm2(pm2Args) {
- return new Promise((resolve, reject) => {
- // node_modules/pm2 can go stale (e.g. a dangling symlink left by a reaped
- // worktree install) without require.resolve('pm2/package.json') noticing,
- // since that only resolves the package dir, not this bin file. Catch it
- // here with a one-line message instead of spawning node against a missing
- // path, which surfaces as an opaque multi-line MODULE_NOT_FOUND dump.
- if (!existsSync(PM2_BIN)) {
- reject(new Error(`PM2 binary not found at ${PM2_BIN} — run "npm install" in the repo root`));
- return;
- }
- const child = spawn(process.execPath, [PM2_BIN, ...pm2Args], { windowsHide: true });
- let stdout = '';
- let stderr = '';
- child.stdout.on('data', (d) => { stdout += d.toString(); });
- child.stderr.on('data', (d) => { stderr += d.toString(); });
- child.on('close', (code) => {
- if (code !== 0) return reject(new Error(stderr || `pm2 exited with code ${code}`));
- resolve({ stdout, stderr });
+export async function execPm2(pm2Args, { timeoutMs = COMMAND_TIMEOUT_MS } = {}) {
+ // Package resolution can succeed while the PM2 entry point is a dangling link.
+ if (!existsSync(PM2_BIN)) {
+ throw new Error(`PM2 binary not found at ${PM2_BIN} — run "npm install" in the repo root`);
+ }
+ const child = spawn(process.execPath, [PM2_BIN, ...pm2Args], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
+ const result = await waitForChild(child, { timeoutMs });
+ if (result.timedOut) {
+ throw Object.assign(new Error(`pm2 ${pm2Args.join(' ')} timed out after ${timeoutMs / 1000}s; CLI cleanup ${result.cleanupConfirmed ? 'confirmed' : 'unconfirmed'}, daemon outcome unknown`), {
+ code: 'PM2_TIMEOUT', timedOut: true, cleanupConfirmed: result.cleanupConfirmed, outcome: 'unknown',
});
- child.on('error', reject);
- });
+ }
+ if (result.error) throw result.error;
+ if (result.code !== 0) throw new Error(result.stderr || `pm2 exited with code ${result.code}`);
+ return { stdout: result.stdout, stderr: result.stderr };
}
/**
diff --git a/autofixer/shared.test.js b/autofixer/shared.test.js
index e529c090ca..fa8318197f 100644
--- a/autofixer/shared.test.js
+++ b/autofixer/shared.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { existsSync } from 'fs';
import { EventEmitter } from 'events';
import { join, dirname } from 'path';
@@ -172,3 +172,42 @@ describeShared('autofixer/shared — listProcessesStrict', () => {
await expect(shared.listProcessesStrict()).resolves.toBeNull();
});
});
+
+describeShared('autofixer command lifecycle', () => {
+ afterEach(() => vi.useRealTimers());
+
+ it('bounds a hung PM2 mutation without claiming its daemon outcome', async () => {
+ vi.useFakeTimers();
+ const child = new EventEmitter();
+ child.stdout = Object.assign(new EventEmitter(), { destroy: vi.fn() });
+ child.stderr = Object.assign(new EventEmitter(), { destroy: vi.fn() });
+ child.kill = vi.fn(() => false);
+ child.unref = vi.fn();
+ spawnMock.mockReturnValue(child);
+ const result = shared.execPm2(['stop', 'example-process'], { timeoutMs: 10 }).catch(error => error);
+ child.stdout.emit('data', 'partial');
+ await vi.advanceTimersByTimeAsync(2010);
+ expect(await result).toMatchObject({ code: 'PM2_TIMEOUT', outcome: 'unknown', cleanupConfirmed: false });
+ expect(child.kill.mock.calls).toEqual([['SIGTERM'], ['SIGKILL']]);
+ expect(child.stdout.listenerCount('data')).toBe(0);
+ expect(child.stdout.destroy).toHaveBeenCalledOnce();
+ expect(child.unref).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ expect(() => child.emit('error', new Error('late kill failure'))).not.toThrow();
+ });
+
+ it('clears escalation when the CLI confirms close after termination', async () => {
+ vi.useFakeTimers();
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = vi.fn(() => { child.emit('close', null); return true; });
+ spawnMock.mockReturnValue(child);
+ const result = shared.execPm2(['jlist'], { timeoutMs: 10 }).catch(error => error);
+ await vi.advanceTimersByTimeAsync(10);
+ expect(await result).toMatchObject({ code: 'PM2_TIMEOUT', cleanupConfirmed: true });
+ expect(child.kill.mock.calls).toEqual([['SIGTERM']]);
+ expect(child.listenerCount('close')).toBe(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/autofixer/ui.js b/autofixer/ui.js
index 362375385b..285158cb45 100644
--- a/autofixer/ui.js
+++ b/autofixer/ui.js
@@ -1,5 +1,6 @@
import express from 'express';
import { spawn } from 'child_process';
+import { waitForChild } from './childProcess.js';
import { readFile } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
@@ -149,97 +150,64 @@ app.get('/', (req, res) => {
// Server-Sent Events endpoint for streaming logs
app.get('/logs', async (req, res) => {
const processName = req.query.process || 'portos-autofixer';
-
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
-
res.write(`: connected\n\n`);
- let pm2Process = null;
-
- const cleanup = () => {
- if (pm2Process && !pm2Process.killed) {
- pm2Process.kill();
- pm2Process = null;
- }
- };
-
- req.on('close', cleanup);
+ const controller = new AbortController();
+ const closed = () => controller.signal.aborted || req.aborted || res.destroyed || res.writableEnded;
+ const cleanup = () => controller.abort();
+ req.on('aborted', cleanup);
res.on('close', cleanup);
-
- // Get initial logs via node pm2/bin/pm2 (bypasses pm2.cmd on Windows)
- const initialChild = spawn(process.execPath, [PM2_BIN, 'logs', processName, '--lines', '50', '--nostream', '--raw'], { windowsHide: true });
- let initialStdout = '';
- initialChild.stdout.on('data', (d) => { initialStdout += d.toString(); });
- initialChild.on('close', () => {
- if (res.writableEnded) return;
-
- if (initialStdout) {
- const lines = initialStdout.split('\n').filter(line => line.trim());
- lines.forEach(line => {
- const event = {
- type: 'log',
- message: line,
- stream: 'out',
- timestamp: new Date().toISOString()
- };
- res.write(`data: ${JSON.stringify(event)}\n\n`);
- });
- }
-
- // Stream new logs via node pm2/bin/pm2 (bypasses pm2.cmd on Windows)
- pm2Process = spawn(process.execPath, [PM2_BIN, 'logs', processName, '--lines', '0', '--raw'], { windowsHide: true });
-
- pm2Process.stdout.on('data', (data) => {
- if (res.writableEnded) {
- cleanup();
- return;
- }
-
- const lines = data.toString().split('\n').filter(line => line.trim());
- lines.forEach(line => {
- res.write(`data: ${JSON.stringify({
- type: 'log',
- message: line,
- stream: 'out',
- timestamp: new Date().toISOString()
- })}\n\n`);
- });
- });
-
- pm2Process.stderr.on('data', (data) => {
- if (res.writableEnded) {
- cleanup();
- return;
- }
-
- const lines = data.toString().split('\n').filter(line => line.trim());
- lines.forEach(line => {
- res.write(`data: ${JSON.stringify({
- type: 'log',
- message: line,
- stream: 'err',
- timestamp: new Date().toISOString()
- })}\n\n`);
- });
- });
-
- pm2Process.on('error', (error) => {
- if (!res.writableEnded) {
- res.write(`data: ${JSON.stringify({
- type: 'log',
- message: `[ERROR] Failed to spawn pm2: ${error.message}`,
- stream: 'err',
- timestamp: new Date().toISOString()
- })}\n\n`);
+ const send = (data, stream = 'out') => {
+ if (closed()) return;
+ try {
+ for (const message of data.toString().split('\n').filter(line => line.trim())) {
+ res.write(`data: ${JSON.stringify({ type: 'log', message, stream, timestamp: new Date().toISOString() })}\n\n`);
}
+ } catch (error) {
+ console.error(`❌ [Autofixer UI] Log stream write failed: ${error.message}`);
cleanup();
+ }
+ };
+ let streamChild;
+ let onStdout;
+ let onStderr;
+ try {
+ if (closed()) return;
+ const initialChild = spawn(process.execPath, [PM2_BIN, 'logs', processName, '--lines', '50', '--nostream', '--raw'], {
+ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
});
-
- pm2Process.on('exit', cleanup);
- });
+ const initial = await waitForChild(initialChild, { signal: controller.signal });
+ if (closed()) return;
+ if (initial.error || initial.timedOut || initial.code !== 0) {
+ send(`[ERROR] Failed to read pm2 logs: ${initial.error?.message || (initial.timedOut ? 'command timed out' : initial.stderr || `exit ${initial.code}`)}`, 'err');
+ return;
+ }
+ send(initial.stdout);
+ if (closed()) return;
+ streamChild = spawn(process.execPath, [PM2_BIN, 'logs', processName, '--lines', '0', '--raw'], {
+ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ onStdout = data => send(data);
+ onStderr = data => send(data, 'err');
+ streamChild.stdout.on('data', onStdout);
+ streamChild.stderr.on('data', onStderr);
+ const result = await waitForChild(streamChild, { signal: controller.signal, timeoutMs: null, capture: false });
+ if (result.error) send(`[ERROR] Failed to spawn pm2: ${result.error.message}`, 'err');
+ } catch (error) {
+ send(`[ERROR] Failed to spawn pm2: ${error.message}`, 'err');
+ } finally {
+ if (streamChild) {
+ streamChild.stdout.removeListener('data', onStdout);
+ streamChild.stderr.removeListener('data', onStderr);
+ }
+ req.removeListener('aborted', cleanup);
+ res.removeListener('close', cleanup);
+ if (!closed()) res.end();
+ }
});
// Registry failures reach every consumer (apps, process controls and staged
diff --git a/autofixer/ui.test.js b/autofixer/ui.test.js
index 7205d903cb..f8c4352ad5 100644
--- a/autofixer/ui.test.js
+++ b/autofixer/ui.test.js
@@ -2,9 +2,11 @@ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vite
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { EventEmitter } from 'node:events';
import { hashPassword, hashToken } from '../lib/portosAuthCore.js';
-const harness = vi.hoisted(() => ({ routes: new Map(), gates: [], auth: null, execPm2: vi.fn(), loadApps: vi.fn() }));
+const harness = vi.hoisted(() => ({ routes: new Map(), gates: [], auth: null, execPm2: vi.fn(), loadApps: vi.fn(), spawn: vi.fn() }));
+vi.mock('child_process', () => ({ spawn: harness.spawn }));
vi.mock('express', () => {
const express = () => ({
use: (handler) => harness.gates.push(handler),
@@ -34,12 +36,13 @@ let dataDir;
beforeAll(async () => { passwordHash = await hashPassword(PASSWORD, SALT); }, 30_000);
beforeEach(async () => {
dataDir = await mkdtemp(join(tmpdir(), 'autofixer-authority-'));
+ harness.spawn.mockReset();
harness.execPm2.mockReset().mockResolvedValue({ stdout: 'ok', stderr: '' });
harness.loadApps.mockReset().mockResolvedValue([{ pm2ProcessNames: ['example-process'] }]);
harness.gates.length = 0;
harness.routes.clear();
});
-afterEach(async () => { await rm(dataDir, { recursive: true, force: true }); });
+afterEach(async () => { vi.useRealTimers(); await rm(dataDir, { recursive: true, force: true }); });
const loadUi = async (enabled = false) => {
await writeFile(join(dataDir, 'settings.json'), JSON.stringify({ secrets: { auth: {
@@ -157,3 +160,77 @@ describe('Autofixer process-control authority', () => {
expect(harness.execPm2).not.toHaveBeenCalled();
});
});
+
+
+describe('Autofixer log child lifecycle', () => {
+ const child = () => {
+ const proc = new EventEmitter();
+ proc.stdout = Object.assign(new EventEmitter(), { destroy: vi.fn() });
+ proc.stderr = Object.assign(new EventEmitter(), { destroy: vi.fn() });
+ proc.kill = vi.fn(() => true);
+ proc.unref = vi.fn();
+ return proc;
+ };
+ const openLogs = () => {
+ const req = Object.assign(new EventEmitter(), { query: {} });
+ const res = Object.assign(new EventEmitter(), response(), { write: vi.fn(), end: vi.fn() });
+ const done = harness.routes.get('/logs')[0](req, res);
+ return { req, res, done };
+ };
+
+ it('reports an initial spawn error and ends SSE without starting a live stream', async () => {
+ await loadUi();
+ const initial = child();
+ harness.spawn.mockReturnValue(initial);
+ const { res, done } = openLogs();
+ initial.emit('error', new Error('example spawn failure'));
+ initial.emit('close', -1);
+ await done;
+ expect(res.write.mock.calls.flat().join('')).toContain('example spawn failure');
+ expect(res.end).toHaveBeenCalledOnce();
+ expect(harness.spawn).toHaveBeenCalledOnce();
+ expect(res.listenerCount('close')).toBe(0);
+ });
+
+ it('cancels the initial read on disconnect and never starts a later stream', async () => {
+ await loadUi();
+ vi.useFakeTimers();
+ const initial = child();
+ harness.spawn.mockReturnValue(initial);
+ const { res, done } = openLogs();
+ res.destroyed = true;
+ res.emit('close');
+ await vi.advanceTimersByTimeAsync(2000);
+ await done;
+ initial.emit('close', 0);
+ expect(initial.kill.mock.calls).toEqual([['SIGTERM'], ['SIGKILL']]);
+ expect(initial.unref).toHaveBeenCalledOnce();
+ expect(harness.spawn).toHaveBeenCalledOnce();
+ expect(res.write).toHaveBeenCalledTimes(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('delivers initial and live logs then cleans the streaming child on disconnect', async () => {
+ await loadUi();
+ vi.useFakeTimers();
+ const initial = child();
+ const live = child();
+ harness.spawn.mockReturnValueOnce(initial).mockReturnValueOnce(live);
+ const { req, res, done } = openLogs();
+ initial.stdout.emit('data', 'initial log\n');
+ initial.emit('close', 0);
+ await Promise.resolve();
+ // A completed request body does not close an SSE response.
+ req.emit('close');
+ live.stdout.emit('data', 'live log\n');
+ expect(res.write.mock.calls.flat().join('')).toContain('initial log');
+ expect(res.write.mock.calls.flat().join('')).toContain('live log');
+ res.destroyed = true;
+ res.emit('close');
+ live.emit('close', null);
+ await done;
+ expect(live.kill.mock.calls).toEqual([['SIGTERM']]);
+ expect(live.stdout.listenerCount('data')).toBe(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});