Repository navigation
Description
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
tmuxmodule:Snapshot.from_tmux_capture()andTerminal.from_tmux_capture()importlibvt.tmuxfromsrc/libvt/terminal.pyand discardCaptureCompleteness(such asexact_cells=Falsewhen tabs were expanded withoutpane_tabs), whileProfile.tmux(),TMUX_PROFILE, andTMUX_CAPTURE_POLICYcouplesrc/libvt/config.pyto multiplexer versioning and provide neither a dedicatedlibvt.contrib.<peer>namespace nor decoupled submodules ascontroldecoding and non-tmuxintegrations arrive. - Eager root exports defeating
pytest11startup hygiene:.github/CONTRIBUTING.mddocuments thatsrc/libvt/pytest_plugin.pydefers imports inside fixture bodies so test collection avoids startup overhead, yetsrc/libvt/__init__.pyeagerly imports core, graphics, status, andtmuxsubmodules at package initialization, soimport libvt.pytest_pluginloads almost the entire package duringpyteststartup in every environment wherelibvtis installed. - Uncommitted
Appearancestate across?2026holds:Snapshotomits palette and default-color state whileTerminalmutates_fg_rgb,_bg_rgb,_cursor_rgb, and_palette_overridesdirectly on the live instance, soFormatter.format_snapshot()cannot seeOSC 4orOSC 10throughOSC 12overrides andTerminalexposes neither aset_theme()host-theme API for?2031(CSI ? 997 ; Ps n) notifications norDECSCNM(?5) reverse video. - Flat
Profilefields and closedEventunion churn:Profilemixes identity, query, screen, input, and Unicode flags as flat attributes (including peer-namedtmux_window_renameand missing East Asianambiguous_width), andtype Eventis a closed union with no nominal base class, so every new sequence event breaks downstreamtyping.assert_nevercallers. - Observer double-reply, fabricated empty
OSC 52reads, and deadallow_checksum_report:TerminalqueuesDSRandDAreplies unconditionally when observing atmux -CC%outputstream whose pane queriestmuxalready answered;Policy.allow_clipboard_read=Trueemitsb"\x1b]52;{sel};\x1b\\"(reporting an empty clipboard when no host provider exists); andPolicy.allow_checksum_reporthas zero references insrc/libvt/terminal.pywhileDECRQCRA(CSI * y) has zero callers inlibtmuxand zero implementations intmux, Ghostty, Kitty, Zellij, or GNU Screen.
Evidence
Verified runtime checks at 6c33073 and upstream tmux pane behavior at 3daf263
- Importing
libvt.pytest_pluginat 6c33073 executessrc/libvt/__init__.pyfirst and loads 18libvtmodules despite function-local imports insrc/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']
- Inspecting
SnapshotafterOSC 11,Policy(allow_clipboard_read=True)onOSC 52 ; c ; ?, unconditionalDSRreplies, andallow_checksum_reportreferences 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
- Upstream
tmuxpane query andRISbehavior intmux/tmuxinput.cat3daf263andinput.c#L1476-L1486(confirmed against livetmux 3.8aPTY probes):input_dcs_dispatchdispatches onlySIXEL(qwith empty intermediates),DECRQSS($intermediate +qatinput.c#L2860-L2865), andtmux;passthrough, ignoringXTGETTCAP(DCS + q), whileINPUT_ESC_RIS(ESC c) callsscreen_write_resetwithout exiting the alternate screen or clearingsaved_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));
}- Upstream
tmuxpause-afterdiscard behavior intmux/tmuxcontrol.cat3daf263setsCONTROL_PANE_PAUSED, callscontrol_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 decoupledlibvt.contrib.tmuxsubmodules:libvt.contribhouses maintained peer integrations (libvt.contrib.tmuxnow, keepinglibvt.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 insrc/libvt/profiles.py. Insidesrc/libvt/contrib/tmux/,capture.py,control.py, andprofile.pystay decoupled so importinglibvt.contrib.tmux.profileloads neithercapturenorcontrol, importinglibvt.contrib.tmux.captureloadsprofilewithoutcontrol, and importinglibvt.contrib.tmux.controlloads neithercapturenorprofile, withsrc/libvt/contrib/tmux/__init__.pyserving lazy PEP 562 re-exports. Core modules (parser.py,modes.py,style.py,config.py,_ucd.py,_grid.py,screen.py,terminal.py) never importlibvt.contrib.*;Terminal.from_tmux_capture(),Snapshot.from_tmux_capture(),Profile.tmux(),TMUX_PROFILE, andTMUX_CAPTURE_POLICYcome out of core before0.1.0, andTmuxCaptureResultremains the capture entry point soCaptureCompletenessstays 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 withif t.TYPE_CHECKING:imports and canonical submodule__module__attributes, soimport libvt.pytest_pluginloads neitherlibvt.terminalnorlibvt._ucdduringpytestcollection. - Peer-neutral
Profilecapability groups:Profilecomposes frozen, slotted, hashable capability dataclasses (Identity,QueryBehavior,ScreenBehavior,InputBehavior,UnicodeBehaviorincludingambiguous_width: t.Literal[1, 2] = 1) with zero callables and zero peer-name branches interminal.py,screen.py, orparser.py;libvt.contrib.tmux.profile.tmux_profile(*, version=..., sixel=..., clipboard=...)expressestmuxpane behavior (XTGETTCAP,CSI ? u, andDECSTRsilent,DECRQSSenabled,RISin?1049hkeepingalternate_onandsaved_grid, andDA1parameterized onSIXELandset-clipboard). - Atomic
?2026committed frame state:Snapshotexposes an immutableAppearancerecord inside a unified committed frame aggregate shared byTerminal.committed,Formatter.format_snapshot(), andScreenDelta(appearance_revisionon_SyncState), separating host defaults (Terminal.set_theme(),OSC 104andOSC 110throughOSC 112reset targets) from guestOSC 4andOSC 10throughOSC 12overrides andDECSCNM(?5), and emittingCSI ? 997 ; Ps n(?2031) on palette updates as well as dark/light scheme changes per Contour synchronized output and palette update notifications. - Open nominal
Eventbase andOSC 133/OSC 633normalization:class Eventbecomes an open frozen base class (kw_only=True,match_args=False) returned bydrain_events() -> tuple[Event, ...]with consolidated variants (TitleChangedtarget field,WorkingDirectoryChangedsource field) plus an opt-intype KnownEvent = ...union;OSC 133and VS CodeOSC 633A/B/C/Dnormalize intoPromptZone(exit_code: int | None), splitting;before unescaping\xABand\\on633;E;<cmd>[;<nonce>], deduplicating same-cell133+633marks, and keeping633;Eand633;Pout ofStopOn.PROMPT_MARK. - Passive observer policy, non-fabricated
OSC 52, andDECRQCRAremoval:Policydrops deadallow_checksum_report(DECRQCRAstays unimplemented so_Row._extremainsNoneon plain ASCII spaces), addsemit_replies: bool = True(Falsefor passivetmux -CCobservers), and replacesallow_clipboard_read: boolwith a default-deny enum that emitsClipboardReadRequestedinstead of fabricating empty clipboard replies, paired withTerminal.enqueue_reply(data: bytes)andParser.at_ground_state. - Pure
Terminal.encode()and narrowAsyncSessiondriving protocol:Terminal.encode(event)stays stateless across TUI modes (?5,?8,?66,?67, andXTSAVE/XTRESTORE), session-scoped duplicate mouse-cell suppression lives onMouseTrackerinlibvt.input, andlibvt.aioexposes a narrow structuralAsyncSessiont.Protocol(terminal,send,send_event,send_key,paste,drain,wait_for,aclose) backed by an unconditional reader loop and atomic outbound frames (never splitting bracketedpaste()payloads), while keepingwrite_eof()onAsyncTerminalStreamandreturncode,TIOCSWINSZ, LinuxEIOEOFhandling, and process-group reaping onPtySession.
Intent (non-binding)
- How this work splits across one or several incremental pull requests before
0.1.0stays open so each slice (libvt.contrib.tmuxsubmodule layout and lazy__init__,ProfileandPolicycleanup, committedAppearanceand?2031/?5, openEventandOSC 633, input modes and bidirectionalAsyncTerminalStream/AsyncSession) can land in whatever order and granularity keeps reviews small andruff,ty, andpytestgreen. - Document
libvt.contribexplicitly in the API reference as CI-tested peer integrations shipped inlibvt(modeled on Django'sdjango.contriblayout) while enforcing zerolibvt.contribimports from core intests/test_import_hygiene.py. - Defer
AsyncTerminalStream.from_blocking()past0.1.0because blockingread()worker threads cannot be cancelled cleanly, and keep session recording schemas, mid-sequence parser checkpoints, RGBA8 pixel rasterization, and correlated async host futures outsidelibvtcore.
Alternatives
- Keeping
src/libvt/tmux.pyas a monolithic top-level module or placing peers underlibvt.mux: rejected becausetmuxis an external integration rather than VT emulation core, future integrations will span tools beyondtmux(some of which are not multiplexers), and keepingcapture,control, andprofilein one file forces narrow callers to import unrelated machinery. - Adding
Terminal.from_snapshot(snapshot)as a round-trip constructor: rejected becauseSnapshotrepresents a committed visual observation rather than a resumable machine state and omits hidden screen buffers,DECSCslots,G0–G3charsets, tab stops, and parser state so?2026commits stay cheap. - Implementing xterm
DECRQCRA(CSI * y) behindPolicy.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,DECRQCRApermits 1x1 cell brute-forcing when enabled, and neitherlibtmuxnor 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 mutatinglast_mouse_cellinsideTerminal.encode(ev)causes read-only assertions or debug logs to drop the nextsession.send_event(ev), and interleaving aCPRreply insideESC[200~..ESC[201~injects escape bytes into the guest's pasted text buffer.
References
- Related open issues: Add byte-oriented
TmuxControlParserand two-phase-CCPaneAttach#27, SupportXTSAVE(CSI ? Pm s) andXTRESTORE(CSI ? Pm r) private mode save/restore #29 libvtat 6c33073:src/libvt/__init__.py,src/libvt/config.py,src/libvt/terminal.py,src/libvt/events.py,.github/CONTRIBUTING.md- Upstream specifications:
tmux/tmuxinput.c(3daf263),tmux/tmuxcontrol.c(3daf263), PEP 562, Contour synchronized output (?2026), Contour palette update notifications (?2031), VS Code shell integration (OSC 633)
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
0.0.xto0.1.0and beyond Roadmap #35tony commentedon Nov 28, 2026
Completed and shipped in v0.0.1a2 (#44, #45, #47, #48, #49, #50, #51).