From a19eadd81bda4a25048f354461d96bbcf3ebd1ce Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Tue, 13 Oct 2026 00:54:52 -0400 Subject: [PATCH] In a chat, our messages go under our name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A channel, a direct chat, a room, and the Messages list show our messages under "★ Name" instead of the bare star. The chip has our key's hue turned over: dark ink on a light fill, where each other sender is light on dark. A mention of our name takes the same chip, as "★ @Name". The PicoCalc cannot draw a light background, so there the chip keeps the normal colours and the star marks it. Path lines keep the bare star. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 10 ++++++ CLAUDE.md | 12 +++++++ meshterm/tools/chat.py | 78 ++++++++++++++++++++++++++++++----------- meshterm/ui/chat.py | 65 ++++++++++++++++++++++++---------- meshterm/ui/pathline.py | 20 ++++++++++- meshterm/ui/room.py | 18 +++++++++- meshterm/ui/specimen.py | 20 ++++++++--- meshterm/ui/widgets.py | 34 ++++++++++++++++++ tests/test_chat.py | 60 ++++++++++++++++++++++++------- tests/test_pathline.py | 12 +++++++ tests/test_widgets.py | 40 +++++++++++++++++++++ 11 files changed, 312 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 222c9a0..b222a59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,16 @@ can change how things behave. It does not only add new things. ## [Unreleased] +### Changed + +- **In a chat, your messages show your name.** A channel, a direct chat, and a room put + your messages under `★` and your node's name, and the Messages list shows them in the + same way. Your name has the colour of your key, but in reverse: dark text on a light + fill, where each other sender has light text on a dark fill. A mention of your name in a + message has the same mark, so a message that names you is easy to see. On the PicoCalc, + the console cannot draw a light fill, so there the `★` alone marks your messages. Before, + your messages showed only the `★`. + ## [0.11.1] - 2026-10-13 **Show private key shows the key again, and the uConsole and the Cardputer Zero can import diff --git a/CLAUDE.md b/CLAUDE.md index 8ec4883..3ac4311 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -477,6 +477,18 @@ as a grouped list does. Filling a page in is editing its `.md`; no Python follow `sender → recipient`), and a lone hop carries no `PATH_INK`, so a cursor row whitens it like any name. A chip in prose never breaks across lines (`render_hanging` holds every `whole` run together, spaces and all). +- **In a chat, we go by our name** (channel, DM, room, and the Messages list's preview — + nowhere else; JP, 2026-10-13). A route's bare `★` says "you already know who this is", + but a chat is a conversation between names, so our sender chip and every `@mention` of + our name are `widgets.self_chip`: `★ Name` (a mention: `★ @Name`, the star before the + `@`) on the chip of *our key's hue, turned over* — dark ink on a light fill of the hue + (`PathHop.inverse`, the same pair as any chip in the other order), the one light chip + among the senders. The `★` takes the chip's dark ink: a yellow star measured under 3:1 + on the light fill for 238 of 256 hues, and outside the chip on the page it was tried + and put back (JP, 2026-10-13). Arrow mode draws it as a padded reverse-video block. The + PicoCalc can't put a bright slot behind text, so there it keeps the normal colours and + the `★` alone marks us. With no name or key from the device, the bare `★` chip stays. + Path lines (delivery paths, the packet viewer, routes) keep `★`. - Concept icons: 📡 advert · 🕒 clock/sync · 🔄 reboot · 💾 backup · 📂 restore · 🔑 channel/credential key · 🔐 identity/auth secret · 🔒 lock (a locked contact, a private channel) · 🔓 unlock · 🗑 clear/delete · ✎ compose/edit · diff --git a/meshterm/tools/chat.py b/meshterm/tools/chat.py index 9b54572..dd041f8 100644 --- a/meshterm/tools/chat.py +++ b/meshterm/tools/chat.py @@ -58,7 +58,7 @@ from ..services.trace_runner import ( from ..ui import renderers from ..ui.fields import ChannelRef, NodeRef from ..ui.menus import Lane, column_header, fit_cells, section_heading -from ..ui.pathline import SELF_GLYPH, PathHop +from ..ui.pathline import PathHop from ..ui.termfont import powerline_enabled from ..ui.theme import name_style from ..ui.tui import Choice, DeleteRequest, Separator @@ -71,6 +71,7 @@ from ..ui.widgets import ( format_age, hop_chip, name_chip, + self_chip, ) from .base import Tool, ToolResult, register @@ -230,6 +231,10 @@ class ChatTool(Tool): stored_names, named_at = ctx.repo.node_names_with_times() key_of = make_name_key_resolver(contacts, stored_names, heard=named_at) name_of = make_node_resolver(contacts, stored_names) + # Our name and key, for our own messages and the mentions of us in the previews. + from ..ui.chat import our_node + + us = await our_node(ctx) # List the contacts by recency: first the contacts with messages, with the newest # exchange at the top. Then the contacts with no messages, in alphabetical order @@ -253,7 +258,7 @@ class ChatTool(Tool): for conversation in channels: items.append( Choice( - title=_row_title(ctx, conversation, live, key_of, lanes), + title=_row_title(ctx, conversation, live, key_of, lanes, us=us), value=conversation, # ←→ move only the message. The lanes before it stay (_Lanes.head). hscroll_from=lanes.head, @@ -264,7 +269,9 @@ class ChatTool(Tool): for conversation in rooms: items.append( Choice( - title=_row_title(ctx, conversation, live, key_of, lanes, name_of=name_of), + title=_row_title( + ctx, conversation, live, key_of, lanes, name_of=name_of, us=us + ), value=conversation, deletable=lasts.get(conversation.key) is not None, hscroll_from=lanes.head, @@ -280,7 +287,7 @@ class ChatTool(Tool): for conversation in direct: items.append( Choice( - title=_row_title(ctx, conversation, live, key_of, lanes), + title=_row_title(ctx, conversation, live, key_of, lanes, us=us), value=conversation, # Del offers to delete the stored history of this thread, only # where there is history to delete. @@ -895,6 +902,7 @@ def _row_title( lanes: _Lanes, *, name_of: NodeResolver | None = None, + us: tuple[str | None, str | None] = (None, None), ) -> Callable[[], str | Text]: """Return the row title as a *callable* that the select screen renders on each paint. @@ -911,11 +919,13 @@ def _row_title( key_of: Maps a sender name back to the key of its node, for the hues of the preview. lanes: The measured lane widths of the list. name_of: Maps the author key of a room post to a name (only for rooms). + us: The name and the key of our node (refer to + :func:`~meshterm.ui.chat.our_node`), for our own chip in the preview. Returns: A callable with no arguments, which makes the current row title. """ - return lambda: _title(ctx, conversation, lasts, key_of, lanes, name_of=name_of) + return lambda: _title(ctx, conversation, lasts, key_of, lanes, name_of=name_of, us=us) def _title( @@ -926,6 +936,7 @@ def _title( lanes: _Lanes, *, name_of: NodeResolver | None = None, + us: tuple[str | None, str | None] = (None, None), ) -> str | Text: """Make a picker row from lanes of fixed width, with colour codes. @@ -951,6 +962,7 @@ def _title( node. lanes: The measured lane widths of the list. name_of: Maps the author key of a room post to a name (only for rooms). + us: The name and the key of our node, for our own chip in the preview. Returns: The row title as a styled :class:`~rich.text.Text`. @@ -979,7 +991,7 @@ def _title( text.append(f"{age:>{_AGE_WIDTH}}", style="muted") text.append(" ") if last is not None: - text.append_text(_preview_text(last, key_of, name_of)) + text.append_text(_preview_text(last, key_of, name_of, us=us)) return text @@ -1025,13 +1037,18 @@ def _append_marker( def _preview_text( - last: ChatMessage, key_of: NameKeyResolver, name_of: NodeResolver | None = None + last: ChatMessage, + key_of: NameKeyResolver, + name_of: NodeResolver | None = None, + *, + us: tuple[str | None, str | None] = (None, None), ) -> Text: """A muted preview of the last message, with sender names and ``@mentions`` lit in their hue. It is the same as the live transcript: - - Our own messages start with our author (refer to :func:`_append_author`). + - Our own messages start with our chip, ``★ Name`` turned over, and a mention of our + name takes the same chip (refer to :func:`~meshterm.ui.widgets.self_chip`). - In a received channel message, the inline ``Name:`` sender is the author, in the hue that comes from its key (the node grey when no known node has the name). - A room post starts with its author, named by key in the same way as the room screen @@ -1050,29 +1067,39 @@ def _preview_text( body_raw = last.text.replace("\n", " ") text = Text() if last.outbound: - _append_author(text, PathHop(SELF_GLYPH, you=True), Text("you: ", style="accent")) - _append_body(text, body_raw, key_of) + name, key = us + chip = self_chip(name, key, role=ORIGIN) + # Where no chips are drawn, the chip is a block in reverse video. Our node with no + # name keeps the old byline. + byline = chip + Text(" ") if name and key else Text("you: ", style="accent") + _append_author(text, chip, byline) + _append_body(text, body_raw, key_of, us) elif last.is_channel: name, body = split_channel_sender(body_raw) if name is not None: key = key_of(name) - _append_author(text, PathHop(name, key=key), _byline(name, key)) - _append_body(text, body, key_of) + _append_author(text, _origin(name, key), _byline(name, key)) + _append_body(text, body, key_of, us) else: _append_body(text, body_raw, key_of) elif last.author and name_of is not None: from ..ui.room import author_label name, key = author_label(last.author, name_of) - _append_author(text, PathHop(name, key=key), _byline(name, key)) - _append_body(text, body_raw, key_of) + _append_author(text, _origin(name, key), _byline(name, key)) + _append_body(text, body_raw, key_of, us) else: - _append_body(text, body_raw, key_of) + _append_body(text, body_raw, key_of, us) return text -def _append_author(text: Text, hop: PathHop, byline: Text) -> None: - """Append the author of a preview: an origin chip where chips are drawn, else ``byline``. +def _origin(name: str, key: str | None) -> Text: + """The chip of the author of a preview: it closes on the point, as in the transcript.""" + return hop_chip(PathHop(name, key=key), role=ORIGIN) + + +def _append_author(text: Text, chip: Text, byline: Text) -> None: + """Append the author of a preview: its origin ``chip`` where chips are drawn, else ``byline``. The chip closes on the point, the same as the sender chip of the transcript, and the body follows it after one space. The point says what the colon of ``Name:`` says, so @@ -1080,7 +1107,7 @@ def _append_author(text: Text, hop: PathHop, byline: Text) -> None: ``byline`` (``Name: ``, or ``you: `` for us), as it always was (JP, 2026-10-10). """ if powerline_enabled(): - text.append_text(hop_chip(hop, role=ORIGIN)) + text.append_text(chip) text.append(" ") else: text.append_text(byline) @@ -1093,19 +1120,28 @@ def _byline(name: str, key: str | None) -> Text: return text -def _append_body(text: Text, body: str, key_of: NameKeyResolver) -> None: +def _append_body( + text: Text, + body: str, + key_of: NameKeyResolver, + us: tuple[str | None, str | None] = (None, None), +) -> None: """Append ``body`` to ``text``, muted, and light the names that it mentions. Each ``@[Name]`` is drawn in the hue that comes from the key of that node, as a chip that opens on the notch where the terminal draws chips (the same as in the transcript). - It takes the node grey when the name resolves to no node that we know. + It takes the node grey when the name resolves to no node that we know. A mention of our + own name (``us``) takes our chip, as in the transcript. """ pos = 0 for match in MENTION.finditer(body): if match.start() > pos: text.append(body[pos : match.start()], style="muted") name = match.group(1) - text.append_text(name_chip(f"@{name}", key_of(name), role=DESTINATION)) + if us[0] and name == us[0]: + text.append_text(self_chip(name, us[1], mention=True, role=DESTINATION)) + else: + text.append_text(name_chip(f"@{name}", key_of(name), role=DESTINATION)) pos = match.end() if pos < len(body): text.append(body[pos:], style="muted") diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index c466e91..b57051c 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -44,7 +44,7 @@ from .tui.prompt import ( from .tui.render import render_hanging, render_lines, right_aligned_tail from .tui.screen import CANCEL, Screen from .tui.spinner import Spinner, spinner_interval -from .widgets import DESTINATION, ORIGIN, name_chip +from .widgets import DESTINATION, ORIGIN, name_chip, self_chip if TYPE_CHECKING: from ..context import AppContext @@ -222,6 +222,8 @@ class ChatScreen(Screen): resend_unscoped: Callable[[ChatMessage], Awaitable[ChatMessage | None]] | None = None, locator: Locator | None = None, pages: ContactPages | None = None, + self_name: str | None = None, + self_key: str | None = None, ) -> None: """Build the chat screen. @@ -259,8 +261,13 @@ class ChatScreen(Screen): pages: The contacts, for ^O: the node page of the author of the selected message (refer to :class:`~meshterm.ui.node_detail_screen.ContactPages`). With ``None``, ^O does nothing. + self_name: The name of our node (refer to :func:`our_node`). Our messages and + the mentions of our name show it (:func:`~meshterm.ui.widgets.self_chip`). + self_key: Our public key, which gives the hue of that chip. """ super().__init__() + self._self_name = self_name + self._self_key = self_key self._scope = scope if conversation.is_channel else None self.title = f"{conversation.label} · {self._scope}" if self._scope else conversation.label self._is_channel = conversation.is_channel @@ -678,10 +685,12 @@ class ChatScreen(Screen): The chip makes a *label* different from the prose under it. A name alone above its messages then reads as a tag, not as a coloured word that a person typed. It is the chip of a path line (refer to :func:`~meshterm.ui.widgets.name_chip`). Thus a - sender looks exactly like that node as a hop in a route, also for our messages: - the ``★``, never our name. + sender looks exactly like that node as a hop in a route. - Our star comes from the direction of the message (``outbound``), not from the + Our messages are the exception. They go under our name, as ``★ Name`` on a chip + that is turned over (refer to :func:`~meshterm.ui.widgets.self_chip`). A route + shows our end as the bare ``★``, but a chat is a conversation between names. + Our chip comes from the direction of the message (``outbound``), not from the ``"you"`` label. Thus a remote sender with the name ``you`` still gets the hue of its key, and does not look like our node. @@ -690,7 +699,7 @@ class ChatScreen(Screen): the other end, and it opens on the notch (refer to :meth:`_render_mentions`). """ if message.outbound: - return name_chip("", you=True, role=ORIGIN) + return self_chip(self._self_name, self._self_key, role=ORIGIN) # ``·`` is a channel line that arrived with no sender prefix: there is no key to use. key = None if sender == "·" else self._header_key(sender, message) return name_chip(sender, key, role=ORIGIN) @@ -783,7 +792,9 @@ class ChatScreen(Screen): :meth:`_begin_reply`). Here it shows as ``@Name`` in a chip of the hue of that node. Thus the user sees that a mention belongs to the node that it names. The text around the mentions keeps the base style of the line (``cursor`` when the message - is the selected reply target, or else no style). + is the selected reply target, or else no style). A mention of our own name takes + our chip (:func:`~meshterm.ui.widgets.self_chip`), so that a message that names us + is easy to see. The chip opens on the notch, because the node that a mention names is the destination of a route that came from the sender (refer to :meth:`_group_header`, @@ -798,8 +809,11 @@ class ChatScreen(Screen): if match.start() > pos: text.append(body[pos : match.start()], style=base) name = match.group(1) - key = self._sender_key(name, mention=True) - text.append_text(name_chip(f"@{name}", key, role=DESTINATION)) + if self._self_name and name == self._self_name: + chip = self_chip(name, self._self_key, mention=True, role=DESTINATION) + else: + chip = name_chip(f"@{name}", self._sender_key(name, mention=True), role=DESTINATION) + text.append_text(chip) pos = match.end() if pos < len(body): text.append(body[pos:], style=base) @@ -1423,6 +1437,24 @@ class ChatScreen(Screen): pass +async def our_node(ctx: AppContext) -> tuple[str | None, str | None]: + """The name and the public key of our node, from the cache of the session. + + A chat shows them on our messages (refer to :func:`~meshterm.ui.widgets.self_chip`), + and a direct chat names one end of each of its packets with the key. The read uses the + cache, so it does not ask the device again. + + Returns: + ``(name, key)``. An item is ``None`` when the device did not report it, or when the + read failed. Our node with no name only keeps the bare ``★`` in a chat. + """ + try: + info = await ctx.devstate.self_info() + except Exception: # noqa: BLE001 - our node with no name keeps the bare star + return None, None + return str(info.get("name") or "") or None, str(info.get("public_key") or "") or None + + async def open_chat(ctx: AppContext, conversation: Conversation) -> int: """Open the live chat screen for ``conversation`` and run it until the user closes it. @@ -1504,6 +1536,7 @@ async def open_chat(ctx: AppContext, conversation: Conversation) -> int: from .node_detail_screen import ContactPages paths = await _make_paths_presenter(ctx, conversation, device) + self_name, self_key = await our_node(ctx) screen = ChatScreen( conversation, history, @@ -1517,6 +1550,8 @@ async def open_chat(ctx: AppContext, conversation: Conversation) -> int: resend_unscoped=resend_unscoped, locator=await Locator.gather(ctx), pages=await ContactPages.gather(ctx), + self_name=self_name, + self_key=self_key, ) ctx.chat.set_active(conversation.key) @@ -1733,16 +1768,10 @@ async def _make_paths_presenter( type_of = trace_runner.make_node_type_resolver(contacts) key_of = trace_runner.make_name_key_resolver(contacts, stored_names, heard=named_at) prefix_bytes = await ctx.devstate.routing_prefix_bytes() - self_name: str | None = None - self_key: str | None = None - try: - info = await ctx.devstate.self_info() - self_name = str(info.get("name") or "") or None - # Our key names one end of each direct packet in this conversation. The key of - # the contact names the other end (refer to :func:`direct_arrivals`). - self_key = str(info.get("public_key") or "") or None - except Exception: # noqa: BLE001 - our node with no name only gets no white highlight - self_name = None + # Our key names one end of each direct packet in this conversation. The key of the + # contact names the other end (refer to :func:`direct_arrivals`). Our node with no name + # only gets no white highlight. + self_name, self_key = await our_node(ctx) secret = conversation.secret if conversation.is_channel and not secret and conversation.channel_idx is not None: diff --git a/meshterm/ui/pathline.py b/meshterm/ui/pathline.py index c893dc3..ef593b0 100644 --- a/meshterm/ui/pathline.py +++ b/meshterm/ui/pathline.py @@ -309,6 +309,11 @@ class PathHop: continues again". A chip says the opposite: that a node in the route has the name ``⋯``. Arrow mode does not need a special case, because a bare label between two arrows is already the same thing. + inverse: Draw the chip turned over: the hue of ``key`` is the fill, and the darker + fill of each other chip is the ink. It is our node in a chat (refer to + :func:`~meshterm.ui.widgets.self_chip`). Arrow mode draws the label in reverse + video, with the padding of a chip. The console of the PicoCalc has no light + background, so there the chip keeps the colours of each other chip. """ label: str @@ -320,6 +325,7 @@ class PathHop: style: str | None = None cursor: bool = False gap: bool = False + inverse: bool = False def elision_hop() -> PathHop: @@ -1001,6 +1007,8 @@ class PathLine: text.append(hop.label, style="selected") elif hop.dim: text.append(hop.label, style="faint") + elif hop.inverse and hop.key: + text.append(f" {hop.label} ", style=f"{node_style(hop.key)} reverse") elif hop.style: text.append(hop.label, style=hop.style) elif hop.you: @@ -1201,6 +1209,10 @@ def _spectrum_colours(hop: PathHop) -> _ChipColours: automatic return home, a mirrored return leg). Our end must recede with the rest of that automatic half, and not keep its yellow among the greys. Plain mode says the same thing when it fades the name. + + A chip that is turned over (``inverse``, our node in a chat) has the same two colours + as the chip of its key, in the other order: the hue is the fill, and the dark fill is + the ink. It is the one light chip in a chat, and the contrast of the pair stays the same. """ if hop.cursor: return _ChipColours(_style_hex("cursor") or _KEYLESS_BG, _CHIP_FG, _CHIP_FG) @@ -1209,9 +1221,11 @@ def _spectrum_colours(hop: PathHop) -> _ChipColours: return _ChipColours(_chip_fill(resolved), resolved, resolved) if hop.dim: return _ChipColours(_DIM_BG, _DIM_FG, _DIM_FG) + hue = _style_hex(node_style(hop.key)) if hop.key else None + if hop.inverse and hue: + return _ChipColours(hue, _chip_fill(hue), _chip_fill(hue)) if hop.you: return _ChipColours(_YOU_BG, _SELF_INK, _SELF_INK) - hue = _style_hex(node_style(hop.key)) if hop.key else None if hue: return _ChipColours(_chip_fill(hue), hue, hue) return _ChipColours(_KEYLESS_BG, _KEYLESS_FG, _KEYLESS_FG) @@ -1233,6 +1247,10 @@ def _slot_colours(hop: PathHop) -> _ChipColours: yellow, a faded hop in the dark grey, and the slot as a white ``+`` in a break of the ribbon. The order of the rules is the same as on a truecolor terminal (:func:`_spectrum_colours`). + + A chip that is turned over (``inverse``) keeps the colours of each other chip here. Its + fill would be a bright slot, and the console cannot draw one as a background. In a chat, + the ``★`` in its label still tells our node from the others. """ if hop.cursor: return _ChipColours(_SLOT_PAGE, _SLOT_WHITE, _SLOT_WHITE) diff --git a/meshterm/ui/room.py b/meshterm/ui/room.py index 6bb5c8a..bd7411b 100644 --- a/meshterm/ui/room.py +++ b/meshterm/ui/room.py @@ -47,7 +47,14 @@ from ..core.models import ( RoomAccess, RoomLogin, ) -from .chat import ChatScreen, _belongs, _contact_names, _make_paths_presenter, _with_restore +from .chat import ( + ChatScreen, + _belongs, + _contact_names, + _make_paths_presenter, + _with_restore, + our_node, +) if TYPE_CHECKING: from ..context import AppContext @@ -141,6 +148,8 @@ class RoomScreen(ChatScreen): key_of: Callable[[str], str | None] | None = None, locator: Locator | None = None, pages: ContactPages | None = None, + self_name: str | None = None, + self_key: str | None = None, ) -> None: """Build the room screen. @@ -169,6 +178,8 @@ class RoomScreen(ChatScreen): key_of: Gives the key of its node for a name, for the hues of ``@mention``. locator: The located nodes, for ^L: the map on the author of a post. pages: The contacts, for ^O: the node page of the author of a post. + self_name: The name of our node, on our posts and on the mentions of us. + self_key: Our public key, which gives the hue of that chip. """ super().__init__( conversation, @@ -181,6 +192,8 @@ class RoomScreen(ChatScreen): key_of=key_of, locator=locator, pages=pages, + self_name=self_name, + self_key=self_key, ) self._label = conversation.label self._resolve = resolve @@ -425,6 +438,7 @@ async def open_room(ctx: AppContext, conversation: Conversation) -> int: async def join(ask: bool) -> RoomLogin | None: return await join_room(ctx, await fresh(), ask=ask) + self_name, self_key = await our_node(ctx) screen = RoomScreen( conversation, board, @@ -441,6 +455,8 @@ async def open_room(ctx: AppContext, conversation: Conversation) -> int: key_of=trace_runner.make_name_key_resolver(contacts, stored_names, heard=named_at), locator=await Locator.gather(ctx), pages=ContactPages(ctx, list(contacts)), + self_name=self_name, + self_key=self_key, ) ctx.chat.set_active(conversation.key) diff --git a/meshterm/ui/specimen.py b/meshterm/ui/specimen.py index cb9b991..a065dea 100644 --- a/meshterm/ui/specimen.py +++ b/meshterm/ui/specimen.py @@ -20,7 +20,14 @@ from ..platforms import get_platform from .packet_viewer import KIND_ICONS, PAYLOAD_ICONS from .theme import _VT_SLOTS, fold_text, glyph, name_style, snr_style from .tui.fkeys import FPair, active_deck -from .widgets import DESTINATION, ORIGIN, _recency_style, channel_glyph, name_chip +from .widgets import ( + DESTINATION, + ORIGIN, + _recency_style, + channel_glyph, + name_chip, + self_chip, +) #: Demonstration identities for the row of name colours: ``(name, key)``. The keys are #: synthetic. We chose them so that their first bytes are in three different sectors of @@ -28,6 +35,9 @@ from .widgets import DESTINATION, ORIGIN, _recency_style, channel_glyph, name_ch #: ``theme._NODE_SLOT_HEXES``). _DEMO_NAMES = (("Alice", "a1b2"), ("Lakeside", "3d63"), ("Lounge", "cc10")) +#: The key of our own node in the specimen, which gives the hue of its chat chip. +_DEMO_SELF_KEY = "5e7f" + def _palette_row() -> Text: """The 16 slots as filled blocks: first the dim bank, then the bright bank. @@ -135,13 +145,15 @@ def specimen_lines() -> list[RenderableType]: # because a message goes on from its author. The mention at the end opens on the # notch, because the node that it names is where the message goes. The path line's # own segment draws them, so this row is also a one-hop sample of the route language: - # the hue in the fill, the star for our end, and the keyless grey for a node that - # nobody can identify. + # the hue in the fill and the keyless grey for a node that nobody can identify. Our own + # messages go under ``★ me``, on the one chip that is turned over (dark on a light fill + # of our hue). The console of the PicoCalc has no light background, so there only the + # star marks it. chips = Text("chips ") for name, key in _DEMO_NAMES[:2]: chips.append_text(name_chip(name, key, role=ORIGIN)) chips.append(" ") - chips.append_text(name_chip("", you=True, role=ORIGIN)) + chips.append_text(self_chip("me", _DEMO_SELF_KEY, role=ORIGIN)) chips.append(" ") chips.append_text(name_chip("·", role=ORIGIN)) chips.append(" ") diff --git a/meshterm/ui/widgets.py b/meshterm/ui/widgets.py index bb2fb27..c9fcefe 100644 --- a/meshterm/ui/widgets.py +++ b/meshterm/ui/widgets.py @@ -683,6 +683,40 @@ def name_chip( return hop_chip(hop, role=role) +def self_chip( + name: str | None, key: str | None, *, mention: bool = False, role: str | None = None +) -> Text: + """Our node in a chat: ``★ Name``, in the hue of our key, on a chip that is turned over. + + A chat (a channel, a direct chat, a room) names each sender, and our node too. A route + shows our end as the bare ``★``, because the user never has to be told who that is. A + chat is a conversation between names, so our messages go under our name (JP, + 2026-10-13). Two things make it different from the name of each other node. The ``★`` + of the app comes first. Also, the chip is turned over: the other senders are a light + hue on a dark fill, and ours is dark on a light fill of our hue. The console of the + PicoCalc cannot draw a light background, so there only the ``★`` marks us (refer to + :attr:`~meshterm.ui.pathline.PathHop.inverse`). A mention of our name in a message + takes the same chip, so that a message that names us is easy to see. + + Our node with no name or no key (the device did not report them) keeps the bare ``★`` + chip of a route. + + Args: + name: The name of our node. + key: Our public key, which gives the hue. + mention: ``True`` for an ``@mention`` of our name. The label is ``★ @Name``: + the star comes before the ``@`` (JP, 2026-10-13). + role: :data:`ORIGIN`, :data:`DESTINATION`, or ``None``, as for :func:`name_chip`. + + Returns: + The chip as a one-line :class:`Text`. + """ + if not name or not key: + return name_chip("", you=True, role=role) + label = f"{SELF_GLYPH} @{name}" if mention else f"{SELF_GLYPH} {name}" + return hop_chip(PathHop(label, key=key, inverse=True), role=role) + + def _shorten_hash(value: str, hash_bytes: int | None) -> str: """Return ``value`` as bare hex truncated to ``hash_bytes`` bytes. diff --git a/tests/test_chat.py b/tests/test_chat.py index d5d4d20..4f8d5bc 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -415,6 +415,10 @@ def _keys_of(mapping: dict[str, str]): return lambda name: mapping.get(name.casefold()) +#: The public key of our node in the tests of our chat chip. +_OUR_KEY = "5e" + "7f" * 31 + + def _ink(text, run: str) -> str: """The style that colours ``run`` in ``text``: its identity span, not the path line's stamp.""" from meshterm.ui.pathline import PATH_INK @@ -438,7 +442,9 @@ def test_preview_prefixes_own_messages_only() -> None: dm_in = ChatMessage(text="hey", peer="aa", peer_name="Bob") assert _preview_text(dm_in, _NO_KEYS).plain == "hey" mine = ChatMessage(text="yo", outbound=True, is_channel=True, channel_idx=0) - assert _preview_text(mine, _NO_KEYS).plain == "you: yo" + assert _preview_text(mine, _NO_KEYS).plain == "you: yo" # our node with no name + # With our name, the preview shows our chat chip: a padded block in reverse video. + assert _preview_text(mine, _NO_KEYS, us=("Me", _OUR_KEY)).plain == " ★ Me yo" def test_preview_colours_channel_sender_and_mentions() -> None: @@ -462,8 +468,9 @@ def test_preview_colours_channel_sender_and_mentions() -> None: def test_preview_draws_the_author_and_the_mentions_as_the_transcript_does(powerline) -> None: """With chips, the author closes on the point and a mention opens on the notch. - The point says what the colon said, so the chip has no colon. Our own author is the - ``★``, as the sender chip of our messages in the transcript. + The point says what the colon said, so the chip has no colon. Our own author is + ``★ Name``, as the sender chip of our messages in the transcript, and a mention of our + name takes the same chip. With no name for our node, the bare ``★`` stays. """ from meshterm.ui.pathline import POWERLINE_ROUND_CLOSE, POWERLINE_ROUND_OPEN, POWERLINE_SEP @@ -474,6 +481,11 @@ def test_preview_draws_the_author_and_the_mentions_as_the_transcript_does(powerl assert _preview_text(theirs, _NO_KEYS).plain == f"{author} hi {mention}" mine = ChatMessage(text="yo", outbound=True, is_channel=True, channel_idx=0) assert _preview_text(mine, _NO_KEYS).plain == f"{POWERLINE_ROUND_OPEN} ★ {POWERLINE_SEP} yo" + us = ("Me", _OUR_KEY) + ours = f"{POWERLINE_ROUND_OPEN} ★ Me {POWERLINE_SEP} yo" + assert _preview_text(mine, _NO_KEYS, us=us).plain == ours + named = ChatMessage(text="Bob: hi @[Me]", is_channel=True, channel_idx=0) + assert "★ @Me" in _preview_text(named, _NO_KEYS, us=us).plain def test_preview_keeps_the_whole_message() -> None: @@ -1190,12 +1202,20 @@ def test_channel_transcript_groups_by_sender() -> None: text="hello all", outbound=True, is_channel=True, channel_idx=0, created_at=at(9) ), ] - screen = ChatScreen(conv, messages, send=None, names={}, session=_StubSession()) + screen = ChatScreen( + conv, + messages, + send=None, + names={}, + session=_StubSession(), + self_name="Me", + self_key=_OUR_KEY, + ) rendered = _strip_ansi("\n".join(screen._render_grouped(80))) assert rendered.count("Alice") == 1 # the two Alice messages share one header - # The header of our group is the ★ that a route uses for our end, not our name. - assert "Bob" in rendered and "★" in rendered + # The header of our group is our name after the ★ (JP, 2026-10-13), not the bare ★. + assert "Bob" in rendered and "★ Me" in rendered assert "hi" in rendered and "again" in rendered # the bodies are there, without the prefix assert "Alice: hi" not in rendered # the raw name prefix moved into the header # Each message keeps its own timestamp on its line, also when grouped under one sender. @@ -1489,7 +1509,7 @@ def test_chat_channel_home_moves_the_compose_cursor() -> None: def test_channel_self_style_keyed_on_concept_not_label() -> None: - """Our white 'self' style depends on the message being outbound, not on the 'you' label. + """Our own chip depends on the message being outbound, not on the 'you' label. A remote sender with the name 'you' must not take the white style that is only for us. It reads as a normal sender (the hue of its key if the key resolves, and muted if not). @@ -1498,8 +1518,11 @@ def test_channel_self_style_keyed_on_concept_not_label() -> None: ours = ChatMessage(text="hi", is_channel=True, channel_idx=0, outbound=True) theirs = ChatMessage(text="you: hi", is_channel=True, channel_idx=0) + mine = _channel_screen([], self_name="Me", self_key=_OUR_KEY) + turned = f"{node_style(_OUR_KEY)} reverse" + assert _ink(mine._group_header("you", ours), " ★ Me ") == turned # our name, turned over screen = _channel_screen([]) - assert _ink(screen._group_header("you", ours), "★") == "you" # us: the white star + assert _ink(screen._group_header("you", ours), "★") == "you" # no name: the white star assert _ink(screen._group_header("you", theirs), "you") == "node.unknown" # no key: grey keyed = _channel_screen([], key_of=_keys_of({"you": "d4" + "0" * 62})) remote = _ink(keyed._group_header("you", theirs), "you") @@ -1515,13 +1538,24 @@ def test_channel_own_messages_do_not_merge_with_remote_namesake() -> None: ChatMessage(text="you: impostor", is_channel=True, channel_idx=0, created_at=base), ChatMessage(text="mine", outbound=True, is_channel=True, channel_idx=0, created_at=base), ] - screen = _channel_screen(messages) + screen = _channel_screen(messages, self_name="Me", self_key=_OUR_KEY) rendered = _strip_ansi("\n".join(screen._render_grouped(80))) - # Two headers, and they are not only apart: theirs is the name that they sent, ours is the ★. - assert rendered.count("you") == 1 and rendered.count("★") == 1 + # Two headers, and they are not only apart: theirs is the name that they sent, ours is + # our name after the ★. + assert rendered.count("you") == 1 and rendered.count("★ Me") == 1 -def _channel_screen(messages, session=None, key_of=None) -> ChatScreen: +def test_a_mention_of_our_name_takes_our_chip() -> None: + """A message that names us is easy to see. A mention of each other node is as before.""" + screen = _channel_screen([], self_name="Me", self_key=_OUR_KEY) + text = screen._render_mentions("hi @[Me] and @[Bob]", selected=False) + assert "★ @Me" in text.plain and "@Bob" in text.plain + assert "★ Bob" not in text.plain + + +def _channel_screen( + messages, session=None, key_of=None, self_name=None, self_key=None +) -> ChatScreen: """Build a channel ChatScreen for ``messages``, for the selection and reply tests.""" conv = Conversation(label="#public", is_channel=True, channel_idx=0) return ChatScreen( @@ -1531,6 +1565,8 @@ def _channel_screen(messages, session=None, key_of=None) -> ChatScreen: names={}, session=session or _StubSession(), key_of=key_of, + self_name=self_name, + self_key=self_key, ) diff --git a/tests/test_pathline.py b/tests/test_pathline.py index fdf5927..dd2f8c1 100644 --- a/tests/test_pathline.py +++ b/tests/test_pathline.py @@ -236,6 +236,18 @@ def picocalc(monkeypatch: pytest.MonkeyPatch) -> None: set_platform(PICOCALC_LYRA) +def test_the_picocalc_cannot_turn_our_chat_chip_over(picocalc: None) -> None: + """The console has no light background, so our chat chip keeps the colours of each chip. + + Its fill would be a bright slot, and the VT draws a background only from slots 0 to 7. + In a chat, the ``★`` in the label still tells our node from the others. + """ + from meshterm.ui.pathline import _slot_colours + + ours = PathHop(f"{SELF_GLYPH} Me", key="1c", inverse=True) + assert _slot_colours(ours) == _slot_colours(PathHop("Me", key="1c")) + + def test_the_picocalc_draws_chips_from_its_eight_backgrounds(picocalc: None) -> None: """The chip of a node is the dim twin of its hue, and the label is the hue itself. diff --git a/tests/test_widgets.py b/tests/test_widgets.py index c549ceb..834bb0e 100644 --- a/tests/test_widgets.py +++ b/tests/test_widgets.py @@ -32,6 +32,7 @@ from meshterm.ui.widgets import ( path_text, revisit_note, route_ends, + self_chip, ) @@ -348,6 +349,45 @@ def test_name_chip_draws_us_as_the_star_never_as_our_name(powerline) -> None: assert _span_style(chip, "★").bgcolor.name == "#3f3f46" # a neutral grey, not a hue +def test_self_chip_is_the_chip_of_our_key_turned_over(powerline) -> None: + """In a chat, our messages go under ``★ Name``, dark on a light fill of our hue. + + The two colours are those of the chip of our key, in the other order. Thus the contrast + stays the same, and it is the one light chip among the senders (JP, 2026-10-13). + """ + powerline(True) + ours = self_chip("Me", "5e7f", role=ORIGIN) + theirs = name_chip("Me", "5e7f", role=ORIGIN) + + assert "★ Me" in ours.plain + ink, normal = _span_style(ours, "★ Me"), _span_style(theirs, "Me") + assert (ink.color.name, ink.bgcolor.name) == (normal.bgcolor.name, normal.color.name) + + +def test_self_chip_is_a_block_in_reverse_video_without_powerline(powerline) -> None: + """With no chips, our name is still dark on the hue of our key, padded as a chip is.""" + powerline(False) + chip = self_chip("Me", "5e7f") + + assert chip.plain == " ★ Me " + style = _span_style(chip, " ★ Me ") + assert style.reverse and style.color.name == node_style("5e7f").removeprefix("bold ") + + +def test_self_chip_of_a_mention_keeps_its_at(powerline) -> None: + """A mention of our name takes our chip, with the star before the ``@``.""" + powerline(True) + assert "★ @Me" in self_chip("Me", "5e7f", mention=True, role=DESTINATION).plain + + +def test_self_chip_keeps_the_bare_star_without_our_name_or_key(powerline) -> None: + """A device that did not report our name or key leaves the star of a route.""" + powerline(True) + star = name_chip("", you=True).plain + assert self_chip(None, "5e7f").plain == star + assert self_chip("Me", None).plain == star + + def test_name_chip_greys_a_node_it_cannot_place(powerline) -> None: """With no key there is no hue. Only identities that have a key get colour, in a chip too.""" powerline(True)