diff --git a/seeds/simplex/next_message/skill.py b/seeds/simplex/next_message/skill.py index 5f93733..c68cc53 100644 --- a/seeds/simplex/next_message/skill.py +++ b/seeds/simplex/next_message/skill.py @@ -9,6 +9,11 @@ the configured default contact is used; with no configured default (or a default with no unread message) the weak winner stands. It then pops and reports the oldest unread message for that conversation. +When the live buffer is empty it falls back to the daemon's persistent unread +(`/unread` + `/history`), so a message that arrived before the bridge started is +still reported. (v7 has no mark-read command, so a persistent-unread message can +be reported again until the user reads it in their own client.) + The bridge owns the read cursor, so this skill keeps no state of its own. It never opens a WebSocket to the `simplex-chat` daemon — the bridge is the only messaging surface it uses. @@ -97,6 +102,20 @@ def _senders(messages): return senders +def _is_healthy(sender): + """A conversation is healthy when its connection is not known-bad. + + `connected` is absent when the source did not report it (treat as unknown); + `auth_errors` counts failed sends on the connection and marks a stale peer. + """ + if sender.get("connected") is False: + return False + try: + return int(sender.get("auth_errors") or 0) == 0 + except (TypeError, ValueError): + return True + + def _default_sender(ctx, senders): """The configured default contact, if it has unread messages.""" default = str(ctx.config.get("simplex_default_contact", "") or "").strip() @@ -142,11 +161,15 @@ def act(ctx, request): except BridgeError as exc: return ActionResult(action_log=str(exc), new_state=request.text) senders = _senders(payload.get("messages") or []) - if not senders: - return ActionResult( - action_log="no unread SimpleX messages.", - new_state="no unread SimpleX messages", - ) + if senders: + return _read_live(ctx, request, senders) + # The live buffer only holds messages that arrived while the bridge was + # connected; fall back to the daemon's persistent unread so a message that + # landed before the bridge started is not silently missed. + return _read_persistent(ctx, request) + + +def _read_live(ctx, request, senders): decisions = [] contact = _resolve_contact(ctx, request, senders, decisions) try: @@ -166,7 +189,70 @@ def act(ctx, request): new_state="no unread SimpleX messages", decisions=decisions, ) - sender = message.get("display_name") or contact - body = str(message.get("text") or "") - report = f"SimpleX message from {sender}: {body}" + return _report(message.get("display_name") or contact, message.get("text"), decisions) + + +def _read_persistent(ctx, request): + try: + payload = _get(ctx, "/unread") + except BridgeError as exc: + return ActionResult( + action_log=f"no unread SimpleX messages ({exc}).", + new_state="no unread SimpleX messages", + ) + chats = [c for c in (payload.get("chats") or []) if c.get("unread")] + if not chats: + return ActionResult( + action_log="no unread SimpleX messages.", + new_state="no unread SimpleX messages", + ) + senders = [ + { + "id": str(chat.get("contact_id") or ""), + "display_name": chat.get("display_name") or str(chat.get("contact_id") or ""), + "connected": chat.get("connected"), + "auth_errors": chat.get("auth_errors"), + } + for chat in chats + if chat.get("contact_id") + ] + decisions = [] + healthy = [s for s in senders if _is_healthy(s)] + if len(healthy) == 1: + # Exactly one conversation is on a healthy connection (the rest are + # stale duplicates): read it without a coin-flip decision. + contact = healthy[0]["id"] + else: + contact = _resolve_contact(ctx, request, senders, decisions) + try: + history = _get( + ctx, f"/history?contact={urllib.parse.quote(contact)}&count=50" + ) + except BridgeError as exc: + return ActionResult( + action_log=f"failed reading {contact!r}: {exc}", + new_state=request.text, + decisions=decisions, + ) + messages = [m for m in (history.get("messages") or []) if m.get("unread")] + if not messages: + # Fall back to the previewed unread messages from /unread. + chat = next( + (c for c in chats if str(c.get("contact_id")) == str(contact)), {} + ) + messages = [m for m in (chat.get("messages") or []) if m.get("unread")] + if not messages: + return ActionResult( + action_log=f"no unread message from {contact!r}.", + new_state="no unread SimpleX messages", + decisions=decisions, + ) + sender = next( + (s["display_name"] for s in senders if s["id"] == str(contact)), str(contact) + ) + return _report(sender, messages[0].get("text"), decisions) + + +def _report(sender, body, decisions): + report = f"SimpleX message from {sender}: {str(body or '')}" return ActionResult(action_log=report, new_state=report, decisions=decisions) diff --git a/seeds/simplex/next_message/skill.test.py b/seeds/simplex/next_message/skill.test.py index 7381c2b..bd10ebb 100644 --- a/seeds/simplex/next_message/skill.test.py +++ b/seeds/simplex/next_message/skill.test.py @@ -51,6 +51,8 @@ class FakeEngine: class BridgeHandler(BaseHTTPRequestHandler): messages = [] + unread_chats = [] + history = {} requests = [] tokens = [] @@ -76,6 +78,13 @@ class BridgeHandler(BaseHTTPRequestHandler): found = self.messages.pop(index) break self._send({"message": found}) + elif url.path == "/unread": + self._send({"chats": list(self.unread_chats)}) + elif url.path == "/history": + contact = (urllib.parse.parse_qs(url.query).get("contact") or [None])[0] + self._send( + {"contact_id": contact, "messages": list(self.history.get(str(contact), []))} + ) else: self._send({"error": "not found"}, 404) @@ -83,11 +92,17 @@ class BridgeHandler(BaseHTTPRequestHandler): pass -def start_server(messages): +def start_server(messages, unread_chats=None, history=None): handler = type( "Handler", (BridgeHandler,), - {"messages": list(messages), "requests": [], "tokens": []}, + { + "messages": list(messages), + "unread_chats": list(unread_chats or []), + "history": dict(history or {}), + "requests": [], + "tokens": [], + }, ) server = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=server.serve_forever, daemon=True).start() @@ -225,7 +240,88 @@ def test_empty_inbox_is_reported_honestly(): request = Request("read my next simplex message") action = skill.act(ctx, request) assert "no unread" in action.action_log, action.action_log - assert handler.requests == ["/inbox"], "an empty inbox needs no pop" + # An empty live buffer falls back to the daemon's persistent unread. + assert handler.requests == ["/inbox", "/unread"], handler.requests + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_empty_live_inbox_falls_back_to_persistent_unread(): + server, handler, url = start_server( + [], + unread_chats=[ + { + "contact_id": "3", + "display_name": "pepper", + "unread_count": 2, + "min_unread_item_id": "8", + "unread": True, + "messages": [], + } + ], + history={ + "3": [ + {"item_id": "8", "text": "hello", "status": "rcvNew", "unread": True}, + {"item_id": "9", "text": "hey yo", "status": "rcvNew", "unread": True}, + ] + }, + ) + try: + engine = FakeEngine() + ctx = ActionContext(engine=engine, config=config(url)) + request = Request("read my next simplex message") + action = skill.act(ctx, request) + assert engine.decisions == [], "a single unread chat needs no decision" + assert "hello" in action.action_log, action.action_log + assert "pepper" in action.action_log, action.action_log + assert handler.requests == ["/inbox", "/unread", "/history?contact=3&count=50"], ( + handler.requests + ) + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_persistent_unread_prefers_a_healthy_conversation(): + server, handler, url = start_server( + [], + unread_chats=[ + { + "contact_id": "3", + "display_name": "pepper", + "unread_count": 1, + "unread": True, + "connected": True, + "auth_errors": 2, + "messages": [], + }, + { + "contact_id": "4", + "display_name": "pepper", + "unread_count": 1, + "unread": True, + "connected": True, + "auth_errors": 0, + "messages": [], + }, + ], + history={ + "3": [{"item_id": "8", "text": "stale hello", "status": "rcvNew", "unread": True}], + "4": [{"item_id": "20", "text": "fresh hello", "status": "rcvNew", "unread": True}], + }, + ) + try: + engine = FakeEngine() + ctx = ActionContext(engine=engine, config=config(url)) + action = skill.act(ctx, Request("read my next simplex message")) + assert engine.decisions == [], "one healthy chat must win without a decision" + assert "fresh hello" in action.action_log, action.action_log + assert handler.requests == ["/inbox", "/unread", "/history?contact=4&count=50"], ( + handler.requests + ) print(action.action_log) finally: server.shutdown() @@ -264,6 +360,8 @@ def main(): test_weak_winner_without_default_stands() test_single_sender_needs_no_decision() test_empty_inbox_is_reported_honestly() + test_empty_live_inbox_falls_back_to_persistent_unread() + test_persistent_unread_prefers_a_healthy_conversation() test_unreachable_bridge_fails_honestly() test_auth_token_is_sent_when_configured() print("ok") diff --git a/semif_agent/bridges/inbox.py b/semif_agent/bridges/inbox.py index 34f2ab6..ae257b0 100644 --- a/semif_agent/bridges/inbox.py +++ b/semif_agent/bridges/inbox.py @@ -18,7 +18,7 @@ class MessagingInbox: self._lock = threading.Lock() self._items: deque[dict] = deque() self._max = max(1, int(max_size)) - self._contacts: dict[str, str] = {} + self._contacts: dict[str, dict] = {} def record(self, message: dict) -> dict: contact_id = str(message.get("contact_id") or "") @@ -31,15 +31,26 @@ class MessagingInbox: "received_at": time.time(), } with self._lock: - if display_name: - self._contacts[contact_id] = display_name - else: - self._contacts.setdefault(contact_id, "") + self._remember(contact_id, message) self._items.append(entry) while len(self._items) > self._max: self._items.popleft() return entry + def _remember(self, contact_id: str, contact: dict) -> None: + """Upsert the cached contact for an id (caller holds the lock).""" + current = self._contacts.setdefault( + contact_id, {"id": contact_id, "display_name": ""} + ) + name = contact.get("display_name") or "" + if name: + current["display_name"] = name + # Keep the unique local name and connection health when the source knows + # them; never invent them (an inbound item has no connection state). + for key in ("local_name", "connected", "auth_errors"): + if key in contact and contact[key] not in (None, ""): + current[key] = contact[key] + def peek(self) -> list[dict]: with self._lock: return list(self._items) @@ -59,22 +70,17 @@ class MessagingInbox: """Upsert contacts learned from the daemon (not from a message). A non-empty incoming name overwrites a cached one; an empty name never - clobbers a name already learned from an inbound message. + clobbers a name already learned from an inbound message. The unique + local name and connection health ride along when the daemon reports + them. """ with self._lock: for contact in contacts: contact_id = str(contact.get("id") or "") if not contact_id: continue - name = contact.get("display_name") or "" - if name: - self._contacts[contact_id] = name - else: - self._contacts.setdefault(contact_id, "") + self._remember(contact_id, contact) def contacts(self) -> list[dict]: with self._lock: - return [ - {"id": contact_id, "display_name": name} - for contact_id, name in self._contacts.items() - ] + return [dict(contact) for contact in self._contacts.values()] diff --git a/semif_agent/bridges/simplex.py b/semif_agent/bridges/simplex.py index d0c5ef3..c71c92c 100644 --- a/semif_agent/bridges/simplex.py +++ b/semif_agent/bridges/simplex.py @@ -14,12 +14,21 @@ gateway process. from __future__ import annotations import threading +import time -from semif_agent.simplex_ws import SimplexDaemon +from semif_agent.simplex_ws import SimplexDaemon, parse_send_response from .base import BridgeInfo, BridgeService from .inbox import MessagingInbox +#: Send statuses that mean the message really left the agent. +SEND_OK_STATUSES = frozenset({"sndSent", "sndRcvd"}) +#: Send statuses that are final (no further polling needed). +SEND_TERMINAL_STATUSES = frozenset({"sndSent", "sndRcvd", "sndError"}) +#: How long to poll the daemon for a terminal send status before giving up. +SEND_CONFIRM_TIMEOUT = 6.0 +SEND_POLL_INTERVAL = 0.5 + class SimplexBridge(BridgeService): name = "simplex" @@ -34,9 +43,13 @@ class SimplexBridge(BridgeService): endpoints=( "GET /health -> 200 {\"ok\": true, \"platform\": \"simplex\"} — the " "bridge is up", - "GET /contacts -> 200 {\"contacts\": [{\"id\", \"display_name\"}]} — " - "contacts known to the daemon (learned from inbound messages and " - "refreshed from the daemon's contact list)", + "GET /contacts -> 200 {\"contacts\": [{\"id\", \"display_name\", " + "\"local_name\"?, \"connected\"?}]} — contacts known to the daemon " + "(learned from inbound messages and refreshed from the daemon's " + "contact list). `display_name` is the peer's profile name and can " + "collide; `local_name` is the daemon's unique local name; " + "`connected` (when the daemon reports it) is false for a peer whose " + "connection is not ready — prefer a connected peer", "GET /inbox -> 200 {\"messages\": [{\"id\", \"contact_id\", " "\"display_name\", \"text\", \"received_at\"}]} — peek buffered " "inbound messages; does not consume", @@ -44,22 +57,29 @@ class SimplexBridge(BridgeService): "the oldest unread message (optionally from one contact); null means " "none buffered. The bridge owns the read cursor", "GET /unread -> 200 {\"chats\": [{\"contact_id\", \"display_name\", " - "\"unread_count\", \"min_unread_item_id\", \"unread\", \"messages\": " + "\"unread_count\", \"min_unread_item_id\", \"unread\", " + "\"connected\"?, \"auth_errors\"?, \"messages\": " "[{item_id, text, status, unread, direction, sent_at}]}]} — the " "daemon's persistent unread chats (survives bridge restarts), not " "just what arrived while connected. Read-only; 503 when the daemon " "is not connected, 502 when the lookup fails", "GET /history?contact=&count= -> 200 {\"contact_id\", " "\"messages\": [{item_id, text, status, unread, direction, " - "sent_at}]} — recent message history for one contact (count default " - "20); status is rcvNew (unread) or rcvRead. Read-only; 503/502 as " - "/unread, 400 without a contact", + "sent_at, error?}]} — recent message history for one contact (count " + "default 20); status is rcvNew (unread), rcvRead, sndSent, sndRcvd, " + "or sndError, and `error` carries the agent reason (e.g. auth) on a " + "failed send. Read-only; 503/502 as /unread, 400 without a contact", "GET /address -> 200 {\"short_link\", \"full_link\", \"created\"} — " "the agent's contact link; creates it on first call. 503 when the " "daemon is not connected, 502 when the lookup fails", - "POST /send {\"recipient\": \"\", \"text\": \"...\"} " - "-> 200 {\"ok\": true, \"contact_id\": \"\"}; 400 {\"error\": " - "\"...\"} on a missing/invalid field or an unknown recipient", + "POST /send {\"recipient\": \"\", " + "\"text\": \"...\"} -> 200 {\"ok\": bool, \"contact_id\": \"\", " + "\"item_id\": \"\", \"status\": \"sndSent|sndRcvd|sndError\", " + "\"error\": \"...\"?}. The bridge resolves the recipient, sends, and " + "waits for the daemon's real send status: `ok` is true only for " + "sndSent/sndRcvd, and a failed send (e.g. an auth error on a dead " + "connection) returns ok:false with the reason — never a false " + "success. 400 on a missing/invalid field or an unknown recipient", "any request -> 401 {\"error\": \"unauthorized\"} when the token is " "configured and the auth header is missing or wrong", ), @@ -170,10 +190,10 @@ class SimplexBridge(BridgeService): if not isinstance(text, str) or not text.strip(): return 400, {"error": "text is required"} try: - contact_id = self.send(recipient, text) + result = self.send(recipient, text) except ValueError as exc: return 400, {"error": str(exc)} - return 200, {"ok": True, "contact_id": contact_id} + return 200, result # ---- actions ---- @@ -207,8 +227,25 @@ class SimplexBridge(BridgeService): return 503, {"error": f"unread lookup is not available: {exc}"[:300]} except Exception as exc: # TimeoutError, daemon error return 502, {"error": f"unread lookup failed: {exc}"[:300]} + self._attach_health(chats) return 200, {"chats": chats} + def _attach_health(self, chats: list[dict]) -> None: + """Merge cached connection health into each chat summary, in place. + + Lets a caller prefer a live conversation over a stale duplicate when + several chats share a display name. Best-effort: a chat with no cached + contact is left untouched. + """ + health = {c["id"]: c for c in self.inbox.contacts()} + for chat in chats: + info = health.get(str(chat.get("contact_id") or "")) + if not info: + continue + for key in ("connected", "auth_errors"): + if key in info: + chat[key] = info[key] + def _history(self, contact: str | None, count: str | None) -> tuple[int, dict]: """Recent message history for one contact, straight from the daemon. @@ -247,20 +284,93 @@ class SimplexBridge(BridgeService): return 502, {"error": "address lookup returned no link"} return 200, link - def send(self, recipient: str, text: str) -> str: - """Resolve a recipient and enqueue the message. Returns the contact id.""" + def send(self, recipient: str, text: str) -> dict: + """Resolve a recipient, send the text, and report the real outcome. + + Returns `{ok, contact_id, item_id?, status?, error?}`. `ok` is True only + when the daemon created the message and it reached a terminal status of + `sndSent` (relayed to the server) or `sndRcvd` (delivered to the peer). + A dead connection surfaces as `ok: false` carrying the daemon's agent + error (e.g. `auth`) — never a false success. + """ contact_id = self.resolve(recipient) if contact_id is None: raise ValueError(f"unknown SimpleX recipient: {recipient!r}") - self.daemon.enqueue(contact_id, text) - return contact_id + try: + response = self.daemon.request_send(contact_id, text) + except RuntimeError as exc: + return { + "ok": False, + "contact_id": contact_id, + "status": "unavailable", + "error": str(exc)[:300], + } + except Exception as exc: # TimeoutError, daemon error + return { + "ok": False, + "contact_id": contact_id, + "status": "error", + "error": str(exc)[:300], + } + parsed = parse_send_response(response) + if parsed["item_id"] is None: + return { + "ok": False, + "contact_id": contact_id, + "status": "rejected", + "error": parsed["error"] or "the daemon rejected the send", + } + item_id = parsed["item_id"] + status, error = parsed["status"], parsed["error"] + if status not in SEND_TERMINAL_STATUSES: + status, error = self._await_send_status(contact_id, item_id, status) + result = { + "ok": status in SEND_OK_STATUSES, + "contact_id": contact_id, + "item_id": item_id, + "status": status, + } + if not result["ok"]: + result["error"] = error or f"send status {status}" + return result + + def _await_send_status( + self, contact_id: str, item_id: str, current: str, + timeout: float = SEND_CONFIRM_TIMEOUT, + ) -> tuple[str, str]: + """Poll the daemon for the item's terminal send status + agent error. + + A send is `sndNew` the moment it is created; the agent then resolves it + to `sndSent`/`sndRcvd` (success) or `sndError` (failure, with the reason + in `agentError`). Returns `(status, error)`; a still-`sndNew` item after + the window stays unconfirmed rather than being reported as sent. + """ + deadline = time.monotonic() + timeout + status, error = current, "" + while True: + try: + messages = self.daemon.request_chat_history(contact_id, count=20) + except Exception: + return status or "unknown", error + for message in messages: + if str(message.get("item_id")) == str(item_id): + status = str(message.get("status") or "") + error = str(message.get("error") or "") + if status in SEND_TERMINAL_STATUSES: + return status, error + if time.monotonic() >= deadline: + return status or "unknown", error + time.sleep(SEND_POLL_INTERVAL) def resolve(self, recipient: str) -> str | None: - """A numeric id (with or without `@`) or a known display name. + """A numeric id (with or without `@`), a unique local name, or a display name. - On a display-name miss, refresh the daemon's contact list once and - retry: a contact the bridge has never received from is still addressable - as long as the daemon knows them. + An explicit id always wins. Two peers can share a profile display name + (the daemon suffixes its own local names, e.g. `pepper` / `pepper_1`), + so a local-name or display-name match that hits several peers prefers + the healthiest (connected, no recorded auth errors). On a miss, refresh + the daemon's contact list once and retry: a contact the bridge has never + received from is still addressable as long as the daemon knows them. """ recipient = str(recipient or "").strip() if not recipient: @@ -275,7 +385,43 @@ class SimplexBridge(BridgeService): return match def _match_contact(self, recipient: str) -> str | None: - for contact in self.inbox.contacts(): - if contact["display_name"] == recipient or contact["id"] == recipient: + contacts = self.inbox.contacts() + for contact in contacts: + if contact["id"] == recipient: return contact["id"] + exact = [ + c + for c in contacts + if c.get("local_name") == recipient or c["display_name"] == recipient + ] + if exact: + return self._prefer_connected(exact) + lowered = recipient.lower() + partial = [ + c + for c in contacts + if lowered in c["display_name"].lower() + or lowered in str(c.get("local_name", "")).lower() + ] + if len(partial) == 1: + return partial[0]["id"] + if partial: + return self._prefer_connected(partial) return None + + @staticmethod + def _prefer_connected(matches: list[dict]) -> str: + """Pick the healthiest peer among equally-named matches. + + Prefer a ready connection, then a connection with no recorded auth + errors (a stale duplicate that fails to send), and finally the first. + """ + + def rank(contact: dict) -> tuple[bool, bool]: + try: + clean = int(contact.get("auth_errors") or 0) == 0 + except (TypeError, ValueError): + clean = True + return (bool(contact.get("connected")), clean) + + return max(matches, key=rank)["id"] diff --git a/semif_agent/simplex_ws.py b/semif_agent/simplex_ws.py index caa1fe3..8719779 100644 --- a/semif_agent/simplex_ws.py +++ b/semif_agent/simplex_ws.py @@ -34,25 +34,45 @@ ConnectedHandler = Callable[[], Awaitable[None]] def contact_entry(contact: dict) -> dict | None: - """Normalize one daemon `Contact` into `{"id", "display_name"}`, or None. + """Normalize one daemon `Contact` into a contact dict, or None. The single source of truth for contact identity across the wire: the same shape appears in `newChatItems` items and in the `/_contacts` list. v7's `Contact.displayName` is null and the real peer name lives in - `profile.displayName`; `localDisplayName` is auto-suffixed on collisions - (e.g. a second contact becomes `pepper_1`). + `profile.displayName`; `localDisplayName` is the daemon's **unique** local + name, auto-suffixed on collisions (e.g. a second contact becomes + `pepper_1`). We keep both: `display_name` is the peer's profile name (what + a human recognizes, but it can collide) and `local_name` is the daemon's + unique name, so two peers with the same profile name stay distinguishable. + When the daemon reports connection state (the `/_contacts` list does), + `connected` and `auth_errors` are included so callers can prefer a live + peer over a dead one. """ contact_id = str(contact.get("contactId") or contact.get("chatId") or "") if not contact_id: return None profile = contact.get("profile") or {} + local_name = ( + contact.get("localDisplayName") + or contact.get("displayName") + or profile.get("displayName") + or "" + ) display_name = ( profile.get("displayName") or contact.get("displayName") - or contact.get("localDisplayName") + or local_name or "" ) - return {"id": contact_id, "display_name": display_name} + entry = {"id": contact_id, "display_name": display_name, "local_name": local_name} + active = contact.get("activeConn") or {} + conn = active.get("connStatus") or {} + status = contact.get("contactStatus") + if status is not None or conn: + entry["connected"] = status == "active" and conn.get("type") == "ready" + if isinstance(active.get("authErrCounter"), int): + entry["auth_errors"] = active["authErrCounter"] + return entry def contact_link(resp: dict) -> dict: @@ -111,8 +131,9 @@ def parse_chat_item(item: dict) -> dict | None: text = _text_from_content(item.get("content") or {}) if not text: return None - status = (meta.get("itemStatus") or {}).get("type") or "" - return { + status_obj = meta.get("itemStatus") or {} + status = status_obj.get("type") or "" + entry = { "item_id": str(item_id), "text": text, "status": status, @@ -120,6 +141,12 @@ def parse_chat_item(item: dict) -> dict | None: "direction": (item.get("chatDir") or {}).get("type") or "", "sent_at": meta.get("itemTs") or "", } + # A failed send carries the agent-level reason (`{"type":"auth"}` etc.); + # surface it so a caller can report *why* a message did not go out. + agent_error = status_obj.get("agentError") or {} + if agent_error: + entry["error"] = agent_error.get("type") or str(agent_error) + return entry def parse_chat(achat: dict) -> dict | None: @@ -198,6 +225,7 @@ def parse_direct_text_item(item: dict) -> InboundDict | None: "text": text, "contact_id": entry["id"], "display_name": entry["display_name"], + "local_name": entry.get("local_name", ""), "raw": item, } @@ -228,6 +256,31 @@ def accept_command(resp: dict) -> str | None: return f"/_accept {req_id}" +def parse_send_response(resp: dict) -> dict: + """Normalize a `/_send` response into `{item_id, status, error}`. + + A successful send comes back as `newChatItems` carrying the freshly created + `chatItem` (its `meta.itemId` and initial `meta.itemStatus`, usually + `sndNew`). A rejected send comes back as `chatCmdError`. `item_id` is None + on any rejection so the caller can tell "no message was created" from + "created but later failed at the agent layer". + """ + if not isinstance(resp, dict): + return {"item_id": None, "status": "", "error": "empty daemon response"} + if resp.get("type") == "chatCmdError" or resp.get("error"): + detail = resp.get("chatError") or resp.get("error") or "chat command failed" + return {"item_id": None, "status": "", "error": str(detail)[:300]} + for item in resp.get("chatItems") or []: + meta = (item.get("chatItem") or {}).get("meta") or {} + item_id = meta.get("itemId") + if item_id is None: + continue + status = (meta.get("itemStatus") or {}).get("type") or "" + error = ((meta.get("itemStatus") or {}).get("agentError") or {}).get("type") or "" + return {"item_id": str(item_id), "status": status, "error": error} + return {"item_id": None, "status": "", "error": "daemon returned no message id"} + + class SimplexDaemon: """One WebSocket connection to a `simplex-chat` daemon. @@ -434,6 +487,37 @@ class SimplexDaemon: future.cancel() raise TimeoutError("simplex address request timed out") from exc + # ---- send ---- + + async def send(self, chat_id: str, text: str, timeout: float = 20.0) -> dict: + """Send a direct text message and return the daemon's correlated reply. + + Unlike `enqueue` (fire-and-forget, used by the command gateway), this + awaits the `/_send` response so the caller sees whether the message was + created and its initial status. The daemon reports agent-level failures + (auth, quota) asynchronously, so a caller that needs delivery truth must + still poll `chat_history` for the item's terminal status. + """ + return await self._roundtrip(send_text_command(chat_id, text), timeout) + + def request_send(self, chat_id: str, text: str, timeout: float = 20.0) -> dict: + """Thread-safe correlated send for callers off the event loop. + + Raises `RuntimeError` when no live connection exists and `TimeoutError` + when the daemon does not answer in time — never a fabricated success. + """ + loop = self._loop + if loop is None or not loop.is_running(): + raise RuntimeError("simplex gateway is not connected") + future = asyncio.run_coroutine_threadsafe( + self.send(chat_id, text, timeout=timeout), loop + ) + try: + return future.result(timeout=timeout + 5.0) + except concurrent.futures.TimeoutError as exc: + future.cancel() + raise TimeoutError("simplex send request timed out") from exc + # ---- contacts ---- async def active_user(self, timeout: float = 20.0) -> int: diff --git a/tests/test_bridges.py b/tests/test_bridges.py index f312966..3a2e34c 100644 --- a/tests/test_bridges.py +++ b/tests/test_bridges.py @@ -32,6 +32,8 @@ class FakeDaemon: chats_error=None, history=None, history_error=None, + send_response=None, + send_error=None, ): self.link = link self.error = error @@ -41,6 +43,8 @@ class FakeDaemon: self.chats_error = chats_error self.history_list = history or [] self.history_error = history_error + self.send_response = send_response + self.send_error = send_error self.refresh_count = 0 self.chat_calls = [] self.history_calls = [] @@ -58,6 +62,19 @@ class FakeDaemon: if chat_id is not None: self.sent.append((chat_id, text)) + def request_send(self, chat_id, text, timeout=20.0): + self.sent.append((chat_id, text)) + if self.send_error is not None: + raise self.send_error + if self.send_response is not None: + return self.send_response + return { + "type": "newChatItems", + "chatItems": [ + {"chatItem": {"meta": {"itemId": 1, "itemStatus": {"type": "sndRcvd"}}}} + ], + } + def request_address(self, timeout=20.0): if self.error is not None: raise self.error @@ -186,7 +203,9 @@ def test_send_routes_to_daemon(): bridge, daemon, base = start_bridge() try: result = post(f"{base}/send", {"recipient": "7", "text": "on my way"}) - assert result == {"ok": True, "contact_id": "7"} + assert result["ok"] is True, result + assert result["contact_id"] == "7", result + assert result["status"] == "sndRcvd", result assert daemon.sent == [("7", "on my way")] finally: bridge.stop() @@ -203,6 +222,80 @@ def test_send_resolves_known_display_name(): bridge.stop() +def test_send_reports_a_failed_send_not_a_false_success(): + # A dead connection: the daemon creates the item then marks it sndError. + # The bridge must surface ok:false with the reason, never a false success. + failed = { + "type": "newChatItems", + "chatItems": [ + { + "chatItem": { + "meta": { + "itemId": 12, + "itemStatus": { + "type": "sndError", + "agentError": {"type": "auth"}, + }, + } + } + } + ], + } + daemon = FakeDaemon(send_response=failed) + bridge, _, base = start_bridge(daemon=daemon) + try: + result = post(f"{base}/send", {"recipient": "7", "text": "hey"}) + assert result["ok"] is False, result + assert result["status"] == "sndError", result + assert result["error"] == "auth", result + assert result["contact_id"] == "7" + finally: + bridge.stop() + + +def test_send_verifies_status_via_history(): + # The daemon accepts the send (sndNew) and only later resolves it to a + # delivered status; the bridge polls history to confirm. + accepted = { + "type": "newChatItems", + "chatItems": [ + {"chatItem": {"meta": {"itemId": 5, "itemStatus": {"type": "sndNew"}}}} + ], + } + history = [ + {"item_id": "5", "text": "hi", "status": "sndRcvd", "unread": False, + "direction": "directSnd", "sent_at": ""}, + ] + daemon = FakeDaemon(send_response=accepted, history=history) + bridge, _, base = start_bridge(daemon=daemon) + try: + result = post(f"{base}/send", {"recipient": "7", "text": "hi"}) + assert result["ok"] is True, result + assert result["status"] == "sndRcvd", result + assert daemon.history_calls, "the bridge must poll for the real status" + finally: + bridge.stop() + + +def test_resolve_prefers_a_healthy_duplicate(): + # Two peers share the display name "pepper"; the stale one has auth errors. + daemon = FakeDaemon( + contacts=[ + {"id": "3", "display_name": "pepper", "local_name": "pepper", + "connected": True, "auth_errors": 2}, + {"id": "4", "display_name": "pepper", "local_name": "pepper_1", + "connected": True, "auth_errors": 0}, + ] + ) + bridge, _, _ = start_bridge(daemon=daemon) + try: + assert bridge.resolve("pepper") == "4", "a stale duplicate must lose" + assert bridge.resolve("pepper_1") == "4" + assert bridge.resolve("3") == "3", "an explicit id always wins" + finally: + bridge.stop() + + def test_contacts_refreshed_from_daemon(): # A contact the bridge has never received from must still be visible: the # daemon knows them, so /send can address them. @@ -222,7 +315,7 @@ def test_send_resolves_daemon_only_contact(): bridge, _, base = start_bridge(daemon=daemon) try: result = post(f"{base}/send", {"recipient": "Zed", "text": "hello"}) - assert result == {"ok": True, "contact_id": "42"} + assert result["ok"] is True and result["contact_id"] == "42", result assert daemon.sent == [("42", "hello")] finally: bridge.stop() @@ -370,6 +463,23 @@ def test_unread_returns_daemon_chats(): bridge.stop() +def test_unread_attaches_cached_connection_health(): + daemon = FakeDaemon(chats=[chat_summary(contact_id="4", display_name="pepper")]) + bridge, _, base = start_bridge(daemon=daemon) + try: + bridge.inbox.merge_contacts( + [ + {"id": "4", "display_name": "pepper", "local_name": "pepper_1", + "connected": True, "auth_errors": 0}, + ] + ) + chats = get(f"{base}/unread")["chats"] + assert chats[0]["connected"] is True + assert chats[0]["auth_errors"] == 0 + finally: + bridge.stop() + + def test_unread_honours_count_query(): daemon = FakeDaemon(chats=[]) bridge, _, base = start_bridge(daemon=daemon) diff --git a/tests/test_simplex_ws.py b/tests/test_simplex_ws.py index 21c9300..732d359 100644 --- a/tests/test_simplex_ws.py +++ b/tests/test_simplex_ws.py @@ -141,18 +141,66 @@ def test_contact_link_reads_both_shapes(): def test_contact_entry_reads_v7_shape(): assert contact_entry( {"contactId": 4, "displayName": None, "profile": {"displayName": "Alice"}} - ) == {"id": "4", "display_name": "Alice"} + ) == {"id": "4", "display_name": "Alice", "local_name": "Alice"} assert contact_entry({"contactId": 7, "localDisplayName": "bob_1"}) == { "id": "7", "display_name": "bob_1", + "local_name": "bob_1", } assert contact_entry({"chatId": 9, "profile": {"displayName": "Carol"}}) == { "id": "9", "display_name": "Carol", + "local_name": "Carol", } assert contact_entry({"profile": {"displayName": "no id"}}) is None +def test_contact_entry_keeps_unique_local_name_and_health(): + # Two peers share the profile name "pepper"; the daemon's local name is + # unique, and the connection health tells a live peer from a stale one. + healthy = contact_entry( + { + "contactId": 4, + "localDisplayName": "pepper_1", + "profile": {"displayName": "pepper"}, + "contactStatus": "active", + "activeConn": {"connStatus": {"type": "ready"}, "authErrCounter": 0}, + } + ) + assert healthy == { + "id": "4", + "display_name": "pepper", + "local_name": "pepper_1", + "connected": True, + "auth_errors": 0, + } + stale = contact_entry( + { + "contactId": 3, + "localDisplayName": "pepper", + "profile": {"displayName": "pepper"}, + "contactStatus": "active", + "activeConn": {"connStatus": {"type": "ready"}, "authErrCounter": 2}, + } + ) + assert stale["local_name"] == "pepper" + assert stale["connected"] is True + assert stale["auth_errors"] == 2 + + +def test_contact_entry_marks_a_non_ready_connection_disconnected(): + entry = contact_entry( + { + "contactId": 4, + "profile": {"displayName": "Alice"}, + "contactStatus": "active", + "activeConn": {"connStatus": {"type": "connecting"}}, + } + ) + assert entry["connected"] is False + assert "auth_errors" not in entry + + # ---- daemon: accept + round-trips ---- class FakeWS: @@ -315,8 +363,8 @@ def test_contacts_parses_contacts_list(): result, ws = asyncio.run(scenario()) assert result == [ - {"id": "4", "display_name": "Alice"}, - {"id": "7", "display_name": "bob_1"}, + {"id": "4", "display_name": "Alice", "local_name": "Alice"}, + {"id": "7", "display_name": "bob_1", "local_name": "bob_1"}, ] assert [m["cmd"] for m in ws.sent] == ["/user", "/_contacts 3"]