From 017fdcfce774599299f22b6605e4508d6911c352 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Thu, 19 Nov 2026 21:58:45 -0500 Subject: [PATCH] Chat shows an MCOimg pixel image as a short line instead of Base91 noise MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A message whose body is an MCOimg image (im3:, or im: for v1/v2) now reads "🎨 image · 24×24 · 16 colours" in the transcript and the Messages preview. The v3 header gives the size and the palette; the pixels are not decoded yet. The Base91 text no longer makes false mention chips, links, or QR codes. Checked against all 51 reference vectors. Refs #37. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/development/writing-style.md | 1 + meshterm/core/mcoimg.py | 183 ++++++++++++++++++++++++++++++ meshterm/tools/chat.py | 17 ++- meshterm/ui/chat.py | 30 +++-- meshterm/ui/theme.py | 1 + meshterm/ui/widgets.py | 30 +++++ tests/test_chat.py | 17 +++ tests/test_mcoimg.py | 63 ++++++++++ 9 files changed, 334 insertions(+), 10 deletions(-) create mode 100644 meshterm/core/mcoimg.py create mode 100644 tests/test_mcoimg.py diff --git a/CLAUDE.md b/CLAUDE.md index 1f6afd5..9b0f211 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -556,7 +556,7 @@ as a grouped list does. Filling a page in is editing its `.md`; no Python follow 📤 send now · 📨 courier/queue · 💬 chat · 🔔 notify · 🔕 mute (notifications off) · 📱 QR · 🔗 link · ↻ re-read · ↕ reorder · ⇄ reverse (flip a path's direction) · 🔖 region/scope · 📌 rooms · 🏆 trophy case/record · ⌨ command line · 📖 read/about · 💰 support/donate · - 🚪 quit. Packet-class icons (feed/viewer + 🎨 pixel image (an MCOimg picture in a message) · 🚪 quit. Packet-class icons (feed/viewer lane): 📢 advert · 📊 telemetry · 📦 packet · 💬 message · ✅ ack. Raw payload classes (`PAYLOAD_ICONS`): 📻 channel text · 💽 channel data · 📩 direct message (overheard) · 📥 request · 📮 response · 🎭 anon request · 🧭 path · 🎯 trace · diff --git a/docs/development/writing-style.md b/docs/development/writing-style.md index 8d57647..54db11b 100644 --- a/docs/development/writing-style.md +++ b/docs/development/writing-style.md @@ -204,6 +204,7 @@ and in quoted text. | packet | One radio transmission | frame (for radio data) | | protocol frame | One unit of the companion protocol on USB, Bluetooth, or TCP: a command, a reply, or a push from the companion. In code that handles only this protocol, "frame" alone is permitted | packet (for this) | | message | A text message, direct or on a channel | | +| pixel image | A very small picture in the MCOimg format that a message carries as text (`im3:` and Base91 characters) | picture, MCOimg image | | sender time | The time that a message or an advert carries, from the clock of the node that sent it. It is a claim, and a node with a wrong clock makes it false | timestamp (alone) | | arrival time | Our clock when MeshTerm got a received message from the companion (`received_at`) | receive time | | clock offset | The sender time minus the arrival time. A positive offset is a clock ahead of ours. The offset of a node is the median of its three newest clock samples | skew, drift (for this) | diff --git a/meshterm/core/mcoimg.py b/meshterm/core/mcoimg.py new file mode 100644 index 0000000..17ba985 --- /dev/null +++ b/meshterm/core/mcoimg.py @@ -0,0 +1,183 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Recognize a pixel image in the body of a message: the MCOimg format. + +MCOimg is a format for very small pictures (1 to 256 pixels for each side, in practice 10 +to 30) that some MeshCore apps send on a channel. Each image is one packet. As a text +message, it is a prefix and then Base91 text: ``im:`` for the versions 1 and 2, ``im3:`` +for version 3. A client that does not know the format shows that text as noise. The +reference is ``docs/mcoimg_v3_reference.md`` in the HDDen/meshcore-open repository (MIT). + +This module does not decode the pixels. It finds that a body is an image, and for a +version 3 image it reads the header: the size and the number of colours of the palette. +Thus the chat can show a short line in place of the noise. + +Version 3 data, after the Base91 decode:: + + 0x13 subtype 1 (MCOimg) in the high nibble, revision 3 in the low + nonce: u8 changes with each send, and has no meaning for the picture + header: u8 bit 7 transparent, bit 6 white background, bits 5..4 scan, + bits 3..0 palette profile + dimensions bit-packed, LSB first (refer to :func:`_dimensions`) + ... the pixels, which this module does not read +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass + +#: The Base91 alphabet of MCOimg, in the order of its values. It is the alphabet of +#: basE91, which has no space, no ``'``, no ``-``, and no ``\\``. +_ALPHABET = ( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + '!#$%&()*+,./:;<=>?@[]^_`{|}~"' +) +_VALUE = {char: index for index, char in enumerate(_ALPHABET)} + +#: A body that is an image: the prefix and one word of Base91 text. The version digit is +#: optional, because the versions 1 and 2 use ``im:``. +_IMAGE = re.compile(r"im(\d?):(\S+)") + +#: The shortest Base91 text that MeshTerm accepts as an image of a version whose header it +#: cannot read. The smallest such image of the reference tests has 11 characters. A +#: shorter word after ``im:`` is more probably words that a person typed. A version 3 image +#: needs no minimum, because its first byte and its header must be correct. +_MIN_TEXT = 8 + +#: The first byte of a version 3 image: subtype 1 (MCOimg), revision 3. +_V3 = 0x13 + +#: The number of colours of each palette profile of version 3, by profile id. The ids +#: 0 to 5 are the master palettes, 6 to 8 are the grey palettes, and 9 to 15 are the +#: dynamic palettes (subsets of the global palette of 512 colours). +_PROFILE_COLOURS = (2, 4, 8, 16, 32, 64, 16, 32, 8, 8, 16, 32, 64, 128, 256, 512) + + +@dataclass(frozen=True) +class PixelImage: + """What a message body tells about the pixel image that it carries. + + Attributes: + version: The format version: 3 for ``im3:``, or ``None`` for ``im:``, which is + version 1 or 2 (its text does not say which). + width: The width in pixels, or ``None`` when MeshTerm cannot read the header. + height: The height in pixels, or ``None`` when MeshTerm cannot read the header. + colours: The number of colours of the palette, or ``None`` when MeshTerm cannot + read the header. + """ + + version: int | None + width: int | None = None + height: int | None = None + colours: int | None = None + + +def recognize(body: str) -> PixelImage | None: + """Return the pixel image that ``body`` carries, or ``None`` when it is not an image. + + The body must be the image and nothing else (spaces at the ends are permitted). An + ``im3:`` body must also start with the version 3 byte after the decode. A body with a + version that MeshTerm does not know (``im4:``) is an image with no header. + + Args: + body: The text of a message, without the ``Name: `` of a channel sender. + + Returns: + The image, or ``None``. + """ + match = _IMAGE.fullmatch(body.strip()) + if match is None: + return None + digit, text = match.groups() + data = base91_decode(text) + if data is None: + return None + version = int(digit) if digit else None + if version != 3: + # Here MeshTerm cannot read a header, so only the length makes the claim. + return PixelImage(version=version) if len(text) >= _MIN_TEXT else None + if len(data) < 4 or data[0] != _V3: + return None + header = data[2] + size = _dimensions(_Bits(data[3:])) + if size is None: + return PixelImage(version=3) + width, height = size + return PixelImage(3, width, height, _PROFILE_COLOURS[header & 0x0F]) + + +def base91_decode(text: str) -> bytes | None: + """Decode the Base91 text of an image, or return ``None`` for a character not in it. + + Each pair of characters holds 13 or 14 bits: 13 when the low 13 bits of the pair are + more than 88, or else 14. A last single character holds the remaining bits. + """ + out = bytearray() + queue = bits = 0 + value = -1 + for char in text: + index = _VALUE.get(char) + if index is None: + return None + if value < 0: + value = index + continue + value += index * 91 + queue |= value << bits + bits += 13 if (value & 8191) > 88 else 14 + while bits > 7: + out.append(queue & 0xFF) + queue >>= 8 + bits -= 8 + value = -1 + if value >= 0: + out.append((queue | (value << bits)) & 0xFF) + return bytes(out) + + +class _Bits: + """A reader of bit fields, LSB first, from a byte string.""" + + def __init__(self, data: bytes) -> None: + self._value = int.from_bytes(data, "little") + self._left = len(data) * 8 + self._pos = 0 + + def read(self, count: int) -> int | None: + """The next ``count`` bits as an unsigned number, or ``None`` past the end.""" + if self._pos + count > self._left: + return None + value = (self._value >> self._pos) & ((1 << count) - 1) + self._pos += count + return value + + +def _dimensions(bits: _Bits) -> tuple[int, int] | None: + """Read the width and the height of a version 3 image, or ``None`` past the end. + + The first two bits are the mode. Each mode stores the sizes minus one: + + - 0: a square up to 64, one width of 6 bits. + - 1: up to 32 × 32, a width and a height of 5 bits each. + - 2: up to 64 × 64, a width and a height of 6 bits each. + - 3: up to 256 × 256. One bit is set for a rectangle. Then there is a width of 8 bits, + and for a rectangle a height of 8 bits. + """ + mode = bits.read(2) + if mode == 0: + side = bits.read(6) + return None if side is None else (side + 1, side + 1) + if mode in (1, 2): + size = 5 if mode == 1 else 6 + width, height = bits.read(size), bits.read(size) + elif mode == 3: + rectangle = bits.read(1) + if rectangle is None: + return None + width = bits.read(8) + height = bits.read(8) if rectangle else width + else: + return None + if width is None or height is None: + return None + return width + 1, height + 1 diff --git a/meshterm/tools/chat.py b/meshterm/tools/chat.py index 6ed1863..d645432 100644 --- a/meshterm/tools/chat.py +++ b/meshterm/tools/chat.py @@ -27,7 +27,7 @@ from rich.cells import cell_len from rich.text import Text from ..context import AppContext -from ..core import exitcodes +from ..core import exitcodes, mcoimg from ..core.channels import ( CHANNEL_SLOT_PROBE_CAP, DEFAULT_PUBLIC_SECRET, @@ -71,6 +71,7 @@ from ..ui.widgets import ( format_age, mention_chip, mention_mark, + pixel_image_text, self_chip, ) from .base import Tool, ToolResult, register @@ -1191,7 +1192,14 @@ def _append_body( refer to :func:`~meshterm.ui.widgets.mention_chip`). It takes the node grey when the name resolves to no node that we know. A mention of our own name (``us``) has the chip of our key with a white label, as in the transcript. + + A body that is a pixel image shows the short line of the transcript in place of its + Base91 text (refer to :func:`~meshterm.ui.widgets.pixel_image_text`). """ + image = mcoimg.recognize(body) + if image is not None: + text.append_text(pixel_image_text(image)) + return pos = 0 for match in MENTION.finditer(body): if match.start() > pos: @@ -1209,7 +1217,12 @@ def _append_body( def _names_us(last: ChatMessage, us: tuple[str | None, str | None]) -> bool: """Whether the message ``last`` has a mention of our name (``us``).""" name = us[0] - return bool(name) and any(match.group(1) == name for match in MENTION.finditer(last.text)) + if not name: + return False + body = split_channel_sender(last.text)[1] if last.is_channel and not last.outbound else last.text + if mcoimg.recognize(body) is not None: + return False # the Base91 text of an image can hold an ``@[`` by chance + return any(match.group(1) == name for match in MENTION.finditer(body)) def _ago(when: Any) -> str: diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index f90b216..c18fe4d 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -25,7 +25,7 @@ from rich.cells import cell_len from rich.console import Group, RenderableType from rich.text import Text -from ..core import links +from ..core import links, mcoimg from ..core.channels import MENTION, split_channel_sender from ..core.connection import ContactNotOnDeviceError from ..core.events import EventKind, MeshEvent @@ -61,6 +61,7 @@ from .widgets import ( mention_hop, mention_mark, picked_hop, + pixel_image_text, self_chip, ) @@ -912,10 +913,11 @@ class ChatScreen(Screen): """ tolerance = self._tolerance_s corrected = message.corrected(tolerance) + image = mcoimg.recognize(body) stamp = message.shown_at(tolerance).astimezone() prefix = Text() prefix.append("❯ " if selected else " ", style="cursor" if selected else None) - if self._names_us(body): + if image is None and self._names_us(body): prefix.append_text(mention_mark(self._self_key)) prefix.append(" ") else: @@ -926,7 +928,7 @@ class ChatScreen(Screen): else: prefix.append(" ") prefix.append(" ") - body_text = self._body_text(body, message, selected=selected) + body_text = self._body_text(body, message, selected=selected, image=image) whole = [m.span() for m in _WORD.finditer(body_text.plain) if links.urls(m.group())] # A mention is a chip, and a chip never breaks across two lines. whole += [(s.start, s.end) for s in body_text.spans if str(s.style) == PATH_INK] @@ -943,14 +945,28 @@ class ChatScreen(Screen): ) indent = prefix.cell_len lines += render_hanging(Text(" " * indent), note, width, indent=indent) - urls = links.urls(body) if _URL_CODES else [] + urls = links.urls(body) if _URL_CODES and image is None else [] if urls: lines += render_lines(qr_strip(urls, width, indent=prefix.cell_len), width) return lines - def _body_text(self, body: str, message: ChatMessage, *, selected: bool) -> Text: - """Build the styled body of a message: mentions in colour, then the glyphs at the end.""" - text = self._render_mentions(body, selected=selected) + def _body_text( + self, + body: str, + message: ChatMessage, + *, + selected: bool, + image: mcoimg.PixelImage | None = None, + ) -> Text: + """Build the styled body of a message: mentions in colour, then the glyphs at the end. + + A body that is a pixel image (``image``) shows a short line in place of its Base91 + text (refer to :func:`~meshterm.ui.widgets.pixel_image_text`). + """ + if image is not None: + text = pixel_image_text(image, style="cursor" if selected else "muted") + else: + text = self._render_mentions(body, selected=selected) if message.outbound: # A direct message shows its own delivery (spinner → ✓/✗, and a retry is # possible). A channel broadcast has no ack. Thus mark only a channel message diff --git a/meshterm/ui/theme.py b/meshterm/ui/theme.py index e7c9f9f..f83bd7f 100644 --- a/meshterm/ui/theme.py +++ b/meshterm/ui/theme.py @@ -852,6 +852,7 @@ _GLYPH_MAP: dict[str, str] = { "🔔": "•", # notify: the badge dot "🔕": "·", # mute: the hollowed-out dot "📱": "▓", # QR: a dense block + "🎨": "░", # pixel image (MCOimg): a fine grid of dots "🔗": "&", # link: the joining glyph "🏆": "★", # trophy case: the best/winner star "⌨": "❯", # command line: the prompt pointer diff --git a/meshterm/ui/widgets.py b/meshterm/ui/widgets.py index 5c17c06..3a59d92 100644 --- a/meshterm/ui/widgets.py +++ b/meshterm/ui/widgets.py @@ -64,6 +64,7 @@ from .theme import glyph, mark_rgb, name_style, node_style, snr_style if TYPE_CHECKING: from ..core.discovery import DiscoveredDevice + from ..core.mcoimg import PixelImage from ..core.regions import Scope @@ -98,6 +99,35 @@ def channel_glyph(name: str, secret: bytes | None) -> str: #: The concept icon for a region (the scope of a flood). Refer to the icon table of ``CLAUDE.md``. REGION_ICON = "🔖" +#: The concept icon for a pixel image in a message (MCOimg). It is the palette of pixel +#: art. ``🖼`` is not used, because it is a text character by default and terminals do +#: not agree about its width. +IMAGE_ICON = "🎨" + + +def pixel_image_text(image: PixelImage, *, style: str | None = "muted") -> Text: + """The short line that a message shows in place of the Base91 text of a pixel image. + + The Base91 text is noise to the user. Its ``@[``, ``]``, and ``.`` characters can also + look like a mention or a link. Thus the chat and the Messages list show this line in + its place: ``🎨 image · 24×24 · 16 colours`` when MeshTerm can read the header of the + image, or else the version of the format. + + Args: + image: The image that :func:`~meshterm.core.mcoimg.recognize` found in the body. + style: The style of the line: ``muted``, or ``cursor`` on the selected message. + """ + parts = [f"{glyph(IMAGE_ICON)} image"] + if image.width is not None and image.height is not None: + parts.append(f"{image.width}×{image.height}") + if image.colours is not None: + parts.append(f"{image.colours} colours") + elif image.version is None: + parts.append("MCOimg v1/v2") + else: + parts.append(f"MCOimg v{image.version}") + return Text(" · ".join(parts), style=style) + def scope_text(scope: Scope | None, *, bare: bool = False) -> Text: """The only rendering of the scope of a flood, for each surface that states one. diff --git a/tests/test_chat.py b/tests/test_chat.py index 1ebdd0d..6b5d497 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -490,6 +490,12 @@ def test_preview_draws_the_author_and_the_mentions_as_the_transcript_does(powerl assert _preview_text(named, _NO_KEYS, us=us).plain == f"{author} hi {me}" +def test_preview_shows_a_pixel_image_as_a_short_line() -> None: + """The Base91 text of an MCOimg image is noise, so the preview shows what it is.""" + image = ChatMessage(text="Bob: im3:g/5WjAL`NA", is_channel=True, channel_idx=0) + assert _preview_text(image, _NO_KEYS).plain.endswith("image · 4×2 · 4 colours") + + def test_preview_keeps_the_whole_message() -> None: """The preview is built whole. The cut of the row is the part that the ←→ scroll passes.""" long = ChatMessage(text="x" * 300, is_channel=True, channel_idx=0) @@ -972,6 +978,17 @@ def test_chat_screen_shows_delivery_glyphs() -> None: assert "^R" in screen.footer_hint +def test_a_pixel_image_shows_a_short_line_not_its_text() -> None: + """A body that is an MCOimg image shows its size in place of its Base91 text.""" + text = "im3:g/5WjAL`NA" + messages = [ChatMessage(text=text, peer="d4e5f6a7")] + screen = _screen(_StubSession(), send=None, messages=messages) + lines = [_strip_ansi(ln) for ln in screen._body_lines(text, messages[0], 60)] + assert len(lines) == 1 + assert lines[0].endswith("image · 4×2 · 4 colours") + assert "g/5W" not in lines[0] + + def test_wrapped_body_hangs_under_the_first_line() -> None: """A body that is too long for the width wraps with a hanging indent under its first line.""" from datetime import datetime, timezone diff --git a/tests/test_mcoimg.py b/tests/test_mcoimg.py new file mode 100644 index 0000000..6b299e9 --- /dev/null +++ b/tests/test_mcoimg.py @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Tests for the recognition of a pixel image (MCOimg) in the body of a message. + +The cases come from the reference test vectors of the format +(``docs/mcoimg-js/tests/v3-js-*-fixtures.json`` and ``v2-js-fixtures.json`` in the +HDDen/meshcore-open repository, MIT). Each one is the text of an image and the size and +the palette profile that its encoder used. +""" + +from __future__ import annotations + +import pytest + +from meshterm.core.mcoimg import PixelImage, base91_decode, recognize + +#: (text, width, height, colours) from the version 3 vectors: one case for each mode of +#: the dimensions and for each palette profile that the vectors use. +_V3_CASES = [ + ("im3:g/5WjAL`NA", 4, 2, 4), # rawGlobal, master4, mode 1 + ("im3:g/LAU)", 1, 1, 4), # solidBackground, the shortest image + ("im3:g/)FCtB", 2, 2, 4), # implicitWhiteSolid, mode 0 + ("im3:TAYL>iBNGbA", 9, 7, 2), # mono, from the encoder vectors +] + + +@pytest.mark.parametrize(("text", "width", "height", "colours"), _V3_CASES) +def test_a_version_3_image_gives_its_size_and_colours( + text: str, width: int, height: int, colours: int +) -> None: + assert recognize(text) == PixelImage(3, width, height, colours) + + +def test_base91_decodes_to_the_payload_of_the_vector() -> None: + """``im3:g/5WjAL`NA`` is the app payload ``E3oBjQBCvgE=`` (base64) of the vectors.""" + assert base91_decode("g/5WjAL`NA") == bytes.fromhex("137a018d0042be01") + + +def test_a_version_1_or_2_image_has_no_header_to_read() -> None: + assert recognize("im:CC&tj68MFSB") == PixelImage(None) + + +def test_spaces_at_the_ends_are_permitted() -> None: + assert recognize(" im3:g/5WjAL`NA \n") == PixelImage(3, 4, 2, 4) + + +@pytest.mark.parametrize( + "body", + [ + "hello", + "im: ok", # a person typed it + "im:abc", # too short to be an image with no header + "im3:g/5WjAL`NA and more", # an image is the whole body + "see im3:g/5WjAL`NA", + "im3:hello", # Base91, but not the version 3 byte + "im:CC&tj68M'SB", # ' is not in the alphabet + ], +) +def test_text_that_is_not_an_image(body: str) -> None: + assert recognize(body) is None + + +def test_an_unknown_version_is_an_image_with_no_header() -> None: + assert recognize("im4:CC&tj68MFSB") == PixelImage(4)