diff --git a/packages/hub/src/node/__tests__/host-terminals.test.ts b/packages/hub/src/node/__tests__/host-terminals.test.ts index 626103e0..89c85f94 100644 --- a/packages/hub/src/node/__tests__/host-terminals.test.ts +++ b/packages/hub/src/node/__tests__/host-terminals.test.ts @@ -4,6 +4,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import process from 'node:process' +import { exec } from 'tinyexec' import { describe, expect, it, vi } from 'vitest' import { hasNative } from 'zigpty' import { DevframeTerminalsHost } from '../host-terminals' @@ -14,6 +15,8 @@ const zigptyModuleMock = vi.hoisted(() => ({ spawn: vi.fn(), })) +vi.mock('tinyexec', { spy: true }) + vi.mock('zigpty', async (importOriginal) => { const originalModule = await importOriginal() zigptyModuleMock.spawn.mockImplementation(originalModule.spawn) @@ -309,6 +312,65 @@ describe('devframeTerminalHost stream lifecycle', () => { expect(result.exitCode).toBe(0) }) + it.skipIf(process.platform === 'win32')('terminates the subprocess started by a running command', async () => { + const { host } = createTerminalHost() + const session = await host.startChildProcess({ + command: NODE, + args: ['-e', `require('node:child_process').spawn(process.execPath, ['-e', 'process.stdout.write(String(process.pid)); setInterval(() => {}, 1000)'], { stdio: 'inherit' })`], + }, { id: 'tree', title: 'Tree' }) + const result = session.getResult() + let pid = 0 + try { + await waitUntil(() => { + pid = Number(session.buffer?.join('').trim()) + expect(pid).toBeGreaterThan(0) + }, 5000) + await session.terminate() + await waitUntil(() => expect(() => process.kill(pid, 0)).toThrow(), 5000) + expect((await result).exitCode).toBeUndefined() + expect(result.killed).toBe(true) + } + finally { + if (pid > 0) { + try { + process.kill(pid) + } + catch {} + } + } + }) + + it.skipIf(process.platform === 'win32')('keeps streaming when the old command exits during restart', async () => { + const { host, sinks } = createTerminalHost() + const session = await host.startChildProcess({ + command: NODE, + args: ['-e', 'console.log(String(process.pid)); process.stdin.resume()'], + }, { id: 'child', title: 'Child' }) + const previous = session.getResult() + const child = session.getChildProcess()! + const snapshot = vi.mocked(exec) + try { + snapshot.mockImplementationOnce((command) => { + expect(command).toBe('ps') + // Hold the snapshot open until the old command closes. + const ps = exec(NODE, ['-e', 'process.stdin.resume()']) + child.once('close', () => ps.process?.stdin?.end()) + child.stdin!.end() + return ps + }) + await session.restart() + const pid = session.getResult().pid + await waitUntil(() => expect(sinks.get('child')?.write).toHaveBeenCalledWith(`${pid}\n`), 5000) + expect(session.status).toBe('running') + expect((await previous).exitCode).toBeUndefined() + await session.restart() + } + finally { + snapshot.mockReset() + await session.terminate() + } + }) + it('getResult() tracks the new run after restart()', async () => { const { host } = createTerminalHost() diff --git a/packages/hub/src/node/host-terminals.ts b/packages/hub/src/node/host-terminals.ts index ac0cb5bb..5e8161e5 100644 --- a/packages/hub/src/node/host-terminals.ts +++ b/packages/hub/src/node/host-terminals.ts @@ -36,25 +36,44 @@ const TERMINAL_BUFFER_LIMIT = 1000 /** TERM handed to spawned PTYs; also used to reject fallback process labels. */ const PTY_TERM_NAME = 'xterm-256color' -/** - * Kill a `startChildProcess()` run together with everything it spawned. - * - * On Windows, tinyexec runs anything that isn't a `.exe`/`.com` - including - * the `node_modules/.bin/*.cmd` shims package managers generate - through - * `cmd.exe /d /s /c`, so the pid held here is the wrapper's. Killing a process - * on Windows doesn't reach its descendants, so `cp.kill()` alone would leave - * the real program running (and holding its ports). `taskkill /T /F` ends the - * whole tree; `cp.kill()` stays the fallback and the POSIX path. - */ +function processTree(pid: number, psOutput: string): number[] { + const children = new Map() + for (const [, childPid, parentPid] of psOutput.matchAll(/^\s*(\d+)\s+(\d+)$/gm)) { + const parent = Number(parentPid) + if (!children.has(parent)) + children.set(parent, []) + children.get(parent)!.push(Number(childPid)) + } + const tree = new Set([pid]) + for (const parent of tree) { + for (const child of children.get(parent) ?? []) + tree.add(child) + } + return [...tree] +} + +// On Windows, tinyexec runs non-.exe/.com commands such as node_modules/.bin/*.cmd +// through cmd.exe /d /s /c. Killing that shell PID leaves the real program running. +// taskkill stops the whole tree. On POSIX, use ps to stop children before their parents. async function killProcessTree(cp: TinyExecResult): Promise { const child = cp.process const pid = child?.pid - if (process.platform !== 'win32' || !child || pid === undefined || child.exitCode !== null || child.signalCode !== null) { + if (!child || pid === undefined || child.exitCode !== null || child.signalCode !== null) { cp.kill() return } const { exec } = await import('tinyexec') try { + if (process.platform !== 'win32') { + const { stdout } = await exec('ps', ['-A', '-o', 'pid=,ppid='], { throwOnError: true }) + for (const target of processTree(pid, stdout).reverse()) { + try { + process.kill(target, 'SIGTERM') + } + catch {} + } + return + } const { exitCode } = await exec('taskkill', [ '/pid', String(pid), @@ -324,7 +343,7 @@ export class DevframeTerminalsHost implements DevframeTerminalsHostType { }) const settle = (exitCode: number | undefined) => { - if (settled || currentRun !== runId) + if (settled) return settled = true resolveOutput({ @@ -335,19 +354,15 @@ export class DevframeTerminalsHost implements DevframeTerminalsHostType { } cp.process?.stdout?.on('data', (chunk: Buffer | string) => { - if (currentRun !== runId) - return const text = chunk.toString() stdoutChunks.push(text) - if (!state.streamClosed) + if (!state.streamClosed && currentRun === runId) state.controller?.enqueue(text) }) cp.process?.stderr?.on('data', (chunk: Buffer | string) => { - if (currentRun !== runId) - return const text = chunk.toString() stderrChunks.push(text) - if (!state.streamClosed) + if (!state.streamClosed && currentRun === runId) state.controller?.enqueue(text) }) cp.process?.once('error', (error) => { @@ -400,7 +415,8 @@ export class DevframeTerminalsHost implements DevframeTerminalsHostType { const restart = async () => { if (state.streamClosed) throw diagnostics.DF8206({ id: terminal.id }) - // Wait for the old tree to go away so the new run can reclaim its ports. + // Keep the old run from closing the stream while its process tree stops. + runId++ await killRun(cp) cp = createChildProcess() markStatus('running')