Skip to content
Closed
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
25 changes: 25 additions & 0 deletions patches/libuv/win-tty-read-stop-match-pending-req.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
--- a/src/win/tty.c
+++ b/src/win/tty.c
@@ -1093,7 +1093,21 @@ int uv__tty_read_stop(uv_tty_t* handle) {
if (!(handle->flags & UV_HANDLE_READ_PENDING))
return 0;

- if (uv__is_raw_tty_mode(handle->tty.rd.mode.mode)) {
+ /* Pick the cancellation method from the type of the still-pending request,
+ * not from mode.mode. uv_tty_set_mode() flips mode.mode between its calls
+ * to uv__tty_read_stop() and uv__tty_read_start(), so when it is called
+ * twice back-to-back (e.g. setRawMode(false) immediately followed by
+ * setRawMode(true) in the same tick) the second read_stop sees the new
+ * mode while the original request is still pending. Dispatching on
+ * mode.mode then sends the line-read cancel path against a raw request:
+ * it calls uv__cancel_read_console() (a no-op, no line read exists) and
+ * sets UV_HANDLE_CANCELLATION_PENDING, which is only ever cleared in
+ * uv_process_tty_read_line_req(), so it never clears. The next time a
+ * real line read needs cancelling, the flag is already set and the cancel
+ * is skipped, leaving ReadConsoleW blocked until the user presses Enter.
+ * read_line_buffer.len > 0 iff the pending request is a line read; this
+ * is the same invariant uv__process_tty_read_req() dispatches on. */
+ if (handle->tty.rd.read_line_buffer.len == 0) {
/* Cancel raw read. Write some bullshit event to force the console wait to
* return. */
memset(&record, 0, sizeof record);
32 changes: 23 additions & 9 deletions scripts/build/deps/libuv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,29 @@ export const libuv: Dependency = {
commit: LIBUV_COMMIT,
}),

// Re-arm the AFD ioctl before poll_cb (matching wepoll's
// port__update_events_if_polling-before-return). AFD is level-triggered
// (ReactOS AfdSelect: `Events & FCB->PollState` checked on IRP arrival),
// so a peer RST that lands during poll_cb is caught by the freshly-
// submitted req. Upstream libuv re-arms *after* poll_cb, leaving a gap
// an in-process loopback fetch().abort() can fall into. To upstream:
// send to libuv/libuv with the wepoll/ReactOS references in the patch
// comment as the rationale.
patches: ["patches/libuv/win-poll-rearm-before-callback.patch", "patches/libuv/win-poll-abort-with-disconnect.patch"],
patches: [
// Re-arm the AFD ioctl before poll_cb (matching wepoll's
// port__update_events_if_polling-before-return). AFD is level-triggered
// (ReactOS AfdSelect: `Events & FCB->PollState` checked on IRP arrival),
// so a peer RST that lands during poll_cb is caught by the freshly-
// submitted req. Upstream libuv re-arms *after* poll_cb, leaving a gap
// an in-process loopback fetch().abort() can fall into. To upstream:
// send to libuv/libuv with the wepoll/ReactOS references in the patch
// comment as the rationale.
"patches/libuv/win-poll-rearm-before-callback.patch",
"patches/libuv/win-poll-abort-with-disconnect.patch",
// uv__tty_read_stop picked the cancellation path from mode.mode, but
// uv_tty_set_mode flips mode.mode *between* stop/start. A synchronous
// setRawMode(false); setRawMode(true) hits read_stop twice against the
// same still-pending raw request; the second call sees mode=Normal,
// takes the line-read path, and sets UV_HANDLE_CANCELLATION_PENDING,
// which only uv_process_tty_read_line_req clears. The flag sticks, and
// the next real cooked-read cancel is skipped, leaving ReadConsoleW
// blocked until Enter (Ink reattach, readline reinit). Fix: dispatch on
// read_line_buffer.len (the pending-request type), same as
// uv__process_tty_read_req already does. Upstreamable as-is.
"patches/libuv/win-tty-read-stop-match-pending-req.patch",
],

build: () => ({
kind: "direct",
Expand Down
146 changes: 146 additions & 0 deletions test/js/node/tty.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
import { describe, expect, it, test } from "bun:test";
import { bunEnv, bunExe, isWindows } from "harness";
import os from "node:os";
import { WriteStream } from "node:tty";

// ConPTY on Windows 10 1809 / Server 2019 (build 17763) is the original v1
// implementation. It does not reliably propagate raw single-byte input to
// the child after the console mode has been bounced between cooked and raw
// — the child's stdin tty can error and its event loop drain under that
// sequence. The cancel-cooked-read test below exercises exactly that path,
// so skip it on pre-19041 (20H1) Windows where ConPTY got its first major
// input-handling overhaul. The libuv fix itself still ships for those
// builds; only the ConPTY-backed regression harness cannot observe it.
const windowsBuild = isWindows ? Number(os.release().split(".")[2] ?? 0) : 0;
const isConPTYv1 = isWindows && windowsBuild > 0 && windowsBuild < 19041;

describe("ReadStream.prototype.setRawMode", () => {
// Regression: on Windows, the `fd === 0` branch returned early on success
// without ever reaching `this.isRaw = flag`, so `process.stdin.isRaw` stayed
Expand Down Expand Up @@ -190,6 +202,140 @@ describe("ReadStream.prototype.setRawMode", () => {
});
expect(await proc.exited).toBe(0);
});

// Regression (Windows): a synchronous `setRawMode(false); setRawMode(true)`
// while a raw read is pending used to leave libuv's
// UV_HANDLE_CANCELLATION_PENDING stuck on the stdin tty. On the *next*
// `setRawMode(false)` → (yield) → `setRawMode(true)` cycle — where the
// yield lets a cooked ReadConsoleW actually get queued — `uv__tty_read_stop`
// saw the stale flag, skipped `uv__cancel_read_console`, and the worker
// thread stayed blocked in ReadConsoleW: the next raw keystroke was
// consumed by that read, dispatched through uv_process_tty_read_line_req,
// and dropped on the floor because CANCELLATION_PENDING was set. Seen in
// the wild as frozen-until-Enter / lost keystrokes after Ink App
// unmount/remount.
//
// On POSIX there is no reader thread and no line-read work item; termios
// mode changes take effect immediately on the same fd, so the sequence is
// a no-op there. The test still runs on POSIX to lock the behaviour in.
//
// Skipped on ConPTY v1 (Windows Server 2019 / 1809) — see isConPTYv1 above.
test.skipIf(isConPTYv1)(
"setRawMode(true) cancels a pending cooked read after a prior synchronous false/true bounce",
async () => {
let output = "";
const decoder = new TextDecoder();
const ready = Promise.withResolvers<void>();
const gotKey = Promise.withResolvers<void>();
const eof = Promise.withResolvers<void>();

const proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
const tick = () => new Promise(r => setImmediate(r));
let armed = false;
// Keepalive: an stdin-reader error after the mode bounce must not
// drain the event loop before the diagnostics below reach the
// parent. The interval never fires; it is purely a ref'd handle.
const keepalive = setInterval(() => {}, 1 << 30);
process.stdin.on("error", e => process.stdout.write("STDIN_ERR " + String(e) + " "));
process.on("uncaughtException", e => {
process.stdout.write("UNCAUGHT " + String(e) + " ");
process.exit(1);
});
process.stdin.setRawMode(true);
process.stdin.on("data", d => {
if (!armed) return; // ignore noise (FOCUS_EVENT echoes etc.) before READY
process.stdout.write("KEY " + JSON.stringify([...d]));
clearInterval(keepalive);
process.exit(0);
});
(async () => {
// Let the raw read arm (RegisterWaitForSingleObject on Windows).
await tick();
// First cycle, synchronous: both mode switches happen before the
// loop can process the raw-read completion. Before the fix this
// misroutes uv__tty_read_stop down the line-read path against a
// raw request, setting UV_HANDLE_CANCELLATION_PENDING on the
// stdin tty with nothing to ever clear it.
process.stdin.setRawMode(false);
process.stdin.setRawMode(true);
await tick();
// Second cycle: drop to cooked, then yield enough event-loop
// turns for libuv to process the raw-read completion, queue a
// line read (QueueUserWorkItem), and for the threadpool to pick
// it up and commit to ReadConsoleW.
process.stdin.setRawMode(false);
for (let i = 0; i < 20; i++) await tick();
// Before the fix, UV_HANDLE_CANCELLATION_PENDING is still set
// here so uv__tty_read_stop skips uv__cancel_read_console and
// the in-flight ReadConsoleW is never cancelled.
process.stdin.setRawMode(true);
armed = true;
process.stdout.write("READY");
})();
`,
],
env: bunEnv,
terminal: {
// Wide enough that ConPTY does not hard-wrap the KEY line.
cols: 200,
rows: 24,
data(_t, chunk: Uint8Array) {
output += decoder.decode(chunk, { stream: true });
if (output.includes("READY")) ready.resolve();
if (/KEY \[[^\]]*\]/.test(Bun.stripANSI(output))) gotKey.resolve();
},
exit() {
eof.resolve();
},
},
});

// Wait until the child has re-armed raw mode after the double bounce.
await Promise.race([ready.promise, eof.promise]);

// Send a single keystroke — no Enter. Before the fix this was swallowed
// by the uncancelled cooked ReadConsoleW (consumed and then dropped by
// uv_process_tty_read_line_req because CANCELLATION_PENDING was set).
proc.terminal!.write("x");

// Sentinel so the failure mode is a clean assertion rather than a hang:
// give the 'x' a generous number of loop turns to propagate through
// ConPTY and the child's raw read, then send a second keystroke. If the
// first one was lost (the bug), the raw read has since been re-armed by
// the line-req completion and the child receives the sentinel instead —
// failing the toContain('x') assertion with useful output.
for (let i = 0; i < 50; i++) {
if (/KEY \[[^\]]*\]/.test(Bun.stripANSI(output))) break;
await new Promise(r => setImmediate(r));
}
if (!/KEY \[[^\]]*\]/.test(Bun.stripANSI(output))) {
proc.terminal!.write("z");
}

await Promise.race([gotKey.promise, eof.promise]);
proc.kill();
await proc.exited;
proc.terminal?.close();
output += decoder.decode();

const stripped = Bun.stripANSI(output).replace(/[\r\n]/g, "");
const match = stripped.match(/KEY (\[[^\]]*\])/);
if (!match) {
throw new Error("child never received a keystroke in raw mode; terminal output was: " + JSON.stringify(output));
}
// The essential property is that the child's data handler fired for the
// first bare keystroke after re-entering raw mode — i.e. it was not
// swallowed by a stuck cooked ReadConsoleW. ConPTY may tack VT bytes
// around the payload and POSIX PTYs may translate, so just assert 'x'
// is present somewhere in the first chunk the child received.
const bytes = JSON.parse(match[1]);
expect(bytes).toContain("x".charCodeAt(0));
},
);
});

describe("WriteStream.prototype.getColorDepth", () => {
Expand Down
Loading