Repository navigation
Migrate the Windows terminal backend from winpty to ConPTY - #17814
Conversation
Temporarily un-ignores docs/superpowers to allow committing the spec and forthcoming plan; .gitignore and these docs will be reverted during final cleanup.
Address roborev design review: final-output drain before onExit, writer thread for input, bounded output buffer with backpressure, bounded deadlock-free shutdown, race guards, failure-path cleanup, move persistence bump into the integration phase, resolve CUSTOM-shell replay, and narrow the temporary .gitignore exception to specs/ and plans/.
Resolve the shutdown-while-paused deadlock: stop() wakes the backpressure-paused reader (stopped_ + notify outCv_) so drain/close cannot hang and final output is not lost. Writer abandons queued input on stop (clears queue, no resume). Bound the input queue with reject-on-overflow. Reuse the bounded teardown for partial-startup failures after CreateProcess. Surface writer errors via poll(). Scope tuning constants and the full test enumeration to the plan; Ctrl+C stays FIFO (unchanged from today).
Address review job 45: never detach the writer (CancelSynchronousIo unblocks it for a reliable join); closer thread captures only the HPCON so detach is the use-after-free-safe last resort; cap the output buffer during shutdown with a logged truncation; make stopped_/abandon_ atomic; launch reader/writer before CreateProcess to close the failure window; scope the lossless-final-output guarantee to normal shutdown; update the class sketch (abandon_, writerError_, byte accounting).
Address roborev review job 47: closer-first teardown so ClosePseudoConsole breaking both pipes is the reliable unblock (with repeated-cancel backstop for the writer TOCTOU and a single post-timeout cancel for the reader, never closing its handle under it); add ConPty::closeInput() so PTY stdin EOF is delivered; lock stateMutex_ in setSize; reject ConPty reuse after stop; surface async writer errors via takeWriterError() each poll tick; fold the console08 persistence bump into the atomic swap commit. Also introduce teardownLocked() in phase 1a as the single teardown path so the writer thread is always joined.
Address roborev review job 48: give the reader/writer teardown a bounded escalation ladder (closer breaks pipe -> CancelSynchronousIo -> last-resort close-our-handle) so join() can never hang even if the closer stalls and a cancel misses; document why closing our own handle is safe as the final teardown-only resort. Separate persistent writerExited_ (rejects further writeInput so input is never queued to a dead writer) from the report-once writerError_ that takeWriterError() clears. Replace the non-deterministic writer-error test with a deterministic input-rejection-after-EOF test.
Address roborev review job 49: remove the last-resort close-our-handle step (closing a handle under another thread's in-flight I/O is the handle-reuse race earlier reviews flagged; ConPTY's synchronous-handle requirement rules out cancelable overlapped I/O). Instead guarantee bounded joins via repeated CancelSynchronousIo, which always unblocks a thread in cancellable synchronous I/O; the writer loop-cancels, the reader drains cleanly first then falls back to the same loop. Handles are closed only after the joins. Document why deterministic writer-WriteFile-failure injection is declined (would need a production test seam) and keep the deterministic input-rejection-after-EOF test.
Phase 0 empirically validated the ConPTY contract on Windows: the build approach (dynamic kernel32 load under _WIN32_WINNT=0x601, attr 0x00020016) compiles and resolves; routing works with EXTENDED_STARTUPINFO_PRESENT + clean std handles + handle-close-order even when the host owns a console; a confound experiment isolated std-handle redirection (STARTF_USESTDHANDLES) as the real prior-failure cause, not console ownership (no FreeConsole needed); ClosePseudoConsole + a draining reader tears down non-cooperative children in single-digit ms. Add guardrails to launchChild against DETACHED_PROCESS/CREATE_NO_WINDOW/STARTF_USESTDHANDLES.
An empty Unicode environment block must still be two nulls; the prior single-null could make CreateProcessW read past the buffer (roborev job 52 finding #4).
Removes the async writer thread, input queue, and cap that could silently drop terminal input on overflow (roborev job 56). writeInput now does a blocking WriteFile on the caller thread, matching winpty. Simplifies teardown (no writer to join). Bump kConsoleDir to console08 only on Windows.
Terminal input may arrive on the websocket thread while stop()/closeInput() close hInputWrite_ on the session thread. Guard the handle with a dedicated inputMutex_; teardown closes the pseudoconsole first so an in-flight WriteFile returns before the handle is closed under the lock (deadlock-free). Also drop an unused iostream include. (roborev job 57)
writeInput held inputMutex_ across the blocking WriteFile, so closeInput()/ teardown could block behind a stalled write. Duplicate the handle under the lock and write on the duplicate outside it, so handle close never waits and there is no handle-reuse race. Add a concurrent write/closeInput watchdog test. (roborev job 58)
…th option The Windows terminal now uses ConPTY, so the winpty path/plainText/conerr Pseudoterminal fields and the external-winpty-path session option are dead. Trim the struct, update the terminal construction, drop the option, and regenerate SessionOptions.gen.hpp.
The --external-winpty-path option was removed, and the session option parser rejects unregistered options, so leaving this entry would break dev desktop session startup. (roborev job 60)
The Windows terminal now uses native ConPTY, so drop the winpty CMake include/install wiring, the install-dependencies fetch, the vendored winpty archive, and its license attribution.
ConPTY emits clean VT sequences (unlike WinPty's screen-scraped output), so recorded terminal buffers now replay faithfully on reconnect for all shell types. Always allow reload in shellSupportsReload().
shellSupportsReload() now always returns true after the ConPTY migration, so the createdByApi flag (threaded through SwitchToTerminalEvent, TerminalPopupMenu, TerminalTabPresenter, TerminalPane, TerminalDeckPanel, and TerminalSession) is no longer read anywhere. Remove the field, constructor params, event accessor, and the method parameters that carried it. (roborev job 63)
RStudio Desktop launches rsession from the Electron GUI with its std handles redirected to pipes; the ConPTY child inherited those by value instead of binding to the pseudoconsole, so terminals showed a blank cursor with no output or echo. Clear the host std handles across CreateProcessW so the child attaches to the pseudoconsole, then restore them. Add a regression test that spawns with the host std handles redirected to a file. (#3798)
…dle) Replace the process-global SetStdHandle(NULL)+restore around CreateProcess (which could race other threads/spawns) with a per-child fix: give the child explicit NULL std handles via STARTF_USESTDHANDLES so it cannot inherit rsession's redirected std handles by value and instead attaches to the pseudoconsole. Verified to route output and accept input. (roborev job 66)
A restarted terminal's ConPTY host emits a one-time screen clear (CSI 2J followed by a cursor home) when the new shell starts up (microsoft/terminal#4252). For shells whose scrollback we replay on reconnect (e.g. Git Bash), that clear was persisted into the replayable buffer, so replaying it wiped the restored history -- the terminal flashed the old output then went blank. Strip the clear (and its accompanying SGR reset and cursor home) from the restarted shell's first output, so the fresh prompt follows the preserved history inline. The strip is Windows-only, one-shot per restart, and applies only to shells that keep their buffer for replay; cmd/PowerShell already delete their buffer on restart and are unaffected. Other platforms are untouched (their PTYs emit no such clear).
Addresses review feedback on the previous commit: - The conhost startup clear can be split across output chunks; a regex run on a single chunk could miss it and persist the destructive bytes. Accumulate the restarted shell's initial output and resolve the clear across chunk boundaries (holding output until the frame is complete or a bound is hit) before buffering or forwarding it. - Strip only the first clear rather than every match, so a legitimate later clear (e.g. a real `clear`) in the same output is preserved, and clear the pending flag once resolved so it can't strip a future clear. Unit tests cover inline stripping, a clear split across chunks, and that only the first clear is removed.
Addresses review feedback: if a restarted shell emitted little output and never the expected clear, the previous logic could withhold output indefinitely (hiding the prompt) and drop the held bytes if the shell exited. Bound the hold to a small number of output callbacks; once the window closes the buffer is flushed (stripping a complete clear if present, but never withholding further). Also flush any held output from onExit() so nothing is lost when the shell exits before the clear resolves.
Addresses review feedback: bounding the hold by output-callback count didn't bound elapsed time -- a restarted shell that emitted a short prompt without a clear and then waited for input would keep that prompt hidden, since no further callback arrived to close the window. Instead, hold output only while it is purely the leading control sequences that precede the clear (where a clear may still arrive). As soon as real content (printable text or an OSC title) appears with no clear, forward immediately. Holding is therefore transient -- the conhost startup frame is emitted contiguously -- and visible content is never withheld waiting for output that will not come. The byte bound and onExit flush remain as backstops.
Addresses review feedback: with only a callback-count/byte bound, a restarted shell that emitted just leading control sequences and then idled could keep stripping enabled indefinitely, risking a later user-issued clear being mistaken for the startup clear. Record a short deadline (a few seconds) when the restart begins. Once it elapses, any held output is flushed unchanged and stripping stops, so a later clear is never affected. Visible content already flushes immediately (it is never part of the leading frame), and onExit still flushes anything held, so the deadline only bounds the rare control-only idle case.
Replace the cross-callback output-buffering approach (which had to defend a clear split across output reads) with a simple per-chunk strip. Each buffering variant introduced its own edge -- byte/callback bounds, idle stalls, withheld output -- because it withheld output waiting for a frame that the reader already delivers whole. Now: within a short window after restart, strip the first complete clear from output and forward immediately, never withholding. Stop once the clear is stripped or the window elapses, so a later user clear is unaffected. Mode-sets and the clear arriving in separate chunks are still handled (mode-sets forward harmlessly; the clear is stripped when it arrives). Only a clear split mid-escape-sequence is not handled, which the reader's whole-write delivery makes impractical.
If a restarted shell's first output is a prompt with no startup clear, stripping previously stayed armed until the deadline, so a user-issued clear in that window could be removed. Now, as soon as output containing visible content (printable text or an OSC) is forwarded without a clear, stop stripping -- the startup clear is absent. Combined with stopping after the clear is stripped (the normal case) and the deadline backstop, a later user clear is never affected. Still no buffering.
If a prompt and a user-issued clear were coalesced into one output callback, the previous code stripped the first clear it found -- removing the user's clear. Now a clear is stripped only when everything before it in the chunk is leading control output (mode-sets), which is true only for the conhost startup clear; a clear that follows visible content is a user clear and is left intact. Adds a same-chunk prompt-plus-clear test.
Command Prompt, PowerShell, PowerShell Core and (on Windows) custom shells had their saved buffer deleted on restart, a WinPty-era workaround from when those shells could not reload. The frontend now reports every shell as reloadable, so deleting the buffer left nothing to replay -- the terminal came back empty. Under ConPTY these shells emit clean VT and replay like any other, so keep their buffer on restart and arm the conhost startup-clear strip for them as well. This also makes the backend consistent on non-Windows, where PowerShell Core buffers were likewise being discarded.
Command Prompt and PowerShell repaint their startup screen with absolute cursor positioning -- PowerShell's PSReadLine redraws its whole banner and prompt on the reconnect resize -- which does not compose with replayed scrollback: the restored output is preserved but the fresh prompt lands in the middle of it. These shells never reloaded their buffer under winpty either, so keep reload disabled for them (shellSupportsReload returns false; the backend deletes their buffer on restart). Git Bash and other shells that position with relative line feeds still reload and keep the conhost startup-clear strip. Corrects the NEWS entry, which had claimed cmd/PowerShell scrollback restore.
Returning false outright for cmd/PowerShell also suppressed the initial replay an API-created terminal needs: such a terminal can emit its banner and prompt before the UI attaches, and those bytes live only in the saved buffer. The mid-output problem is specific to restart (a new shell's absolute-positioned repaint layered over restored content), so reload cmd/PowerShell unless the process was restarted. That still shows an API-created terminal's initial output and same-shell reconnect scrollback while suppressing the broken restart case (where the backend also deletes the buffer).
These internal design/plan docs were committed temporarily by relaxing the docs/superpowers ignore rule. Restore the single ignore line and drop the docs so they are not part of the change.
Address PR review findings on the ConPTY backend: - Surface the readOutput() error on the on-exit drain instead of dropping it, matching every other call site. - Salvage bytes delivered alongside a terminating read error/EOF and log genuinely unexpected reader-loop failures even when n > 0. - Track and report the dropped-byte count when a forced shutdown truncates output, replacing the context-free warning. - Read hPC_ under stateMutex_ in running() so the lifecycle state is observed consistently from any thread. - Clamp terminal dimensions to SHRT_MAX before the COORD cast so an absurd size cannot wrap negative. - Reject a null pProcess in start() before dereferencing it. - Drop stale implementation-plan and removed-winpty references from comments.
Address the PR review's test-gap findings: - Pin PROMPT in the prompt-waiting tests so the cmd prompt deterministically ends in '>', removing a silent hang-then-proceed flake when the runner has a custom PROMPT. - Add reuse-after-stop rejection, readOutput-after-stop, and setSize (live then post-stop) lifecycle tests. - Add environment-block and working-directory round-trip tests. - Add a cross-chunk startup-clear strip test exercising the keep-watching path across successive chunks. - Drop stale plan references from test comments.
teardownLocked() runs while holding stateMutex_, and its idempotent short-circuit called running(), which now re-locks the same non-recursive mutex. The first teardown short-circuits before that call (stopped_ was false), but a repeat teardown -- the destructor after an explicit stop() or a failed start -- evaluated running() and deadlocked. Read hPC_ directly instead, as start() and setSize() already do.
kevinushey
left a comment
There was a problem hiding this comment.
Summary
BLUF: This is genuinely good work -- and I went in looking for blood. A ConPTY rewrite touches three minefields at once (Win32 handle lifetime, multi-threaded teardown, and terminal VT semantics), and each one has clearly been walked. Handle ownership is accounted for on every error path, the teardown is ordered and idempotent, the reader/backpressure model is sound, and the test suite exercises the exact failure modes I would have demanded (shutdown-while-paused, concurrent write+stop, redirected host handles, fast-exit attach race). The dense comments document non-obvious Win32/ConPTY behavior rather than narrating the obvious -- they earn their place.
I found no blocking issues. The items below are verification gaps and refinements, not defects I can prove.
Critical Issues (Blocking)
None.
I specifically tried to break these and couldn't:
- Handle leaks: every failure path in
createPipesAndConsole(Win32ConPty.cpp:137-170) andlaunchChild(:199-268) closes what it opened; the attribute-listHeapAllocis freed on all four exit paths. - Teardown races:
teardownLocked(:449-505) closes the pseudoconsole on a thread capturing only the HPCON value, so a detached closer can't touch freed members; the reader is joined beforehOutputRead_is closed (:492before:499); theCancelSynchronousIobackstop loop guarantees the join can't hang. interrupt()no-op (:438-441): I assumed this silently broke the "Interrupt child" terminal command -- but the oldWinPty::interrupt()onmainis literally// TODO (gary)returningSuccess(). This is exact parity, not a regression. The real Ctrl+C fix for #3798 is ConPTY correctly translating the0x03input byte (verified byCtrlCByteTerminatesBusyChild).
Required Changes
Nothing rises to this tier. The code is not slop. The one thing close to it -- the command-line quoting in buildCommandLine (Win32ConPty.cpp:67-82), which doesn't escape embedded quotes or backslashes -- is a faithful copy of the pre-existing logic in Win32ChildProcess.cpp:531-547 (whose own comment admits "This is kind of gross"). Not a new defect, but see the DRY suggestion below.
Suggestions / Verify
-
[Verify -- gating] Manual validation is incomplete. The PR body says Windows desktop validation is "in progress." For a backend swap of this blast radius, that's the actual risk, not the code. Buffer reload, TUI alt-buffer, resize reflow, large paste, and Unicode should be confirmed green before merge.
-
[Verify]
--external-winpty-pathremoval and existing configs. The option is gone fromsession-options.json/SessionOptions.gen.hpp. If any deployed config file or launcher invocation still passes--external-winpty-path, confirm the session tolerates the unknown option rather than refusing to start. It was Windows-desktop-only, so risk is low -- but worth one check. -
[Verify] Worst-case
stop()latency is additive: ~8s.kShutdownTimeout(4s) gates both the closer wait (:475) and the reader wait before the cancel loop (:487). On a wedged conhost that's ~8s blocking whatever thread drives the run loop.ShutdownWhilePausedAtWatermarkbounds it at 8000ms, confirming the design but also confirming the ceiling. Consider splitting the budget or documenting the additive worst case. -
[Noted] Detached-closer thread leak on a truly hung
ClosePseudoConsole(:478). Bounded-probability and the documented pre-24H2 mitigation, but over a long session with many terminal open/close cycles a wedged host leaks a thread each time. Acceptable; just naming it. -
[Suggestion] DRY the quoting. Two copies of the same fragile quote-if-space-and-no-quote logic now exist (
Win32ConPty.cpp:75-79andWin32ChildProcess.cpp:537-546). Extracting one shared helper would mean a future fix lands in one place. -
[Suggestion]
setSizevalidation inconsistency.createPipesAndConsoleclampscols < 1up to 80 (:129-130), butsetSizerejectscols < 1asinvalid_argument(:423). Minor, but the same input is treated two ways. -
[Suggestion] CSI 2J split across read chunks isn't stripped.
stripRestartClearFromChunk(SessionConsoleProcess.cpp:655) regex-matches within a single chunk; if conhost's startup clear straddles twoReadFileboundaries,isPureLeadingControlkeeps watching but the next chunk starts mid-sequence and won't match. ConPTY emits it atomically in practice, and the failure mode is benign (history wiped once, rare). Worth a comment acknowledging the single-chunk assumption. -
[Suggestion] Dormant feature opportunity. Now that
0x03-as-input works,ptyInterrupt()could write0x03to make the "Interrupt child" menu command functional -- it's been a no-op since the winpty days. Out of scope for this PR, but a natural follow-up given #3798's theme.
Verdict
Approve (pending item 1).
No blocking issues after rigorous review. The concurrency model and handle discipline are correct as far as I can statically verify, and the tests are unusually honest about the hard cases. The only thing standing between this and merge is completing the manual Windows validation already flagged -- the bugs in a change like this live in real-shell behavior, not in the logic, and the logic is sound. Knock out the --external-winpty-path config check (item 2) on the way.
Backport of #18519 (9e0e8e9) to Yellow Yarrow. The multiarch Windows Desktop build installs the 32-bit session into <build>/src/cpp/session/x86, and the 64-bit build had an install rule that collected that directory into resources/app/bin/x86 at package time. That rule sat inside an "install winpty on windows" block and was deleted with it in 04db3f5 (#17814), so the shipped installer has resources/app/bin/x86 with only the x86 VC runtime DLLs -- no rsession.exe, and since #18070 no rsession.dll. With a 32-bit R, session-launcher.ts finds no x86/rsession.exe and falls back to the 64-bit session, which cannot load a 32-bit R.dll. Restore the rule under a comment that names its actual source, and keep the file(MAKE_DIRECTORY) call: install(DIRECTORY) errors on a missing source directory, and non-multiarch builds never create it. This is what makes the x86 binaries signed by 999de99 (#18562) actually reach the installer. The NEWS entry goes in version/news/os/NEWS-2026.08.1-yellow-yarrow.md, since NEWS.md is not carried on this branch. Addresses #18558
Intent
Addresses #3798.
Summary
The Windows terminal pane now uses the native Windows pseudoconsole (ConPTY) instead of the winpty library. winpty predates ConPTY; RStudio supports Windows 11 and current Windows 10, where ConPTY is always available.
Backend
ConPtyclass (src/cpp/core/system/Win32ConPty.{hpp,cpp}) that resolvesCreatePseudoConsole/ResizePseudoConsole/ClosePseudoConsoledynamically from kernel32, launches the child throughSTARTUPINFOEXwith the pseudoconsole attribute, reads output on a dedicated thread into a bounded buffer with backpressure, writes input synchronously, sends Ctrl+C as0x03, and tears down by closing the pseudoconsole on a separate thread while the reader drains.Win32ChildProcessusesConPtyfor terminal processes. The winpty backend, theWin32Ptyclass, and the--external-winpty-pathsession option are removed.CMakeLists.txt,install-dependencies.cmd), thePseudoterminaloptions,NOTICE, and the dev config.Terminal buffer reload on restart
Tests
Validation
Manual desktop validation on Windows is in progress: per-shell start/echo, Ctrl+C on a busy command, TUI alt-buffer, resize reflow, buffer reload, Unicode, large paste, and confirming no winpty-agent.exe process.