import type { DevframeTerminalSession } from '../../types/terminals' import type { DevframeHubContext } from '../context' import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import process from 'node:process' import { describe, expect, it, vi } from 'vitest' import { hasNative } from 'zigpty' import { DevframeTerminalsHost } from '../host-terminals' type DeepPartial = { [K in keyof T]?: DeepPartial } const zigptyModuleMock = vi.hoisted(() => ({ spawn: vi.fn(), })) vi.mock('zigpty', async (importOriginal) => { const originalModule = await importOriginal() zigptyModuleMock.spawn.mockImplementation(originalModule.spawn) return { ...originalModule, spawn: zigptyModuleMock.spawn, } }) const NODE = process.execPath // A real PTY works wherever zigpty's native bindings load (incl. Windows // ConPTY); skip when they're unavailable. const itPty = hasNative ? it : it.skip // Interactive stdin echo relies on POSIX PTY semantics that Windows ConPTY // doesn't reliably provide (echo timing); skip there, mirroring the terminals // plugin's own `itPosixPty` gate. const itPosixPty = (hasNative && process.platform !== 'win32') ? it : it.skip const itWindowsPty = (hasNative && process.platform === 'win32') ? it : it.skip interface FakeSink { write: ReturnType close: ReturnType error: ReturnType readonly closed: boolean } function createTerminalHost() { const sinks = new Map() const partial: DeepPartial = { rpc: { streaming: { create: () => ({ start: ({ id }: { id: string }) => { let closed = false const sink: FakeSink = { write: vi.fn(), close: vi.fn(() => { closed = true }), error: vi.fn(() => { closed = true }), get closed() { return closed }, } sinks.set(id, sink) return sink }, }), }, }, } const context = partial as DevframeHubContext return { host: new DevframeTerminalsHost(context), sinks, } } async function waitUntil(assertion: () => void, timeout = 1000): Promise { const deadline = Date.now() + timeout let lastError: unknown while (Date.now() < deadline) { try { assertion() return } catch (error) { lastError = error await new Promise(resolve => setTimeout(resolve, 10)) } } throw lastError } describe('devframeTerminalHost stream lifecycle', () => { it('cancels a bound stream when a session is removed', async () => { const { host, sinks } = createTerminalHost() let controller: ReadableStreamDefaultController let cancelled = false const stream = new ReadableStream({ start(_controller) { controller = _controller }, cancel() { cancelled = true }, }) const session: DevframeTerminalSession = { id: 'terminal', title: 'Terminal', status: 'running', stream, } host.register(session) controller!.enqueue('hello') await waitUntil(() => { expect(session.buffer).toEqual(['hello']) }) host.remove(session) await waitUntil(() => { expect(cancelled).toBe(true) }) expect(sinks.get('terminal')?.closed).toBe(true) }) it('closes child-process streams after natural process exit', async () => { const { host, sinks } = createTerminalHost() const session = await host.startChildProcess({ command: process.execPath, args: ['-e', 'process.stdout.write("done")'], }, { id: 'child', title: 'Child', }) await waitUntil(() => { expect(sinks.get('child')?.closed).toBe(true) }) expect(session.buffer?.join('')).toContain('done') }) it('closes child-process streams on terminate', async () => { const { host, sinks } = createTerminalHost() const session = await host.startChildProcess({ command: process.execPath, args: ['-e', 'setInterval(() => {}, 1000)'], }, { id: 'child', title: 'Child', }) await session.terminate() await waitUntil(() => { expect(sinks.get('child')?.closed).toBe(true) }) expect(session.getChildProcess()).toBeUndefined() }) it('bounds the session scrollback buffer', async () => { const { host } = createTerminalHost() let controller: ReadableStreamDefaultController const stream = new ReadableStream({ start(_controller) { controller = _controller }, }) const session: DevframeTerminalSession = { id: 't', title: 'T', status: 'running', stream, } host.register(session) for (let i = 0; i < 1200; i++) controller!.enqueue(`line-${i}`) // Wait for the read loop to drain every enqueued chunk (each read is its // own microtask tick) before asserting the trimmed shape. await waitUntil(() => { expect(session.buffer!.at(-1)).toBe('line-1199') }) // Keeps the newest, drops the oldest. expect(session.buffer!.length).toBeLessThanOrEqual(1000) expect(session.buffer!.includes('line-0')).toBe(false) }) it('evicts one scrollback chunk without producing discarded splice results', async () => { const { host, sinks } = createTerminalHost() const buffer: string[] = [] const splice = vi.spyOn(buffer, 'splice') const chunks = Array.from({ length: 1200 }, (_, i) => `line-${i}`) const stream = new ReadableStream({ start(controller) { for (const chunk of chunks) controller.enqueue(chunk) controller.close() }, }) const session: DevframeTerminalSession = { id: 't', title: 'T', status: 'running', stream, buffer, } host.register(session) try { await waitUntil(() => expect(sinks.get('t')?.closed).toBe(true)) expect(session.buffer).toBe(buffer) expect([...buffer]).toEqual(chunks.slice(-1000)) expect(sinks.get('t')?.write.mock.calls).toEqual(chunks.map(chunk => [chunk])) expect(splice).not.toHaveBeenCalled() } finally { splice.mockRestore() host.remove(session) } }) it('trims an oversized supplied scrollback buffer on the next chunk', async () => { const { host, sinks } = createTerminalHost() const buffer = Array.from({ length: 1500 }, (_, i) => `line-${i}`) const expected = [...buffer, 'latest'].slice(-1000) const stream = new ReadableStream({ start(controller) { controller.enqueue('latest') controller.close() }, }) const session: DevframeTerminalSession = { id: 't', title: 'T', status: 'running', stream, buffer, } host.register(session) try { await waitUntil(() => expect(sinks.get('t')?.closed).toBe(true)) expect(session.buffer).toBe(buffer) expect(buffer).toEqual(expected) } finally { host.remove(session) } }) it('rejects restarting a terminated child-process session', async () => { const { host, sinks } = createTerminalHost() const session = await host.startChildProcess( { command: process.execPath, args: ['-e', 'setInterval(() => {}, 1000)'], }, { id: 'child', title: 'Child' }, ) await session.terminate() await waitUntil(() => { expect(sinks.get('child')?.closed).toBe(true) }) await expect(session.restart()).rejects.toThrow(expect.objectContaining({ code: 'DF8206' })) // Stream stays closed; no orphan output stream. expect(sinks.get('child')?.closed).toBe(true) }) it('getResult() resolves with separately captured stdout/stderr and the exit code', async () => { const { host } = createTerminalHost() const session = await host.startChildProcess({ command: process.execPath, args: ['-e', 'process.stdout.write("out"); process.stderr.write("err"); process.exit(3)'], }, { id: 'child', title: 'Child', }) const output = await session.getResult() expect(output).toEqual({ stdout: 'out', stderr: 'err', exitCode: 3 }) // The merged display stream still carries both, for terminal rendering. expect(session.buffer?.join('')).toContain('out') expect(session.buffer?.join('')).toContain('err') }) it('getResult() exposes live pid/exitCode/killed before and after exit', async () => { const { host } = createTerminalHost() const session = await host.startChildProcess({ command: process.execPath, args: ['-e', 'setTimeout(() => process.exit(0), 50)'], }, { id: 'child', title: 'Child', }) const result = session.getResult() expect(result.pid).toBeTypeOf('number') expect(result.exitCode).toBeUndefined() expect(result.killed).toBe(false) await result expect(result.exitCode).toBe(0) }) it('getResult() tracks the new run after restart()', async () => { const { host } = createTerminalHost() // Long-running, so the stream is still open (and `restart()` allowed) // by the time we restart it. const session = await host.startChildProcess({ command: process.execPath, args: ['-e', 'setInterval(() => {}, 1000)'], }, { id: 'child', title: 'Child', }) const firstHandle = session.getResult() expect(firstHandle.exitCode).toBeUndefined() await session.restart() const secondHandle = session.getResult() // A fresh result handle for the fresh run, not the stale first one. expect(secondHandle).not.toBe(firstHandle) await session.terminate() }) it('getResult() still settles with the real exit code after terminate()', async () => { const { host, sinks } = createTerminalHost() const session = await host.startChildProcess( { command: process.execPath, args: ['-e', 'setInterval(() => {}, 1000)'], }, { id: 'child', title: 'Child' }, ) const result = session.getResult() await session.terminate() await waitUntil(() => { expect(sinks.get('child')?.closed).toBe(true) }) const output = await result expect(output.exitCode).toBeUndefined() }) }) describe('devframeTerminalHost child-process status lifecycle', () => { it('marks status stopped and emits an update on a clean exit', async () => { const { host } = createTerminalHost() const updates: string[] = [] host.events.on('terminals:session:updated', s => updates.push(s.status)) const session = await host.startChildProcess({ command: process.execPath, args: ['-e', 'process.exit(0)'], }, { id: 'child', title: 'Child' }) await waitUntil(() => { expect(session.status).toBe('stopped') }) expect(updates).toContain('stopped') }) it('marks status error on a non-zero exit', async () => { const { host } = createTerminalHost() const session = await host.startChildProcess({ command: process.execPath, args: ['-e', 'process.exit(3)'], }, { id: 'child', title: 'Child' }) await waitUntil(() => { expect(session.status).toBe('error') }) }) it('marks status error when the process fails to spawn', async () => { const { host } = createTerminalHost() const session = await host.startChildProcess({ command: 'this-command-does-not-exist-df', args: [], }, { id: 'child', title: 'Child' }) await waitUntil(() => { expect(session.status).toBe('error') }) }) it('marks status stopped on terminate() rather than error', async () => { const { host, sinks } = createTerminalHost() const session = await host.startChildProcess({ command: process.execPath, args: ['-e', 'setInterval(() => {}, 1000)'], }, { id: 'child', title: 'Child' }) expect(session.status).toBe('running') await session.terminate() await waitUntil(() => { expect(sinks.get('child')?.closed).toBe(true) }) expect(session.status).toBe('stopped') }) it('returns to running after restart() without an error flash', async () => { const { host } = createTerminalHost() const session = await host.startChildProcess({ command: process.execPath, args: ['-e', 'setInterval(() => {}, 1000)'], }, { id: 'child', title: 'Child' }) await session.restart() expect(session.status).toBe('running') await session.terminate() }) }) // On Windows, tinyexec runs anything that isn't a `.exe`/`.com` (e.g. the // `node_modules/.bin/*.cmd` shims package managers generate) through // `cmd.exe /d /s /c`, so the pid the host holds belongs to `cmd.exe`, not to // the program the shim starts. Killing only that pid leaves the real process // orphaned (still holding its ports). describe.runIf(process.platform === 'win32')('devframeTerminalHost child-process tree on Windows', { timeout: 20_000 }, () => { function isAlive(pid: number): boolean { try { process.kill(pid, 0) return true } catch { return false } } async function startShimSession(host: DevframeTerminalsHost, id: string) { const dir = mkdtempSync(join(tmpdir(), 'devframe-terminals-shim-')) writeFileSync(join(dir, 'child.cjs'), 'console.log("pid:" + process.pid); setInterval(() => {}, 1000)\n') const shim = join(dir, 'child.cmd') writeFileSync(shim, `@"${NODE}" "%~dp0\\child.cjs" %*\r\n`) // The shim resolves `child.cjs` via `%~dp0`, so it needs no cwd of its own. // Running out of `dir` would make Windows hold it as a working directory and // fail the later `rmdir` with EBUSY, so keep the shim's dir off the cwd. const session = await host.startChildProcess({ command: shim, args: [], cwd: tmpdir(), }, { id, title: id }) let pid = 0 await waitUntil(() => { const match = session.buffer?.join('').match(/pid:(\d+)/) expect(match).toBeTruthy() pid = Number(match![1]) }, 10_000) // The host holds the `cmd.exe` wrapper, not the node child. expect(session.getChildProcess()?.pid).not.toBe(pid) // Windows releases the killed process's file handles asynchronously, so an // immediate `rm` can still hit EPERM; retry until the handles are gone. return { session, pid, cleanup: () => rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100, }), } } it('terminate() kills the process started by a .cmd shim', async () => { const { host } = createTerminalHost() const { session, pid, cleanup } = await startShimSession(host, 'shim-terminate') try { await session.terminate() await waitUntil(() => expect(isAlive(pid)).toBe(false), 5000) expect(session.status).toBe('stopped') } finally { if (isAlive(pid)) process.kill(pid) cleanup() } }) it('terminate() reports a stopped, killed run rather than a crash', async () => { const { host, sinks } = createTerminalHost() const { session, pid, cleanup } = await startShimSession(host, 'shim-result') const result = session.getResult() try { await session.terminate() await waitUntil(() => expect(sinks.get('shim-result')?.closed).toBe(true)) const output = await result expect(output.exitCode).toBeUndefined() expect(result.killed).toBe(true) expect(session.status).toBe('stopped') } finally { if (isAlive(pid)) process.kill(pid) cleanup() } }) it('restart() kills the previous run started by a .cmd shim', async () => { const { host } = createTerminalHost() const { session, pid, cleanup } = await startShimSession(host, 'shim-restart') try { await session.restart() await waitUntil(() => expect(isAlive(pid)).toBe(false), 5000) expect(session.status).toBe('running') await session.terminate() } finally { if (isAlive(pid)) process.kill(pid) cleanup() } }) it('cancelling the stream kills the process started by a .cmd shim', async () => { const { host } = createTerminalHost() const { session, pid, cleanup } = await startShimSession(host, 'shim-cancel') try { host.remove(session) await waitUntil(() => expect(isAlive(pid)).toBe(false), 5000) } finally { if (isAlive(pid)) process.kill(pid) cleanup() } }) }) describe('devframeTerminalHost interactive PTY sessions', () => { itPty('inherits the parent process environment', async () => { expect.assertions(1) const environmentVariable = 'DEVFRAME_PTY_INHERITED_ENV' const previousValue = process.env[environmentVariable] process.env[environmentVariable] = 'inherited' let session: Awaited> | undefined try { const { host, sinks } = createTerminalHost() session = await host.startPtySession({ command: NODE, args: ['-e', `process.stdout.write(process.env.${environmentVariable} ?? "missing")`], }, { id: 'pty-environment', title: 'PTY environment', }) await waitUntil(() => { if (!sinks.get('pty-environment')?.closed) throw new Error('PTY stream is still open') }) expect(session.buffer?.join('')).toContain('inherited') } finally { await session?.terminate() if (previousValue === undefined) delete process.env[environmentVariable] else process.env[environmentVariable] = previousValue } }) itPosixPty('spawns an interactive PTY that accepts input and is marked interactive', async () => { const { host, sinks } = createTerminalHost() const session = await host.startPtySession({ command: NODE, args: ['-e', 'process.stdin.on("data", d => process.stdout.write("echo:" + d)); setTimeout(() => {}, 4000)'], }, { id: 'pty', title: 'PTY', }) expect(session.type).toBe('pty') expect(session.interactive).toBe(true) expect(host.sessions.get('pty')?.interactive).toBe(true) session.write('ping\n') await waitUntil(() => { expect(sinks.get('pty')?.write).toHaveBeenCalled() const written = sinks.get('pty')!.write.mock.calls.map(c => c[0]).join('') expect(written).toContain('echo:ping') }) await session.terminate() await waitUntil(() => { expect(sinks.get('pty')?.closed).toBe(true) }) }) itPty('closes the PTY stream after natural process exit', async () => { const { host, sinks } = createTerminalHost() const session = await host.startPtySession({ command: NODE, args: ['-e', 'process.stdout.write("done")'], }, { id: 'pty-exit', title: 'PTY exit', }) // Session shape (cross-platform): a PTY session is flagged interactive so // hub-aware UIs enable stdin. expect(session.type).toBe('pty') expect(session.interactive).toBe(true) expect(host.sessions.get('pty-exit')?.interactive).toBe(true) await waitUntil(() => { expect(sinks.get('pty-exit')?.closed).toBe(true) }) }) itPty('getResult() resolves merged PTY output after natural exit', async () => { expect.assertions(9) const { host } = createTerminalHost() const session = await host.startPtySession({ command: NODE, args: ['-e', 'process.stdout.write("out"); process.stderr.write("err")'], }, { id: 'pty-result', title: 'PTY result' }) const result = session.getResult() expect(result.pid).toBeTypeOf('number') expect(result.exitCode).toBeUndefined() expect(result.killed).toBe(false) const output = await result expect(output.output).toContain('out') expect(output.output).toContain('err') expect(output.exitCode).toBe(0) expect(output.signal).toBeUndefined() expect(result.exitCode).toBe(0) expect(result.killed).toBe(false) }) itWindowsPty('runs .cmd shims, which ConPTY cannot spawn directly', async () => { const dir = mkdtempSync(join(tmpdir(), 'devframe-pty-shim-')) try { const pathKey = Object.keys(process.env).find(key => key.toUpperCase() === 'PATH') ?? 'PATH' writeFileSync(join(dir, 'echo-args.cmd'), `@"${NODE}" -e "process.stdout.write(JSON.stringify(process.argv.slice(1)))" %*\r\n`) const { host } = createTerminalHost() const session = await host.startPtySession({ command: 'echo-args', args: ['a&b', 'c d', 'src\\x&y'], // Reuse the inherited key: Windows env blocks are case-insensitive. env: { [pathKey]: `${dir};${process.env[pathKey]}` }, }, { id: 'pty-cmd-shim', title: 'PTY .cmd shim' }) const output = await session.getResult() expect(output.output).toContain('["a&b","c d","src\\\\x&y"]') expect(output.exitCode).toBe(0) } finally { rmSync(dir, { recursive: true, force: true }) } }) itPty('getResult() preserves a non-zero PTY exit code', async () => { expect.assertions(3) const { host } = createTerminalHost() const session = await host.startPtySession({ command: NODE, args: ['-e', 'process.stdout.write("failed"); process.exit(3)'], }, { id: 'pty-result-error', title: 'PTY result error' }) const result = session.getResult() await expect(result).resolves.toMatchObject({ output: expect.stringContaining('failed'), exitCode: 3, signal: undefined, }) expect(result.exitCode).toBe(3) expect(result.killed).toBe(false) }) itPty('getResult() marks a terminated PTY run as killed', async () => { expect.assertions(6) const { host } = createTerminalHost() const updates: string[] = [] host.events.on('terminals:session:updated', session => updates.push(session.status)) const session = await host.startPtySession({ command: NODE, args: ['-e', 'process.stdout.write("started"); setInterval(() => {}, 4000)'], }, { id: 'pty-result-terminate', title: 'PTY result terminate' }) const result = session.getResult() await waitUntil(() => { if (!session.buffer?.join('').includes('started')) throw new Error('PTY output has not started') }) await session.terminate() expect(result.killed).toBe(true) expect(result.exitCode).toBeUndefined() await expect(result).resolves.toMatchObject({ output: expect.stringContaining('started'), exitCode: undefined, }) if (process.platform === 'win32') await expect(result).resolves.toHaveProperty('signal', undefined) else await expect(result).resolves.toHaveProperty('signal', expect.any(Number)) expect(session.status).toBe('stopped') expect(updates).not.toContain('error') }) itPty('getResult() isolates the previous PTY run after restart()', async () => { expect.assertions(8) const { host } = createTerminalHost() const session = await host.startPtySession({ command: NODE, args: ['-e', 'process.stdout.write("run:" + process.pid); setInterval(() => {}, 4000)'], }, { id: 'pty-result-restart', title: 'PTY result restart' }) const firstResult = session.getResult() await waitUntil(() => { if (!session.buffer?.join('').includes(`run:${firstResult.pid}`)) throw new Error('First PTY run has not started') }) await session.restart() const secondResult = session.getResult() expect(secondResult).not.toBe(firstResult) expect(secondResult.pid).not.toBe(firstResult.pid) await waitUntil(() => { if (!session.buffer?.join('').includes(`run:${secondResult.pid}`)) throw new Error('Second PTY run has not started') }) await session.terminate() const [firstOutput, secondOutput] = await Promise.all([firstResult, secondResult]) expect(firstResult.killed).toBe(true) expect(secondResult.killed).toBe(true) expect(firstOutput.output).toContain(`run:${firstResult.pid}`) expect(firstOutput.output).not.toContain(`run:${secondResult.pid}`) expect(secondOutput.output).toContain(`run:${secondResult.pid}`) expect(secondOutput.output).not.toContain(`run:${firstResult.pid}`) }) itPty('allows retry after a structured PTY restart spawn error', async () => { expect.assertions(9) const { host } = createTerminalHost() const session = await host.startPtySession({ command: NODE, args: ['-e', 'process.stdout.write("started:" + process.pid); setInterval(() => {}, 4000)'], }, { id: 'pty-result-restart-error', title: 'PTY result restart error' }) const result = session.getResult() await waitUntil(() => { if (!session.buffer?.join('').includes(`started:${result.pid}`)) throw new Error('PTY output has not started') }) zigptyModuleMock.spawn.mockImplementationOnce(() => { throw new Error('restart spawn failed') }) await expect(session.restart()).rejects.toThrow(expect.objectContaining({ code: 'DF8203' })) expect(session.status).toBe('error') expect(session.getProcessName()).toBeUndefined() expect(session.getResult()).toBe(result) await expect(session.restart()).resolves.toBeUndefined() expect(session.status).toBe('running') const retryResult = session.getResult() expect(retryResult).not.toBe(result) await waitUntil(() => { if (!session.buffer?.join('').includes(`started:${retryResult.pid}`)) throw new Error('Retried PTY output has not started') }) expect(session.buffer?.join('')).toContain(`started:${retryResult.pid}`) await session.terminate() await expect(result).resolves.toMatchObject({ output: expect.stringContaining(`started:${result.pid}`), exitCode: undefined, }) await retryResult }) itPty('does not accept resize after termination without throwing', async () => { const { host } = createTerminalHost() const session = await host.startPtySession({ command: NODE, args: ['-e', 'setInterval(() => {}, 4000)'], cols: 80, rows: 24, }, { id: 'pty-resize', title: 'PTY resize', }) expect(() => session.resize(120, 40)).not.toThrow() await session.terminate() expect(() => session.resize(100, 30)).not.toThrow() }) }) describe('devframeTerminalHost PTY status lifecycle', () => { itPty('marks status stopped and emits an update on a clean exit', async () => { const { host } = createTerminalHost() const updates: string[] = [] host.events.on('terminals:session:updated', s => updates.push(s.status)) const session = await host.startPtySession({ command: NODE, args: ['-e', 'process.exit(0)'], }, { id: 'pty-status', title: 'PTY status' }) await waitUntil(() => { expect(session.status).toBe('stopped') }) expect(updates).toContain('stopped') }) itPty('marks status error on a non-zero exit', async () => { const { host } = createTerminalHost() const session = await host.startPtySession({ command: NODE, args: ['-e', 'process.exit(3)'], }, { id: 'pty-status-error', title: 'PTY status error' }) await waitUntil(() => { expect(session.status).toBe('error') }) }) itPty('marks status stopped on terminate() rather than error', async () => { const { host, sinks } = createTerminalHost() const session = await host.startPtySession({ command: NODE, args: ['-e', 'setInterval(() => {}, 4000)'], }, { id: 'pty-status-terminate', title: 'PTY status terminate' }) expect(session.status).toBe('running') await session.terminate() await waitUntil(() => { expect(sinks.get('pty-status-terminate')?.closed).toBe(true) }) expect(session.status).toBe('stopped') }) itPty('returns to running after restart() without an error flash', async () => { const { host } = createTerminalHost() const session = await host.startPtySession({ command: NODE, args: ['-e', 'setInterval(() => {}, 4000)'], }, { id: 'pty-status-restart', title: 'PTY status restart' }) await session.restart() expect(session.status).toBe('running') await session.terminate() }) itPty('keeps status stopped when restart() is called after the process exited', async () => { const { host } = createTerminalHost() const session = await host.startPtySession({ command: NODE, args: ['-e', 'process.exit(0)'], }, { id: 'pty-status-restart-exited', title: 'PTY status restart exited' }) await waitUntil(() => { expect(session.status).toBe('stopped') }) // The stream is closed for good, so `restart()` rejects and the session // stays reported as stopped rather than flipping back to running. await expect(session.restart()).rejects.toThrow(expect.objectContaining({ code: 'DF8206' })) expect(session.status).toBe('stopped') }) })