Skip to content

Commit d284022

Browse files
authored
fix(uninstall): stop confirm prompt auto-abort on TTY (#5163)
<!-- markdownlint-disable MD041 --> ## Summary Interactive `nemoclaw uninstall` printed `Proceed? [y/N]` and then immediately `Aborted.` before the user could type — on every Linux TTY. Regression from #5020, which replaced the child-shell stdin read with an in-process `fs.readSync(0)` loop: `buildRuntime` touches `process.stdin` to detect a TTY, which flips fd 0 to non-blocking (libuv side effect), so the empty read throws `EAGAIN` and the catch treated it as EOF. This PR detects the TTY without side effects, retries transient read errors, and clarifies the abort message. ## Related Issue <!-- Fixes #NNN or Closes #NNN. Remove this section if none. --> Fixes #5188 ## Changes - Detect TTY via `tty.isatty(0)` in `buildRuntime` instead of `process.stdin.isTTY`, which instantiates the stdin stream and switches fd 0 to non-blocking mode for the rest of the process. - Retry `EAGAIN`/`EWOULDBLOCK` (25 ms sleep) and `EINTR` in `defaultReadLine` instead of conflating them with EOF; hard errors and real EOF keep prior behavior (return buffered bytes or null). - Print a `re-run with --yes` hint when stdin yields no input at the confirm prompt instead of a bare `Aborted.`. - Export `defaultReadLine` with injectable `readSync`/`sleep` deps; add 7 unit tests (EAGAIN retry, EINTR, EOF, CRLF, partial-line, hard errors) and 1 integration test for the no-input message. Manually verified under a pty against the compiled CLI: with fd 0 poisoned non-blocking, the prompt now waits for input (read `"y"` after ~1 s) instead of aborting in ~1 ms; full `internal uninstall run-plan` waits and aborts only after an actual `n`. ## Type of Change - [x] Code change (feature, bug fix, or refactor) - [ ] Code change with doc updates - [ ] Doc only (prose changes, no code sample modifications) - [ ] Doc only (includes code sample changes) ## Verification <!-- Check each item you ran and confirmed. Leave unchecked items you skipped. Doc-only changes do not require npm test unless you ran it. --> - [ ] `npx prek run --all-files` passes - [ ] `npm test` passes - [ ] Tests added or updated for new or changed behavior - [ ] No secrets, API keys, or credentials committed - [ ] Docs updated for user-facing behavior changes - [ ] `npm run docs` builds without warnings (doc changes only) - [ ] Doc pages follow the [style guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md) (doc changes only) - [ ] New doc pages include SPDX header and frontmatter (new pages only) --- <!-- DCO sign-off required by CI. Run: git config user.name && git config user.email --> Signed-off-by: Hung Le <[email protected]> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved uninstall confirmation behavior when stdin is closed/non-interactive; now logs a clear message and guides rerunning with --yes. * Better terminal detection to avoid unwanted side effects and ensure interactive prompts behave correctly. * **Tests** * Added robust tests covering no-stdin, TTY vs non-TTY, retry/error cases, and PTY-driven prompt interactions to prevent regressions. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent ea5c423 commit d284022

6 files changed

Lines changed: 503 additions & 26 deletions

File tree

‎src/lib/actions/uninstall/run-plan.test.ts‎

Lines changed: 77 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import path from "node:path";
77

88
import { describe, expect, it, vi } from "vitest";
99

10-
import { buildRunPlan, runUninstallPlan, type RunResult } from "./run-plan";
10+
import { buildRunPlan, type RunResult, runUninstallPlan } from "./run-plan";
1111

1212
function ok(stdout = ""): RunResult {
1313
return { status: 0, stdout, stderr: "" };
@@ -77,6 +77,7 @@ describe("uninstall run plan", () => {
7777
commandExists: () => true,
7878
env: {
7979
HOME: "/tmp/nemoclaw-uninstall-test",
80+
NEMOCLAW_AGENT: "",
8081
TMPDIR: "/tmp/nemoclaw-uninstall-test",
8182
} as NodeJS.ProcessEnv,
8283
existsSync: () => false,
@@ -206,7 +207,7 @@ describe("uninstall run plan", () => {
206207
const result = runUninstallPlan(
207208
{ assumeYes: false, deleteModels: false, keepOpenShell: true },
208209
{
209-
env: { HOME: "/tmp/nemoclaw-uninstall-test" } as NodeJS.ProcessEnv,
210+
env: { HOME: "/tmp/nemoclaw-uninstall-test", NEMOCLAW_AGENT: "" } as NodeJS.ProcessEnv,
210211
existsSync: () => false,
211212
isTty: true,
212213
log: (line) => logs.push(line),
@@ -241,6 +242,53 @@ describe("uninstall run plan", () => {
241242
expect(run).not.toHaveBeenCalled();
242243
});
243244

245+
it("explains how to proceed when stdin yields no input at the confirm prompt", () => {
246+
const logs: string[] = [];
247+
const run = vi.fn();
248+
const result = runUninstallPlan(
249+
{ assumeYes: false, deleteModels: false, keepOpenShell: true },
250+
{
251+
env: { HOME: "/tmp/nemoclaw-uninstall-test" } as NodeJS.ProcessEnv,
252+
log: (line) => logs.push(line),
253+
readLine: () => null,
254+
run,
255+
},
256+
);
257+
258+
expect(result.exitCode).toBe(0);
259+
expect(logs).toContain(
260+
"No input available on stdin (closed or non-interactive); re-run with --yes to skip this prompt.",
261+
);
262+
expect(logs).toContain("Aborted.");
263+
expect(run).not.toHaveBeenCalled();
264+
});
265+
266+
it("builds the default runtime without touching process.stdin (#5188)", () => {
267+
const stdinGet = vi.spyOn(process, "stdin", "get");
268+
try {
269+
const result = runUninstallPlan(
270+
{ assumeYes: true, deleteModels: false, keepOpenShell: true },
271+
{
272+
commandExists: () => false,
273+
env: { HOME: "/tmp/nemoclaw-uninstall-test" } as NodeJS.ProcessEnv,
274+
existsSync: () => false,
275+
kill: () => true,
276+
log: () => {},
277+
rmSync: vi.fn(),
278+
run: vi.fn(() => ok()),
279+
runDocker: () => ok(""),
280+
// isTty/readLine intentionally not injected: the default
281+
// isStdinTty/readLineFromStdin pair must never instantiate
282+
// process.stdin, which would flip fd 0 non-blocking (#5188).
283+
},
284+
);
285+
expect(result.exitCode).toBe(0);
286+
expect(stdinGet).not.toHaveBeenCalled();
287+
} finally {
288+
stdinGet.mockRestore();
289+
}
290+
});
291+
244292
it("kills the Ollama auth proxy via the persisted PID file (#2759)", () => {
245293
const logs: string[] = [];
246294
const killed: number[] = [];
@@ -580,7 +628,14 @@ describe("uninstall run plan", () => {
580628
{ assumeYes: true, deleteModels: false, keepOpenShell: true },
581629
{
582630
commandExists: (command) => command !== "docker" && command !== "pgrep",
583-
env: { HOME: "/home/test", TMPDIR: "/tmp/test" } as NodeJS.ProcessEnv,
631+
// Neutralize NEMOCLAW_NON_INTERACTIVE: the runtime merges the real
632+
// process.env, so a developer shell exporting it would silently flip
633+
// this interactive scenario onto the non-interactive path.
634+
env: {
635+
HOME: "/home/test",
636+
NEMOCLAW_NON_INTERACTIVE: "",
637+
TMPDIR: "/tmp/test",
638+
} as NodeJS.ProcessEnv,
584639
error: (line) => warnings.push(line),
585640
existsSync: (target) =>
586641
target === "/swapfile" || target === "/home/test/.nemoclaw/managed_swap",
@@ -664,7 +719,10 @@ describe("uninstall run plan", () => {
664719
{ assumeYes: true, deleteModels: false, keepOpenShell: true },
665720
{
666721
commandExists: () => false,
667-
env: { HOME: tmpHome } as NodeJS.ProcessEnv,
722+
env: {
723+
HOME: tmpHome,
724+
NEMOCLAW_UNINSTALL_DESTROY_USER_DATA: "",
725+
} as NodeJS.ProcessEnv,
668726
existsSync: tempScopedExistsSync(tmpHome),
669727
isTty: false,
670728
log: (line) => logs.push(line),
@@ -735,7 +793,11 @@ describe("uninstall run plan", () => {
735793
{ assumeYes: false, deleteModels: false, keepOpenShell: true },
736794
{
737795
commandExists: () => false,
738-
env: { HOME: tmpHome } as NodeJS.ProcessEnv,
796+
env: {
797+
HOME: tmpHome,
798+
NEMOCLAW_NON_INTERACTIVE: "",
799+
NEMOCLAW_UNINSTALL_DESTROY_USER_DATA: "",
800+
} as NodeJS.ProcessEnv,
739801
existsSync: tempScopedExistsSync(tmpHome),
740802
isTty: true,
741803
log: (line) => logs.push(line),
@@ -763,7 +825,11 @@ describe("uninstall run plan", () => {
763825
{ assumeYes: false, deleteModels: false, keepOpenShell: true },
764826
{
765827
commandExists: () => false,
766-
env: { HOME: tmpHome } as NodeJS.ProcessEnv,
828+
env: {
829+
HOME: tmpHome,
830+
NEMOCLAW_NON_INTERACTIVE: "",
831+
NEMOCLAW_UNINSTALL_DESTROY_USER_DATA: "",
832+
} as NodeJS.ProcessEnv,
767833
existsSync: tempScopedExistsSync(tmpHome),
768834
isTty: true,
769835
log: (line) => logs.push(line),
@@ -799,6 +865,7 @@ describe("uninstall run plan", () => {
799865
env: {
800866
HOME: tmpHome,
801867
NEMOCLAW_NON_INTERACTIVE: "1",
868+
NEMOCLAW_UNINSTALL_DESTROY_USER_DATA: "",
802869
} as NodeJS.ProcessEnv,
803870
existsSync: tempScopedExistsSync(tmpHome),
804871
// Simulate a TTY so we exercise the env-var-only branch (the prior
@@ -850,7 +917,10 @@ describe("uninstall run plan", () => {
850917
{ assumeYes: true, deleteModels: false, keepOpenShell: true },
851918
{
852919
commandExists: () => false,
853-
env: { HOME: tmpHome } as NodeJS.ProcessEnv,
920+
env: {
921+
HOME: tmpHome,
922+
NEMOCLAW_UNINSTALL_DESTROY_USER_DATA: "",
923+
} as NodeJS.ProcessEnv,
854924
error: (line) => warnings.push(line),
855925
existsSync: tempScopedExistsSync(tmpHome),
856926
isTty: false,

‎src/lib/actions/uninstall/run-plan.ts‎

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import path from "node:path";
88

99
import { dockerSpawnSync } from "../../adapters/docker/exec";
1010
import { type AgentBranding, getAgentBranding } from "../../cli/branding";
11+
import { isStdinTty, readLineFromStdin } from "../../core/stdin";
1112
import { sleepMs } from "../../core/wait";
1213
import {
1314
defaultUninstallPaths,
@@ -92,23 +93,6 @@ function defaultCommandExists(command: string, env: NodeJS.ProcessEnv): boolean
9293
return false;
9394
}
9495

95-
function defaultReadLine(): string | null {
96-
const chunks: Buffer[] = [];
97-
const byte = Buffer.alloc(1);
98-
while (true) {
99-
let bytesRead = 0;
100-
try {
101-
bytesRead = fs.readSync(0, byte, 0, 1, null);
102-
} catch {
103-
return chunks.length > 0 ? Buffer.concat(chunks).toString("utf-8") : null;
104-
}
105-
if (bytesRead === 0 || byte[0] === 10) break;
106-
chunks.push(Buffer.from(byte));
107-
}
108-
if (chunks.length === 0) return null;
109-
return Buffer.concat(chunks).toString("utf-8").replace(/\r$/, "");
110-
}
111-
11296
function splitNonEmptyLines(output: string): string[] {
11397
return output
11498
.split(/\r?\n/)
@@ -254,7 +238,9 @@ function buildRuntime(deps: UninstallRunDeps): UninstallRuntime {
254238
env,
255239
error: deps.error ?? ((message) => console.error(message)),
256240
existsSync: deps.existsSync ?? ((target) => fs.existsSync(target)),
257-
isTty: deps.isTty ?? !!process.stdin.isTTY,
241+
// Side-effect-free TTY check + EAGAIN-tolerant reader; the
242+
// process.stdin/non-blocking-fd hazard is documented in core/stdin.ts.
243+
isTty: deps.isTty ?? isStdinTty(),
258244
kill:
259245
deps.kill ??
260246
((pid, signal) => {
@@ -266,7 +252,7 @@ function buildRuntime(deps: UninstallRunDeps): UninstallRuntime {
266252
}
267253
}),
268254
log: deps.log ?? ((message) => console.log(message)),
269-
readLine: deps.readLine ?? defaultReadLine,
255+
readLine: deps.readLine ?? readLineFromStdin,
270256
rmSync: deps.rmSync ?? fs.rmSync,
271257
run: deps.run ?? defaultRun,
272258
runDocker: deps.runDocker ?? defaultRunDocker,
@@ -311,6 +297,11 @@ function confirm(options: UninstallRunOptions, runtime: UninstallRuntime): boole
311297
runtime.log("Proceed? [y/N]");
312298
const reply = runtime.readLine();
313299
if (reply && /^(y|yes)$/i.test(reply.trim())) return true;
300+
if (reply === null) {
301+
runtime.log(
302+
"No input available on stdin (closed or non-interactive); re-run with --yes to skip this prompt.",
303+
);
304+
}
314305
runtime.log("Aborted.");
315306
return false;
316307
}

‎src/lib/core/stdin.test.ts‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
import { describe, expect, it, vi } from "vitest";
5+
6+
import { isStdinTty, readLineFromStdin } from "./stdin";
7+
8+
/**
9+
* Scripted fs.readSync stand-in: a single character delivers that byte, 0
10+
* reports EOF, and any longer string throws an error with that code.
11+
*/
12+
function makeReadSync(events: Array<string | 0>) {
13+
return vi.fn((_fd: number, buffer: Buffer): number => {
14+
const event = events.shift();
15+
if (event === undefined) throw new Error("readSync called past end of script");
16+
if (event === 0) return 0;
17+
if (event.length === 1) {
18+
buffer[0] = event.charCodeAt(0);
19+
return 1;
20+
}
21+
const err = new Error(event) as NodeJS.ErrnoException;
22+
err.code = event;
23+
throw err;
24+
});
25+
}
26+
27+
describe("readLineFromStdin", () => {
28+
it("retries on EAGAIN until input arrives instead of treating it as EOF (#5020)", () => {
29+
const sleep = vi.fn();
30+
const readSync = makeReadSync(["EAGAIN", "EAGAIN", "y", "\n"]);
31+
32+
expect(readLineFromStdin({ readSync, sleep })).toBe("y");
33+
expect(sleep).toHaveBeenCalledTimes(2);
34+
expect(sleep).toHaveBeenCalledWith(25);
35+
});
36+
37+
it("retries immediately on EINTR without sleeping", () => {
38+
const sleep = vi.fn();
39+
const readSync = makeReadSync(["EINTR", "n", "\n"]);
40+
41+
expect(readLineFromStdin({ readSync, sleep })).toBe("n");
42+
expect(sleep).not.toHaveBeenCalled();
43+
});
44+
45+
it.each([
46+
["returns null at immediate EOF", [0], null],
47+
["strips the trailing CR from CRLF input", ["y", "e", "s", "\r", "\n"], "yes"],
48+
["returns buffered bytes when EOF arrives before a newline", ["y", 0], "y"],
49+
["returns null on a hard error with no buffered bytes", ["EBADF"], null],
50+
["returns buffered bytes when a hard error interrupts mid-line", ["y", "e", "EBADF"], "ye"],
51+
] as const)("%s", (_label, events, expected) => {
52+
expect(readLineFromStdin({ readSync: makeReadSync([...events]), sleep: vi.fn() })).toBe(
53+
expected,
54+
);
55+
});
56+
57+
it.each([
58+
["EAGAIN"],
59+
["EWOULDBLOCK"],
60+
] as const)("gives up with null after the non-TTY deadline on persistent %s", (code) => {
61+
const sleep = vi.fn();
62+
const readSync = vi.fn((): number => {
63+
const err = new Error(code) as NodeJS.ErrnoException;
64+
err.code = code;
65+
throw err;
66+
});
67+
68+
expect(readLineFromStdin({ isTty: () => false, readSync, sleep })).toBeNull();
69+
// 10s virtual deadline at 25ms per retry = exactly 400 bounded waits.
70+
expect(sleep).toHaveBeenCalledTimes(400);
71+
});
72+
73+
it("keeps waiting past the deadline on a TTY until input arrives", () => {
74+
const sleep = vi.fn();
75+
const events = [...Array.from({ length: 450 }, () => "EAGAIN"), "y", "\n"];
76+
77+
expect(readLineFromStdin({ isTty: () => true, readSync: makeReadSync(events), sleep })).toBe(
78+
"y",
79+
);
80+
expect(sleep).toHaveBeenCalledTimes(450);
81+
});
82+
});
83+
84+
describe("isStdinTty", () => {
85+
it("reports false when stdin is not a terminal", () => {
86+
// Vitest workers run with piped stdio, so fd 0 is never a TTY here.
87+
expect(isStdinTty()).toBe(false);
88+
});
89+
});

0 commit comments

Comments
 (0)