Files
hapi/cli/src/modules/common/remote/RemoteLauncherBase.ts
T
db4ee82c80 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>
2026-10-28 12:09:49 +08:00

274 lines
10 KiB
TypeScript

import { render } from 'ink';
import type { ReactElement } from 'react';
import { MessageBuffer } from '@/ui/ink/messageBuffer';
import { restoreTerminalState } from '@/ui/terminalState';
import { ensureLiveStdin } from '@/utils/stdinLifecycle';
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
export type RemoteLauncherExitReason = 'switch' | 'exit';
export type LaunchOutcome = {
reachedReady: boolean;
authFailed?: boolean;
error?: Error;
};
export type RemoteLauncherDisplayContext = {
messageBuffer: MessageBuffer;
logPath?: string;
onExit: () => void | Promise<void>;
/** Optional: remote-only flavors (e.g. agy) expose no local-switch action. */
onSwitchToLocal?: () => void | Promise<void>;
};
export type RemoteLauncherTerminalHandlers = {
onExit: () => void | Promise<void>;
/** Optional: remote-only flavors (e.g. agy) expose no local-switch action. */
onSwitchToLocal?: () => void | Promise<void>;
};
export type RemoteLauncherAbortHandlers = {
onAbort: () => void | Promise<void>;
onSwitch: () => void | Promise<void>;
};
type RpcHandlerManagerLike = {
registerHandler<TRequest = unknown, TResponse = unknown>(
method: string,
handler: (params: TRequest) => Promise<TResponse> | TResponse
): void;
};
export abstract class RemoteLauncherBase {
protected readonly messageBuffer: MessageBuffer;
protected readonly logPath?: string;
protected exitReason: RemoteLauncherExitReason | null = null;
protected shouldExit: boolean = false;
protected ptyAbortController: AbortController | null = null;
private inkInstance: ReturnType<typeof render> | null = null;
protected constructor(logPath?: string) {
this.logPath = logPath;
this.messageBuffer = new MessageBuffer();
}
// Computed lazily: stdin may be destroyed while a local-mode child owns
// the terminal (see utils/stdinLifecycle) and re-created in setupTerminal.
protected get hasTTY(): boolean {
return Boolean(
process.stdout.isTTY
&& process.stdin.isTTY
&& !process.stdin.destroyed
);
}
protected abstract createDisplay(context: RemoteLauncherDisplayContext): ReactElement;
protected abstract runMainLoop(): Promise<void>;
protected abstract cleanup(): Promise<void>;
protected getCurrentSessionId(): string | null {
return null;
}
protected async runRespawnLoop(opts: {
maxImmediateFailures?: number;
respawnBackoffMs?: number;
maxAuthRetries?: number;
authRetryDelayMs?: number;
onLaunchStart: (isNewSession: boolean) => void;
launchOnce: (signal: AbortSignal) => Promise<LaunchOutcome>;
onLaunchSuccess?: () => void;
onLaunchFailure?: (error: Error) => void;
}): Promise<void> {
const maxImmediateFailures = opts.maxImmediateFailures ?? 3;
const respawnBackoffMs = opts.respawnBackoffMs ?? 1000;
const maxAuthRetries = opts.maxAuthRetries ?? 8;
const authRetryDelayMs = opts.authRetryDelayMs ?? 1500;
let consecutiveImmediateFailures = 0;
let authRetries = 0;
let previousSessionId: string | null = null;
while (!this.exitReason) {
const currentSessionId = this.getCurrentSessionId();
const isNewSession = currentSessionId !== previousSessionId;
opts.onLaunchStart(isNewSession);
previousSessionId = currentSessionId;
const controller = new AbortController();
this.ptyAbortController = controller;
let reachedReady = false;
try {
const outcome = await opts.launchOnce(controller.signal);
reachedReady = outcome.reachedReady;
if (outcome.authFailed) {
if (!this.exitReason && !controller.signal.aborted) {
authRetries++;
if (authRetries > maxAuthRetries) {
opts.onLaunchFailure?.(new Error(`Authentication failed after ${maxAuthRetries} attempts`));
this.exitReason = 'exit';
break;
}
await new Promise((r) => setTimeout(r, authRetryDelayMs));
continue;
}
}
if (reachedReady) {
consecutiveImmediateFailures = 0;
authRetries = 0;
opts.onLaunchSuccess?.();
}
if (outcome.error) {
throw outcome.error;
}
} catch (e) {
if (this.exitReason) break;
const error = e instanceof Error ? e : new Error(String(e));
opts.onLaunchFailure?.(error);
if (!reachedReady) {
consecutiveImmediateFailures++;
if (consecutiveImmediateFailures >= maxImmediateFailures) {
opts.onLaunchFailure?.(new Error(`PTY failed to start after ${maxImmediateFailures} attempts; ending session.`));
this.exitReason = 'exit';
break;
}
await new Promise((r) => setTimeout(r, respawnBackoffMs));
}
continue;
} finally {
// launchOnce may have raced PTY exit against an abort-aware queue
// read. Cancel the losing read before the next launch starts so it
// cannot steal that launch's first queued message.
controller.abort();
if (this.ptyAbortController === controller) {
this.ptyAbortController = null;
}
}
}
}
protected setupTerminal(handlers: RemoteLauncherTerminalHandlers): void {
// Local mode destroys stdin so the child TUI gets all console input
// (Bun keeps reading fd 0 after pause()). Re-create it before the
// remote-mode UI reads keys again.
ensureLiveStdin();
if (this.hasTTY) {
console.clear();
this.inkInstance = render(this.createDisplay({
messageBuffer: this.messageBuffer,
logPath: this.logPath,
onExit: handlers.onExit,
onSwitchToLocal: handlers.onSwitchToLocal
}), {
exitOnCtrlC: false,
patchConsole: false
});
}
if (this.hasTTY) {
process.stdin.resume();
if (process.stdin.isTTY) {
process.stdin.setRawMode(true);
}
process.stdin.setEncoding('utf8');
}
}
protected setupAbortHandlers(
rpcHandlerManager: RpcHandlerManagerLike,
handlers: RemoteLauncherAbortHandlers
): void {
rpcHandlerManager.registerHandler(RPC_METHODS.Abort, async () => {
await handlers.onAbort();
});
rpcHandlerManager.registerHandler(RPC_METHODS.Switch, async () => {
await handlers.onSwitch();
});
}
protected clearAbortHandlers(rpcHandlerManager: RpcHandlerManagerLike): void {
rpcHandlerManager.registerHandler(RPC_METHODS.Abort, async () => {});
rpcHandlerManager.registerHandler(RPC_METHODS.Switch, async () => {});
}
/**
* Hook for flavor-specific "we are leaving remote mode" bookkeeping.
* No-op by default — override only if a flavor has state that must stop
* being valid the instant remote mode starts tearing down (OpenCode's
* /compact availability flag is the motivating case; see
* OpencodeRemoteLauncher's override).
*
* Called from two places, both intentionally, since neither alone covers
* every way a launcher can stop being "in remote mode":
* 1. `requestExit()`, synchronously, as its very first action — before
* `shouldExit`/`exitReason` are even set, and long before the
* `handler` it's about to await (e.g. OpenCode's `handleAbort()`,
* which does real async teardown work like cancelling the ACP
* prompt) gets a chance to run. This is what actually closes a race
* window: anything gated on flavor state this hook resets can no
* longer slip through between "a switch/exit was requested" and
* "the async teardown for it finished".
* 2. `start()`'s `finally` block, unconditionally, as a backstop for
* every other way `runMainLoop()` can end — a thrown exception, for
* instance, never goes through `requestExit()` at all. Firing here
* too is what guarantees the hook always runs by the time this
* launcher's promise settles, not just on the two deliberate exit
* paths.
*
* Must stay synchronous and idempotent — it can run twice per exit (once
* from each call site above) and must never assume `handler`/`cleanup()`
* have run yet.
*/
protected onLeavingRemote(): void {}
protected async requestExit(
reason: RemoteLauncherExitReason,
handler: () => void | Promise<void>
): Promise<void> {
this.onLeavingRemote();
if (!this.exitReason) {
this.exitReason = reason;
}
this.shouldExit = true;
await handler();
}
protected finalizeTerminal(): void {
restoreTerminalState();
if (this.hasTTY) {
try {
process.stdin.pause();
} catch {
}
}
if (this.inkInstance) {
this.inkInstance.unmount();
}
this.messageBuffer.clear();
}
protected async start(handlers: RemoteLauncherTerminalHandlers): Promise<RemoteLauncherExitReason> {
this.setupTerminal(handlers);
try {
await this.runMainLoop();
} finally {
// Backstop call — see onLeavingRemote()'s doc comment for why
// this needs to run here too, not just from requestExit().
this.onLeavingRemote();
await this.cleanup();
this.finalizeTerminal();
}
return this.exitReason || 'exit';
}
}