diff --git a/CHANGES b/CHANGES index 5d67e611..2d784d2b 100644 --- a/CHANGES +++ b/CHANGES @@ -79,6 +79,13 @@ Deleting an attribute on {class}`~libvt.snapshot.Snapshot` now raises ### Documentation +#### Observe a pane and its attached tmux client (#141) + +The {ref}`tmux screen guide ` compares pane captures, +composited layouts, control streams, and attached-client copy-mode views, +and demonstrates pane-local click translation and explicit focus checks after +resize. + #### Drive a Python child from the README (#131) The README quickstart uses {func}`~libvt.aio.open_pty` and diff --git a/README.md b/README.md index 5ae7ea41..cb4cfd0f 100644 --- a/README.md +++ b/README.md @@ -244,8 +244,10 @@ styles: Escape, and Ctrl-C outcomes). Read `tmux` captures as screen cells and decode control-mode output with -[`libvt.contrib.tmux`](https://libvt.git-pull.com/api/contrib/tmux/). Full -guides and API reference are at [libvt.git-pull.com](https://libvt.git-pull.com/). +[`libvt.contrib.tmux`][contrib_tmux]. See +[Which screen am I testing?][tmux_screens] for attached-client and copy-mode +checks. Full guides and API reference are at +[libvt.git-pull.com](https://libvt.git-pull.com/). ## License @@ -268,3 +270,5 @@ MIT License. See [LICENSE](LICENSE). [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/ +[tmux_screens]: https://libvt.git-pull.com/topics/tmux-screens/ diff --git a/docs/topics/index.md b/docs/topics/index.md index 596eeb7d..de4a5d18 100644 --- a/docs/topics/index.md +++ b/docs/topics/index.md @@ -3,8 +3,9 @@ # Topics Guides covering `libvt`'s parser and screen design, immutable snapshots, -terminal testing systems, synchronized redraws and `asyncio` adapters, terminal -protocols and input encoding, and migrating from `pyte`. +terminal testing systems, tmux screen and attached-client observation, +synchronized redraws and `asyncio` adapters, terminal protocols and input +encoding, and migrating from `pyte`. ::::{grid} 1 1 2 2 :gutter: 2 2 3 3 @@ -27,6 +28,13 @@ Immutable {class}`~libvt.snapshot.Snapshot` captures, {attr}`~libvt.terminal.Ter Three decoupled testing systems built on snapshots: {mod}`libvt.testing`, {mod}`libvt.pytest_plugin` (`libvt[pytest]`), and {mod}`libvt.contrib.syrupy` (`libvt[syrupy]`). ::: +:::{grid-item-card} Which screen am I testing? +:link: tmux-screens +:link-type: doc +Compare a tmux pane with an attached client in copy mode and route a mouse +click after a resize. +::: + :::{grid-item-card} Synchronized Output & `asyncio` :link: sync-and-asyncio :link-type: doc @@ -55,6 +63,7 @@ Differences in terminal construction, coordinates, alternate screens, and query architecture snapshots testing +tmux-screens sync-and-asyncio protocols-and-input migrating-from-pyte diff --git a/docs/topics/tmux-screens.md b/docs/topics/tmux-screens.md new file mode 100644 index 00000000..cd80d9a4 --- /dev/null +++ b/docs/topics/tmux-screens.md @@ -0,0 +1,135 @@ +(topics-tmux-screens)= + +# Which screen am I testing? + +Choose the screen whose behavior your test checks. Each tmux observation layer +shows a different buffer: + +| Layer | API | What it observes | +| --- | --- | --- | +| Single pane grid | {func}`~libvt.contrib.tmux.capture.build_tmux_capture_command` | Application primary grid and scrollback ({meth}`~libvt.snapshot.Snapshot.viewport` pages history statelessly; `-a` reads saved primary behind `?1049`). | +| Multi-pane layout | {func}`~libvt.contrib.tmux.window.composite_tmux_window` | Composited application grids across panes without tmux copy-mode overlays or status chrome. | +| Control stream | {mod}`libvt.contrib.tmux.control` | Incremental pane output and layout notifications streamed from `tmux -CC`. | +| Attached client | {func}`~libvt.aio.open_pty` | Full rendered terminal window including copy mode, selection highlights, borders, and the status line. | + +Use an attached client when checking what a person sees or clicks. On an +attached client, {meth}`~libvt.aio.PtySession.wait_for` and +{attr}`~libvt.terminal.Terminal.committed` inspect completed frames across +`?2026` synchronized updates, whereas {meth}`~libvt.terminal.Terminal.snapshot` +reads the immediate working buffer (see +{ref}`testing-working-and-committed-frames`). + +## Compare a pane with its copy-mode viewport + +The example opens an archive on the left and a mouse-aware picker on the right. +The archive prints 32 ledger entries and `ARCHIVE LIVE`. After tmux enters +copy mode and moves to the start of history, the two observations differ: + +| Observation | Text in the archive pane | +| --- | --- | +| Application grid from {func}`~libvt.contrib.tmux.capture.build_tmux_capture_command` | `ARCHIVE LIVE` | +| Rendering from a tmux client attached through {func}`~libvt.aio.open_pty` | `Ledger entry 00` | + +The example runs the capture bundle against the same server and crops the +attached {class}`~libvt.snapshot.Snapshot` by cell coordinates. The one-row +offset accounts for the status line above the window. The example selects at +the start of the ledger and checks for the configured selection colors in the +attached frame. + +```{literalinclude} ../../examples/tmux_screens.py +:language: python +:start-at: Compare the application grid +:end-before: Read the mode grid +:dedent: 16 +``` + +When `tmux list-commands capture-pane` advertises `-M`, use it to read the +frozen copy-mode grid even after the live application writes new output behind +it. Read `#{scroll_position}` while the pane is in copy mode and use an +inclusive range from `-scroll` through `pane_height - 1 - scroll`. Without `-M` +and that range, `capture-pane` can return rows from the live grid instead. An +attached client also observes presentation details such as selection colors and +the copy-mode position indicator. + +```{literalinclude} ../../examples/tmux_screens.py +:language: python +:start-at: Read the mode grid +:end-before: Leave copy mode +:dedent: 16 +``` + +On builds that omit `-M`, use the attached snapshot for visible copy-mode rows. + +## Translate a click after resize + +Cancel copy mode, call {meth}`~libvt.aio.PtySession.resize` on the attached +PTY, and wait for tmux to report the new client and window dimensions. Query +`#{pane_top}` and `#{pane_left}` again. For this single-client, unpanned window +with status at the top, add the one-row status line and the pane origin to the +target's local row and column. Here `PIN` holds the target's `(row, column)` +inside the picker. + +```{literalinclude} ../../examples/tmux_screens.py +:language: python +:start-at: outer_row = 1 + top + PIN[0] +:end-at: outer_col = left + PIN[1] +:dedent: 20 +``` + +Use zero-based rows and columns for {class}`~libvt.input.MouseEvent`. The +encoder converts them to one-based SGR mouse wire coordinates (`+1` on both +axes): + +```python +>>> from libvt import Terminal +>>> from libvt.input import MouseAction, MouseButton, MouseEvent +>>> term = Terminal(rows=14, cols=68) +>>> term.feed(b"\x1b[?1000;1006h") +>>> status_rows, pane_top, pane_left = 1, 0, 35 +>>> pin_row, pin_col = 2, 3 +>>> outer_row = status_rows + pane_top + pin_row +>>> outer_col = pane_left + pin_col +>>> term.encode(MouseEvent(MouseButton.LEFT, MouseAction.PRESS, outer_row, outer_col)) +b'\x1b[<0;39;4M' +``` + +Check the target cell against the attached snapshot before clicking. Borders +and status cells belong to tmux, and any change to window layout, status +position, or viewport offset changes the mapping. + +A delivered mouse click does not guarantee that keyboard focus moved to the +clicked pane. Default tmux `MouseDown1Pane` bindings run `select-pane` before +forwarding the click, so the picker gains focus automatically. Custom tmux +bindings (for example `bind -T root MouseDown1Pane send-keys -M`) or other +multiplexers can deliver mouse events to an unfocused pane while leaving +keyboard focus elsewhere. Check the active pane after clicking and issue an +explicit focus command (such as `select-pane`) before sending a dependent key +with {meth}`~libvt.aio.PtySession.send_key`. + +The example sends both button edges with +{meth}`~libvt.aio.PtySession.send_event`, waits for the picker to report the +pane-local coordinates, verifies focus (issuing `select-pane` under +`--no-focus-on-click`), and then sends the key: + +```{literalinclude} ../../examples/tmux_screens.py +:language: python +:start-at: MouseEvent accepts zero-based +:end-before: The child has received +:dedent: 16 +``` + +## Run the example + +From the repository root with `libvt` installed, run the +{download}`example <../../examples/tmux_screens.py>` on POSIX with tmux 3.1 or +newer that advertises `capture-pane -N`. The example starts a private server +and shuts it down on exit. + +```console +$ python examples/tmux_screens.py +``` + +Use `--tmux` to select another binary. Pass `--stale-origin` to see the picker +receive column 11 in place of column 3 after the split's origin moves, or pass +`--no-focus-on-click` to see a delivered click leave focus on the archive pane +until `select-pane` transfers it explicitly. diff --git a/examples/tmux_screens.py b/examples/tmux_screens.py new file mode 100644 index 00000000..6169fbc1 --- /dev/null +++ b/examples/tmux_screens.py @@ -0,0 +1,404 @@ +"""Compare tmux pane and attached-client screens, then click after a resize.""" + +from __future__ import annotations + +import argparse +import asyncio +import contextlib +import functools +import os +import pathlib +import shutil +import subprocess +import sys +import tempfile +import time + +from libvt.aio import open_pty +from libvt.contrib.tmux import ( + build_tmux_capture_command, + parse_tmux_version, + tmux_profile, +) +from libvt.input import MouseAction, MouseButton, MouseEvent +from libvt.profiles import XTERM_PROFILE +from libvt.style import AnsiColor + +START = (12, 84) +RESIZED = (14, 68) +PIN = (2, 3) + + +def _check(condition: bool, message: str) -> None: + if not condition: + raise AssertionError(message) + + +async def _run(*argv: str, env: dict[str, str], check: bool = True) -> str: + """Read both pipes while the attached client continues to receive output.""" + proc = await asyncio.create_subprocess_exec( + *argv, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env + ) + try: + async with asyncio.timeout(5): + output, error = await proc.communicate() + finally: + if proc.returncode is None: + with contextlib.suppress(ProcessLookupError): + proc.kill() + await proc.communicate() + if check and proc.returncode: + raise subprocess.CalledProcessError(proc.returncode, argv, output, error) + return output.decode().removesuffix("\n") + + +def _guest(role: str, trigger: str | None = None) -> None: + if sys.platform == "win32": + msg = "The tmux example requires a POSIX terminal" + raise NotImplementedError(msg) + + import tty + + if role == "archive": + for number in range(32): + sys.stdout.write(f"Ledger entry {number:02}\n") + sys.stdout.write("ARCHIVE LIVE\n") + sys.stdout.flush() + if trigger is not None: + marker = pathlib.Path(trigger) + while not marker.exists(): + time.sleep(0.01) + sys.stdout.write("\x1b[2J\x1b[3J\x1b[HARCHIVE UPDATED\n") + sys.stdout.flush() + sys.stdin.read() + return + + tty.setraw(0) + os.write(1, b"\x1b[?1000;1006hPicker READY\x1b[3;4H[Pin]") + for label, edge, line in (("press", b"M", 5), ("release", b"m", 6)): + packet = bytearray() + while (byte := os.read(0, 1)) not in (b"M", b"m"): + if not byte: + msg = "Incomplete mouse report" + raise EOFError(msg) + packet.extend(byte) + _check(packet.startswith(b"\x1b[<") and byte == edge, f"Mouse bytes {packet!r}") + button, col, row = map(int, packet[3:].split(b";")) + _check(button == 0, f"Expected the left mouse button, received {button}") + os.write( + 1, f"\x1b[{line};1HPicker {label} row={row - 1} col={col - 1};".encode() + ) + key = os.read(0, 1) + os.write(1, b"\x1b[7;1HPicker key " + key) + sys.stdin.read() + + +async def _demo( + binary: str, + version: str, + *, + stale_origin: bool, + no_focus_on_click: bool = False, +) -> None: + env = dict(os.environ, TERM="xterm-256color") + env.pop("TMUX", None) + env.pop("TMUX_PANE", None) + profile = tmux_profile(version) + + with tempfile.TemporaryDirectory(prefix="vt-tmux-") as folder: + env["TMPDIR"] = folder + socket = pathlib.Path(folder) / "s" + trigger = pathlib.Path(folder) / "advance" + server = [binary, "-u", "-S", str(socket), "-f", "/dev/null"] + + tm = functools.partial(_run, *server, env=env) + + commands = await tm("list-commands", "capture-pane") + flags = commands.partition("[")[2].partition("]")[0] + if "N" not in flags: + msg = "This example requires a tmux build with capture-pane -N" + raise RuntimeError(msg) + + async def geometry(pane: str) -> tuple[int, int, int, int]: + value = await tm( + "display-message", + "-p", + "-t", + pane, + "#{pane_top} #{pane_left} #{pane_height} #{pane_width}", + ) + top, left, height, width = map(int, value.split()) + return top, left, height, width + + async def capture(pane: str) -> tuple[str, ...]: + bundle = build_tmux_capture_command(pane, tmux_version=version) + return bundle.parse(await tm(*bundle.argv), profile=profile).snapshot.lines + + guest = [sys.executable, "-u", str(pathlib.Path(__file__).resolve()), "--guest"] + try: + archive = await tm( + "new-session", + "-d", + "-s", + "desk", + "-x", + str(START[1]), + "-y", + str(START[0]), + "-P", + "-F", + "#{pane_id}", + *guest, + "archive", + *(("--trigger", str(trigger)) if "M" in flags else ()), + ) + await tm("set", "-g", "status", "on") + await tm("set", "-g", "status-position", "top") + await tm("set", "-g", "mouse", "on") + await tm("set", "-g", "mode-style", "fg=yellow,bg=blue") + if no_focus_on_click: + await tm("bind", "-T", "root", "MouseDown1Pane", "send-keys", "-M") + picker = await tm( + "split-window", + "-dh", + "-t", + archive, + "-P", + "-F", + "#{pane_id}", + *guest, + "picker", + ) + await tm("select-pane", "-t", archive) + async with open_pty( + [*server, "attach-session", "-t", "=desk"], + rows=START[0], + cols=START[1], + profile=XTERM_PROFILE, + env=env, + ) as client: + await client.wait_for("ARCHIVE LIVE", timeout=6) + await client.wait_for("Picker READY", timeout=6) + + # Compare the application grid with the rendered client. + await tm("copy-mode", "-t", archive) + await tm("send-keys", "-X", "-t", archive, "history-top") + await tm("send-keys", "-X", "-t", archive, "begin-selection") + await tm("send-keys", "-X", "-t", archive, "cursor-right") + pane_y, pane_x, height, width = await geometry(archive) + # This example puts one status row above the window. + client_y = 1 + pane_y + rows = slice(client_y, client_y + height) + cols = slice(pane_x, pane_x + width) + ledger = tuple(f"Ledger entry {index:02}" for index in range(height)) + visible = await client.wait_for( + lambda snap: ( + snap[client_y, pane_x].style.bg == AnsiColor.BLUE + and snap[client_y, pane_x].style.fg == AnsiColor.YELLOW + and all( + row.startswith(label) + for row, label in zip( + snap[rows, cols].lines, ledger, strict=True + ) + ) + ), + timeout=6, + ) + _check(visible[client_y, pane_x].text == "L", "Missing selected L") + _check( + visible[client_y, pane_x + 2].style.bg != AnsiColor.BLUE, + "Selection extends past the marked cells", + ) + app = await capture(archive) + _check( + "ARCHIVE LIVE" in app and "Ledger entry 00" not in app, + "Pane capture did not show the live archive", + ) + sys.stdout.write( + "app pane: ARCHIVE LIVE\nattached copy mode: Ledger entry 00\n" + ) + + # Read the mode grid at the current scroll offset. + if "M" in flags: + # Advance the live pane while copy mode stays frozen on history. + trigger.write_text("go", encoding="ascii") + deadline = asyncio.get_running_loop().time() + 5 + while "ARCHIVE UPDATED" not in await capture(archive): + if asyncio.get_running_loop().time() >= deadline: + msg = "Live archive did not update behind copy mode" + raise AssertionError(msg) + await asyncio.sleep(0.02) + scroll = int( + await tm( + "display-message", "-p", "-t", archive, "#{scroll_position}" + ) + ) + mode_rows = await tm( + "capture-pane", + "-p", + "-M", + "-t", + archive, + "-S", + str(-scroll), + "-E", + str(height - 1 - scroll), + ) + live_rows = await tm( + "capture-pane", + "-p", + "-t", + archive, + "-S", + str(-scroll), + "-E", + str(height - 1 - scroll), + ) + attached_rows = visible[rows, cols].lines + # Compare ledger labels before any copy-mode decorations. + label_width = len(ledger[0]) + _check( + tuple(row[:label_width] for row in mode_rows.splitlines()) + == tuple(row[:label_width] for row in attached_rows), + "Copy-mode rows differ from the attached viewport", + ) + _check( + "Ledger entry 00" not in live_rows, + "Plain capture-pane matched frozen copy-mode history", + ) + sys.stdout.write("mode capture at scroll offset: Ledger entry 00\n") + + # Leave copy mode before sending application input. + await tm("send-keys", "-X", "-t", archive, "cancel") + live_label = "ARCHIVE UPDATED" if "M" in flags else "ARCHIVE LIVE" + await client.wait_for(live_label, timeout=6) + old_left = (await geometry(picker))[1] + client.resize(rows=RESIZED[0], cols=RESIZED[1]) + deadline = asyncio.get_running_loop().time() + 6 + while True: + native = await tm( + "list-clients", + "-F", + "#{client_height} #{client_width} " + "#{window_height} #{window_width}", + ) + top, left, pane_rows, pane_cols = await geometry(picker) + snap = client.terminal.committed + outer_row = 1 + top + PIN[0] + outer_col = left + PIN[1] + if ( + native + == f"{RESIZED[0]} {RESIZED[1]} {RESIZED[0] - 1} {RESIZED[1]}" + and left != old_left + and (snap.rows, snap.cols) == RESIZED + and 0 <= PIN[0] < pane_rows + and 0 <= PIN[1] < pane_cols + and snap[outer_row, outer_col].text == "[" + ): + break + if asyncio.get_running_loop().time() >= deadline: + msg = ( + f"Client and picker did not settle after resize: {native!r}" + ) + raise AssertionError(msg) + await asyncio.sleep(0.025) + + active = await tm("display-message", "-p", "-t", "desk:", "#{pane_id}") + _check( + active == archive, + f"Expected the archive to own focus, got {active}", + ) + if stale_origin: + outer_col = old_left + PIN[1] + + # MouseEvent accepts zero-based outer coordinates and encodes them. + for edge in (MouseAction.PRESS, MouseAction.RELEASE): + client.send_event( + MouseEvent(MouseButton.LEFT, edge, outer_row, outer_col) + ) + press_row = 1 + top + 4 + release_row = 1 + top + 5 + receipt = await client.wait_for( + lambda s: ( + ( + line := s[release_row, left : left + pane_cols].lines[0] + ).startswith("Picker release ") + and line.endswith(";") + ), + timeout=6, + ) + want = f"Picker release row={PIN[0]} col={PIN[1]}" + actual = receipt[release_row, left : left + pane_cols].lines[0] + actual = actual.removesuffix(";") + _check( + actual == want, + f"Picker reported {actual.removeprefix('Picker ')}, wanted {want}", + ) + press_line = receipt[press_row, left : left + pane_cols].lines[0] + _check( + press_line == f"Picker press row={PIN[0]} col={PIN[1]};", + f"Picker missed the button press: {press_line!r}", + ) + active = await tm("display-message", "-p", "-t", "desk:", "#{pane_id}") + if no_focus_on_click: + _check( + active == archive, + f"Expected focus to stay on archive, got {active}", + ) + await tm("select-pane", "-t", picker) + active = await tm( + "display-message", "-p", "-t", "desk:", "#{pane_id}" + ) + _check( + active == picker, f"Expected the picker to own focus, got {active}" + ) + if no_focus_on_click: + sys.stdout.write( + "focus after click: stayed on archive; " + "transferred via select-pane\n" + ) + client.send_key("v") + await client.wait_for("Picker key v", timeout=6) + # The child has received both button edges and the key. + sys.stdout.write(f"Picker received press, release and key at {PIN}\n") + finally: + await tm("kill-server", check=False) + + +def _main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--tmux", default="tmux", help="tmux executable") + parser.add_argument( + "--stale-origin", action="store_true", help="Reuse the old pane origin" + ) + parser.add_argument( + "--no-focus-on-click", + action="store_true", + help="Send mouse events without moving focus, then focus explicitly", + ) + parser.add_argument( + "--guest", choices=("archive", "picker"), help=argparse.SUPPRESS + ) + parser.add_argument("--trigger", help=argparse.SUPPRESS) + args = parser.parse_args() + if args.guest: + _guest(args.guest, args.trigger) + else: + binary = shutil.which(args.tmux) + if binary is None: + parser.error(f"Cannot find tmux executable {args.tmux!r}") + version = subprocess.check_output([binary, "-V"], text=True, timeout=5).strip() + if parse_tmux_version(version) < (3, 1): + parser.error("The example requires tmux 3.1 or newer with capture-pane -N") + asyncio.run( + _demo( + binary, + version, + stale_origin=args.stale_origin, + no_focus_on_click=args.no_focus_on_click, + ) + ) + + +if __name__ == "__main__": + _main() diff --git a/tests/test_tmux.py b/tests/test_tmux.py index dfbbacdf..d7721d0a 100644 --- a/tests/test_tmux.py +++ b/tests/test_tmux.py @@ -2,11 +2,14 @@ from __future__ import annotations +import asyncio +import importlib.util import os import pathlib import selectors import shutil import subprocess +import sys import tempfile import time @@ -24,6 +27,7 @@ build_tmux_capture_command, decode_tmux_capture, parse_flagged_line, + parse_tmux_version, tmux_profile, unescape_tmux_control_output, ) @@ -2078,3 +2082,122 @@ def begin_capture(locate: str) -> list[TmuxCommandBlock]: with pytest.raises(ProtocolError, match=r"3\.2"): TmuxPaneSync("%0", tmux_version="3.1c").watch_process() + + +@pytest.mark.integration +@pytest.mark.skipif(os.name != "posix", reason="attached tmux requires a POSIX PTY") +@pytest.mark.parametrize( + ("stale", "optimized", "no_focus"), + [ + (False, False, False), + (True, False, False), + (True, True, False), + (False, False, True), + ], +) +def test_attached_tmux_screen_example( + stale: bool, optimized: bool, no_focus: bool +) -> None: + """Exercise the guide against a real attached client and focus policies.""" + binary = shutil.which(os.environ.get("TMUX_BIN", "tmux")) + if binary is None: + pytest.skip("tmux binary not installed") + version = subprocess.check_output([binary, "-V"], text=True, timeout=5).strip() + if parse_tmux_version(version) < (3, 1): + pytest.skip("The example requires tmux 3.1 or newer") + probe_env = dict(os.environ) + probe_env.pop("TMUX", None) + probe_env.pop("TMUX_PANE", None) + probe_env.pop("TMUX_TMPDIR", None) + probe_socket = new_tmux_socket_name() + try: + commands = subprocess.check_output( + [ + binary, + "-L", + probe_socket, + "-f", + "/dev/null", + "list-commands", + "capture-pane", + ], + env=probe_env, + text=True, + timeout=5, + ) + finally: + subprocess.run( + [binary, "-L", probe_socket, "-f", "/dev/null", "kill-server"], + env=probe_env, + capture_output=True, + timeout=5, + check=False, + ) + flags = commands.partition("[")[2].partition("]")[0] + if "N" not in flags: + pytest.skip("tmux capture-pane -N is unavailable") + script = pathlib.Path(__file__).resolve().parents[1] / "examples/tmux_screens.py" + args = [sys.executable, str(script), "--tmux", binary] + if optimized: + args.insert(1, "-O") + if stale: + args.append("--stale-origin") + if no_focus: + args.append("--no-focus-on-click") + result = subprocess.run( + args, capture_output=True, text=True, timeout=30, check=False + ) + if stale: + assert result.returncode == 1, result.stdout + result.stderr + assert "Picker reported release row=2 col=11" in result.stderr + else: + assert result.returncode == 0, result.stdout + result.stderr + assert "app pane: ARCHIVE LIVE" in result.stdout + assert "attached copy mode: Ledger entry 00" in result.stdout + assert "Picker received press, release and key at (2, 3)" in result.stdout + assert ("mode capture at scroll offset: Ledger entry 00" in result.stdout) == ( + "M" in flags + ) + assert ( + "focus after click: stayed on archive; transferred via select-pane" + in result.stdout + ) == no_focus + + +async def test_tmux_example_reaps_cancelled_command(tmp_path: pathlib.Path) -> None: + """Drain full command pipes and reap the child when the caller cancels.""" + if sys.platform == "win32": + pytest.skip("the tmux guide runs on a POSIX terminal") + script_path = ( + pathlib.Path(__file__).resolve().parents[1] / "examples/tmux_screens.py" + ) + spec = importlib.util.spec_from_file_location("_tmux_screens_example", script_path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + run_cmd = module._run + + ready = tmp_path / "ready" + script = ( + "import os, pathlib, sys, time\n" + "sys.stdout.buffer.write(b'O' * 262144)\n" + "sys.stderr.buffer.write(b'E' * 262144)\n" + "ready = pathlib.Path(sys.argv[1])\n" + "pending = ready.with_suffix('.tmp')\n" + "pending.write_text(str(os.getpid()))\n" + "pending.rename(ready)\n" + "time.sleep(30)\n" + ) + task = asyncio.create_task( + run_cmd(sys.executable, "-c", script, str(ready), env=dict(os.environ)) + ) + try: + async with asyncio.timeout(4): + while not ready.exists(): + await asyncio.sleep(0.01) + finally: + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + with pytest.raises(ProcessLookupError): + os.kill(int(ready.read_text()), 0)