Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
22 changes: 11 additions & 11 deletions src/bun_core/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,8 @@ pub mod windows_stdio {
}

pub(crate) fn restore() {
crate::tty::reset_active_dec_modes();

// SAFETY: PEB access is sound on Windows; handles are valid for process
// lifetime. `peb()` returns a raw pointer because the OS/CRT mutate the
// PEB out-of-band (`SetStdHandle`, …), so we must not materialize a
Expand Down Expand Up @@ -2831,23 +2833,21 @@ pub fn synchronized() -> Synchronized {
Synchronized::begin()
}

pub struct Synchronized;
/// Writes `SYNCHRONIZED_START` on `begin` and `SYNCHRONIZED_END` (plus a
/// flush) on `end`/drop.
pub struct Synchronized {
_mode: Option<crate::tty::DecModesGuard>,
}

impl Synchronized {
pub(crate) fn begin() -> Synchronized {
#[cfg(unix)]
{
print(format_args!("{}", SYNCHRONIZED_START));
Synchronized {
_mode: cfg!(unix)
.then(|| crate::tty::DecModesGuard::set(crate::tty::dec::SYNCHRONIZED_OUTPUT)),
}
Synchronized
}

pub fn end(self) {
#[cfg(unix)]
{
print(format_args!("{}", SYNCHRONIZED_END));
}
}
pub fn end(self) {}
}

#[cfg(test)]
Expand Down
137 changes: 137 additions & 0 deletions src/bun_core/tty.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use core::ffi::{c_int, c_void};
use core::sync::atomic::{AtomicU8, Ordering};

/// Terminal size as reported by the tty (`struct winsize` on POSIX).
#[repr(C)]
Expand Down Expand Up @@ -94,3 +95,139 @@ impl Drop for RawModeGuard {
unsafe extern "C" {
unsafe fn Bun__ttySetMode(fd: c_int, mode: c_int, state: *mut c_void, drain: c_int) -> c_int;
}

/// DEC private modes (`CSI ? Pm h` / `CSI ? Pm l`) that a CLI widget flips on
/// stdout's terminal for its lifetime. They are terminal-emulator state, not
/// termios, so writing the startup termios back at exit does not undo them:
/// each one needs its inverse sequence written to the terminal.
pub mod dec {
/// `?25`: text cursor hidden.
pub const HIDDEN_CURSOR: u8 = 1 << 0;
/// `?1000` + `?1006`: mouse button and wheel reporting, SGR-encoded.
pub const MOUSE_REPORTING: u8 = 1 << 1;
/// `?2026`: synchronized output (the terminal defers rendering).
pub const SYNCHRONIZED_OUTPUT: u8 = 1 << 2;
}

/// `(mode bit, set sequence, reset sequence)` for every [`dec`] mode.
const DEC_MODES: [(u8, &[u8], &[u8]); 3] = [
(dec::HIDDEN_CURSOR, b"\x1b[?25l", b"\x1b[?25h"),
(
dec::MOUSE_REPORTING,
b"\x1b[?1000h\x1b[?1006h",
b"\x1b[?1000l\x1b[?1006l",
),
(dec::SYNCHRONIZED_OUTPUT, b"\x1b[?2026h", b"\x1b[?2026l"),
];

/// The [`dec`] modes currently set on stdout's terminal. Atomic because
/// [`reset_active_dec_modes`] reads it from signal context.
static ACTIVE_DEC_MODES: AtomicU8 = AtomicU8::new(0);

/// RAII guard over a set of [`dec`] modes on stdout's terminal. `set` writes
/// the set sequences through the buffered stdout writer; `Drop` writes the
/// reset sequences and flushes. In between, the modes are recorded in
/// [`ACTIVE_DEC_MODES`], so an exit that never runs `Drop` (SIGINT/SIGTERM,
/// a crash, `Global::exit`, console Ctrl+C on Windows) still resets them: see
/// [`reset_active_dec_modes`].
#[must_use = "the modes are reset when the guard drops"]
pub struct DecModesGuard(u8);

impl DecModesGuard {
pub fn set(modes: u8) -> Self {
ACTIVE_DEC_MODES.fetch_or(modes, Ordering::Relaxed);
for (bit, set, _) in DEC_MODES {
if modes & bit != 0 {
crate::output::print_bytes(set);
}
}
Self(modes)
}
}

impl Drop for DecModesGuard {
fn drop(&mut self) {
for (bit, _, reset) in DEC_MODES {
if self.0 & bit != 0 {
crate::output::print_bytes(reset);
}
}
// Flush before clearing the bits: until the reset bytes reach the
// terminal, a signal must still find the modes marked active.
crate::output::flush();
ACTIVE_DEC_MODES.fetch_and(!self.0, Ordering::Relaxed);
}
}

/// Writes the reset sequence of every mode in [`ACTIVE_DEC_MODES`] directly
/// to stdout (when it is a terminal) and clears the set. Every exit path that
/// writes the startup termios back calls this (`bun_restore_stdio()` on POSIX,
/// `windows_stdio::restore()` on Windows). Some of those run inside a signal
/// handler, so this is async-signal-safe: an atomic swap, a stack buffer, and
/// `write(2)`.
pub fn reset_active_dec_modes() {
let active = ACTIVE_DEC_MODES.swap(0, Ordering::Relaxed);
if active == 0 || !crate::output::is_stdout_tty() {
return;
}
let mut buf = [0u8; 64];
let mut len = 0;
for (bit, _, reset) in DEC_MODES {
if active & bit != 0 {
buf[len..len + reset.len()].copy_from_slice(reset);
len += reset.len();
}
}
write_stdout_raw(&buf[..len]);
}

#[unsafe(no_mangle)]
extern "C" fn Bun__ttyResetActiveDecModes() {
reset_active_dec_modes();
}

#[cfg(unix)]
fn write_stdout_raw(mut bytes: &[u8]) {
// SAFETY: plain libc calls on stack-local, fully initialized values.
unsafe {
// A background job writing to a TOSTOP terminal gets SIGTTOU, whose
// default action stops the process mid-exit. With it blocked the
// write fails with EIO instead.
let mut ttou: libc::sigset_t = crate::ffi::zeroed();
let mut old: libc::sigset_t = crate::ffi::zeroed();
libc::sigemptyset(&raw mut ttou);
libc::sigaddset(&raw mut ttou, libc::SIGTTOU);
libc::pthread_sigmask(libc::SIG_BLOCK, &raw const ttou, &raw mut old);
while !bytes.is_empty() {
let rc = libc::write(libc::STDOUT_FILENO, bytes.as_ptr().cast(), bytes.len());
if rc < 0 {
if crate::ffi::errno() == libc::EINTR {
continue;
}
break;
}
bytes = &bytes[rc as usize..];
}
libc::pthread_sigmask(libc::SIG_SETMASK, &raw const old, core::ptr::null_mut());
}
}

#[cfg(windows)]
fn write_stdout_raw(bytes: &[u8]) {
use crate::windows_sys as w;
let Some(handle) = w::GetStdHandle(w::STD_OUTPUT_HANDLE) else {
return;
};
let mut written: w::DWORD = 0;
// SAFETY: `bytes` outlives the synchronous call; `lpOverlapped` may be
// null for a non-OVERLAPPED handle.
unsafe {
let _ = w::kernel32::WriteFile(
handle,
bytes.as_ptr(),
bytes.len() as w::DWORD,
&raw mut written,
core::ptr::null_mut(),
);
}
}
4 changes: 4 additions & 0 deletions src/jsc/PosixSignalHandle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ extern "C" fn Bun__onPosixSignal(number: i32) {
&& WATCH_MODE_KILL_SIGNAL.load(Ordering::Relaxed) != 0
&& WATCH_SIGINT_LISTENERS.load(Ordering::Acquire) == 0
{
// This handler replaced `onExitSignal` (c-bindings.cpp), so it owns
// writing the startup termios back; `_exit` skips the atexit hook
// that would. Async-signal-safe (tcsetattr + write).
bun_core::Output::source::stdio::restore();
// SAFETY: `_exit(2)` is async-signal-safe and takes no pointers.
unsafe { libc::_exit(0) };
}
Expand Down
4 changes: 4 additions & 0 deletions src/jsc/bindings/c-bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,9 @@ extern "C" ssize_t pwritev2(int fd, const struct iovec* iov, int iovcnt,
#endif

extern "C" void Bun__onExit();
// bun_core::tty: async-signal-safe; writes the inverse of any DEC private
// modes (hidden cursor, mouse reporting, ...) a CLI widget still has set.
extern "C" void Bun__ttyResetActiveDecModes();
extern "C" int32_t bun_stdio_tty[3];
#if !OS(WINDOWS)
static termios termios_to_restore_later[3];
Expand All @@ -599,6 +602,7 @@ extern "C" void bun_restore_stdio()
{

#if !OS(WINDOWS)
Bun__ttyResetActiveDecModes();

// Only suppress the restore when Bun is a pipeline producer (stdout is a
// pipe, not a TTY) and it didn't touch termios itself. That's the #29592
Expand Down
11 changes: 3 additions & 8 deletions src/runtime/cli/init_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,9 @@ impl InitCommand {
bstr::BStr::new(label),
);

if colors {
Output::print(format_args!("\x1b[?25l")); // hide cursor
}
scopeguard::defer! {
if colors {
Output::print(format_args!("\x1b[?25h")); // show cursor
}
};
// Hide the cursor until this returns or the process exits.
let _cursor =
colors.then(|| bun_core::tty::DecModesGuard::set(bun_core::tty::dec::HIDDEN_CURSOR));

let mut selected: C = C::DEFAULT;
let mut initial_draw = true;
Expand Down
20 changes: 7 additions & 13 deletions src/runtime/cli/update_interactive_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1326,19 +1326,13 @@ impl UpdateInteractiveCommand {
Output::print(format_args!("\x1B[1A\x1B[2K")); // Move up one line and clear it too
Output::flush();

// Enable mouse tracking for scrolling (if terminal supports it)
if colors {
Output::print(format_args!("\x1b[?25l")); // hide cursor
Output::print(format_args!("\x1b[?1000h")); // Enable basic mouse tracking
Output::print(format_args!("\x1b[?1006h")); // Enable SGR extended mouse mode
}
scopeguard::defer! {
if colors {
Output::print(format_args!("\x1b[?25h")); // show cursor
Output::print(format_args!("\x1b[?1000l")); // Disable mouse tracking
Output::print(format_args!("\x1b[?1006l")); // Disable SGR extended mouse mode
}
}
// Hide the cursor and enable mouse reporting (for wheel scrolling)
// until this returns or the process exits.
let _modes = colors.then(|| {
bun_core::tty::DecModesGuard::set(
bun_core::tty::dec::HIDDEN_CURSOR | bun_core::tty::dec::MOUSE_REPORTING,
)
});

let mut initial_draw = true;
let mut reprint_menu = true;
Expand Down
44 changes: 44 additions & 0 deletions test/cli/init/init.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,50 @@ const initEnv = { ...bunEnv, BUN_AGENT_RULE_DISABLED: "1" };
expect(fs.existsSync(path.join(temp, "package.json"))).toBe(false);
});

// The template menu hides the cursor while it is up. A signal exit writes
// the startup termios back but the hidden cursor is terminal state, not
// termios: the exit path has to write `CSI ? 25 h` itself.
for (const signal of ["SIGINT", "SIGTERM"] as const) {
test.skipIf(isWindows)(`bun init shows the cursor again when ${signal} ends the template menu`, async () => {
await using temp = tempDir("bun-init-" + signal.toLowerCase(), {});

const decoder = new TextDecoder();
let output = "";
const hidden = Promise.withResolvers<void>();
const closed = Promise.withResolvers<void>();
await using proc = Bun.spawn({
cmd: [bunExe(), "init"],
cwd: String(temp),
// Colors on (the tty default), otherwise the menu leaves the cursor alone.
env: { ...initEnv, NO_COLOR: undefined },
terminal: {
cols: 80,
rows: 24,
data(_, chunk: Uint8Array) {
output += decoder.decode(chunk, { stream: true });
if (output.includes("\x1b[?25l")) hidden.resolve();
},
exit() {
closed.resolve();
},
},
});
const exitedEarly = proc.exited.then(code => {
throw new Error(`bun init exited before the menu (code ${code}):\n${output}`);
});
exitedEarly.catch(() => {});
await Promise.race([hidden.promise, exitedEarly]);

proc.kill(signal);
await proc.exited;
await closed.promise;

expect(output.slice(output.lastIndexOf("\x1b[?25l"))).toContain("\x1b[?25h");
expect(proc.signalCode).toBe(signal);
expect(fs.existsSync(path.join(temp, "package.json"))).toBe(false);
});
}

test("bun init in folder", async () => {
await using temp = tempDir("bun-init-in-folder", {
"mydir": {
Expand Down
56 changes: 56 additions & 0 deletions test/cli/update_interactive_formatting.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,62 @@ describe.concurrent("bun update --interactive", () => {
}
});

// The picker hides the cursor and turns on SGR mouse reporting. Key-driven
// exits undo both, but a signal (supervisor kill, `timeout 60 bun update -i`,
// CI cancel) ends the process through the exit-signal handler, which only
// wrote termios back: the shell was left typing `^[[<0;41;12M` on every
// click, with no cursor.
for (const signal of ["SIGINT", "SIGTERM"] as const) {
it.skipIf(isWindows)(`should reset cursor and mouse modes when ${signal} ends the picker`, async () => {
await using dir = tempDir("update-interactive-" + signal.toLowerCase(), {
"bunfig.toml": bunfig(),
"package.json": JSON.stringify({
name: "test-project",
version: "1.0.0",
dependencies: { "no-deps": "1.0.0" },
}),
});
await install(dir);

const decoder = new TextDecoder();
let output = "";
const shown = Promise.withResolvers<void>();
const closed = Promise.withResolvers<void>();
await using proc = Bun.spawn({
cmd: [bunExe(), "update", "--interactive", "--latest", "--dry-run"],
cwd: String(dir),
// Colors on (the tty default), otherwise the picker sets no modes.
env: { ...bunEnv, NO_COLOR: undefined },
terminal: {
cols: 120,
rows: 30,
data(_, chunk: Uint8Array) {
output += decoder.decode(chunk, { stream: true });
if (output.includes("\x1b[?1006h")) shown.resolve();
},
exit() {
closed.resolve();
},
},
});
const exitedEarly = proc.exited.then(code => {
throw new Error(`bun update -i exited before the picker (code ${code}):\n${output}`);
});
exitedEarly.catch(() => {});
await Promise.race([shown.promise, exitedEarly]);

proc.kill(signal);
await proc.exited;
await closed.promise;

const afterShown = output.slice(output.lastIndexOf("\x1b[?1006h"));
expect(afterShown).toContain("\x1b[?25h");
expect(afterShown).toContain("\x1b[?1000l");
expect(afterShown).toContain("\x1b[?1006l");
expect(proc.signalCode).toBe(signal);
});
}

it("should update packages when 'a' (select all) is used", async () => {
await using dir = tempDir("update-interactive-select-all", {
"bunfig.toml": bunfig(),
Expand Down
Loading
Loading