Repository navigation
Description
Summary
Split src/libvt/terminal.py and src/libvt/screen.py along acyclic layer boundaries, replace cross-module private attribute coupling with explicit internal protocols, and sequence a structural split PR ahead of rebasing and fixing the pending cohort currently exercised in #193.
Motivation
At v0.0.1a5 (587227c), libvt has grown to 29,897 lines across 28 modules, and the pending cohort in #193 pushes src/libvt/ to 33,598 lines. That growth concentrated several structural couplings that already cause integration regressions when independent PRs land together.
src/libvt/terminal.pyspans 7,216 lines (7,635 on#193), packingSnapshot,SyncToken,ScreenDelta,Formatter,FlightRecorder, CSI/OSC/ESC/DCS dispatch, and a 5,097-lineTerminalclass (77 instance attributes, no__slots__) into one module.Terminal._handle_csialone is 699 lines with cyclomatic complexity 245, and the private-mode support matrix is duplicated in four places.src/libvt/screen.pyspans 2,442 lines and importslibvt.terminalinside method bodies (Screen.blitandScreen.snapshot) to work around a circular dependency.Screen._reflow_primaryis 332 lines in one function,RowView.runsunpacks a freshStyleper column on mutable_Rowobjects (measured 56.6x slower thanFrozenRow), and top-levelScreenexposes raw 64-bit_gridwords (bce_word) and internal hooks (heal_before_edit,heal_wrapped_spacer_head,ensure_graphics).libvt.contrib.tmuxreaches into 163 private attributes and methods onTerminalandScreenacrosscapture.py(78 accesses) andcontrol.py(85 accesses)._adopt_terminal_stateincontrol.pyhand-copies 43 ofTerminal's 77 attributes and misses 36, leaking guestOSC 10/11/4colors,OSC 7501status, title stacks, pendingOSC 99state, and_repliesacrossTmuxPaneSync.resync().- Core
src/libvt/testing.pyimportslibvt.contrib.tmux.capture.TmuxCaptureResultat runtime inside_extract_target, inverting the core-to-contrib boundary, and calls arbitrary.snapshot()attributes on nested objects. src/libvt/contrib/tmux/window.py(3,156 lines) portstmux's C theme, border, format-draw, and 650-entry X11 color renderer into the corelibvtwheel, whilesrc/libvt/graphics.py(2,127 lines) is loaded eagerly onTerminalimport even when noSIXELor KittyAPC Gsequence arrives.- Six modules import private
_parse_ascii_uintor_parse_ascii_intfromlibvt.parser, and siblingBufferentry points (src/libvt/aio.py,src/libvt/contrib/tmux/control.py, and#139'ssrc/libvt/pytest_plugin.py) still callmemoryview.cast("B")directly instead of sharing#186's_byte_viewhelper. - Merging 48 open PRs into
#193exposed concrete cross-PR seam defects:#139monkey-patchesterm.feed,term.feed_until, andterm.resizeonto liveTerminalinstances (permanently blocking__slots__), breaks#186strided buffers viaview.cast("B"), and misses#164'sencoding="latin-1"insupported=;#142enforcesVT.raw_limit >= 64against#182'sFlightRecorder(max_bytes >= 0)contract and double-boots Python on macOS (open_ptytrampoline into_LEADER);#158raisesProtocolErrorwhile#167raisesValueErrorfor the sametmux < 3.2check onTmuxPaneSync;#149deleted_absorb_2d_slackwithout updatingREADME.md; and several draft concept PRs (#133,#138,#139,#140,#141,#142) added relative repository links toREADME.md.
Proposal
Land a structural split and decoupling PR on master first, keeping public top-level libvt exports and PEP 562 lazy import behavior unchanged, then rebase and repair each source PR on top of that base before regenerating the omnibus integration branch (#193).
Target 4-tier acyclic module layout
src/libvt/
├── _util.py # Shared _parse_ascii_{uint,int}, _byte_view, baseline mode sets
├── snapshot.py # Snapshot, CellSpan, SyncToken, ScreenDelta, ResyncReason, SnapshotDict
├── views.py # Cell, RowRun, RowView (uniform-attr fast path), RegionView, _HistoryView
├── _reflow.py # Extracted Screen._reflow_primary pipeline
├── screen.py # Screen, ScreenSet, Cursor, ScrollRegion (no terminal.py import)
├── format.py # OutputFormat, Formatter (PLAIN / VT / HTML)
├── recorder.py # TerminalRecorder protocol, FlightRecorder, opt-in replay tap
├── _vt_dispatch.py # Table-driven CSI / OSC / ESC / DCS dispatch + single mode-support table
├── terminal.py # Lean Terminal facade with __slots__, hydrate/replace_from hooks
├── graphics/ # Lazy-loaded package (_tracker.py, _sixel.py, _kitty.py)
├── aio/ # Shared _core.py (sync timer, _FrameWaits, wait_for) + _stream.py + PTY backends
├── testing.py # Assertions, boxed serialization, scrubbing via SupportsVtTarget protocol
└── contrib/
├── syrupy.py # Thin AmberSnapshotExtension adapter
└── tmux/ # profile.py, _layout.py, capture.py, control.py (window.py moved out to libtmux)
Specific architectural changes
- Break the
screen.py/terminal.pycycle by movingSnapshot,SyncToken,ScreenDelta,ResyncReason, and_make_snapshotintosrc/libvt/snapshot.py, and movingFormatterandOutputFormatintosrc/libvt/format.py. Keep re-exports insrc/libvt/terminal.pyduring0.0.xso existing imports keep working. - Move
Screen._reflow_primaryintosrc/libvt/_reflow.py, moveCell/RowRun/RowView/RegionView/_HistoryViewintosrc/libvt/views.py, add a uniform-attribute and raw-word fast path toRowView.runson_Row, hide_scroll_up_raw(bce_word=...)and_heal_*behind_-prefixed internal methods, and validateScreen.cursorandScreen.scroll_regionmutations. - Move CSI/OSC/ESC/DCS handlers into
src/libvt/_vt_dispatch.pywith aprefix == 0 and not intermediatesfast path, consolidate the four copies of the private-mode support matrix intosrc/libvt/modes.py, and add__slots__toTerminal. - Add
Terminal.replace_from(other)(or_replace_state_from) backed by a slot-completeness test soTmuxPaneSync.resync()transfers all terminal state cleanly instead of hand-copying 43 attributes, and add a structured hydration constructor onTerminal/Screensocontrib/tmux/capture.pydrops its 78 private attribute writes. - Deduplicate V1/V2 tmux layout parsing into
src/libvt/contrib/tmux/_layout.py, and plan extraction of the 3,156-linesrc/libvt/contrib/tmux/window.pycompositor intolibtmuxwhile retainingScreen.blit,Screen.put_text, andScreen.snapshotinlibvt. - Invert the
testing.pytocontrib/tmuximport via an explicitSupportsVtTargetprotocol (__vt_target__) implemented byTmuxCaptureResult,PtySession, andAsyncTerminalStream, removing the runtimecontribimport and stopping_extract_targetfrom invoking arbitrary.snapshot()callables. - Replace
#139's instance monkey-patching with a two-methodTerminalRecorderprotocol (on_feed(data: memoryview)andon_resize(rows, cols, reflow)) wired throughTerminal(..., recorder=...)after_byte_viewnormalization, capturingencoding,scrollback,profile,policy, andlimitsdirectly from the terminal. - Split
src/libvt/aio.pyintoaio/_core.py,aio/_stream.py, and platform PTY backends (_pty_posix.py,_pty_conpty.py), sharing sync-timer,_FrameWaits,wait_for, and input-send logic betweenAsyncTerminalStreamandPtySession, fixing or removing deadAsyncTerminalStream.write_high_water, and replacing rawterminal._on_reply_queuedmutation with a clean registration hook. - Lazy-import
libvt.graphicsonly when the firstSIXELor KittyAPC Gsequence arrives, unify the 17 repeatederase_sixel_rectcall sites behind oneScreenerase hook, and decouplestatus.pyOSC 9;4validation from malformedOSC 7501frames. - Extract
_parse_ascii_uint,_parse_ascii_int, and_byte_viewintosrc/libvt/_util.pyso everycollections.abc.Bufferentry point uses one contiguous-safe path.
PR restack and recut sequence
- Land the Tier 0/1 structural split PR (
_util.py,snapshot.py,views.py,_reflow.py,format.py,_vt_dispatch.py,recorder.py,Terminal.__slots__,Terminal.replace_from,SupportsVtTarget,aio/split) with zero behavioral regressions againstmastertests and doctests. - Rebase and fix the clean bugfix PRs individually in their own PR branches:
#149(updateREADME.mdalongside_absorb_2d_slackremoval),#150,#152,#156–#165,#167–#192(align#158and#167to raise the same exception type ontmux < 3.2, route remaining.cast("B")sites through_util._byte_view), plus#131and#133(fix relativeREADME.mdURLs to absolute docs links). - Redesign or hold back the speculative draft concept PRs before merging them into trunk or
#193: recut#139onTerminalRecorder, recut#142onto the shared PTY backend without stdlibPopen/runre-exports or double-Python Darwin launch (and alignraw_limitwith#182), reconsider#151's bespokelibvt snapshot sections 1wire format incontrib/syrupy.py, and keep#140out of the core package path. - Rebuild the omnibus integration PR (
#193) from the rebased and repaired source PRs and verify all Linux, macOS, Windows, and PyPy gates.
Alternatives
- Keeping
terminal.pyandscreen.pymonolithic and landing the 48 PRs directly ontomasterwas weighed and rejected because concurrent edits toterminal.py,screen.py,testing.py,aio.py, andpytest_plugin.pyalready produced merge-seam regressions in#193(#139x#164,#139x#186,#142x#182,#158x#167) and leaveTerminalunable to adopt__slots__or eliminate the circularscreen.pyimport. - Splitting every CSI or OSC sequence into per-sequence micro-modules (40+ files) was rejected per ADR 0002 to preserve fast cold imports and direct dispatch.
References
- Omnibus integration cohort: Exercise pending terminal changes together on Linux #193
- Roadmap tracking issue:
0.0.xto0.1.0and beyond Roadmap #35 Terminalclass without__slots__:src/libvt/terminal.pyTerminal._handle_csimonolith:src/libvt/terminal.pyTerminal._tabstops_from_listcontrib backdoor:src/libvt/terminal.pyScreencircular imports oflibvt.terminal:Screen.blitandScreen.snapshotRowView.runs_Rowpath andScreen._reflow_primary:src/libvt/screen.pyandsrc/libvt/screen.pytesting.pyruntimecontrib/tmuximport and duck-typed.snapshot()call:src/libvt/testing.py_adopt_terminal_statepartial field copy:src/libvt/contrib/tmux/control.py
Activity
aio(refactor): Split package with _SessionCore
Merge pull request #204 from tmux-python/refactor/203-structural-split
core(refactor): Split views, terminal, and aio (#204)
docs(api): Add per-module pages and split aio (#205)