Skip to content

Split terminal.py and screen.py, decouple contrib, restack PRs #203

Done

Description

@tony

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.py spans 7,216 lines (7,635 on #193), packing Snapshot, SyncToken, ScreenDelta, Formatter, FlightRecorder, CSI/OSC/ESC/DCS dispatch, and a 5,097-line Terminal class (77 instance attributes, no __slots__) into one module. Terminal._handle_csi alone is 699 lines with cyclomatic complexity 245, and the private-mode support matrix is duplicated in four places.
  • src/libvt/screen.py spans 2,442 lines and imports libvt.terminal inside method bodies (Screen.blit and Screen.snapshot) to work around a circular dependency. Screen._reflow_primary is 332 lines in one function, RowView.runs unpacks a fresh Style per column on mutable _Row objects (measured 56.6x slower than FrozenRow), and top-level Screen exposes raw 64-bit _grid words (bce_word) and internal hooks (heal_before_edit, heal_wrapped_spacer_head, ensure_graphics).
  • libvt.contrib.tmux reaches into 163 private attributes and methods on Terminal and Screen across capture.py (78 accesses) and control.py (85 accesses). _adopt_terminal_state in control.py hand-copies 43 of Terminal's 77 attributes and misses 36, leaking guest OSC 10/11/4 colors, OSC 7501 status, title stacks, pending OSC 99 state, and _replies across TmuxPaneSync.resync().
  • Core src/libvt/testing.py imports libvt.contrib.tmux.capture.TmuxCaptureResult at 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) ports tmux's C theme, border, format-draw, and 650-entry X11 color renderer into the core libvt wheel, while src/libvt/graphics.py (2,127 lines) is loaded eagerly on Terminal import even when no SIXEL or Kitty APC G sequence arrives.
  • Six modules import private _parse_ascii_uint or _parse_ascii_int from libvt.parser, and sibling Buffer entry points (src/libvt/aio.py, src/libvt/contrib/tmux/control.py, and #139's src/libvt/pytest_plugin.py) still call memoryview.cast("B") directly instead of sharing #186's _byte_view helper.
  • Merging 48 open PRs into #193 exposed concrete cross-PR seam defects: #139 monkey-patches term.feed, term.feed_until, and term.resize onto live Terminal instances (permanently blocking __slots__), breaks #186 strided buffers via view.cast("B"), and misses #164's encoding="latin-1" in supported=; #142 enforces VT.raw_limit >= 64 against #182's FlightRecorder(max_bytes >= 0) contract and double-boots Python on macOS (open_pty trampoline into _LEADER); #158 raises ProtocolError while #167 raises ValueError for the same tmux < 3.2 check on TmuxPaneSync; #149 deleted _absorb_2d_slack without updating README.md; and several draft concept PRs (#133, #138, #139, #140, #141, #142) added relative repository links to README.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.py cycle by moving Snapshot, SyncToken, ScreenDelta, ResyncReason, and _make_snapshot into src/libvt/snapshot.py, and moving Formatter and OutputFormat into src/libvt/format.py. Keep re-exports in src/libvt/terminal.py during 0.0.x so existing imports keep working.
  • Move Screen._reflow_primary into src/libvt/_reflow.py, move Cell/RowRun/RowView/RegionView/_HistoryView into src/libvt/views.py, add a uniform-attribute and raw-word fast path to RowView.runs on _Row, hide _scroll_up_raw(bce_word=...) and _heal_* behind _-prefixed internal methods, and validate Screen.cursor and Screen.scroll_region mutations.
  • Move CSI/OSC/ESC/DCS handlers into src/libvt/_vt_dispatch.py with a prefix == 0 and not intermediates fast path, consolidate the four copies of the private-mode support matrix into src/libvt/modes.py, and add __slots__ to Terminal.
  • Add Terminal.replace_from(other) (or _replace_state_from) backed by a slot-completeness test so TmuxPaneSync.resync() transfers all terminal state cleanly instead of hand-copying 43 attributes, and add a structured hydration constructor on Terminal/Screen so contrib/tmux/capture.py drops 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-line src/libvt/contrib/tmux/window.py compositor into libtmux while retaining Screen.blit, Screen.put_text, and Screen.snapshot in libvt.
  • Invert the testing.py to contrib/tmux import via an explicit SupportsVtTarget protocol (__vt_target__) implemented by TmuxCaptureResult, PtySession, and AsyncTerminalStream, removing the runtime contrib import and stopping _extract_target from invoking arbitrary .snapshot() callables.
  • Replace #139's instance monkey-patching with a two-method TerminalRecorder protocol (on_feed(data: memoryview) and on_resize(rows, cols, reflow)) wired through Terminal(..., recorder=...) after _byte_view normalization, capturing encoding, scrollback, profile, policy, and limits directly from the terminal.
  • Split src/libvt/aio.py into aio/_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 between AsyncTerminalStream and PtySession, fixing or removing dead AsyncTerminalStream.write_high_water, and replacing raw terminal._on_reply_queued mutation with a clean registration hook.
  • Lazy-import libvt.graphics only when the first SIXEL or Kitty APC G sequence arrives, unify the 17 repeated erase_sixel_rect call sites behind one Screen erase hook, and decouple status.py OSC 9;4 validation from malformed OSC 7501 frames.
  • Extract _parse_ascii_uint, _parse_ascii_int, and _byte_view into src/libvt/_util.py so every collections.abc.Buffer entry point uses one contiguous-safe path.

PR restack and recut sequence

  1. 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 against master tests and doctests.
  2. Rebase and fix the clean bugfix PRs individually in their own PR branches: #149 (update README.md alongside _absorb_2d_slack removal), #150, #152, #156–#165, #167–#192 (align #158 and #167 to raise the same exception type on tmux < 3.2, route remaining .cast("B") sites through _util._byte_view), plus #131 and #133 (fix relative README.md URLs to absolute docs links).
  3. Redesign or hold back the speculative draft concept PRs before merging them into trunk or #193: recut #139 on TerminalRecorder, recut #142 onto the shared PTY backend without stdlib Popen/run re-exports or double-Python Darwin launch (and align raw_limit with #182), reconsider #151's bespoke libvt snapshot sections 1 wire format in contrib/syrupy.py, and keep #140 out of the core package path.
  4. 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.py and screen.py monolithic and landing the 48 PRs directly onto master was weighed and rejected because concurrent edits to terminal.py, screen.py, testing.py, aio.py, and pytest_plugin.py already produced merge-seam regressions in #193 (#139 x #164, #139 x #186, #142 x #182, #158 x #167) and leave Terminal unable to adopt __slots__ or eliminate the circular screen.py import.
  • 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

Activity

  1. added
    enhancement
    on Dec 5, 2026
  2. added 2 commits that reference this issue on Dec 5, 2026
  3. added 2 commits that reference this issue on Dec 5, 2026
    aeb55d4
    d087b05
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

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions