portless leaves orphaned dev servers and a corrupted console input mode (keystrokes get swallowed)
Disclosure: researched with a coding agent (AI-assisted)
I am a portless user on Windows. The investigation behind this report — console-mode and process-table instrumentation, reading the shipped bundle and
main, and the A/B control experiments — was done in a session with a coding agent that had shell access to the affected machine, and this write-up is AI-assisted.Every number below is a real measurement from that machine, run and re-run with the commands shown; anything derived from source rather than observed is labelled inferred / "source-level reasoning". The agent did not author a patch, so "Suggested fixes" are directions rather than a tested diff — the A/B-verified parts are the
taskkill /Tbehaviour in section 1 and the exit-path control in section 2 (graceful exit →0x0E7vstaskkill /F→0x208). Everything else is measurement or source reading, labelled as such.This started as a user-level symptom ("after exiting portless I have to hit keys several times, and Enter still eventually runs"), so the repro is hand-run PowerShell rather than an automated test; see the "Why this is not a duplicate" section just below (after Environment) for what is and is not new here.
Environment
- Windows 10.0.29667, Windows Terminal / ConPTY
- Node v24.14.0
- portless 0.13.1 (installed globally with pnpm)
- Reproduced with PowerShell 5.1 (Windows PowerShell) + Powershell 7.6.6 + PSReadLine 2.4.5,
cmd.exe, and Git Bash C:\Program Files\nodejs\node.exeis the child runtime
Why this is not a duplicate of the existing issues
I searched the tracker first (keywords: console, stdin, keystroke, taskkill, orphan,
kill tree, "input mode", windows; the issue list view only reaches back to #181, so the rest
was searched through the GitHub search API). Result:
| existing | what it covers | how this report differs |
|---|---|---|
| #288 (open) | hostless free-port probe — the same bug as defect 4 here | Not different: same defect, already open, already fixed once (PR #302, closed unmerged). It is carried here only so the repro is honest about why it needs --app-port. Please consolidate on #288 — I am not asking for that part to be triaged again. |
| #322 (closed) + PR #385 (merged) | orphans when the parent is signalled; fixed with POSIX process groups (ps -axo, kill(-pgid)) |
Same family (parent dies, child survives), different platform reach and different symptom. trackProcessTree() returns early on Windows, so the Windows tree is still killed root-only — that part is still open, not a regression. #322 also reports damage to .next/dev/lock on macOS/Linux; nothing there concerns a damaged console. |
| #411 (+ PR #413, open) | an orphan left by a child that self-daemonizes (it exits 0 while its server keeps listening) | Different trigger (child leaves on its own vs. parent force-killed) and different damage (route dropped, prune blind). That orphan detaches from the terminal, so it does not read stdin; mine stays attached to the console and is what eats the keystrokes. |
| #382 (+ PR #383, open) | routes.json torn when a kill lands mid-cleanup |
Shares the "killed at the wrong moment" cause but is about file integrity. It never touches console mode or input records, and its reporters can still type into their shell. |
| #311 (PR, open) | SIGHUP not wired into cleanup | Narrower signal-coverage fix. Windows terminals never deliver SIGHUP to the app, so it cannot reach defects 1–3. |
| #259 (open) | feature request: --no-stdin for runtimes with interactive stdin handlers |
Not a duplicate; it is the cheapest mitigation for defects 2 + 3 (a child with stdin.isTTY === false never calls setRawMode and never reads the console). It does not remove the orphan, and it does not repair a console that is already dirty. |
What is actually new here: defects 2 and 3. keystroke and "input mode" return zero results,
and every console match is about flashing windows (PR #223 / PR #428), cmd.exe argument quoting
(PR #160 / PR #354) or PATH length (#305 / PR #306) — nobody has reported a console input mode left
corrupted, or a surviving child eating the shell's input records. Defect 1 is a re-report of an
unfixed platform gap (PR #385 is why it exists); defect 4 is a duplicate of #288.
Windows-console changes are clearly accepted in this repo when they come with traces — see PR #160, PR #223, PR #428, PR #155 / #247 / #306 — which is the bar this report tries to meet.
Summary
On Windows, portless <name> <command> produces three defects that together make the shell that
launched portless misbehave after portless exits, plus an unrelated Windows-only port bug:
killTree()never kills the dev-server process tree — only thecmd.exewrapper dies, so the real dev server survives as an orphan.- The console input mode is never restored to its original value. The leftover value is never
PROCESSED_INPUT|LINE_INPUT|ECHO_INPUT|INSERT_MODE|QUICK_EDIT_MODE|EXTENDED_FLAGS(0xE7, the normal state) and it does not self-heal: either ECHO/LINE are gone (0x200/0x208) orVIRTUAL_TERMINAL_INPUTis left on with INSERT_MODE/QUICK_EDIT/EXTENDED lost (0x20F). - The surviving raw-mode dev server keeps reading from the same console, so it competes
with the shell for console input records. The console hands each input record to whichever
read request is pending, so a typed command is split between the two readers at a timing-
dependent point — either the user presses keys several times before a character lands, or the
characters land but the orphan takes the
Enterso the line never executes. - (Unrelated, also Windows-only)
findFreePort()probes with a host-lesslisten(), so it hands the child a port that the child cannot actually bind.
1. killTree() never kills the dev-server tree on Windows
dist/cli.js:
function killTree(child, signal = "SIGTERM") {
if (!child.pid) { child.kill(signal); return; }
if (!isWindows) {
try { process.kill(-child.pid, signal); return; } catch {}
}
try { child.kill(signal); } catch {}
}and spawnCommand() spawns the user command through a cmd.exe wrapper:
const child = isWindows
? spawn("cmd.exe", ["/d", "/s", "/c", commandArgs.join(" ")], { stdio: "inherit", env })
: spawn("/bin/sh", ["-c", commandArgs.map(shellEscape).join(" ")], { stdio: "inherit", env, detached: true });So the process tree is
powershell/cmd/bash ── portless(node) ── cmd.exe ── node <dev server>and child.kill() on Windows is TerminateProcess(cmd.exe). The grandchild — the actual
dev server — is never signalled. Verified by force-killing the portless process only:
$ portless demo --app-port 3000 node dev.js
DEVUP pid=40364 ppid=41504 port=3000 tty=true raw=true
$ taskkill /F /PID 36748 # portless itself
$ # process table afterwards:
40364 ppid=41504 node.exe # <-- dev server alive, parent chain brokenSame result in separate runs on cmd.exe (DEVUP pid=13324, portless 18276) and Git Bash
(DEVUP pid=6124, portless 38892).
Still true on main today (checked 2026-09-28 against packages/portless/src/cli-utils.ts).
main now has a graceful-shutdown path (from PR #385), but it is POSIX-only on purpose:
// cli-utils.ts — trackProcessTree()
tracked.set(rootPid, { pid: rootPid, pgid: rootPid });
if (isWindows) {
return; // <- no descendant walk on Windows
}
// … walks `ps -axo pid=,ppid=,pgid=` to find descendantsso on Windows signalTrackedProcesses() (which does process.kill(pid, signal) per tracked pid)
only ever signals the root, and killTree()'s Windows branch is still the single child.kill(signal)
shown above. Windows has neither ps nor process groups to lean on, so the fix has to be different
(taskkill /T or a Job Object) — see "Suggested fixes".
2. The console input mode is never restored
Measured on the console shared by the shell, with GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE))
(see the probe script below):
| moment | mode | decoded |
|---|---|---|
| shell at a clean prompt | 0x0E7 |
PROCESSED_INPUT+LINE_INPUT+ECHO_INPUT+INSERT_MODE+QUICK_EDIT_MODE+EXTENDED_FLAGS |
while portless + raw-mode dev server run |
0x208 |
PROCESSED_INPUT+VIRTUAL_TERMINAL_INPUT |
| after portless is force-killed | 0x200 |
VIRTUAL_TERMINAL_INPUT (persists; measured again later, unchanged) |
| after a fully graceful portless exit (dev server exits by itself, portless exits normally, no signals involved) | 0x20F |
PROCESSED_INPUT+LINE_INPUT+ECHO_INPUT+WINDOW_INPUT+VIRTUAL_TERMINAL_INPUT |
The value also drifts between 0x200 / 0x208 / 0x20F across runs, i.e. it is a race
between whoever restores the mode last.
Control experiment isolating the kill path (same console, same child, only the exit path differs):
| child exit path | console mode after the child is gone |
|---|---|
process.exit(0) (normal exit) |
0x0E7 — fully restored |
taskkill /F (= what child.kill() does on Windows) |
0x208 — permanently left dirty |
Analysis: the bundled dist/cli.js (line ~6097 in 0.13.1) only does
(packages/portless/src/cli.ts in main() on main — unchanged):
if (process.stdin.isTTY) {
process.on("exit", () => { try { process.stdin.setRawMode(false); } catch {} });
}setRawMode(false) maps to libuv's uv_tty_set_mode(UV_TTY_MODE_NORMAL), which on Windows
installs a hardcoded flag set (ENABLE_ECHO_INPUT|ENABLE_LINE_INPUT|ENABLE_PROCESSED_INPUT)
instead of restoring the original mode. That matches the observed 0x20F exactly: it is
ECHO|LINE|PROCESSED (0x07) plus ENABLE_WINDOW_INPUT and ENABLE_VIRTUAL_TERMINAL_INPUT
left over from the raw mode, while INSERT_MODE, MOUSE_INPUT, QUICK_EDIT_MODE and
EXTENDED_FLAGS are lost. (libuv-internals part is source-level reasoning; the mode values
above are measured.)
Additionally, process.on("exit", ...) does not run for TerminateProcess, signals delivered
by the OS, or a crashed/closed terminal, so even this partial restore is skipped in practice.
Note that this defect alone does not swallow input. Measured on the same console after the child had been force-killed (so no second reader was left) but with the mode still dirty:
$ Get-ConMode # child is gone, mode was never restored
0x208 [PROCESSED_INPUT+VIRTUAL_TERMINAL_INPUT]
$ echo AFTER_DIRTY
AFTER_DIRTY # command executed fine, mode stayed 0x208i.e. a dirty mode costs echo, line editing and cursor-key handling, but a surviving second reader (defect 3) is what actually steals the records.
3. The surviving raw-mode process steals the shell's keystrokes
The dev server is still attached to the same console (GetConsoleProcessList):
MODE=0x208 ATTACHED_COUNT=7
ATTACHED=… 40364:node(dev.js) 41504:cmd 36748:node(portless) … 8792:powershell …and it keeps reading stdin in raw mode. Injecting a command into the shell that shared that console (the dev server logs every byte it receives):
| shell | injected | delivered to the shell | eaten by the orphan dev server |
|---|---|---|---|
| PowerShell 5.1 | echo ZZZ1\r (10 B) |
1 byte (e) |
9 bytes "cho ZZZ1\r" |
| PowerShell 5.1 | echo QQQQ777\r (12 B) |
0 bytes | 12 bytes "cho QQQQ777\r" |
| cmd.exe | echo ZZZ1\r (10 B) |
10 bytes (worked) | 0 |
| cmd.exe | ping -n 3 127.0.0.1 >nul\recho CT1\r (34 B) |
0 bytes | 34 bytes |
| Git Bash | echo GB1\necho GB2\n (18 B) |
0 bytes | 18 bytes |
So it is not shell-specific. It is also not random per byte: the console delivers input records to whichever read request is pending, so the split point is set by which reader is blocked in a read at that instant. Injecting the same command as one write vs. character-by-character moves the split point to the opposite end, deterministically (same console, same machine, 8 and 6 runs; the "pending read wins the record" mechanism is inferred from this behaviour, the counts are measured):
| injection cadence | result |
|---|---|
whole line in one write (echo A3 + CR) |
shell kept the first byte only; the orphan took cho A3 + CR — 8/8 runs identical |
| one character per write, 45 ms apart, CR 200 ms later | shell received every character; the orphan took only the CR — 6/6 runs identical |
That is why it presents as both "sometimes I have to press the keys several times before it lands"
and "the text shows up but nothing runs until I hit Enter again" — the two are the same defect at
different cadences. With real interactive typing the timing varies, which is why the older
observation set (cmd.exe, second injection of the session) looked inconsistent; the only
confounder there is that an extra raw-mode process had joined that console in between.
Minimal isolation of the mechanism, with no portless involved (plain PowerShell console plus a
sibling that only does process.stdin.setRawMode(true); process.stdin.resume()):
$ Start-Process node -NoNewWindow -ArgumentList '<raw-mode sibling>.js'
$ Get-ConMode
0x208 …
PS> echo ST1<CR> # 9 bytes injected
[XSTOLE 8] "cho ST1\r" # sibling consumed 8 of them, PowerShell got only the first byte4. findFreePort() probes the wrong bind address on Windows
const server = net.createServer();
server.listen(port, () => { server.close(() => resolve(true)); });listen(port) without a host binds :: on Windows, while frameworks bind 127.0.0.1.
On this machine port 4395 is blocked for IPv4 only:
0.0.0.0:4395 -> EADDRINUSE
127.0.0.1:4395 -> EACCES
::4395 -> OKnetstat -ano shows no owner, so it is a WFP/dynamic exclusion rather than a real listener.
portless therefore reports -- Using port 4395, passes PORT=4395 to the dev server, and the
dev server dies immediately:
Error: listen EACCES: permission denied 127.0.0.1:4395Duplicate of #288 — open since 2026-05-06, reproduced independently on macOS with the same
split (listen(4051) → free, listen(4051, "127.0.0.1") → EADDRINUSE), and PR #302 fixed it
before being closed unmerged; two commenters have since asked the maintainers to take a refreshed
PR. Still hostless on main (cli-utils.ts → findFreePort). I hit it only because it forces
--app-port in the repro below, so treat this section as a duplicate and not as new work.
Minimal repro (defects 1 + 2 + 3)
dev.js — stands in for Vite/Next, which put the console into raw mode for keypress handling:
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.on('data', (b) => console.log('[dev stole]', JSON.stringify(b.toString())));
require('http').createServer((_, res) => res.end('ok')).listen(Number(process.env.PORT), '127.0.0.1',
() => console.log('DEVUP pid=' + process.pid + ' ppid=' + process.ppid));
setInterval(() => {}, 1000);PS> portless demo --app-port 3000 node dev.js # --app-port avoids defect 4
PS> # wait for DEVUP, then kill the portless process only
PS> taskkill /F /PID <portless pid>
PS> Get-Process node # dev server is still alive
PS> # now type a command — characters and/or the Enter get taken by the orphan
PS> # (which side loses depends on typing cadence; see section 3)Console mode probe (PowerShell 5.1):
Add-Type -Namespace W -Name K -MemberDefinition @'
[DllImport("kernel32.dll", SetLastError=true)] public static extern IntPtr GetStdHandle(int n);
[DllImport("kernel32.dll", SetLastError=true)] public static extern bool GetConsoleMode(IntPtr h, out uint m);
[DllImport("kernel32.dll", SetLastError=true)] public static extern bool SetConsoleMode(IntPtr h, uint m);
'@
$h = [W.K]::GetStdHandle(-10); $m = [uint32]0
[void][W.K]::GetConsoleMode($h, [ref]$m); '0x{0:X}' -f $mSuggested fixes
killTree()— kill the tree on Windows, not just the wrapper:if (isWindows) { try { execFileSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore" }); return; } catch {} }(or create the child inside a Job Object with
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE).Console mode — do not rely on
setRawMode(false). ReadGetConsoleModebefore spawning the child, and write the saved value back on every exit path (exit,SIGINT,SIGTERM,SIGHUP,uncaughtException), because libuv's "normal" mode writes a hardcoded flag set and never clearsENABLE_VIRTUAL_TERMINAL_INPUT. Node cannot P/Invoke, so this needs either a tiny bundled native helper or a documentedpowershell -NoProfile -Commandone-shot on the exit path. Note that no JS-level hook can coverTerminateProcess/ closed-terminal paths, so this is best-effort by construction — it fixes the mode only when portless gets to exit on its own. The user-visible symptom, however, is mostly fixed by (1): with no orphan left attached to the console there is no second reader to fight over the input records, and a child that exits gracefully restores the mode itself (process.exit(0)→0x0E7, measured).findFreePort()— probe the address the child will actually bind:server.listen(port, "127.0.0.1", ...)(and, if--lan/HOSTcan be non-loopback, probe for that address), or hand the already-bound listener to the child. (= #288 / PR #302.)(Cheap, optional) Stop handing the console to the child as stdin —
stdio: ["ignore", "inherit", "inherit"], or the--no-stdinflag requested in #259. A child whosestdin.isTTYis false never callssetRawMode, so defects 2 and 3 cannot occur in the first place; the cost is losing dev-server keypress shortcuts (Vite'srto restart,qto quit). This is a mitigation, not a replacement for (1) — it does nothing for the orphan itself.
Workarounds for users
- After exiting portless, look for orphans:
Get-Process node/tasklist | findstr nodeand kill the leftover chain with/T(taskkill /PID <pid> /T /F) — they are what steals the keystrokes. - If the shell is already corrupted, kill the orphan chain first, then reset the console input
mode with the
SetConsoleModecall in the probe above (e.g. back to0xE7). Resetting the mode while the orphan is still alive does not stop the stealing — it only brings back echo/line editing. Closing the affected window and opening a new one is faster and always works (a new window gets a new console). portless proxy stopto clean up a leftover proxy that a killed portless left behind.
Verification of fix 1
The proposed taskkill /T /F behaviour was A/B tested on this machine by reproducing the
cmd.exe wrapper → node child chain directly:
taskkill /F (wrapper only) cmdPid=39540 childPids=39056 childrenAliveAfterKill=39056
taskkill /T /F (whole tree) cmdPid=35008 childPids=45952 childrenAliveAfterKill=i.e. without /T the dev server survives (current behaviour), with /T the tree is gone.
Live evidence from a real machine (not a synthetic repro)
Scanning every console on the affected machine (GetConsoleProcessList + GetConsoleMode
per console) found this, with no artificial test in place:
console title 'PowerShell' mode=0x1E4 (ECHO on, LINE/PROCESSED off) members=4
35668:pwsh.exe 39388:pnpm.exe 43388:cmd.exe
+ a powershell probe
orphan chain:
pid=43388 cmd.exe(43388) <- pnpm.exe(39388) <- <35104 dead> :: "C:\WINDOWS\system32\cmd.exe" /d /s /c vite
pid=39388 pnpm.exe(39388) <- <35104 dead> :: pnpm run dev
pid=44892 node.exe(44892) <- <15524 dead> :: portless proxy start --foregroundcmd.exe /d /s /c vite is exactly what spawnCommand() produces; its ancestor (the portless
node pro
Source: vercel-labs/portless