From 2e9ceee5b23fc5b7491c765076f2035960611b67 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 19:18:12 -0600 Subject: [PATCH] docs(readme): Refresh quickstart and cut boxes why: Replace repeated boxed serialize_vt_snapshot() snippets with executable plain Python and console examples that surface core inspection, synchronous process control, pytest/syrupy testing, CLI disassembly, and pure-Python tmux compositing while shrinking README.md. what: - Collapse optional extra install fences into prose and rewrite the opening quickstart around Terminal.feed(), term.committed, Snapshot.lines/cursor, Cell.style, and RowView.runs without libvt.testing - Replace the async-only PTY example with synchronous open_terminal() and send_line(), noting Windows build 26100 ConPTY and .snapshot caveats alongside pointers to libvt.aio (AsyncTerminalStream, open_pty()) and pytest vt_pty replay capture - Keep wide-char assert_screen_box(), consolidate testing into a real pytest test_status_diff() using vt_factory(..., recorder=vt_recorder), feed_str(), tmp_path scrubbing, and vt_screen(..., diff=...), plus --vt-replay-dir -> python -m libvt replay and a runnable syrupy vt_snapshot test - Contrast render() and strip() on overwrite input, state render() viewport/no-scrollback boundaries and defaults accurately, and run POSIX-safe printf | python -m libvt explain - Cover Snapshot.format()/to_dict(), drain_replies()/Profile/Policy/ Limits, prompt_zones/cwd/Notification, migrating-from-pyte, and add a pure-Python libvt.contrib.tmux capture and window-compositing example while fixing the vt_snapshot anchor link --- README.md | 376 ++++++++++++++++++++++++++---------------------------- 1 file changed, 183 insertions(+), 193 deletions(-) diff --git a/README.md b/README.md index 60931fe..1377328 100644 --- a/README.md +++ b/README.md @@ -13,266 +13,256 @@ annotations and no runtime dependencies. ## Installation -Install with `uv`: +Install with `uv` or `pip`: ```console $ uv add "libvt>=0.0.1a6,<0.1" ``` -Install with `pip`: - ```console $ pip install "libvt>=0.0.1a6,<0.1" ``` -Optional extras install the `pytest` fixture plugin (`libvt[pytest]`) or the -`syrupy` `.ambr` snapshot adapter (`libvt[syrupy]`): - -```console -$ uv add --dev "libvt[pytest]>=0.0.1a6,<0.1" -``` - -```console -$ uv add --dev "libvt[syrupy]>=0.0.1a6,<0.1" -``` - -`libvt` is in pre-alpha (`0.0.1a6`). Minor and `0.0.x` releases may include -breaking API changes; pin `libvt>=0.0.1a6,<0.1` while the package is pre-1.0. +Optional extras install the [`pytest` fixture plugin][pytest_plugin] +(`libvt[pytest]`) or the [`syrupy` `.ambr` snapshot adapter][contrib_syrupy] +(`libvt[syrupy]`), for example `uv add --dev "libvt[pytest]>=0.0.1a6,<0.1"`. +`libvt` is in pre-alpha (`0.0.1a6`); pin `libvt>=0.0.1a6,<0.1` while pre-1.0 +releases may include breaking API changes. ## Quickstart -### Feed bytes and inspect immutable snapshots +### Feed bytes and inspect snapshots -Each call to [`feed()`][feed] updates the screen. Read live text and cursor -coordinates directly, or capture an immutable [`Snapshot`][committed] that holds -the last completed frame during synchronized redraws (`?2026`) and pages -backward through scrollback with [`viewport()`][viewport]: +Each call to [`feed()`][feed] updates the screen. Read +[`term.committed`][committed] for an immutable [`Snapshot`][snapshot] — safe to +pass across threads, holding the last completed frame during synchronized +redraws (`?2026`) — to inspect lines, cursor position, runs, and cell styles: ```python ->>> import libvt ->>> from libvt.testing import serialize_vt_snapshot ->>> term = libvt.Terminal(rows=2, cols=20) ->>> term.feed(b"booting\r\nLoading 10%") ->>> term.feed(b"\r\x1b[2K\x1b[1;32mLoading 20%\x1b[0m\r\ndone") ->>> snap = term.committed ->>> print(serialize_vt_snapshot(snap)) -size=20x2 cursor=(1,4,vis=True) alt=False modes=[] -┌────────────────────┐ -│Loading 20% │ -│done │ -└────────────────────┘ -styles: - r0[0..11]: bold fg=green ->>> snap.viewport(offset=1).lines -('booting', 'Loading 20%') ->>> snap.find_cells("20%") -(CellSpan(row=0, start=8, stop=11),) +import libvt +from libvt.style import AnsiColor + +term = libvt.Terminal(rows=2, cols=20) +term.feed(b"booting\r\nLoading 10%") +term.feed(b"\r\x1b[2K\x1b[1;32mLoading 20%\x1b[0m\r\ndone") +snap = term.committed +assert snap.lines == ("Loading 20%", "done") +assert (snap.cursor.row, snap.cursor.col) == (1, 4) +assert snap[0, 0].style.bold and snap[0, 0].style.fg == AnsiColor.GREEN +assert snap[0].runs[0].text == "Loading 20%" ``` -Use [`Snapshot.find_cells()`][find_cells] to turn a visible label into cell -coordinates for a click, highlight, or assertion. - ### Drive a terminal program -On POSIX, use [`open_pty()`][open_pty] to launch a program, send input, and -wait for a committed [`Snapshot`][snapshot] showing the child's response. The -child prints `Taken: key` only after it reads the command: +Use [`libvt.contrib.subprocess`][contrib_subprocess] (`open_terminal()` for +interactive sessions and `run_terminal()` for one-shot commands) to launch a +program, submit lines atomically with `send_line()`, and wait for screen state +synchronously. It runs on POSIX PTYs and Windows ConPTY on Windows 11 24H2 or +Windows Server 2025 (build 26100, which provides `ReleasePseudoConsole`); older +Windows builds raise `NotImplementedError`: ```python ->>> import asyncio ->>> import os ->>> import sys ->>> from libvt import Snapshot ->>> from libvt.aio import open_pty - ->>> async def take_key() -> Snapshot: -... child = "print('Quay'); print('Taken: ' + input())" -... async with open_pty([sys.executable, "-u", "-c", child]) as session: -... await session.wait_for("Quay", timeout=5) -... session.paste("key") -... session.send_key("enter") -... return await session.wait_for( -... lambda snap: "Taken: key" in snap.lines, timeout=5 -... ) - ->>> if os.name == "posix": -... snap = asyncio.run(take_key()) -... assert "Taken: key" in snap.lines +import sys + +from libvt.contrib import subprocess as sp + +cmd = [sys.executable, "-u", "-c", "print('Quay'); print('Taken: ' + input())"] +try: + with sp.open_terminal(cmd, vt=sp.VT(rows=4, cols=40)) as child: + child.wait_for("Quay", timeout=8) + child.send_line("key") + snap = child.wait_for(lambda s: "Taken: key" in s.lines, timeout=8) + assert "Taken: key" in snap.lines + assert child.wait(timeout=8) == 0 +except NotImplementedError: + pass ``` -### Assert screen boxes inline +Pass `.snapshot` (or `.snapshot()` on a live handle) to `assert_screen()` and +`assert_screen_box()`; `vt_screen()` and `serialize_vt_snapshot()` accept +handles and captures directly. Use [`libvt.aio`][aio] (`AsyncTerminalStream` +for `asyncio` streams and [`open_pty()`][open_pty] for custom-`Profile` POSIX +PTYs), or the `vt_pty` fixture from [`libvt[pytest]`][pytest_plugin] for +`pytest --vt-replay-dir` PTY capture. + +### Assert screens inline Most unit tests can stop at [`assert_screen_box()`][assert_screen_box], which checks visible text, wide-character column alignment, and cursor coordinates inline without extra dependencies or snapshot files: ```python ->>> import libvt ->>> from libvt.testing import assert_screen_box ->>> t = libvt.Terminal(rows=2, cols=8) ->>> t.feed("日本ok\r\ndone".encode()) ->>> assert_screen_box( -... t, -... """ -... ┌────────┐ -... │日本ok │ -... │done │ -... └────────┘ -... """, -... cursor=(1, 4), -... ) +import libvt +from libvt.testing import assert_screen_box + +term = libvt.Terminal(rows=2, cols=8) +term.feed_str("日本ok\r\ndone") +assert_screen_box( + term, + """ + ┌────────┐ + │日本ok │ + │done │ + └────────┘ + """, + cursor=(1, 4), +) ``` -### Serialize and scrub multi-row TUIs (`libvt.testing`) +### Test with `pytest`, `syrupy`, diffs, and replay -When a TUI, progress panel, or `tmux` layout spans many styled rows or dynamic -IDs, [`vt_screen()`][vt_screen] and -[`serialize_vt_snapshot()`][serialize_vt_snapshot] in `libvt.testing` emit -escape-free boxes with run-length `styles:` spans and regex scrubbing with no -extra dependencies (`unittest`, `assert`, `inline-snapshot`, or -`pytest-regressions`). Scrubbers match within one visible row at a time; the -serializer pads or clips each row to the captured viewport width: +For multi-row TUIs, [`vt_screen()`][vt_screen] and +[`serialize_vt_snapshot()`][serialize_vt_snapshot] emit escape-free boxes with +`region=` cropping, `diff=` transition deltas, and regex or `os.PathLike` +(such as `tmp_path`) row scrubbers with zero extra dependencies. With +`libvt[pytest]`, `vt_terminal` and POSIX `vt_pty` attach a 4 KiB +`FlightRecorder` automatically, while `vt_factory` defaults to `recorder=None` +so you pass `recorder=vt_recorder` explicitly when you want `FlightRecorder` +traces on `assert_screen()` or `assert_screen_box()` failures: ```python ->>> import libvt ->>> from libvt.testing import serialize_vt_snapshot, vt_screen ->>> ui = libvt.Terminal(rows=3, cols=22) ->>> ui.feed( -... b"\x1b[?1049h\x1b[H" -... b"\xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" -... b"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" -... b"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" -... b"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" -... b"\xe2\x94\x80\xe2\x94\x90\r\n" -... b"\xe2\x94\x82 \x1b[1;32mREADY\x1b[0m pid=48210 \xe2\x94\x82\r\n" -... b"\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" -... b"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" -... b"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" -... b"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80" -... b"\xe2\x94\x80\xe2\x94\x98" -... ) ->>> print(serialize_vt_snapshot(vt_screen(ui, scrubbers=[(r"pid=\d+", "pid=")]))) -size=22x3 cursor=(2,21,vis=True) alt=True modes=[] -┌──────────────────────┐ -│┌────────────────────┐│ -││ READY pid= ││ -│└────────────────────┘│ -└──────────────────────┘ -styles: - r1[2..7]: bold fg=green +import pathlib + +from libvt.pytest_plugin import TerminalFactory +from libvt.recorder import FlightRecorder +from libvt.testing import serialize_vt_snapshot, vt_screen + + +def test_status_diff( + vt_factory: TerminalFactory, + vt_recorder: FlightRecorder, + tmp_path: pathlib.Path, +) -> None: + cols = max(32, len(str(tmp_path)) + 20) + term = vt_factory(rows=2, cols=cols, recorder=vt_recorder) + term.feed_str(f"[ ] build {tmp_path}\r\nwaiting") + before = term.committed + term.feed_str("\x1b[H[x] build\r\n\x1b[1;32mdone\x1b[0m ") + view = vt_screen(term, diff=before, scrubbers=[(tmp_path, "")]) + diff = serialize_vt_snapshot(view) + assert "row 0 cols 1..2: ' ' -> 'x'" in diff and "" in diff + assert "r1[0..4]: bold fg=green" in diff ``` -### Test with `pytest` fixtures (`libvt[pytest]`) +Run `pytest --vt-replay-dir=replays` to save failing byte streams and resizes, +then inspect them with `python -m libvt replay --chunk-size 1 ` (see +[Replay a failed terminal test][pytest_replay]). With `libvt[syrupy]`, +[`vt_snapshot`][vt_snapshot] persists boxed `.ambr` golden files through +[`VtSnapshotExtension`][contrib_syrupy]: -[`libvt.pytest_plugin`][pytest_plugin] (`libvt[pytest]`) provides `vt_terminal` -(wired to a 4 KiB `FlightRecorder`), `vt_factory`, `vt_recorder`, `vt_parser`, -and POSIX `vt_pty` fixtures with no snapshot-tool dependencies. +```python +from libvt.terminal import Terminal +from libvt.testing import vt_screen +from syrupy.assertion import SnapshotAssertion -Use `--vt-replay-dir` to [replay a failed terminal test][pytest_replay] -from the bytes and resizes saved by pytest. -```python ->>> import libvt ->>> from libvt.pytest_plugin import TerminalFactory ->>> from libvt.testing import assert_screen_box ->>> def test_prompt(vt_factory: TerminalFactory) -> None: -... term = vt_factory(rows=2, cols=10) -... term.feed(b"\x1b[1;32mOK\x1b[0m\r\nready> ") -... assert_screen_box( -... term, -... """ -... ┌──────────┐ -... │OK │ -... │ready> │ -... └──────────┘ -... """, -... cursor=(1, 7), -... ) ->>> test_prompt(libvt.Terminal) +def test_banner(vt_terminal: Terminal, vt_snapshot: SnapshotAssertion) -> None: + vt_terminal.feed_str("\x1b[1;32mREADY\x1b[0m pid=48210\r\nok") + view = vt_screen(vt_terminal, scrubbers=[(r"pid=\d+", "pid=")]) + assert view == vt_snapshot ``` -### Persist `.ambr` snapshots (`libvt[syrupy]`) +### Render, strip, and explain VT streams -[`libvt.contrib.syrupy`][contrib_syrupy] (`libvt[syrupy]`) adapts -`libvt.testing` into `VtSnapshotExtension` for `syrupy` `.ambr` golden files and -conditionally registers [`vt_snapshot`][vt_snapshot] when `syrupy` is active: +[`render()`][render] emulates cursor overwrites on a `rows=24`, `cols=80` +viewport with no scrollback (`newline_mode=False` and `unwrap=False` by +default; pass `newline_mode=True` for LF-only streams or `unwrap=True` to join +soft-wrapped lines). [`strip()`][strip] removes control sequences and `\r` +without replaying cursor movement. [`explain()`][explain] disassembles each +sequence in a stream: ```python ->>> import libvt ->>> from libvt.contrib.syrupy import VtSnapshotExtension ->>> term = libvt.Terminal(rows=1, cols=12) ->>> term.feed(b"\x1b[1;32mPASS\x1b[0m") ->>> print(VtSnapshotExtension().serialize(term)) -size=12x1 cursor=(0,4,vis=True) alt=False modes=[] -┌────────────┐ -│PASS │ -└────────────┘ -styles: - r0[0..4]: bold fg=green -``` +import libvt +from libvt.codec import explain -### Render, strip, and explain VT byte streams +raw = b"Loading 10%\r\x1b[2K\x1b[32mDone\x1b[0m" +assert libvt.render(raw, rows=1, cols=20) == "Done" +assert libvt.strip(raw) == "Loading 10%Done" +assert [s.mnemonic for s in explain(raw)] == ["TEXT", "CR", "EL", "SGR", "TEXT", "SGR"] +``` -[`render()`][render] returns screen text after processing terminal output. -[`strip()`][strip] removes control sequences without applying cursor movements. -[`explain()`][explain] identifies the sequences in a byte stream: +Invoke the CLI via `python -m libvt` (`render`, `strip`, `explain`, and +`replay`; no standalone script binary is installed): -```python ->>> import libvt ->>> from libvt.codec import explain ->>> libvt.render(b"\x1b[1;32mready\x1b[0m\r\nitem 1", rows=4, cols=20) -'ready\nitem 1' ->>> libvt.strip(b"\x1b[31merror:\x1b[0m failed") -'error: failed' ->>> [s.mnemonic for s in explain(b"\x1b[31merror:\x1b[0m")] -['SGR', 'TEXT', 'SGR'] +```console +$ printf '\033[32mDone\033[0m' | python -m libvt explain +CSI SGR 32m +PRINT TEXT 'Done' +CSI SGR 0m ``` ## Features -- Check screen contents and cursor positions inline or with `.ambr` `SGR` - snapshots, showing expected and actual screens on failure. -- Handle wide characters and emoji sequences using Unicode 17 width and - grapheme rules. -- Keep scrollback and reflow wrapped lines when the primary screen is resized. -- Inspect completed redraws from applications that use synchronized output - (`?2026`). -- Encode keyboard, mouse, focus, and paste events according to the active - terminal modes. -- Drive [terminal processes](https://libvt.git-pull.com/api/contrib/subprocess/) - synchronously on POSIX or Windows. -- Run terminal programs on POSIX PTYs or connect to `asyncio` streams (see the - [fzf cookbook][fzf_cookbook] for driving a live picker and verifying Enter, - Escape, and Ctrl-C outcomes). - -Read `tmux` captures as screen cells and decode control-mode output with -[`libvt.contrib.tmux`][contrib_tmux]. See -[Which screen am I testing?][tmux_screens] for attached-client and copy-mode -checks, or [play, test, and replay The Last Beacon][interactive_game] for a -complete PTY walkthrough. Full guides and API reference are at -[libvt.git-pull.com](https://libvt.git-pull.com/). +- Keep scrollback, reflow wrapped lines on resize, page history via + [`viewport()`][viewport], locate cells with [`find_cells()`][find_cells], + and read completed frames during synchronized output (`?2026`). +- Handle wide characters and emoji via Unicode 17 width and grapheme rules. +- Export plain text, `
` `HTML`, or replayable `VT` with
+  [`Snapshot.format()`][snapshot_format] (`OutputFormat.HTML` / `VT`), or a
+  deterministic JSON-compatible `dict` via [`to_dict()`][snapshot_to_dict].
+- Handle sans-I/O protocols: emit query replies via
+  [`drain_replies()`][drain_replies], pick host [`Profile`][profiles] presets,
+  bound streams with default-deny [`Policy`][config] and [`Limits`][config], and
+  encode keyboard, mouse, focus, and paste input for active terminal modes.
+- Track semantic shell integration (`prompt_zones`, `cwd`) and typed
+  [events][events] (`Notification`, title updates).
+- Drive processes via [`libvt.contrib.subprocess`][contrib_subprocess] (sync)
+  or [`libvt.aio`][aio] streams and POSIX PTYs (async; see the
+  [fzf cookbook][fzf_cookbook]).
+
+## `tmux` integration
+
+[`libvt.contrib.tmux`][contrib_tmux] decodes `capture-pane` output, composites
+multi-pane layouts (`composite_tmux_window()`), and syncs live `-C` / `-CC`
+control-mode panes (`TmuxPaneSync`, configurable with `tmux_version=`):
+
+```python
+from libvt.contrib import tmux
+from libvt.style import AnsiColor
+
+left = tmux.decode_tmux_capture(b"\x1b[1;32mBUILD PASS\x1b[0m\n", rows=2, cols=10)
+right = tmux.decode_tmux_capture(b"logs: ok\n", rows=2, cols=10)
+layout = tmux.parse_tmux_window_layout("21x2,0,0{10x2,0,0,1,10x2,11,0,2}")
+window = tmux.composite_tmux_window(layout, {"%1": left, "%2": right})
+assert window.lines == ("BUILD PASS│logs: ok", "          │")
+assert window[0, 0].style.bold and window[0, 0].style.fg == AnsiColor.GREEN
+```
+
+See [Which screen am I testing?][tmux_screens],
+[Migrating from `pyte`][migrating_pyte], or
+[play, test, and replay The Last Beacon][interactive_game]. Full guides and API
+reference are at [libvt.git-pull.com](https://libvt.git-pull.com/).
 
 ## License
 
 MIT License. See [LICENSE](LICENSE).
 
 [feed]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.Terminal.feed
-[find_cells]: https://libvt.git-pull.com/topics/snapshots/#locate-text-by-cell-coordinates
 [committed]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.Terminal.committed
+[snapshot]: https://libvt.git-pull.com/api/snapshot/#libvt.snapshot.Snapshot
 [viewport]: https://libvt.git-pull.com/api/snapshot/#libvt.snapshot.Snapshot.viewport
+[find_cells]: https://libvt.git-pull.com/topics/snapshots/#locate-text-by-cell-coordinates
+[snapshot_format]: https://libvt.git-pull.com/api/snapshot/#libvt.snapshot.Snapshot.format
+[snapshot_to_dict]: https://libvt.git-pull.com/api/snapshot/#libvt.snapshot.Snapshot.to_dict
+[drain_replies]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.Terminal.drain_replies
+[profiles]: https://libvt.git-pull.com/api/profiles/
+[config]: https://libvt.git-pull.com/api/config/
+[events]: https://libvt.git-pull.com/api/events/
+[aio]: https://libvt.git-pull.com/api/aio/
 [open_pty]: https://libvt.git-pull.com/api/aio/pty/#libvt.aio.open_pty
-[snapshot]: https://libvt.git-pull.com/api/snapshot/#libvt.snapshot.Snapshot
+[contrib_subprocess]: https://libvt.git-pull.com/api/contrib/subprocess/
 [assert_screen_box]: https://libvt.git-pull.com/api/testing/#libvt.testing.assert_screen_box
-[contrib_syrupy]: https://libvt.git-pull.com/api/contrib/syrupy/
-[pytest_plugin]: https://libvt.git-pull.com/api/pytest_plugin/
-[pytest_replay]: https://libvt.git-pull.com/topics/testing/#replay-a-failed-terminal-test
-[vt_snapshot]: https://libvt.git-pull.com/api/contrib/syrupy/#libvt.contrib.syrupy.vt_snapshot
 [vt_screen]: https://libvt.git-pull.com/api/testing/#libvt.testing.vt_screen
 [serialize_vt_snapshot]: https://libvt.git-pull.com/api/testing/#libvt.testing.serialize_vt_snapshot
+[pytest_plugin]: https://libvt.git-pull.com/api/pytest_plugin/
+[pytest_replay]: https://libvt.git-pull.com/topics/testing/#replay-a-failed-terminal-test
+[contrib_syrupy]: https://libvt.git-pull.com/api/contrib/syrupy/
+[vt_snapshot]: https://libvt.git-pull.com/api/contrib/syrupy/#fixture
 [render]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.render
 [strip]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.strip
 [explain]: https://libvt.git-pull.com/api/codec/#libvt.codec.explain
 [fzf_cookbook]: https://libvt.git-pull.com/topics/testing/#topics-testing-fzf
 [contrib_tmux]: https://libvt.git-pull.com/api/contrib/tmux/
+[migrating_pyte]: https://libvt.git-pull.com/topics/migrating-from-pyte/
 [tmux_screens]: https://libvt.git-pull.com/topics/tmux-screens/
 [interactive_game]: https://libvt.git-pull.com/topics/interactive-game/