From d4d03b3c03787b52a5cbd60ca7a776b84b103f83 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 28 Nov 2026 13:52:26 -0600 Subject: [PATCH] events(feat[notify]): Add OSC notifications (#31) why: Terminal applications emit desktop notifications via iTerm2 OSC 9, chunked Kitty OSC 99, and rxvt OSC 777;notify that callers need as sanitized, bounded, typed Event records. what: - Add NotificationSource, NotificationUrgency, and Notification (in KnownEvent) plus Policy.allow_notifications, Policy.allow_notification_queries, Limits.max_pending_notifications, and Limits.max_notification_bytes - Parse OSC 9 (filtering ConEmu 9;1..9;12), chunked Kitty OSC 99 (raw byte buffering across e=0/e=1 Base64 chunks, d=0/d=1, p=?, u=0..2), and OSC 777;notify in Terminal with C0/C1/DEL sanitization and byte caps - Document and test notification parsing across events, terminal, and docs --- CHANGES | 14 ++ docs/api/events.md | 2 +- docs/topics/protocols-and-input.md | 11 +- src/libvt/config.py | 17 ++ src/libvt/events.py | 87 +++++++++ src/libvt/terminal.py | 298 +++++++++++++++++++++++++++-- tests/test_status.py | 88 +++++++++ tests/test_terminal.py | 13 +- 8 files changed, 505 insertions(+), 25 deletions(-) diff --git a/CHANGES b/CHANGES index e08ec50..1c52fbf 100644 --- a/CHANGES +++ b/CHANGES @@ -140,6 +140,20 @@ prof = Profile( ### What's new +#### Desktop notifications for `OSC 9`, Kitty `OSC 99`, and `OSC 777` (#31) + +{class}`~libvt.terminal.Terminal` parses iTerm2 `OSC 9` (filtering ConEmu +`9;1`–`9;12` subcommands), chunked Kitty `OSC 99` (`d=0`/`d=1`, `e=0`/`e=1` +Base64, `p=title`/`p=body`/`p=?`, `u=0..2`), and rxvt `OSC 777 ; notify` +sequences into sanitized {class}`~libvt.events.Notification` events +({class}`~libvt.events.NotificationSource`, +{class}`~libvt.events.NotificationUrgency`, included in +{type}`~libvt.events.KnownEvent`), gated on +{attr}`~libvt.config.Policy.allow_notifications`, +{attr}`~libvt.config.Policy.allow_notification_queries`, +{attr}`~libvt.config.Limits.max_pending_notifications`, and +{attr}`~libvt.config.Limits.max_notification_bytes`. + #### Stateful `XTSMGRAPHICS` color and geometry registers (#28) {class}`~libvt.terminal.Terminal` implements stateful `XTSMGRAPHICS` diff --git a/docs/api/events.md b/docs/api/events.md index ed0a1fb..4ab59eb 100644 --- a/docs/api/events.md +++ b/docs/api/events.md @@ -8,7 +8,7 @@ .. py:type:: KnownEvent :module: libvt.events - :canonical: Bell | TitleChanged | WorkingDirectoryChanged | ClipboardWrite | ClipboardReadRequested | PromptMark | ShellCommandReported | ShellPropertyChanged | ProgramStatusChanged | RenderHoldChanged | ColorSchemeQueried | InBandResize | SixelGraphic | KittyGraphic | ScreenErased | Passthrough | UnhandledSequence + :canonical: Bell | TitleChanged | WorkingDirectoryChanged | ClipboardWrite | ClipboardReadRequested | PromptMark | ShellCommandReported | ShellPropertyChanged | ProgramStatusChanged | RenderHoldChanged | ColorSchemeQueried | InBandResize | SixelGraphic | KittyGraphic | ScreenErased | Passthrough | Notification | UnhandledSequence Closed union of built-in core :class:`~libvt.events.Event` subclasses for callers opting into static ``typing.assert_never`` exhaustiveness checks. diff --git a/docs/topics/protocols-and-input.md b/docs/topics/protocols-and-input.md index 7b3f296..31b497d 100644 --- a/docs/topics/protocols-and-input.md +++ b/docs/topics/protocols-and-input.md @@ -72,7 +72,8 @@ to {meth}`~libvt.terminal.Terminal.drain_replies` according to active {class}`~libvt.config.Profile` and {class}`~libvt.config.Policy` settings (or stay silent when {attr}`~libvt.config.Policy.emit_replies` is `False` on passive observer streams). Notifications (`OSC 0`/`1`/`2` and `ESC k` title, -`OSC 7` / `9;9` / `633;P` working directory, `OSC 52` +`OSC 7` / `9;9` / `633;P` working directory, `OSC 9` / Kitty `OSC 99` / +`OSC 777;notify` desktop {class}`~libvt.events.Notification` events, `OSC 52` {class}`~libvt.events.ClipboardWrite` events and {class}`~libvt.events.ClipboardReadRequested` queries under {attr}`~libvt.config.ClipboardReadPolicy.EMIT_EVENT` answered via @@ -83,10 +84,10 @@ observer streams). Notifications (`OSC 0`/`1`/`2` and `ESC k` title, to {attr}`Cell.hyperlink `: ```python ->>> term = libvt.Terminal(rows=4, cols=20) ->>> term.feed(b"\x1b[?1;1;0S") ->>> term.drain_replies() -b'\x1b[?1;0;256S' +>>> term = libvt.Terminal(rows=4, cols=20, record_events=True) +>>> term.feed(b"\x1b[?1;1;0S\x1b]99;i=build:u=2:p=title;CI\x1b\\") +>>> term.drain_replies(), term.drain_events()[0].title +(b'\x1b[?1;0;256S', 'CI') ``` ## Keyboard, mouse, and focus encoding diff --git a/src/libvt/config.py b/src/libvt/config.py index 5768a18..2fc3a1e 100644 --- a/src/libvt/config.py +++ b/src/libvt/config.py @@ -391,6 +391,13 @@ class Policy: track_graphics : bool Track ``SIXEL`` and Kitty ``APC G`` image metadata and grid placements (default ``True``). + allow_notifications : bool + Emit :class:`~libvt.events.Notification` events on ``OSC 9``, Kitty + ``OSC 99``, and ``OSC 777;notify`` sequences (default ``True``). + allow_notification_queries : bool + Answer Kitty ``OSC 99`` ``p=?`` capability queries when + ``emit_replies`` and ``allow_notifications`` are ``True`` (default + ``False``). """ emit_replies: bool = True @@ -405,6 +412,8 @@ class Policy: osc7_hosts: frozenset[str] | None = None strict: bool = False track_graphics: bool = True + allow_notifications: bool = True + allow_notification_queries: bool = False @dataclass(frozen=True, slots=True, kw_only=True) @@ -453,6 +462,12 @@ class Limits: max_image_dimension : int Maximum pixel width or height accepted for ``SIXEL`` or Kitty images (default ``10_000``). + max_pending_notifications : int + Maximum concurrent incomplete Kitty ``OSC 99`` (``d=0``) chunked + notifications retained (default ``16``). + max_notification_bytes : int + Maximum cumulative UTF-8 text bytes retained per notification payload + (default ``16_384``). """ max_grapheme_codepoints: int = 32 @@ -471,6 +486,8 @@ class Limits: max_images: int = 256 max_placements: int = 1_024 max_image_dimension: int = 10_000 + max_pending_notifications: int = 16 + max_notification_bytes: int = 16_384 #: Default modern VT500 / ``Ghostty``-aligned terminal profile. diff --git a/src/libvt/events.py b/src/libvt/events.py index fd4756a..d26ab72 100644 --- a/src/libvt/events.py +++ b/src/libvt/events.py @@ -465,6 +465,89 @@ class Passthrough(Event): data: bytes +class NotificationSource(enum.StrEnum): + """Protocol origin of a :class:`Notification` event. + + References + ---------- + - `Kitty Desktop Notification Protocol (OSC 99) + `__ + + Examples + -------- + >>> from libvt.events import NotificationSource + >>> NotificationSource.OSC_99.value + 'osc_99' + """ + + OSC_9 = "osc_9" + OSC_99 = "osc_99" + OSC_777 = "osc_777" + + +class NotificationUrgency(enum.StrEnum): + """Desktop notification urgency level (Kitty ``OSC 99`` ``u=0/1/2``). + + References + ---------- + - `Kitty Desktop Notification Protocol (OSC 99) — Urgency + `__ + + Examples + -------- + >>> from libvt.events import NotificationUrgency + >>> NotificationUrgency.HIGH.value + 'high' + """ + + LOW = "low" + NORMAL = "normal" + HIGH = "high" + + +@dataclass(frozen=True, slots=True, kw_only=True, match_args=False) +class Notification(Event): + r"""Emitted when ``OSC 9``, Kitty ``OSC 99``, or ``OSC 777`` notifies. + + Attributes + ---------- + source : NotificationSource + Originating escape protocol (``OSC_9``, ``OSC_99``, or ``OSC_777``). + title : str + Sanitized notification title (``""`` for ``OSC 9`` body-only messages). + body : str + Sanitized notification body text. + notification_id : str + Optional notification identifier from Kitty ``OSC 99`` ``i=`` metadata. + urgency : NotificationUrgency + Urgency level (``LOW``, ``NORMAL``, or ``HIGH``; defaults to ``NORMAL``). + + References + ---------- + - `Kitty Desktop Notification Protocol (OSC 99) + `__ + - `ghostty-org/ghostty kitty_desktop_notification.zig (v1.4.0) + `__ + - `ghostty-org/ghostty rxvt_extension.zig (v1.4.0) + `__ + + Examples + -------- + >>> from libvt.terminal import Terminal + >>> term = Terminal(record_events=True) + >>> term.feed(b"\x1b]777;notify;Build;All green\x07") + >>> ev = term.drain_events()[0] + >>> (ev.source.value, ev.title, ev.body) + ('osc_777', 'Build', 'All green') + """ + + source: NotificationSource + title: str = "" + body: str = "" + notification_id: str = "" + urgency: NotificationUrgency = NotificationUrgency.NORMAL + + @dataclass(frozen=True, slots=True, kw_only=True, match_args=False) class UnhandledSequence(Event): """Recorded when an unrecognized control sequence arrives and ``strict=False``. @@ -498,6 +581,7 @@ class UnhandledSequence(Event): | KittyGraphic | ScreenErased | Passthrough + | Notification | UnhandledSequence ) @@ -513,6 +597,9 @@ class UnhandledSequence(Event): "KittyCommand", "KittyGraphic", "KnownEvent", + "Notification", + "NotificationSource", + "NotificationUrgency", "Passthrough", "ProgramStatusChanged", "PromptKind", diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index 6e787bf..2046fe2 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -67,6 +67,9 @@ KittyCommand, KittyGraphic, KnownEvent, + Notification, + NotificationSource, + NotificationUrgency, Passthrough, ProgramStatusChanged, PromptKind, @@ -1310,6 +1313,7 @@ def _utf8_len(text: str) -> int: ColorSchemeQueried, InBandResize, KittyGraphic, + Notification, Passthrough, ProgramStatusChanged, PromptMark, @@ -1414,6 +1418,13 @@ def _known_event_byte_cost(event: KnownEvent) -> int: return 64 + _utf8_len(event.selection) + _utf8_len(event.text) if isinstance(event, ClipboardReadRequested): return 64 + _utf8_len(event.selection) + if isinstance(event, Notification): + return ( + 64 + + _utf8_len(event.notification_id) + + _utf8_len(event.title) + + _utf8_len(event.body) + ) if isinstance(event, TitleChanged): return 64 + _utf8_len(event.title) if isinstance(event, WorkingDirectoryChanged): @@ -1828,6 +1839,10 @@ def __init__( self._status_store = ProgramStatusStore( max_records=limits.max_status_records, ) + self._pending_osc99: dict[ + str, + tuple[bytearray, bytearray, NotificationUrgency, int], + ] = {} self._replies = bytearray() @classmethod @@ -2965,6 +2980,7 @@ def reset(self, *, soft: bool = False) -> None: self._cwd = "" self._cwd_uri = "" self._status_store.reset() + self._pending_osc99.clear() self._aux_revision += 1 self._notify_erase( Rect(0, 0, self.rows, self.cols), @@ -5615,6 +5631,222 @@ def _record_prompt_mark( ProgramStatusChanged(status=self._status_store.most_urgent), ) + @staticmethod + def _cap_sanitized_bytes( + raw: bytes | bytearray, + max_bytes: int, + ) -> tuple[str, int]: + r"""Decode, sanitize, and cap *raw* UTF-8 bytes to at most *max_bytes*. + + Examples + -------- + >>> from libvt.terminal import Terminal + >>> Terminal._cap_sanitized_bytes(b"ok\x01", 6) + ('ok\\x01', 6) + >>> Terminal._cap_sanitized_bytes(b"ok\x01", 5) + ('ok', 2) + """ + if max_bytes <= 0 or not raw: + return ("", 0) + decoded = bytes(raw[:max_bytes]).decode("utf-8", errors="ignore") + sanitized = sanitize_terminal_text(decoded) + enc = sanitized.encode("utf-8") + if len(enc) <= max_bytes: + return (sanitized, len(enc)) + out: list[str] = [] + used = 0 + for ch in decoded: + frag = sanitize_terminal_text(ch) + cost = len(frag.encode("utf-8")) + if used + cost > max_bytes: + break + out.append(frag) + used += cost + return ("".join(out), used) + + def _handle_osc_777(self, data: bytes) -> None: + r"""Parse ``OSC 777 ; notify ; ; <body>`` desktop notifications. + + References + ---------- + - `ghostty-org/ghostty rxvt_extension.zig (v1.4.0) + <https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/terminal/osc/parsers/rxvt_extension.zig#L8-L45>`__ + + Examples + -------- + >>> from libvt.terminal import Terminal + >>> term = Terminal(record_events=True) + >>> term.feed(b"\x1b]777;notify;Alert;Done\x07") + >>> term.drain_events()[0].title + 'Alert' + """ + if not self._policy.allow_notifications: + return + k = data.find(b";") + if k == -1 or data[:k] != b"notify": + return + t_sep = data.find(b";", k + 1) + if t_sep == -1: + return + max_nb = max(0, self._limits.max_notification_bytes) + title_s, title_used = self._cap_sanitized_bytes(data[k + 1 : t_sep], max_nb) + body_s, _ = self._cap_sanitized_bytes( + data[t_sep + 1 :], + max(0, max_nb - title_used), + ) + if not title_s and not body_s: + return + self._emit_event( + Notification( + source=NotificationSource.OSC_777, + title=title_s, + body=body_s, + ), + ) + + def _handle_osc_99(self, data: bytes, out_term: bytes) -> None: + r"""Parse Kitty ``OSC 99 ; <metadata> ; <payload>`` desktop notifications. + + Supports ``i=`` identifiers, ``d=0``/``1`` multi-chunk reassembly + bounded by :attr:`~libvt.config.Limits.max_pending_notifications` and + :attr:`~libvt.config.Limits.max_notification_bytes`, ``e=1`` Base64 + decoding, ``p=title``/``body``/``?``/``close``/``alive``, and + ``u=0``/``1``/``2`` urgency levels. + + References + ---------- + - `Kitty Desktop Notification Protocol (OSC 99) + <https://sw.kovidgoyal.net/kitty/desktop-notifications/>`__ + - `ghostty-org/ghostty kitty_desktop_notification.zig (v1.4.0) + <https://github.com/ghostty-org/ghostty/blob/v1.4.0/src/terminal/osc/parsers/kitty_desktop_notification.zig#L287-L335>`__ + + Examples + -------- + >>> from libvt.terminal import Terminal + >>> term = Terminal(record_events=True) + >>> term.feed(b"\x1b]99;i=n1:d=0:p=title;Hi\x1b\\") + >>> term.feed(b"\x1b]99;i=n1:d=1:p=body;Ok\x1b\\") + >>> ev = term.drain_events()[0] + >>> (ev.notification_id, ev.title, ev.body) + ('n1', 'Hi', 'Ok') + """ + if not self._policy.allow_notifications: + return + sep = data.find(b";") + if sep == -1 or not data[:sep].isascii(): + return + meta_s = data[:sep].decode("ascii") + payload_b = data[sep + 1 :] + + notif_id = "" + done = True + b64 = False + ptype = "title" + urgency: NotificationUrgency | None = None + if meta_s: + for item in meta_s.split(":"): + eq = item.find("=") + if eq == -1: + continue + key = item[:eq] + val = item[eq + 1 :] + if key == "i": + if val and all( + "a" <= ch <= "z" + or "A" <= ch <= "Z" + or "0" <= ch <= "9" + or ch in "-_+." + for ch in val + ): + notif_id = val[:128] + elif key == "d": + done = val != "0" + elif key == "e": + b64 = val == "1" + elif key == "p": + ptype = val or "unknown" + elif key == "u": + if val == "0": + urgency = NotificationUrgency.LOW + elif val == "1": + urgency = NotificationUrgency.NORMAL + elif val == "2": + urgency = NotificationUrgency.HIGH + + if ptype == "?": + if self._policy.allow_notification_queries: + qid = notif_id or "0" + reply = ( + f"\x1b]99;i={qid}:p=?;p=title,body:a=focus:u=0,1,2".encode("ascii") + + out_term + ) + self._emit_reply(reply) + return + + if ptype in ("close", "alive"): + self._pending_osc99.pop(notif_id, None) + return + + max_nb = max(0, self._limits.max_notification_bytes) + max_pend = max(0, self._limits.max_pending_notifications) + entry = self._pending_osc99.get(notif_id) + if entry is None: + title_buf = bytearray() + body_buf = bytearray() + cur_urg = urgency if urgency is not None else NotificationUrgency.NORMAL + used = 0 + else: + title_buf, body_buf, prev_urg, used = entry + cur_urg = urgency if urgency is not None else prev_urg + + rem = max(0, max_nb - used) + if ptype in ("title", "body"): + if b64: + cleaned = payload_b.strip(b" \t\r\n") + if len(cleaned) % 4 == 1: + return + padded = cleaned + (b"=" * ((-len(cleaned)) % 4)) + try: + decoded_b = ( + base64.b64decode(padded, validate=True) if rem > 0 else b"" + ) + except binascii.Error: + return + else: + decoded_b = payload_b + chunk_b = decoded_b[:rem] + used += len(chunk_b) + if ptype == "body": + body_buf.extend(chunk_b) + else: + title_buf.extend(chunk_b) + + if not done: + if max_pend > 0: + if ( + notif_id not in self._pending_osc99 + and len(self._pending_osc99) >= max_pend + ): + oldest_key = next(iter(self._pending_osc99)) + self._pending_osc99.pop(oldest_key, None) + self._pending_osc99[notif_id] = (title_buf, body_buf, cur_urg, used) + return + + self._pending_osc99.pop(notif_id, None) + title_s, title_used = self._cap_sanitized_bytes(title_buf, max_nb) + body_s, _ = self._cap_sanitized_bytes(body_buf, max(0, max_nb - title_used)) + if not title_s and not body_s: + return + self._emit_event( + Notification( + source=NotificationSource.OSC_99, + notification_id=sanitize_terminal_text(notif_id), + title=title_s, + body=body_s, + urgency=cur_urg, + ), + ) + def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: self._last_printed = "" out_term = b"\x07" if terminator == b"\x07" else b"\x1b\\" @@ -5702,23 +5934,53 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: elif code == 9: text = data.decode("utf-8", errors="replace") parts = text.split(";") - if len(parts) >= 2 and parts[0] == "4": - sub = _parse_ascii_uint(parts[1], max_val=255) - if sub is not None: - self._before_mutate() - prog = ( - _parse_ascii_uint(parts[2], max_val=1_000) - if len(parts) >= 3 - else None - ) - changed, status = self._status_store.apply_osc_9_4(sub, prog) - if changed: - self._aux_revision += 1 - self._emit_event( - ProgramStatusChanged(status=status, task_id="") - ) + if ( + len(parts) >= 2 + and parts[0] == "4" + and parts[1] + in ( + "0", + "1", + "2", + "3", + "4", + ) + ): + sub = int(parts[1]) + self._before_mutate() + prog = ( + _parse_ascii_uint(parts[2], max_val=1_000) + if len(parts) >= 3 + else None + ) + changed, status = self._status_store.apply_osc_9_4(sub, prog) + if changed: + self._aux_revision += 1 + self._emit_event(ProgramStatusChanged(status=status, task_id="")) elif len(parts) >= 2 and parts[0] == "9": self._update_cwd(";".join(parts[1:]), source=CwdSource.OSC_9_9) + elif ( + (len(parts) == 1 and parts[0] in ("5", "10", "12")) + or ( + len(parts) == 2 + and parts[0] == "10" + and parts[1] in ("0", "1", "2", "3") + ) + or ( + len(parts) >= 2 and parts[0] in ("1", "2", "3", "6", "7", "8", "11") + ) + ): + return + elif data and self._policy.allow_notifications: + max_nb = max(0, self._limits.max_notification_bytes) + body_s, _ = self._cap_sanitized_bytes(data, max_nb) + if body_s: + self._emit_event( + Notification( + source=NotificationSource.OSC_9, + body=body_s, + ), + ) elif code in (10, 11, 12): if not data: return @@ -5772,8 +6034,10 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: self._guest_cursor_rgb = parsed_rgb self._bump_appearance() cur_code += 1 - elif code in (99, 777): - return + elif code == 99: + self._handle_osc_99(data, out_term) + elif code == 777: + self._handle_osc_777(data) elif code == 104: if not self._guest_palette: return diff --git a/tests/test_status.py b/tests/test_status.py index 98ec983..58c413d 100644 --- a/tests/test_status.py +++ b/tests/test_status.py @@ -472,3 +472,91 @@ def test_passive_observer_policy_clipboard_read_event_and_ground_state() -> None strict_t = libvt.Terminal(rows=2, cols=10, policy=Policy(strict=True)) strict_t.feed(b"\x1b[1;1;1;1;2;2*y") assert strict_t.drain_replies() == b"" + + +def test_osc_9_osc_99_and_osc_777_notifications() -> None: + """``OSC 9``, Kitty ``OSC 99``, and ``OSC 777`` emit bounded ``Notification``.""" + from libvt.events import ( + KnownEvent, + Notification, + NotificationSource, + NotificationUrgency, + ) + from libvt.terminal import _KNOWN_EVENT_TYPES + + assert frozenset(t.get_args(KnownEvent.__value__)) == _KNOWN_EVENT_TYPES + + term = libvt.Terminal( + rows=2, + cols=20, + policy=Policy(strict=True, allow_notification_queries=True), + limits=Limits(max_pending_notifications=2, max_notification_bytes=64), + record_events=True, + ) + term.feed(b"\x1b]9;Build \xe2\x80\xaesucceeded\x07") + term.feed( + b"\x1b]9;4;1;50\x07\x1b]9;9;/tmp\x07" + b"\x1b]9;1;100\x07\x1b]9;5\x07\x1b]9;10;1\x07" + b"\x1b]9;5;warnings\x07\x1b]9;10;abc\x07\x1b]9;4;foo\x07" + ) + term.feed(b"\x1b]777;notify;CI;step 1; step 2\x1b\\") + # Split multi-byte UTF-8 across two unpadded e=1 chunks + d=1:p=icon: + jp_bytes = "日本".encode() + c1_b64 = base64.b64encode(jp_bytes[:4]).decode("ascii").rstrip("=") + c2_b64 = base64.b64encode(jp_bytes[4:]).decode("ascii").rstrip("=") + term.feed(f"\x1b]99;i=job-1:d=0:e=1:p=title:u=2;{c1_b64}\x1b\\".encode("ascii")) + term.feed(f"\x1b]99;i=job-1:d=0:e=1:p=title;{c2_b64}\x1b\\".encode("ascii")) + term.feed(b"\x1b]99;i=job-1:d=0:p=body;v1.0 live\x1b\\") + term.feed(b"\x1b]99;i=job-1:d=1:p=icon;ignored-icon\x1b\\") + # Anonymous (omitted i=) d=0 -> d=1 reassembly: + term.feed(b"\x1b]99;d=0;AnonTitle\x1b\\\x1b]99;d=1:p=body;AnonBody\x1b\\") + # Capability query echoes BEL vs ST: + term.feed(b"\x1b]99;i=q1:p=?;?\x07\x1b]99;i=q2:p=?;?\x1b\\") + + evs = [e for e in term.drain_events() if isinstance(e, Notification)] + assert evs == [ + Notification(source=NotificationSource.OSC_9, body="Build \\u202esucceeded"), + Notification(source=NotificationSource.OSC_9, body="5;warnings"), + Notification(source=NotificationSource.OSC_9, body="10;abc"), + Notification(source=NotificationSource.OSC_9, body="4;foo"), + Notification( + source=NotificationSource.OSC_777, title="CI", body="step 1; step 2" + ), + Notification( + source=NotificationSource.OSC_99, + notification_id="job-1", + title="日本", + body="v1.0 live", + urgency=NotificationUrgency.HIGH, + ), + Notification( + source=NotificationSource.OSC_99, + title="AnonTitle", + body="AnonBody", + ), + ] + assert term.cwd == "/tmp" + assert term.program_status is not None + replies = term.drain_replies() + assert replies.startswith(b"\x1b]99;i=q1:p=?;") + assert b"\x07\x1b]99;i=q2:p=?;" in replies and replies.endswith(b"\x1b\\") + + # RIS clears pending chunks; C0 escapes stay within max_notification_bytes: + cap_t = libvt.Terminal( + limits=Limits(max_pending_notifications=1, max_notification_bytes=10), + record_events=True, + ) + cap_t.feed( + b"\x1b]99;i=stale:d=0;Stale\x1b\\\x1bc\x1b]99;i=stale:d=1:p=body;Fresh\x1b\\" + ) + cap_t.feed(b"\x1b]9;" + (b"\x01" * 10) + b"\x07") + cap_evs = [e for e in cap_t.drain_events() if isinstance(e, Notification)] + assert (cap_evs[0].title, cap_evs[0].body) == ("", "Fresh") + assert len(cap_evs[1].body.encode("utf-8")) <= 10 + + muted = libvt.Terminal( + policy=Policy(allow_notifications=False), + record_events=True, + ) + muted.feed(b"\x1b]9;hi\x07\x1b]777;notify;t;b\x07\x1b]99;;hi\x1b\\") + assert muted.drain_events() == () diff --git a/tests/test_terminal.py b/tests/test_terminal.py index 959c91c..5e00cbf 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -945,14 +945,23 @@ def test_osc_palette_dynamic_colors_decrqm_xtsmgraphics_and_notifications() -> N term.resize(rows=10, cols=40) assert term.drain_replies() == b"\x1b[48;10;40;160;320t" - # OSC 9 (text), OSC 99, and OSC 777 consume silently under Policy(strict=True). + # OSC 9 (text), OSC 99, and OSC 777 emit Notification under Policy(strict=True). + from libvt.events import Notification, NotificationSource + term.drain_events() term.feed( b"\x1b]9;Desktop alert\x07" b"\x1b]99;i=1:d=0;Hello\x1b\\" b"\x1b]777;notify;Build;Done\x07" ) - assert term.drain_events() == () + assert term.drain_events() == ( + Notification(source=NotificationSource.OSC_9, body="Desktop alert"), + Notification( + source=NotificationSource.OSC_777, + title="Build", + body="Done", + ), + ) def test_profile_capability_groups_hashable_queries_and_ris_alt_screen() -> None: