From 8e8324958f78e7c5546dfb417ebebf03bff05c64 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 19:09:02 -0600 Subject: [PATCH 1/2] aio(fix[reply]): Claim replies on stream use why: Preparing a successor early can leave terminal replies unclaimed. what: - Claim the reply writer when a successor starts, pumps or sends. - Flush pending terminal replies before outbound input. - Exercise writer handoff and reply write failure. Fixes #109 --- docs/topics/sync-and-asyncio.md | 5 +++ src/libvt/aio.py | 14 ++++++- tests/test_aio.py | 74 +++++++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 1 deletion(-) diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md index e933d7a2..b95a5aa4 100644 --- a/docs/topics/sync-and-asyncio.md +++ b/docs/topics/sync-and-asyncio.md @@ -116,6 +116,11 @@ background flusher on {class}`~libvt.aio.AsyncTerminalStream`, paired with {meth}`~libvt.aio.PtySession.drain`) to flush or apply backpressure; exceeding `max_write_buffer` raises {exc}`BufferError`. +You can prepare a replacement stream around the same terminal before +closing the current stream. Close the current stream before starting the +replacement. Pending terminal replies flow to the replacement before the +next input it sends. + ### Resizing {meth}`PtySession.resize() ` updates the kernel diff --git a/src/libvt/aio.py b/src/libvt/aio.py index f5890646..f6fbfb16 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -468,8 +468,16 @@ def __init__( self._read_waiters = 0 self._writer_task: asyncio.Task[None] | None = None self._close_task: asyncio.Task[None] | None = None - if self.terminal._on_reply_queued is None: + self._attach_reply_writer(flush_pending=False) + + def _attach_reply_writer(self, *, flush_pending: bool = True) -> None: + if self.writer is None: + return + owner = self.terminal._on_reply_queued + if owner is None: self.terminal._on_reply_queued = self._flush_terminal_replies + if flush_pending and (owner is None or owner == self._flush_terminal_replies): + self._flush_terminal_replies() def _flush_terminal_replies(self) -> None: r"""Flush out-of-band :meth:`~libvt.terminal.Terminal.enqueue_reply` bytes. @@ -615,6 +623,8 @@ def _enqueue_stream_write( if is_reply: return raise OSError(errno.EBADF, "stream writer is closed") + if not is_reply and self._write_error is None: + self._attach_reply_writer() if self._write_error is not None: if is_reply: return @@ -1127,6 +1137,7 @@ async def _read_chunk(self) -> bool: await self._frame_waits.drained.wait() if self._closed: return False + self._attach_reply_writer() pending = self._read_pending chunk, offset = ( (await self.reader.read(self.chunk_size), 0) if pending is None else pending @@ -1189,6 +1200,7 @@ def start(self) -> asyncio.Task[None]: if self._task is None or self._task.done(): self._close_task = None self._closed = False + self._attach_reply_writer() self._task = asyncio.create_task(self._pump_loop()) if self._write_queue or self._writer_draining: self._ensure_writer_task() diff --git a/tests/test_aio.py b/tests/test_aio.py index 9dcf6b06..a368a249 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -52,6 +52,80 @@ async def wait_closed(self) -> None: await asyncio.sleep(0) +@pytest.mark.parametrize("activate", ["start", "pump", "send"]) +async def test_prepared_successor_claims_reply_writer(activate: str) -> None: + """Deliver unsolicited replies to the successor ahead of user input.""" + terminal = libvt.Terminal() + old_writer, new_writer = _MemoryWriter(), _MemoryWriter() + predecessor = AsyncTerminalStream( + asyncio.StreamReader(), old_writer, terminal=terminal + ) + reader = asyncio.StreamReader() + successor = AsyncTerminalStream(reader, new_writer, terminal=terminal) + await predecessor.aclose() + + try: + terminal.feed(b"\x1b[?2031h") + if activate == "start": + successor.start() + elif activate == "pump": + reader.feed_data(b"READY") + assert await successor.pump_once() + terminal.set_theme(scheme=ColorScheme.LIGHT) + if activate != "send": + assert bytes(new_writer.buffer) == b"\x1b[?997;2n" + + await predecessor.aclose() + terminal.enqueue_reply(b"-") + successor.send(b"|") + await successor.drain() + assert bytes(new_writer.buffer) == b"\x1b[?997;2n-|" + assert old_writer.buffer == b"" + finally: + await successor.aclose() + + +async def test_read_only_stream_leaves_reply_writer_available() -> None: + """Attach a writer after constructing a read-only stream.""" + terminal = libvt.Terminal() + read_only = AsyncTerminalStream(asyncio.StreamReader(), terminal=terminal) + writer = _MemoryWriter() + async with AsyncTerminalStream( + asyncio.StreamReader(), writer, terminal=terminal + ) as stream: + terminal.enqueue_reply(b"reply") + assert writer.buffer == b"reply" + await read_only.aclose() + terminal.enqueue_reply(b"!") + await stream.drain() + assert writer.buffer == b"reply!" + + +async def test_successor_reports_reply_write_error_before_sending_input() -> None: + """Keep later input out of the writer if the earlier reply fails.""" + + class RejectFirstWrite(_MemoryWriter): + def write(self, data: bytes, /) -> None: + super().write(data) + if len(self.buffer) == len(data): + raise OSError(errno.EIO, "reply write failed") + + terminal = libvt.Terminal() + predecessor = AsyncTerminalStream( + asyncio.StreamReader(), _MemoryWriter(), terminal=terminal + ) + writer = RejectFirstWrite() + successor = AsyncTerminalStream(asyncio.StreamReader(), writer, terminal=terminal) + try: + await predecessor.aclose() + terminal.enqueue_reply(b"reply") + with pytest.raises(OSError, match="reply write failed"): + successor.send(b"input") + assert writer.buffer == b"reply" + finally: + await successor.aclose() + + async def test_async_terminal_stream_sync_coalescing_replies_and_timeout() -> None: """``AsyncTerminalStream`` coalesces ``?2026``, flushes DSR, and formats errors.""" reader = asyncio.StreamReader() From 81541523c755c12b28cb3b956eb3911d53bd000e Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 19:36:31 -0600 Subject: [PATCH 2/2] CHANGES(docs): Explain replies at stream handoff why: A terminal may have a pending reply when a successor stream takes over its writer. what: - Document when the successor sends replies ahead of new input. --- CHANGES | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGES b/CHANGES index f2e02fa8..b7b3dbfa 100644 --- a/CHANGES +++ b/CHANGES @@ -165,6 +165,13 @@ Closing an async stream now closes its writer even when the input pump fails. Concurrent close calls share cleanup, and a cancelled caller receives its cancellation after cleanup finishes. +#### Route unsolicited replies after a stream handoff (#168) + +After the previous stream closes, a prepared +{class}`~libvt.aio.AsyncTerminalStream` with a writer claims terminal +replies when it starts, pumps once, or sends data. It queues pending +replies before new input. + ### Documentation #### Assert effective colors alongside screen goldens (#190)