Skip to content

Move tmux to libvt.contrib.tmux and harden pre-0.1 core APIs #34

Done

Description

@tony

Summary

Before tagging 0.1.0, libvt (6c33073) carries six coupled surfaces that will turn into compatibility debt once libtmux and external callers pin them: src/libvt/tmux.py sitting as a monolithic root module with reverse constructors on core Terminal and Snapshot, eager root re-exports in src/libvt/__init__.py that pull emulation submodules into memory whenever libvt.pytest_plugin initializes, flat peer-specific fields on Profile, mutable palette and default-color slots on Terminal omitted from Snapshot across ?2026 synchronized-output holds, a closed type Event = ... union in src/libvt/events.py, and missing passive-observer and clipboard-read dispositions on Policy. Because tmux is an external integration and additional non-tmux integrations will follow, moving tmux into libvt.contrib.tmux (src/libvt/contrib/tmux/) with decoupled capture, control, and profile submodules while separating pure host-terminal presets into libvt.profiles establishes a clean boundary between VT emulation core and peer integrations before 0.1.0.

Motivation

  • Integration coupling and monolithic tmux module: Snapshot.from_tmux_capture() and Terminal.from_tmux_capture() import libvt.tmux from src/libvt/terminal.py and discard CaptureCompleteness (such as exact_cells=False when tabs were expanded without pane_tabs), while Profile.tmux(), TMUX_PROFILE, and TMUX_CAPTURE_POLICY couple src/libvt/config.py to multiplexer versioning and provide neither a dedicated libvt.contrib.<peer> namespace nor decoupled submodules as control decoding and non-tmux integrations arrive.
  • Eager root exports defeating pytest11 startup hygiene: .github/CONTRIBUTING.md documents that src/libvt/pytest_plugin.py defers imports inside fixture bodies so test collection avoids startup overhead, yet src/libvt/__init__.py eagerly imports core, graphics, status, and tmux submodules at package initialization, so import libvt.pytest_plugin loads almost the entire package during pytest startup in every environment where libvt is installed.
  • Uncommitted Appearance state across ?2026 holds: Snapshot omits palette and default-color state while Terminal mutates _fg_rgb, _bg_rgb, _cursor_rgb, and _palette_overrides directly on the live instance, so Formatter.format_snapshot() cannot see OSC 4 or OSC 10 through OSC 12 overrides and Terminal exposes neither a set_theme() host-theme API for ?2031 (CSI ? 997 ; Ps n) notifications nor DECSCNM (?5) reverse video.
  • Flat Profile fields and closed Event union churn: Profile mixes identity, query, screen, input, and Unicode flags as flat attributes (including peer-named tmux_window_rename and missing East Asian ambiguous_width), and type Event is a closed union with no nominal base class, so every new sequence event breaks downstream typing.assert_never callers.
  • Observer double-reply, fabricated empty OSC 52 reads, and dead allow_checksum_report: Terminal queues DSR and DA replies unconditionally when observing a tmux -CC %output stream whose pane queries tmux already answered; Policy.allow_clipboard_read=True emits b"\x1b]52;{sel};\x1b\\" (reporting an empty clipboard when no host provider exists); and Policy.allow_checksum_report has zero references in src/libvt/terminal.py while DECRQCRA (CSI * y) has zero callers in libtmux and zero implementations in tmux, Ghostty, Kitty, Zellij, or GNU Screen.

Evidence

Verified runtime checks at 6c33073 and upstream tmux pane behavior at 3daf263
  1. Importing libvt.pytest_plugin at 6c33073 executes src/libvt/__init__.py first and loads 18 libvt modules despite function-local imports in src/libvt/pytest_plugin.py:
$ PYTHONPATH=src python3 -c "import sys; import libvt.pytest_plugin, libvt; mods = sorted(m for m in sys.modules if m == 'libvt' or m.startswith('libvt.')); print(len(libvt.__all__), len(mods), mods)"
130 18 ['libvt', 'libvt.__about__', 'libvt._grid', 'libvt._ucd', 'libvt.codec', 'libvt.config', 'libvt.events', 'libvt.exc', 'libvt.graphics', 'libvt.input', 'libvt.modes', 'libvt.parser', 'libvt.pytest_plugin', 'libvt.screen', 'libvt.status', 'libvt.style', 'libvt.terminal', 'libvt.tmux']
  1. Inspecting Snapshot after OSC 11, Policy(allow_clipboard_read=True) on OSC 52 ; c ; ?, unconditional DSR replies, and allow_checksum_report references at 6c33073:
$ PYTHONPATH=src python3 -c "import pathlib, libvt; t = libvt.Terminal(rows=4, cols=10); t.feed(b'hi\x1b]11;rgb:11/22/33\x1b\\'); html = libvt.Formatter(libvt.OutputFormat.HTML).format_snapshot(t.committed); tc = libvt.Terminal(policy=libvt.Policy(allow_clipboard_read=True)); tc.feed(b'\x1b]52;c;?\x1b\\'); to = libvt.Terminal(); to.feed(b'\x1b[6n'); refs = pathlib.Path('src/libvt/terminal.py').read_text().count('allow_checksum_report'); print(hasattr(t.committed, 'appearance'), '#112233' in html.lower(), tc.drain_replies(), to.drain_replies(), refs)"
False False b'\x1b]52;c;\x1b\\' b'\x1b[1;1R' 0
  1. Upstream tmux pane query and RIS behavior in tmux/tmux input.c at 3daf263 and input.c#L1476-L1486 (confirmed against live tmux 3.8a PTY probes): input_dcs_dispatch dispatches only SIXEL (q with empty intermediates), DECRQSS ($ intermediate + q at input.c#L2860-L2865), and tmux; passthrough, ignoring XTGETTCAP (DCS + q), while INPUT_ESC_RIS (ESC c) calls screen_write_reset without exiting the alternate screen or clearing saved_grid:
	/* DCS sequences with intermediate byte '$' (includes DECRQSS). */
	if (ictx->interm_len == 1 && ictx->interm_buf[0] == '$') {
		/* DECRQSS is DCS $ q Pt ST. */
		if (len >= 1 && buf[0] == 'q')
			return (input_handle_decrqss(ictx));
	}
  1. Upstream tmux pause-after discard behavior in tmux/tmux control.c at 3daf263 sets CONTROL_PANE_PAUSED, calls control_discard_pane, and emits %pause:
	if (c->flags & CLIENT_CONTROL_PAUSEAFTER) {
		if (age < c->pause_age)
			return (0);
		cp->flags |= CONTROL_PANE_PAUSED;
		control_discard_pane(c, cp);
		control_notify_write(c, "%%pause %%%u", wp->id);
	}

Proposal

Invariants

The invariants below are load-bearing; everything under Intent is open.

  • One-way libvt.contrib.<peer> boundary and decoupled libvt.contrib.tmux submodules: libvt.contrib houses maintained peer integrations (libvt.contrib.tmux now, keeping libvt.contrib.<peer> open for future multiplexers and external peer protocols), while pure host-terminal presets (XTERM_PROFILE, LINUX_CONSOLE_PROFILE, KITTY_PROFILE, GHOSTTY_PROFILE) live as frozen data in src/libvt/profiles.py. Inside src/libvt/contrib/tmux/, capture.py, control.py, and profile.py stay decoupled so importing libvt.contrib.tmux.profile loads neither capture nor control, importing libvt.contrib.tmux.capture loads profile without control, and importing libvt.contrib.tmux.control loads neither capture nor profile, with src/libvt/contrib/tmux/__init__.py serving lazy PEP 562 re-exports. Core modules (parser.py, modes.py, style.py, config.py, _ucd.py, _grid.py, screen.py, terminal.py) never import libvt.contrib.*; Terminal.from_tmux_capture(), Snapshot.from_tmux_capture(), Profile.tmux(), TMUX_PROFILE, and TMUX_CAPTURE_POLICY come out of core before 0.1.0, and TmuxCaptureResult remains the capture entry point so CaptureCompleteness stays intact.
  • Curated lazy root namespace: libvt.__all__ shrinks to the quickstart entry points (Terminal, Snapshot, Screen, Cell, Style, Appearance, Profile, Policy, Limits, Event, render, strip, LibVtError, ProtocolError, __version__) served via a static PEP 562 __getattr__ and __dir__ map paired with if t.TYPE_CHECKING: imports and canonical submodule __module__ attributes, so import libvt.pytest_plugin loads neither libvt.terminal nor libvt._ucd during pytest collection.
  • Peer-neutral Profile capability groups: Profile composes frozen, slotted, hashable capability dataclasses (Identity, QueryBehavior, ScreenBehavior, InputBehavior, UnicodeBehavior including ambiguous_width: t.Literal[1, 2] = 1) with zero callables and zero peer-name branches in terminal.py, screen.py, or parser.py; libvt.contrib.tmux.profile.tmux_profile(*, version=..., sixel=..., clipboard=...) expresses tmux pane behavior (XTGETTCAP, CSI ? u, and DECSTR silent, DECRQSS enabled, RIS in ?1049h keeping alternate_on and saved_grid, and DA1 parameterized on SIXEL and set-clipboard).
  • Atomic ?2026 committed frame state: Snapshot exposes an immutable Appearance record inside a unified committed frame aggregate shared by Terminal.committed, Formatter.format_snapshot(), and ScreenDelta (appearance_revision on _SyncState), separating host defaults (Terminal.set_theme(), OSC 104 and OSC 110 through OSC 112 reset targets) from guest OSC 4 and OSC 10 through OSC 12 overrides and DECSCNM (?5), and emitting CSI ? 997 ; Ps n (?2031) on palette updates as well as dark/light scheme changes per Contour synchronized output and palette update notifications.
  • Open nominal Event base and OSC 133 / OSC 633 normalization: class Event becomes an open frozen base class (kw_only=True, match_args=False) returned by drain_events() -> tuple[Event, ...] with consolidated variants (TitleChanged target field, WorkingDirectoryChanged source field) plus an opt-in type KnownEvent = ... union; OSC 133 and VS Code OSC 633 A/B/C/D normalize into PromptZone (exit_code: int | None), splitting ; before unescaping \xAB and \\ on 633;E;<cmd>[;<nonce>], deduplicating same-cell 133+633 marks, and keeping 633;E and 633;P out of StopOn.PROMPT_MARK.
  • Passive observer policy, non-fabricated OSC 52, and DECRQCRA removal: Policy drops dead allow_checksum_report (DECRQCRA stays unimplemented so _Row._ext remains None on plain ASCII spaces), adds emit_replies: bool = True (False for passive tmux -CC observers), and replaces allow_clipboard_read: bool with a default-deny enum that emits ClipboardReadRequested instead of fabricating empty clipboard replies, paired with Terminal.enqueue_reply(data: bytes) and Parser.at_ground_state.
  • Pure Terminal.encode() and narrow AsyncSession driving protocol: Terminal.encode(event) stays stateless across TUI modes (?5, ?8, ?66, ?67, and XTSAVE/XTRESTORE), session-scoped duplicate mouse-cell suppression lives on MouseTracker in libvt.input, and libvt.aio exposes a narrow structural AsyncSession t.Protocol (terminal, send, send_event, send_key, paste, drain, wait_for, aclose) backed by an unconditional reader loop and atomic outbound frames (never splitting bracketed paste() payloads), while keeping write_eof() on AsyncTerminalStream and returncode, TIOCSWINSZ, Linux EIO EOF handling, and process-group reaping on PtySession.

Intent (non-binding)

  • How this work splits across one or several incremental pull requests before 0.1.0 stays open so each slice (libvt.contrib.tmux submodule layout and lazy __init__, Profile and Policy cleanup, committed Appearance and ?2031/?5, open Event and OSC 633, input modes and bidirectional AsyncTerminalStream / AsyncSession) can land in whatever order and granularity keeps reviews small and ruff, ty, and pytest green.
  • Document libvt.contrib explicitly in the API reference as CI-tested peer integrations shipped in libvt (modeled on Django's django.contrib layout) while enforcing zero libvt.contrib imports from core in tests/test_import_hygiene.py.
  • Defer AsyncTerminalStream.from_blocking() past 0.1.0 because blocking read() worker threads cannot be cancelled cleanly, and keep session recording schemas, mid-sequence parser checkpoints, RGBA8 pixel rasterization, and correlated async host futures outside libvt core.

Alternatives

  • Keeping src/libvt/tmux.py as a monolithic top-level module or placing peers under libvt.mux: rejected because tmux is an external integration rather than VT emulation core, future integrations will span tools beyond tmux (some of which are not multiplexers), and keeping capture, control, and profile in one file forces narrow callers to import unrelated machinery.
  • Adding Terminal.from_snapshot(snapshot) as a round-trip constructor: rejected because Snapshot represents a committed visual observation rather than a resumable machine state and omits hidden screen buffers, DECSC slots, G0–G3 charsets, tab stops, and parser state so ?2026 commits stay cheap.
  • Implementing xterm DECRQCRA (CSI * y) behind Policy.allow_checksum_report: rejected because distinguishing written ASCII ' ' (0x20) from erased blanks (0x00) forces per-cell extension state onto ordinary ASCII text in _grid.py, DECRQCRA permits 1x1 cell brute-forcing when enabled, and neither libtmux nor modern peers (tmux, Ghostty, Kitty, Zellij, GNU Screen) implement or call it.
  • Stateful mouse deduplication inside Terminal.encode() or chunked mid-paste priority replies: rejected because mutating last_mouse_cell inside Terminal.encode(ev) causes read-only assertions or debug logs to drop the next session.send_event(ev), and interleaving a CPR reply inside ESC[200~..ESC[201~ injects escape bytes into the guest's pasted text buffer.

References

Activity

  1. added
    enhancement
    on Nov 28, 2026
  2. tony commented on Nov 28, 2026

    @tony
    MemberAuthor

    Completed and shipped in v0.0.1a2 (#44, #45, #47, #48, #49, #50, #51).

  3. moved this from Todo to Done in libvton Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    • Status
      Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions