From 4dc960876114c5ac751512dac1d52abc93117372 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sun, 19 Jul 2026 01:04:57 -0400 Subject: [PATCH] =?UTF-8?q?Colour:=20every=20hue=20rides=20a=20key=20?= =?UTF-8?q?=E2=80=94=20name-seeding=20retires?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new make_name_key_resolver (beside its trace_runner siblings) maps a display name back to the node's key — contacts win, the recorder's stored advert names fill in strangers — and name_style's keyless fallback becomes muted: colour now always marks a keyed identity, never a character-sum accident that two spellings of one node disagree on. Wired through every keyless call site: the chat transcript's sender headers and @mentions (a direct thread falls back to the peer's key), the picker previews, the live feed's channel-sender lane, and the route graph's origin label (new key_of hook on route_graph_style, threaded through the packet viewer and Message paths). The chat picker's contact dot switches to the standard companion pink — shape still marks history — and contact labels take their key-derived hue. name_rgb guards the muted style so braille canvases render the grey. Co-Authored-By: Claude Fable 5 --- CLAUDE.md | 6 +- meshterm/services/trace_runner.py | 49 ++++++++++++ meshterm/tools/chat.py | 103 ++++++++++++++++-------- meshterm/ui/chat.py | 49 +++++++----- meshterm/ui/livefeed_screen.py | 16 +++- meshterm/ui/message_paths_screen.py | 16 +++- meshterm/ui/packet_viewer.py | 7 ++ meshterm/ui/theme.py | 17 ++-- meshterm/ui/widgets.py | 27 ++++++- tests/test_chat.py | 118 ++++++++++++++++++---------- tests/test_widgets.py | 51 ++++++++++++ 11 files changed, 350 insertions(+), 109 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 684835e..6095188 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -110,8 +110,10 @@ Relative ages: `format_ago` for prose ("now", "5m ago", "never" — never "now a ### Colour - Node names are always coloured: `name_style(name, key)` palette hue, derived from the - node's key (its first byte — any known prefix agrees) so a rename keeps the colour; - the name's characters seed it only when no key exists (a channel sender). Our own node + node's key (its first byte — any known prefix agrees) so a rename keeps the colour. + A surface holding only a name resolves it first (`make_name_key_resolver`); a name + no known node carries stays muted — colour is reserved for keyed identities, never + seeded from a name's characters. Our own node is the pure-white `you` style; a context colouring (chart quality) may still win. Recency heat colours heard/first-heard ages, never names. A key lane (via `highlighted_hash`) lights its hash in the same key-derived hue; the rest of the key, diff --git a/meshterm/services/trace_runner.py b/meshterm/services/trace_runner.py index 0d53e9a..c48a69a 100644 --- a/meshterm/services/trace_runner.py +++ b/meshterm/services/trace_runner.py @@ -146,6 +146,55 @@ def make_key_resolver(contacts: Optional[list[Contact]]) -> NodeResolver: return resolve +#: Maps a display name to the node's key (as full as we hold one — a public key, a key +#: prefix, or a stored node id), or ``None`` for a name no known node carries. The +#: colour side of :func:`make_node_resolver`: where that resolver turns hex into names, +#: this one turns a bare name back into the key its palette hue derives from. +NameKeyResolver = Callable[[str], Optional[str]] + + +def make_name_key_resolver( + contacts: Optional[list[Contact]], + stored_names: Optional[dict[str, str]] = None, +) -> NameKeyResolver: + """Build a resolver that finds the key behind a display name. + + The app-wide colour rule keys every name's hue on the node's key; some surfaces + (a channel message's inline sender, an ``@mention``, a route graph's origin) hold + only a *name*. This maps that name — casefolded — back to a key: the device's + contacts win (their keys are canonical), then the recorder's stored names fill in + nodes the companion never befriended, so a known stranger still lands on its own + hue. A name nobody carries resolves to ``None`` — the caller renders it muted, + because colour is reserved for keyed identities. + + Args: + contacts: Known contacts to resolve against (name → public key/key prefix). + stored_names: The recorder's latest advertised name per stored node id + (:meth:`~meshterm.persistence.repository.Repository.node_names`), inverted + here into a name → node-id fallback. + + Returns: + A callable taking a display name and returning the best key hex we hold for + it, or ``None`` when the name matches no known node. + """ + keys: dict[str, str] = {} + for node, name in (stored_names or {}).items(): + ident = node.lower().removeprefix("0x") + if name and ident: + keys.setdefault(name.casefold(), ident) + for c in contacts or []: + ident = (c.public_key or c.key_prefix or "").lower().removeprefix("0x") + if c.name and ident: + keys[c.name.casefold()] = ident # contacts win over stored names + + def key_of(name: str) -> Optional[str]: + if not name: + return None + return keys.get(name.casefold()) + + return key_of + + def parse_trace_path(spec: str, contacts: Optional[list[Contact]] = None) -> str: """Parse a user path spec into the hex path string ``send_trace`` expects. diff --git a/meshterm/tools/chat.py b/meshterm/tools/chat.py index 8f4f6fb..b6fbc54 100644 --- a/meshterm/tools/chat.py +++ b/meshterm/tools/chat.py @@ -28,11 +28,13 @@ from ..core.channels import ( ) from ..core.connection import Device from ..core.events import EventKind, MeshEvent -from ..core.models import ChatMessage, Contact, Conversation, utcnow -from ..ui.chat import _MENTION, _sender_hue, _split_channel_sender +from ..core.models import NODE_TYPE_CHAT, ChatMessage, Contact, Conversation, utcnow +from ..services.trace_runner import NameKeyResolver, make_name_key_resolver +from ..ui.chat import _MENTION, _split_channel_sender from ..ui.menus import fit_cells +from ..ui.theme import name_style from ..ui.tui import Choice, Separator -from ..ui.widgets import channel_glyph +from ..ui.widgets import _NODE_GLYPHS, channel_glyph from .base import Tool, ToolResult, register if TYPE_CHECKING: @@ -128,13 +130,18 @@ class ChatTool(Tool): # while a self-refreshing view feeds each row's live preview (see _LiveLasts). lasts = ctx.repo.last_chat_messages() live = _LiveLasts(ctx, seed=lasts) + # Names in previews/mentions resolve back to keys for their hue (the app-wide + # colour rule); a name no contact or stored advert carries stays muted. + key_of = make_name_key_resolver(contacts, ctx.repo.node_names()) items: list = [ Separator(_picker_header()), Separator("── 📡 Channels ──", style="accent"), ] for conversation in channels: - items.append(Choice(title=_row_title(ctx, conversation, live), value=conversation)) + items.append( + Choice(title=_row_title(ctx, conversation, live, key_of), value=conversation) + ) items.append(Separator("── 👤 Direct ──", style="accent")) if contacts: @@ -145,7 +152,12 @@ class ChatTool(Tool): ] direct.sort(key=lambda conv: _recency_key(conv, lasts)) for conversation in direct: - items.append(Choice(title=_row_title(ctx, conversation, live), value=conversation)) + items.append( + Choice( + title=_row_title(ctx, conversation, live, key_of), + value=conversation, + ) + ) else: items.append(Separator(" (no contacts yet — receive an advert first)")) @@ -576,7 +588,10 @@ def _picker_header() -> str: def _row_title( - ctx: AppContext, conversation: Conversation, lasts: "_LiveLasts" + ctx: AppContext, + conversation: Conversation, + lasts: "_LiveLasts", + key_of: NameKeyResolver, ) -> Callable[[], Union[str, Text]]: """Return a picker-row title *callable* the select screen re-renders on each repaint. @@ -588,30 +603,36 @@ def _row_title( ctx: Shared application context (for the live unread count). conversation: The conversation the row represents. lasts: The self-refreshing latest-message view feeding the preview. + key_of: Maps a sender name back to its node's key, for the preview hues. Returns: A zero-argument callable producing the current row title. """ - return lambda: _title(ctx, conversation, lasts) + return lambda: _title(ctx, conversation, lasts, key_of) def _title( - ctx: AppContext, conversation: Conversation, lasts: "_LiveLasts" + ctx: AppContext, + conversation: Conversation, + lasts: "_LiveLasts", + key_of: NameKeyResolver, ) -> Union[str, Text]: """Build a picker row as fixed-width, colour-coded lanes. Alignment carries the readability — marker, label, unread badge, relative age, and preview each sit in their own lane, so every row's message text starts in the same column. Colour is - kept light and purposeful: the name stays in the base colour, a contact's leading dot is - tinted in that person's chat hue, the unread ``●`` badge is red, the age is muted, and the - preview mutes its body while lighting sender names and ``@mentions`` in their hue — the same - colours the live transcript uses. The row is always a Rich :class:`~rich.text.Text` so those - spans survive under the select screen's row highlight. + purposeful: a direct contact's name takes its key-derived palette hue (a channel label stays + base), the leading dot is the standard companion pink with its shape marking history, the + unread ``●`` badge is red, the age is muted, and the preview mutes its body while lighting + sender names and ``@mentions`` in their key-derived hue — the same colours the live + transcript uses. The row is always a Rich :class:`~rich.text.Text` so those spans survive + under the select screen's row highlight. Args: ctx: Shared application context (for the live unread count). conversation: The conversation the row represents. lasts: The self-refreshing latest-message view. + key_of: Maps a preview sender/mention name back to its node's key. Returns: The row title as a styled :class:`~rich.text.Text`. @@ -620,7 +641,13 @@ def _title( last = lasts.get(conversation.key) text = Text(no_wrap=True, overflow="ellipsis") _append_marker(text, conversation, last) - text.append(fit_cells(conversation.label, _LABEL_WIDTH)) + label_style = "" + if not conversation.is_channel and conversation.contact is not None: + contact = conversation.contact + label_style = name_style( + conversation.label, contact.public_key or contact.key_prefix + ) + text.append(fit_cells(conversation.label, _LABEL_WIDTH), style=label_style or None) text.append(" ") # Unread badge lane (_BADGE_WIDTH cells): a red ● with the count in warn, or blank filler so # the following lanes still line up on rows with nothing unread. @@ -636,62 +663,70 @@ def _title( text.append(f"{age:>{_AGE_WIDTH}}", style="muted") text.append(" ") if last is not None: - text.append_text(_preview_text(last)) + text.append_text(_preview_text(last, key_of)) return text +#: The standard companion pink — the shared plain-node ``●`` colour — the contact dot's +#: hue: the shape (filled/hollow) marks history, the colour marks "a companion", and the +#: name beside it carries the person's own key-derived hue. +_COMPANION_DOT_STYLE = _NODE_GLYPHS[NODE_TYPE_CHAT][1] + + def _append_marker(text: Text, conversation: Conversation, last: Optional[ChatMessage]) -> None: """Prepend the row's leading marker (3 display cells) — a channel glyph or a contact dot. - A channel keeps its openness marker (# / 🌐 / 🔒). A contact gets a small circle tinted in - that person's chat hue — filled (``●``) once we've exchanged messages, a hollow ring (``○``) - before any — so the colour identifies the person and the hollow-vs-filled shape marks whether - there's history, while the name itself stays in the base colour. The contact dot is padded to - the same width as a channel's double-cell glyph so the labels line up across both sections. + A channel keeps its openness marker (# / 🌐 / 🔒). A contact gets a small circle in the + standard companion pink — filled (``●``) once we've exchanged messages, a hollow ring + (``○``) before any — so the hollow-vs-filled shape marks whether there's history while the + name itself carries the person's key-derived hue. The contact dot is padded to the same + width as a channel's double-cell glyph so the labels line up across both sections. """ if conversation.is_channel: text.append(f"{channel_glyph(conversation.label, conversation.secret)} ") else: dot = "●" if last is not None else "○" - text.append(dot, style=_sender_hue(conversation.label)) + text.append(dot, style=_COMPANION_DOT_STYLE) text.append(" ") -def _preview_text(last: ChatMessage) -> Text: - """A muted last-message preview with sender names and ``@mentions`` lit in their chat hue. +def _preview_text(last: ChatMessage, key_of: NameKeyResolver) -> Text: + """A muted last-message preview with sender names and ``@mentions`` lit in their hue. Mirrors the live transcript: our own messages get a ``you:`` prefix, an inbound channel - message's inline ``Name:`` sender is coloured in that sender's hue, and every ``@[Name]`` - mention reads as a bare ``@Name`` in the mentioned person's hue — so the list and the chat - speak the same colour language. The result is clipped to :data:`_PREVIEW_WIDTH` cells. + message's inline ``Name:`` sender is coloured in its key-derived hue (muted when no known + node carries the name), and every ``@[Name]`` mention reads as a bare ``@Name`` the same + way — so the list and the chat speak the same colour language. The result is clipped to + :data:`_PREVIEW_WIDTH` cells. """ body_raw = last.text.replace("\n", " ") text = Text() if last.outbound: text.append("you: ", style="accent") - _append_body(text, body_raw) + _append_body(text, body_raw, key_of) elif last.is_channel: name, body = _split_channel_sender(body_raw) if name is not None: - text.append(name, style=_sender_hue(name)) + text.append(name, style=name_style(name, key_of(name))) text.append(": ", style="muted") - _append_body(text, body) + _append_body(text, body, key_of) else: - _append_body(text, body_raw) + _append_body(text, body_raw, key_of) else: - _append_body(text, body_raw) + _append_body(text, body_raw, key_of) text.truncate(_PREVIEW_WIDTH, overflow="ellipsis") return text -def _append_body(text: Text, body: str) -> None: - """Append ``body`` to ``text``, muted, with each ``@[Name]`` mention drawn in the name's hue.""" +def _append_body(text: Text, body: str, key_of: NameKeyResolver) -> None: + """Append ``body`` to ``text``, muted, with each ``@[Name]`` mention drawn in the + mentioned node's key-derived hue (muted when the name resolves to no known node).""" 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(f"@{name}", style=_sender_hue(name)) + text.append(f"@{name}", style=name_style(name, key_of(name))) 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 3125f71..f9f50d7 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -59,18 +59,6 @@ _FAILED = ("✗", "err") #: Seconds between spinner frames on a message that is still awaiting its ack. _SPINNER_INTERVAL = 0.12 -def _sender_hue(sender: str) -> str: - """The stable per-sender colour a name is drawn in, keyed on the name's characters. - - The app-wide name palette (:func:`~meshterm.ui.theme.name_style`), shared by the live - transcript (sender headers, ``@mentions``), the conversation list (a contact's colour - dot, a channel preview's inline sender), the dashboard feed, and the packet viewer, so - a person reads the same colour everywhere. ``you`` and unknown (``·``) senders are - handled by the caller. - """ - return name_style(sender) - - #: The sender-prefix parser, shared app-wide from the protocol layer (the transcript, #: the conversation picker, the dashboard feed, and the message-paths matcher must all #: split ``Name: body`` identically). Kept under its old private name for the callers @@ -102,6 +90,7 @@ class ChatScreen(Screen): session, # noqa: ANN001 - TuiSession, imported lazily to avoid a cycle resend: Optional[Callable[[ChatMessage], Awaitable[ChatMessage]]] = None, paths: Optional[Callable[[ChatMessage], Awaitable[None]]] = None, + key_of: Optional[Callable[[str], Optional[str]]] = None, ) -> None: """Build the chat screen. @@ -118,10 +107,22 @@ class ChatScreen(Screen): message, updating it in place (direct chats only; ``None`` for channels). paths: Async callable that presents the delivery paths of one message (the ^P view); ``None`` leaves the affordance quietly inert. + key_of: Maps a sender's display name back to its node's key (see + :func:`~meshterm.services.trace_runner.make_name_key_resolver`), the seed + of the sender's hue; ``None`` (or a name it can't place) leaves senders + muted — colour is reserved for keyed identities. """ super().__init__() self.title = conversation.label self._is_channel = conversation.is_channel + self._key_of: Callable[[str], Optional[str]] = key_of or (lambda name: None) + # A direct thread's one remote sender is the peer; its key colours the header + # even when the resolver can't place the display name. + contact = conversation.contact + self._peer_key = ( + "" if conversation.is_channel or contact is None + else (contact.public_key or contact.key_prefix or "") + ) self._messages = list(messages) self._send = send self._resend = resend @@ -402,18 +403,24 @@ class ChatScreen(Screen): ) def _sender_style(self, sender: str, *, is_self: bool = False) -> str: - """Pick a stable color for a channel sender. + """Pick a stable color for a sender name — keyed on the sender's node key. Our own messages are white — keyed on ``is_self`` (the message being outbound), not on the ``"you"`` label, so a remote sender who happens to be named ``you`` still gets - a hue from the palette rather than masquerading as us. ``·`` (unknown) is muted; every - other sender gets a stable hue derived from its name. + a hue from the palette rather than masquerading as us. ``·`` (unknown) is muted. + Every other sender resolves its name back to a key (contacts, then the recorder's + stored names; a direct thread falls back to the peer's own key) and takes that + key's hue; a name no known node carries stays muted — the app-wide rule that + colour marks a keyed identity. """ if is_self: return "you" # white, out of the per-sender hue range — always easy to spot if sender == "·": return "muted" - return _sender_hue(sender) + key = self._key_of(sender) + if not key and not self._is_channel: + key = self._peer_key or None + return name_style(sender, key) # --- input --------------------------------------------------------------- @@ -744,13 +751,17 @@ async def open_chat(ctx: "AppContext", conversation: Conversation) -> int: except Exception: # noqa: BLE001 - the hub may already be running; recording is best-effort pass + from ..services import trace_runner + history = ctx.repo.recent_chat_messages( is_channel=conversation.is_channel, channel_id=conversation.channel_id, peer=conversation.peer, limit=_HISTORY_LIMIT, ) - names = _contact_names(await ctx.devstate.contacts()) + contacts = await ctx.devstate.contacts() + names = _contact_names(contacts) + key_of = trace_runner.make_name_key_resolver(contacts, ctx.repo.node_names()) async def send(text: str) -> Optional[ChatMessage]: if conversation.is_channel: @@ -777,6 +788,7 @@ async def open_chat(ctx: "AppContext", conversation: Conversation) -> int: session=session, resend=resend, paths=paths, + key_of=key_of, ) ctx.chat.set_active(conversation.key) @@ -868,6 +880,7 @@ async def _make_paths_presenter( contacts = await ctx.devstate.contacts() resolve = trace_runner.make_node_resolver(contacts, ctx.repo.node_names()) type_of = trace_runner.make_node_type_resolver(contacts) + key_of = trace_runner.make_name_key_resolver(contacts, ctx.repo.node_names()) prefix_bytes = await _routing_prefix_bytes(ctx) self_name: Optional[str] = None try: @@ -923,7 +936,7 @@ async def _make_paths_presenter( MessagePathsScreen( message, arrivals, matched=matched, resolve=resolve, prefix_bytes=prefix_bytes, self_name=self_name, summary=summary, - source=source or None, type_of=type_of, + source=source or None, type_of=type_of, key_of=key_of, ) ) diff --git a/meshterm/ui/livefeed_screen.py b/meshterm/ui/livefeed_screen.py index 6730e19..d5307a3 100644 --- a/meshterm/ui/livefeed_screen.py +++ b/meshterm/ui/livefeed_screen.py @@ -41,7 +41,7 @@ from .packet_viewer import ( from .theme import name_style, snr_style from .tui.render import render_to_ansi from .tui.screen import ListWindow, Screen -from .widgets import TypeOf, path_text +from .widgets import NameKeyResolver, TypeOf, path_text if TYPE_CHECKING: from ..context import AppContext @@ -90,6 +90,7 @@ class LiveFeedScreen(Screen): self_name: Optional[str] = None, channels: Sequence[tuple[str, bytes]] = (), type_of: Optional[TypeOf] = None, + key_of: Optional[NameKeyResolver] = None, ) -> None: """Create the feed over its data feeds. @@ -106,6 +107,10 @@ class LiveFeedScreen(Screen): so it can attempt to decrypt an overheard channel-text packet. type_of: Maps a relay hash to its node type, handed to the packet viewer so a relayed packet's route graph marks a repeater ``▲`` (etc.) over a dot. + key_of: Maps a sender's display name back to its node's key (see + :func:`~meshterm.services.trace_runner.make_name_key_resolver`), so a + channel sender the contacts or the recorder know takes its key-derived + hue; an unresolvable name stays muted. """ super().__init__() self.title = "Live feed" @@ -116,6 +121,7 @@ class LiveFeedScreen(Screen): self._self_name = self_name self._channels = channels self._type_of = type_of + self._key_of: NameKeyResolver = key_of or (lambda name: None) #: The feed: latest events of every class as data, newest first — rendered #: fresh each paint (rows adapt to width) and handed whole to the viewer. self._feed: deque[PacketEntry] = deque(maxlen=_FEED_CAP) @@ -230,7 +236,7 @@ class LiveFeedScreen(Screen): list(self._feed), self._selected, resolve=self._resolve, prefix_bytes=self._prefix_bytes, self_name=self._self_name, on_navigate=follow, - channels=self._channels, type_of=self._type_of, + channels=self._channels, type_of=self._type_of, key_of=self._key_of, # The live feed itself (newest first), so the viewer keeps up with packets # that arrive while it is open instead of freezing at this snapshot. source=lambda: list(self._feed), @@ -324,7 +330,9 @@ class LiveFeedScreen(Screen): sender = _channel_sender(entry.text) if sender: ours = self._self_name and sender == self._self_name - return sender, ("you" if ours else name_style(sender)) + # A resolvable sender takes its key-derived hue; a stranger stays + # muted — colour is reserved for keyed identities. + return sender, ("you" if ours else name_style(sender, self._key_of(sender))) return "channel", "muted" if entry.kind == "packet": cls = payload_class(entry.raw) @@ -394,6 +402,7 @@ async def open_livefeed(ctx: "AppContext") -> None: # app-wide rule that a node we can name never renders as a bare hash. resolve = trace_runner.make_node_resolver(contacts, ctx.repo.node_names()) type_of = trace_runner.make_node_type_resolver(contacts) + key_of = trace_runner.make_name_key_resolver(contacts, ctx.repo.node_names()) prefix_bytes = await _routing_prefix_bytes(ctx) seed = ctx.repo.recent_observations(since=utcnow() - OBSERVATION_WINDOW) @@ -406,6 +415,7 @@ async def open_livefeed(ctx: "AppContext") -> None: self_name=self_name, channels=channels, type_of=type_of, + key_of=key_of, ) unsubscribe = ctx.events.subscribe(screen.on_event) diff --git a/meshterm/ui/message_paths_screen.py b/meshterm/ui/message_paths_screen.py index be03f0d..7f5fd98 100644 --- a/meshterm/ui/message_paths_screen.py +++ b/meshterm/ui/message_paths_screen.py @@ -38,7 +38,14 @@ from .pathgraph import PathLayer, render_path_graph from .theme import snr_style from .tui.render import crop_cells, render_to_ansi from .tui.screen import Screen -from .widgets import NodeResolver, TypeOf, node_type_legend, path_text, route_graph_style +from .widgets import ( + NameKeyResolver, + NodeResolver, + TypeOf, + node_type_legend, + path_text, + route_graph_style, +) #: Cells one ←/→ press shifts the selected row by. _HSTEP = 4 @@ -63,6 +70,7 @@ class MessagePathsScreen(Screen): summary: str, source: Optional[str] = None, type_of: Optional[TypeOf] = None, + key_of: Optional["NameKeyResolver"] = None, ) -> None: """Build the dialog over one message's matched arrivals. @@ -82,6 +90,9 @@ class MessagePathsScreen(Screen): (``None`` reads as an unknown ``?`` origin). type_of: Maps a relay hash to its node type, so the graph marks a repeater ``▲`` (etc.) instead of a generic dot; ``None`` keeps the plain dots. + key_of: Maps the origin's display name back to its node's key, so the + graph's left endpoint takes its key-derived hue; ``None`` (or an + unresolvable name) leaves it muted. """ super().__init__() self.title = "Message paths" @@ -94,6 +105,7 @@ class MessagePathsScreen(Screen): self._summary = summary self._source = source self._type_of = type_of + self._key_of = key_of self._index = 0 #: Cells the selected row is shifted left by (reset whenever ↑↓ move), and #: how far it *can* shift, measured against the width of the last render. @@ -277,7 +289,7 @@ class MessagePathsScreen(Screen): ] glyph_of, label_of, label_rgb_of = route_graph_style( resolve=self._resolve, self_name=self._self_name, source=self._source, - type_of=self._type_of, + type_of=self._type_of, key_of=self._key_of, ) return render_path_graph( layers, width, diff --git a/meshterm/ui/packet_viewer.py b/meshterm/ui/packet_viewer.py index 9337e3e..1e7783d 100644 --- a/meshterm/ui/packet_viewer.py +++ b/meshterm/ui/packet_viewer.py @@ -43,6 +43,7 @@ from .trace_screen import snr_bar from .tui.render import render_lines, render_to_ansi from .tui.screen import Screen from .widgets import ( + NameKeyResolver, TypeOf, _age_seconds, format_ago, @@ -293,6 +294,7 @@ class PacketViewer(Screen): channels: Sequence[tuple[str, bytes]] = (), source: Optional[Callable[[], Sequence[PacketEntry]]] = None, type_of: Optional[TypeOf] = None, + key_of: Optional[NameKeyResolver] = None, ) -> None: """Open the viewer over a packet list. @@ -316,6 +318,9 @@ class PacketViewer(Screen): type_of: Maps a relay hash to its node type, so a relayed packet's route graph marks a repeater ``▲`` (etc.) instead of a generic dot; ``None`` keeps the plain named-dot / unknown-ring fallback. + key_of: Maps an origin's display name back to its node's key, so the route + graph's left endpoint takes its key-derived hue; ``None`` (or an + unresolvable name) leaves it muted. """ super().__init__() self._entries = list(entries) @@ -327,6 +332,7 @@ class PacketViewer(Screen): self._channels = channels self._source = source self._type_of = type_of + self._key_of = key_of #: The packet currently shown, tracked by identity so a live prepend to the #: source (which shifts every index) never slides the view onto another packet. self._current: Optional[PacketEntry] = ( @@ -540,6 +546,7 @@ class PacketViewer(Screen): glyph_of, label_of, label_rgb_of = route_graph_style( resolve=self._resolve, self_name=self._self_name, source=self._graph_source(entry), type_of=self._type_of, + key_of=self._key_of, ) return render_path_graph( [PathLayer(hops=hops, color=_ROUTE_EDGE, priority=3)], diff --git a/meshterm/ui/theme.py b/meshterm/ui/theme.py index 94cae43..11b67ed 100644 --- a/meshterm/ui/theme.py +++ b/meshterm/ui/theme.py @@ -174,20 +174,23 @@ def name_style(name: str, key: Optional[str] = None) -> str: """The stable colour a node or sender name is drawn in — keyed on the node's key. Args: - name: The display name. + name: The display name (unused for the hue; kept so every call site reads + ``name_style(name, key)`` and the pair stays greppable). key: Any known prefix of the node's key/hash; when given, the hue is :func:`node_style`'s — hash-derived, so a rename keeps the colour and every - surface that knows the key agrees. ``None``/empty marks a genuinely keyless - sender (a channel message's inline name), coloured by the name's characters - as the stable fallback. + surface that knows the key agrees. ``None``/empty marks a sender whose key + we couldn't resolve — drawn ``muted``, because colour is reserved for keyed + identities (callers with only a name resolve it first via + :func:`~meshterm.services.trace_runner.make_name_key_resolver`). Returns: - A style string from :data:`NAME_COLORS`; the same node always maps to the - same hue, so it keeps its colour across screens and sessions. + A style string from :data:`NAME_COLORS` (or ``muted`` for the keyless); the + same node always maps to the same hue, so it keeps its colour across screens + and sessions. """ if key: return node_style(key) - return NAME_COLORS[sum(map(ord, name)) % len(NAME_COLORS)] + return "muted" def snr_style(snr: float | None) -> str: diff --git a/meshterm/ui/widgets.py b/meshterm/ui/widgets.py index c66cd06..3a0cd42 100644 --- a/meshterm/ui/widgets.py +++ b/meshterm/ui/widgets.py @@ -48,6 +48,10 @@ if TYPE_CHECKING: #: Maps a hop's raw key-prefix hash to a display label (a contact name when known). NodeResolver = Callable[[Optional[str]], Optional[str]] +#: Maps a display name back to its node's key hex, or ``None`` for a name no known +#: node carries (built by :func:`~meshterm.services.trace_runner.make_name_key_resolver`). +NameKeyResolver = Callable[[str], Optional[str]] + def channel_glyph(name: str, secret: Optional[bytes]) -> str: """The one-character openness marker for a channel, shared across channel-facing screens. @@ -440,9 +444,19 @@ def _shorten_hash(value: str, hash_bytes: Optional[int]) -> str: _SELF_RGB: RGB = (255, 255, 255) +#: The truecolour of the ``muted`` grey — what a keyless name's hue collapses to on a +#: raster (mirrors ``theme``'s muted ``#94a3b8``). +_MUTED_RGB: RGB = (148, 163, 184) + + def _name_rgb(name: str, key: Optional[str] = None) -> RGB: - """The RGB of a node's stable palette hue (``theme.name_style`` minus its bold).""" - return parse_hex(name_style(name, key).split()[-1]) + """The RGB of a node's stable palette hue (``theme.name_style`` minus its bold). + + A name with no resolvable key styles ``muted`` (no hex to parse), so it lands on + the muted grey here — the raster twin of the app-wide keyless-stays-muted rule. + """ + hexpart = name_style(name, key).split()[-1] + return parse_hex(hexpart) if hexpart.startswith("#") else _MUTED_RGB def name_rgb(name: str, key: Optional[str] = None) -> RGB: @@ -468,6 +482,7 @@ def route_graph_style( self_name: Optional[str], source: Optional[str], type_of: Optional[TypeOf] = None, + key_of: Optional[NameKeyResolver] = None, ) -> tuple[GlyphOf, LabelOf, LabelRgbOf]: """Build the per-node callbacks that draw a route on THE route graph (``pathgraph``). @@ -489,6 +504,10 @@ def route_graph_style( (``▲`` repeater, ``■`` room, ``◉`` sensor) in the shared palette instead of a generic dot. ``None``, or a hash whose type it can't resolve, keeps the old named-dot / unknown-ring fallback. + key_of: Maps the ``source`` display name back to its node's key (see + :func:`~meshterm.services.trace_runner.make_name_key_resolver`), so the left + endpoint's label takes its key-derived hue; ``None``, or a name it can't + place, leaves the origin muted — colour is reserved for keyed identities. Returns: The ``(glyph_of, label_of, label_rgb_of)`` triple to hand to @@ -524,7 +543,9 @@ def route_graph_style( if node == SRC_NODE: if src_is_self: return _SELF_RGB - return _name_rgb(source) if source else parse_hex(_UNKNOWN[1]) + if not source: + return parse_hex(_UNKNOWN[1]) + return _name_rgb(source, key_of(source) if key_of else None) named = resolve(node) if named and named != node: return _name_rgb(named, node) diff --git a/tests/test_chat.py b/tests/test_chat.py index bc5d215..be093e2 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -234,6 +234,15 @@ def test_live_lasts_serves_seed_within_ttl(repo: Repository) -> None: assert live.get("chan:c0").text == "seed" +#: A resolver that places no name — every hue falls back to muted. +_NO_KEYS = lambda name: None # noqa: E731 - a one-line stub reads best inline + + +def _keys_of(mapping: dict[str, str]): + """A canned name→key resolver over ``mapping`` (casefolded, like the real one).""" + return lambda name: mapping.get(name.casefold()) + + def test_preview_prefixes_own_messages_only() -> None: """Only outbound messages get a ``you:`` prefix; inbound text is shown verbatim. @@ -241,28 +250,37 @@ def test_preview_prefixes_own_messages_only() -> None: synthesized (that would double it), and a direct message's author is the row label. """ chan_in = ChatMessage(text="Bob: hi", is_channel=True, channel_idx=0) # sender inline - assert _preview_text(chan_in).plain == "Bob: hi" + assert _preview_text(chan_in, _NO_KEYS).plain == "Bob: hi" dm_in = ChatMessage(text="hey", peer="aa", peer_name="Bob") - assert _preview_text(dm_in).plain == "hey" + 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).plain == "you: yo" + assert _preview_text(mine, _NO_KEYS).plain == "you: yo" def test_preview_colours_channel_sender_and_mentions() -> None: - """A channel preview lights its inline sender name and any ``@[Name]`` mention in a hue.""" - from meshterm.ui.chat import _sender_hue + """A preview lights resolvable sender/mention names in their key-derived hue. - msg = ChatMessage(text="Bob: hi @[Alice]", is_channel=True, channel_idx=0) - preview = _preview_text(msg) - assert preview.plain == "Bob: hi @Alice" # the mention's brackets are dropped for display + A name no known node carries stays muted — colour is reserved for keyed identities. + """ + from meshterm.ui.theme import node_style + + key_of = _keys_of({"bob": "d4" + "0" * 62, "alice": "60" + "0" * 62}) + msg = ChatMessage(text="Bob: hi @[Alice] @[Zed]", is_channel=True, channel_idx=0) + preview = _preview_text(msg, key_of) + assert preview.plain == "Bob: hi @Alice @Zed" # brackets dropped for display styles = {span.style for span in preview.spans} - assert _sender_hue("Bob") in styles and _sender_hue("Alice") in styles + assert node_style("d4") in styles and node_style("60") in styles + # The unresolvable @Zed stays muted like the body around it. + zed = preview.plain.index("@Zed") + assert any( + s.style == "muted" and s.start <= zed < s.end for s in preview.spans + ) def test_preview_ellipsizes_long_text() -> None: """An over-long preview is clipped to the width budget with a trailing ellipsis.""" long = ChatMessage(text="x" * 100, is_channel=True, channel_idx=0) - out = _preview_text(long).plain + out = _preview_text(long, _NO_KEYS).plain assert len(out) == _PREVIEW_WIDTH and out.endswith("…") @@ -271,7 +289,7 @@ def test_title_shows_badge_and_author_preview(repo: Repository) -> None: conv = Conversation(label="General", is_channel=True, channel_idx=0, channel_id="c0") ctx = _RowCtx(repo, unread={"chan:c0": 3}) last = ChatMessage(text="Bob: hi there", is_channel=True, channel_id="c0") # sender inline - title = _title(ctx, conv, {"chan:c0": last}) + title = _title(ctx, conv, {"chan:c0": last}, _NO_KEYS) line = title.plain # a Text, since there is unread assert line.startswith("🔒 General") # a private channel leads with its openness glyph assert "● 3" in line @@ -283,7 +301,7 @@ def test_title_reddens_only_the_unread_dot(repo: Repository) -> None: from rich.text import Text conv = Conversation(label="General", is_channel=True, channel_idx=0, channel_id="c0") - unread = _title(_RowCtx(repo, unread={"chan:c0": 2}), conv, {}) + unread = _title(_RowCtx(repo, unread={"chan:c0": 2}), conv, {}, _NO_KEYS) assert isinstance(unread, Text) dot = unread.plain.index("●") reddened = [ @@ -291,7 +309,7 @@ def test_title_reddens_only_the_unread_dot(repo: Repository) -> None: ] assert reddened and all(span.end - span.start == 1 for span in reddened) # just the glyph - read = _title(_RowCtx(repo, unread={}), conv, {}) + read = _title(_RowCtx(repo, unread={}), conv, {}, _NO_KEYS) assert isinstance(read, Text) # always a Text now, so its spans can carry the row's colour assert "●" not in read.plain # nothing unread -> no badge dot assert not any(span.style == "err" for span in read.spans) @@ -304,15 +322,15 @@ def test_title_preview_column_aligns_regardless_of_label_length(repo: Repository long = Conversation(label="A much longer channel name here", is_channel=True, channel_idx=1, channel_id="c1") m0 = ChatMessage(text="X: hello", is_channel=True, channel_id="c0") m1 = ChatMessage(text="Y: hello", is_channel=True, channel_id="c1") - l0 = _title(ctx, short, {"chan:c0": m0}).plain - l1 = _title(ctx, long, {"chan:c1": m1}).plain + l0 = _title(ctx, short, {"chan:c0": m0}, _NO_KEYS).plain + l1 = _title(ctx, long, {"chan:c1": m1}, _NO_KEYS).plain assert l0.index("X: hello") == l1.index("Y: hello") def test_title_leads_with_openness_glyph(repo: Repository) -> None: """Channel rows lead with an openness glyph: # name-derived, 🌐 fixed-key public, 🔒 private.""" ctx = _RowCtx(repo) - head = lambda conv: _title(ctx, conv, {}).plain.split(" ", 1)[0] + head = lambda conv: _title(ctx, conv, {}, _NO_KEYS).plain.split(" ", 1)[0] named = Conversation( label="#general", is_channel=True, channel_id="c0", secret=derive_secret("#general") ) @@ -328,29 +346,35 @@ def test_title_leads_with_openness_glyph(repo: Repository) -> None: def test_title_contact_dot_reflects_conversation_history(repo: Repository) -> None: - """A contact's dot is filled ● once we've talked, hollow ○ before — always in her hue.""" - from meshterm.ui.chat import _sender_hue + """A contact's dot fills ● once we've talked, hollow ○ before — companion pink both + ways — while the name itself carries the contact's key-derived hue.""" + from meshterm.tools.chat import _COMPANION_DOT_STYLE + from meshterm.ui.theme import node_style ctx = _RowCtx(repo) contact = Conversation( label="Alice", is_channel=False, contact=Contact(name="Alice", public_key="d4" + "0" * 62) ) - head = lambda lasts: _title(ctx, contact, lasts).plain.split(" ", 1)[0] - def dot_is_hued(row) -> bool: + def dot_is_pink(row) -> bool: return any( - span.style == _sender_hue("Alice") and span.start == 0 and span.end == 1 + span.style == _COMPANION_DOT_STYLE and span.start == 0 and span.end == 1 for span in row.spans ) - # No history yet — a hollow ring, but still tinted in Alice's stable chat hue. - fresh = _title(ctx, contact, {}) - assert fresh.plain.startswith("○") and dot_is_hued(fresh) + # No history yet — a hollow ring in the standard companion pink. + fresh = _title(ctx, contact, {}, _NO_KEYS) + assert fresh.plain.startswith("○") and dot_is_pink(fresh) + # The name lane carries Alice's key-derived hue. + name_at = fresh.plain.index("Alice") + assert any( + s.style == node_style("d4") and s.start <= name_at < s.end for s in fresh.spans + ) - # Once we've exchanged messages the same-hued dot fills in. + # Once we've exchanged messages the same pink dot fills in. last = ChatMessage(text="hi", peer=contact.peer) - talked = _title(ctx, contact, {contact.key: last}) - assert talked.plain.startswith("●") and dot_is_hued(talked) + talked = _title(ctx, contact, {contact.key: last}, _NO_KEYS) + assert talked.plain.startswith("●") and dot_is_pink(talked) # -- chat service ------------------------------------------------------------- @@ -696,30 +720,40 @@ def test_wrapped_body_hangs_under_the_first_line() -> None: def test_at_mention_renders_as_name_in_sender_hue() -> None: - """An ``@[Name]`` token renders as a bare ``@Name`` colored in that sender's hue.""" + """An ``@[Name]`` token renders as a bare ``@Name`` in the node's key-derived hue. + + A mentioned name no contact or stored advert carries stays muted — the app-wide + rule that colour marks a keyed identity. + """ from datetime import datetime, timezone - from meshterm.ui.theme import NAME_COLORS as _SENDER_COLORS + from meshterm.ui.theme import NAME_COLORS as _SENDER_COLORS, node_style base = datetime(2026, 7, 5, 14, 24, tzinfo=timezone.utc) conv = Conversation(label="#public", is_channel=True, channel_idx=0) message = ChatMessage( - text="Bob: @[Alice] you around?", is_channel=True, channel_idx=0, created_at=base + text="Bob: @[Alice] and @[Zed] around?", is_channel=True, channel_idx=0, + created_at=base, + ) + screen = ChatScreen( + conv, [message], send=None, names={}, session=_StubSession(), + key_of=_keys_of({"alice": "60" + "0" * 62}), ) - screen = ChatScreen(conv, [message], send=None, names={}, session=_StubSession()) _, body = screen._sender_and_body(message) text = screen._render_mentions(body, selected=False) assert "@Alice" in text.plain # bracketed token collapsed to a bare mention assert "@[Alice]" not in text.plain and "[Alice]" not in text.plain - # The "@Alice" run carries Alice's palette hue (the same the header would use). + # The "@Alice" run carries the key-derived hue (the same the header would use). hue = screen._sender_style("Alice") - assert hue in _SENDER_COLORS + assert hue == node_style("60") and hue in _SENDER_COLORS at = text.plain.index("@Alice") hue_spans = [ s for s in text.spans if s.style == hue and s.start <= at and at + len("@Alice") <= s.end ] assert hue_spans + # The unknown @Zed stays muted — no key, no colour. + assert screen._sender_style("Zed") == "muted" def test_direct_transcript_groups_under_sender_headers() -> None: @@ -996,15 +1030,18 @@ 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 follows the message being outbound, not the 'you' label. - A remote sender who happens to be named 'you' must still get a palette hue, never the - white style reserved for us. + A remote sender who happens to be named 'you' must never take the white style + reserved for us — it reads as a normal sender (its key's hue when resolvable, + muted otherwise). """ - from meshterm.ui.theme import NAME_COLORS as _SENDER_COLORS + from meshterm.ui.theme import NAME_COLORS as _SENDER_COLORS, node_style screen = _channel_screen([]) assert screen._sender_style("you", is_self=True) == "you" # us → white - remote = screen._sender_style("you", is_self=False) - assert remote != "you" and remote in _SENDER_COLORS # remote 'you' → a normal hue + assert screen._sender_style("you", is_self=False) == "muted" # no key → muted + keyed = _channel_screen([], key_of=_keys_of({"you": "d4" + "0" * 62})) + remote = keyed._sender_style("you", is_self=False) + assert remote == node_style("d4") and remote in _SENDER_COLORS def test_channel_own_messages_do_not_merge_with_remote_namesake() -> None: @@ -1021,11 +1058,12 @@ def test_channel_own_messages_do_not_merge_with_remote_namesake() -> None: assert rendered.count("you") == 2 # two separate headers, not one merged group -def _channel_screen(messages, session=None) -> ChatScreen: +def _channel_screen(messages, session=None, key_of=None) -> ChatScreen: """Build a channel ChatScreen over ``messages`` for selection/reply tests.""" conv = Conversation(label="#public", is_channel=True, channel_idx=0) return ChatScreen( - conv, messages, send=None, names={}, session=session or _StubSession() + conv, messages, send=None, names={}, session=session or _StubSession(), + key_of=key_of, ) diff --git a/tests/test_widgets.py b/tests/test_widgets.py index 62c177d..49dca22 100644 --- a/tests/test_widgets.py +++ b/tests/test_widgets.py @@ -122,3 +122,54 @@ def test_path_text_cursor_arrow_reads_as_a_reverse_block() -> None: # The cursor wins over dim_from: the arrow into a dimmed tail still reads selected. dimmed = path_text([None, "aa", None], _resolve, self_name="us", dim_from=2, cursor_arrow=1) assert any(str(s.style) == "selected" for s in dimmed.spans) + + +# --- the name→key resolver and the keyless-stays-muted rule -------------------------- + + +def test_make_name_key_resolver_contacts_win_over_stored_names() -> None: + """Contacts resolve first; stored advert names fill in strangers; misses are None.""" + from meshterm.core.models import Contact + from meshterm.services.trace_runner import make_name_key_resolver + + contacts = [Contact(name="Alice", public_key="d4" + "0" * 62)] + stored = {"60aabbccdd11": "Bob", "77ee00112233": "Alice"} # a stale stored Alice + key_of = make_name_key_resolver(contacts, stored) + assert key_of("Alice") == "d4" + "0" * 62 # the contact's key, not the stored id + assert key_of("alice") == "d4" + "0" * 62 # casefolded + assert key_of("Bob") == "60aabbccdd11" # a stored-name stranger still lands + assert key_of("Zed") is None # nobody carries the name + + +def test_name_style_without_a_key_is_muted() -> None: + """A keyless name has no hue — colour is reserved for keyed identities.""" + from meshterm.ui.theme import NAME_COLORS, name_style + + assert name_style("Stranger") == "muted" + assert name_style("Alice", "d4" + "0" * 62) in NAME_COLORS + + +def test_name_rgb_keyless_lands_on_the_muted_grey() -> None: + """The raster twin: a keyless name's RGB is the muted grey, never a crash.""" + from meshterm.ui.widgets import name_rgb + + assert name_rgb("Stranger") == (148, 163, 184) + assert name_rgb("Alice", "d4" + "0" * 62) != (148, 163, 184) + + +def test_route_graph_source_label_takes_its_resolved_keys_hue() -> None: + """The graph's left endpoint hue rides key_of: resolved → the key's hue, else muted.""" + from meshterm.ui.widgets import name_rgb, route_graph_style + + _, _, rgb_known = route_graph_style( + resolve=lambda h: h, self_name="us", source="Alice", + key_of=lambda name: "d4" + "0" * 62 if name == "Alice" else None, + ) + from meshterm.ui.pathgraph import SRC_NODE + + assert rgb_known(SRC_NODE) == name_rgb("Alice", "d4" + "0" * 62) + + _, _, rgb_unknown = route_graph_style( + resolve=lambda h: h, self_name="us", source="Alice", + ) + assert rgb_unknown(SRC_NODE) == (148, 163, 184) # unresolvable origin stays muted