Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 82 additions & 8 deletions src/runtime/webcore/prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,83 @@ use bun_core::Output;
use bun_jsc::ZigStringJsc as _;
use bun_jsc::zig_string::ZigString;

/// RAII guard that forces stdin into canonical ("cooked") mode for the
/// duration of a blocking line read and restores whatever termios were in
/// effect afterwards.
///
/// `node:readline` (and anything else that calls `setRawMode(true)`) clears
/// `ICANON`, `ECHO`, `ISIG` and `ICRNL`. While in that state, Enter delivers a
/// bare `\r`, typed characters are not echoed, and Ctrl+C is not translated to
/// `SIGINT`. `alert`/`confirm`/`prompt` all do a blocking read that waits for
/// `\n`, so without this guard they hang with no visible feedback.
///
/// On non-TTY stdin `tcgetattr` fails and the guard is inert, so piped input
/// keeps its existing behaviour.
#[cfg(unix)]
struct CookedStdinGuard {
saved: Option<libc::termios>,
}

#[cfg(unix)]
impl CookedStdinGuard {
fn new() -> Self {
let saved = match bun_sys::posix::tcgetattr(0) {
Ok(orig) => {
let mut cooked = orig;
cooked.c_iflag |= libc::ICRNL;
cooked.c_lflag |= libc::ICANON | libc::ECHO | libc::ISIG | libc::IEXTEN;
match bun_sys::posix::tcsetattr(0, bun_sys::posix::TCSA::Drain, &cooked) {
Ok(()) => Some(orig),
Err(_) => None,
}
}
Err(_) => None,
};
Self { saved }
}
}

#[cfg(unix)]
impl Drop for CookedStdinGuard {
fn drop(&mut self) {
if let Some(orig) = self.saved.as_ref() {
let _ = bun_sys::posix::tcsetattr(0, bun_sys::posix::TCSA::Drain, orig);
}
}
}

/// Windows equivalent of the cooked-mode guard: re-enable line input, echo and
/// Ctrl+C processing on the console and clear `ENABLE_VIRTUAL_TERMINAL_INPUT`
/// so Backspace edits the line instead of arriving as an escape sequence.
/// `StdinModeGuard` is inert when stdin is not a console.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[cfg(windows)]
struct CookedStdinGuard(#[allow(dead_code)] bun_sys::windows::StdinModeGuard);

#[cfg(windows)]
impl CookedStdinGuard {
fn new() -> Self {
Self(bun_sys::windows::StdinModeGuard::set(
bun_sys::windows::UpdateStdioModeFlagsOpts {
set: bun_sys::windows::ENABLE_LINE_INPUT
| bun_sys::windows::ENABLE_ECHO_INPUT
| bun_sys::windows::ENABLE_PROCESSED_INPUT,
unset: bun_sys::windows::ENABLE_VIRTUAL_TERMINAL_INPUT,
},
))
}
}

#[cfg(not(any(unix, windows)))]
struct CookedStdinGuard;

#[cfg(not(any(unix, windows)))]
impl CookedStdinGuard {
#[inline]
fn new() -> Self {
Self
}
}
Comment thread
claude[bot] marked this conversation as resolved.
Resolved

/// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-alert
#[bun_jsc::host_fn(export = "WebCore__alert")]
fn alert(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
Expand Down Expand Up @@ -48,6 +125,8 @@ fn alert(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
// * Not pertinent to use their complex system in a server context.
Output::flush();

let _cooked = CookedStdinGuard::new();

// 7. Optionally, pause while waiting for the user to acknowledge the message.
let mut reader = Output::stdin_reader();
loop {
Expand Down Expand Up @@ -102,6 +181,8 @@ fn confirm(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
// * Not relevant in a server context.
Output::flush();

let _cooked = CookedStdinGuard::new();

// 6. Pause until the user responds either positively or negatively.
let mut reader = Output::stdin_reader();

Expand Down Expand Up @@ -293,14 +374,7 @@ pub mod prompt {
// * Not relevant in a server context.
Output::flush();

// unset `ENABLE_VIRTUAL_TERMINAL_INPUT` on windows. This prevents backspace from
// deleting the entire line
#[cfg(windows)]
let _restore =
bun_sys::windows::StdinModeGuard::set(bun_sys::windows::UpdateStdioModeFlagsOpts {
unset: bun_sys::windows::ENABLE_VIRTUAL_TERMINAL_INPUT,
..Default::default()
});
let _cooked = CookedStdinGuard::new();

// 7. Pause while waiting for the user's response.
// `bun.Output.buffered_stdin.reader()` — process-global 4 KiB buffered stdin.
Expand Down
26 changes: 26 additions & 0 deletions test/js/bun/repl/repl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1175,6 +1175,32 @@ describe.todoIf(isWindows)("Bun REPL (Terminal)", () => {
await waitFor(/\n\s*2\b/);
});
});

// https://github.com/oven-sh/bun/issues/27542, https://github.com/oven-sh/bun/issues/5267
// The REPL keeps stdin in raw mode while evaluating, so without a cooked-mode
// guard inside alert/confirm/prompt pressing Enter delivers a bare CR and the
// blocking LF read never returns.
test("alert/confirm/prompt return when called from the REPL", async () => {
await withTerminalRepl(async ({ send, waitFor }) => {
send("prompt('name?')\n");
await waitFor("name? ");
send("alice\r");
await waitFor(/['"]alice['"]/);

send("confirm('ok?')\n");
await waitFor("[y/N]");
send("y\r");
await waitFor("true");

send("alert('bye')\n");
await waitFor("[Enter]");
send("\r");
// Back at the prompt and still able to evaluate.
await waitFor(/\u276f|> /);
send("41 + 1\n");
await waitFor("42");
});
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});

// History file written on REPL exit must be owner-only (0600), since it can
Expand Down
87 changes: 87 additions & 0 deletions test/js/web/web-globals.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,93 @@ test("confirm (no) windows newline", async () => {
expect(await proc.stderr.text()).toBe("No\n");
});

// https://github.com/oven-sh/bun/issues/5267
// readline puts the TTY into raw mode (no ICANON, no ECHO, no ICRNL), so
// Enter delivers a bare CR and typed input is invisible. alert/confirm/prompt
// must temporarily restore cooked mode so the blocking line read sees LF and
// the user can see what they typed, then put raw mode back for readline.
test.skipIf(isWindows)("alert/confirm/prompt work while readline has stdin in raw mode", async () => {
const childSrc = `
const readline = require("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const ask = q => new Promise(resolve => rl.question(q, resolve));
const say = s => process.stdout.write(s + "\\n");
(async () => {
say("RL1 " + JSON.stringify(await ask("rl1? ")));
say("PROMPT " + JSON.stringify(prompt("name?")));
say("CONFIRM " + JSON.stringify(confirm("ok?")));
alert("bye");
say("ALERT done");
say("RL2 " + JSON.stringify(await ask("rl2? ")));
rl.close();
process.exit(0);
})().catch(e => { say("ERR " + e.message); process.exit(1); });
`;

const decoder = new TextDecoder();
let out = "";
const waiters = [];
const pump = () => {
for (let i = waiters.length - 1; i >= 0; i--) {
if (out.includes(waiters[i].marker)) waiters.splice(i, 1)[0].resolve();
}
};
const exited = Promise.withResolvers();
const waitFor = marker =>
Promise.race([
new Promise(resolve => {
waiters.push({ marker, resolve });
pump();
}),
exited.promise.then(() =>
Promise.reject(new Error("child exited before " + JSON.stringify(marker) + "; out=" + JSON.stringify(out))),
),
]);

await using terminal = new Bun.Terminal({
data(_t, chunk) {
out += decoder.decode(chunk, { stream: true });
pump();
},
exit() {
exited.resolve();
},
});
await using proc = Bun.spawn({ cmd: [bunExe(), "-e", childSrc], env: bunEnv, terminal });

await waitFor("rl1? ");
terminal.write("first\r");
await waitFor('RL1 "first"');

await waitFor("name?");
terminal.write("alice\r");
await waitFor('PROMPT "alice"');

await waitFor("ok?");
terminal.write("y\r");
await waitFor("CONFIRM true");

await waitFor("[Enter]");
terminal.write("\r");
await waitFor("ALERT done");

await waitFor("rl2? ");
terminal.write("second\r");
await waitFor('RL2 "second"');

await proc.exited;

const flat = Bun.stripANSI(out).replace(/\r/g, "");
// Echo must have been on during prompt(): the characters we typed should be
// visible between the prompt text and the PROMPT result line.
expect(flat).toContain("name? alice");
// Raw mode must have been restored for readline: if the guard left stdin
// cooked the kernel would echo "second" in addition to readline's own echo,
// so it would appear twice between the second prompt and the result line.
const rl2 = flat.slice(flat.indexOf("rl2? "), flat.indexOf('RL2 "second"'));
expect(rl2.split("second").length - 1).toBe(1);
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

test("globalThis.self = 123 works", () => {
expect(Object.getOwnPropertyDescriptor(globalThis, "self")).toMatchObject({
configurable: true,
Expand Down
Loading