The command line joins rooms, posts to them, and reads them by author
chat join logs in to a room server and prints what it allowed: member, admin or read-only. It uses --password, or the password MeshTerm remembers for the room. A room says nothing to a wrong password, so a join that hears nothing fails (exit 4) and names both possible reasons. send --to a room posts to it, and its receipt says kind "room". A room's history names each post's author where a direct transcript names the peer, drawn the way a route draws a hop: "Alice (d4e5f6a7)", or the bare hash when nothing names the key. The document carries the author on every row, null outside a room, so history answers in one shape for every kind of conversation; listen streams it too. chat list calls a room a room. The CLI manual, the features guide and the README describe rooms, and CLAUDE.md adds room and post to the lexicon, 📌 to the icons, and ^L to the chord list. Refs: #24 Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
1ceda7e22f
commit
1a101613b0
6 files changed
+366
-32
No files matched your search
@@ -67,6 +67,8 @@ them instead of hand-rolling:
|
||||
| region | a named area a repeater relays floods for (`region put yul`); shown bare, never `#yul` — the `#` belongs to key derivation only |
|
||||
| scope | the region a flood is limited to — a packet's, a channel's send scope, the device's default scope. A direct packet has none. MeshCore's sense and the only one: the menu's This node / Other nodes / This app sections name *whose* a setting is, never a "scope" |
|
||||
| unscoped | a plain flood, relayed by any repeater that allows the wildcard `*` |
|
||||
| room | a room server's message board — what you *join*, read, and *post* to. The node is the *room server*; the people let in are its *members*, at an *access* of member, admin, or read-only. Its two passwords are the *room password* and the *admin password* |
|
||||
| post | a message on a room's board, filed under its *author*: the key prefix the room signs it with, named by whatever names that key. A room's other traffic (its command replies) shares its key and is never a post |
|
||||
| Back | leave the current screen/list — Esc's word, and a row's only where leaving is a *choice* (see below) |
|
||||
| Quit | leave the app (main menu, device splash) — nowhere else |
|
||||
|
||||
@@ -252,7 +254,7 @@ deliberately, one at a time, and say why in the code.
|
||||
- **A bare-letter shortcut only where nothing is typed.** A screen that filters, finds or
|
||||
composes as you type has no free letters, so its verbs are Ctrl chords — one table,
|
||||
`session._CTRL_LETTER_CHORDS`, each letter the mnemonic of its action (`^P` paths,
|
||||
`^U` URL, `^Y` you). A screen that takes no typing may spend a bare letter instead (the
|
||||
`^U` URL, `^Y` you, `^L` log in). A screen that takes no typing may spend a bare letter instead (the
|
||||
Time Machine's `w`, the dashboard's `s`, the device splash's `h`). Either way the key
|
||||
is named where it acts: in the hint, and on the PicoCalc's lane.
|
||||
- Empty states are lowercase muted, optionally `— explanation`, never parenthesized.
|
||||
@@ -425,7 +427,7 @@ as a grouped list does. Filling a page in is editing its `.md`; no Python follow
|
||||
⚙ parameter · `#` count · ▶ run · ⚡ explore/probe · ★ best/winner · ⭐ watch ·
|
||||
📤 send now · 📨 courier/queue · 💬 chat · 🔔 notify · 🔕 mute (notifications off) ·
|
||||
📱 QR · 🔗 link · ↻ re-read · ↕ reorder · ⇄ reverse (flip a path's direction) ·
|
||||
🔖 region/scope · 🏆 trophy case/record · ⌨ command line · 📖 read/about · 💰 support/donate ·
|
||||
🔖 region/scope · 📌 rooms · 🏆 trophy case/record · ⌨ command line · 📖 read/about · 💰 support/donate ·
|
||||
🚪 quit. Packet-class icons (feed/viewer
|
||||
lane): 📢 advert · 📊 telemetry · 📦 packet · 💬 message · ✅ ack. Raw payload
|
||||
classes (`PAYLOAD_ICONS`): 📻 channel text · 💽 channel data · 📩 direct message
|
||||
|
||||
@@ -56,8 +56,9 @@ https://github.com/user-attachments/assets/f91a6695-14d5-4ae0-8fdc-e65492d0955d
|
||||
charts, and the Time Machine all read back that history.
|
||||
- **It measures.** Live trace with per-hop reliability, a coarse→refine→verify TX-power
|
||||
sweep, and a walkable graph of how the mesh actually hangs together.
|
||||
- **It talks.** Live channel and direct messaging, store-and-forward courier delivery for
|
||||
contacts that aren't there yet, and shareable channels as QR codes and `meshcore://` links.
|
||||
- **It talks.** Live channel and direct messaging, room servers' message boards,
|
||||
store-and-forward courier delivery for contacts that aren't there yet, and shareable
|
||||
channels as QR codes and `meshcore://` links.
|
||||
- **It connects however your companion does.** Serial (USB), Bluetooth LE, or TCP (a Wi-Fi
|
||||
board or a network proxy) — the discoverable transports are auto-found and picked
|
||||
interactively, a network device is named by hand, and every kind reconnects live when a link
|
||||
|
||||
+51
-5
@@ -1000,11 +1000,12 @@ The live transcript is a menu screen; from the command line, pick a subcommand.
|
||||
|
||||
| Subcommand | What it does |
|
||||
| --- | --- |
|
||||
| `send TEXT --to NAME` | Send a direct message. |
|
||||
| `send TEXT --to NAME` | Send a direct message, or post to a room. |
|
||||
| `send TEXT --channel N [--scope REGION]` | Broadcast on a channel slot, under the channel's scope — or under `REGION` for this one message, `*` for unscoped. |
|
||||
| `history [--to NAME \| --channel N] [--limit N]` | Print a conversation's stored transcript. Default limit 50. |
|
||||
| `list` | Every channel and contact with its unread count and last message. |
|
||||
| `list` | Every channel, room and contact with its unread count and last message. |
|
||||
| `listen [-s SECONDS] [--debug]` | Tail inbound messages live. `-s 0` (the default) runs until Ctrl-C. |
|
||||
| `join ROOM [--password PASSWORD]` | Log in to a room server, and print what it lets you do. |
|
||||
|
||||
Exactly one of `--to` and `--channel` is required on `send` and `history`.
|
||||
|
||||
@@ -1034,6 +1035,39 @@ $ meshterm --absolute chat history --to Alice
|
||||
of the line — a message body is the one field that can hold absolutely anything, so
|
||||
nothing may follow it.
|
||||
|
||||
**Rooms.** A room server is a message board that lives on a radio. It keeps the latest
|
||||
posts, and once you have logged in it sends you every post you missed, then each new one as
|
||||
people write it. You join a room by logging in with its password, which you get from
|
||||
whoever runs it:
|
||||
|
||||
```console
|
||||
$ meshterm chat join "Lakeside BBS" --password hello
|
||||
member
|
||||
```
|
||||
|
||||
`join` prints what the room let you do: `member` (read and post), `admin` (the room's
|
||||
owner), or `read-only` (the room drops anything you post). A password that works is
|
||||
remembered, so the next `join` needs no `--password`; an empty one (`--password ""`) asks
|
||||
the room whether it already knows you. A room never says a password is wrong. It just
|
||||
doesn't answer, so a `join` that hears nothing fails with exit `4`, and the message names
|
||||
both possible reasons. The posts the room sends after a login wait on your radio until
|
||||
something collects them: `chat listen`, or Chat in the menu.
|
||||
|
||||
Post with `send --to`, exactly like a direct message. `acked yes` means the room stored the
|
||||
post, not that anyone has read it. A room's `history` names who wrote each post, where a
|
||||
direct conversation names the peer:
|
||||
|
||||
```console
|
||||
$ meshterm chat history --to "Lakeside BBS"
|
||||
TIME DIR AUTHOR SNR_DB TEXT
|
||||
12m in Alice (d4e5f6a7) +6.5 Anyone driving to the swap meet Saturday?
|
||||
5m in e5f6a7b8 +2.0 Is the north repeater down?
|
||||
now out MockCompanion (00000000) - I'll check it tonight
|
||||
```
|
||||
|
||||
An author is a name with its key's hash, or just the hash when nothing you've heard names
|
||||
that key. Your own posts name your own node.
|
||||
|
||||
```console
|
||||
$ meshterm chat list
|
||||
CONVERSATION KIND UNREAD LAST LAST_TEXT
|
||||
@@ -1042,6 +1076,7 @@ Yagi-Repeater direct 0 never -
|
||||
Local-Repeater direct 0 never -
|
||||
Observer-Bot direct 0 never -
|
||||
Alice direct 0 never -
|
||||
Lakeside BBS room 0 never -
|
||||
```
|
||||
|
||||
```console
|
||||
@@ -1066,7 +1101,8 @@ $ meshterm chat send "net in 5" --channel 0 --json
|
||||
{"kind":"channel","node":null,"channel":{"slot":0,"name":"#0","public":true,"hash":null},"sent":true,"acked":null}
|
||||
```
|
||||
|
||||
`kind` is `"direct"` \| `"channel"` and says which of `node` / `channel` is populated.
|
||||
`kind` is `"direct"` \| `"room"` \| `"channel"` and says which of `node` / `channel` is
|
||||
populated (a room is a `node`).
|
||||
A channel send also carries `scope`, in the same shape `monitor` gives a received packet's:
|
||||
`{"state":"scoped","region":"harbour","code":null}` for a region, `"unscoped"` for a plain
|
||||
flood, and `null` where it isn't known (a direct message, or a channel with no scope of its
|
||||
@@ -1091,7 +1127,7 @@ there, having no way to say it.
|
||||
`history` is an array, oldest first:
|
||||
|
||||
```json
|
||||
{"created_at":"2026-09-08T08:27:37Z","direction":"out","node":{"name":"Alice","key":null,"hash":"d4e5f6a7","type":null,"self":false},"channel":null,"snr_db":null,"text":"on my way","acked":true}
|
||||
{"created_at":"2026-09-08T08:27:37Z","direction":"out","node":{"name":"Alice","key":null,"hash":"d4e5f6a7","type":null,"self":false},"channel":null,"author":null,"snr_db":null,"text":"on my way","acked":true}
|
||||
```
|
||||
|
||||
| Field | Type | Meaning |
|
||||
@@ -1100,6 +1136,7 @@ there, having no way to say it.
|
||||
| `direction` | string | `"in"` \| `"out"`. |
|
||||
| `node` | object \| null | The *other* party, for a direct conversation. |
|
||||
| `channel` | object \| null | The `channel` shape, for a channel conversation. |
|
||||
| `author` | object \| null | Who wrote a room post, as a `node`; on your own posts, your node. `null` outside a room. |
|
||||
| `snr_db` | number \| null | Reception SNR; `null` on an outbound message. |
|
||||
| `text` | string | The body, raw and unescaped. |
|
||||
| `acked` | boolean \| null | Delivery state of an outbound direct message; `null` inbound and on a channel. |
|
||||
@@ -1109,13 +1146,22 @@ there, having no way to say it.
|
||||
shape as `history`, with **`received_at`** in place of `created_at`:
|
||||
|
||||
```json
|
||||
{"received_at":"2026-09-08T08:30:47Z","node":{"name":null,"key":null,"hash":"b2c3d4e5","type":null,"self":false},"channel":null,"snr_db":4.9,"text":"hello from Local-Repeater #1","direction":"in","acked":null}
|
||||
{"received_at":"2026-09-08T08:30:47Z","node":{"name":null,"key":null,"hash":"b2c3d4e5","type":null,"self":false},"channel":null,"author":null,"snr_db":4.9,"text":"hello from Local-Repeater #1","direction":"in","acked":null}
|
||||
```
|
||||
|
||||
A room post arrives from the room, so its `node` is the room and its `author` carries the
|
||||
writer's hash.
|
||||
|
||||
An inbound message carries only the sender's key prefix, so its `node` is thinner than the
|
||||
same node in `contacts` — `name` is whatever the resolver could find and `key` is `null`.
|
||||
Join on `hash`.
|
||||
|
||||
`join` is the room and the access it granted:
|
||||
|
||||
```json
|
||||
{"room":{"name":"Lakeside BBS","key":"f6a7b8c900000000000000000000000000000000000000000000000000000000","hash":"f6a7b8c9","type":"room server","self":false},"access":"member"}
|
||||
```
|
||||
|
||||
`history`, `list` and `listen` return `5` when there is nothing to report.
|
||||
|
||||
#### `meshterm channels`
|
||||
|
||||
@@ -14,7 +14,7 @@ Every interactive screen is listed here with its scripted equivalent, where one
|
||||
|
||||
| Feature | What it does | Scripted |
|
||||
| --- | --- | --- |
|
||||
| **💬 Chat** | Live full-screen channel and direct messaging — a scrolling transcript with a pinned input line where sent and received messages stream together. Every message is logged; unread counts show in the menu header. | `meshterm chat send / history / list` |
|
||||
| **💬 Chat** | Live full-screen channel and direct messaging — a scrolling transcript with a pinned input line where sent and received messages stream together. **Rooms** are here too: a room server is a message board on a radio that keeps the latest posts and sends you the ones you missed. Join one with its password, then read and post, each post shown under whoever wrote it. Every message is logged; unread counts show in the menu header. | `meshterm chat send / history / list / listen / join` |
|
||||
| **📻 Channels** | Create, join, reorder, mute, and share mesh channels — with QR codes and `meshcore://` share links. Give a channel a **send scope** and its messages are flooded into one region, relayed only by the repeaters that carry it. | `meshterm channels list / add / join / import / share / clear / scope` |
|
||||
| **📨 Courier** | Store-and-forward outbox for contacts that aren't reachable yet. Queue a message; it goes out (with ack tracking and polite exponential backoff) the moment the contact is next heard, or at a scheduled time. | `meshterm courier queue / list / send / cancel / clear` |
|
||||
| **👥 Contacts** | This node and its known contacts — a recency heat-map, overheard packet counts, and full public keys with the path-hash prefix highlighted. The scripted listing is the contacts alone (this node is `meshterm info`'s answer, in far more detail). | `meshterm contacts` |
|
||||
|
||||
+215
-22
@@ -2,9 +2,11 @@
|
||||
"""The ``chat`` tool: channel and direct messaging over the mesh.
|
||||
|
||||
Interactively it opens a conversation picker and then a live, full-screen chat (see
|
||||
:mod:`meshterm.ui.chat`) where sent and received messages stream together. On the CLI it
|
||||
exposes ``send``, ``history``, and ``list`` subcommands for scripted use. Channels are only
|
||||
*listed* here for picking; creating and editing channel slots lives in the ``channels`` tool.
|
||||
:mod:`meshterm.ui.chat`) where sent and received messages stream together — or, for a room
|
||||
server, its board (:mod:`meshterm.ui.room`). On the CLI it exposes ``send``, ``history``,
|
||||
``list``, ``listen`` and ``join`` subcommands for scripted use; a room is addressed by
|
||||
``--to`` like a contact, and ``join`` logs in to one. Channels are only *listed* here for
|
||||
picking; creating and editing channel slots lives in the ``channels`` tool.
|
||||
|
||||
Every inbound message is recorded to history by the always-on
|
||||
:class:`~meshterm.services.chat_service.ChatService`, and outbound messages are recorded on
|
||||
@@ -316,7 +318,7 @@ class ChatTool(Tool):
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
action: One of ``send``, ``history``, ``list``.
|
||||
action: One of ``send``, ``history``, ``listen``, ``join``, ``list``.
|
||||
params: The action's arguments.
|
||||
|
||||
Returns:
|
||||
@@ -324,6 +326,8 @@ class ChatTool(Tool):
|
||||
"""
|
||||
if action == "send":
|
||||
return await self._cli_send(ctx, params)
|
||||
if action == "join":
|
||||
return await self._cli_join(ctx, params)
|
||||
if action == "history":
|
||||
return await self._cli_history(ctx, params)
|
||||
if action == "listen":
|
||||
@@ -343,6 +347,10 @@ class ChatTool(Tool):
|
||||
this one message (a region name, or ``*`` for unscoped); the document says which it
|
||||
went under. A radio that can't send under the scope refuses before anything is
|
||||
transmitted, and that is a failure (exit 1), never a quiet unscoped send.
|
||||
|
||||
``--to`` a room server posts to it. The room acknowledges a post once it has stored
|
||||
it, so ``acked`` reads the same way; a room that no longer knows us (it restarted,
|
||||
or we never joined) drops the post unacknowledged — ``chat join`` first.
|
||||
"""
|
||||
device = await ctx.device()
|
||||
text = str(params["text"])
|
||||
@@ -357,17 +365,30 @@ class ChatTool(Tool):
|
||||
)
|
||||
|
||||
contact = _resolve_contact(await device.get_contacts(), str(params["to"]))
|
||||
message = await ctx.chat.send_direct(contact, text)
|
||||
if contact.is_room:
|
||||
message = await ctx.chat.send_post(contact, text)
|
||||
else:
|
||||
message = await ctx.chat.send_direct(contact, text)
|
||||
return ToolResult(
|
||||
summary={"to": contact.name, "acked": bool(message.acked)},
|
||||
report=(_sent(contact=contact, acked=bool(message.acked)),),
|
||||
)
|
||||
|
||||
async def _cli_history(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Print a conversation's stored transcript."""
|
||||
"""Print a conversation's stored transcript — for a room, its board by author.
|
||||
|
||||
A room's transcript is its posts (its command replies are left out, as on its
|
||||
board in the menu), and it names each post's author where a direct transcript
|
||||
names the peer: the room is the conversation the caller already named, and every
|
||||
post in it has a different writer. Our own posts name our node, as every hop of
|
||||
ours does on this face.
|
||||
"""
|
||||
limit = int(params.get("limit") or _HISTORY_LIMIT)
|
||||
channel = params.get("channel")
|
||||
to = params.get("to")
|
||||
room = False
|
||||
name_of: NodeResolver | None = None
|
||||
me: NodeRef | None = None
|
||||
if channel is not None:
|
||||
channel_id = await ctx.chat.channel_id_for(int(channel))
|
||||
messages = ctx.repo.recent_chat_messages(
|
||||
@@ -376,20 +397,70 @@ class ChatTool(Tool):
|
||||
label = f"#{channel}"
|
||||
else:
|
||||
device = await ctx.device()
|
||||
contact = _resolve_contact(await device.get_contacts(), str(to))
|
||||
contacts = await device.get_contacts()
|
||||
contact = _resolve_contact(contacts, str(to))
|
||||
room = contact.is_room
|
||||
messages = ctx.repo.recent_chat_messages(
|
||||
is_channel=False,
|
||||
peer=contact.key_prefix or contact.public_key[:12],
|
||||
limit=limit,
|
||||
posts_only=room,
|
||||
)
|
||||
label = contact.name
|
||||
if room:
|
||||
name_of = make_node_resolver(contacts, ctx.repo.node_names())
|
||||
me = _self_ref(await device.get_self_info())
|
||||
|
||||
return ToolResult(
|
||||
summary={"conversation": label, "messages": len(messages)},
|
||||
report=(_transcript(messages),),
|
||||
report=(_transcript(messages, room=room, name_of=name_of, me=me),),
|
||||
exit_code=exitcodes.OK if messages else exitcodes.NO_RESULT,
|
||||
)
|
||||
|
||||
async def _cli_join(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Log in to a room server — one exchange — and print the access it granted.
|
||||
|
||||
The password is ``--password``, else the one MeshTerm remembers for the room (its
|
||||
room password, then its admin password); one that works is remembered, exactly as
|
||||
the menu's join prompt remembers it. The room then sends every post the companion
|
||||
hasn't seen, one at a time — they wait on the radio for whatever reads it next
|
||||
(``chat listen``, the menu), and ``chat history`` has them from then on.
|
||||
|
||||
A room never says no: a wrong password gets no reply at all, so silence is a
|
||||
failure here (exit 4) that names both of its causes, and keeps whatever password
|
||||
was remembered.
|
||||
"""
|
||||
from ..core.connection import DeviceCommandError
|
||||
from ..core.models import LoginResult
|
||||
|
||||
device = await ctx.device()
|
||||
name = str(params["room"])
|
||||
room = _resolve_contact(await device.get_contacts(), name)
|
||||
# Both are the argument being wrong, with nothing yet on the air: usage errors.
|
||||
if not room.is_room:
|
||||
raise typer.BadParameter(f"{room.name!r} is not a room server")
|
||||
password = params.get("password")
|
||||
if password is None:
|
||||
password = ctx.rooms.password(room)
|
||||
if password is None:
|
||||
raise typer.BadParameter(
|
||||
f"no password remembered for {room.name!r}; pass --password "
|
||||
"(an empty one asks the room whether it already knows you)"
|
||||
)
|
||||
login = await ctx.rooms.login(room, str(password))
|
||||
if login.result is LoginResult.REFUSED:
|
||||
raise DeviceCommandError(f"the radio refused the login to {room.name!r}")
|
||||
if login.access is None:
|
||||
raise DeviceCommandError(
|
||||
f"{room.name!r} did not answer the login — it is out of reach, or the "
|
||||
"password is wrong (a room says nothing to a wrong one). Any remembered "
|
||||
"password was kept."
|
||||
)
|
||||
return ToolResult(
|
||||
summary={"room": room.name, "access": login.access.value},
|
||||
report=(_joined(room, login.access.value),),
|
||||
)
|
||||
|
||||
async def _cli_listen(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Tail inbound messages live in the console (and record them to history).
|
||||
|
||||
@@ -438,6 +509,7 @@ class ChatTool(Tool):
|
||||
"direction": "in",
|
||||
"node": None if message.is_channel else NodeRef(hash=message.sender),
|
||||
"channel": channel,
|
||||
"author": NodeRef(hash=message.author) if message.author else None,
|
||||
"snr_db": message.snr,
|
||||
"text": message.text,
|
||||
"acked": None,
|
||||
@@ -466,7 +538,8 @@ class ChatTool(Tool):
|
||||
device = await ctx.device()
|
||||
channels = await _read_channels(device)
|
||||
contacts = await device.get_contacts()
|
||||
lasts = ctx.repo.last_chat_messages()
|
||||
rooms = [(c.key_prefix or c.public_key[:12]).lower() for c in contacts if c.is_room]
|
||||
lasts = ctx.repo.last_chat_messages(rooms=rooms)
|
||||
|
||||
rows = [*channels] + [
|
||||
Conversation(label=c.name, is_channel=False, contact=c) for c in contacts
|
||||
@@ -487,10 +560,10 @@ class ChatTool(Tool):
|
||||
|
||||
chat_app = typer.Typer(help=self.help, no_args_is_help=True, rich_markup_mode=None)
|
||||
|
||||
@chat_app.command("send", help="Send a message to a contact or channel")
|
||||
@chat_app.command("send", help="Send a message to a contact or channel, or post to a room")
|
||||
def _send_cmd(
|
||||
text: str = typer.Argument(..., help="The message body"),
|
||||
to: str | None = typer.Option(None, "--to", help="Contact name or key prefix"),
|
||||
to: str | None = typer.Option(None, "--to", help="Contact or room name, or key prefix"),
|
||||
channel: int | None = typer.Option(None, "--channel", help="Channel slot index"),
|
||||
scope: str | None = typer.Option(
|
||||
None,
|
||||
@@ -509,7 +582,7 @@ class ChatTool(Tool):
|
||||
|
||||
@chat_app.command("history", help="Show a conversation's stored history")
|
||||
def _history_cmd(
|
||||
to: str | None = typer.Option(None, "--to", help="Contact name or key prefix"),
|
||||
to: str | None = typer.Option(None, "--to", help="Contact or room name, or key prefix"),
|
||||
channel: int | None = typer.Option(None, "--channel", help="Channel slot index"),
|
||||
limit: int = typer.Option(_HISTORY_LIMIT, "--limit", help="Max messages to show"),
|
||||
) -> None:
|
||||
@@ -520,10 +593,19 @@ class ChatTool(Tool):
|
||||
{"cli_action": "history", "to": to, "channel": channel, "limit": limit},
|
||||
)
|
||||
|
||||
@chat_app.command("list", help="List channels, contacts, and recent messages")
|
||||
@chat_app.command("list", help="List channels, rooms, contacts, and recent messages")
|
||||
def _list_cmd() -> None:
|
||||
run_tool_command(self, {"cli_action": "list"})
|
||||
|
||||
@chat_app.command("join", help="Log in to a room server, so it sends you its posts")
|
||||
def _join_cmd(
|
||||
room: str = typer.Argument(..., help="The room server's name or key prefix"),
|
||||
password: str | None = typer.Option(
|
||||
None, "--password", help="Room or admin password (else remembered)"
|
||||
),
|
||||
) -> None:
|
||||
run_tool_command(self, {"cli_action": "join", "room": room, "password": password})
|
||||
|
||||
@chat_app.command("listen", help="Tail inbound messages live in the console")
|
||||
def _listen_cmd(
|
||||
seconds: int = typer.Option(
|
||||
@@ -1071,7 +1153,7 @@ def _channel_ref(idx: int | None, label: str, secret: bytes | None) -> ChannelRe
|
||||
)
|
||||
|
||||
|
||||
def _message_columns() -> tuple:
|
||||
def _message_columns(*, author_lane: bool = False) -> tuple:
|
||||
"""One transcript row's columns, shared by ``history`` and the ``listen`` stream.
|
||||
|
||||
``DIR`` carries what the menu's transcript writes into its sender lane as the word
|
||||
@@ -1083,25 +1165,91 @@ def _message_columns() -> tuple:
|
||||
stops being true the moment a body holds a newline — after which the remainder reads
|
||||
as a second record with an empty time. The document carries the body raw, a JSON string
|
||||
holding a newline natively.
|
||||
|
||||
``author`` is a room post's writer, in every document (``null`` off a room) so one
|
||||
command answers in one shape; ``author_lane`` draws it as ``AUTHOR`` too, for a room's
|
||||
transcript, where it is the column a reader is there for.
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
from ..ui import fields
|
||||
|
||||
peer = fields.plain_only(fields.name("conversation", "PEER"))
|
||||
return (
|
||||
fields.when("created_at", "TIME"),
|
||||
fields.word("direction", "DIR"),
|
||||
# One column for whichever end the conversation had; the document keeps the two
|
||||
# apart, because a parser cannot tell a channel from a contact by its label.
|
||||
fields.plain_only(fields.name("conversation", "PEER")),
|
||||
# apart, because a parser cannot tell a channel from a contact by its label. A
|
||||
# room's transcript names the room on every row, so there AUTHOR stands instead.
|
||||
replace(peer, lanes=()) if author_lane else peer,
|
||||
fields.node("node", lanes=()),
|
||||
fields.channel("channel", lanes=()),
|
||||
_author_column(lane=author_lane),
|
||||
fields.snr("snr_db", "SNR_DB"),
|
||||
fields.free("text", "TEXT"),
|
||||
fields.hidden("acked"),
|
||||
)
|
||||
|
||||
|
||||
def _transcript(messages: list[ChatMessage]) -> Listing:
|
||||
"""A conversation's stored messages, oldest first, one record each."""
|
||||
def _author_column(*, lane: bool) -> Any:
|
||||
"""A room post's author: the shared node object, drawn as one hop — ``Name (hash)``.
|
||||
|
||||
The hop's grammar (:func:`~meshterm.ui.script.route`), because that is the plain
|
||||
face's one way of naming a node by name *and* key: an author nothing names is its hash
|
||||
alone, never an empty ``()``.
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
from ..ui import fields, script
|
||||
from ..ui.report import Lane
|
||||
|
||||
column = fields.node("author", lanes=())
|
||||
if not lane:
|
||||
return column
|
||||
|
||||
def hop(ref: NodeRef | None) -> str:
|
||||
return script.route([(ref.name, ref.hash)]) if ref is not None else script.NONE
|
||||
|
||||
return replace(column, lanes=(Lane(header="AUTHOR", render=hop),))
|
||||
|
||||
|
||||
def _self_ref(info: dict) -> NodeRef:
|
||||
"""Our own node, from the companion's self info — how a post of ours names its author."""
|
||||
key = str(info.get("public_key") or "").lower()
|
||||
return NodeRef(
|
||||
name=str(info.get("name") or "") or None,
|
||||
key=key or None,
|
||||
hash=key[:8] or None,
|
||||
type=NODE_TYPE_LABELS.get(info.get("adv_type")),
|
||||
is_self=True,
|
||||
)
|
||||
|
||||
|
||||
def _author_ref(author: str, name_of: NodeResolver | None) -> NodeRef:
|
||||
"""A post's author as a node: its hash always, its name where something names it."""
|
||||
from ..ui.room import author_label
|
||||
|
||||
label, key = author_label(author, name_of) if name_of is not None else (author, None)
|
||||
return NodeRef(name=label if key else None, hash=author)
|
||||
|
||||
|
||||
def _transcript(
|
||||
messages: list[ChatMessage],
|
||||
*,
|
||||
room: bool = False,
|
||||
name_of: NodeResolver | None = None,
|
||||
me: NodeRef | None = None,
|
||||
) -> Listing:
|
||||
"""A conversation's stored messages, oldest first, one record each.
|
||||
|
||||
Args:
|
||||
messages: The transcript.
|
||||
room: Whether it is a room's board: each row then names its author, in an
|
||||
``AUTHOR`` lane standing where ``PEER`` would (the peer being the room on
|
||||
every row).
|
||||
name_of: Names an author's key, for a room.
|
||||
me: Our own node, the author of our own posts in a room.
|
||||
"""
|
||||
from ..ui.report import Listing
|
||||
|
||||
rows = []
|
||||
@@ -1120,6 +1268,11 @@ def _transcript(messages: list[ChatMessage]) -> Listing:
|
||||
if message.is_channel
|
||||
else NodeRef(name=message.peer_name, hash=message.peer),
|
||||
"channel": channel,
|
||||
"author": (
|
||||
_author_ref(message.author, name_of)
|
||||
if message.author
|
||||
else (me if room and message.outbound else None)
|
||||
),
|
||||
"snr_db": message.snr,
|
||||
"text": message.text,
|
||||
"acked": message.acked,
|
||||
@@ -1127,9 +1280,9 @@ def _transcript(messages: list[ChatMessage]) -> Listing:
|
||||
)
|
||||
return Listing(
|
||||
key="messages",
|
||||
columns=_message_columns(),
|
||||
columns=_message_columns(author_lane=room),
|
||||
rows=rows,
|
||||
order=("TIME", "DIR", "PEER", "SNR_DB", "TEXT"),
|
||||
order=("TIME", "DIR", "AUTHOR" if room else "PEER", "SNR_DB", "TEXT"),
|
||||
)
|
||||
|
||||
|
||||
@@ -1156,6 +1309,9 @@ def _live_messages() -> Listing:
|
||||
pin(fields.plain_only(fields.name("conversation", "PEER")), 16),
|
||||
fields.node("node", lanes=()),
|
||||
fields.channel("channel", lanes=()),
|
||||
# A room post's writer rides in the document; the tail itself names the room,
|
||||
# which is the node that sent it.
|
||||
_author_column(lane=False),
|
||||
pin(fields.snr("snr_db", "SNR_DB"), 6),
|
||||
fields.free("text", "TEXT"),
|
||||
fields.hidden("direction"),
|
||||
@@ -1184,9 +1340,15 @@ def _conversations(ctx: AppContext, rows: list, lasts: dict) -> Listing:
|
||||
else None
|
||||
)
|
||||
contact = getattr(conversation, "contact", None)
|
||||
if conversation.is_channel:
|
||||
kind = "channel"
|
||||
elif conversation.is_room:
|
||||
kind = "room"
|
||||
else:
|
||||
kind = "direct"
|
||||
records.append(
|
||||
{
|
||||
"kind": "channel" if conversation.is_channel else "direct",
|
||||
"kind": kind,
|
||||
"conversation": conversation.label,
|
||||
"channel": channel,
|
||||
"node": None
|
||||
@@ -1221,6 +1383,33 @@ def _conversations(ctx: AppContext, rows: list, lasts: dict) -> Listing:
|
||||
)
|
||||
|
||||
|
||||
def _joined(room: Contact, access: str) -> Facts:
|
||||
"""What ``chat join`` won: the access a room granted, bare — the one fact asked for.
|
||||
|
||||
The room rides in the document, the caller having named it; the plain face prints the
|
||||
access word alone (``member``, ``admin`` or ``read-only``), which is what a script
|
||||
deciding whether it may post branches on.
|
||||
"""
|
||||
from ..ui import fields
|
||||
from ..ui.report import BARE, Facts
|
||||
|
||||
return Facts(
|
||||
key="joined",
|
||||
fields=(fields.node("room", lanes=()), fields.word("access", "access")),
|
||||
values={
|
||||
"room": NodeRef(
|
||||
name=room.name,
|
||||
key=(room.public_key or "").lower() or None,
|
||||
hash=(room.key_prefix or "").lower() or None,
|
||||
type=NODE_TYPE_LABELS.get(room.node_type),
|
||||
),
|
||||
"access": access,
|
||||
},
|
||||
shape=BARE,
|
||||
bare="access",
|
||||
)
|
||||
|
||||
|
||||
def _sent(
|
||||
*,
|
||||
contact: object | None = None,
|
||||
@@ -1279,7 +1468,11 @@ def _sent(
|
||||
replace(fields.scope("scope", "scope"), lanes=()),
|
||||
),
|
||||
values={
|
||||
"kind": "channel" if channel is not None else "direct",
|
||||
"kind": (
|
||||
"channel"
|
||||
if channel is not None
|
||||
else ("room" if getattr(contact, "is_room", False) else "direct")
|
||||
),
|
||||
"node": node,
|
||||
"channel": (
|
||||
_channel_ref(channel, f"#{channel}", None) if channel is not None else None
|
||||
|
||||
@@ -798,3 +798,95 @@ async def test_joining_a_room_end_to_end(tmp_path: Path) -> None:
|
||||
assert ctx.rooms.access(ROOM) is RoomAccess.MEMBER
|
||||
finally:
|
||||
await ctx.aclose()
|
||||
|
||||
|
||||
# --- the command line -----------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def cli(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): # noqa: ANN201 - a closure
|
||||
"""The real CLI against the simulator, in a home of its own (see test_cli_contract)."""
|
||||
from typer.testing import CliRunner
|
||||
|
||||
from meshterm.cli import app
|
||||
|
||||
monkeypatch.setenv("MESHTERM_HOME", str(tmp_path / "home"))
|
||||
runner = CliRunner()
|
||||
db = tmp_path / "cli.db"
|
||||
|
||||
def invoke(*args: str): # noqa: ANN202
|
||||
return runner.invoke(app, ["--mock", "--db", str(db), *args])
|
||||
|
||||
invoke.db = db
|
||||
return invoke
|
||||
|
||||
|
||||
def test_chat_list_names_a_room_as_one(cli) -> None: # noqa: ANN001
|
||||
"""A room is its own kind of conversation, on both faces."""
|
||||
import json
|
||||
|
||||
assert "Lakeside BBS room" in cli("chat", "list").stdout
|
||||
rows = json.loads(cli("--json", "chat", "list").stdout)
|
||||
kinds = {r["node"]["name"]: r["kind"] for r in rows if r["node"]}
|
||||
assert kinds["Lakeside BBS"] == "room" and kinds["Alice"] == "direct"
|
||||
|
||||
|
||||
def test_chat_join_answers_with_the_access_won(cli) -> None: # noqa: ANN001
|
||||
"""The access word alone on the plain face; the room and the access in the document."""
|
||||
import json
|
||||
|
||||
from meshterm.core import exitcodes
|
||||
|
||||
unknown = cli("chat", "join", "Lakeside BBS")
|
||||
assert unknown.exit_code == exitcodes.USAGE, "nothing remembered, nothing sent"
|
||||
assert cli("chat", "join", "Alice", "--password", "x").exit_code == exitcodes.USAGE
|
||||
|
||||
silent = cli("chat", "join", "Lakeside BBS", "--password", "nope")
|
||||
assert silent.exit_code == exitcodes.DEVICE
|
||||
assert silent.stdout == "" and "wrong" in silent.stderr
|
||||
|
||||
joined = cli("chat", "join", "Lakeside BBS", "--password", "hello")
|
||||
assert joined.exit_code == exitcodes.OK and joined.stdout == "member\n"
|
||||
again = json.loads(cli("--json", "chat", "join", "Lakeside BBS").stdout) # remembered
|
||||
assert again["access"] == "member"
|
||||
assert again["room"]["name"] == "Lakeside BBS" and again["room"]["type"] == "room server"
|
||||
|
||||
|
||||
def test_chat_history_reads_a_room_by_author(cli) -> None: # noqa: ANN001
|
||||
"""AUTHOR stands where PEER would; a command reply is not on the board; one shape."""
|
||||
import json
|
||||
|
||||
repo = Repository(cli.db)
|
||||
try:
|
||||
repo.record_chat_message(ChatMessage.from_message(_post("swap meet?")))
|
||||
repo.record_chat_message(ChatMessage.from_message(_post("north down?", STRANGER_KEY)))
|
||||
repo.record_chat_message(ChatMessage(text="> hello", peer=ROOM.key_prefix))
|
||||
finally:
|
||||
repo.close()
|
||||
|
||||
header, *rows = cli("chat", "history", "--to", "Lakeside BBS").stdout.splitlines()
|
||||
assert header.split() == ["TIME", "DIR", "AUTHOR", "SNR_DB", "TEXT"]
|
||||
assert "Alice (d4e5f6a7)" in rows[0] and rows[0].endswith("swap meet?")
|
||||
assert STRANGER_KEY in rows[1] and "(" not in rows[1].split("north")[0]
|
||||
assert len(rows) == 2
|
||||
|
||||
docs = json.loads(cli("--json", "chat", "history", "--to", "Lakeside BBS").stdout)
|
||||
assert docs[0]["author"]["name"] == "Alice" and docs[0]["author"]["hash"] == ALICE_KEY
|
||||
assert docs[1]["author"] == {
|
||||
"name": None,
|
||||
"key": None,
|
||||
"hash": STRANGER_KEY,
|
||||
"type": None,
|
||||
"self": False,
|
||||
}
|
||||
direct = json.loads(cli("--json", "chat", "list").stdout)
|
||||
assert direct, "the list still answers"
|
||||
|
||||
|
||||
def test_chat_send_to_a_room_is_a_post(cli) -> None: # noqa: ANN001
|
||||
"""The receipt says it was a room it went to."""
|
||||
import json
|
||||
|
||||
receipt = json.loads(cli("--json", "chat", "send", "--to", "Lakeside BBS", "hi").stdout)
|
||||
assert receipt["kind"] == "room"
|
||||
assert receipt["acked"] is False, "this simulator never joined, so the room drops it"
|
||||
Reference in new issue
Block a user