import type { RpcStreamingChannel } from 'devframe/types' import type { Buffer } from 'node:buffer' import type { Result as TinyExecResult } from 'tinyexec' import type { IPty } from 'zigpty' import type { DevframeChildProcessExecuteOptions, DevframeChildProcessOutput, DevframeChildProcessResult, DevframeChildProcessTerminalSession, DevframePtyExecuteOptions, DevframePtyOutput, DevframePtyResult, DevframePtyTerminalSession, DevframeTerminalSession, DevframeTerminalSessionBase, DevframeTerminalsHost as DevframeTerminalsHostType, } from '../types/terminals' import type { DevframeHubContext } from './context' import process from 'node:process' import { createEventEmitter } from 'devframe/utils/events' import { HUB_EVENTS } from '../events' import { diagnostics } from './diagnostics' import { resolvePtyCommand } from './pty-command' type PartialWithoutId = Partial & { id: string } /** * Channel name used for terminal stream output. Stable, well-known so * hub-aware clients can subscribe by name. */ const TERMINAL_STREAM_CHANNEL = HUB_EVENTS.stream.terminals const TERMINAL_REPLAY_WINDOW = 1000 /** Max chunks retained in the per-session scrollback buffer (bounded like the replay window). */ 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. */ 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) { cp.kill() return } const { exec } = await import('tinyexec') try { const { exitCode } = await exec('taskkill', [ '/pid', String(pid), '/T', '/F', ]) if (exitCode === 0) return } catch {} cp.kill() } export class DevframeTerminalsHost implements DevframeTerminalsHostType { public readonly sessions: DevframeTerminalsHostType['sessions'] = new Map() public readonly events: DevframeTerminalsHostType['events'] = createEventEmitter() private _boundStreams = new Map void stream: ReadableStream }>() private _channel?: RpcStreamingChannel constructor( public readonly context: DevframeHubContext, ) { } /** * Lazily acquire the streaming channel, since `context.rpc` isn't assigned * until after every host is constructed, so we can't grab it in the * constructor. */ private getStreamingChannel(): RpcStreamingChannel | undefined { if (this._channel) return this._channel if (!this.context.rpc?.streaming) return undefined this._channel = this.context.rpc.streaming.create( TERMINAL_STREAM_CHANNEL, { replayWindow: TERMINAL_REPLAY_WINDOW }, ) return this._channel } /** * Per-run stream lifecycle shared by the child-process and PTY paths: guards * the single-close/error transition and keeps the session's `status` in step * with the process lifecycle (a hub-aware client sees `running` → * `stopped`/`error` instead of a value frozen at spawn time). */ private createStreamLifecycle() { const state: { controller?: ReadableStreamDefaultController streamClosed: boolean session?: DevframeTerminalSession } = { streamClosed: false } const markStatus = (next: DevframeTerminalSession['status']): void => { const session = state.session! if (session.status === next) return session.status = next this.events.emit(HUB_EVENTS.bus.terminalsSessionUpdated, session) } const closeStream = (): void => { if (state.streamClosed) return state.streamClosed = true try { state.controller?.close() } catch { // The stream may already be closed by cancellation. } } const errorStream = (error: unknown): void => { if (state.streamClosed) return state.streamClosed = true try { state.controller?.error(error) } catch { // The stream may already be closed by cancellation. } } return { state, markStatus, closeStream, errorStream, } } register(session: DevframeTerminalSession): DevframeTerminalSession { if (this.sessions.has(session.id)) { throw diagnostics.DF8200({ id: session.id }) } this.sessions.set(session.id, session) this.bindStream(session) this.events.emit(HUB_EVENTS.bus.terminalsSessionUpdated, session) return session } update(patch: PartialWithoutId): void { if (!this.sessions.has(patch.id)) { throw diagnostics.DF8201({ id: patch.id }) } const session = this.sessions.get(patch.id)! Object.assign(session, patch) this.sessions.set(patch.id, session) this.bindStream(session) this.events.emit(HUB_EVENTS.bus.terminalsSessionUpdated, session) } remove(session: DevframeTerminalSession): void { this._boundStreams.get(session.id)?.dispose() this.sessions.delete(session.id) this.events.emit(HUB_EVENTS.bus.terminalsSessionUpdated, session) this._boundStreams.delete(session.id) } /** Drain a session's output stream into its scrollback buffer and streaming sink. */ private async pumpStream( reader: ReadableStreamDefaultReader, sessionBuffer: string[], sink: ReturnType['start']> | undefined, isDisposed: () => boolean, ): Promise { try { while (!isDisposed()) { const result = await reader.read() if (isDisposed() || result.done) break // Mirror to the legacy session.buffer used by `terminals:read`: // a bounded tail kept for the snapshot endpoint. sessionBuffer.push(result.value) if (sessionBuffer.length === TERMINAL_BUFFER_LIMIT + 1) sessionBuffer.shift() else if (sessionBuffer.length > TERMINAL_BUFFER_LIMIT) sessionBuffer.splice(0, sessionBuffer.length - TERMINAL_BUFFER_LIMIT) sink?.write(result.value) } if (!isDisposed() && sink && !sink.closed) sink.close() } catch (error) { if (!isDisposed() && sink && !sink.closed) sink.error(error) } finally { try { reader.releaseLock() } catch { // Already released by the stream implementation. } } } private bindStream(session: DevframeTerminalSession) { // Skip when the same stream is already bound if (this._boundStreams.has(session.id) && this._boundStreams.get(session.id)?.stream === session.stream) return // Dispose the previous stream this._boundStreams.get(session.id)?.dispose() this._boundStreams.delete(session.id) // If new stream is not available, skip if (!session.stream) return session.buffer ||= [] const sessionBuffer = session.buffer const channel = this.getStreamingChannel() // The streaming channel reuses `session.id` as the stream id so clients // can subscribe immediately after seeing the session in // `devframe:terminals:list`. const sink = channel?.start({ id: session.id }) const reader = session.stream.getReader() let disposed = false void this.pumpStream(reader, sessionBuffer, sink, () => disposed) this._boundStreams.set(session.id, { dispose: () => { disposed = true reader.cancel('terminal stream disposed').catch(() => {}) if (sink && !sink.closed) sink.close() }, stream: session.stream, }) } async startChildProcess( executeOptions: DevframeChildProcessExecuteOptions, terminal: Omit, ): Promise { if (this.sessions.has(terminal.id)) { throw diagnostics.DF8200({ id: terminal.id }) } const { exec } = await import('tinyexec') const { state, markStatus, closeStream, errorStream } = this.createStreamLifecycle() let cp: TinyExecResult | undefined let currentResult: DevframeChildProcessResult | undefined let runId = 0 // Runs stopped on purpose (terminate/restart/cancel). On Windows the tree // kill ends them with exit code 1 rather than a signal, so this keeps them // reported as a deliberate stop instead of a crash on every platform. const hostKilled = new WeakSet() const killRun = (target: TinyExecResult | undefined): Promise => { if (!target) return Promise.resolve() hostKilled.add(target) return killProcessTree(target) } const stream = new ReadableStream({ start(_controller) { state.controller = _controller }, cancel() { const target = cp cp = undefined closeStream() return killRun(target) }, }) function createChildProcess() { const currentRun = ++runId let runErrored = false const cp = exec( executeOptions.command, executeOptions.args || [], { nodeOptions: { env: { COLORS: 'true', FORCE_COLOR: 'true', ...(executeOptions.env || {}), }, cwd: executeOptions.cwd ?? process.cwd(), stdio: 'pipe', }, }, ) // Capture stdout/stderr separately (for `getResult()`) by listening on // the raw child process directly, rather than consuming `cp`'s own // async iterator/promise, which merge stdout+stderr line-by-line and // would starve one another if both were read from. const stdoutChunks: string[] = [] const stderrChunks: string[] = [] let settled = false let resolveOutput!: (output: DevframeChildProcessOutput) => void const outputPromise = new Promise((resolve) => { resolveOutput = resolve }) const settle = (exitCode: number | undefined) => { if (settled || currentRun !== runId) return settled = true resolveOutput({ stdout: stdoutChunks.join(''), stderr: stderrChunks.join(''), exitCode, }) } cp.process?.stdout?.on('data', (chunk: Buffer | string) => { if (currentRun !== runId) return const text = chunk.toString() stdoutChunks.push(text) if (!state.streamClosed) 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) state.controller?.enqueue(text) }) cp.process?.once('error', (error) => { if (currentRun !== runId) return runErrored = true settle(cp.process?.exitCode ?? undefined) errorStream(error) markStatus('error') }) cp.process?.once('close', (code) => { const killed = hostKilled.has(cp) settle(killed ? undefined : code ?? undefined) if (currentRun !== runId) return closeStream() // A spawn/runtime error already settled the status; a non-zero exit // code is a crash. A clean exit, or a kill by the host (terminate()/ // restart()), is a deliberate/normal stop. if (!runErrored) { markStatus(!killed && typeof code === 'number' && code !== 0 ? 'error' : 'stopped') } }) currentResult = { get pid() { return cp.process?.pid }, get exitCode() { return hostKilled.has(cp) ? undefined : cp.process?.exitCode ?? undefined }, get killed() { return hostKilled.has(cp) || cp.process?.killed === true }, kill: signal => cp.kill(signal), then: (onfulfilled, onrejected) => outputPromise.then(onfulfilled, onrejected), } return cp } cp = createChildProcess() 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. await killRun(cp) cp = createChildProcess() markStatus('running') } const terminate = async () => { const target = cp cp = undefined await killRun(target) closeStream() markStatus('stopped') } const session: DevframeChildProcessTerminalSession = { ...terminal, status: 'running', stream, type: 'child-process', executeOptions, getChildProcess: () => cp?.process, getResult: () => currentResult!, terminate, restart, } state.session = session this.register(session) return Promise.resolve(session) } async startPtySession( executeOptions: DevframePtyExecuteOptions, terminal: Omit, ): Promise { if (this.sessions.has(terminal.id)) { throw diagnostics.DF8200({ id: terminal.id }) } const { spawn } = await import('zigpty') const cols = executeOptions.cols ?? 80 const rows = executeOptions.rows ?? 24 const { state, markStatus, closeStream, errorStream } = this.createStreamLifecycle() let pty: IPty | undefined let currentResult: DevframePtyResult | undefined let killCurrentRun: (() => void) | undefined let runId = 0 const stream = new ReadableStream({ start(_controller) { state.controller = _controller }, cancel() { killCurrentRun?.() pty = undefined closeStream() }, }) const spawnPty = (): IPty => { const currentRun = ++runId const cwd = executeOptions.cwd ?? process.cwd() const env = { ...process.env, TERM: PTY_TERM_NAME, COLORTERM: 'truecolor', FORCE_COLOR: '1', ...(executeOptions.env ?? {}), } const { command, args } = resolvePtyCommand(executeOptions.command, executeOptions.args ?? [], { cwd, env }) const ptyProcess = spawn(command, args, { name: PTY_TERM_NAME, cols, rows, cwd, env, }) const outputChunks: string[] = [] let killed = false let settled = false let settledExitCode: number | undefined let resolveOutput!: (output: DevframePtyOutput) => void const outputPromise = new Promise((resolve) => { resolveOutput = resolve }) const settle = (exitCode: number, signal: number): void => { if (settled) return settled = true killed ||= signal !== 0 settledExitCode = killed ? undefined : exitCode resolveOutput({ output: outputChunks.join(''), exitCode: settledExitCode, signal: signal === 0 ? undefined : signal, }) } ptyProcess.onData((data) => { const text = typeof data === 'string' ? data : data.toString('utf8') outputChunks.push(text) if (!state.streamClosed && currentRun === runId) state.controller?.enqueue(text) }) ptyProcess.onExit(({ exitCode, signal }) => { settle(exitCode, signal) if (currentRun !== runId) return closeStream() /** * Killed runs and clean exits are stopped. Only a non-killed non-zero exit * code is a crash, matching the child-process path. */ markStatus(!killed && exitCode !== 0 ? 'error' : 'stopped') }) currentResult = { get pid() { return ptyProcess.pid }, get exitCode() { return killed ? undefined : (ptyProcess.exitCode ?? settledExitCode) }, get killed() { return killed }, then: (onfulfilled, onrejected) => outputPromise.then(onfulfilled, onrejected), } killCurrentRun = () => { if (ptyProcess.exitCode !== null) return killed = true ptyProcess.kill() } return ptyProcess } try { pty = spawnPty() } catch (error) { errorStream(error) throw diagnostics.DF8203({ command: executeOptions.command, reason: error instanceof Error ? error.message : String(error), }) } const session: DevframePtyTerminalSession = { ...terminal, status: 'running', interactive: true, stream, type: 'pty', executeOptions, write: (data) => { try { pty?.write(data) } catch { // Process already gone. } }, resize: (nextCols, nextRows) => { try { pty?.resize(Math.max(1, nextCols), Math.max(1, nextRows)) } catch { // Resize after exit is a no-op. } }, getProcessName: () => { try { const name = pty?.process return name && name !== PTY_TERM_NAME ? name : undefined } catch { return undefined } }, getResult: () => currentResult!, terminate: async () => { killCurrentRun?.() pty = undefined closeStream() markStatus('stopped') }, restart: async () => { if (state.streamClosed) throw diagnostics.DF8206({ id: terminal.id }) killCurrentRun?.() killCurrentRun = undefined pty = undefined try { pty = spawnPty() } catch (error) { markStatus('error') throw diagnostics.DF8203({ command: executeOptions.command, reason: error instanceof Error ? error.message : String(error), }) } markStatus('running') }, } state.session = session this.register(session) return session } }