diff --git a/docs/topics/testing.md b/docs/topics/testing.md index 7d96c248..c7a86ed4 100644 --- a/docs/topics/testing.md +++ b/docs/topics/testing.md @@ -179,6 +179,143 @@ styles: [' r0[0..10]: fg=green'] -> [' r0[0..10]: fg=red'] --- +## Direct FIRE tests + +Run the Fidelity, Isolation, Recovery, and Evidence (FIRE) cases from a +libvt checkout. Pytest lists the name and delivery schedule of each case with +`--collect-only -q`. + +```console +$ uv run pytest tests/test_fire.py +``` + +Each attempt uses a fresh in-memory `Terminal`. Cases feed application bytes, +encode semantic input with `Terminal.encode()`, or change geometry with +`Terminal.resize()`. Cases with feed bytes run in whole-action and one-byte +delivery schedules and observe state at the same action boundaries. +Encoding and resize calls remain indivisible. These runs require Python and +pytest. They use UTF-8 and `DEFAULT_PROFILE`, with per-case settings recorded +in the report. The profile gives the East Asian Ambiguous character `è` +(U+00E8) one cell. +[Unicode East Asian Width][fire-width] + +The suite has 210 distinct behavior vectors. Of these, 201 run under both feed +schedules and nine semantic-input cases run once. Two fault controls run under +both feed schedules, for 415 collected attempts in all. + +| Family | Vectors | Observations | +| --- | ---: | --- | +| Parsing and Unicode | 23 | Incomplete and malformed UTF-8, CSI cancellation and restart, OSC/DCS/APC boundaries, DEC graphics, combining and wide cells. [ECMA-48][fire-ecma48], [DEC parser][fire-ansi-parser], [UTF-8 decoder][fire-utf8], [Unicode segmentation][fire-graphemes] | +| Cursor and margins | 29 | Absolute and relative movement, tabs, both margin axes, saved cursor and deferred wrap. [ECMA-48][fire-ecma48], [xterm 413][fire-xterm-source] | +| Grid edits and scrolling | 26 | Partial erases, insertion and deletion, protected cells, region scrolling, history and wide-cell repair. [ECMA-48][fire-ecma48], [xterm 413][fire-xterm-source] | +| Rendition | 21 | Cell attributes, selective resets, indexed and RGB colors, underlines, hyperlinks and background erasure. [ECMA-48][fire-ecma48], [ITU T.416][fire-t416], [styled underlines][fire-underlines] | +| Replies | 15 | Exact ordered DA, DSR, CPR, DECRQM, DECRQSS, color and geometry responses, with drain checkpoints. [ECMA-48][fire-ecma48], [xterm 413][fire-xterm-source], [color scheme replies][fire-color-scheme] | +| Buffer isolation | 7 | Alternate-mode reconciliation, primary cursor and pen restoration, viewport and history separation, reset. [xterm 413][fire-xterm-source], [libvt mode reconciliation](../project/adr/0006-charset-designations-and-single-truth-mode-reconciliation.md) | +| Synchronized publication | 8 | Working versus committed rows, cursor, history, title and appearance across holds and releases. [Synchronized output][fire-sync] | +| Snapshots and replica recovery | 19 | Immutable saved views, applying dirty rows, following working and committed tokens through successive edits, history eviction and full resync. [Snapshots and scrollback](snapshots.md) | +| Semantic input | 41 | Legacy keys, mode and flag negotiation, per-screen keyboard stacks, exact mouse and focus reports, paste framing and fail-closed paste policy. [xterm 413][fire-xterm-source], [keyboard protocol notes][fire-keyboard], [Ghostty 1.4.0 key codes][fire-key-codes], [libvt input contract](../project/adr/0008-mode-aware-input-encoding-and-paste-safety.md) | +| Resize and geometry | 21 | Hard breaks, soft wraps across scrollback and viewport, cursor and style remapping, alternate-screen cropping, held geometry, replica resync and exact size reports after resize. [libvt resize contract](../project/adr/0004-zero-based-row-col-coordinates-and-sync-stepping.md), [xterm 413][fire-xterm-source], [in-band resize][fire-in-band-resize] | + +CUP places the cursor at wire position (2, 4). CUD moves it two rows down. +Subtract one from each wire coordinate to get libvt's zero-based position. +[ECMA-48, fifth edition, §§8.3.19 and 8.3.21][fire-ecma48] + +```python +>>> from libvt import Terminal +>>> terminal = Terminal(rows=6, cols=9) +>>> terminal.feed(b"\x1b[2;4H") +>>> terminal.feed(b"\x1b[2B") +>>> terminal.cursor.row, terminal.cursor.col +(3, 3) +``` + +The publication case erases `base` and prints `è` during a synchronized +update. The working row changes immediately. The committed row changes on +release. A cursor query returns `1b5b313b3252` once (row 1, column 2 in +wire coordinates). A second terminal sees an empty reply queue while that +reply is pending. The saved snapshot and the second terminal retain their +original rows. [Synchronized output][fire-sync] +[ECMA-48, §§8.3.14, 8.3.15, 8.3.35 and 8.3.41][fire-ecma48] + +The recovery case rebuilds a replica when a token belongs to another terminal. +It then leaves the replica on the alternate screen while the terminal returns +to the primary screen. A full resync replaces the alternate rows, and the new +token identifies the starting point for the next incremental update. +[XTerm alternate-screen mode][fire-xterm] +{meth}`~libvt.terminal.Terminal.changes_since` + +Changing the CUD count to one reports only `cursor_after_move`. Omitting the +release reports only `committed_after_release`. Pytest prints expected and +observed values under the failing case and feed schedule. + +The following implementation faults were each injected in an isolated +checkout. Both delivery schedules failed at the named check for each fault. + +| Fault | Case and failing check | +| --- | --- | +| Substitute `?` for an incomplete UTF-8 replacement character | `parser-invalid-utf8-reprocesses-escape`, `exercise.rows` | +| Make CNL keep its old column | `cursor-cnl-selects-next-left`, `exercise.cursor` | +| Make DCH delete one cell regardless of its count | `grid-dch-shifts-tail-left`, `exercise.rows` | +| Leave bold active after SGR 22 | `rendition-normal-intensity-keeps-italic`, `exercise.cell[0,1].bold` | +| Drop the primary DA reply | `reply-da-primary-and-secondary-identity`, `exercise.replies` | +| Leave alternate rows intact on `?1047l` | `buffer-1047-exit-clears-alternate`, `return-primary.alternate_buffer_rows` | +| Ignore synchronized-output release | `publication-holds-title-while-working-metadata-changes`, `release-title.committed_title` | +| Skip copying changed rows into the replica | `delta-one-dirty-row-with-restored-cursor`, `after.rows` | +| Return the previous token after a working edit or a committed publication | `test_fire_incremental_token_tracks_each_view`, `working_read_again` or `published_read_again` | +| Skip copying a repainted row when the word stays the same | `test_fire_incremental_token_tracks_each_view`, `repainted_replica_ink` | +| Leave an empty hyperlink on the cell after closing OSC 8 | `rendition-osc8-sgr-reset-keeps-link-until-osc8-close`, `exercise.cell[0,2].has_hyperlink` | +| Send the normal cursor-key sequence while application mode is active | `input-cursor-mode-set-and-reset`, `application.encoded_input` | +| Replace active keyboard flags when the update requests bitwise OR | `input-kitty-bitwise-update-and-clear`, `or-kept-escape.encoded_input` | +| Permit BEL in pasted text | `input-paste-rejects-bell-while-bracketed`, `encode.encoded_input` | +| Disable reflow during resize | `resize-widen-joins-soft-wrapped-rows`, `after.rows` | +| Leave the pre-resize token valid after width changes | `resize-widen-joins-soft-wrapped-rows`, `replica.full_resync` and `replica.reason` | +| Drop the in-band size report on resize | `resize-queues-enabled-in-band-geometry`, `after.replies` | + +Each case writes `fire.json` to its pytest temporary directory, including +successful runs and the two fault controls. The file records the profile, +partition, terminal dimensions, bytes passed to each feed call, +and expected and actual values for each evaluated check. `operations` +records input-event arguments and explicit geometry changes. Its +`after_feeds` count records how many feed calls preceded each operation. +The `main` and `peer` feed targets name terminal instances. A feed to +`main` reaches its active buffer. +Pytest clears an existing base directory before the run. Choose a fresh +directory name each time to keep earlier reports. + +```console +$ uv run pytest \ + --basetemp fire-evidence-01 \ + tests/test_fire.py +$ rg --files --hidden --no-ignore \ + --glob fire.json \ + fire-evidence-01 +``` + +Pass the quoted `pytest_node` value to pytest to replay one case and +partition from the same checkout. + +```console +$ uv run pytest \ + 'tests/test_fire.py::test_fire_working_and_committed_frames[one-byte]' +``` + +[fire-color-scheme]: https://github.com/contour-terminal/contour/blob/d5541aa85daa1b5df77e90eb91f159cc91f12a61/docs/vt-extensions/color-palette-update-notifications.md +[fire-ansi-parser]: https://vt100.net/emu/dec_ansi_parser +[fire-ecma48]: https://ecma-international.org/wp-content/uploads/ECMA-48_5th_edition_june_1991.pdf +[fire-graphemes]: https://www.unicode.org/reports/tr29/tr29-47.html +[fire-in-band-resize]: https://github.com/toppk/revenant/blob/3188a7034222fead92501d6103e5260eff4491c8/tdn/docs/csi/window-ops.md#size-reports +[fire-key-codes]: https://github.com/ghostty-org/ghostty/blob/83fb95624b0439ee660c2679b43b38c8b63769cd/src/input/kitty.zig#L91-L108 +[fire-keyboard]: https://github.com/toppk/revenant/blob/3188a7034222fead92501d6103e5260eff4491c8/tdn/docs/input/kitty-keyboard.md +[fire-sync]: https://github.com/contour-terminal/contour/blob/d5541aa85daa1b5df77e90eb91f159cc91f12a61/docs/vt-extensions/synchronized-output.md +[fire-t416]: https://www.itu.int/rec/T-REC-T.416-199303-I/en +[fire-underlines]: https://github.com/wezterm/wezterm/blob/20240203-110809-5046fc22/docs/escape-sequences.md#graphic-rendition-sgr +[fire-utf8]: https://github.com/whatwg/encoding/blob/7d2e3e08e11f57ba1b080390b490d53648c6f69c/encoding.bs +[fire-width]: https://www.unicode.org/reports/tr11/tr11-44.html +[fire-xterm]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-The-Alternate-Screen-Buffer +[fire-xterm-source]: https://github.com/ThomasDickey/xterm-snapshots/blob/517713af0e45745f7405d8d3154e00fcc625c6b2/ctlseqs.ms + +--- + ## Pytest plugin (`libvt.pytest_plugin`) Install `libvt[pytest]` when running under diff --git a/tests/fire_interaction_vectors.py b/tests/fire_interaction_vectors.py new file mode 100644 index 00000000..c6db6240 --- /dev/null +++ b/tests/fire_interaction_vectors.py @@ -0,0 +1,637 @@ +"""Authored FIRE vectors for semantic input and native resize.""" + +from __future__ import annotations + +import typing as t + +from libvt.input import ( + FocusEvent, + InputEvent, + KeyAction, + KeyEvent, + KeyMod, + MouseAction, + MouseButton, + MouseEvent, + PasteEvent, +) +from tests.fire_vectors import CellCheck, Value, cell + + +class InputStep(t.NamedTuple): + """An input event under the modes established by preceding feed bytes.""" + + name: str + event: InputEvent + expected: bytes | t.Literal["UnsafePasteError"] + setup: bytes = b"" + + +class InputCase(t.NamedTuple): + """An independent application-facing encoding contract.""" + + name: str + steps: tuple[InputStep, ...] + keyboard_stack: int = 8 + + +def input_case( + name: str, + event: InputEvent, + expected: bytes | t.Literal["UnsafePasteError"], + setup: bytes = b"", +) -> InputCase: + """Declare one input event and its expected application bytes.""" + return InputCase(name, (InputStep("encode", event, expected, setup),)) + + +# xterm 413 ctlseqs: PC-style function keys, DECCKM, DECNKM, DECBKM, +# modifyOtherKeys, focus, bracketed paste, and mouse tracking. +# TDN's keyboard protocol documentation and Ghostty 1.4.0: event types, +# alternate keys, associated text, functional key codes, and stack operations. +# Paste policy and pixel coordinates: libvt ADR 0008 and ScreenBehavior. +INPUT_CASES = ( + InputCase( + "input-cursor-mode-set-and-reset", + ( + InputStep("normal", KeyEvent("right"), b"\x1b[C"), + InputStep("application", KeyEvent("right"), b"\x1bOC", b"\x1b[?1h"), + InputStep("restored", KeyEvent("right"), b"\x1b[C", b"\x1b[?1l"), + ), + ), + input_case( + "input-modifiers-keep-cursor-key-in-csi", + KeyEvent("left", KeyMod.SHIFT | KeyMod.CTRL), + b"\x1b[1;6D", + b"\x1b[?1h", + ), + input_case( + "input-end-in-application-cursor-mode", KeyEvent("end"), b"\x1bOF", b"\x1b[?1h" + ), + input_case("input-f2-alt-uses-csi", KeyEvent("f2", KeyMod.ALT), b"\x1b[1;3Q"), + input_case("input-page-up-uses-tilde", KeyEvent("page_up"), b"\x1b[5~"), + InputCase( + "input-keypad-mode-set-and-reset", + ( + InputStep("numeric", KeyEvent("kp_4"), b"4"), + InputStep("application", KeyEvent("kp_4"), b"\x1bOt", b"\x1b[?66h"), + InputStep("restored", KeyEvent("kp_4"), b"4", b"\x1b[?66l"), + ), + ), + InputCase( + "input-escape-keypad-selectors-alias-mode", + ( + InputStep("deckpam", KeyEvent("kp_enter"), b"\x1bOM", b"\x1b="), + InputStep("reset-via-mode", KeyEvent("kp_enter"), b"\r", b"\x1b[?66l"), + InputStep("enable-via-mode", KeyEvent("kp_enter"), b"\x1bOM", b"\x1b[?66h"), + InputStep("deckpnm", KeyEvent("kp_enter"), b"\r", b"\x1b>"), + ), + ), + InputCase( + "input-backarrow-switches-del-and-bs", + ( + InputStep("default", KeyEvent("backspace"), b"\x7f"), + InputStep("bs", KeyEvent("backspace"), b"\x08", b"\x1b[?67h"), + InputStep("control-bs", KeyEvent("backspace", KeyMod.CTRL), b"\x7f"), + ), + ), + input_case("input-shift-tab-backtab", KeyEvent("tab", KeyMod.SHIFT), b"\x1b[Z"), + InputCase( + "input-auto-repeat-gates-repeat-only", + ( + InputStep( + "repeat-disabled", + KeyEvent("d", action=KeyAction.REPEAT), + b"", + b"\x1b[?8l", + ), + InputStep("press-enabled", KeyEvent("d"), b"d"), + InputStep( + "repeat-enabled", + KeyEvent("d", action=KeyAction.REPEAT), + b"d", + b"\x1b[?8h", + ), + ), + ), + input_case( + "input-legacy-key-release-suppressed", + KeyEvent("q", action=KeyAction.RELEASE), + b"", + ), + input_case( + "input-alt-control-keeps-escape-and-c0", + KeyEvent("g", KeyMod.ALT | KeyMod.CTRL), + b"\x1b\x07", + ), + input_case("input-alt-char-keeps-utf8", KeyEvent("è", KeyMod.ALT), b"\x1b\xc3\xa8"), + InputCase( + "input-modify-other-keys-level-one-preserves-control", + ( + InputStep( + "legacy-control", KeyEvent("x", KeyMod.CTRL), b"\x18", b"\x1b[>4;1m" + ), + InputStep("modified-space", KeyEvent(" ", KeyMod.SHIFT), b"\x1b[27;2;32~"), + ), + ), + InputCase( + "input-modify-other-keys-level-two-encodes-control", + ( + InputStep( + "extended", KeyEvent("x", KeyMod.CTRL), b"\x1b[27;5;120~", b"\x1b[>4;2m" + ), + InputStep("reset", KeyEvent("x", KeyMod.CTRL), b"\x18", b"\x1b[>4;0m"), + ), + ), + InputCase( + "input-kitty-disambiguates-escape-and-keeps-text", + ( + InputStep("escape", KeyEvent("escape"), b"\x1b[27u", b"\x1b[>1u"), + InputStep("text", KeyEvent("q"), b"q"), + ), + ), + input_case( + "input-kitty-report-all-plain-letter", KeyEvent("q"), b"\x1b[113u", b"\x1b[>8u" + ), + InputCase( + "input-kitty-key-lifecycle-suffixes", + ( + InputStep("press", KeyEvent("j", KeyMod.CTRL), b"\x1b[106;5u", b"\x1b[>3u"), + InputStep( + "repeat", KeyEvent("j", KeyMod.CTRL, KeyAction.REPEAT), b"\x1b[106;5:2u" + ), + InputStep( + "release", + KeyEvent("j", KeyMod.CTRL, KeyAction.RELEASE), + b"\x1b[106;5:3u", + ), + ), + ), + input_case( + "input-kitty-alternate-and-base-layout-key", + KeyEvent("é", KeyMod.SHIFT, shifted_key="É", base_key="2"), + b"\x1b[233:201:50;2u", + b"\x1b[>12u", + ), + input_case( + "input-kitty-base-layout-without-shifted-key", + KeyEvent("é", base_key="2"), + b"\x1b[233::50u", + b"\x1b[>12u", + ), + InputCase( + "input-kitty-associated-text-omitted-on-release", + ( + InputStep( + "press", KeyEvent("a", text="åλ"), b"\x1b[97;;229:955u", b"\x1b[>26u" + ), + InputStep( + "release", + KeyEvent("a", action=KeyAction.RELEASE, text="åλ"), + b"\x1b[97;1:3u", + ), + ), + ), + input_case( + "input-kitty-keypad-has-distinct-code", + KeyEvent("kp_0"), + b"\x1b[57399u", + b"\x1b[>1u", + ), + InputCase( + "input-kitty-takes-precedence-over-modify-other-keys", + ( + InputStep( + "kitty", + KeyEvent("x", KeyMod.CTRL), + b"\x1b[120;5u", + b"\x1b[>4;2m\x1b[>1u", + ), + InputStep( + "xterm", KeyEvent("x", KeyMod.CTRL), b"\x1b[27;5;120~", b"\x1b[2u\x1b[>1u\x1b[>8u" + ), + InputStep("previous", KeyEvent("escape"), b"\x1b[27u", b"\x1b[1u"), + InputStep("alternate-start", KeyEvent("escape"), b"\x1b", b"\x1b[?1049h"), + InputStep("alternate-own-flags", KeyEvent("q"), b"\x1b[113u", b"\x1b[>8u"), + InputStep( + "return-primary", KeyEvent("escape"), b"\x1b[27u", b"\x1b[?1049l" + ), + InputStep("primary-text", KeyEvent("q"), b"q"), + ), + ), + InputCase( + "input-kitty-bitwise-update-and-clear", + ( + InputStep( + "or", + KeyEvent("j", action=KeyAction.RELEASE), + b"\x1b[106;1:3u", + b"\x1b[=1;1u\x1b[=2;2u", + ), + InputStep("or-kept-escape", KeyEvent("escape"), b"\x1b[27u"), + InputStep("cleared-escape", KeyEvent("escape"), b"\x1b", b"\x1b[=1;3u"), + InputStep( + "kept-events", KeyEvent("j", action=KeyAction.RELEASE), b"\x1b[106;1:3u" + ), + ), + ), + InputCase( + "input-focus-negotiation", + ( + InputStep("disabled", FocusEvent(True), b""), + InputStep("focus-gain", FocusEvent(True), b"\x1b[I", b"\x1b[?1004h"), + InputStep("focus-loss", FocusEvent(False), b"\x1b[O"), + InputStep("reset", FocusEvent(False), b"", b"\x1b[?1004l"), + ), + ), + InputCase( + "input-paste-bracketing-negotiation", + ( + InputStep( + "bracketed", + PasteEvent("a\r\nb"), + b"\x1b[200~a\r\nb\x1b[201~", + b"\x1b[?2004h", + ), + InputStep( + "after-reset", PasteEvent("a\r\nb"), "UnsafePasteError", b"\x1b[?2004l" + ), + ), + ), + input_case("input-paste-retains-tabs-and-utf8", PasteEvent("a\tλ"), b"a\t\xce\xbb"), + input_case( + "input-paste-sanitize-keeps-explicitly-allowed-newlines", + PasteEvent("a\x00\r\nb\x7f", sanitize=True, allow_unbracketed_newlines=True), + b"a\r\nb", + ), + input_case( + "input-paste-rejects-bell-while-bracketed", + PasteEvent("a\x07b"), + "UnsafePasteError", + b"\x1b[?2004h", + ), + input_case( + "input-paste-sanitize-keeps-wrappers-and-tabs", + PasteEvent("a\x00\x7f\tλ", sanitize=True), + b"\x1b[200~a\t\xce\xbb\x1b[201~", + b"\x1b[?2004h", + ), + input_case( + "input-paste-sanitize-strips-unbracketed-newline", + PasteEvent("a\nb\r", sanitize=True), + b"ab", + ), + InputCase( + "input-mouse-x10-only-reports-press", + ( + InputStep( + "press", + MouseEvent(MouseButton.LEFT, MouseAction.PRESS, 1, 3), + b'\x1b[M $"', + b"\x1b[?9h", + ), + InputStep( + "release", MouseEvent(MouseButton.LEFT, MouseAction.RELEASE, 1, 3), b"" + ), + ), + ), + input_case( + "input-mouse-vt200-release-and-coordinate-cap", + MouseEvent(MouseButton.LEFT, MouseAction.RELEASE, 2, 250), + b"\x1b[M#\xff#", + b"\x1b[?1000h", + ), + InputCase( + "input-mouse-sgr-preserves-button-on-release", + ( + InputStep( + "press", + MouseEvent( + MouseButton.RIGHT, + MouseAction.PRESS, + 2, + 4, + KeyMod.SHIFT | KeyMod.CTRL, + ), + b"\x1b[<22;5;3M", + b"\x1b[?1000h\x1b[?1006h", + ), + InputStep( + "release", + MouseEvent(MouseButton.RIGHT, MouseAction.RELEASE, 2, 4), + b"\x1b[<2;5;3m", + ), + ), + ), + InputCase( + "input-mouse-button-tracking-distinguishes-drag-from-hover", + ( + InputStep( + "drag", + MouseEvent(MouseButton.MIDDLE, MouseAction.MOVE, 1, 3), + b"\x1b[<33;4;2M", + b"\x1b[?1002h\x1b[?1006h", + ), + InputStep( + "hover", MouseEvent(MouseButton.NONE, MouseAction.MOVE, 1, 3), b"" + ), + ), + ), + input_case( + "input-mouse-any-event-reports-hover", + MouseEvent(MouseButton.NONE, MouseAction.MOVE, 1, 3), + b"\x1b[<35;4;2M", + b"\x1b[?1003h\x1b[?1006h", + ), + InputCase( + "input-mouse-pixel-centers-and-explicit-coordinates", + ( + InputStep( + "cell-center", + MouseEvent(MouseButton.LEFT, MouseAction.PRESS, 1, 3), + b"\x1b[<0;28;24M", + b"\x1b[?1000h\x1b[?1016h", + ), + InputStep( + "explicit-pixel", + MouseEvent( + MouseButton.LEFT, MouseAction.RELEASE, 1, 3, pixel_x=71, pixel_y=42 + ), + b"\x1b[<0;71;42m", + ), + ), + ), + InputCase( + "input-mouse-wheel-alternate-scroll-follows-cursor-mode", + ( + InputStep( + "primary", + MouseEvent(MouseButton.WHEEL_UP, MouseAction.PRESS, 0, 0), + b"", + b"\x1b[?1007h", + ), + InputStep( + "alternate-cursor", + MouseEvent(MouseButton.WHEEL_UP, MouseAction.PRESS, 0, 0), + b"\x1bOA", + b"\x1b[?1049h\x1b[?1h", + ), + InputStep( + "normal-cursor", + MouseEvent(MouseButton.WHEEL_DOWN, MouseAction.PRESS, 0, 0), + b"\x1b[B", + b"\x1b[?1l", + ), + ), + ), + input_case( + "input-mouse-tracking-takes-precedence-over-alternate-scroll", + MouseEvent(MouseButton.WHEEL_DOWN, MouseAction.PRESS, 1, 2), + b"\x1b[<65;3;2M", + b"\x1b[?1049h\x1b[?1007h\x1b[?1000h\x1b[?1006h", + ), +) + + +class ResizeCase(t.NamedTuple): + """Before and after projections for one explicit native resize.""" + + name: str + setup: bytes + size: tuple[int, int] + size_after: tuple[int, int] + before: dict[str, Value] + after: dict[str, Value] + reflow: bool | None = None + finish: bytes = b"" + final: dict[str, Value] | None = None + cells: tuple[CellCheck, ...] = () + scrollback: int = 4 + profile_reflow: bool = True + replica_after: dict[str, Value] | None = None + + +# libvt ADR 0004 defines primary reflow, alternate clipping and cursor +# mapping. Xterm ctlseqs defines text-area and cell-size reports. +# TDN's window operations documents in-band resize order (rows, cols, height, +# width). DEFAULT_PROFILE supplies 8 px by 16 px cells. +RESIZE_CASES = ( + ResizeCase( + "resize-widen-joins-soft-wrapped-rows", + b"canopy", + (2, 4), + (2, 8), + before={"rows": ("cano", "py"), "wrapped": (0,)}, + after={"rows": ("canopy", "")}, + replica_after={ + "before_rows": ("cano", "py"), + "before_widths": (4, 4), + "full_resync": True, + "reason": "epoch_changed", + "rows": ("canopy", ""), + "widths": (8, 8), + }, + ), + ResizeCase( + "resize-widen-preserves-hard-break", + b"cane\r\npy", + (2, 4), + (2, 8), + before={"rows": ("cane", "py"), "wrapped": ()}, + after={"rows": ("cane", "py"), "wrapped": (), "cursor": (1, 2)}, + ), + ResizeCase( + "resize-narrow-wraps-text-and-maps-caret", + b"cedar", + (3, 8), + (3, 3), + before={"rows": ("cedar", "", ""), "cursor": (0, 5)}, + after={"rows": ("ced", "ar", ""), "cursor": (1, 2), "wrapped": (0,)}, + ), + ResizeCase( + "resize-explicitly-disable-reflow-crops-right", + b"cedar", + (3, 8), + (3, 3), + before={"rows": ("cedar", "", "")}, + after={"rows": ("ced", "", ""), "cursor": (0, 2)}, + reflow=False, + ), + ResizeCase( + "resize-profile-in-place-widen-preserves-physical-rows", + b"canopy", + (2, 4), + (2, 8), + before={"rows": ("cano", "py")}, + after={"rows": ("cano", "py"), "cursor": (1, 2)}, + profile_reflow=False, + ), + ResizeCase( + "resize-explicit-reflow-overrides-profile", + b"orchid", + (2, 4), + (2, 8), + before={"rows": ("orch", "id")}, + after={"rows": ("orchid", ""), "cursor": (0, 6)}, + reflow=True, + profile_reflow=False, + ), + ResizeCase( + "resize-grow-height-without-history-appends-blank-rows", + b"arch\r\nbay", + (2, 8), + (4, 8), + before={"rows": ("arch", "bay"), "history": ()}, + after={"rows": ("arch", "bay", "", ""), "cursor": (1, 3), "history": ()}, + ), + ResizeCase( + "resize-shrink-height-at-bottom-moves-top-to-history", + b"arch\r\nbay\r\ncove\r\ndune", + (4, 8), + (2, 8), + before={"rows": ("arch", "bay", "cove", "dune"), "history": ()}, + after={"rows": ("cove", "dune"), "cursor": (1, 4), "history": ("arch", "bay")}, + ), + ResizeCase( + "resize-reflow-restores-newest-hard-line-from-history", + b"arch\r\nbay\r\ncove\r\ndune", + (2, 8), + (3, 9), + before={"rows": ("cove", "dune"), "history": ("arch", "bay")}, + after={"rows": ("bay", "cove", "dune"), "cursor": (2, 4), "history": ("arch",)}, + ), + ResizeCase( + "resize-cut-wide-pair-clears-orphan", + "ab界".encode(), + (2, 6), + (2, 3), + before={"rows": ("ab界", "")}, + after={"rows": ("ab", "")}, + reflow=False, + cells=(cell(0, 2, text=" ", width=1),), + ), + ResizeCase( + "resize-reflow-discards-wide-wrap-padding", + "abc界Q".encode(), + (2, 4), + (2, 8), + before={"rows": ("abc", "界Q"), "wrapped": (0,)}, + after={"rows": ("abc界Q", ""), "cursor": (0, 6), "wrapped": ()}, + cells=( + cell(0, 3, text="界", width=2), + cell(0, 4, width=0), + cell(0, 5, text="Q"), + ), + ), + ResizeCase( + "resize-reflow-remaps-cursor-on-continuation", + b"canopy\x1b[2;1H", + (2, 4), + (2, 8), + before={"cursor": (1, 0)}, + after={"cursor": (0, 4)}, + finish=b"X", + final={"rows": ("canoXy", "")}, + ), + ResizeCase( + "resize-alternate-preserves-wrapped-physical-rows", + b"\x1b[?1049hharbor", + (2, 4), + (2, 8), + before={"rows": ("harb", "or"), "alt": True}, + after={"rows": ("harb", "or"), "alt": True, "cursor": (1, 2), "history": ()}, + ), + ResizeCase( + "resize-primary-caret-reflows-behind-alternate", + b"canopy\x1b[?1049haux", + (2, 4), + (2, 8), + before={"rows": ("aux", ""), "alt": True}, + after={"rows": ("aux", ""), "alt": True}, + finish=b"\x1b[?1049l", + final={"rows": ("canopy", ""), "cursor": (0, 6), "alt": False}, + ), + ResizeCase( + "resize-reflow-keeps-style-on-moved-cells", + b"\x1b[31mABCD\x1b[34mE", + (2, 4), + (2, 8), + before={"rows": ("ABCD", "E")}, + after={"rows": ("ABCDE", "")}, + cells=(cell(0, 3, text="D", fg="ansi:1"), cell(0, 4, text="E", fg="ansi:4")), + ), + ResizeCase( + "resize-queues-enabled-in-band-geometry", + b"\x1b[?2048hhome", + (2, 8), + (3, 10), + before={"rows": ("home", "")}, + after={"rows": ("home", "", ""), "replies": b"\x1b[48;3;10;48;80t"}, + ), + ResizeCase( + "resize-stops-in-band-replies-after-mode-reset", + b"\x1b[?2048h\x1b[?2048ldune", + (2, 8), + (3, 10), + before={"rows": ("dune", "")}, + after={"replies": b""}, + ), + ResizeCase( + "resize-updates-text-area-geometry-query", + b"home", + (2, 6), + (3, 10), + before={"rows": ("home", "")}, + after={"replies": b""}, + finish=b"\x1b[18t\x1b[14t\x1b[16t", + final={"replies": b"\x1b[8;3;10t\x1b[4;48;80t\x1b[6;16;8t"}, + ), + ResizeCase( + "resize-rejoins-logical-line-from-scrollback", + b"abcdefghij", + (2, 4), + (2, 12), + before={"rows": ("efgh", "ij"), "history": ("abcd",), "wrapped": (0,)}, + after={"rows": ("abcdefghij", ""), "history": (), "cursor": (0, 10)}, + ), + ResizeCase( + "resize-shrink-respects-scrollback-limit", + b"arch\r\nbay\r\ncove\r\ndune", + (4, 8), + (2, 8), + before={"rows": ("arch", "bay", "cove", "dune"), "history": ()}, + after={"rows": ("cove", "dune"), "history": ("bay",)}, + scrollback=1, + ), + ResizeCase( + "resize-committed-geometry-waits-for-sync-release", + b"home\x1b[?2026h", + (2, 8), + (3, 10), + before={"rows": ("home", "")}, + after={"rows": ("home", "", ""), "committed_geometry": (2, 8)}, + finish=b"\x1b[?2026l", + final={"committed_geometry": (3, 10)}, + ), +) diff --git a/tests/fire_protocol_vectors.py b/tests/fire_protocol_vectors.py new file mode 100644 index 00000000..d08eef06 --- /dev/null +++ b/tests/fire_protocol_vectors.py @@ -0,0 +1,248 @@ +"""First-party FIRE vectors for rendition and terminal reports.""" + +from __future__ import annotations + +from tests.fire_vectors import FrameCase, cell, frame, step + +# ECMA-48 §8.3.117, ITU T.416 color/underline forms, and XTerm SGR extensions. +# Cell checks use authored colors with their encoding family preserved. +RENDITION_CASES = ( + frame( + "rendition-normal-intensity-keeps-italic", + b"\x1b[1;2;3mA\x1b[22mB", + cells=( + cell(0, 0, bold=True, dim=True, italic=True), + cell(0, 1, bold=False, dim=False, italic=True), + ), + ), + frame( + "rendition-italic-reset-keeps-bold", + b"\x1b[1;3mA\x1b[23mB", + cells=(cell(0, 0, bold=True, italic=True), cell(0, 1, bold=True, italic=False)), + ), + frame( + "rendition-underline-subparameter-and-reset", + b"\x1b[4:3mA\x1b[24mB", + cells=(cell(0, 0, underline=3), cell(0, 1, underline=0)), + ), + frame( + "rendition-double-underline-after-single", + b"\x1b[4mA\x1b[21mB", + cells=(cell(0, 0, underline=1), cell(0, 1, underline=2)), + ), + frame( + "rendition-underline-color-reset-keeps-foreground", + b"\x1b[31;4;58;5;113mA\x1b[59mB", + cells=( + cell(0, 0, fg="ansi:1", underline=1, underline_color="index:113"), + cell(0, 1, fg="ansi:1", underline=1, underline_color="default"), + ), + ), + frame( + "rendition-low-index-is-distinct-from-ansi-color", + b"\x1b[31mA\x1b[38;5;1mB", + cells=(cell(0, 0, fg="ansi:1"), cell(0, 1, fg="index:1")), + ), + frame( + "rendition-semicolon-rgb-keeps-indexed-background", + b"\x1b[48;5;114;38;2;18;52;86mA", + cells=(cell(0, 0, fg="rgb:123456", bg="index:114"),), + ), + frame( + "rendition-colon-rgb-uses-rgb-after-empty-colorspace", + b"\x1b[48:2::1:2:3;32mA", + cells=(cell(0, 0, fg="ansi:2", bg="rgb:010203"),), + ), + frame( + "rendition-foreground-reset-keeps-background", + b"\x1b[36;44mA\x1b[39mB", + cells=( + cell(0, 0, fg="ansi:6", bg="ansi:4"), + cell(0, 1, fg="default", bg="ansi:4"), + ), + ), + frame( + "rendition-background-reset-keeps-foreground", + b"\x1b[35;42mA\x1b[49mB", + cells=( + cell(0, 0, fg="ansi:5", bg="ansi:2"), + cell(0, 1, fg="ansi:5", bg="default"), + ), + ), + frame( + "rendition-full-reset-affects-only-future-cells", + b"\x1b[1;4;31;46mA\x1b[mB", + cells=( + cell(0, 0, bold=True, underline=1, fg="ansi:1", bg="ansi:6"), + cell(0, 1, bold=False, underline=0, fg="default", bg="default"), + ), + ), + frame( + "rendition-screen-inverse-keeps-stored-cell-colors", + b"\x1b[?5h", + setup=b"\x1b[31;44mA", + reverse_video=True, + cells=(cell(0, 0, fg="ansi:1", bg="ansi:4", reverse=False),), + ), + frame( + "rendition-strike-reset-keeps-overline", + b"\x1b[9;53mA\x1b[29mB\x1b[55mC", + cells=( + cell(0, 0, strikethrough=True, overline=True), + cell(0, 1, strikethrough=False, overline=True), + cell(0, 2, strikethrough=False, overline=False), + ), + ), + frame( + "rendition-unconceal-and-blink-reset-keep-reverse", + b"\x1b[5;7;8mA\x1b[25;28mB", + cells=( + cell(0, 0, blink=True, reverse=True, hidden=True), + cell(0, 1, blink=False, reverse=True, hidden=False), + ), + ), + frame( + "rendition-decrc-restores-saved-pen", + b"\x1b[31mA\x1b7\x1b[32mB\x1b8C", + rows=("AC", "", "", ""), + cells=(cell(0, 0, fg="ansi:1"), cell(0, 1, fg="ansi:1", text="C")), + ), + frame( + "rendition-osc8-sgr-reset-keeps-link-until-osc8-close", + b"\x1b]8;id=rack;https://example.test/r\x1b\\\x1b[1mA\x1b[0mB\x1b]8;;\x1b\\C", + cells=( + cell( + 0, + 0, + link_id="rack", + link_uri="https://example.test/r", + has_hyperlink=True, + bold=True, + ), + cell(0, 1, link_id="rack", link_uri="https://example.test/r", bold=False), + cell(0, 2, has_hyperlink=False), + ), + ), + frame( + "rendition-osc8-replaces-link-for-new-cells", + b"\x1b]8;id=a;https://example.test/a\x07A" + b"\x1b]8;id=b;https://example.test/b\x07B", + cells=( + cell(0, 0, link_id="a", link_uri="https://example.test/a"), + cell(0, 1, link_id="b", link_uri="https://example.test/b"), + ), + ), + frame( + "rendition-bright-colors-are-independent-of-bold", + b"\x1b[1;93;105mA\x1b[22mB", + cells=( + cell(0, 0, fg="ansi:11", bg="ansi:13", bold=True), + cell(0, 1, fg="ansi:11", bg="ansi:13", bold=False), + ), + ), + frame( + "rendition-erasure-uses-current-background", + b"\x1b[44mABC\x1b[42m\r\x1b[1X", + rows=(" BC", "", "", ""), + cells=(cell(0, 0, text=" ", bg="ansi:2"), cell(0, 1, text="B", bg="ansi:4")), + ), + frame( + "rendition-delete-moves-color-with-surviving-cell", + b"\x1b[31mA\x1b[32mB\x1b[34mC\x1b[0m\x1b[2G\x1b[P", + rows=("AC", "", "", ""), + cells=(cell(0, 1, text="C", fg="ansi:4"), cell(0, 2, text=" ", fg="default")), + ), + frame( + "rendition-decstr-resets-pen-and-keeps-old-cells", + b"\x1b[31;1mA\x1b[!p\x1b[2GB", + rows=("AB", "", "", ""), + cells=( + cell(0, 0, fg="ansi:1", bold=True), + cell(0, 1, fg="default", bold=False), + ), + ), +) + +# ECMA-48 CPR/DA/DSR, XTerm request and report formats, and libvt's +# configured capabilities and default colors under DEFAULT_PROFILE. +REPLY_CASES = ( + FrameCase( + "reply-ordered-dsr-cpr-and-drain", + ( + step( + "query", + b"\x1b[2;5H\x1b[5n\x1b[6n\x1b[5n", + cursor=(1, 4), + replies=b"\x1b[0n\x1b[2;5R\x1b[0n", + ), + step("drain-again", b"", replies=b""), + ), + ), + frame("reply-private-cpr", b"\x1b[3;6H\x1b[?6n", replies=b"\x1b[?3;6R"), + frame( + "reply-cpr-uses-origin-relative-row", + b"\x1b[2;3r\x1b[?6h\x1b[2;4H\x1b[6n", + cursor=(2, 3), + replies=b"\x1b[2;4R", + ), + frame( + "reply-da-primary-and-secondary-identity", + b"\x1b[c\x1b[>c", + replies=b"\x1b[?62;22c\x1b[>1;10;0c", + ), + FrameCase( + "reply-decrqm-distinguishes-set-reset-and-unknown", + ( + step("set", b"\x1b[?2004h\x1b[?2004$p", replies=b"\x1b[?2004;1$y"), + step("reset", b"\x1b[?2004l\x1b[?2004$p", replies=b"\x1b[?2004;2$y"), + step("unknown", b"\x1b[?9999$p", replies=b"\x1b[?9999;0$y"), + ), + ), + frame( + "reply-decrqm-standard-insert-mode", b"\x1b[4h\x1b[4$p", replies=b"\x1b[4;1$y" + ), + frame( + "reply-decrqss-scroll-margins", + b"\x1b[2;3r\x1bP$qr\x1b\\", + replies=b"\x1bP1$r2;3r\x1b\\", + ), + frame( + "reply-decrqss-current-sgr", + b"\x1b[32m\x1bP$qm\x1b\\", + replies=b"\x1bP1$r0;32m\x1b\\", + ), + frame( + "reply-decrqss-unrecognized-request", + b"\x1bP$qz\x1b\\", + replies=b"\x1bP0$r\x1b\\", + ), + frame( + "reply-osc-default-foreground-and-background", + b"\x1b]10;?\x1b\\\x1b]11;?\x1b\\", + replies=b"\x1b]10;rgb:e5e5/e5e5/e5e5\x1b\\\x1b]11;rgb:1e1e/1e1e/1e1e\x1b\\", + ), + frame( + "reply-osc-palette-set-then-query", + b"\x1b]4;35;#a1b2c3\x1b\\\x1b]4;35;?\x1b\\", + replies=b"\x1b]4;35;rgb:a1a1/b2b2/c3c3\x1b\\", + ), + frame( + "reply-osc-foreground-query-after-set-and-reset", + b"\x1b]10;#102030\x07\x1b]10;?\x1b\\\x1b]110\x07\x1b]10;?\x1b\\", + replies=b"\x1b]10;rgb:1010/2020/3030\x1b\\\x1b]10;rgb:e5e5/e5e5/e5e5\x1b\\", + fg_rgb=(229, 229, 229), + ), + frame("reply-color-scheme-default-dark", b"\x1b[?996n", replies=b"\x1b[?997;1n"), + frame( + "reply-text-area-and-cell-pixel-size", + b"\x1b[18t\x1b[16t", + size=(5, 9), + replies=b"\x1b[8;5;9t\x1b[6;16;8t", + ), + frame( + "reply-text-area-pixel-size", + b"\x1b[14t", + size=(3, 11), + replies=b"\x1b[4;48;88t", + ), +) diff --git a/tests/fire_state_vectors.py b/tests/fire_state_vectors.py new file mode 100644 index 00000000..cbb20065 --- /dev/null +++ b/tests/fire_state_vectors.py @@ -0,0 +1,477 @@ +"""First-party FIRE vectors for buffers, publication, and replica recovery.""" + +from __future__ import annotations + +import typing as t + +from tests.fire_vectors import FrameCase, Value, cell, frame, step + +# DEC/XTerm alternate buffers, Contour's synchronized-output contract, and +# the libvt working/committed snapshot contract. Keep both sides of the gate. +PUBLICATION_CASES = ( + FrameCase( + "buffer-47-reset-reconciles-1049-mode", + ( + step( + "paint-alternate", + b"\x1b[?1049haux\x1b[?1049$p", + alt=True, + rows=("aux", "", "", ""), + replies=b"\x1b[?1049;1$y", + ), + step( + "reset-via-47", + b"\x1b[?47l\x1b[?47$p\x1b[?1047$p\x1b[?1049$p", + alt=False, + rows=("root", "", "", ""), + replies=b"\x1b[?47;2$y\x1b[?1047;2$y\x1b[?1049;2$y", + ), + ), + setup=b"root", + ), + FrameCase( + "buffer-1047-exit-clears-alternate", + ( + step( + "paint-alternate", b"\x1b[?1047haux", alt=True, rows=("aux", "", "", "") + ), + step( + "return-primary", + b"\x1b[?1047l", + alt=False, + rows=("root", "", "", ""), + alternate_buffer_rows=("", "", "", ""), + ), + ), + setup=b"root", + ), + FrameCase( + "buffer-1049-restores-primary-cursor-and-pen", + ( + step( + "use-alternate", + b"\x1b[?1049h\x1b[33maux\x1b[3;4H", + alt=True, + cursor=(2, 3), + rows=("aux", "", "", ""), + ), + step( + "return-primary-and-print", + b"\x1b[?1049lY", + alt=False, + cursor=(1, 3), + rows=("old", " Y", "", ""), + cells=(cell(1, 2, fg="ansi:2"),), + ), + ), + setup=b"old\x1b[2;3H\x1b[32m", + ), + FrameCase( + "buffer-alternate-scroll-does-not-mix-history", + ( + step( + "scroll-alternate", + b"\x1b[?1049hred\r\nblue\r\ngreen", + alt=True, + rows=("blue", "green"), + history=("arch",), + scrolled_viewport=("blue", "green"), + ), + step( + "restore-primary", + b"\x1b[?1049l", + alt=False, + rows=("bay", "cove"), + history=("arch",), + scrolled_viewport=("arch", "bay"), + ), + ), + setup=b"arch\r\nbay\r\ncove", + size=(2, 8), + ), + frame( + "buffer-ed3-on-alternate-keeps-primary-history", + b"\x1b[?1049haux\x1b[3J\x1b[?1049l", + size=(2, 8), + setup=b"arch\r\nbay\r\ncove", + rows=("bay", "cove"), + history=("arch",), + alt=False, + ), + FrameCase( + "buffer-ris-clears-both-viewports-and-keeps-history", + ( + step( + "dirty-alternate", + b"\x1b[?1049haux\x1b[?25l", + alt=True, + rows=("aux", ""), + cursor_visible=False, + ), + step( + "reset", + b"\x1bc", + alt=False, + rows=("", ""), + alternate_buffer_rows=("", ""), + history=("arch",), + cursor=(0, 0), + cursor_visible=True, + ), + ), + setup=b"arch\r\nbay\r\ncove", + size=(2, 8), + ), + FrameCase( + "buffer-cursor-visibility-is-shared-between-screens", + ( + step("enter-alternate", b"\x1b[?1049h", alt=True, cursor_visible=False), + step( + "show-and-close", + b"\x1b[?25h\x1b[?1049l", + alt=False, + cursor_visible=True, + ), + ), + setup=b"\x1b[?25l", + ), + FrameCase( + "publication-holds-title-while-working-metadata-changes", + ( + step( + "hold-title", + b"\x1b[?2026h\x1b]2;after\x07", + title="after", + committed_title="before", + ), + step( + "release-title", b"\x1b[?2026l", title="after", committed_title="after" + ), + ), + setup=b"\x1b]2;before\x07", + ), + FrameCase( + "publication-holds-cursor-until-release", + ( + step( + "hold-cursor", + b"\x1b[?2026h\x1b[?25l\x1b[3;4H", + cursor=(2, 3), + committed_cursor=(0, 0), + cursor_visible=False, + committed_cursor_visible=True, + ), + step( + "release-cursor", + b"\x1b[?2026l", + committed_cursor=(2, 3), + committed_cursor_visible=False, + ), + ), + ), + FrameCase( + "publication-holds-history-while-working-viewport-scrolls", + ( + step( + "hold-scroll", + b"\x1b[?2026h\r\nridge", + rows=("pool", "ridge"), + committed_rows=("bank", "pool"), + history=("bank",), + committed_history=(), + ), + step( + "release-scroll", + b"\x1b[?2026l", + committed_rows=("pool", "ridge"), + committed_history=("bank",), + ), + ), + setup=b"bank\r\npool", + size=(2, 8), + ), + FrameCase( + "publication-holds-reverse-video", + ( + step( + "hold-inversion", + b"\x1b[?2026h\x1b[?5h", + reverse_video=True, + committed_reverse_video=False, + ), + step("release-inversion", b"\x1b[?2026l", committed_reverse_video=True), + ), + setup=b"\x1b[31;44mA", + ), + FrameCase( + "publication-second-hold-freezes-last-published-frame", + ( + step( + "first-release", + b"\x1b[?2026h\rfox\x1b[?2026l", + committed_rows=("fox", "", "", ""), + ), + step( + "second-hold", + b"\x1b[?2026h\rowl", + rows=("owl", "", "", ""), + committed_rows=("fox", "", "", ""), + ), + step("second-release", b"\x1b[?2026l", committed_rows=("owl", "", "", "")), + ), + setup=b"yak", + ), + FrameCase( + "publication-holds-default-foreground-color", + ( + step( + "hold-color", + b"\x1b[?2026h\x1b]10;#305070\x07", + fg_rgb=(48, 80, 112), + committed_fg_rgb=(229, 229, 229), + ), + step("release-color", b"\x1b[?2026l", committed_fg_rgb=(48, 80, 112)), + ), + ), + FrameCase( + "publication-holds-cursor-shape-and-blink", + ( + step( + "hold-shape", + b"\x1b[?2026h\x1b[6 q", + cursor_shape="bar", + cursor_blinking=False, + committed_cursor_shape="block", + committed_cursor_blinking=True, + ), + step( + "release-shape", + b"\x1b[?2026l", + committed_cursor_shape="bar", + committed_cursor_blinking=False, + ), + ), + ), +) + + +type View = t.Literal["committed", "working"] + + +class DeltaCase(t.NamedTuple): + """One independently specified replica update from a real prior snapshot.""" + + name: str + setup: bytes + update: bytes + before: dict[str, Value] + after: dict[str, Value] + size: tuple[int, int] = (3, 8) + scrollback: int = 4 + token_view: View = "committed" + view: View = "committed" + + +# The libvt ScreenDelta contract supplies the reasons and the update flags. +# Row and history values are worked out from the cursor and scroll operations. +DELTA_CASES = ( + DeltaCase( + "delta-one-dirty-row-with-restored-cursor", + b"ink\r\noak\r\npin", + b"\x1b[2;1HX\x1b[3;4H", + before={"rows": ("ink", "oak", "pin")}, + after={ + "rows": ("ink", "Xak", "pin"), + "dirty_rows": (1,), + "cursor_changed": False, + }, + ), + DeltaCase( + "delta-disjoint-dirty-rows", + b"ink\r\noak\r\npin", + b"\x1b[1;2HX\x1b[3;2HY", + before={"rows": ("ink", "oak", "pin")}, + after={"rows": ("iXk", "oak", "pYn"), "dirty_rows": (0, 2)}, + ), + DeltaCase( + "delta-cursor-motion-does-not-dirty-cells", + b"ink", + b"\x1b[3;5H", + before={"rows": ("ink", "", ""), "cursor": (0, 3)}, + after={ + "rows": ("ink", "", ""), + "cursor": (2, 4), + "dirty_rows": (), + "cursor_changed": True, + "metadata_changed": False, + }, + ), + DeltaCase( + "delta-cursor-visibility-changes-at-same-position", + b"ink", + b"\x1b[?25l", + before={"cursor": (0, 3), "cursor_visible": True}, + after={ + "rows": ("ink", "", ""), + "cursor": (0, 3), + "cursor_visible": False, + "dirty_rows": (), + "cursor_changed": True, + }, + ), + DeltaCase( + "delta-bracketed-paste-mode-changes-without-edit", + b"ink", + b"\x1b[?2004h", + before={"rows": ("ink", "", "")}, + after={ + "rows": ("ink", "", ""), + "dirty_rows": (), + "cursor_changed": False, + "modes_changed": True, + }, + ), + DeltaCase( + "delta-repeated-mode-set-is-idempotent", + b"\x1b[?2004hink", + b"\x1b[?2004h", + before={"rows": ("ink", "", "")}, + after={"rows": ("ink", "", ""), "has_changes": False, "modes_changed": False}, + ), + DeltaCase( + "delta-title-keeps-old-snapshot-and-dirties-metadata-only", + b"ink\x1b]2;before\x07", + b"\x1b]2;after\x07", + before={"rows": ("ink", "", ""), "title": "before"}, + after={ + "rows": ("ink", "", ""), + "title": "after", + "dirty_rows": (), + "metadata_changed": True, + "appearance_changed": False, + }, + ), + DeltaCase( + "delta-osc7-cwd-decodes-percent-escape", + b"ink\x1b]7;file:///crate\x07", + b"\x1b]7;file:///crate%20a\x07", + before={"cwd": "/crate"}, + after={ + "rows": ("ink", "", ""), + "cwd": "/crate a", + "dirty_rows": (), + "metadata_changed": True, + }, + ), + DeltaCase( + "delta-default-color-changes-appearance-only", + b"ink", + b"\x1b]10;#305070\x07", + before={"rows": ("ink", "", ""), "fg_rgb": (229, 229, 229)}, + after={ + "rows": ("ink", "", ""), + "fg_rgb": (48, 80, 112), + "dirty_rows": (), + "appearance_changed": True, + "metadata_changed": False, + }, + ), + DeltaCase( + "delta-scroll-reconstructs-viewport-and-history", + b"bank\r\npool\r\nreed", + b"\r\nridge", + before={"rows": ("bank", "pool", "reed"), "history": ()}, + after={ + "rows": ("pool", "reed", "ridge"), + "history": ("bank",), + "viewport_scroll_up": 1, + "new_history": ("bank",), + "dirty_rows": (2,), + }, + ), + DeltaCase( + "delta-ed3-clears-cached-history", + b"arch\r\nbay\r\ncove", + b"\x1b[3J", + before={"rows": ("bay", "cove"), "history": ("arch",)}, + after={ + "rows": ("bay", "cove"), + "history": (), + "history_cleared": True, + "viewport_scroll_up": 0, + "dirty_rows": (), + }, + size=(2, 8), + ), + DeltaCase( + "delta-history-eviction-forces-full-rebuild", + b"arch\r\nbay", + b"\r\ncove\r\ndune", + before={"rows": ("arch", "bay"), "history": ()}, + after={ + "rows": ("cove", "dune"), + "history": ("bay",), + "reason": "history_evicted", + "full_resync": True, + "dirty_rows": (0, 1), + }, + size=(2, 8), + scrollback=1, + ), + DeltaCase( + "delta-single-eviction-removes-old-cached-row", + b"arch\r\nbay\r\ncove", + b"\r\ndune", + before={"rows": ("bay", "cove"), "history": ("arch",)}, + after={ + "rows": ("cove", "dune"), + "history": ("bay",), + "history_evicted": 1, + "viewport_scroll_up": 1, + "new_history": ("bay",), + "dirty_rows": (1,), + }, + size=(2, 8), + scrollback=1, + ), + DeltaCase( + "delta-token-view-mismatch-rebuilds-working-rows", + b"ink", + b"\x1b[?2026h\r\x1b[2Koak", + before={"rows": ("ink", "", "")}, + after={ + "rows": ("oak", "", ""), + "reason": "terminal_mismatch", + "full_resync": True, + }, + view="working", + ), + DeltaCase( + "delta-ris-invalidates-old-epoch", + b"ink\r\noak\r\npin", + b"\x1bc", + before={"rows": ("ink", "oak", "pin")}, + after={"rows": ("", "", ""), "reason": "epoch_changed", "full_resync": True}, + ), + DeltaCase( + "delta-open-update-keeps-committed-token", + b"ink", + b"\x1b[?2026h\r\x1b[2Koak", + before={"rows": ("ink", "", ""), "cursor": (0, 3)}, + after={ + "rows": ("ink", "", ""), + "cursor": (0, 3), + "dirty_rows": (), + "has_changes": False, + }, + ), + DeltaCase( + "delta-open-update-reaches-working-replica", + b"\x1b[?2026hink", + b"\r\x1b[2Koak", + before={"rows": ("ink", "", "")}, + after={"rows": ("oak", "", ""), "dirty_rows": (0,), "has_changes": True}, + token_view="working", + view="working", + ), +) diff --git a/tests/fire_vectors.py b/tests/fire_vectors.py new file mode 100644 index 00000000..28713df5 --- /dev/null +++ b/tests/fire_vectors.py @@ -0,0 +1,492 @@ +"""First-party FIRE vectors with byte inputs and hand-derived checkpoints.""" + +from __future__ import annotations + +import typing as t + +type Value = tuple[str, ...] | tuple[int, ...] | bytes | bool | str | int + + +class CellCheck(t.NamedTuple): + """Expected public cell fields at one zero-based position.""" + + row: int + col: int + expected: dict[str, Value] + + +class Step(t.NamedTuple): + """One feed action followed by a named checkpoint.""" + + name: str + data: bytes + expected: dict[str, Value] + cells: tuple[CellCheck, ...] = () + + +class FrameCase(t.NamedTuple): + """A terminal viewport and a sequence of authored actions.""" + + name: str + steps: tuple[Step, ...] + setup: bytes = b"" + size: tuple[int, int] = (4, 8) + + +def cell(row: int, col: int, /, **expected: Value) -> CellCheck: + """Select cell fields by name.""" + return CellCheck(row, col, expected) + + +def step( + name: str, data: bytes, /, *, cells: tuple[CellCheck, ...] = (), **expected: Value +) -> Step: + """Name the action that produced the expected state.""" + return Step(name, data, expected, cells) + + +def frame( + name: str, + data: bytes, + /, + *, + setup: bytes = b"", + size: tuple[int, int] = (4, 8), + cells: tuple[CellCheck, ...] = (), + **expected: Value, +) -> FrameCase: + """Declare a case with one post-action checkpoint.""" + return FrameCase( + name, (step("exercise", data, cells=cells, **expected),), setup, size + ) + + +# ECMA-48 §8.3, DEC ANSI parser dispatch, Unicode 17 UAX #11 and #29, +# and the WHATWG UTF-8 decoder. Each partial input has its own checkpoint. +PARSING_CASES = ( + frame( + "parser-utf8-two-byte-followed-by-ascii", + "µ:a".encode(), + rows=("µ:a", "", "", ""), + cursor=(0, 3), + ), + frame( + "parser-utf8-wide-han", + "界+".encode(), + rows=("界+", "", "", ""), + cursor=(0, 3), + cells=(cell(0, 0, width=2), cell(0, 1, width=0), cell(0, 2, text="+")), + ), + frame( + "parser-utf8-four-byte-emoji", + "🚀.".encode(), + rows=("🚀.", "", "", ""), + cursor=(0, 3), + cells=(cell(0, 0, width=2), cell(0, 2, text=".")), + ), + frame( + "parser-invalid-utf8-reprocesses-ascii", + b"\xc2q", + rows=("�q", "", "", ""), + cursor=(0, 2), + ), + frame( + "parser-invalid-utf8-reprocesses-escape", + b"\xe2\x1b[2;2HQ", + rows=("�", " Q", "", ""), + cursor=(1, 2), + ), + FrameCase( + "parser-incomplete-utf8-stays-pending", + ( + step("prefix", b"\xe2\x82", rows=("", "", "", ""), cursor=(0, 0)), + step("finish", b"\xac!", rows=("€!", "", "", ""), cursor=(0, 2)), + ), + ), + frame( + "parser-escape-restarts-incomplete-csi", + b"a\x1b[2;\x1b[2;3HX", + rows=("a", " X", "", ""), + cursor=(1, 3), + ), + frame("parser-can-cancels-csi", b"\x1b[3;\x18A", rows=("A", "", "", "")), + frame("parser-sub-cancels-csi", b"\x1b[3;\x1aB", rows=("B", "", "", "")), + frame( + "parser-backspace-executes-during-csi", + b"abc\x1b[\x08K", + rows=("ab", "", "", ""), + cursor=(0, 2), + ), + frame( + "parser-nul-during-cup-keeps-parameters", + b"\x1b[2;\x004HQ", + rows=("", " Q", "", ""), + cursor=(1, 4), + ), + frame( + "parser-unsupported-csi-does-not-print", + b"k\x1b[999zq", + rows=("kq", "", "", ""), + replies=b"", + ), + frame( + "parser-osc-bel-terminates-title", + b"\x1b]2;orchard\x07R", + title="orchard", + rows=("R", "", "", ""), + ), + frame( + "parser-osc-st-keeps-payload-semicolon", + b"\x1b]2;rack;west\x1b\\R", + title="rack;west", + rows=("R", "", "", ""), + ), + FrameCase( + "parser-incomplete-osc-st-keeps-old-title", + ( + step("prefix", b"\x1b]2;new\x1b", title="old", rows=("", "", "", "")), + step("finish", b"\\N", title="new", rows=("N", "", "", "")), + ), + setup=b"\x1b]2;old\x07", + ), + frame( + "parser-can-cancels-osc-title", + b"\x1b]2;abandoned\x18X", + setup=b"\x1b]2;keep\x07", + title="keep", + rows=("X", "", "", ""), + ), + FrameCase( + "parser-unknown-dcs-hides-payload-until-st", + ( + step("prefix", b"\x1bP9zjunk", rows=("", "", "", "")), + step("finish", b"\x1b\\D", rows=("D", "", "", ""), replies=b""), + ), + ), + frame( + "parser-unknown-apc-consumes-payload", + b"\x1b_test\x1b\\P", + rows=("P", "", "", ""), + ), + frame("parser-del-ignored-between-glyphs", b"z\x7fx", rows=("zx", "", "", "")), + frame( + "parser-combining-mark-stays-in-cell", + "e\u0301!".encode(), + rows=("e\u0301!", "", "", ""), + cursor=(0, 2), + cells=(cell(0, 0, text="e\u0301", width=1), cell(0, 1, text="!")), + ), + frame( + "parser-zwj-grapheme-in-mode-2027", + b"\x1b[?2027h" + "👩‍💻X".encode(), + cursor=(0, 3), + cells=(cell(0, 0, text="👩‍💻", width=2), cell(0, 2, text="X")), + ), + frame( + "parser-empty-leading-cup-parameter", + b"\x1b[;4HX", + rows=(" X", "", "", ""), + cursor=(0, 4), + ), + frame( + "parser-dec-special-graphics-then-ascii", + b"\x1b(0lqk\x1b(Bz", + rows=("┌─┐z", "", "", ""), + cursor=(0, 4), + ), +) + + +# ECMA-48 §8.3 (movement and tabulation) and DEC/XTerm margin, origin, +# save-cursor, and autowrap behavior. +CURSOR_CASES = ( + frame("cursor-bs-overwrites-preceding-cell", b"ref\bX", rows=("reX", "", "", "")), + frame( + "cursor-bs-at-first-column-stays-in-row", + b"\x1b[2;1H\bX", + rows=("", "X", "", ""), + cursor=(1, 1), + ), + frame("cursor-cr-keeps-row", b"\x1b[3;4H\r", cursor=(2, 0)), + frame("cursor-lf-keeps-column", b"\x1b[2;4H\n", cursor=(2, 3)), + frame("cursor-vt-keeps-column", b"\x1b[1;6H\v", cursor=(1, 5)), + frame("cursor-nel-returns-to-left", b"\x1b[2;5H\x1bE", cursor=(2, 0)), + frame("cursor-cuu-clamps-at-top", b"\x1b[3;5H\x1b[9A", cursor=(0, 4)), + frame("cursor-cuf-clamps-at-right", b"\x1b[3;5H\x1b[9C", cursor=(2, 7)), + frame("cursor-cub-clamps-at-left", b"\x1b[3;5H\x1b[9D", cursor=(2, 0)), + frame("cursor-cud-clamps-at-bottom", b"\x1b[2;5H\x1b[9B", cursor=(3, 4)), + frame("cursor-hvp-positions-both-axes", b"\x1b[3;6f", cursor=(2, 5)), + frame("cursor-cha-keeps-row", b"\x1b[3;6H\x1b[2G", cursor=(2, 1)), + frame("cursor-vpa-keeps-column", b"\x1b[4;6H\x1b[2d", cursor=(1, 5)), + frame("cursor-hpr-is-relative", b"\x1b[3;2H\x1b[3a", cursor=(2, 4)), + frame("cursor-vpr-is-relative", b"\x1b[2;6H\x1b[2e", cursor=(3, 5)), + frame("cursor-cnl-selects-next-left", b"\x1b[1;6H\x1b[2E", cursor=(2, 0)), + frame("cursor-cpl-selects-preceding-left", b"\x1b[4;6H\x1b[2F", cursor=(1, 0)), + frame( + "cursor-ht-finds-custom-stop", + b"\x1b[1;4H\x1bH\r|\tX", + rows=("| X", "", "", ""), + cursor=(0, 4), + ), + frame( + "cursor-cbt-counts-back-from-right", + b"\x1b[1;3H\x1bH\x1b[6G\x1bH\x1b[8G\x1b[2Z", + cursor=(0, 2), + ), + frame("cursor-tbc-clears-custom-stop", b"\x1b[4G\x1bH\x1b[3g\r\t", cursor=(0, 7)), + frame( + "cursor-tbc-clears-only-current-stop", + b"\x1b[3G\x1bH\x1b[6G\x1bH\x1b[3G\x1b[g\r\t", + cursor=(0, 5), + ), + frame( + "cursor-decom-offsets-cup-within-vertical-margins", + b"\x1b[2;3r\x1b[?6h\x1b[2;3H", + cursor=(2, 2), + ), + frame( + "cursor-decom-reset-permits-page-coordinate", + b"\x1b[2;3r\x1b[?6h\x1b[?6l\x1b[4;3H", + cursor=(3, 2), + ), + frame( + "cursor-decom-offsets-horizontal-and-vertical-margins", + b"\x1b[2;4r\x1b[?69h\x1b[3;7s\x1b[?6h\x1b[2;2H", + cursor=(2, 3), + ), + frame( + "cursor-decstbm-alone-leaves-cup-page-relative", + b"\x1b[2;3r\x1b[4;2H", + cursor=(3, 1), + ), + frame( + "cursor-scosc-restores-both-axes", b"\x1b[3;5H\x1b[s\x1b[H\x1b[u", cursor=(2, 4) + ), + FrameCase( + "cursor-autowrap-defers-until-next-print", + ( + step( + "fill", + b"branch", + rows=("branch", "", "", ""), + cursor=(0, 5), + pending_wrap=True, + ), + step( + "wrap", + b"Z", + rows=("branch", "Z", "", ""), + cursor=(1, 1), + pending_wrap=False, + ), + ), + size=(4, 6), + ), + frame( + "cursor-disabled-wrap-overwrites-right-edge", + b"\x1b[?7lbranchZ", + size=(4, 6), + rows=("brancZ", "", "", ""), + cursor=(0, 5), + pending_wrap=False, + ), +) + +# ECMA-48 §8.3 (erasure, insertion, deletion, and scrolling). DEC margins +# constrain line edits. Unicode double cells must remain paired after edits. +_GRID = b"north\r\nlake\r\nfern\r\ndune" +_WORD = b"violet" + +GRID_CASES = ( + frame( + "grid-el-to-end-keeps-prefix", + b"\x1b[3G\x1b[K", + setup=_WORD, + rows=("vi", "", "", ""), + cursor=(0, 2), + ), + frame( + "grid-el-to-start-keeps-suffix", + b"\x1b[3G\x1b[1K", + setup=_WORD, + rows=(" let", "", "", ""), + cursor=(0, 2), + ), + frame( + "grid-el-full-line-keeps-neighbors", + b"\x1b[2;3H\x1b[2K", + setup=_GRID, + rows=("north", "", "fern", "dune"), + cursor=(1, 2), + ), + frame( + "grid-ech-keeps-suffix-in-original-columns", + b"\x1b[3G\x1b[2X", + setup=_WORD, + rows=("vi et", "", "", ""), + cursor=(0, 2), + ), + frame( + "grid-ed-to-end-keeps-earlier-rows-and-prefix", + b"\x1b[2;3H\x1b[J", + setup=_GRID, + rows=("north", "la", "", ""), + cursor=(1, 2), + ), + frame( + "grid-ed-to-start-keeps-later-rows-and-suffix", + b"\x1b[2;2H\x1b[1J", + setup=_GRID, + rows=("", " ke", "fern", "dune"), + cursor=(1, 1), + ), + frame( + "grid-ed-full-page-keeps-cursor", + b"\x1b[2;3H\x1b[2J", + setup=_GRID, + rows=("", "", "", ""), + cursor=(1, 2), + ), + frame( + "grid-ed3-clears-history-only", + b"\x1b[3J", + size=(2, 8), + setup=b"h0\r\nh1\r\nh2", + rows=("h1", "h2"), + history=(), + cursor=(1, 2), + ), + frame( + "grid-dch-shifts-tail-left", + b"\x1b[3G\x1b[2P", + setup=_WORD, + rows=("viet", "", "", ""), + cursor=(0, 2), + ), + frame( + "grid-ich-shifts-tail-right", + b"\x1b[3G\x1b[2@", + setup=_WORD, + rows=("vi olet", "", "", ""), + cursor=(0, 2), + ), + FrameCase( + "grid-insert-mode-then-overwrite", + ( + step("insert", b"\x1b[3G\x1b[4hX", rows=("viXolet", "", "", "")), + step("overwrite", b"\x1b[4lY", rows=("viXYlet", "", "", "")), + ), + setup=_WORD, + ), + frame( + "grid-il-moves-rows-inside-margins", + b"\x1b[2;3r\x1b[2;3H\x1b[L", + setup=_GRID, + rows=("north", "", "lake", "dune"), + cursor=(1, 0), + history=(), + ), + frame( + "grid-dl-moves-rows-inside-margins", + b"\x1b[2;3r\x1b[2;3H\x1b[M", + setup=_GRID, + rows=("north", "fern", "", "dune"), + cursor=(1, 0), + history=(), + ), + frame( + "grid-il-outside-scroll-region-keeps-rows", + b"\x1b[2;3r\x1b[4;2H\x1b[L", + setup=_GRID, + rows=("north", "lake", "fern", "dune"), + ), + frame( + "grid-su-moves-only-scroll-region", + b"\x1b[2;3r\x1b[S", + setup=_GRID, + rows=("north", "fern", "", "dune"), + history=(), + ), + frame( + "grid-sd-moves-only-scroll-region", + b"\x1b[2;3r\x1b[T", + setup=_GRID, + rows=("north", "", "lake", "dune"), + history=(), + ), + frame( + "grid-lf-scrolls-at-bottom-margin", + b"\x1b[2;3r\x1b[3;3H\nZ", + setup=_GRID, + rows=("north", "fern", " Z", "dune"), + history=(), + cursor=(2, 3), + ), + frame( + "grid-ri-scrolls-at-top-margin", + b"\x1b[2;3r\x1b[2;3H\x1bMZ", + setup=_GRID, + rows=("north", " Z", "lake", "dune"), + cursor=(1, 3), + ), + frame( + "grid-lf-seals-history-at-viewport-edge", + b"\r\nrope", + setup=_GRID, + rows=("lake", "fern", "dune", "rope"), + history=("north",), + ), + frame( + "grid-horizontal-margins-clip-region-scroll", + b"\x1b[2;3r\x1b[?69h\x1b[3;5s\x1b[S", + setup=b"AAxyzBB\r\nCCuvwDD\r\nEErstFF\r\nGGnopHH", + rows=("AAxyzBB", "CCrstDD", "EE FF", "GGnopHH"), + history=(), + ), + frame( + "grid-overwrite-wide-head-clears-tail", + b"\rY", + setup="界Z".encode(), + rows=("Y Z", "", "", ""), + cells=(cell(0, 1, text=" ", width=1),), + ), + frame( + "grid-overwrite-wide-tail-clears-head", + b"\x1b[2GX", + setup="界Z".encode(), + rows=(" XZ", "", "", ""), + cells=(cell(0, 0, text=" ", width=1),), + ), + frame( + "grid-wide-glyph-at-last-column-wraps-whole", + "界Q".encode(), + setup=b"abc", + size=(2, 4), + rows=("abc", "界Q"), + cursor=(1, 3), + wrapped=(0,), + ), + frame( + "grid-rep-repeats-across-right-edge", + b"\x1b[5b", + setup=b"u", + size=(2, 5), + rows=("uuuuu", "u"), + cursor=(1, 1), + wrapped=(0,), + ), + frame( + "grid-selective-erase-retains-protected-cell", + b"\x1b[?2K", + setup=b'\x1b[1"qA\x1b[0"qB', + rows=("A", "", "", ""), + cells=(cell(0, 0, protected=True), cell(0, 1, text=" ")), + ), + frame( + "grid-normal-erase-clears-protected-cell", + b"\x1b[2K", + setup=b'\x1b[1"qA\x1b[0"qB', + rows=("", "", "", ""), + cells=(cell(0, 0, protected=False, text=" "),), + ), +) diff --git a/tests/test_fire.py b/tests/test_fire.py new file mode 100644 index 00000000..06cfbb6a --- /dev/null +++ b/tests/test_fire.py @@ -0,0 +1,675 @@ +"""Direct FIRE cases for terminal state, replies, and resynchronization.""" + +from __future__ import annotations + +import collections.abc +import dataclasses +import json +import pathlib +import sys +import typing as t + +import pytest + +import libvt +from libvt.config import DEFAULT_PROFILE, Limits, Policy +from libvt.exc import UnsafePasteError +from libvt.screen import Cell, RowView +from libvt.style import AnsiColor, Color, IndexedColor, RgbColor +from libvt.terminal import ResyncReason, ScreenDelta, Snapshot +from tests.fire_interaction_vectors import ( + INPUT_CASES, + RESIZE_CASES, + InputCase, + ResizeCase, +) +from tests.fire_protocol_vectors import RENDITION_CASES, REPLY_CASES +from tests.fire_state_vectors import DELTA_CASES, PUBLICATION_CASES, DeltaCase +from tests.fire_vectors import ( + CURSOR_CASES, + GRID_CASES, + PARSING_CASES, + CellCheck, + FrameCase, + Value as _Value, +) + +_POSITION_CURSOR = b"\x1b[2;4H" +_MOVE_DOWN_TWO = b"\x1b[2B" +_MOVE_DOWN_ONE = b"\x1b[1B" +_RELEASE = b"\x1b[?2026l" +_BASE = b"base" +_HELD_UPDATE = b"\x1b[?2026h\r\x1b[2K\xc3\xa8\x1b[6n" + +# ECMA-48, fifth edition, §§8.3.19 and 8.3.21. Wire (2, 4) is (1, 3) +# in libvt. CUD advances the zero-based row by two and leaves col at three. +_CURSOR_EXPECTED = {"start_position": (1, 3), "cursor_after_move": (3, 3)} + +_PUBLICATION_EXPECTED: dict[str, _Value] = { + "working_during_hold": ("è", ""), + "working_cursor_during_hold": (0, 1), + "committed_during_hold": ("base", ""), + "peer_working_during_hold": ("peer", ""), + "peer_reply_while_primary_pending": b"", + "reply_bytes": b"\x1b[1;2R", + "committed_after_release": ("è", ""), + "reply_queue_empty_after_drain": b"", + "snapshot_before_hold": ("base", ""), + "peer_committed": ("peer", ""), +} + +type _OperationValue = _Value | dict[str, str | int | bool | None] | None + + +class _Attempt: + def __init__(self, *, bytewise: bool) -> None: + self.bytewise = bytewise + self.settings: dict[str, _Value] = {} + self.viewports: dict[str, dict[str, int]] = {} + self.feeds: list[dict[str, str]] = [] + self.operations: list[dict[str, _OperationValue]] = [] + self.checks: dict[str, dict[str, _Value | None]] = {} + + def feed( + self, + terminal: libvt.Terminal, + action: str, + data: bytes, + *, + target: str = "main", + ) -> None: + self.viewports.setdefault( + target, {"rows": terminal.rows, "cols": terminal.cols} + ) + chunks = [bytes((byte,)) for byte in data] if self.bytewise else [data] + for chunk in chunks: + self.feeds.append( + {"action": action, "target": target, "bytes_hex": chunk.hex()} + ) + terminal.feed(chunk) + + def differences( + self, + expected: collections.abc.Mapping[str, _Value], + observed: collections.abc.Mapping[str, _Value], + ) -> dict[str, tuple[_Value, _Value | None]]: + differences = {} + for name, value in expected.items(): + actual = observed.get(name) + self.checks[name] = {"expected": value, "actual": actual} + if actual != value: + differences[name] = (value, actual) + return differences + + def expect(self, name: str, *, expected: _Value, actual: _Value) -> None: + assert self.differences({name: expected}, {name: actual}) == {} + + def record_operation(self, action: str, **fields: _OperationValue) -> None: + self.operations.append( + {"action": action, "after_feeds": len(self.feeds), **fields} + ) + + +def _encode_bytes(value: bytes) -> dict[str, str]: + return {"bytes_hex": value.hex()} + + +@pytest.fixture(params=(False, True), ids=("whole-action", "one-byte")) +def attempt( + request: pytest.FixtureRequest, tmp_path: pathlib.Path +) -> t.Iterator[_Attempt]: + """Write each case's feed calls and named observations for inspection.""" + trace = _Attempt(bytewise=request.param is True) + yield trace + partition = "one-byte" if trace.bytewise else "whole-action" + if request.param is None: + partition = "semantic-only" + evidence = { + "pytest_node": request.node.nodeid, + "attempt": tmp_path.name, + "partition": partition, + "libvt_version": libvt.__version__, + "python_version": sys.version.split()[0], + "profile": "DEFAULT_PROFILE", + "encoding": "utf-8", + "ambiguous_width": DEFAULT_PROFILE.unicode.ambiguous_width, + "settings": trace.settings, + "viewports": trace.viewports, + "feeds": trace.feeds, + "operations": trace.operations, + "checks": trace.checks, + } + (tmp_path / "fire.json").write_text( + json.dumps(evidence, default=_encode_bytes, ensure_ascii=False, indent=2) + + "\n", + encoding="utf-8", + ) + + +def _state(snapshot: Snapshot) -> dict[str, _Value]: + return { + "geometry": (snapshot.rows, snapshot.cols), + "rows": snapshot.lines, + "cursor": (snapshot.cursor.row, snapshot.cursor.col), + "pending_wrap": snapshot.cursor.pending_wrap, + "cursor_visible": snapshot.cursor.visible, + "cursor_shape": snapshot.cursor.shape.value, + "cursor_blinking": snapshot.cursor.blinking, + "title": snapshot.title, + "cwd": snapshot.cwd, + "alt": snapshot.active_is_alt, + "history": tuple(row.text for row in snapshot.history), + "scrolled_viewport": snapshot.viewport(offset=1).lines, + "wrapped": tuple(row for row in range(snapshot.rows) if snapshot[row].wrapped), + "fg_rgb": snapshot.appearance.fg_rgb, + "bg_rgb": snapshot.appearance.bg_rgb, + "reverse_video": snapshot.appearance.reverse_video, + } + + +def _color(color: Color) -> str: + if isinstance(color, AnsiColor): + return f"ansi:{int(color)}" + if isinstance(color, IndexedColor): + return f"index:{color.index}" + if isinstance(color, RgbColor): + return f"rgb:{color.r:02x}{color.g:02x}{color.b:02x}" + return "default" + + +def _cell_state(cell: Cell) -> dict[str, _Value]: + style = cell.style + return { + "text": cell.text, + "width": cell.width, + "protected": cell.protected, + "fg": _color(style.fg), + "bg": _color(style.bg), + "underline_color": _color(style.underline_color), + "underline": int(style.underline), + "bold": style.bold, + "dim": style.dim, + "italic": style.italic, + "blink": style.blink, + "reverse": style.reverse, + "hidden": style.hidden, + "strikethrough": style.strikethrough, + "overline": style.overline, + "has_hyperlink": cell.hyperlink is not None, + "link_uri": cell.hyperlink.uri if cell.hyperlink else "", + "link_id": cell.hyperlink.id if cell.hyperlink else "", + } + + +def _check_snapshot( + attempt: _Attempt, + name: str, + snapshot: Snapshot, + fields: dict[str, _Value], + cells: tuple[CellCheck, ...] = (), + additional: dict[str, _Value] | None = None, +) -> None: + state = _state(snapshot) + if additional is not None: + state.update(additional) + expected = {f"{name}.{key}": value for key, value in fields.items()} + actual = {f"{name}.{key}": value for key, value in state.items()} + for check in cells: + prefix = f"{name}.cell[{check.row},{check.col}]" + expected.update( + {f"{prefix}.{key}": value for key, value in check.expected.items()} + ) + actual.update( + { + f"{prefix}.{key}": value + for key, value in _cell_state(snapshot[check.row, check.col]).items() + } + ) + assert attempt.differences(expected, actual) == {} + + +def _check_terminal( + attempt: _Attempt, + name: str, + terminal: libvt.Terminal, + fields: dict[str, _Value], + cells: tuple[CellCheck, ...] = (), +) -> None: + working = terminal.snapshot() + additional = {} + if any(key.startswith("committed_") for key in fields): + additional.update( + { + f"committed_{key}": value + for key, value in _state(terminal.committed).items() + } + ) + if "replies" in fields: + additional["replies"] = terminal.drain_replies() + if "alternate_buffer_rows" in fields: + additional["alternate_buffer_rows"] = terminal.screens.alternate.lines + _check_snapshot(attempt, name, working, fields, cells, additional) + + +@pytest.mark.parametrize( + "case", + [ + pytest.param(case, id=case.name) + for case in ( + *PARSING_CASES, + *CURSOR_CASES, + *GRID_CASES, + *RENDITION_CASES, + *REPLY_CASES, + *PUBLICATION_CASES, + ) + ], +) +def test_fire_frame(attempt: _Attempt, case: FrameCase) -> None: + """Replay an authored byte vector and compare its named checkpoints.""" + rows, cols = case.size + terminal = libvt.Terminal(rows=rows, cols=cols, profile=DEFAULT_PROFILE) + if case.setup: + attempt.feed(terminal, "setup", case.setup) + for checkpoint in case.steps: + if checkpoint.data: + attempt.feed(terminal, checkpoint.name, checkpoint.data) + _check_terminal( + attempt, checkpoint.name, terminal, checkpoint.expected, checkpoint.cells + ) + + +@pytest.mark.parametrize( + ("attempt", "case"), + [ + pytest.param(bytewise, case, id=f"{schedule}-{case.name}") + for case in INPUT_CASES + for bytewise, schedule in ( + ((False, "whole-action"), (True, "one-byte")) + if any(step.setup for step in case.steps) + else ((None, "semantic-only"),) + ) + ], + indirect=["attempt"], +) +def test_fire_input(attempt: _Attempt, case: InputCase) -> None: + """Check encoded bytes at the application-facing boundary.""" + terminal = libvt.Terminal( + rows=8, + cols=16, + profile=DEFAULT_PROFILE, + limits=Limits(max_keyboard_stack=case.keyboard_stack), + ) + attempt.settings.update( + max_keyboard_stack=case.keyboard_stack, + cell_width_px=DEFAULT_PROFILE.screen.cell_width_px, + cell_height_px=DEFAULT_PROFILE.screen.cell_height_px, + ) + attempt.viewports["main"] = {"rows": terminal.rows, "cols": terminal.cols} + for step in case.steps: + if step.setup: + attempt.feed(terminal, step.name, step.setup) + attempt.record_operation( + "encode", + checkpoint=step.name, + event_type=type(step.event).__name__, + event=dataclasses.asdict(step.event), + ) + try: + observed: _Value = terminal.encode(step.event) + except UnsafePasteError: + observed = "UnsafePasteError" + attempt.expect( + f"{step.name}.encoded_input", expected=step.expected, actual=observed + ) + + +@pytest.mark.parametrize( + "case", [pytest.param(case, id=case.name) for case in RESIZE_CASES] +) +def test_fire_resize(attempt: _Attempt, case: ResizeCase) -> None: + """Check native geometry changes and the readability of the pre-resize view.""" + rows, cols = case.size + profile = dataclasses.replace( + DEFAULT_PROFILE, + screen=dataclasses.replace( + DEFAULT_PROFILE.screen, reflow_on_resize=case.profile_reflow + ), + ) + terminal = libvt.Terminal( + rows=rows, cols=cols, profile=profile, scrollback=case.scrollback + ) + attempt.settings.update( + scrollback=case.scrollback, + reflow_on_resize=case.profile_reflow, + cell_width_px=profile.screen.cell_width_px, + cell_height_px=profile.screen.cell_height_px, + ) + attempt.feed(terminal, "setup", case.setup) + saved = terminal.snapshot() + before = case.before | {"geometry": case.size} + _check_snapshot(attempt, "before", saved, before) + initial_delta = None + history: list[RowView] = [] + viewport: list[RowView] = [] + if case.replica_after is not None: + attempt.settings["replica_view"] = "working" + attempt.record_operation("initialize_replica") + initial_delta = terminal.changes_since(view="working") + initial_delta.apply_rows(history, viewport) + if "replies" in case.after: + # Isolate notifications caused by resize from any pending setup replies. + attempt.record_operation("drain_replies", reply_bytes=terminal.drain_replies()) + resized_rows, resized_cols = case.size_after + attempt.record_operation( + "resize", rows=resized_rows, cols=resized_cols, reflow=case.reflow + ) + terminal.resize(rows=resized_rows, cols=resized_cols, reflow=case.reflow) + _check_terminal( + attempt, + "after", + terminal, + case.after | {"geometry": case.size_after}, + case.cells, + ) + _check_snapshot(attempt, "saved_snapshot", saved, before) + if initial_delta is not None and case.replica_after is not None: + before_rows = tuple(row.text for row in viewport) + before_widths = tuple(len(row) for row in viewport) + attempt.record_operation("update_replica") + resized_delta = terminal.changes_since(initial_delta.token, view="working") + resized_delta.apply_rows(history, viewport) + assert ( + attempt.differences( + {f"replica.{key}": value for key, value in case.replica_after.items()}, + { + "replica.before_rows": before_rows, + "replica.before_widths": before_widths, + "replica.full_resync": resized_delta.full_resync, + "replica.reason": resized_delta.resync_reason.value, + "replica.rows": tuple(row.text for row in viewport), + "replica.widths": tuple(len(row) for row in viewport), + }, + ) + == {} + ) + if case.final is not None: + attempt.feed(terminal, "finish", case.finish) + _check_terminal(attempt, "finish", terminal, case.final) + + +def _replica_state( + snapshot: Snapshot, history: list[RowView], viewport: list[RowView] +) -> dict[str, _Value]: + return _state(snapshot) | { + "rows": tuple(row.text for row in viewport), + "history": tuple(row.text for row in history), + } + + +def _delta_state(delta: ScreenDelta) -> dict[str, _Value]: + return { + "reason": delta.resync_reason.value, + "full_resync": delta.full_resync, + "has_changes": delta.has_changes, + "dirty_rows": delta.dirty_rows, + "cursor_changed": delta.cursor_changed, + "modes_changed": delta.modes_changed, + "metadata_changed": delta.metadata_changed, + "appearance_changed": delta.appearance_changed, + "viewport_scroll_up": delta.viewport_scroll_up, + "history_cleared": delta.history_cleared, + "history_evicted": delta.history_evicted, + "new_history": tuple(row.text for row in delta.new_history), + } + + +@pytest.mark.parametrize( + "case", [pytest.param(case, id=case.name) for case in DELTA_CASES] +) +def test_fire_delta(attempt: _Attempt, case: DeltaCase) -> None: + """Update a cached replica and check that its old snapshot remains readable.""" + rows, cols = case.size + terminal = libvt.Terminal( + rows=rows, cols=cols, scrollback=case.scrollback, profile=DEFAULT_PROFILE + ) + attempt.settings.update( + scrollback=case.scrollback, token_view=case.token_view, delta_view=case.view + ) + attempt.feed(terminal, "setup", case.setup) + initial = terminal.changes_since(view=case.token_view) + history: list[RowView] = [] + viewport: list[RowView] = [] + initial.apply_rows(history, viewport) + before = _replica_state(initial.snapshot, history, viewport) + + attempt.feed(terminal, "update", case.update) + delta = terminal.changes_since(initial.token, view=case.view) + delta.apply_rows(history, viewport) + after = _replica_state(delta.snapshot, history, viewport) | _delta_state(delta) + after["repeated_read_changed"] = terminal.changes_since( + delta.token, view=case.view + ).has_changes + saved = _state(initial.snapshot) + + expected: dict[str, _Value] = { + "reason": "none", + "full_resync": False, + "repeated_read_changed": False, + } | case.after + assert ( + attempt.differences( + {f"before.{key}": value for key, value in case.before.items()} + | {f"saved_snapshot.{key}": value for key, value in case.before.items()} + | {f"after.{key}": value for key, value in expected.items()}, + {f"before.{key}": value for key, value in before.items()} + | {f"saved_snapshot.{key}": value for key, value in saved.items()} + | {f"after.{key}": value for key, value in after.items()}, + ) + == {} + ) + + +def test_fire_incremental_token_tracks_each_view(attempt: _Attempt) -> None: + """Resume two consumers after each has read a different set of changes.""" + terminal = libvt.Terminal(rows=2, cols=8, profile=DEFAULT_PROFILE) + attempt.feed(terminal, "initial_rows", b"\x1b[31mink\r\nlog") + working_start = terminal.sync_token(view="working") + initial = terminal.changes_since(view="committed") + history: list[RowView] = [] + viewport: list[RowView] = [] + initial.apply_rows(history, viewport) + + attempt.feed(terminal, "hold_and_edit_first_row", b"\x1b[?2026h\x1b[1;1Hoak") + first = terminal.changes_since(working_start, view="working") + attempt.expect("working_first_rows", expected=(0,), actual=first.dirty_rows) + attempt.expect( + "committed_during_hold", + expected=False, + actual=terminal.changes_since(initial.token).has_changes, + ) + attempt.expect( + "working_read_again", + expected=False, + actual=terminal.changes_since(first.token, view="working").has_changes, + ) + + attempt.feed(terminal, "edit_second_row", b"\x1b[2;1Hmap") + second = terminal.changes_since(first.token, view="working") + attempt.expect("working_next_rows", expected=(1,), actual=second.dirty_rows) + attempt.expect( + "working_text", expected=("oak", "map"), actual=second.snapshot.lines + ) + + attempt.feed(terminal, "publish_both_edits", _RELEASE) + published = terminal.changes_since(initial.token) + published.apply_rows(history, viewport) + attempt.expect("published_rows", expected=(0, 1), actual=published.dirty_rows) + attempt.expect( + "published_replica_ink", + expected="ansi:1", + actual=_color(viewport[0][0].style.fg), + ) + attempt.expect( + "published_read_again", + expected=False, + actual=terminal.changes_since(published.token).has_changes, + ) + + attempt.feed(terminal, "repaint_same_word", b"\x1b[1;1H\x1b[32moak") + latest = terminal.changes_since(published.token) + latest.apply_rows(history, viewport) + attempt.expect("published_next_rows", expected=(0,), actual=latest.dirty_rows) + attempt.expect( + "published_text", expected=("oak", "map"), actual=latest.snapshot.lines + ) + attempt.expect( + "repainted_replica_ink", + expected="ansi:2", + actual=_color(viewport[0][0].style.fg), + ) + attempt.expect( + "saved_snapshot_ink", + expected="ansi:1", + actual=_color(published.snapshot[0, 0].style.fg), + ) + + +def _cursor_observations(attempt: _Attempt, move: bytes) -> dict[str, tuple[int, int]]: + terminal = libvt.Terminal(rows=6, cols=9, profile=DEFAULT_PROFILE) + attempt.feed(terminal, "place_cursor", _POSITION_CURSOR) + start = terminal.cursor + attempt.feed(terminal, "move_down", move) + finish = terminal.cursor + return { + "start_position": (start.row, start.col), + "cursor_after_move": (finish.row, finish.col), + } + + +def _publication_observations(attempt: _Attempt, release: bytes) -> dict[str, _Value]: + policy = Policy(emit_replies=True) + terminal = libvt.Terminal(rows=2, cols=8, profile=DEFAULT_PROFILE, policy=policy) + peer = libvt.Terminal(rows=2, cols=8, profile=DEFAULT_PROFILE, policy=policy) + attempt.feed(peer, "write_peer", b"peer", target="peer") + attempt.feed(terminal, "write_base", _BASE) + before_hold = terminal.snapshot() + + attempt.feed(terminal, "hold_and_rewrite", _HELD_UPDATE) + working = terminal.snapshot() + held = terminal.committed + peer_working = peer.snapshot().lines + # A shared queue would hand the primary reply to the peer here. + peer_reply = peer.drain_replies() + reply = terminal.drain_replies() + + if release: + attempt.feed(terminal, "release", release) + return { + "working_during_hold": working.lines, + "working_cursor_during_hold": (working.cursor.row, working.cursor.col), + "committed_during_hold": held.lines, + "peer_working_during_hold": peer_working, + "peer_reply_while_primary_pending": peer_reply, + "reply_bytes": reply, + "committed_after_release": terminal.committed.lines, + "reply_queue_empty_after_drain": terminal.drain_replies(), + "snapshot_before_hold": before_hold.lines, + "peer_committed": peer.committed.lines, + } + + +def test_fire_cursor_movement(attempt: _Attempt) -> None: + """Observe the working cursor at both action boundaries.""" + observed = _cursor_observations(attempt, _MOVE_DOWN_TWO) + assert attempt.differences(_CURSOR_EXPECTED, observed) == {} + + +def test_fire_short_move_changes_one_expectation(attempt: _Attempt) -> None: + """A valid CUD with the wrong count fails only the movement check.""" + observed = _cursor_observations(attempt, _MOVE_DOWN_ONE) + assert attempt.differences(_CURSOR_EXPECTED, observed) == { + "cursor_after_move": ((3, 3), (2, 3)), + } + + +def test_fire_working_and_committed_frames(attempt: _Attempt) -> None: + """Observe the held frame, one-shot reply, and isolated snapshots.""" + observed = _publication_observations(attempt, _RELEASE) + assert attempt.differences(_PUBLICATION_EXPECTED, observed) == {} + + +def test_fire_missing_release_changes_one_expectation(attempt: _Attempt) -> None: + """A dropped release leaves the working row correct and the old frame held.""" + observed = _publication_observations(attempt, b"") + assert attempt.differences(_PUBLICATION_EXPECTED, observed) == { + "committed_after_release": (("è", ""), ("base", "")), + } + + +def test_fire_replica_recovers_after_screen_switch(attempt: _Attempt) -> None: + """Rebuild from foreign and stale watermarks, then apply an incremental delta.""" + terminal = libvt.Terminal(rows=2, cols=8, profile=DEFAULT_PROFILE) + peer = libvt.Terminal(rows=2, cols=8, profile=DEFAULT_PROFILE) + attempt.feed(terminal, "write_base", _BASE) + attempt.feed(peer, "write_base", _BASE, target="peer") + foreign = terminal.changes_since(peer.sync_token()) + attempt.expect( + "foreign_token_reason", + expected=ResyncReason.TERMINAL_MISMATCH, + actual=foreign.resync_reason, + ) + attempt.expect( + "foreign_token_full_resync", expected=True, actual=foreign.full_resync + ) + + history: list[RowView] = [] + viewport: list[RowView] = [] + foreign.apply_rows(history, viewport) + attempt.expect( + "foreign_token_rows", + expected=("base", ""), + actual=tuple(row.text for row in viewport), + ) + + attempt.feed(terminal, "enter_alternate", b"\x1b[?1049hALT") + alternate = terminal.changes_since() + alternate.apply_rows(history, viewport) + attempt.feed(terminal, "leave_alternate", b"\x1b[?1049l") + attempt.expect( + "replica_before_epoch_recovery", + expected=("ALT", ""), + actual=tuple(row.text for row in viewport), + ) + restored = terminal.changes_since(alternate.token) + attempt.expect( + "stale_epoch_reason", + expected=ResyncReason.EPOCH_CHANGED, + actual=restored.resync_reason, + ) + attempt.expect( + "stale_epoch_full_resync", expected=True, actual=restored.full_resync + ) + restored.apply_rows(history, viewport) + attempt.expect( + "replica_after_epoch_recovery", + expected=("base", ""), + actual=tuple(row.text for row in viewport), + ) + + attempt.feed(terminal, "write_second_row", b"\x1b[2;1Hnext") + incremental = terminal.changes_since(restored.token) + attempt.expect( + "incremental_reason", + expected=ResyncReason.NONE, + actual=incremental.resync_reason, + ) + attempt.expect( + "incremental_dirty_rows", expected=(1,), actual=incremental.dirty_rows + ) + incremental.apply_rows(history, viewport) + attempt.expect( + "replica_after_incremental_update", + expected=("base", "next"), + actual=tuple(row.text for row in viewport), + )