fix(cli): release stdin before handing terminal to local-mode child (#1932)

* fix(cli): release stdin before handing terminal to local-mode child

hapi ships as a Bun-compiled executable, and Bun's tty.ReadStream keeps
an in-flight read on fd 0 even after process.stdin.pause()
(https://github.com/oven-sh/bun/issues/29126).

Remote mode reads stdin (Ink UI in raw mode, for the double-space
switch-to-local gesture). When switching back to local mode,
spawnWithTerminalGuard only paused stdin before spawning the agent TUI
with stdio:'inherit'. The parent's stale pending read kept racing the
child for console input and won: after a remote -> local switch the
agent TUI rendered but received no keystrokes at all — the input box
was dead and even Ctrl-C never reached it. Instrumented at local spawn
time: dataListeners=0, isPaused=true, but _readableState.reading=true.

Fix: destroy stdin outright before spawning the local child
(releaseStdinForChild) — destroy reliably stops the pending read where
pause() does not — and re-create process.stdin via
`new tty.ReadStream(0)` when remote mode starts again
(ensureLiveStdin, called from RemoteLauncherBase.setupTerminal).
hasTTY is now computed lazily since stdin may legitimately be
destroyed at launcher construction time.

Verified end-to-end on Windows with `hapi kimi` by injecting console
input via WriteConsoleInput and checking the agent session wire log:
remote -> double-space -> local -> typed message reaches the agent;
switch to remote again (double-space detection works on the
re-created stdin) -> local -> input works again. Direct local launch
unaffected. `bun run typecheck:cli` and the cli vitest suite pass.

* fix(cli): preserve piped stdin when releasing terminal for local child

Addresses review feedback on #1932: releaseStdinForChild() destroyed
stdin unconditionally, but destroying a piped stdin closes fd 0 and
starves the child spawned with stdio:'inherit'. The Bun stale-read
workaround is only needed for a TTY, so skip destroy() when stdin is
not a terminal; pause() suffices for pipes. Adds regression coverage
for the piped case.

---------

Co-authored-by: Naitian LIU <Liunaitian@users.noreply.github.com>
This commit is contained in:
Naitian LIU
2026-10-28 12:09:49 +08:00
committed by GitHub
co-authored by Naitian LIU
parent ebca96e575
commit db4ee82c80
4 changed files with 143 additions and 9 deletions
+59 -3
View File
@@ -29,24 +29,58 @@ const dummyOptions = {
describe('spawnWithTerminalGuard', () => {
let stdinPauseSpy: ReturnType<typeof vi.spyOn>;
let stdinResumeSpy: ReturnType<typeof vi.spyOn>;
let stdinDestroySpy: ReturnType<typeof vi.spyOn>;
let destroyedDescriptor: PropertyDescriptor | undefined;
let isTTYDescriptor: PropertyDescriptor | undefined;
const setStdinDestroyed = (value: boolean) => {
Object.defineProperty(process.stdin, 'destroyed', {
configurable: true,
get: () => value
});
};
const setStdinIsTTY = (value: boolean | undefined) => {
Object.defineProperty(process.stdin, 'isTTY', {
configurable: true,
get: () => value
});
};
beforeEach(() => {
vi.clearAllMocks();
stdinPauseSpy = vi.spyOn(process.stdin, 'pause').mockImplementation(() => process.stdin);
stdinResumeSpy = vi.spyOn(process.stdin, 'resume').mockImplementation(() => process.stdin);
stdinDestroySpy = vi.spyOn(process.stdin, 'destroy').mockImplementation(() => process.stdin);
destroyedDescriptor = Object.getOwnPropertyDescriptor(process.stdin, 'destroyed');
isTTYDescriptor = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
setStdinDestroyed(false);
setStdinIsTTY(true);
});
afterEach(() => {
stdinPauseSpy.mockRestore();
stdinResumeSpy.mockRestore();
stdinDestroySpy.mockRestore();
if (destroyedDescriptor) {
Object.defineProperty(process.stdin, 'destroyed', destroyedDescriptor);
} else {
delete (process.stdin as unknown as { destroyed?: unknown }).destroyed;
}
if (isTTYDescriptor) {
Object.defineProperty(process.stdin, 'isTTY', isTTYDescriptor);
} else {
delete (process.stdin as unknown as { isTTY?: unknown }).isTTY;
}
});
it('pauses stdin before spawn and resumes after success', async () => {
it('releases (pauses and destroys) stdin before spawn and resumes after success', async () => {
mockSpawnWithAbort.mockResolvedValue();
await spawnWithTerminalGuard(dummyOptions);
expect(stdinPauseSpy).toHaveBeenCalledOnce();
expect(stdinDestroySpy).toHaveBeenCalledOnce();
expect(stdinResumeSpy).toHaveBeenCalledOnce();
expect(mockRestoreTerminalState).toHaveBeenCalledOnce();
});
@@ -68,6 +102,17 @@ describe('spawnWithTerminalGuard', () => {
expect(mockRestoreTerminalState).toHaveBeenCalledOnce();
});
it('does not resume stdin when the stream was destroyed', async () => {
mockSpawnWithAbort.mockImplementation(async () => {
setStdinDestroyed(true);
});
await spawnWithTerminalGuard(dummyOptions);
expect(stdinResumeSpy).not.toHaveBeenCalled();
expect(mockRestoreTerminalState).toHaveBeenCalledOnce();
});
it('propagates the original error from spawnWithAbort', async () => {
const error = new Error('process exited with code 1');
mockSpawnWithAbort.mockRejectedValue(error);
@@ -75,12 +120,23 @@ describe('spawnWithTerminalGuard', () => {
await expect(spawnWithTerminalGuard(dummyOptions)).rejects.toThrow(error);
});
it('calls pause before spawn, and resume after spawn', async () => {
it('preserves piped stdin: pauses without destroying, then resumes', async () => {
setStdinIsTTY(undefined);
mockSpawnWithAbort.mockResolvedValue();
await spawnWithTerminalGuard(dummyOptions);
expect(stdinPauseSpy.mock.invocationCallOrder[0])
expect(stdinPauseSpy).toHaveBeenCalledOnce();
expect(stdinDestroySpy).not.toHaveBeenCalled();
expect(stdinResumeSpy).toHaveBeenCalledOnce();
});
it('releases stdin before spawn, and resumes after spawn', async () => {
mockSpawnWithAbort.mockResolvedValue();
await spawnWithTerminalGuard(dummyOptions);
expect(stdinDestroySpy.mock.invocationCallOrder[0])
.toBeLessThan(mockSpawnWithAbort.mock.invocationCallOrder[0]);
expect(mockSpawnWithAbort.mock.invocationCallOrder[0])
.toBeLessThan(stdinResumeSpy.mock.invocationCallOrder[0]);