From 98e44257a16df69c0db3435da999a16ce7b4a6e3 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:24:43 -0600 Subject: [PATCH] aio(feat[session]): Add mode-aware send_line() why: Line-oriented terminal prompts had to coordinate paste() and send_key("enter") separately, risking partial writes under buffer limits or hardcoded carriage returns that break ?2004 and Kitty keyboard modes. what: - Add _encode_line_payload() in libvt.input sharing paste control checks while rejecting embedded CR/LF unless sanitize=True and omitting empty ?2004 brackets. - Add send_line(text, /, *, sanitize=False) to AsyncSession, _SessionCore (AsyncTerminalStream, PtySession), and TerminalProcess, encoding text and Enter atomically onto the outbound write queue. - Add stream, POSIX PTY, and subprocess tests, update docs/topics/sync-and-asyncio.md and docs/api/contrib/subprocess.md, and record the entry in CHANGES. Fixes #121 --- CHANGES | 12 ++ docs/api/contrib/subprocess.md | 3 +- docs/topics/sync-and-asyncio.md | 15 +- src/libvt/aio/_core.py | 77 ++++++++++ src/libvt/aio/_pty.py | 6 +- src/libvt/aio/_stream.py | 7 +- src/libvt/contrib/subprocess.py | 21 +++ src/libvt/input.py | 92 ++++++++---- tests/test_aio.py | 248 +++++++++++++++++++++++++++++++- tests/test_input.py | 14 ++ tests/test_subprocess.py | 63 ++++++++ 11 files changed, 515 insertions(+), 43 deletions(-) diff --git a/CHANGES b/CHANGES index b5d5a9d2..5198f6ac 100644 --- a/CHANGES +++ b/CHANGES @@ -8,6 +8,18 @@ _Notes on the upcoming release will go here._ ### What's new +#### Submit mode-aware lines with `send_line()` (#121) + +{class}`~libvt.aio.AsyncSession`, {class}`~libvt.aio.AsyncTerminalStream`, +{class}`~libvt.aio.PtySession`, and +{class}`~libvt.contrib.subprocess.TerminalProcess` now provide +{meth}`~libvt.aio.PtySession.send_line` to submit a single line honoring +DEC `?2004` bracketed paste and active keyboard encoding modes as one atomic +outbound write. Embedded `\r` and `\n` raise +{exc}`~libvt.exc.UnsafePasteError` unless `sanitize=True`, empty text sends +only `Enter`, and a full outbound buffer raises {exc}`BufferError` without +queuing partial bytes. + #### Extended function keys and modifier-only keys (#129) {class}`~libvt.input.KeyEvent` and {func}`~libvt.input.encode_input` now accept diff --git a/docs/api/contrib/subprocess.md b/docs/api/contrib/subprocess.md index 358027d5..56b91b21 100644 --- a/docs/api/contrib/subprocess.md +++ b/docs/api/contrib/subprocess.md @@ -18,8 +18,7 @@ resizes the viewport. ... with sp.open_terminal(command, vt=sp.VT(rows=6, cols=40)) as child: ... _ = child.wait_for("Ready", timeout=8) ... child.resize(rows=8, cols=48) -... child.paste("pear") -... child.send_key("enter") +... child.send_line("pear") ... status = child.wait(timeout=8) ... final = child.wait_eof(timeout=8) ... assert (status, final.snapshot.lines[2]) == (0, "Result: raep") diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md index 8c480a64..9333ea74 100644 --- a/docs/topics/sync-and-asyncio.md +++ b/docs/topics/sync-and-asyncio.md @@ -56,7 +56,7 @@ into a terminal and drives outbound input over an optional writer. {class}`~libvt.aio.PtySession` (Linux, macOS, and BSD; raises {exc}`NotImplementedError` on Windows). Both satisfy the structural {class}`~libvt.aio.AsyncSession` protocol (`terminal`, `eof`, `send`, -`send_event`, `send_key`, `paste`, `drain`, `wait_for`, `aclose`). +`send_event`, `send_key`, `paste`, `send_line`, `drain`, `wait_for`, `aclose`). Pass the executable and its arguments as a sequence, for example `open_pty([sys.executable, "-i"])`. For an executable with no arguments, @@ -131,14 +131,23 @@ Both {class}`~libvt.aio.AsyncTerminalStream` and {class}`~libvt.aio.PtySession` queue outbound {meth}`~libvt.aio.PtySession.send`, {meth}`~libvt.aio.PtySession.send_event`, {meth}`~libvt.aio.PtySession.send_key`, {meth}`~libvt.aio.PtySession.paste`, -and automatic query replies onto a single bounded FIFO queue (`StreamWriter` -background flusher on {class}`~libvt.aio.AsyncTerminalStream`, paired with +{meth}`~libvt.aio.PtySession.send_line`, and automatic query replies onto a +single bounded FIFO queue (`StreamWriter` background flusher on +{class}`~libvt.aio.AsyncTerminalStream`, paired with {meth}`~libvt.aio.AsyncTerminalStream.write_eof` for half-close; `add_writer` on {class}`~libvt.aio.PtySession`). Call `await session.drain()` ({meth}`~libvt.aio.AsyncTerminalStream.drain` / {meth}`~libvt.aio.PtySession.drain`) to flush or apply backpressure; exceeding `max_write_buffer` raises {exc}`BufferError`. +Use {meth}`~libvt.aio.PtySession.send_line` for line-oriented prompts. It +wraps non-empty payloads in `?2004` brackets when active (sending only `Enter` +when empty or sanitized to empty), appends the active mode's `Enter` key, +rejects embedded `\r` / `\n` and unsafe controls with +{exc}`~libvt.exc.UnsafePasteError` unless `sanitize=True`, and enqueues the +entire line atomically so a full buffer raises {exc}`BufferError` without +queuing partial bytes. + Await a stream's `drain()` before closing to flush its queue. A PTY drain waits until buffered bytes drop to `write_high_water` or below. Use `write_high_water=0` to wait for its entire queue. If a concurrent diff --git a/src/libvt/aio/_core.py b/src/libvt/aio/_core.py index d411f9cd..46c37cc1 100644 --- a/src/libvt/aio/_core.py +++ b/src/libvt/aio/_core.py @@ -20,7 +20,9 @@ MouseEvent, MouseTracker, PasteEvent, + _encode_line_payload, ) +from libvt.modes import Mode from libvt.recorder import find_flight_recorder from libvt.snapshot import Snapshot from libvt.terminal import StopOn, Terminal @@ -114,6 +116,9 @@ def send_key(self, chord: str, /) -> None: def paste(self, text: str, /, *, sanitize: bool = False) -> None: """Encode *text* as an atomic :class:`~libvt.input.PasteEvent` frame.""" + def send_line(self, text: str, /, *, sanitize: bool = False) -> None: + """Encode *text* as one line followed by Enter and enqueue atomically.""" + async def drain(self) -> None: """Pause while outbound buffered bytes exceed ``write_high_water``.""" @@ -642,6 +647,78 @@ def paste(self, text: str, /, *, sanitize: bool = False) -> None: """ self.send_event(PasteEvent(text=text, sanitize=sanitize)) + def send_line(self, text: str, /, *, sanitize: bool = False) -> None: + r"""Encode *text* as a single line followed by Enter and enqueue atomically. + + Respects DEC bracketed paste mode ``?2004`` and active keyboard encoding + modes (such as Kitty ``REPORT_ALL_KEYS`` for Enter), enqueueing the line + text and Enter as one atomic outbound write so the payload and Enter + either fit together or fail together with :exc:`BufferError`. + + Embedded ``\r`` and ``\n`` are always rejected when *sanitize* is + ``False``, even when ``?2004`` is active. When *text* is empty (or + becomes empty after sanitization), only the encoded Enter key is sent. + + Parameters + ---------- + text : str + Single-line text to submit. + sanitize : bool + When ``False`` (default), raise :exc:`~libvt.exc.UnsafePasteError` + on embedded line breaks or disallowed control/escape characters; + when ``True``, strip them before encoding. + + Raises + ------ + UnsafePasteError + If *sanitize* is ``False`` and *text* contains ``\r``, ``\n``, or + other disallowed control/escape characters. + RuntimeError + If no outbound writer is attached. + OSError + If the outbound transport is closed or half-closed. + BufferError + If buffered outbound bytes plus the combined line and Enter would + exceed :attr:`max_write_buffer`; no partial bytes are queued. + + Examples + -------- + >>> import asyncio + >>> from libvt.aio import AsyncTerminalStream + >>> class _MemWriter: + ... def __init__(self) -> None: + ... self.buf = bytearray() + ... def write(self, data: bytes, /) -> None: + ... self.buf.extend(data) + ... async def drain(self) -> None: + ... pass + ... def close(self) -> None: + ... pass + ... async def wait_closed(self) -> None: + ... pass + >>> async def _demo() -> tuple[bytes, bytes]: + ... w = _MemWriter() + ... async with AsyncTerminalStream(asyncio.StreamReader(), w) as s: + ... s.send_line("pear") + ... await s.drain() + ... plain = bytes(w.buf) + ... w.buf.clear() + ... s.terminal.feed(b"\x1b[?2004h") + ... s.send_line("pear") + ... await s.drain() + ... bracketed = bytes(w.buf) + ... return plain, bracketed + >>> asyncio.run(_demo()) + (b'pear\r', b'\x1b[200~pear\x1b[201~\r') + """ + paste_bytes = _encode_line_payload( + text, + bracketed=self.terminal.modes.is_set(Mode.BRACKETED_PASTE), + sanitize=sanitize, + ) + enter_bytes = self.terminal.encode(KeyEvent("enter")) + self._enqueue_outbound(paste_bytes + enter_bytes) + def _cancel_sync_timer(self) -> None: if self._sync_timer_handle is not None: self._sync_timer_handle.cancel() diff --git a/src/libvt/aio/_pty.py b/src/libvt/aio/_pty.py index 22aa411e..873dbe83 100644 --- a/src/libvt/aio/_pty.py +++ b/src/libvt/aio/_pty.py @@ -213,9 +213,9 @@ class PtySession(_SessionCore): """Async POSIX PTY subprocess session over :class:`~libvt.terminal.Terminal`. Outbound bytes from :meth:`send`, :meth:`send_event`, :meth:`send_key`, - :meth:`paste`, and synchronous terminal query auto-replies share a single - bounded FIFO queue drained via ``loop.add_writer``, paired with - :meth:`drain` for high-water backpressure. + :meth:`paste`, :meth:`send_line`, and synchronous terminal query + auto-replies share a single bounded FIFO queue drained via + ``loop.add_writer``, paired with :meth:`drain` for high-water backpressure. Attributes ---------- diff --git a/src/libvt/aio/_stream.py b/src/libvt/aio/_stream.py index 734d12f9..327a9237 100644 --- a/src/libvt/aio/_stream.py +++ b/src/libvt/aio/_stream.py @@ -32,9 +32,10 @@ class AsyncTerminalStream(_SessionCore): Coalesces frame wakeups across DEC mode ``?2026`` synchronized-output batches (bounded by *sync_timeout* using generation-safe expiry), expires any active ``?2026`` hold on ``EOF`` and :meth:`aclose`, and queues outbound - :meth:`send`, :meth:`send_event`, :meth:`send_key`, :meth:`paste`, and - automatic query replies onto a non-blocking single-FIFO writer queue so - inbound reads never block on outbound backpressure. + :meth:`send`, :meth:`send_event`, :meth:`send_key`, :meth:`paste`, + :meth:`send_line`, and automatic query replies onto a non-blocking + single-FIFO writer queue so inbound reads never block on outbound + backpressure. """ _eof_wait_reason: t.ClassVar[str] = "stream reached EOF before predicate matched" diff --git a/src/libvt/contrib/subprocess.py b/src/libvt/contrib/subprocess.py index a6977031..6dac20dc 100644 --- a/src/libvt/contrib/subprocess.py +++ b/src/libvt/contrib/subprocess.py @@ -647,6 +647,27 @@ def paste(self, text: str, /, *, sanitize: bool = False) -> None: """ self._call(lambda: self._attachment.io.paste(text, sanitize=sanitize)) + def send_line(self, text: str, /, *, sanitize: bool = False) -> None: + r"""Queue single-line *text* and Enter atomically for active terminal modes. + + Respects DEC bracketed paste ``?2004`` and active keyboard modes while + rejecting embedded ``\r`` / ``\n`` and unsafe controls unless + *sanitize* is ``True``. Empty (or sanitized-empty) input sends only the + encoded Enter key. + + Raises + ------ + libvt.exc.UnsafePasteError + If *text* contains line breaks or unsafe controls and *sanitize* is + false. + BufferError + If the outbound write queue cannot fit the full line and Enter; + call :meth:`drain`. No partial bytes are queued. + ValueError + If the handle is closed. + """ + self._call(lambda: self._attachment.io.send_line(text, sanitize=sanitize)) + def drain(self, timeout: float | None = None) -> None: """Wait until queued outbound input bytes are written to the terminal. diff --git a/src/libvt/input.py b/src/libvt/input.py index 6f93761c..045fdcae 100644 --- a/src/libvt/input.py +++ b/src/libvt/input.py @@ -607,19 +607,21 @@ def filter_event( return event +def _is_disallowed_paste_cp(cp: int, *, allow_newlines: bool) -> bool: + if cp == 0x1B or cp == 0x7F or 0x80 <= cp <= 0x9F or cp == 0: + return True + if cp < 0x20: + if cp == 0x09: + return False + return not (allow_newlines and cp in (0x0A, 0x0D)) + return False + + def is_safe_paste(text: str, *, bracketed: bool = True) -> bool: """Return ``True`` when *text* contains no escape or injection control bytes.""" - for ch in text: - cp = ord(ch) - if cp == 0x1B or cp == 0x7F or 0x80 <= cp <= 0x9F or cp == 0: - return False - if cp < 0x20: - if ch == "\t": - continue - if bracketed and ch in ("\n", "\r"): - continue - return False - return True + return not any( + _is_disallowed_paste_cp(ord(ch), allow_newlines=bracketed) for ch in text + ) def encode_paste( @@ -637,38 +639,66 @@ def encode_paste( :exc:`~libvt.exc.UnsafePasteError`. Pass ``sanitize=True`` to remove disallowed characters instead. """ + allow_newlines = bracketed or allow_unbracketed_newlines if sanitize: - cleaned: list[str] = [] - for ch in text: - cp = ord(ch) - if cp == 0x1B or cp == 0x7F or 0x80 <= cp <= 0x9F or cp == 0: - continue - if cp < 0x20: - if ch == "\t" or ( - (bracketed or allow_unbracketed_newlines) and ch in ("\n", "\r") - ): - cleaned.append(ch) - continue - cleaned.append(ch) - payload = "".join(cleaned).encode("utf-8") + payload = "".join( + ch + for ch in text + if not _is_disallowed_paste_cp(ord(ch), allow_newlines=allow_newlines) + ).encode("utf-8") else: for ch in text: cp = ord(ch) + if not _is_disallowed_paste_cp(cp, allow_newlines=allow_newlines): + continue if cp == 0x1B or cp == 0x7F or 0x80 <= cp <= 0x9F or cp == 0: msg = f"paste contains unsafe control/escape codepoint U+{cp:04X}" raise UnsafePasteError(msg) - if cp < 0x20: - if ch == "\t": - continue - if (bracketed or allow_unbracketed_newlines) and ch in ("\n", "\r"): - continue + msg = ( + f"paste contains newline/control U+{cp:04X} while bracketed " + f"paste (?2004) is {'enabled' if bracketed else 'disabled'}" + ) + raise UnsafePasteError(msg) + payload = text.encode("utf-8") + + if bracketed: + return b"\x1b[200~" + payload + b"\x1b[201~" + return payload + + +def _encode_line_payload( + text: str, + *, + bracketed: bool, + sanitize: bool = False, +) -> bytes: + """Encode single-line text without embedded line breaks for ``send_line()``.""" + if sanitize: + payload = "".join( + ch + for ch in text + if not _is_disallowed_paste_cp(ord(ch), allow_newlines=False) + ).encode("utf-8") + else: + for ch in text: + cp = ord(ch) + if not _is_disallowed_paste_cp(cp, allow_newlines=False): + continue + if cp in (0x0A, 0x0D): msg = ( - f"paste contains newline/control U+{cp:04X} while bracketed " - f"paste (?2004) is {'enabled' if bracketed else 'disabled'}" + f"line contains embedded line break U+{cp:04X}; " + "strip line breaks or pass sanitize=True" ) raise UnsafePasteError(msg) + if cp == 0x1B or cp == 0x7F or 0x80 <= cp <= 0x9F or cp == 0: + msg = f"line contains unsafe control/escape codepoint U+{cp:04X}" + raise UnsafePasteError(msg) + msg = f"line contains disallowed control codepoint U+{cp:04X}" + raise UnsafePasteError(msg) payload = text.encode("utf-8") + if not payload: + return b"" if bracketed: return b"\x1b[200~" + payload + b"\x1b[201~" return payload diff --git a/tests/test_aio.py b/tests/test_aio.py index 8b0cc3d5..766194ff 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -28,7 +28,7 @@ ) from libvt.config import ColorScheme, ScreenBehavior from libvt.events import RenderHoldChanged -from libvt.exc import TerminalTimeoutError +from libvt.exc import TerminalTimeoutError, UnsafePasteError from libvt.input import MouseAction, MouseButton, MouseEvent from libvt.modes import Mode from libvt.parser import ParserState @@ -1879,3 +1879,249 @@ async def test_snapshot_find_cells_clicks_child_target() -> None: MouseEvent(MouseButton.LEFT, MouseAction.PRESS, hit.row, text_index) ) await session.wait_for("ACK Harbor row=2 col=7", timeout=5) + + +async def test_async_stream_send_line_modes_sanitization_and_atomicity() -> None: + """``send_line`` honors paste/key modes, rejects CR/LF, and enqueues atomically.""" + + class _ChunkWriter: + def __init__(self, *, hold_drain: bool = False) -> None: + self.chunks: list[bytes] = [] + self.hold_drain = hold_drain + self.release = asyncio.Event() + self.drain_entered = asyncio.Event() + + def write(self, data: bytes, /) -> None: + self.chunks.append(bytes(data)) + + async def drain(self) -> None: + self.drain_entered.set() + if self.hold_drain: + await self.release.wait() + + def close(self) -> None: + pass + + async def wait_closed(self) -> None: + pass + + writer = _ChunkWriter() + async with AsyncTerminalStream(asyncio.StreamReader(), writer) as stream: + assert isinstance(stream, AsyncSession) + + # Unbracketed (?2004l) + legacy Enter + stream.send_line("pear") + await stream.drain() + assert writer.chunks == [b"pear\r"] + writer.chunks.clear() + + # Tab allowed; empty line emits only Enter + stream.send_line("a\tb") + stream.send_line("") + await stream.drain() + assert writer.chunks == [b"a\tb\r", b"\r"] + writer.chunks.clear() + + # Bracketed paste (?2004h): single atomic frame + Enter; empty skips brackets + stream.terminal.feed(b"\x1b[?2004h") + stream.send_line("pear") + stream.send_line("") + stream.send_line("a\tb") + await stream.drain() + assert writer.chunks == [ + b"\x1b[200~pear\x1b[201~\r", + b"\r", + b"\x1b[200~a\tb\x1b[201~\r", + ] + writer.chunks.clear() + + # Kitty REPORT_ALL_KEYS (>8u and >31u) encodes Enter as CSI 13 u + for kitty_seq in (b"\x1b[>8u", b"\x1b[>31u"): + stream.terminal.feed(b"\x1b[?2004h" + kitty_seq) + stream.send_line("pear") + stream.send_line("") + stream.terminal.feed(b"\x1b[?2004l") + stream.send_line("pear") + await stream.drain() + assert writer.chunks == [ + b"\x1b[200~pear\x1b[201~\x1b[13u", + b"\x1b[13u", + b"pear\x1b[13u", + ] + writer.chunks.clear() + stream.terminal.feed(b"\x1b[ 16 + assert capped.write_buffer_size == 0 + assert capped_writer.chunks == [] + + capped.terminal.feed(b"\x1b[?2004l") + capped.send(b"123456789012") # 12 bytes buffered + assert capped.write_buffer_size == 12 + with pytest.raises(BufferError): + capped.send_line("pear") # 12 + 5 = 17 > 16 + assert capped.write_buffer_size == 12 + assert capped_writer.chunks == [b"123456789012"] + capped_writer.release.set() + await capped.drain() + + # Concurrent aclose() discards queued send_line atomically and reports ECANCELED + cancel_writer = _ChunkWriter(hold_drain=True) + cancel_stream = AsyncTerminalStream(asyncio.StreamReader(), cancel_writer) + cancel_stream.terminal.feed(b"\x1b[?2004h") + cancel_stream.send(b"HEAD") + await cancel_writer.drain_entered.wait() + cancel_stream.send_line("pear") + assert cancel_stream.write_buffer_size == 4 + len(b"\x1b[200~pear\x1b[201~\r") + drain_task = asyncio.create_task(cancel_stream.drain()) + await asyncio.sleep(0) + close_task = asyncio.create_task(cancel_stream.aclose()) + cancel_writer.release.set() + with pytest.raises(OSError, match="closed") as cancel_err: + await drain_task + assert cancel_err.value.errno == errno.ECANCELED + await close_task + assert cancel_writer.chunks == [b"HEAD"] + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required") +async def test_open_pty_send_line_repro_and_atomicity() -> None: + """``PtySession.send_line`` adapts to ``?2004`` transitions and enforces caps.""" + guest = ( + "import os\n" + "for n, mode in enumerate((b'l', b'h')):\n" + " hdr = b'\\x1b[?2004' + mode + b'PROMPT' + str(n).encode() + b'\\r\\n'\n" + " os.write(1, hdr)\n" + " seen = b''\n" + " while not seen.endswith(b'\\r'):\n" + " seen += os.read(0, 1)\n" + " os.write(1, b'RECEIVED=' + seen.hex().encode() + b'\\r\\n')\n" + ) + async with open_pty( + (sys.executable, "-c", guest), + rows=8, + cols=80, + tty_mode="raw", + max_write_buffer=32, + ) as session: + assert isinstance(session, AsyncSession) + for i in range(2): + await session.wait_for(f"PROMPT{i}", timeout=5.0) + if i == 1: + # 6 + 20 + 6 = 32 paste bytes fit alone, + 1 CR = 33 > 32 -> + # atomic rejection prevents a split write from corrupting guest. + with pytest.raises(BufferError): + session.send_line("x" * 20) + assert session.write_buffer_size == 0 + session.send_line("pear") + await session.drain() + snap = await session.wait_for( + lambda s: s.text.count("RECEIVED=") == 2, + timeout=5.0, + ) + received = [ + bytes.fromhex(line.removeprefix("RECEIVED=")) + for line in snap.lines + if line.startswith("RECEIVED=") + ] + assert received == [b"pear\r", b"\x1b[200~pear\x1b[201~\r"] + assert await session.process.wait() == 0 + + # Concurrent aclose() cancels a queued PtySession.send_line() with ECANCELED + stalled_guest = ( + "import os, time\nos.write(1, b'\\x1b[?2004hSTALLED\\r\\n')\ntime.sleep(10)\n" + ) + async with open_pty( + (sys.executable, "-c", stalled_guest), + rows=4, + cols=40, + tty_mode="raw", + write_high_water=0, + max_write_buffer=262_144, + ) as stalled_sess: + await stalled_sess.wait_for("STALLED", timeout=5.0) + # Fill PTY kernel buffer so the next send_line queues in user space. + stalled_sess.send(b"z" * 131_072) + assert stalled_sess.write_buffer_size > 0 + queued_before = stalled_sess.write_buffer_size + stalled_sess.send_line("pear") + assert stalled_sess.write_buffer_size == queued_before + len( + b"\x1b[200~pear\x1b[201~\r" + ) + drain_task = asyncio.create_task(stalled_sess.drain()) + await asyncio.sleep(0) + close_task = asyncio.create_task(stalled_sess.aclose()) + with pytest.raises(OSError, match="closed") as pty_cancel_err: + await drain_task + assert pty_cancel_err.value.errno == errno.ECANCELED + await close_task diff --git a/tests/test_input.py b/tests/test_input.py index 91429222..434a89c2 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -794,3 +794,17 @@ def test_extended_function_keys_and_modifier_only_keys() -> None: for invalid in ("f0", "f36", "shift", "ctrl", "left_shift", "shift_center"): with pytest.raises(ValueError, match="unsupported key identifier"): term.encode(KeyEvent(invalid)) + + +def test_is_safe_paste_controls_and_newlines() -> None: + """``is_safe_paste`` enforces C0/C1/ESC/DEL/NUL and bracketed newline rules.""" + from libvt.input import is_safe_paste + + assert is_safe_paste("hello\tworld 界", bracketed=False) is True + assert is_safe_paste("hello\tworld 界", bracketed=True) is True + assert is_safe_paste("line1\nline2\r", bracketed=True) is True + assert is_safe_paste("line1\nline2", bracketed=False) is False + assert is_safe_paste("line1\rline2", bracketed=False) is False + for unsafe in ("\x00", "\x03", "\x1b", "\x7f", "\x80", "\x9b", "\x9f"): + assert is_safe_paste(f"a{unsafe}b", bracketed=True) is False + assert is_safe_paste(f"a{unsafe}b", bracketed=False) is False diff --git a/tests/test_subprocess.py b/tests/test_subprocess.py index 7369e49d..1b063a72 100644 --- a/tests/test_subprocess.py +++ b/tests/test_subprocess.py @@ -843,3 +843,66 @@ async def _raise_buffer(message: str = async_msg) -> None: p.drain(timeout=5) p.wait_for("DRAINED=32768", timeout=8) assert p.wait(timeout=8) == 0 + + +@pytest.mark.usefixtures("_terminal_platform") +def test_terminal_process_send_line() -> None: + """``TerminalProcess.send_line`` submits mode-aware lines and enforces safety.""" + from libvt.exc import UnsafePasteError + + script = ( + "print('PROMPT_1')\n" + "a = input()\n" + "print(f'GOT1={a}')\n" + "print('PROMPT_2')\n" + "b = input()\n" + "print(f'GOT2={b}')\n" + ) + with sp.open_terminal(_command(script), vt=sp.VT(rows=8, cols=40)) as child: + child.wait_for("PROMPT_1", timeout=8) + with pytest.raises(UnsafePasteError): + child.send_line("bad\nline") + child.send_line("pear") + child.wait_for("GOT1=pear", timeout=8) + child.wait_for("PROMPT_2", timeout=8) + child.send_line("a\nb\x1bc", sanitize=True) + child.wait_for("GOT2=abc", timeout=8) + assert child.wait(timeout=8) == 0 + with pytest.raises(ValueError, match="closed"): + child.send_line("after-close") + + if os.name == "posix": + bracket_guest = ( + "import os, termios, tty\n" + "old = termios.tcgetattr(0)\n" + "tty.setraw(0)\n" + "try:\n" + " os.write(1, b'\\x1b[?2004hBP_READY\\r\\n')\n" + " for n in range(2):\n" + " seen = b''\n" + " while not seen.endswith(b'\\r'):\n" + " seen += os.read(0, 1)\n" + " out = f'HEX{n}='.encode() + seen.hex().encode() + b'\\r\\n'\n" + " os.write(1, out)\n" + "finally:\n" + " termios.tcsetattr(0, termios.TCSADRAIN, old)\n" + ) + with sp.open_terminal( + _command(bracket_guest), vt=sp.VT(rows=6, cols=60) + ) as bp_child: + bp_child.wait_for("BP_READY", timeout=8) + # Even with ?2004h active, send_line rejects CR/LF (unlike paste()). + with pytest.raises(UnsafePasteError, match="embedded line break"): + bp_child.send_line("bad\nline") + bp_child.send_line("pear") + bp_child.wait_for("HEX0=", timeout=8) + # Empty or sanitized-empty line omits empty ?2004 brackets. + bp_child.send_line("\n\r", sanitize=True) + snap = bp_child.wait_for("HEX1=", timeout=8) + hex0 = next(line for line in snap.lines if line.startswith("HEX0=")) + hex1 = next(line for line in snap.lines if line.startswith("HEX1=")) + assert ( + bytes.fromhex(hex0.removeprefix("HEX0=")) == b"\x1b[200~pear\x1b[201~\r" + ) + assert bytes.fromhex(hex1.removeprefix("HEX1=")) == b"\r" + assert bp_child.wait(timeout=8) == 0