Skip to content

repl: PSReadLine-style paste-chunk detection for the Windows console path - #252

Merged
caomengxuan666 merged 1 commit into
masterfrom
feat/paste-chunk-detect
Oct 10, 2026
Merged

caomengxuan666 merged 1 commit into
masterfrom
feat/paste-chunk-detect

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Follows #234 and #202.

Problem

#234 enabled bracketed paste for non-Windows only: crossterm's Win32 console input has no ANSI parser, and ConPTY swallows the ?2004 markers before any parser would see them (crossterm-rs/crossterm#737). On Windows a terminal paste therefore arrives as per-line KeyCode::Char / KeyCode::Enter key events, and reedline's read loop stops draining at each bare Enter — every pasted line repaints a full prompt cycle and EXECUTES as it arrives: #202's slow, self-executing multiline paste (measured below: 186 of 200 lines execute mid-paste, 176 KB of repaint output, 15-17 s).

Approach

reedline has no host-visible event translation layer, but EditMode is a trait — this adds PasteChunkEditMode, a wrapper that delegates to Emacs/Vi and reproduces PSReadLine's arrival-burst heuristic at the parse_event seam:

  • key events closer than 50 ms apart are paste data (the floor of sustained human typing is ~66 ms between keys);
  • a burst's bare Enters — plus the Enter + CONTROL the console reports for a CRLF's LF — are buffered into a pending chunk instead of submitting; the CRLF pair is deduplicated to one line break;
  • while a chunk is pending the paste is quiet (ReedlineEvent::None, zero repaints — PSReadLine's paste silence);
  • when a gap marks the burst's end, the whole chunk is committed as ONE InsertString (one repaint), and the user's own lone Enter submits the buffered script exactly once — the paste's trailing newline never self-executes, matching GNU bash paste semantics.

cfg(windows)-gated: Unix keeps the real bracketed paste of #234 (its Event::Paste never emits a bare Enter). The Ctrl+V PasteSystem clipboard path produces no Enter events and is untouched. ConPTY's focus flicker between pasted lines maps to ReedlineEvent::None upstream and passes through, so it cannot break a pending burst.

Bench (scripts/perf/paste_multiline_bench.py, winpty/ConPTY)

metric (200-line raw paste) before after
executions during paste 186/200 0
output volume 176 KB 3.3 KB
wall time 15-17 s 3.9 s
issue202 author payload (257 lines, set -euo pipefail) >300 s (timeout) 4.6 s

After the paste settles, the user's Enter executes the whole buffered script once (bad_executions_total = 199), which is the GNU-bash/PSReadLine behavior.

Tests

5 new unit tests: burst absorption with CRLF pairing, flush-on-gap submit, lone-Enter submit, stale-burst non-swallowing (the user's Enter after a settled paste must never be swallowed), and typing-pace safety. Full suite: 400 passed, 0 failed. cargo fmt clean.

…path

Windows gets no bracketed paste: crossterm's console input has no ANSI
parser and ConPTY swallows the ?2004 markers (crossterm#737), so a
terminal paste arrives as per-line key events that reedline executes as
they arrive — niubash#202's slow, self-executing multiline paste.

Add PasteChunkEditMode, an EditMode wrapper at reedline's parse_event
seam (cfg(windows) only; Unix keeps the real bracketed paste of #234).
It reproduces PSReadLine's arrival-burst heuristic: key events closer
than 50 ms apart are paste data — the floor of sustained human typing is
~66 ms between keys — so a burst's bare Enters (and the Enter+CONTROL
that the console reports for a CRLF's LF) are buffered into a pending
chunk instead of submitting. The chunk stays quiet (ReedlineEvent::None,
no per-line repaints) and is committed as ONE InsertString when a gap
marks the burst's end; the user's own Enter then submits the buffered
script exactly once.

ConPTY focus flicker between pasted lines maps to ReedlineEvent::None
upstream and is passed through so it cannot break a pending burst.

Bench (scripts/perf/paste_multiline_bench.py, 200-line raw paste,
winpty/ConPTY): paste-phase executions 186 -> 0, output volume 176 KB
-> 3.3 KB, wall time 15-17 s -> 3.9 s. The issue202 author payload
(257 lines, set -euo pipefail) drops from >300 s (timeout) to 4.6 s.
The paste's trailing newline never self-executes; the whole buffer
executes once on the user's Enter, matching GNU bash paste semantics.

Unit tests cover burst absorption, CRLF pairing, flush-on-gap submit,
lone-Enter submit, stale-burst non-swallowing, and typing-pace safety.
@caomengxuan666
caomengxuan666 merged commit 5438781 into master Oct 10, 2026
3 of 9 checks passed
@caomengxuan666
caomengxuan666 deleted the feat/paste-chunk-detect branch October 10, 2026 06:31
caomengxuan666 added a commit that referenced this pull request Oct 10, 2026
…notes draft (#254)

- Version 1.3.4 -> 1.4.0 (workspace root + crates/niubash-runtime;
  Cargo.lock synced; internal niubash-runtime dep requirement aligned
  1.2.5 -> 1.4.0). The rubash engine requirement stays 1.3.4: it is
  semver-open (^1.3.4 admits the engine's 1.4.0), and the committed
  [patch] resolves it to the local ../rubash worktree, whose Cargo.toml
  still says 1.3.4 until the engine cuts its own release.
- CHANGELOG: the Unreleased section becomes [1.4.0] - 2026-10-10. Also
  repairs the committed merge damage from #243 (stray conflict marker
  and the #241 doctor-advice entry glued onto the carapace entry) and
  folds in the merged cycle: #235 #239 #246 #247 #250 #251 #252 #253
  plus a compact rubash 1.4.0 engine summary. #240's P2-batch content
  stays under [1.3.4] where the file already records it (no dup).
- docs/release-notes-1.4.0-draft.md: zh+en draft release notes
  (Added / Fixed / Performance), winuxcmd #1151/#1154-#1157 marked as
  in-flight for the coordinator, plus the local verification log:
  release build PASS (niu.exe 10.6 MB), MSIX packed unsigned with a
  placeholder identity (5.1 MB), wpm-source main carries all four
  preinstall packages, and cargo publish --dry-run chain findings
  (rubash -> niubash-runtime -> niubash, blocked on the engine's
  crates.io release).

No tag, no release workflow trigger, no in-flight PRs merged.
caomengxuan666 added a commit that referenced this pull request Oct 10, 2026
….4.0 (#258)

#257 added a git source line with a pinned rev, but cargo compares a
branch dependency's lock state against the branch HEAD it resolves, so
the recorded rev alone did not satisfy --locked. The historically green
form (e6ea561 'rubash 1.3.3 pin' through #252) carries no source line at
all: --locked stays satisfied as long as the entry's version matches the
version rubash master resolves to (now 1.4.0 since #498). Restore exactly
that form, version-only. Future rubash version bumps need the same
one-line lock sync (see e6ea561 for the release-time precedent).
caomengxuan666 added a commit that referenced this pull request Oct 12, 2026
… issue202 default load, honest harness accounting, full provenance (#261)

The bench still measured the pre-#252 world and its elapsed number mixed
path cost with harness artifacts:

- Default payload was synthetic/200; the calibrated workload is the
  issue202 author payload (257-line fixture, >300 s -> ~4.6 s, CHANGELOG
  1.4.0). issue202 is now the default.
- The bracket flavor timed a path that does not exist on Windows: ConPTY
  swallows the ?2004/?201~ markers (crossterm#737), so a bracketed
  paste through ConPTY exercised the same raw per-line feed as raw — a
  duplicate datapoint under a misleading name (#252 is the Windows
  replacement for bracketed paste; Unix keeps #234's Event::Paste and
  never runs the heuristic). The bench feeds exactly one shape now: the
  raw Ctrl+V burst.
- elapsed smeared in a fixed 0.3 s quiet drain and up to 1 s of retry
  quantization with nothing separating them from the path. The drain is
  now reported as settle_wait (path-vs-harness split), enters_sent counts
  absorbed submit attempts, and the harness cadence (0.3 s settle, 1.0 s
  Enter resend) is a documented contract so elapsed stays comparable with
  the CHANGELOG ~4.6 s reference.
- Bare-line marker matching is incremental (new chunks + carried tail)
  instead of rescanning the whole accumulator every poll tick, so the
  harness's own CPU cannot distort timing on a regressed high-output path.
- Output now carries provenance: the niu --version banner (build rev),
  niubash rev, OS/python/pywinpty, payload stats (pasted lines vs the
  257-line fixture — the post's trailing blank lines are not paste data)
  and the exact repro command. --json emits one object per case for CI.

Windows-only by nature (cfg(windows) code under test, pywinpty/ConPTY
driver): non-Windows runs now explain and exit 2 instead of failing on
the import. CI shape is the existing windows-latest + pywinpty setup the
perfbudget-trend job already uses; documented in the module docstring.

Verified against a fresh build of master (11c1612): issue202 elapsed
4.58-4.60 s (CHANGELOG ~4.6 s), bad_executions_paste 0, bytes_out ~3.7 KB;
synthetic/200 elapsed 3.98 s, bad_executions_total 199 (one execution of
the submitted script, by design).
caomengxuan666 added a commit that referenced this pull request Oct 13, 2026
… timing (#284) (#288)

The 50 ms arrival-burst heuristic of #252 classified every bare Enter
that arrived within one burst as paste data, so "text + Enter" in a
single feed - fast human typing, ConPTY test drivers' send_line,
expect scripts, send-keys - lost its submit and needed a second Enter.
35/47 tests/interactive.rs cases timed out on that swallow.

The submit-versus-paste decision at a bare Enter is now structural:
a machine-fed line break is a CRLF pair (the LF surfaces as
Enter + CONTROL), and reedline's own batch loop stops at a bare Enter,
so the pair's LF is always still queued when the CR is dispatched.
A bounded lookahead (PASTE_LF_PROBE, 10 ms) peeks at the queue: an LF
partner proves paste - the pair folds into the pending chunk and the
Enter never reaches reedline; any other queued key or silence proves a
typed submit, and the lookahead's read is pushed back so it lands, in
order, at the next prompt (GNU typeahead semantics). A bare Ctrl+J
opens a chunk by itself (humans do not submit with it). The 50 ms gap
keeps one job: the burst boundary where a pending chunk flushes as ONE
InsertString.

Multi-line paste keeps buffering quietly until the user's Enter - the
niubash#202 contract holds: the 257-line issue payload benches at
4.62 s end to end with 0 mid-paste executions (calibration ~4.6 s /
0). Interactive suite: 5 passed / 35 failed / 7 ignored before, 43
passed / 0 failed / 7 ignored after.

Also fixes the TypeaheadGuard double-injection (niubash#287): the
sweeper's self-heal path reinjected a borrowed view of the saved
records without draining them, so disarm_and_reinject wrote the same
records back a second time - one swept key per prompt cycle arriving
twice. The self-heal now drains under the lock; a console-input
regression test stages records through a duplicate stdin handle and
asserts each comes back exactly once (verified to fail on the
pre-fix path).

Tests: rapid_input_burst and multiline_raw_paste re-pin the #252/#284
contract (CRLF feed buffers as one chunk, bare-CR feed submits per
line); new send_line_first_enter_submits_and_typeahead_executes pins
the #284 regression shape; multiline_crlf_paste_buffers_whole_chunk_
and_executes_once pins the issue-scale 0-mid-execution surface;
esc_sequenced_arrow_keys_edit_without_absorption pins the #277/#280
arrow path.

Fixes #284, fixes #287
caomengxuan666 added a commit that referenced this pull request Oct 18, 2026
… fold boundaries

CR (APPROVE-WITH-NITS) followups before merge:

- tests/interactive.rs: the owner-script test's doc claimed it was the
  reproduction witness ('pre-fix ... the branch output never appeared').
  That was wrong - the test also passes on unpatched master (CR
  verified; re-verified here 7/7 on master vs a flaky host channel).
  The comment now states the honest scope: regression guard, not
  reproduction; the deterministic RED/GREEN reproduction lives in the
  protocol-simulator unit tests (wt_bare_cr_paste_survives_* in
  repl.rs), which go red on 6332f99 with the exact byte loss.

- tests/keyevent_record_probe.rs (new, ignored by default): the forensic
  tool that established the channel claims, previously scratch-only.
  Executable checks: a fed \r byte synthesizes bare-CR KEY_EVENT records
  only (no LF, no control state); a fed \r\n pair synthesizes the
  VK_CONTROL sandwich plus the Enter+CONTROL LF partner (#252's shape);
  win32-input-mode VT sequences are NOT decoded by this host's conhost
  from the input pipe. Per-case child exe names so the ignored cases
  can run concurrently (LNK1104).

- \r\r\r boundary: a triple-CR run (line break + two empty lines) now
  has its own protocol sweep - the pair fold must neither over- nor
  under-count at every slice cut.

- slice sweep generalization: two independent cut points (three-write
  feed) across every cut pair.

- PR-body accuracy fix tracked separately: the reproduction vehicle is
  the protocol simulator; the integration test is a guard; the runtime
  lib count is stated as 540+1 (the +1 being a pre-existing local
  rubash-path environment failure).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant