diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index b0ef49c0..ae62ab0a 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -112,9 +112,70 @@ jobs: - name: JIT throughput smoke (bench_vt.py) run: uv run python scripts/bench_vt.py --warmup 25 --runs 10 + test-ghostty: + runs-on: ubuntu-24.04-arm + permissions: + contents: read + timeout-minutes: 15 + env: + ZIG_VERSION: "0.17.1" + ZIG_SHA256: "a1546d5646eb184437918d6635ca6b762a0e889eac09cef720ee7a1ed3fe7795" + GHOSTTY_VT_VERSION: "1.0.2" + GHOSTTY_VT_SHA256: "1dcafa8a3357f3a6bbf4f2696e61de611400c5469518716793dfffd35f008b3e" + GHOSTTY_VT_DEPS_SHA256: "c56156dbea82fdf71f13bf0d704cdf4393b6a04208d7f9691e0d7f60c7f9ca4d" + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10.2.0 + with: + version-file: .tool-versions + enable-cache: true + - uses: actions/setup-python@v7 + with: + python-version: "3.14" + - name: Install testing dependencies + run: uv sync --group testing + - name: Cache compiled libghostty-vt + id: cache-ghostty + uses: actions/cache@v6 + with: + path: ~/.cache/libghostty-vt + key: libghostty-vt-${{ runner.os }}-${{ runner.arch }}-${{ env.GHOSTTY_VT_VERSION }}-${{ env.GHOSTTY_VT_SHA256 }}-${{ env.GHOSTTY_VT_DEPS_SHA256 }}-${{ env.ZIG_VERSION }}-${{ env.ZIG_SHA256 }}-baseline + - name: Build pinned libghostty-vt 1.0.2 + if: steps.cache-ghostty.outputs.cache-hit != 'true' + shell: bash + run: | + set -euo pipefail + work="$(mktemp -d)" + trap 'rm -rf "$work"' EXIT + curl -fsSL "https://ziglang.org/download/${ZIG_VERSION}/zig-aarch64-linux-${ZIG_VERSION}.tar.xz" -o "$work/zig.tar.xz" + echo "${ZIG_SHA256} $work/zig.tar.xz" | sha256sum -c - + tar -xf "$work/zig.tar.xz" -C "$work" + zig_bin="$work/zig-aarch64-linux-${ZIG_VERSION}/zig" + "$zig_bin" version + curl -fsSL "https://release.files.ghostty.org/libghostty-vt/${GHOSTTY_VT_VERSION}/libghostty-vt-${GHOSTTY_VT_VERSION}.tar.gz" -o "$work/src.tar.gz" + curl -fsSL "https://release.files.ghostty.org/libghostty-vt/${GHOSTTY_VT_VERSION}/libghostty-vt-${GHOSTTY_VT_VERSION}-deps.tar.gz" -o "$work/deps.tar.gz" + echo "${GHOSTTY_VT_SHA256} $work/src.tar.gz" | sha256sum -c - + echo "${GHOSTTY_VT_DEPS_SHA256} $work/deps.tar.gz" | sha256sum -c - + mkdir -p "$work/src" "$work/deps" "$work/zig-cache" "$HOME/.cache/libghostty-vt" + tar -xzf "$work/src.tar.gz" --strip-components=1 -C "$work/src" + tar -xzf "$work/deps.tar.gz" --strip-components=1 -C "$work/deps" + ( + cd "$work/src" + ZIG_GLOBAL_CACHE_DIR="$work/zig-cache" "$zig_bin" build -Demit-lib-vt -Doptimize=ReleaseFast -Dcpu=baseline --system "$work/deps" --prefix "$HOME/.cache/libghostty-vt" + ) + - name: Run compiled libghostty-vt differential suite + shell: bash + run: | + set -euo pipefail + lib_path="$(readlink -e "$HOME/.cache/libghostty-vt/lib/libghostty-vt.so")" + echo "Zig pin: ${ZIG_VERSION} (${ZIG_SHA256})" + echo "libghostty-vt pin: ${GHOSTTY_VT_VERSION} (${GHOSTTY_VT_SHA256})" + echo "Resolved library: ${lib_path}" + LIBGHOSTTY_VT_PATH="$lib_path" uv run pytest -m ghostty -v tests/test_differential_ghostty.py + release: runs-on: ubuntu-latest - needs: [test, test-macos, test-windows, test-pypy] + needs: [test, test-macos, test-windows, test-pypy, test-ghostty] if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags') timeout-minutes: 10 permissions: diff --git a/CHANGES b/CHANGES index 5198f6ac..9c107545 100644 --- a/CHANGES +++ b/CHANGES @@ -114,6 +114,13 @@ Deleting an attribute on {class}`~libvt.snapshot.Snapshot` now raises ### Documentation +#### Per-profile control-function conformance matrix (#12) + +{ref}`project-conformance` maps every control function and mode in +{mod}`libvt.codec` and {mod}`libvt.modes` across host profiles, guarded by a +CI drift check and backed by a recorded `.jsonl` differential corpus verified +against compiled `libghostty-vt` (`LIBGHOSTTY_VT_PATH`). + #### Play and replay The Last Beacon (#140) The {ref}`game walkthrough ` drives a playable diff --git a/docs/project/conformance.md b/docs/project/conformance.md new file mode 100644 index 00000000..13a7f842 --- /dev/null +++ b/docs/project/conformance.md @@ -0,0 +1,181 @@ +(project-conformance)= + +# Control-Function Conformance + +Per-profile control-function and mode conformance derived from +{mod}`libvt.codec`, {mod}`libvt.modes`, and {mod}`libvt.profiles`, verified +against the recorded differential corpus in `tests/fixtures/ghostty_corpus/` +and compiled `libghostty-vt` (`LIBGHOSTTY_VT_PATH`). + +Status values: + +- **Supported**: Implemented across profiles per ECMA-48, DEC STD 070, VT500, or + the referenced host protocol. +- **Partial**: Parsed and handled for core subcommands or event emission; + unmodeled subcommands are ignored or reported as unhandled. +- **Ignored**: Parsed cleanly and ignored (or gated off by profile/policy). +- **Divergent**: Behavior varies intentionally across host profiles + ({data}`~libvt.config.DEFAULT_PROFILE`, + {data}`~libvt.profiles.GHOSTTY_PROFILE`, + {data}`~libvt.profiles.KITTY_PROFILE`, + {data}`~libvt.profiles.XTERM_PROFILE`, + {data}`~libvt.profiles.LINUX_CONSOLE_PROFILE`, and + {func}`~libvt.contrib.tmux.profile.tmux_profile`). + +## C0 Controls + +| Mnemonic | Byte | Status | Profile notes & test modules | +| --- | --- | --- | --- | +| `BEL` | `0x07` | Supported | Emits `Bell` and terminates `OSC`; `tests/test_terminal.py` | +| `BS` | `0x08` | Supported | Clears `pending_wrap` (or steps back under `?45`); `tests/test_screen.py` | +| `HT` | `0x09` | Supported | Advances to next tab stop or right margin; `tests/test_screen.py` | +| `LF` | `0x0A` | Supported | Line feed (adds `CR` under `LNM`); `tests/test_terminal.py` | +| `VT` | `0x0B` | Supported | Treated as `LF` per ECMA-48/xterm; `tests/test_differential_ghostty.py` | +| `FF` | `0x0C` | Supported | Treated as `LF` per ECMA-48/xterm; `tests/test_differential_ghostty.py` | +| `CR` | `0x0D` | Supported | Moves cursor to left margin and clears `pending_wrap`; `tests/test_screen.py` | +| `SO` | `0x0E` | Supported | Shifts `GL` to `G1` (`LINUX_CONSOLE_PROFILE` defaults `G1` to `'0'`); `tests/test_terminal.py` | +| `SI` | `0x0F` | Supported | Shifts `GL` to `G0`; `tests/test_terminal.py` | + +## ESC, DCS, and APC Sequences + +| Family | Mnemonic | Status | Profile notes & test modules | +| --- | --- | --- | --- | +| `ESC` | `SCS` | Supported | Designates `G0`–`G3` (`'B'`, `'0'`, `'A'`, `'U'` CP437 in `latin-1`); `tests/test_terminal.py` | +| `ESC` | `DOCS` | Divergent | `ESC % G` / `ESC % @` honored when `ScreenBehavior.allow_encoding_switch` is true (`LINUX_CONSOLE_PROFILE`); `tests/test_terminal.py` | +| `DCS` | `SIXEL` | Divergent | Tracks cell-aligned placements (respects `DECSDM` `?80`); `tmux_profile < 3.9` uses `sixel_erase_policy="whole_image"` vs `"cell_mask"`; `tests/test_graphics.py` | +| `DCS` | `DECRQSS` | Divergent | Replies with active SGR/margins/style; disabled on `LINUX_CONSOLE_PROFILE` and `tmux_profile < 3.6`; `tests/test_terminal.py` | +| `DCS` | `XTGETTCAP` | Divergent | Replies with hex-encoded capabilities; disabled on `LINUX_CONSOLE_PROFILE` and `tmux_profile`; `tests/test_terminal.py` | +| `APC` | `KITTY_GFX` | Supported | Tracks Kitty graphics `APC G` placements and responses; `tests/test_graphics.py` | + +## CSI Control Functions + +| Final / Form | Mnemonic | Status | Profile notes & test modules | +| --- | --- | --- | --- | +| `CSI @` | `ICH` | Supported | Inserts BCE blanks within active margins; `tests/test_screen.py` | +| `CSI A` | `CUU` | Supported | Moves cursor up within scroll margins; `tests/test_screen.py` | +| `CSI B` | `CUD` | Supported | Moves cursor down within scroll margins; `tests/test_screen.py` | +| `CSI C` | `CUF` | Supported | Moves cursor right within active margins; `tests/test_screen.py` | +| `CSI D` | `CUB` | Supported | Moves cursor left within active margins; `tests/test_screen.py` | +| `CSI E` | `CNL` | Supported | Moves cursor down and to left margin; `tests/test_differential_ghostty.py` | +| `CSI F` | `CPL` | Supported | Moves cursor up and to left margin; `tests/test_differential_ghostty.py` | +| `CSI G` | `CHA` | Supported | Sets cursor column (1-based); `tests/test_screen.py` | +| `CSI H` | `CUP` | Supported | Sets cursor `(row, col)` honoring `DECOM`; `tests/test_screen.py` | +| `CSI I` | `CHT` | Supported | Advances `Pn` tab stops; `tests/test_differential_ghostty.py` | +| `CSI J` | `ED` | Divergent | `ED 3` clears scrollback on alt screen for `XTERM_PROFILE`, `KITTY_PROFILE`, and `tmux_profile`; `tmux_profile` scrolls primary on `ED 2` (`ed2_scrolls_primary_to_history=True`) and uses `pending_wrap_phantom_col=True`; `GHOSTTY_PROFILE` preserves history wrap (`erase_severs_history_wrap=False`); `tests/test_screen.py` | +| `CSI K` | `EL` | Divergent | BCE erase in line; scalar `text_used` retains earlier `ECH` blank spans after interior `ECH` (unlike Ghostty's per-cell tag); `tmux_profile` sets `pending_wrap_phantom_col=True` and `GHOSTTY_PROFILE` sets `erase_severs_history_wrap=False`; `tests/test_differential_ghostty.py` | +| `CSI L` | `IL` | Divergent | Inserts lines within scroll region; `tmux_profile` preserves cursor column (`il_dl_resets_col=False`); `tests/test_screen.py` | +| `CSI M` | `DL` | Divergent | Deletes lines within scroll region; `tmux_profile` preserves cursor column (`il_dl_resets_col=False`); `tests/test_screen.py` | +| `CSI P` | `DCH` | Supported | Deletes characters within active margins; `tests/test_screen.py` | +| `CSI S` | `SU` | Divergent | Scrolls region up (pushes primary scrollback when full-screen; `tmux_profile` also pushes to history when `top > 0` via `top_margin_scrolls_to_history=True`); `tests/test_screen.py` | +| `CSI T` | `SD` | Supported | Scrolls region down; `tests/test_screen.py` | +| `CSI X` | `ECH` | Supported | Erases `Pn` cells with current BCE background; `tests/test_differential_ghostty.py` | +| `CSI Z` | `CBT` | Divergent | Backward tab stops; `GHOSTTY_PROFILE` and `XTERM_PROFILE` preserve `pending_wrap` (`cbt_preserves_pending_wrap=True`); `tests/test_screen.py` | +| `` CSI ` `` | `HPA` | Supported | Horizontal position absolute; `tests/test_differential_ghostty.py` | +| `CSI a` | `HPR` | Divergent | Horizontal position relative; ignored on `tmux_profile` (`hpr_vpr_enabled=False`); `tests/test_differential_ghostty.py` | +| `CSI b` | `REP` | Divergent | Repeats previous printable cluster; `GHOSTTY_PROFILE` uses `rep_uses_last_graphic=True` and `tmux_profile < 3.9` sets `rep_wraps=False`; `tests/test_terminal.py` | +| `CSI c` | `DA1` | Divergent | Emits `Profile.identity.da1` (silent when `Policy.emit_replies=False`); `tests/test_terminal.py` | +| `CSI d` | `VPA` | Supported | Vertical position absolute; `tests/test_differential_ghostty.py` | +| `CSI e` | `VPR` | Divergent | Vertical position relative; ignored on `tmux_profile` (`hpr_vpr_enabled=False`); `tests/test_differential_ghostty.py` | +| `CSI f` | `HVP` | Supported | Same positioning semantics as `CUP`; `tests/test_screen.py` | +| `CSI g` | `TBC` | Supported | Clears current or all tab stops (`0`/`3`); `tests/test_differential_ghostty.py` | +| `CSI h` | `SM` | Supported | Sets ANSI modes (`IRM`, `LNM`); `tests/test_terminal.py` | +| `CSI l` | `RM` | Supported | Resets ANSI modes (`IRM`, `LNM`); `tests/test_terminal.py` | +| `CSI m` | `SGR` | Supported | Attributes, 16/256/RGB colors, T.416 `:` subparameters, underline styles/colors; `tests/test_differential_ghostty.py` | +| `CSI n` | `DSR` | Supported | Device status (`5n`), cursor position (`6n`), color-scheme query (`?996n`); `tests/test_terminal.py` | +| `CSI q` | `XTVERSION/DECSCUSR` | Divergent | `CSI > q` (`XTVERSION`) emits `Profile.identity.xtversion`; `CSI Ps SP q` sets cursor shape; `tests/test_terminal.py` | +| `CSI r` | `DECSTBM` | Supported | Sets top/bottom scroll margins and homes cursor; `tests/test_screen.py` | +| `CSI s` | `DECSLRM/SCOSC` | Divergent | Sets left/right margins when `DECLRMM` (`?69`) is active (disabled on `LINUX_CONSOLE_PROFILE` and `tmux_profile`), else saves cursor; `tests/test_screen.py` | +| `CSI t` | `XTWINOPS` | Partial | Supports title stack push/pop (`22`/`23`) and pixel/cell geometry reports (`14`/`16`/`18`); ignores window-manager move/resize requests; `tests/test_terminal.py` | +| `CSI u` | `SCORC/KITTY_KBD` | Divergent | Restores cursor (`CSI u`); `CSI > / < / = / ? u` (`KITTY_KBD`) disabled on `XTERM_PROFILE`, `LINUX_CONSOLE_PROFILE`, and `tmux_profile`; `tests/test_input.py` | +| `CSI ? h` | `DECSET` | Supported | Sets supported DEC private modes; `tests/test_terminal.py` | +| `CSI ? l` | `DECRST` | Supported | Resets supported DEC private modes; `tests/test_terminal.py` | +| `CSI ? $ p` | `DECRQM` | Supported | Reports mode status (`0`–`4`) honoring `is_private_mode_supported`; `tests/test_terminal.py` | +| `CSI > q` | `XTVERSION` | Divergent | Emits `DCS > \| ST` when `Profile.identity.xtversion` is non-empty; `tests/test_terminal.py` | +| `CSI " q` | `DECSCA` | Supported | Marks subsequent cells protected/unprotected against `DECSED`/`DECSEL`; `tests/test_screen.py` | +| `CSI ? J` | `DECSED` | Supported | Selective erase in display respecting `DECSCA`; `tests/test_screen.py` | +| `CSI ? K` | `DECSEL` | Supported | Selective erase in line respecting `DECSCA`; `tests/test_screen.py` | +| `CSI ? s` | `XTSAVE` | Divergent | Saves current DEC private mode values; ignored on `tmux_profile` (`xtsave_enabled=False`); `tests/test_input.py` | +| `CSI ? r` | `XTRESTORE` | Divergent | Restores saved DEC private mode values; ignored on `tmux_profile` (`xtsave_enabled=False`); `tests/test_input.py` | +| `CSI ? S` | `XTSMGRAPHICS` | Divergent | Stateful color-register and pixel-geometry queries; disabled on `GHOSTTY_PROFILE`, `KITTY_PROFILE`, `LINUX_CONSOLE_PROFILE`, and default `TMUX_PROFILE` (`sixel=False`; geometry/set remain off when `sixel=True`); `tests/test_terminal.py` | + +## OSC Sequences + +| Code | Mnemonic | Status | Profile notes & test modules | +| --- | --- | --- | --- | +| `0` | `OSC 0 (icon+title)` | Supported | Updates window title and emits `TitleChanged`; `tests/test_terminal.py` | +| `1` | `OSC 1 (icon)` | Supported | Emits `TitleChanged(target=ICON)`; `tests/test_terminal.py` | +| `2` | `OSC 2 (title)` | Supported | Updates window title and emits `TitleChanged(target=WINDOW)`; `tests/test_terminal.py` | +| `4` | `OSC 4 (palette)` | Supported | Sets/queries indexed palette RGB entries; `tests/test_terminal.py` | +| `7` | `OSC 7 (cwd)` | Supported | Emits `WorkingDirectoryChanged(source=OSC7)`; `tests/test_terminal.py` | +| `8` | `OSC 8 (hyperlink)` | Supported | Attaches `Hyperlink` spans to written cells (cleared on BCE); `tests/test_terminal.py` | +| `9` | `OSC 9 (notification/progress)` | Supported | `OSC 9;4` updates root progress; other `OSC 9` emits `Notification`; `tests/test_status.py` | +| `10` | `OSC 10 (fg color)` | Supported | Sets/queries default foreground RGB (held across `?2026`); `tests/test_terminal.py` | +| `11` | `OSC 11 (bg color)` | Supported | Sets/queries default background RGB (held across `?2026`); `tests/test_terminal.py` | +| `12` | `OSC 12 (cursor color)` | Supported | Sets/queries cursor RGB (held across `?2026`); `tests/test_terminal.py` | +| `22` | `OSC 22 (pointer shape)` | Ignored | Parsed and dispatched to `UnhandledSequence` when recorded; `tests/test_codec.py` | +| `52` | `OSC 52 (clipboard)` | Supported | Emits `ClipboardWrite` and policy-gated `ClipboardReadRequested`; `tests/test_terminal.py` | +| `66` | `OSC 66 (text sizing)` | Ignored | Parsed and dispatched to `UnhandledSequence` when recorded; `tests/test_codec.py` | +| `99` | `OSC 99 (kitty notification)` | Supported | Reassembles chunked Kitty notifications into `Notification`; `tests/test_terminal.py` | +| `104` | `OSC 104 (reset palette)` | Supported | Resets one or all palette entries to profile defaults; `tests/test_terminal.py` | +| `110` | `OSC 110 (reset fg color)` | Supported | Resets foreground RGB to profile default; `tests/test_terminal.py` | +| `111` | `OSC 111 (reset bg color)` | Supported | Resets background RGB to profile default; `tests/test_terminal.py` | +| `112` | `OSC 112 (reset cursor color)` | Supported | Resets cursor RGB to profile default; `tests/test_terminal.py` | +| `133` | `OSC 133 (semantic prompt)` | Supported | Tracks monotonic `PromptZone` anchors across scrollback; `tests/test_terminal.py` | +| `633` | `OSC 633 (shell integration)` | Supported | Normalizes `A`–`D` prompts, `E` commands, and `P` properties; `tests/test_terminal.py` | +| `777` | `OSC 777 (notification)` | Supported | Parses `777;notify` into `Notification`; `tests/test_terminal.py` | +| `3008` | `OSC 3008 (context)` | Ignored | Parsed and dispatched to `UnhandledSequence` when recorded; `tests/test_codec.py` | +| `5522` | `OSC 5522 (mime clipboard)` | Ignored | Parsed and dispatched to `UnhandledSequence` when recorded; `tests/test_codec.py` | +| `7501` | `OSC 7501 (program status)` | Divergent | Tracks Rex program status tree and `?` queries; queries disabled when `Profile.identity.osc_7501_capabilities` is empty (`KITTY_PROFILE`, `XTERM_PROFILE`, `LINUX_CONSOLE_PROFILE`, `tmux_profile < 3.9`; `"?"` on `tmux_profile >= 3.9`); `tests/test_status.py` | + +## ANSI and DEC Modes + +| Mode | Code | Status | Profile notes & test modules | +| --- | --- | --- | --- | +| `IRM` | `4` | Supported | Insert mode shifts cells right within active margins; `tests/test_differential_ghostty.py` | +| `LNM` | `20` | Supported | Automatic newline adds `CR` on `LF`/`VT`/`FF`; `tests/test_differential_ghostty.py` | +| `DECCKM` | `?1` | Supported | Switches arrow keys between `CSI` and `SS3`; `tests/test_input.py` | +| `DECCOLM` | `?3` | Divergent | Gated by `?40` (`ALLOW_80_132`) by default; `CLEAR_ONLY` on `tmux_profile`, `IGNORE` on `LINUX_CONSOLE_PROFILE`; `tests/test_terminal.py` | +| `DECSCNM` | `?5` | Supported | Reverse video reflected in committed `Snapshot.appearance`; `tests/test_terminal.py` | +| `DECOM` | `?6` | Supported | Origin mode bounds `CUP`/`HVP` to scroll margins; `tests/test_screen.py` | +| `DECAWM` | `?7` | Supported | Auto-wrap mode (enabled by default); `tests/test_screen.py` | +| `AUTO_REPEAT` | `?8` | Supported | Controls legacy `KeyAction.REPEAT` emission; `tests/test_input.py` | +| `MOUSE_X10` | `?9` | Supported | X10 press-only mouse tracking; `tests/test_input.py` | +| `DECTCEM` | `?25` | Supported | Cursor visibility flag on `Snapshot.cursor.visible`; `tests/test_terminal.py` | +| `ALLOW_80_132` | `?40` | Divergent | Enables `DECCOLM`; unrecognized when `deccolm` is `IGNORE` or `CLEAR_ONLY`; `tests/test_terminal.py` | +| `REVERSE_WRAP` | `?45` | Supported | Allows `BS` to wrap backward across wrapped rows; `tests/test_screen.py` | +| `ALT_SCREEN_47` | `?47` | Divergent | Switches alternate screen without cursor save; `alternate_entry_preserves_cursor` selects home vs preserve (`tmux_profile` preserves), and `libvt` keeps per-screen cursors on exit (Ghostty shares cursor position across `?47`); `tests/test_differential_ghostty.py` | +| `APPLICATION_KEYPAD` | `?66` | Supported | Selects `SS3` keypad encoding; `tests/test_input.py` | +| `BACKARROW_IS_BS` | `?67` | Supported | Switches legacy `backspace` between `0x08` and `0x7F`; `tests/test_input.py` | +| `DECLRMM` | `?69` | Divergent | Left/right margin mode; disabled on `LINUX_CONSOLE_PROFILE` and `tmux_profile`; `tests/test_screen.py` | +| `DECSDM` | `?80` | Supported | SIXEL display scrolling mode; `tests/test_graphics.py` | +| `DECNCSM` | `?95` | Divergent | Preserves screen contents on `DECCOLM`; unrecognized when `deccolm` is `IGNORE` or `CLEAR_ONLY`; `tests/test_terminal.py` | +| `MOUSE_VT200` | `?1000` | Supported | VT200 button press/release tracking; `tests/test_input.py` | +| `MOUSE_BUTTON_EVENT` | `?1002` | Supported | Drag motion tracking with `MouseTracker` deduplication; `tests/test_input.py` | +| `MOUSE_ANY_EVENT` | `?1003` | Supported | Any-motion mouse reporting; `tests/test_input.py` | +| `FOCUS_EVENT` | `?1004` | Supported | Window focus-in/focus-out reporting; `tests/test_input.py` | +| `MOUSE_SGR` | `?1006` | Divergent | SGR mouse coordinates; `GHOSTTY_PROFILE` resets classic coordinates on inactive encoding reset (`reset_any_mouse_encoding=True`); `tests/test_input.py` | +| `ALTERNATE_SCROLL` | `?1007` | Supported | Maps wheel events to `CUU`/`CUD` on alt screen when mouse tracking is off; `tests/test_input.py` | +| `MOUSE_SGR_PIXELS` | `?1016` | Divergent | Pixel SGR coordinates; unrecognized when `cell_width_px <= 0` or `cell_height_px <= 0`; `tests/test_input.py` | +| `ALT_SCREEN_1047` | `?1047` | Divergent | Clears alternate screen on switch; `alternate_entry_preserves_cursor` selects home vs preserve (`tmux_profile` preserves), and `libvt` keeps per-screen cursors on exit (Ghostty shares cursor position across `?1047`); `tests/test_differential_ghostty.py` | +| `DECSC_1048` | `?1048` | Divergent | Saves/restores cursor; unrecognized when `separate_alt_save_cursor=True` (`tmux_profile`); `tests/test_terminal.py` | +| `ALT_SCREEN` | `?1049` | Divergent | Saves cursor and switches alternate screen; `DEFAULT_PROFILE` homes alt cursor, while `alternate_entry_preserves_cursor=True` (`tmux_profile`) preserves it (matching Ghostty) and `tmux_profile` also sets `separate_alt_save_cursor=True`; `tests/test_differential_ghostty.py` | +| `BRACKETED_PASTE` | `?2004` | Supported | Wraps paste frames in `CSI 200 ~ ... CSI 201 ~`; `tests/test_input.py` | +| `SYNCHRONIZED_OUTPUT` | `?2026` | Supported | Holds `Terminal.committed` atomically until `?2026l` or expiry; `tests/test_terminal.py` | +| `GRAPHEME_CLUSTERING` | `?2027` | Supported | Unicode 17 grapheme clustering (enabled by default); `tests/test_ucd.py` | +| `COLOR_SCHEME_UPDATES` | `?2031` | Supported | Emits `CSI ? 997 ; Ps n` on `Terminal.set_theme()`; `tests/test_terminal.py` | +| `IN_BAND_RESIZE` | `?2048` | Supported | Emits `CSI 48 ; rows ; cols ; hpx ; wpx t` on resize; `tests/test_terminal.py` | + +## Running Compiled `libghostty-vt` Parity + +The default test suite runs chunk-boundary prefix determinism over all recorded +`.jsonl` corpus traces in `tests/fixtures/ghostty_corpus/` without requiring a +native compiler. To run compiled `libghostty-vt` differential parity locally, +point `LIBGHOSTTY_VT_PATH` to a built `libghostty-vt` shared library: + +```console +$ LIBGHOSTTY_VT_PATH=/path/to/libghostty-vt.so uv run pytest -m ghostty -v +``` + +When `LIBGHOSTTY_VT_PATH` is unset, `@pytest.mark.ghostty` tests skip. When +`LIBGHOSTTY_VT_PATH` is set to a missing path, `load_optional_ghostty_vt()` +raises {exc}`FileNotFoundError` so configured parity jobs fail visibly. diff --git a/docs/project/index.md b/docs/project/index.md index 37e6dc99..e86f667e 100644 --- a/docs/project/index.md +++ b/docs/project/index.md @@ -56,6 +56,12 @@ Public boundaries, stability policy, and deprecation process. Python runtime and platform support. ::: +:::{grid-item-card} Conformance +:link: conformance +:link-type: doc +Per-profile control-function and mode conformance matrix. +::: + :::{grid-item-card} Deprecations :link: deprecations :link-type: doc @@ -74,6 +80,7 @@ benchmark adr/index public-api compatibility +conformance deprecations ``` diff --git a/tests/_ghostty_vt.py b/tests/_ghostty_vt.py index 0cb28488..791d6cd0 100644 --- a/tests/_ghostty_vt.py +++ b/tests/_ghostty_vt.py @@ -15,6 +15,7 @@ import libvt from libvt.config import DEFAULT_PROFILE, Profile from libvt.modes import Mode +from libvt.style import AnsiColor, Color, IndexedColor, RgbColor, Style, UnderlineStyle GHOSTTY_SUCCESS = 0 GHOSTTY_POINT_TAG_ACTIVE = 0 @@ -80,6 +81,107 @@ class _GhosttySelection(ctypes.Structure): ) +class _GhosttyStyleColorValue(ctypes.Union): + _fields_ = ( + ("palette", ctypes.c_uint8), + ("rgb", _GhosttyColorRgb), + ) + + +class _GhosttyStyleColor(ctypes.Structure): + _fields_ = ( + ("tag", ctypes.c_uint8), + ("value", _GhosttyStyleColorValue), + ) + + +class _GhosttyStyle(ctypes.Structure): + _fields_ = ( + ("fg_color", _GhosttyStyleColor), + ("bg_color", _GhosttyStyleColor), + ("underline_color", _GhosttyStyleColor), + ("flags", ctypes.c_uint16), + ("reserved", ctypes.c_uint16), + ) + + +type _NormalizedColor = tuple[str, int] | tuple[str, int, int, int] | None +type _NormalizedStyle = tuple[ + _NormalizedColor, + _NormalizedColor, + _NormalizedColor, + bool, + bool, + bool, + int, + bool, + bool, + bool, + bool, + bool, +] + + +def _normalize_ghostty_color(color: _GhosttyStyleColor) -> _NormalizedColor: + if color.tag == 0: + return None + if color.tag == 1: + return ("palette", int(color.value.palette)) + if color.tag == 2: + rgb = color.value.rgb + return ("rgb", int(rgb.r), int(rgb.g), int(rgb.b)) + msg = f"unsupported GhosttyStyleColor tag: {color.tag}" + raise ValueError(msg) + + +def _normalize_ghostty_style(style: _GhosttyStyle) -> _NormalizedStyle: + flags = int(style.flags) + return ( + _normalize_ghostty_color(style.fg_color), + _normalize_ghostty_color(style.bg_color), + _normalize_ghostty_color(style.underline_color), + bool(flags & (1 << 0)), + bool(flags & (1 << 2)), + bool(flags & (1 << 1)), + (flags >> 8) & 0x7, + bool(flags & (1 << 3)), + bool(flags & (1 << 4)), + bool(flags & (1 << 5)), + bool(flags & (1 << 6)), + bool(flags & (1 << 7)), + ) + + +def _normalize_libvt_color(color: Color) -> _NormalizedColor: + if color is None: + return None + if isinstance(color, AnsiColor): + return ("palette", int(color)) + if isinstance(color, IndexedColor): + return ("palette", color.index) + if isinstance(color, RgbColor): + return ("rgb", color.r, color.g, color.b) + msg = f"unsupported libvt color: {color!r}" + raise ValueError(msg) + + +def _normalize_libvt_style(style: Style) -> _NormalizedStyle: + return ( + _normalize_libvt_color(style.fg), + _normalize_libvt_color(style.bg), + _normalize_libvt_color(style.underline_color), + style.bold, + style.dim, + style.italic, + int(UnderlineStyle(style.underline)), + style.blink, + style.reverse, + style.hidden, + style.strikethrough, + style.overline, + ) + + def pack_ghostty_mode(value: int, *, ansi: bool = False) -> int: """Pack a mode number and ANSI/DEC flag into a 16-bit ``GhosttyMode``. @@ -120,11 +222,26 @@ class TraceStep: cols: int = 0 +@dataclass(frozen=True, slots=True, kw_only=True) +class RecordedTrace: + """Named differential session trace loaded from ``.jsonl`` fixtures.""" + + name: str + rows: int + cols: int + steps: tuple[TraceStep, ...] + scrollback: int = 200 + profile: Profile = DEFAULT_PROFILE + compare_scrollback: bool = True + + @dataclass(frozen=True, slots=True, kw_only=True) class OracleSnapshot: """Normalized state read from ``libvt`` or ``libghostty-vt`` at ground.""" lines: tuple[str, ...] + wraps: tuple[bool, ...] + styles: tuple[tuple[_NormalizedStyle, ...], ...] scrollback_rows: int cursor_row: int cursor_col: int @@ -180,6 +297,33 @@ def _bind_functions(self) -> None: ctypes.POINTER(_GhosttyGridRef), ] lib.ghostty_terminal_grid_ref.restype = ctypes.c_int + lib.ghostty_grid_ref_style.argtypes = [ + ctypes.POINTER(_GhosttyGridRef), + ctypes.POINTER(_GhosttyStyle), + ] + lib.ghostty_grid_ref_style.restype = ctypes.c_int + lib.ghostty_grid_ref_cell.argtypes = [ + ctypes.POINTER(_GhosttyGridRef), + ctypes.POINTER(ctypes.c_uint64), + ] + lib.ghostty_grid_ref_cell.restype = ctypes.c_int + lib.ghostty_grid_ref_row.argtypes = [ + ctypes.POINTER(_GhosttyGridRef), + ctypes.POINTER(ctypes.c_uint64), + ] + lib.ghostty_grid_ref_row.restype = ctypes.c_int + lib.ghostty_cell_get.argtypes = [ + ctypes.c_uint64, + ctypes.c_int, + ctypes.c_void_p, + ] + lib.ghostty_cell_get.restype = ctypes.c_int + lib.ghostty_row_get.argtypes = [ + ctypes.c_uint64, + ctypes.c_int, + ctypes.c_void_p, + ] + lib.ghostty_row_get.restype = ctypes.c_int lib.ghostty_terminal_vt_write.argtypes = [ ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint8), @@ -551,8 +695,115 @@ def snapshot(self) -> OracleSnapshot: padded = tuple( split_lines[r] if r < len(split_lines) else "" for r in range(rows.value) ) + grid_styles: list[tuple[_NormalizedStyle, ...]] = [] + row_wraps: list[bool] = [] + cell_ref = _GhosttyGridRef() + cell_style = _GhosttyStyle() + cell_val = ctypes.c_uint64(0) + row_val = ctypes.c_uint64(0) + wrap_val = ctypes.c_bool(False) + content_tag = ctypes.c_int(0) + bg_palette = ctypes.c_uint8(0) + bg_rgb = _GhosttyColorRgb() + cell_data_tag = lw.enum_val("GhosttyCellData", "CONTENT_TAG", 2) + cell_data_pal = lw.enum_val("GhosttyCellData", "COLOR_PALETTE", 10) + cell_data_rgb = lw.enum_val("GhosttyCellData", "COLOR_RGB", 11) + tag_bg_pal = lw.enum_val("GhosttyCellContentTag", "BG_COLOR_PALETTE", 2) + tag_bg_rgb = lw.enum_val("GhosttyCellContentTag", "BG_COLOR_RGB", 3) + row_data_wrap = lw.enum_val("GhosttyRowData", "WRAP", 1) + default_flags = (False, False, False, 0, False, False, False, False, False) + for r in range(rows.value): + row_styles: list[_NormalizedStyle] = [] + for c in range(cols.value): + pt = _GhosttyPoint( + tag=GHOSTTY_POINT_TAG_ACTIVE, + value=_GhosttyPointValue( + coordinate=_GhosttyPointCoordinate(x=c, y=r), + ), + ) + self._check( + self._lib.ghostty_terminal_grid_ref( + self._handle, + pt, + ctypes.byref(cell_ref), + ), + f"ghostty_terminal_grid_ref({r},{c})", + ) + if c == 0: + self._check( + self._lib.ghostty_grid_ref_row( + ctypes.byref(cell_ref), + ctypes.byref(row_val), + ), + f"ghostty_grid_ref_row({r})", + ) + self._check( + self._lib.ghostty_row_get( + row_val, + row_data_wrap, + ctypes.byref(wrap_val), + ), + f"ghostty_row_get(WRAP, {r})", + ) + row_wraps.append(bool(wrap_val.value)) + self._check( + self._lib.ghostty_grid_ref_cell( + ctypes.byref(cell_ref), + ctypes.byref(cell_val), + ), + f"ghostty_grid_ref_cell({r},{c})", + ) + self._check( + self._lib.ghostty_cell_get( + cell_val, + cell_data_tag, + ctypes.byref(content_tag), + ), + f"ghostty_cell_get(CONTENT_TAG, {r},{c})", + ) + if content_tag.value == tag_bg_pal: + self._check( + self._lib.ghostty_cell_get( + cell_val, + cell_data_pal, + ctypes.byref(bg_palette), + ), + f"ghostty_cell_get(COLOR_PALETTE, {r},{c})", + ) + row_styles.append( + (None, ("palette", int(bg_palette.value)), None, *default_flags) + ) + elif content_tag.value == tag_bg_rgb: + self._check( + self._lib.ghostty_cell_get( + cell_val, + cell_data_rgb, + ctypes.byref(bg_rgb), + ), + f"ghostty_cell_get(COLOR_RGB, {r},{c})", + ) + row_styles.append( + ( + None, + ("rgb", int(bg_rgb.r), int(bg_rgb.g), int(bg_rgb.b)), + None, + *default_flags, + ) + ) + else: + self._check( + self._lib.ghostty_grid_ref_style( + ctypes.byref(cell_ref), + ctypes.byref(cell_style), + ), + f"ghostty_grid_ref_style({r},{c})", + ) + row_styles.append(_normalize_ghostty_style(cell_style)) + grid_styles.append(tuple(row_styles)) return OracleSnapshot( lines=padded, + wraps=tuple(row_wraps), + styles=tuple(grid_styles), scrollback_rows=sb_rows.value, cursor_row=cy.value, cursor_col=cx.value, @@ -564,16 +815,220 @@ def snapshot(self) -> OracleSnapshot: def load_optional_ghostty_vt() -> GhosttyVtLibrary | None: - """Load ``libghostty-vt`` when ``LIBGHOSTTY_VT_PATH`` points to a library.""" + """Load ``libghostty-vt`` when ``LIBGHOSTTY_VT_PATH`` is configured. + + Returns ``None`` when ``LIBGHOSTTY_VT_PATH`` is unset or blank so local + runs without a native toolchain skip optional differential tests. Raises + :exc:`FileNotFoundError` when ``LIBGHOSTTY_VT_PATH`` is set to a missing + path so configured parity jobs cannot silently skip. + """ raw = os.environ.get("LIBGHOSTTY_VT_PATH", "").strip() if not raw: return None path = pathlib.Path(raw) if not path.is_file(): - return None + msg = f"LIBGHOSTTY_VT_PATH does not point to an existing file: {path}" + raise FileNotFoundError(msg) return GhosttyVtLibrary(path) +def _require_int( + raw: dict[str, object], + key: str, + *, + minimum: int, + default: int | None = None, +) -> int: + if key not in raw: + if default is not None: + return default + msg = f"missing required integer field {key!r} in {raw!r}" + raise ValueError(msg) + val = raw[key] + if isinstance(val, bool) or not isinstance(val, int) or val < minimum: + msg = f"field {key!r} must be an int >= {minimum}, got {val!r}" + raise ValueError(msg) + return val + + +def _require_nonempty_str(raw: dict[str, object], key: str) -> str: + val = raw.get(key) + if not isinstance(val, str) or not val.strip(): + msg = f"field {key!r} must be a non-empty string, got {val!r}" + raise ValueError(msg) + return val + + +def _require_bool(raw: dict[str, object], key: str, *, default: bool) -> bool: + if key not in raw: + return default + val = raw[key] + if not isinstance(val, bool): + msg = f"field {key!r} must be a bool, got {val!r}" + raise TypeError(msg) + return val + + +def _parse_step(raw: object) -> TraceStep: + if not isinstance(raw, dict): + msg = f"trace step must be a JSON object, got {raw!r}" + raise TypeError(msg) + kind = raw.get("type") + if kind == "write": + has_hex = "hex" in raw + has_utf8 = "utf8" in raw + if has_hex == has_utf8: + msg = f"write step requires exactly one of 'hex' or 'utf8', got {raw!r}" + raise ValueError(msg) + if has_hex: + hex_str = raw["hex"] + if not isinstance(hex_str, str): + msg = f"write step 'hex' must be a string, got {hex_str!r}" + raise ValueError(msg) + return TraceStep(kind="write", data=bytes.fromhex(hex_str)) + utf8_str = raw["utf8"] + if not isinstance(utf8_str, str): + msg = f"write step 'utf8' must be a string, got {utf8_str!r}" + raise ValueError(msg) + return TraceStep(kind="write", data=utf8_str.encode("utf-8")) + if kind == "resize": + rows = _require_int(raw, "rows", minimum=1) + cols = _require_int(raw, "cols", minimum=1) + return TraceStep(kind="resize", rows=rows, cols=cols) + if kind == "checkpoint": + return TraceStep(kind="checkpoint") + msg = f"unsupported trace step kind: {kind!r}" + raise ValueError(msg) + + +def _resolve_profile(name: object) -> Profile: + if name is None or name == "default": + return DEFAULT_PROFILE + if name == "ghostty": + from libvt.profiles import GHOSTTY_PROFILE + + return GHOSTTY_PROFILE + msg = f"unsupported trace profile: {name!r}" + raise ValueError(msg) + + +def _build_trace(header: dict[str, object], raw_steps: list[object]) -> RecordedTrace: + steps = tuple(_parse_step(item) for item in raw_steps) + if not any(step.kind == "checkpoint" for step in steps): + msg = f"trace {header.get('name')!r} must include at least one checkpoint step" + raise ValueError(msg) + return RecordedTrace( + name=_require_nonempty_str(header, "name"), + rows=_require_int(header, "rows", minimum=1), + cols=_require_int(header, "cols", minimum=1), + scrollback=_require_int(header, "scrollback", minimum=0, default=200), + profile=_resolve_profile(header.get("profile")), + compare_scrollback=_require_bool(header, "compare_scrollback", default=True), + steps=steps, + ) + + +def load_jsonl_trace(path: pathlib.Path) -> RecordedTrace: + """Load one multi-line ``.jsonl`` trace file (header + step lines).""" + records = [ + json.loads(line) + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if ( + not records + or not isinstance(records[0], dict) + or records[0].get("type") != "header" + ): + msg = f"{path}: first JSONL record must be an object with type='header'" + raise ValueError(msg) + return _build_trace(records[0], records[1:]) + + +def load_corpus_jsonl(path: pathlib.Path) -> tuple[RecordedTrace, ...]: + """Load a multi-session ``.jsonl`` file (one session record per line).""" + traces: list[RecordedTrace] = [] + for line in path.read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + rec = json.loads(line) + if not isinstance(rec, dict): + msg = f"{path}: corpus line must be a JSON object, got {rec!r}" + raise TypeError(msg) + raw_steps = rec.get("steps") + if not isinstance(raw_steps, list): + msg = f"{path}: corpus record requires a 'steps' list, got {rec!r}" + raise TypeError(msg) + traces.append(_build_trace(rec, raw_steps)) + return tuple(traces) + + +def assert_ghostty_differential_parity( + library: GhosttyVtLibrary, + trace: RecordedTrace, + *, + chunk_sizes: tuple[int | None, ...] = (None, 1), +) -> None: + """Verify ``libvt`` matches ``libghostty-vt`` across whole and split feeds.""" + for chunk_size in chunk_sizes: + vt = libvt.Terminal( + rows=trace.rows, + cols=trace.cols, + scrollback=trace.scrollback, + profile=trace.profile, + ) + with GhosttyVtSession( + library, + rows=trace.rows, + cols=trace.cols, + scrollback=trace.scrollback, + profile=trace.profile, + ) as gh: + cp_idx = 0 + for step in trace.steps: + if step.kind == "write": + if chunk_size is None or chunk_size <= 0: + vt.feed(step.data) + gh.feed(step.data) + else: + for idx in range(0, len(step.data), chunk_size): + chunk = step.data[idx : idx + chunk_size] + vt.feed(chunk) + gh.feed(chunk) + elif step.kind == "resize": + vt.resize(rows=step.rows, cols=step.cols) + gh.resize(rows=step.rows, cols=step.cols) + elif step.kind == "checkpoint": + ctx = f"{trace.name} chunk_size={chunk_size} cp={cp_idx}" + gh_snap = gh.snapshot() + vt_snap = vt.snapshot() + vt_styles = tuple( + tuple(_normalize_libvt_style(cell.style) for cell in vt_snap[r]) + for r in range(vt_snap.rows) + ) + assert gh_snap.at_ground == vt.at_ground_state, ctx + assert gh_snap.alt_screen == ( + vt.screens.active is vt.screens.alternate + ), ctx + assert gh_snap.lines == vt.lines, ctx + assert gh_snap.wraps == tuple( + vt_snap[r].wrapped for r in range(vt_snap.rows) + ), ctx + assert gh_snap.styles == vt_styles, ctx + if trace.compare_scrollback: + assert gh_snap.scrollback_rows == len( + vt.screens.active.history + ), ctx + assert (gh_snap.cursor_row, gh_snap.cursor_col) == ( + vt.cursor.row, + vt.cursor.col, + ), ctx + assert gh_snap.pending_wrap == vt.cursor.pending_wrap, ctx + assert gh_snap.replies == vt.drain_replies(), ctx + cp_idx += 1 + assert cp_idx > 0, f"{trace.name}: trace executed zero checkpoints" + + def _snapshot_signature(snap: libvt.Snapshot) -> object: """Capture text, soft-wrap flags, SGR styles, hyperlinks, and history.""" return ( @@ -594,9 +1049,11 @@ def _run_libvt_trace( *, rows: int, cols: int, + scrollback: int = 200, + profile: Profile = DEFAULT_PROFILE, chunk_size: int | None, ) -> list[tuple[object, object, tuple[int, int, bool], bytes]]: - term = libvt.Terminal(rows=rows, cols=cols, scrollback=200) + term = libvt.Terminal(rows=rows, cols=cols, scrollback=scrollback, profile=profile) checkpoints: list[tuple[object, object, tuple[int, int, bool], bytes]] = [] replies = bytearray() for step in steps: @@ -632,12 +1089,43 @@ def assert_prefix_determinism( *, rows: int, cols: int, + scrollback: int = 200, + profile: Profile = DEFAULT_PROFILE, ) -> None: """Assert whole-write, 1-byte, and prime-chunk feeds yield identical states.""" - whole = _run_libvt_trace(steps, rows=rows, cols=cols, chunk_size=None) - bytewise = _run_libvt_trace(steps, rows=rows, cols=cols, chunk_size=1) - prime_3 = _run_libvt_trace(steps, rows=rows, cols=cols, chunk_size=3) - prime_7 = _run_libvt_trace(steps, rows=rows, cols=cols, chunk_size=7) + whole = _run_libvt_trace( + steps, + rows=rows, + cols=cols, + scrollback=scrollback, + profile=profile, + chunk_size=None, + ) + bytewise = _run_libvt_trace( + steps, + rows=rows, + cols=cols, + scrollback=scrollback, + profile=profile, + chunk_size=1, + ) + prime_3 = _run_libvt_trace( + steps, + rows=rows, + cols=cols, + scrollback=scrollback, + profile=profile, + chunk_size=3, + ) + prime_7 = _run_libvt_trace( + steps, + rows=rows, + cols=cols, + scrollback=scrollback, + profile=profile, + chunk_size=7, + ) + assert len(whole) > 0, "trace must include at least one checkpoint step" assert bytewise == whole assert prime_3 == whole assert prime_7 == whole diff --git a/tests/fixtures/ghostty_corpus/core_sessions.jsonl b/tests/fixtures/ghostty_corpus/core_sessions.jsonl new file mode 100644 index 00000000..b907ff7b --- /dev/null +++ b/tests/fixtures/ghostty_corpus/core_sessions.jsonl @@ -0,0 +1,30 @@ +{"name":"cjk_right_margin_wrap","rows":3,"cols":5,"steps":[{"type":"write","hex":"61626364e6bca265"},{"type":"checkpoint"},{"type":"write","hex":"e5ad9721"},{"type":"checkpoint"}]} +{"name":"grapheme_zwj_mode_2027","rows":2,"cols":10,"steps":[{"type":"write","hex":"1b5b3f3230323768f09f91a8e2808df09f91a9e2808df09f91a7e2808df09f91a64f4b"},{"type":"checkpoint"},{"type":"write","hex":"0d0af09f91a9f09f8fbde2808df09f92bb21"},{"type":"checkpoint"}]} +{"name":"grapheme_vs16_keycap","rows":2,"cols":10,"steps":[{"type":"write","hex":"1b5b3f323032376831efb88fe283a341e29da4efb88f42"},{"type":"checkpoint"}]} +{"name":"combining_marks_width","rows":2,"cols":10,"steps":[{"type":"write","hex":"65cc8161cc88cc845a"},{"type":"checkpoint"}]} +{"name":"single_col_wrap_ascii","rows":4,"cols":1,"steps":[{"type":"write","hex":"41424344"},{"type":"checkpoint"},{"type":"write","hex":"45"},{"type":"checkpoint"}]} +{"name":"pending_wrap_overwrite_bs","rows":2,"cols":4,"steps":[{"type":"write","hex":"41424344"},{"type":"checkpoint"},{"type":"write","hex":"085a"},{"type":"checkpoint"},{"type":"write","hex":"5859"},{"type":"checkpoint"}]} +{"name":"bce_el_ed_ech_dch_ich","rows":3,"cols":8,"steps":[{"type":"write","hex":"41424344454647480d0a31323334353637381b5b313b33481b5b34326d1b5b32581b5b313b36481b5b32501b5b323b32481b5b324021"},{"type":"checkpoint"},{"type":"write","hex":"1b5b313b33481b5b4b1b5b323b33481b5b4a"},{"type":"checkpoint"}]} +{"name":"decstbm_su_sd_il_dl","rows":5,"cols":8,"steps":[{"type":"write","hex":"4c310d0a4c320d0a4c330d0a4c340d0a4c351b5b323b34721b5b323b31481b5b53"},{"type":"checkpoint"},{"type":"write","hex":"1b5b541b5b333b31481b5b4c4e45571b5b323b31481b5b4d"},{"type":"checkpoint"}]} +{"name":"decslrm_left_right_margins","rows":3,"cols":8,"steps":[{"type":"write","hex":"1b5b3f3639681b5b323b36731b5b313b324831323334353637383930"},{"type":"checkpoint"},{"type":"write","hex":"1b5b313b33481b5b32501b5b313b32481b5b31405a1b5b3f36396c"},{"type":"checkpoint"}]} +{"name":"origin_mode_decom_cup","rows":5,"cols":10,"steps":[{"type":"write","hex":"544f500d0a1b5b323b34721b5b3f36681b5b313b3148494e310d0a494e320d0a494e330d0a494e34"},{"type":"checkpoint"},{"type":"write","hex":"1b5b3f366c1b5b72"},{"type":"checkpoint"}]} +{"name":"tab_stops_hts_tbc_cht_cbt","rows":2,"cols":20,"steps":[{"type":"write","hex":"1b5b33671b5b313b35481b481b5b313b3132481b481b5b313b31484109420943"},{"type":"checkpoint"},{"type":"write","hex":"1b5b5a211b5b313b31481b5b324958"},{"type":"checkpoint"}]} +{"name":"alt_screen_1049_1047_47","rows":3,"cols":10,"steps":[{"type":"write","hex":"4d41494e310d0a4d41494e32"},{"type":"checkpoint"},{"type":"write","hex":"1b5b3f31303439681b5b48414c5431"},{"type":"checkpoint"},{"type":"write","hex":"1b5b3f313034396c"},{"type":"checkpoint"},{"type":"write","hex":"1b5b3f31303437681b5b48414c5431303437"},{"type":"checkpoint"},{"type":"write","hex":"1b5b3f313034376c1b5b323b3648"},{"type":"checkpoint"},{"type":"write","hex":"1b5b3f3437681b5b48414c543437"},{"type":"checkpoint"},{"type":"write","hex":"1b5b3f34376c1b5b323b3648"},{"type":"checkpoint"}]} +{"name":"decsc_decrc_cursor_attr","rows":3,"cols":10,"steps":[{"type":"write","hex":"41421b371b5b323b35481b5b33316d58591b385a"},{"type":"checkpoint"}]} +{"name":"rep_b_repeat_ascii","rows":2,"cols":10,"steps":[{"type":"write","hex":"411b5b3462421b5b3262"},{"type":"checkpoint"}]} +{"name":"hpa_vpa_hpr_vpr_cnl_cpl","rows":4,"cols":10,"steps":[{"type":"write","hex":"1b5b32641b5b3460581b5b3261591b5b31655a1b5b3145571b5b324656"},{"type":"checkpoint"}]} +{"name":"insert_mode_irm_cjk","rows":2,"cols":8,"steps":[{"type":"write","hex":"414243444546"},{"type":"checkpoint"},{"type":"write","hex":"1b5b313b32481b5b3468e6bca21b5b346c"},{"type":"checkpoint"}]} +{"name":"sgr_colors_underline_reset","rows":2,"cols":12,"steps":[{"type":"write","hex":"1b5b313b333b343a333b33383b323b31303b32303b33303b34383b353b3139366d48491b5b306d706c61696e"},{"type":"checkpoint"}]} +{"name":"erase_scrollback_ed3","rows":2,"cols":6,"steps":[{"type":"write","hex":"310d0a320d0a330d0a34"},{"type":"checkpoint"},{"type":"write","hex":"1b5b334a1b5b324a1b5b486f6b"},{"type":"checkpoint"}]} +{"name":"sync_2026_nested_and_reset","rows":2,"cols":10,"steps":[{"type":"write","hex":"411b5b3f3230323668421b5b3f3230323668431b5b3f323032366c44"},{"type":"checkpoint"}]} +{"name":"decstr_soft_reset_modes","rows":3,"cols":10,"steps":[{"type":"write","hex":"1b5b323b33721b5b3f36681b5b3f376c1b5b21701b5b313b31483132333435363738393058"},{"type":"checkpoint"}]} +{"name":"ris_full_reset","rows":3,"cols":10,"steps":[{"type":"write","hex":"44495254591b5b3f3130343968414c541b63434c45414e"},{"type":"checkpoint"}]} +{"name":"dsr_cpr_device_status","rows":3,"cols":12,"steps":[{"type":"write","hex":"1b5b323b35481b5b356e1b5b366e"},{"type":"checkpoint"}]} +{"name":"decrqm_known_modes","rows":2,"cols":10,"steps":[{"type":"write","hex":"1b5b3f3724701b5b3f32303034681b5b3f3230303424701b5b3f323030346c1b5b3f323030342470"},{"type":"checkpoint"}]} +{"name":"wrap_reflow_shrink_grow","rows":4,"cols":10,"steps":[{"type":"write","hex":"303132333435363738396162636465660d0a6e657874"},{"type":"checkpoint"},{"type":"resize","rows":6,"cols":5},{"type":"checkpoint"},{"type":"resize","rows":4,"cols":12},{"type":"checkpoint"}]} +{"name":"scrollback_eviction_order","rows":2,"cols":6,"scrollback":3,"compare_scrollback":false,"steps":[{"type":"write","hex":"72310d0a72320d0a72330d0a72340d0a72350d0a7236"},{"type":"checkpoint"}]} +{"name":"split_utf8_and_csi_controls","rows":2,"cols":12,"steps":[{"type":"write","hex":"1b5b313b324820636166c3a9201b5b33326df09f9a801b5b306d21"},{"type":"checkpoint"}]} +{"name":"written_spaces_vs_erased_cells","rows":3,"cols":8,"steps":[{"type":"write","hex":"4120200d0a422020201b5b323b32481b5b4b"},{"type":"checkpoint"}]} +{"name":"ansi_c0_cr_lf_ff_vt_bs","rows":4,"cols":8,"steps":[{"type":"write","hex":"414208430a440b450c460d47"},{"type":"checkpoint"}]} +{"name":"newline_mode_lnm_20","rows":3,"cols":8,"steps":[{"type":"write","hex":"1b5b32306841420a43440a45461b5b32306c0a4748"},{"type":"checkpoint"}]} +{"name":"ghostty_profile_cbt_and_rep","rows":2,"cols":5,"profile":"ghostty","steps":[{"type":"write","hex":"41424344451b5b5a21"},{"type":"checkpoint"},{"type":"write","hex":"0d0ae6bca21b5b33316d1b5b3162"},{"type":"checkpoint"}]} diff --git a/tests/fixtures/ghostty_corpus/nvim_edit_scroll_exit.jsonl b/tests/fixtures/ghostty_corpus/nvim_edit_scroll_exit.jsonl new file mode 100644 index 00000000..9be8acd4 --- /dev/null +++ b/tests/fixtures/ghostty_corpus/nvim_edit_scroll_exit.jsonl @@ -0,0 +1,7 @@ +{"type":"header","name":"nvim_edit_scroll_exit","rows":5,"cols":20,"scrollback":200} +{"type":"write","hex":"70726f6d707424206e76696d20612e70790d0a686973746f72792d6b6570740d0a"} +{"type":"checkpoint"} +{"type":"write","hex":"1b371b5b3f31303439681b5b313b34721b5b313b31483120646566206d61696e28293a0d0a32202020202072657475726e20300d0a330d0a7e1b5b353b31481b5b376d204e4f524d414c2020612e7079201b5b306d1b5b313b34721b5b313b31481b5b53"} +{"type":"checkpoint"} +{"type":"write","hex":"1b5b721b5b3f313034396c1b38646f6e650d0a"} +{"type":"checkpoint"} diff --git a/tests/fixtures/ghostty_corpus/resize_mid_sync_wide.jsonl b/tests/fixtures/ghostty_corpus/resize_mid_sync_wide.jsonl new file mode 100644 index 00000000..85f03a6b --- /dev/null +++ b/tests/fixtures/ghostty_corpus/resize_mid_sync_wide.jsonl @@ -0,0 +1,9 @@ +{"type":"header","name":"resize_mid_sync_wide","rows":4,"cols":12,"scrollback":200} +{"type":"write","hex":"30313233343536373839e697a5e69cac0d0af09f9a80e29ca8e6bca2e5ad97210d0a"} +{"type":"checkpoint"} +{"type":"write","hex":"1b5b3f32303236681b5b313b31487265647261772d6d6964"} +{"type":"resize","rows":4,"cols":8} +{"type":"write","hex":"e5ae8c1b5b3f323032366c"} +{"type":"checkpoint"} +{"type":"resize","rows":5,"cols":16} +{"type":"checkpoint"} diff --git a/tests/fixtures/ghostty_corpus/tmux_popup_lifecycle.jsonl b/tests/fixtures/ghostty_corpus/tmux_popup_lifecycle.jsonl new file mode 100644 index 00000000..e6cf6f4c --- /dev/null +++ b/tests/fixtures/ghostty_corpus/tmux_popup_lifecycle.jsonl @@ -0,0 +1,7 @@ +{"type":"header","name":"tmux_popup_lifecycle","rows":6,"cols":24,"scrollback":200} +{"type":"write","hex":"1b5b313b31487368656c6c24206c73202d6c610d0a746f74616c2031360d0a64727778722d78722d7820203420646576202073746166660d0a1b5b363b31481b5b376d5b305d20303a7a73682a1b5b306d"} +{"type":"checkpoint"} +{"type":"write","hex":"1b5b3f32303236681b5b323b34481b5b33383b353b33396de2948ce29480706f707570e29480e294901b5b306d1b5b333b3448e29482206f6b21202020e294821b5b343b3448e29494e29480e29480e29480e29480e29480e29480e29480e29480e294981b5b3f323032366c"} +{"type":"checkpoint"} +{"type":"write","hex":"1b5b3f32303236681b5b323b3148746f74616c203136202020202020202020202020202020201b5b333b314864727778722d78722d7820203420646576202073746166661b5b343b31482020202020202020202020202020202020202020202020201b5b343b31481b5b366e1b5b3f323032366c"} +{"type":"checkpoint"} diff --git a/tests/test_codec.py b/tests/test_codec.py index 362cbaec..bcea1c35 100644 --- a/tests/test_codec.py +++ b/tests/test_codec.py @@ -4,6 +4,7 @@ import io import pathlib +import re import sys import pytest @@ -195,3 +196,82 @@ def release(event: Event) -> None: terminal.feed(view) assert seen == [Bell] assert (terminal.lines, terminal.cursor.col) == (("READY",), 5) + + +def test_conformance_doc_covers_codec_and_modes() -> None: + """Fail if ``codec.py`` or ``modes.py`` drifts from ``conformance.md`` tables.""" + repo_root = pathlib.Path(__file__).resolve().parents[1] + doc = (repo_root / "docs" / "project" / "conformance.md").read_text( + encoding="utf-8" + ) + valid_statuses = {"Supported", "Partial", "Ignored", "Divergent"} + + sections: dict[str, list[list[str]]] = {} + current_section: str | None = None + for raw_line in doc.splitlines(): + line = raw_line.strip() + if line.startswith("## "): + current_section = line.removeprefix("## ").strip() + sections[current_section] = [] + continue + if current_section is None or not line.startswith("|"): + continue + cells = [cell.strip() for cell in re.split(r"(?= 3 and cells[2] == "Status") or all( + set(cell) <= {"-", ":"} for cell in cells + ): + continue + assert len(cells) == 4, ( + f"{current_section}: expected 4 table columns, got {len(cells)}: {line!r}" + ) + sections[current_section].append(cells) + + def _extract_keys(section_name: str, key_col: int) -> set[str]: + rows = sections.get(section_name, []) + assert rows, f"missing table rows in section {section_name!r}" + keys: set[str] = set() + for row in rows: + raw_key = row[key_col].strip("`") + status = row[2] + notes = row[3] + assert status in valid_statuses, ( + f"{section_name} {raw_key!r}: invalid status {status!r}" + ) + test_refs = re.findall(r"`(tests/test_[a-zA-Z0-9_]+\.py)`", notes) + assert test_refs, ( + f"{section_name} {raw_key!r}: missing test module citation in notes" + ) + for test_ref in test_refs: + assert (repo_root / test_ref).is_file(), ( + f"{section_name} {raw_key!r}: cited test {test_ref} does not exist" + ) + assert raw_key not in keys, f"{section_name}: duplicate row {raw_key!r}" + keys.add(raw_key) + return keys + + assert _extract_keys("C0 Controls", 0) == { + mnemonic for mnemonic, _desc in _C0_NAMES.values() + } + assert _extract_keys("ESC, DCS, and APC Sequences", 1) == { + "SCS", + "DOCS", + "SIXEL", + "DECRQSS", + "XTGETTCAP", + "KITTY_GFX", + } + assert _extract_keys("CSI Control Functions", 1) == set(_CSI_NAMES.values()) | { + "DECSET", + "DECRST", + "DECRQM", + "XTVERSION", + "DECSCA", + "DECSED", + "DECSEL", + "XTSAVE", + "XTRESTORE", + "XTSMGRAPHICS", + } + assert _extract_keys("OSC Sequences", 1) == set(_OSC_NAMES.values()) + assert _extract_keys("ANSI and DEC Modes", 0) == {mode.name for mode in Mode} diff --git a/tests/test_differential_ghostty.py b/tests/test_differential_ghostty.py index deaad6cf..94483424 100644 --- a/tests/test_differential_ghostty.py +++ b/tests/test_differential_ghostty.py @@ -1,143 +1,182 @@ -"""Tests for ``libghostty-vt`` differential oracle and split-chunk determinism.""" +"""Tests for ``libghostty-vt`` differential corpus and split-chunk determinism.""" from __future__ import annotations +import pathlib + import pytest import libvt +from libvt.config import Profile, ScreenBehavior from tests._ghostty_vt import ( GhosttyVtSession, + RecordedTrace, TraceStep, + assert_ghostty_differential_parity, assert_prefix_determinism, + load_corpus_jsonl, + load_jsonl_trace, load_optional_ghostty_vt, pack_ghostty_mode, ) -CANONICAL_TRACES: dict[str, tuple[int, int, tuple[TraceStep, ...]]] = { - "tmux_popup_lifecycle": ( - 6, - 24, +_CORPUS_DIR = pathlib.Path(__file__).resolve().parent / "fixtures" / "ghostty_corpus" +_PERMANENT_TRACE_NAMES = ( + "tmux_popup_lifecycle", + "nvim_edit_scroll_exit", + "resize_mid_sync_wide", +) + + +def _load_all_corpus_traces() -> tuple[RecordedTrace, ...]: + permanent = tuple( + load_jsonl_trace(_CORPUS_DIR / f"{name}.jsonl") + for name in _PERMANENT_TRACE_NAMES + ) + core = load_corpus_jsonl(_CORPUS_DIR / "core_sessions.jsonl") + return (*permanent, *core) + + +def test_ghostty_mode_packing_and_oracle_loading( + monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path +) -> None: + """Pack modes per ``modes.h`` and fail loud when a configured library is absent.""" + assert pack_ghostty_mode(2027, ansi=False) == 2027 + assert pack_ghostty_mode(2026, ansi=False) == 2026 + assert pack_ghostty_mode(4, ansi=True) == (4 | (1 << 15)) + assert pack_ghostty_mode(20, ansi=True) == (20 | (1 << 15)) + + monkeypatch.delenv("LIBGHOSTTY_VT_PATH", raising=False) + assert load_optional_ghostty_vt() is None + + monkeypatch.setenv("LIBGHOSTTY_VT_PATH", " ") + assert load_optional_ghostty_vt() is None + + missing = tmp_path / "missing-libghostty-vt.so" + monkeypatch.setenv("LIBGHOSTTY_VT_PATH", str(missing)) + with pytest.raises(FileNotFoundError, match="LIBGHOSTTY_VT_PATH"): + load_optional_ghostty_vt() + + +def test_recorded_jsonl_corpus_prefix_determinism() -> None: + """Every recorded ``.jsonl`` corpus trace is chunk-boundary deterministic.""" + traces = _load_all_corpus_traces() + names = [trace.name for trace in traces] + assert len(traces) >= 30 + assert len(names) == len(set(names)) + for required in _PERMANENT_TRACE_NAMES: + assert required in names + + for trace in traces: + assert_prefix_determinism( + trace.steps, + rows=trace.rows, + cols=trace.cols, + scrollback=trace.scrollback, + profile=trace.profile, + ) + + # Verify exact FIFO scrollback eviction on libvt (Ghostty prunes by whole page). + evict = next(t for t in traces if t.name == "scrollback_eviction_order") + term = libvt.Terminal(rows=evict.rows, cols=evict.cols, scrollback=evict.scrollback) + for step in evict.steps: + if step.kind == "write": + term.feed(step.data) + assert tuple(row.text for row in term.snapshot().history) == ("r2", "r3", "r4") + assert term.lines == ("r5", "r6") + + +def test_jsonl_trace_loader_rejects_malformed_records(tmp_path: pathlib.Path) -> None: + """Corpus loaders validate header types, geometry bounds, and checkpoints.""" + bad_cases: tuple[tuple[str, str, type[Exception]], ...] = ( + ("not_dict.jsonl", '["not-a-dict"]\n', ValueError), ( - TraceStep( - kind="write", - data=( - b"\x1b[1;1Hshell$ ls -la\r\n" - b"total 16\r\n" - b"drwxr-xr-x 4 dev staff\r\n" - b"\x1b[6;1H\x1b[7m[0] 0:zsh*\x1b[0m" - ), - ), - TraceStep(kind="checkpoint"), - TraceStep( - kind="write", - data=( - b"\x1b[?2026h" - b"\x1b[2;4H\x1b[38;5;39m\xe2\x94\x8c\xe2\x94\x80popup\xe2\x94\x80\xe2\x94\x90\x1b[0m" - b"\x1b[3;4H\xe2\x94\x82 ok! \xe2\x94\x82" - b"\x1b[4;4H\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x98" - b"\x1b[?2026l" - ), + "no_checkpoint.jsonl", + '{"type":"header","name":"x","rows":2,"cols":4}\n', + ValueError, + ), + ( + "bool_rows.jsonl", + ( + '{"type":"header","name":"x","rows":true,"cols":4}\n' + '{"type":"checkpoint"}\n' ), - TraceStep(kind="checkpoint"), - TraceStep( - kind="write", - data=( - b"\x1b[?2026h" - b"\x1b[2;1Htotal 16 " - b"\x1b[3;1Hdrwxr-xr-x 4 dev staff" - b"\x1b[4;1H " - b"\x1b[4;1H\x1b[6n\x1b[?2026l" - ), + ValueError, + ), + ( + "zero_cols.jsonl", + '{"type":"header","name":"x","rows":2,"cols":0}\n{"type":"checkpoint"}\n', + ValueError, + ), + ( + "neg_scrollback.jsonl", + ( + '{"type":"header","name":"x","rows":2,"cols":4,"scrollback":-1}\n' + '{"type":"checkpoint"}\n' ), - TraceStep(kind="checkpoint"), + ValueError, ), - ), - "nvim_edit_scroll_exit": ( - 5, - 20, ( - TraceStep(kind="write", data=b"prompt$ nvim a.py\r\nhistory-kept\r\n"), - TraceStep(kind="checkpoint"), - TraceStep( - kind="write", - data=( - b"\x1b7\x1b[?1049h\x1b[1;4r" - b"\x1b[1;1H1 def main():\r\n2 return 0\r\n3\r\n~" - b"\x1b[5;1H\x1b[7m NORMAL a.py \x1b[0m" - b"\x1b[1;4r\x1b[1;1H\x1b[S" - ), + "both_hex_utf8.jsonl", + ( + '{"type":"header","name":"x","rows":2,"cols":4}\n' + '{"type":"write","hex":"41","utf8":"A"}\n' + '{"type":"checkpoint"}\n' ), - TraceStep(kind="checkpoint"), - TraceStep( - kind="write", - data=b"\x1b[r\x1b[?1049l\x1b8done\r\n", + ValueError, + ), + ( + "bad_resize.jsonl", + ( + '{"type":"header","name":"x","rows":2,"cols":4}\n' + '{"type":"resize","rows":0,"cols":4}\n' + '{"type":"checkpoint"}\n' ), - TraceStep(kind="checkpoint"), + ValueError, ), - ), - "resize_mid_sync_wide": ( - 4, - 12, ( - TraceStep( - kind="write", - data="0123456789日本\r\n🚀✨漢字!\r\n".encode(), + "empty_name.jsonl", + '{"type":"header","name":" ","rows":2,"cols":4}\n{"type":"checkpoint"}\n', + ValueError, + ), + ( + "bad_compare_scrollback.jsonl", + ( + '{"type":"header","name":"x","rows":2,"cols":4,' + '"compare_scrollback":"yes"}\n{"type":"checkpoint"}\n' ), - TraceStep(kind="checkpoint"), - TraceStep(kind="write", data=b"\x1b[?2026h\x1b[1;1Hredraw-mid"), - TraceStep(kind="resize", rows=4, cols=8), - TraceStep(kind="write", data="完\x1b[?2026l".encode()), - TraceStep(kind="checkpoint"), - TraceStep(kind="resize", rows=5, cols=16), - TraceStep(kind="checkpoint"), + TypeError, ), - ), -} - - -def test_ghostty_mode_packing_and_canonical_prefix_determinism() -> None: - """Mode packing matches ``modes.h`` and canonical traces stay deterministic.""" - assert pack_ghostty_mode(2027, ansi=False) == 2027 - assert pack_ghostty_mode(2026, ansi=False) == 2026 - assert pack_ghostty_mode(4, ansi=True) == (4 | (1 << 15)) - assert pack_ghostty_mode(20, ansi=True) == (20 | (1 << 15)) + ( + "step_not_dict.jsonl", + '{"type":"header","name":"x","rows":2,"cols":4}\n123\n', + TypeError, + ), + ) + for filename, payload, exc_type in bad_cases: + p = tmp_path / filename + p.write_text(payload, encoding="utf-8") + with pytest.raises(exc_type, match=r".+"): + load_jsonl_trace(p) - for name, (rows, cols, steps) in CANONICAL_TRACES.items(): - assert_prefix_determinism(steps, rows=rows, cols=cols) - assert name != "" + corpus_bad = tmp_path / "bad_corpus.jsonl" + corpus_bad.write_text('{"name":"x","rows":2,"cols":4,"steps":[]}\n') + with pytest.raises(ValueError, match="checkpoint"): + load_corpus_jsonl(corpus_bad) + corpus_bad.write_text('["not-a-dict"]\n') + with pytest.raises(TypeError, match="JSON object"): + load_corpus_jsonl(corpus_bad) @pytest.mark.ghostty -def test_differential_parity_against_libghostty_vt() -> None: - """Compare ``libvt`` ``DEFAULT_PROFILE`` against compiled ``libghostty-vt`` 1.0.""" +def test_differential_corpus_against_libghostty_vt() -> None: + """Compare ``libvt`` against compiled ``libghostty-vt`` whole and 1-byte split.""" library = load_optional_ghostty_vt() if library is None: pytest.skip("LIBGHOSTTY_VT_PATH is not set to a compiled libghostty-vt binary") - for rows, cols, steps in CANONICAL_TRACES.values(): - vt = libvt.Terminal(rows=rows, cols=cols, scrollback=200) - with GhosttyVtSession(library, rows=rows, cols=cols, scrollback=200) as gh: - for step in steps: - if step.kind == "write": - vt.feed(step.data) - gh.feed(step.data) - elif step.kind == "resize": - vt.resize(rows=step.rows, cols=step.cols) - gh.resize(rows=step.rows, cols=step.cols) - elif step.kind == "checkpoint": - gh_snap = gh.snapshot() - vt_lines = vt.lines - assert gh_snap.at_ground == vt.at_ground_state - assert gh_snap.alt_screen == ( - vt.screens.active is vt.screens.alternate - ) - assert gh_snap.lines == vt_lines - assert (gh_snap.cursor_row, gh_snap.cursor_col) == ( - vt.cursor.row, - vt.cursor.col, - ) - assert gh_snap.pending_wrap == vt.cursor.pending_wrap - assert gh_snap.replies == vt.drain_replies() + for trace in _load_all_corpus_traces(): + assert_ghostty_differential_parity(library, trace, chunk_sizes=(None, 1)) @pytest.mark.ghostty @@ -157,3 +196,33 @@ def test_ghostty_keeps_written_spaces_separate_from_unused_cells() -> None: 1, False, ) + + +@pytest.mark.ghostty +def test_ghostty_alt_screen_cursor_preservation_matches_profile_option() -> None: + """Profile ``alternate_entry_preserves_cursor`` matches Ghostty ``?1049h``.""" + library = load_optional_ghostty_vt() + if library is None: + pytest.skip("LIBGHOSTTY_VT_PATH is not set") + + trace = RecordedTrace( + name="alt_screen_preserve_cursor", + rows=3, + cols=10, + profile=Profile(screen=ScreenBehavior(alternate_entry_preserves_cursor=True)), + steps=( + TraceStep(kind="write", data=b"MAIN1\r\nMAIN2"), + TraceStep(kind="checkpoint"), + TraceStep(kind="write", data=b"\x1b[?1049hALT1"), + TraceStep(kind="checkpoint"), + TraceStep(kind="write", data=b"\x1b[?1049l"), + TraceStep(kind="checkpoint"), + ), + ) + assert_ghostty_differential_parity(library, trace, chunk_sizes=(None, 1)) + + # DEFAULT_PROFILE intentionally homes the alternate screen cursor on ?1049h. + default_vt = libvt.Terminal(rows=3, cols=10) + default_vt.feed(b"MAIN1\r\nMAIN2\x1b[?1049hALT1") + assert default_vt.lines == ("ALT1", "", "") + assert (default_vt.cursor.row, default_vt.cursor.col) == (0, 4)