bridges: refresh SimpleX contact list from the daemon

The bridge only learned contacts from observed inbound senders, so /send
could not address a contact it had never received from. Query /_contacts
<userId> (active user from /user, cached) over the existing corrId->Future
path, merge into the inbox on (re)connect via an on_connected hook and on
demand (GET /contacts, send-resolution miss). Best-effort: a disconnected
daemon keeps the cached set.
This commit is contained in:
Denton Social committed 2026-09-30 11:39:28 -05:00
1 parent fb5303928b
commit 4a4fe850e0
6 files changed
+387 -34

No files matched your search

+23 -15
View File
@@ -160,10 +160,12 @@ gateway/ messenger COMMAND intake/reply — and nothing else. base.py:
bridges/ standalone third-party API bridges (SimpleX first). base.py: bridges/ standalone third-party API bridges (SimpleX first). base.py:
BridgeInfo + BridgeService (shared localhost JSON HTTP layer, BridgeInfo + BridgeService (shared localhost JSON HTTP layer,
`X-Semif-Token` guard). inbox.py: MessagingInbox (bounded FIFO + `X-Semif-Token` guard). inbox.py: MessagingInbox (bounded FIFO +
contacts, bridge-owned read cursor). simplex.py: SimplexBridge — contacts learned from inbound DMs and the daemon contact list,
bridge-owned read cursor). simplex.py: SimplexBridge —
owns its OWN simplex-chat daemon/profile (separate from the owns its OWN simplex-chat daemon/profile (separate from the
gateway's), buffers every inbound DM, serves invite-link/read/ gateway's), buffers every inbound DM, refreshes the daemon
send. registry.py: CATALOG, describe_bridges() (catalog injected contact list on (re)connect + on demand, serves invite-link/
read/send. registry.py: CATALOG, describe_bridges() (catalog injected
into the codegen prompts), run_bridges(). Run with `python -m into the codegen prompts), run_bridges(). Run with `python -m
semif_agent.cli bridge [--name NAME]`; config under `bridges`. semif_agent.cli bridge [--name NAME]`; config under `bridges`.
simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway
@@ -833,11 +835,15 @@ CLI, unit tests (24) + box integration tests (2).
localhost-bound, optional shared-secret `X-Semif-Token` header. `SimplexBridge` localhost-bound, optional shared-secret `X-Semif-Token` header. `SimplexBridge`
buffers **every** inbound DM (no allowlist — the user wants to see who reached buffers **every** inbound DM (no allowlist — the user wants to see who reached
the bot through its invite link) in a bounded `MessagingInbox` that owns the the bot through its invite link) in a bounded `MessagingInbox` that owns the
read cursor, and serves `GET /health`, `GET /contacts`, `GET /inbox` (peek), read cursor, and serves `GET /health`, `GET /contacts` (the daemon's contact
`GET /inbox/next?contact=<id>` (pop oldest), `GET /address` (show/create the list, refreshed on (re)connect and on demand — best-effort, falling back to
forwarding bot's contact link; 503 when the daemon is not connected, 502 when the cached/inbound-learned set when the daemon is unavailable), `GET /inbox`
the lookup fails), and `POST /send` `{"recipient","text"}` (resolves a numeric (peek), `GET /inbox/next?contact=<id>` (pop oldest), `GET /address`
id or a known display name and enqueues on the bridge's own daemon). (show/create the forwarding bot's contact link; 503 when the daemon is not
connected, 502 when the lookup fails), and `POST /send`
`{"recipient","text"}` (resolves a numeric id or a known display name —
refreshing the daemon contact list once on a miss — and enqueues on the
bridge's own daemon).
- **Skill-facing config.** The top-level `simplex_bridge_url` is the address a - **Skill-facing config.** The top-level `simplex_bridge_url` is the address a
body calls (the data-contract config search auto-populates it); bootstrap keeps body calls (the data-contract config search auto-populates it); bootstrap keeps
it in sync with the bridge port. Skills reach a bridge with the ordinary `http` it in sync with the bridge port. Skills reach a bridge with the ordinary `http`
@@ -849,13 +855,15 @@ CLI, unit tests (24) + box integration tests (2).
The bridge read path (`simplex.next_message`) and contact-link lookup The bridge read path (`simplex.next_message`) and contact-link lookup
(`simplex.connect_link`) are covered. Deferred follow-ups: (`simplex.connect_link`) are covered. Deferred follow-ups:
- [ ] **1. Contact-list refresh from the daemon** (`bridges/simplex.py`, - [x] **1. Contact-list refresh from the daemon** (`bridges/simplex.py`,
`simplex_ws.py`). The bridge learns contacts only from observed inbound `simplex_ws.py`). Shipped: `SimplexDaemon.contacts()` /
senders, so `/send` cannot address a contact it has never received from. `request_contacts()` query `/_contacts <userId>` (active user from `/user` →
Query `/_contacts <userId>` (active user from `/user` → `activeUser.userId`, cached, falling back to the configured `user_id`) over
`activeUser.userId`) at startup and on demand, caching `contactId` + the existing corrId→Future path; `SimplexBridge` merges the result into the
`profile.displayName`. Reuse the daemon's corrId→Future path inbox on (re)connect via an `on_connected` hook and on demand (`GET
(`SimplexDaemon._roundtrip`) rather than opening a second WebSocket client. /contacts`, and a send-resolution miss), so `/send` can address a contact it
has never received from. Best-effort: a disconnected daemon keeps the cached
set.
- [ ] **2. Message history + true unread** (`bridges/simplex.py`). The in-memory - [ ] **2. Message history + true unread** (`bridges/simplex.py`). The in-memory
inbox is a receive buffer, not the daemon's read state. Use `/_get chats inbox is a receive buffer, not the daemon's read state. Use `/_get chats
<userId> count=<n> <json(PaginationByTime)>` with a `ChatListQuery` unread <userId> count=<n> <json(PaginationByTime)>` with a `ChatListQuery` unread
+17
View File
@@ -55,6 +55,23 @@ class MessagingInbox:
return entry return entry
return None return None
def merge_contacts(self, contacts: list[dict]) -> None:
"""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.
"""
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, "")
def contacts(self) -> list[dict]: def contacts(self) -> list[dict]:
with self._lock: with self._lock:
return [ return [
+43 -3
View File
@@ -35,7 +35,8 @@ class SimplexBridge(BridgeService):
"GET /health -> 200 {\"ok\": true, \"platform\": \"simplex\"} — the " "GET /health -> 200 {\"ok\": true, \"platform\": \"simplex\"} — the "
"bridge is up", "bridge is up",
"GET /contacts -> 200 {\"contacts\": [{\"id\", \"display_name\"}]} — " "GET /contacts -> 200 {\"contacts\": [{\"id\", \"display_name\"}]} — "
"contacts learned from inbound messages", "contacts known to the daemon (learned from inbound messages and "
"refreshed from the daemon's contact list)",
"GET /inbox -> 200 {\"messages\": [{\"id\", \"contact_id\", " "GET /inbox -> 200 {\"messages\": [{\"id\", \"contact_id\", "
"\"display_name\", \"text\", \"received_at\"}]} — peek buffered " "\"display_name\", \"text\", \"received_at\"}]} — peek buffered "
"inbound messages; does not consume", "inbound messages; does not consume",
@@ -88,6 +89,7 @@ class SimplexBridge(BridgeService):
user_id=int(cfg.get("user_id", 1)), user_id=int(cfg.get("user_id", 1)),
auto_accept=bool(cfg.get("auto_accept", True)), auto_accept=bool(cfg.get("auto_accept", True)),
reconnect=cfg.get("reconnect", {}) or {}, reconnect=cfg.get("reconnect", {}) or {},
on_connected=self._refresh_on_connect,
trace=trace, trace=trace,
name=self.name, name=self.name,
) )
@@ -115,13 +117,23 @@ class SimplexBridge(BridgeService):
def _on_message(self, message: dict) -> None: def _on_message(self, message: dict) -> None:
self.inbox.record(message) self.inbox.record(message)
async def _refresh_on_connect(self) -> None:
"""Prime the contact list from the daemon on (re)connect.
Runs on the daemon's event loop, so it awaits `contacts()` directly
rather than the thread-safe wrapper. A failure is traced, not fatal.
"""
contacts = await self.daemon.contacts()
self.inbox.merge_contacts(contacts)
self._event("contacts_refreshed", count=len(contacts))
# ---- routes ---- # ---- routes ----
def handle_get(self, path: str, query: dict) -> tuple[int, dict]: def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
if path == "/health": if path == "/health":
return 200, {"ok": True, "platform": self.name} return 200, {"ok": True, "platform": self.name}
if path == "/contacts": if path == "/contacts":
return 200, {"contacts": self.inbox.contacts()} return 200, {"contacts": self.refresh_contacts()}
if path == "/inbox": if path == "/inbox":
return 200, {"messages": self.inbox.peek()} return 200, {"messages": self.inbox.peek()}
if path == "/inbox/next": if path == "/inbox/next":
@@ -148,6 +160,22 @@ class SimplexBridge(BridgeService):
# ---- actions ---- # ---- actions ----
def refresh_contacts(self) -> list[dict]:
"""Best-effort refresh of the daemon's contact list into the inbox.
Never raises: when the daemon is not connected (or is slow) it returns
whatever contacts are already cached, so `/contacts` and `/send` stay
available. The read cursor and inbound-learned names are preserved.
"""
try:
contacts = self.daemon.request_contacts()
except Exception as exc: # RuntimeError, TimeoutError, daemon error
self._event("contacts_refresh_failed", message=str(exc)[:200])
return self.inbox.contacts()
self.inbox.merge_contacts(contacts)
self._event("contacts_refreshed", count=len(contacts))
return self.inbox.contacts()
def _address(self) -> tuple[int, dict]: def _address(self) -> tuple[int, dict]:
try: try:
link = self.daemon.request_address() link = self.daemon.request_address()
@@ -168,13 +196,25 @@ class SimplexBridge(BridgeService):
return contact_id return contact_id
def resolve(self, recipient: str) -> str | None: def resolve(self, recipient: str) -> str | None:
"""A numeric id (with or without `@`) or a known display name.""" """A numeric id (with or without `@`) or a known 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.
"""
recipient = str(recipient or "").strip() recipient = str(recipient or "").strip()
if not recipient: if not recipient:
return None return None
bare = recipient.lstrip("@") bare = recipient.lstrip("@")
if bare.isdigit(): if bare.isdigit():
return bare return bare
match = self._match_contact(recipient)
if match is None:
self.refresh_contacts()
match = self._match_contact(recipient)
return match
def _match_contact(self, recipient: str) -> str | None:
for contact in self.inbox.contacts(): for contact in self.inbox.contacts():
if contact["display_name"] == recipient or contact["id"] == recipient: if contact["display_name"] == recipient or contact["id"] == recipient:
return contact["id"] return contact["id"]
+98 -15
View File
@@ -23,12 +23,36 @@ import json
import queue import queue
import random import random
import threading import threading
from typing import Any, Callable from typing import Any, Awaitable, Callable
#: One received direct text message, normalized across the v7 wire shapes. #: One received direct text message, normalized across the v7 wire shapes.
InboundDict = dict[str, Any] InboundDict = dict[str, Any]
#: Callback invoked in the event loop for each received direct text message. #: Callback invoked in the event loop for each received direct text message.
MessageHandler = Callable[[InboundDict], None] MessageHandler = Callable[[InboundDict], None]
#: Async callback invoked in the event loop once a connection is established.
ConnectedHandler = Callable[[], Awaitable[None]]
def contact_entry(contact: dict) -> dict | None:
"""Normalize one daemon `Contact` into `{"id", "display_name"}`, 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`).
"""
contact_id = str(contact.get("contactId") or contact.get("chatId") or "")
if not contact_id:
return None
profile = contact.get("profile") or {}
display_name = (
profile.get("displayName")
or contact.get("displayName")
or contact.get("localDisplayName")
or ""
)
return {"id": contact_id, "display_name": display_name}
def contact_link(resp: dict) -> dict: def contact_link(resp: dict) -> dict:
@@ -84,23 +108,16 @@ def parse_direct_text_item(item: dict) -> InboundDict | None:
text = str(msg_content.get("text", "")).strip() text = str(msg_content.get("text", "")).strip()
if not text: if not text:
return None return None
contact = chat_info.get("contact") or {} contact = dict(chat_info.get("contact") or {})
contact_id = str(contact.get("contactId") or chat_info.get("chatId") or "") if not contact.get("contactId") and not contact.get("chatId"):
if not contact_id: contact["chatId"] = chat_info.get("chatId")
entry = contact_entry(contact)
if entry is None:
return None return None
profile = contact.get("profile") or {}
# v7's Contact has `displayName: null`; the real peer name lives in
# `profile.displayName`, and `localDisplayName` is auto-suffixed on
# collisions (e.g. a second contact becomes `pepper_1`).
display_name = (
profile.get("displayName")
or contact.get("displayName")
or contact.get("localDisplayName")
)
return { return {
"text": text, "text": text,
"contact_id": contact_id, "contact_id": entry["id"],
"display_name": display_name, "display_name": entry["display_name"],
"raw": item, "raw": item,
} }
@@ -149,6 +166,7 @@ class SimplexDaemon:
user_id: int = 1, user_id: int = 1,
auto_accept: bool = True, auto_accept: bool = True,
reconnect: dict | None = None, reconnect: dict | None = None,
on_connected: ConnectedHandler | None = None,
trace=None, trace=None,
name: str = "simplex", name: str = "simplex",
): ):
@@ -159,6 +177,7 @@ class SimplexDaemon:
self.reconnect_initial = float(settings.get("initial", 1.0)) self.reconnect_initial = float(settings.get("initial", 1.0))
self.reconnect_max = float(settings.get("max", 60.0)) self.reconnect_max = float(settings.get("max", 60.0))
self.reconnect_jitter = float(settings.get("jitter", 0.2)) self.reconnect_jitter = float(settings.get("jitter", 0.2))
self.on_connected = on_connected
self.trace = trace self.trace = trace
self.name = name self.name = name
self._corr = 0 self._corr = 0
@@ -168,6 +187,7 @@ class SimplexDaemon:
self._outbound: "queue.Queue[tuple[str, str] | None]" = queue.Queue() self._outbound: "queue.Queue[tuple[str, str] | None]" = queue.Queue()
self._stop = threading.Event() self._stop = threading.Event()
self._on_message: MessageHandler | None = None self._on_message: MessageHandler | None = None
self._active_user_id: int | None = None
# ---- requirements ---- # ---- requirements ----
@@ -208,6 +228,7 @@ class SimplexDaemon:
self._ws = ws self._ws = ws
backoff = self.reconnect_initial backoff = self.reconnect_initial
self._event("gateway_connected", url=self.ws_url) self._event("gateway_connected", url=self.ws_url)
await self._notify_connected()
sender = asyncio.create_task(self._outbound_loop(ws)) sender = asyncio.create_task(self._outbound_loop(ws))
try: try:
async for raw in ws: async for raw in ws:
@@ -231,6 +252,20 @@ class SimplexDaemon:
while not self._stop.is_set(): while not self._stop.is_set():
await asyncio.sleep(0.2) await asyncio.sleep(0.2)
async def _notify_connected(self) -> None:
"""Run the optional `on_connected` hook; a hook failure must not drop
the socket (it is traced and the connection stays up)."""
if self.on_connected is None:
return
try:
await self.on_connected()
except Exception as exc:
self._event(
"gateway_error",
phase="on_connected",
message=str(exc)[:300],
)
async def _outbound_loop(self, ws) -> None: async def _outbound_loop(self, ws) -> None:
loop = asyncio.get_running_loop() loop = asyncio.get_running_loop()
while True: while True:
@@ -313,6 +348,54 @@ class SimplexDaemon:
future.cancel() future.cancel()
raise TimeoutError("simplex address request timed out") from exc raise TimeoutError("simplex address request timed out") from exc
# ---- contacts ----
async def active_user(self, timeout: float = 20.0) -> int:
"""Resolve the active user id via `/user`, caching it after first use.
Falls back to the configured `user_id` when the daemon does not report
one, so a profile with a single user keeps working even on a shape drift.
"""
if self._active_user_id is not None:
return self._active_user_id
resp = await self._roundtrip("/user", timeout)
user = resp.get("user") or {}
user_id = user.get("userId")
self._active_user_id = int(user_id) if user_id is not None else self.user_id
return self._active_user_id
async def contacts(self, timeout: float = 20.0) -> list[dict]:
"""The daemon's contact list as `[{"id", "display_name"}]`.
`/_contacts <userId>` returns `contactsList` with a `Contact` array.
A `chatCmdError` or malformed reply yields an empty list rather than a
fabricated contact.
"""
user_id = await self.active_user(timeout)
resp = await self._roundtrip(f"/_contacts {user_id}", timeout)
contacts: list[dict] = []
for contact in resp.get("contacts") or []:
entry = contact_entry(contact)
if entry is not None:
contacts.append(entry)
return contacts
def request_contacts(self, timeout: float = 20.0) -> list[dict]:
"""Thread-safe contact-list lookup 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 list.
"""
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.contacts(timeout=timeout), loop)
try:
return future.result(timeout=timeout + 5.0)
except concurrent.futures.TimeoutError as exc:
future.cancel()
raise TimeoutError("simplex contacts request timed out") from exc
# ---- inbound ---- # ---- inbound ----
async def _consume(self, raw: Any) -> None: async def _consume(self, raw: Any) -> None:
+75 -1
View File
@@ -7,6 +7,7 @@ mechanics a skill depends on: peek/pop of buffered inbound messages, recipient
resolution, outbound routing, address lookup, and token/body validation. resolution, outbound routing, address lookup, and token/body validation.
""" """
import asyncio
import json import json
import urllib.error import urllib.error
import urllib.request import urllib.request
@@ -20,9 +21,12 @@ from semif_agent.bridges.simplex import SimplexBridge
class FakeDaemon: class FakeDaemon:
"""Stands in for the bridge's own simplex-chat connection.""" """Stands in for the bridge's own simplex-chat connection."""
def __init__(self, link=None, error=None): def __init__(self, link=None, error=None, contacts=None, contacts_error=None):
self.link = link self.link = link
self.error = error self.error = error
self.contacts_list = contacts or []
self.contacts_error = contacts_error
self.refresh_count = 0
self.sent = [] self.sent = []
self.closed = False self.closed = False
self.on_message = None self.on_message = None
@@ -42,6 +46,15 @@ class FakeDaemon:
raise self.error raise self.error
return self.link return self.link
def request_contacts(self, timeout=20.0):
self.refresh_count += 1
if self.contacts_error is not None:
raise self.contacts_error
return list(self.contacts_list)
async def contacts(self, timeout=20.0):
return self.request_contacts(timeout)
def close(self): def close(self):
self.closed = True self.closed = True
@@ -161,6 +174,67 @@ def test_send_resolves_known_display_name():
bridge.stop() 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.
daemon = FakeDaemon(contacts=[{"id": "42", "display_name": "Zed"}])
bridge, _, base = start_bridge(daemon=daemon)
try:
assert get(f"{base}/contacts") == {
"contacts": [{"id": "42", "display_name": "Zed"}]
}
assert daemon.refresh_count >= 1
finally:
bridge.stop()
def test_send_resolves_daemon_only_contact():
daemon = FakeDaemon(contacts=[{"id": "42", "display_name": "Zed"}])
bridge, _, base = start_bridge(daemon=daemon)
try:
result = post(f"{base}/send", {"recipient": "Zed", "text": "hello"})
assert result == {"ok": True, "contact_id": "42"}
assert daemon.sent == [("42", "hello")]
finally:
bridge.stop()
def test_refresh_on_connect_primes_contacts():
daemon = FakeDaemon(contacts=[{"id": "42", "display_name": "Zed"}])
bridge, _, base = start_bridge(daemon=daemon)
try:
asyncio.run(bridge._refresh_on_connect())
assert get(f"{base}/contacts")["contacts"] == [
{"id": "42", "display_name": "Zed"}
]
finally:
bridge.stop()
def test_contacts_failure_keeps_cached_and_stays_available():
bridge, _, base = start_bridge()
try:
bridge._on_message(inbound("hi", contact_id="4", display_name="Alice"))
bridge.daemon.contacts_error = RuntimeError("not connected")
assert get(f"{base}/contacts") == {
"contacts": [{"id": "4", "display_name": "Alice"}]
}
finally:
bridge.stop()
def test_daemon_refresh_does_not_clobber_inbound_name():
daemon = FakeDaemon(contacts=[{"id": "4", "display_name": ""}])
bridge, _, base = start_bridge(daemon=daemon)
try:
bridge._on_message(inbound("hi", contact_id="4", display_name="Alice"))
assert get(f"{base}/contacts") == {
"contacts": [{"id": "4", "display_name": "Alice"}]
}
finally:
bridge.stop()
def test_send_rejects_unknown_recipient(): def test_send_rejects_unknown_recipient():
bridge, daemon, base = start_bridge() bridge, daemon, base = start_bridge()
try: try:
+131
View File
@@ -14,6 +14,7 @@ import pytest
from semif_agent.simplex_ws import ( from semif_agent.simplex_ws import (
SimplexDaemon, SimplexDaemon,
accept_command, accept_command,
contact_entry,
contact_link, contact_link,
parse_direct_text_item, parse_direct_text_item,
send_text_command, send_text_command,
@@ -135,6 +136,21 @@ def test_contact_link_reads_both_shapes():
assert contact_link({}) == {} assert contact_link({}) == {}
def test_contact_entry_reads_v7_shape():
assert contact_entry(
{"contactId": 4, "displayName": None, "profile": {"displayName": "Alice"}}
) == {"id": "4", "display_name": "Alice"}
assert contact_entry({"contactId": 7, "localDisplayName": "bob_1"}) == {
"id": "7",
"display_name": "bob_1",
}
assert contact_entry({"chatId": 9, "profile": {"displayName": "Carol"}}) == {
"id": "9",
"display_name": "Carol",
}
assert contact_entry({"profile": {"displayName": "no id"}}) is None
# ---- daemon: accept + round-trips ---- # ---- daemon: accept + round-trips ----
class FakeWS: class FakeWS:
@@ -269,3 +285,118 @@ def test_request_address_without_connection_raises():
daemon = SimplexDaemon("ws://x") daemon = SimplexDaemon("ws://x")
with pytest.raises(RuntimeError): with pytest.raises(RuntimeError):
daemon.request_address(timeout=1) daemon.request_address(timeout=1)
# ---- daemon: contacts + on_connected hook ----
def test_contacts_parses_contacts_list():
daemon = SimplexDaemon("ws://x", user_id=1)
async def scenario():
daemon._loop = asyncio.get_running_loop()
ws = FakeWS(
daemon,
[
{"type": "activeUser", "user": {"userId": 3}},
{
"type": "contactsList",
"contacts": [
{"contactId": 4, "profile": {"displayName": "Alice"}},
{"contactId": 7, "localDisplayName": "bob_1"},
{"profile": {"displayName": "no id"}},
],
},
],
)
daemon._ws = ws
return await daemon.contacts(timeout=5), ws
result, ws = asyncio.run(scenario())
assert result == [
{"id": "4", "display_name": "Alice"},
{"id": "7", "display_name": "bob_1"},
]
assert [m["cmd"] for m in ws.sent] == ["/user", "/_contacts 3"]
def test_contacts_falls_back_to_configured_user_id():
daemon = SimplexDaemon("ws://x", user_id=1)
async def scenario():
daemon._loop = asyncio.get_running_loop()
ws = FakeWS(
daemon,
[
{"type": "chatCmdError", "chatError": {"type": "error"}},
{"type": "contactsList", "contacts": []},
],
)
daemon._ws = ws
return await daemon.contacts(timeout=5), ws
result, ws = asyncio.run(scenario())
assert result == []
assert [m["cmd"] for m in ws.sent] == ["/user", "/_contacts 1"]
def test_active_user_is_cached_across_calls():
daemon = SimplexDaemon("ws://x", user_id=1)
async def scenario():
daemon._loop = asyncio.get_running_loop()
ws = FakeWS(
daemon,
[
{"type": "activeUser", "user": {"userId": 3}},
{"type": "contactsList", "contacts": []},
{"type": "contactsList", "contacts": []},
],
)
daemon._ws = ws
await daemon.contacts(timeout=5)
await daemon.contacts(timeout=5)
return ws
ws = asyncio.run(scenario())
assert [m["cmd"] for m in ws.sent] == ["/user", "/_contacts 3", "/_contacts 3"]
def test_contacts_returns_empty_on_error_response():
daemon = SimplexDaemon("ws://x", user_id=1)
async def scenario():
daemon._loop = asyncio.get_running_loop()
ws = FakeWS(
daemon,
[
{"type": "activeUser", "user": {"userId": 1}},
{"type": "chatCmdError", "chatError": {"type": "error"}},
],
)
daemon._ws = ws
return await daemon.contacts(timeout=5)
assert asyncio.run(scenario()) == []
def test_request_contacts_without_connection_raises():
daemon = SimplexDaemon("ws://x")
with pytest.raises(RuntimeError):
daemon.request_contacts(timeout=1)
def test_on_connected_hook_runs_and_failures_are_swallowed():
calls = []
async def hook():
calls.append(1)
asyncio.run(SimplexDaemon("ws://x", on_connected=hook)._notify_connected())
assert calls == [1]
async def bad():
raise ValueError("nope")
# A hook failure must not propagate (it would tear down the connection).
asyncio.run(SimplexDaemon("ws://x", on_connected=bad)._notify_connected())
asyncio.run(SimplexDaemon("ws://x")._notify_connected())