bridges: standalone third-party API bridges; isolate the command gateway
Split messaging UX (invite links, read, send) out of the command gateway into a
new `semif_agent.bridges` layer. Each bridge is its own process (`cli bridge`)
against its own service daemon/profile; the SimpleX bridge owns a second
simplex-chat daemon and buffers every inbound DM, so a message sent to the
connect-link address shows up in `simplex.next_message`.
- new: bridges/{base,inbox,registry,simplex}.py + neutral semif_agent/simplex_ws.py
- gateway: delete bridge.py; drop address/observer/pull-mode from the command path
- codegen: inject the bridge catalog (describe_bridges) into body + elicitation prompts
- seeds: repoint simplex.next_message/connect_link to top-level `simplex_bridge_url`
- config/bootstrap: new top-level `bridges` block + `simplex_bridge_url`; render
semif-simplex-forward + semif-bridge units; gateway config loses bridge/inbox
- docs: AGENTS.md gateway isolation is non-negotiable
This commit is contained in:
1 parent
d46fbdca19
commit
ddc5cb66c8
31 files changed
+1702
-1088
No files matched your search
@@ -1,35 +1,60 @@
|
||||
"""Pure-stdlib tests for the gateway's local messaging bridge.
|
||||
"""Pure-stdlib tests for the standalone bridge services.
|
||||
|
||||
The bridge is exercised over a real loopback HTTP server (no mocking of its
|
||||
transport); the decision engine and LLM are never involved. These prove the
|
||||
The SimpleX bridge is exercised over a real loopback HTTP server (no mocking of
|
||||
its HTTP transport) with a fake daemon standing in for the `simplex-chat`
|
||||
connection — the decision engine and LLM are never involved. These prove the
|
||||
mechanics a skill depends on: peek/pop of buffered inbound messages, recipient
|
||||
resolution, outbound routing onto the adapter queue, and token/body validation.
|
||||
resolution, outbound routing, address lookup, and token/body validation.
|
||||
"""
|
||||
|
||||
import json
|
||||
import queue
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import pytest
|
||||
|
||||
from semif_agent.gateway.base import InboundMessage, OutboundMessage
|
||||
from semif_agent.gateway.bridge import MessagingBridge
|
||||
from semif_agent.bridges.registry import describe_bridges, known_infos
|
||||
from semif_agent.bridges.simplex import SimplexBridge
|
||||
|
||||
|
||||
def start_bridge(address_provider=None, **config):
|
||||
outbound = queue.Queue()
|
||||
bridge = MessagingBridge(
|
||||
outbound, config=config, address_provider=address_provider
|
||||
)
|
||||
class FakeDaemon:
|
||||
"""Stands in for the bridge's own simplex-chat connection."""
|
||||
|
||||
def __init__(self, link=None, error=None):
|
||||
self.link = link
|
||||
self.error = error
|
||||
self.sent = []
|
||||
self.closed = False
|
||||
self.on_message = None
|
||||
|
||||
def check_requirements(self):
|
||||
return True, None
|
||||
|
||||
def run(self, on_message):
|
||||
self.on_message = on_message
|
||||
|
||||
def enqueue(self, chat_id, text=""):
|
||||
if chat_id is not None:
|
||||
self.sent.append((chat_id, text))
|
||||
|
||||
def request_address(self, timeout=20.0):
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
return self.link
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def start_bridge(daemon=None, **config):
|
||||
daemon = daemon or FakeDaemon()
|
||||
bridge = SimplexBridge(config, daemon=daemon)
|
||||
port = bridge.start()
|
||||
return bridge, outbound, f"http://127.0.0.1:{port}"
|
||||
return bridge, daemon, f"http://127.0.0.1:{port}"
|
||||
|
||||
|
||||
def inbound(text, contact_id="4", display_name="Alice"):
|
||||
return InboundMessage(
|
||||
text=text, chat_id=contact_id, contact_id=contact_id, display_name=display_name
|
||||
)
|
||||
return {"text": text, "contact_id": contact_id, "display_name": display_name}
|
||||
|
||||
|
||||
def get(url, token=None):
|
||||
@@ -53,7 +78,7 @@ def test_health_and_contacts():
|
||||
bridge, _, base = start_bridge()
|
||||
try:
|
||||
assert get(f"{base}/health") == {"ok": True, "platform": "simplex"}
|
||||
bridge.record_inbound(inbound("hi", contact_id="4", display_name="Alice"))
|
||||
bridge._on_message(inbound("hi", contact_id="4", display_name="Alice"))
|
||||
assert get(f"{base}/contacts") == {
|
||||
"contacts": [{"id": "4", "display_name": "Alice"}]
|
||||
}
|
||||
@@ -64,8 +89,8 @@ def test_health_and_contacts():
|
||||
def test_inbox_peek_then_pop_consumes_oldest():
|
||||
bridge, _, base = start_bridge()
|
||||
try:
|
||||
bridge.record_inbound(inbound("first", contact_id="4", display_name="Alice"))
|
||||
bridge.record_inbound(inbound("second", contact_id="7", display_name="Bob"))
|
||||
bridge._on_message(inbound("first", contact_id="4", display_name="Alice"))
|
||||
bridge._on_message(inbound("second", contact_id="7", display_name="Bob"))
|
||||
peeked = get(f"{base}/inbox")["messages"]
|
||||
assert [m["text"] for m in peeked] == ["first", "second"]
|
||||
assert get(f"{base}/inbox")["messages"] == peeked, "peek must not consume"
|
||||
@@ -82,8 +107,8 @@ def test_inbox_peek_then_pop_consumes_oldest():
|
||||
def test_inbox_next_filters_by_contact():
|
||||
bridge, _, base = start_bridge()
|
||||
try:
|
||||
bridge.record_inbound(inbound("first", contact_id="4", display_name="Alice"))
|
||||
bridge.record_inbound(inbound("second", contact_id="7", display_name="Bob"))
|
||||
bridge._on_message(inbound("first", contact_id="4", display_name="Alice"))
|
||||
bridge._on_message(inbound("second", contact_id="7", display_name="Bob"))
|
||||
popped = get(f"{base}/inbox/next?contact=7")["message"]
|
||||
assert popped["text"] == "second"
|
||||
assert get(f"{base}/inbox/next?contact=7")["message"] is None
|
||||
@@ -92,60 +117,69 @@ def test_inbox_next_filters_by_contact():
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_inbox_buffers_any_sender():
|
||||
# No allowlist: a brand-new contact who reached the bot via its invite link
|
||||
# must be visible, which is the whole point of the forwarding bridge.
|
||||
bridge, _, base = start_bridge()
|
||||
try:
|
||||
bridge._on_message(inbound("who are you?", contact_id="99", display_name="stranger"))
|
||||
messages = get(f"{base}/inbox")["messages"]
|
||||
assert [m["text"] for m in messages] == ["who are you?"]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_inbox_is_bounded():
|
||||
bridge, _, base = start_bridge(max_inbox=2)
|
||||
try:
|
||||
for text in ("one", "two", "three"):
|
||||
bridge.record_inbound(inbound(text))
|
||||
bridge._on_message(inbound(text))
|
||||
messages = get(f"{base}/inbox")["messages"]
|
||||
assert [m["text"] for m in messages] == ["two", "three"], "oldest must be dropped"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_routes_to_outbound_queue():
|
||||
bridge, outbound, base = start_bridge()
|
||||
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"}
|
||||
message = outbound.get_nowait()
|
||||
assert isinstance(message, OutboundMessage)
|
||||
assert message.chat_id == "7"
|
||||
assert message.text == "on my way"
|
||||
assert daemon.sent == [("7", "on my way")]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_resolves_known_display_name():
|
||||
bridge, outbound, base = start_bridge()
|
||||
bridge, daemon, base = start_bridge()
|
||||
try:
|
||||
bridge.record_inbound(inbound("hi", contact_id="4", display_name="Alice"))
|
||||
bridge._on_message(inbound("hi", contact_id="4", display_name="Alice"))
|
||||
result = post(f"{base}/send", {"recipient": "Alice", "text": "hello"})
|
||||
assert result["contact_id"] == "4"
|
||||
assert outbound.get_nowait().chat_id == "4"
|
||||
assert daemon.sent == [("4", "hello")]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_rejects_unknown_recipient():
|
||||
bridge, outbound, base = start_bridge()
|
||||
bridge, daemon, base = start_bridge()
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
post(f"{base}/send", {"recipient": "ghost", "text": "hello"})
|
||||
assert exc.value.code == 400
|
||||
assert outbound.empty(), "a rejected send must not enqueue anything"
|
||||
assert daemon.sent == [], "a rejected send must not enqueue anything"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_validates_body():
|
||||
bridge, outbound, base = start_bridge()
|
||||
bridge, daemon, base = start_bridge()
|
||||
try:
|
||||
for payload in ({"recipient": "", "text": "hi"}, {"recipient": "4", "text": " "}):
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
post(f"{base}/send", payload)
|
||||
assert exc.value.code == 400
|
||||
assert outbound.empty()
|
||||
assert daemon.sent == []
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
@@ -164,17 +198,19 @@ def test_token_is_required_when_configured():
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_address_uses_provider():
|
||||
def test_address_returns_daemon_link():
|
||||
link = {"short_link": "simplex:/abc", "full_link": "https://x", "created": False}
|
||||
bridge, _, base = start_bridge(address_provider=lambda: link)
|
||||
bridge, _, base = start_bridge(daemon=FakeDaemon(link=link))
|
||||
try:
|
||||
assert get(f"{base}/address") == link
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_address_without_provider_is_unavailable():
|
||||
bridge, _, base = start_bridge()
|
||||
def test_address_without_connection_is_unavailable():
|
||||
bridge, _, base = start_bridge(
|
||||
daemon=FakeDaemon(error=RuntimeError("not connected"))
|
||||
)
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
get(f"{base}/address")
|
||||
@@ -183,14 +219,33 @@ def test_address_without_provider_is_unavailable():
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_address_provider_failure_is_reported():
|
||||
def boom():
|
||||
raise RuntimeError("not connected")
|
||||
|
||||
bridge, _, base = start_bridge(address_provider=boom)
|
||||
def test_address_lookup_failure_is_reported():
|
||||
bridge, _, base = start_bridge(daemon=FakeDaemon(error=TimeoutError("slow")))
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
get(f"{base}/address")
|
||||
assert exc.value.code == 502
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_stop_closes_the_daemon():
|
||||
bridge, daemon, _ = start_bridge()
|
||||
bridge.stop()
|
||||
assert daemon.closed is True
|
||||
|
||||
|
||||
# ---- catalog / codegen surface ----
|
||||
|
||||
def test_known_infos_include_simplex():
|
||||
infos = {info.name: info for info in known_infos()}
|
||||
assert "simplex" in infos
|
||||
assert infos["simplex"].url_config_var == "simplex_bridge_url"
|
||||
|
||||
|
||||
def test_describe_bridges_names_the_service_and_config_var():
|
||||
text = describe_bridges()
|
||||
assert "simplex" in text
|
||||
assert "simplex_bridge_url" in text
|
||||
assert "/inbox/next" in text
|
||||
assert "never speak" in text
|
||||
@@ -1680,17 +1680,17 @@ def test_skill_contract_lists_all_transports():
|
||||
assert transport in text
|
||||
|
||||
|
||||
def test_skill_contract_documents_messaging_bridge():
|
||||
def test_skill_contract_documents_bridge_services():
|
||||
text = read_skill_contract()
|
||||
assert "messaging_bridge_url" in text
|
||||
assert "simplex_bridge_url" in text
|
||||
assert "/inbox/next" in text
|
||||
assert "/send" in text
|
||||
assert "never opens a WebSocket" in text
|
||||
assert "never speak a service's native protocol" in text
|
||||
|
||||
|
||||
def test_body_directives_expose_messaging_bridge():
|
||||
assert "messaging_bridge_url" in BODY_DIRECTIVES
|
||||
assert "never open a WebSocket" in BODY_DIRECTIVES
|
||||
def test_body_directives_expose_bridge_services():
|
||||
assert "bridge services" in BODY_DIRECTIVES
|
||||
assert "never speak the service's native protocol" in BODY_DIRECTIVES
|
||||
|
||||
|
||||
def test_body_prompts_require_real_action_and_integration():
|
||||
|
||||
+7
-261
@@ -1,16 +1,17 @@
|
||||
"""Pure-stdlib tests for the messenger gateway (SimpleX adapter + router).
|
||||
"""Pure-stdlib tests for the messenger gateway (SimpleX command adapter + router).
|
||||
|
||||
The decision engine is never loaded and the LLM endpoint is unreachable, so
|
||||
scheduler calls degrade to errors — which is fine: these tests exercise the
|
||||
gateway's own routing, authorization, parsing, and batching. The real
|
||||
`websockets` transport against a live `simplex-chat` daemon is a jarvis
|
||||
The gateway is the agent's command surface only. These tests exercise its own
|
||||
routing, authorization, and batching; parsing/accept/address live in
|
||||
`tests/test_simplex_ws.py`. The decision engine is never loaded and the LLM
|
||||
endpoint is unreachable, so scheduler calls degrade to errors — which is fine.
|
||||
The real `websockets` transport against a live `simplex-chat` daemon is a jarvis
|
||||
integration concern, not a dev-box unit test.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Request
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.engine import EngineConfig, SemIfEngine
|
||||
from semif_agent.gateway.base import InboundMessage
|
||||
from semif_agent.gateway.service import GatewayService
|
||||
@@ -63,105 +64,6 @@ def test_check_requirements_needs_url():
|
||||
assert "ws_url" in hint
|
||||
|
||||
|
||||
# ---- adapter: parsing ----
|
||||
|
||||
def direct_item(text="hello", contact_id="4", display="alice", direction="directRcv", kind="text"):
|
||||
# v7 wire shape: the Contact's `displayName` is null and the peer name lives
|
||||
# in `profile.displayName`; `localDisplayName` is auto-suffixed on collision.
|
||||
# Received text is tagged `rcvMsgContent` with the message under `msgContent`.
|
||||
return {
|
||||
"chatInfo": {
|
||||
"type": "direct",
|
||||
"chatId": contact_id,
|
||||
"contact": {
|
||||
"contactId": contact_id,
|
||||
"localDisplayName": display,
|
||||
"displayName": None,
|
||||
"profile": {"displayName": display},
|
||||
},
|
||||
},
|
||||
"chatItem": {
|
||||
"chatDir": {"type": direction},
|
||||
"content": {
|
||||
"type": "rcvMsgContent",
|
||||
"msgContent": {"type": kind, "text": text},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_parse_authorized_direct_text():
|
||||
adapter = SimplexAdapter({"allowed_users": ["4"]})
|
||||
message = adapter._parse_chat_item(direct_item())
|
||||
assert message is not None
|
||||
assert message.text == "hello"
|
||||
assert message.chat_id == "4"
|
||||
assert message.contact_id == "4"
|
||||
assert message.display_name == "alice"
|
||||
|
||||
|
||||
def test_parse_filters_echo_group_and_non_text():
|
||||
adapter = SimplexAdapter({"allow_all_users": True})
|
||||
assert adapter._parse_chat_item(direct_item(direction="directSnd")) is None
|
||||
assert adapter._parse_chat_item(direct_item(kind="image")) is None
|
||||
group = direct_item()
|
||||
group["chatInfo"]["type"] = "group"
|
||||
assert adapter._parse_chat_item(group) is None
|
||||
|
||||
|
||||
def test_parse_filters_unauthorized_contact():
|
||||
adapter = SimplexAdapter({"allowed_users": ["9"]})
|
||||
assert adapter._parse_chat_item(direct_item(contact_id="4", display="alice")) is None
|
||||
|
||||
|
||||
def test_parse_real_v7_payload_with_suffixed_local_name():
|
||||
# Captured live from simplex-chat v7 (`/_get chat @3`): the text is nested
|
||||
# under content.msgContent; Contact.displayName is null, the peer name is in
|
||||
# profile.displayName, and a collision-suffixed localDisplayName must not
|
||||
# defeat the allowlist.
|
||||
adapter = SimplexAdapter({"allowed_users": ["pepper"]})
|
||||
item = {
|
||||
"chatInfo": {
|
||||
"type": "direct",
|
||||
"chatId": 6,
|
||||
"contact": {
|
||||
"contactId": 6,
|
||||
"localDisplayName": "pepper_1",
|
||||
"displayName": None,
|
||||
"profile": {"displayName": "pepper"},
|
||||
},
|
||||
},
|
||||
"chatItem": {
|
||||
"chatDir": {"type": "directRcv"},
|
||||
"content": {
|
||||
"type": "rcvMsgContent",
|
||||
"msgContent": {
|
||||
"type": "text",
|
||||
"text": "what is the next thing on my calendar?",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
message = adapter._parse_chat_item(item)
|
||||
assert message is not None
|
||||
assert message.text == "what is the next thing on my calendar?"
|
||||
assert message.contact_id == "6"
|
||||
assert message.display_name == "pepper"
|
||||
|
||||
|
||||
def test_parse_accepts_aeson_nested_content_shape():
|
||||
# The daemon's DB/Aeson encoding nests under the constructor key instead of
|
||||
# tagging with `type`; the parser tolerates both.
|
||||
adapter = SimplexAdapter({"allow_all_users": True})
|
||||
item = direct_item()
|
||||
item["chatItem"]["content"] = {
|
||||
"rcvMsgContent": {"msgContent": {"type": "text", "text": "hi"}}
|
||||
}
|
||||
message = adapter._parse_chat_item(item)
|
||||
assert message is not None
|
||||
assert message.text == "hi"
|
||||
|
||||
|
||||
# ---- adapter: send command ----
|
||||
|
||||
def test_send_command_is_structured_not_shortcut():
|
||||
@@ -174,44 +76,6 @@ def test_send_command_is_structured_not_shortcut():
|
||||
assert command != "/_send @4 hello"
|
||||
|
||||
|
||||
# ---- adapter: contact request acceptance ----
|
||||
|
||||
class _FakeWS:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
async def send(self, data):
|
||||
self.sent.append(json.loads(data)["cmd"])
|
||||
|
||||
|
||||
def _contact_request_event(req):
|
||||
return json.dumps(
|
||||
{"resp": {"type": "receivedContactRequest", "contactRequest": req}}
|
||||
)
|
||||
|
||||
|
||||
def test_accept_uses_v7_contact_request_id():
|
||||
# v7 exposes contactRequestId (and contactId_); /_accept takes the request id.
|
||||
adapter = SimplexAdapter({"auto_accept": True})
|
||||
ws = _FakeWS()
|
||||
asyncio.run(adapter._consume(_contact_request_event({"contactRequestId": 7, "contactId_": 9}), lambda m: None, ws))
|
||||
assert ws.sent == ["/_accept 7"]
|
||||
|
||||
|
||||
def test_accept_falls_back_to_contact_id_for_legacy_events():
|
||||
adapter = SimplexAdapter({"auto_accept": True})
|
||||
ws = _FakeWS()
|
||||
asyncio.run(adapter._consume(_contact_request_event({"contactId": 4}), lambda m: None, ws))
|
||||
assert ws.sent == ["/_accept 4"]
|
||||
|
||||
|
||||
def test_accept_disabled_sends_nothing():
|
||||
adapter = SimplexAdapter({"auto_accept": False})
|
||||
ws = _FakeWS()
|
||||
asyncio.run(adapter._consume(_contact_request_event({"contactRequestId": 7, "contactId_": 9}), lambda m: None, ws))
|
||||
assert ws.sent == []
|
||||
|
||||
|
||||
# ---- adapter: batching ----
|
||||
|
||||
def test_batching_concatenates_rapid_messages():
|
||||
@@ -340,121 +204,3 @@ def test_service_answered_question_routes_back(tmp_path):
|
||||
|
||||
service.handle_inbound(InboundMessage(text="work", chat_id="4", contact_id="4"))
|
||||
assert not scheduler.pending_questions()
|
||||
|
||||
|
||||
def test_service_observer_sees_authorized_inbound(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
service = build_service(scheduler)
|
||||
seen = []
|
||||
service.observer = seen.append
|
||||
service.handle_inbound(InboundMessage(text="hi", chat_id="4", contact_id="4"))
|
||||
assert [m.text for m in seen] == ["hi"]
|
||||
|
||||
|
||||
def test_service_pull_mode_buffers_without_dispatch(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
service = GatewayService(scheduler, FakeAdapter(), config={"inbox": {"dispatch": False}})
|
||||
seen = []
|
||||
service.observer = seen.append
|
||||
service.handle_inbound(InboundMessage(text="hi", chat_id="4", contact_id="4"))
|
||||
assert [m.text for m in seen] == ["hi"], "pull mode must still buffer for a read skill"
|
||||
assert drain_outbound(service) == [], "pull mode must not reply or dispatch"
|
||||
assert scheduler.current is None
|
||||
assert scheduler.pending is None
|
||||
|
||||
|
||||
# ---- adapter: correlated request/response + contact address ----
|
||||
|
||||
|
||||
class FakeWS:
|
||||
"""A fake simplex-chat socket that answers correlated commands."""
|
||||
|
||||
def __init__(self, adapter, responses):
|
||||
self.adapter = adapter
|
||||
self.responses = list(responses)
|
||||
self.sent = []
|
||||
|
||||
async def send(self, raw):
|
||||
message = json.loads(raw)
|
||||
self.sent.append(message)
|
||||
response = self.responses.pop(0)
|
||||
await self.adapter._consume(
|
||||
json.dumps({"corrId": message["corrId"], "resp": response}), None, self
|
||||
)
|
||||
|
||||
|
||||
def test_correlated_response_resolves_pending_future():
|
||||
adapter = SimplexAdapter({})
|
||||
|
||||
async def scenario():
|
||||
adapter._loop = asyncio.get_running_loop()
|
||||
adapter._ws = FakeWS(adapter, [])
|
||||
future = adapter._loop.create_future()
|
||||
adapter._pending["req-9"] = future
|
||||
await adapter._consume(
|
||||
json.dumps({"corrId": "req-9", "resp": {"type": "ok", "value": 1}}), None, adapter._ws
|
||||
)
|
||||
assert "req-9" not in adapter._pending, "a resolved request must be dropped"
|
||||
return future.result()
|
||||
|
||||
assert asyncio.run(scenario()) == {"type": "ok", "value": 1}
|
||||
|
||||
|
||||
def test_address_returns_existing_link():
|
||||
adapter = SimplexAdapter({"user_id": 3})
|
||||
|
||||
async def scenario():
|
||||
adapter._loop = asyncio.get_running_loop()
|
||||
ws = FakeWS(
|
||||
adapter,
|
||||
[
|
||||
{
|
||||
"type": "userContactLink",
|
||||
"user": {"userId": 3},
|
||||
"contactLink": {
|
||||
"userContactLinkId": 1,
|
||||
"connLinkContact": {
|
||||
"connShortLink": "simplex:/a",
|
||||
"connFullLink": "https://a",
|
||||
},
|
||||
},
|
||||
}
|
||||
],
|
||||
)
|
||||
adapter._ws = ws
|
||||
return await adapter.address(timeout=5), ws
|
||||
|
||||
result, ws = asyncio.run(scenario())
|
||||
assert result == {"short_link": "simplex:/a", "full_link": "https://a", "created": False}
|
||||
assert [m["cmd"] for m in ws.sent] == ["/_show_address 3"]
|
||||
|
||||
|
||||
def test_address_creates_when_missing():
|
||||
adapter = SimplexAdapter({"user_id": 1})
|
||||
|
||||
async def scenario():
|
||||
adapter._loop = asyncio.get_running_loop()
|
||||
ws = FakeWS(
|
||||
adapter,
|
||||
[
|
||||
{"type": "userContactLink", "contactLink": None},
|
||||
{
|
||||
"type": "userContactLinkCreated",
|
||||
"connLinkContact": {"connShortLink": "simplex:/new", "connFullLink": ""},
|
||||
},
|
||||
],
|
||||
)
|
||||
adapter._ws = ws
|
||||
return await adapter.address(timeout=5), ws
|
||||
|
||||
result, ws = asyncio.run(scenario())
|
||||
assert result == {"short_link": "simplex:/new", "full_link": "", "created": True}
|
||||
assert [m["cmd"] for m in ws.sent] == ["/_show_address 1", "/_address 1"]
|
||||
|
||||
|
||||
def test_request_address_without_connection_raises():
|
||||
import pytest
|
||||
|
||||
adapter = SimplexAdapter({})
|
||||
with pytest.raises(RuntimeError):
|
||||
adapter.request_address(timeout=1)
|
||||
@@ -0,0 +1,271 @@
|
||||
"""Pure-stdlib tests for the neutral SimpleX daemon protocol layer.
|
||||
|
||||
`semif_agent.simplex_ws` is shared by the command gateway and the forwarding
|
||||
bridge, so its parsing/accept/address behavior is tested here, independent of
|
||||
either front end. The real `websockets` transport against a live daemon is a
|
||||
jarvis integration concern.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from semif_agent.simplex_ws import (
|
||||
SimplexDaemon,
|
||||
accept_command,
|
||||
contact_link,
|
||||
parse_direct_text_item,
|
||||
send_text_command,
|
||||
)
|
||||
|
||||
|
||||
# ---- parsing ----
|
||||
|
||||
def direct_item(text="hello", contact_id="4", display="alice", direction="directRcv", kind="text"):
|
||||
# v7 wire shape: the Contact's `displayName` is null and the peer name lives
|
||||
# in `profile.displayName`; `localDisplayName` is auto-suffixed on collision.
|
||||
# Received text is tagged `rcvMsgContent` with the message under `msgContent`.
|
||||
return {
|
||||
"chatInfo": {
|
||||
"type": "direct",
|
||||
"chatId": contact_id,
|
||||
"contact": {
|
||||
"contactId": contact_id,
|
||||
"localDisplayName": display,
|
||||
"displayName": None,
|
||||
"profile": {"displayName": display},
|
||||
},
|
||||
},
|
||||
"chatItem": {
|
||||
"chatDir": {"type": direction},
|
||||
"content": {
|
||||
"type": "rcvMsgContent",
|
||||
"msgContent": {"type": kind, "text": text},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_parse_direct_text():
|
||||
message = parse_direct_text_item(direct_item())
|
||||
assert message is not None
|
||||
assert message["text"] == "hello"
|
||||
assert message["contact_id"] == "4"
|
||||
assert message["display_name"] == "alice"
|
||||
|
||||
|
||||
def test_parse_filters_echo_group_and_non_text():
|
||||
assert parse_direct_text_item(direct_item(direction="directSnd")) is None
|
||||
assert parse_direct_text_item(direct_item(kind="image")) is None
|
||||
group = direct_item()
|
||||
group["chatInfo"]["type"] = "group"
|
||||
assert parse_direct_text_item(group) is None
|
||||
|
||||
|
||||
def test_parse_is_policy_free():
|
||||
# No allowlist lives here: the bridge buffers everyone; the gateway filters.
|
||||
assert parse_direct_text_item(direct_item(contact_id="999", display="ghost")) is not None
|
||||
|
||||
|
||||
def test_parse_real_v7_payload_with_suffixed_local_name():
|
||||
item = {
|
||||
"chatInfo": {
|
||||
"type": "direct",
|
||||
"chatId": 6,
|
||||
"contact": {
|
||||
"contactId": 6,
|
||||
"localDisplayName": "pepper_1",
|
||||
"displayName": None,
|
||||
"profile": {"displayName": "pepper"},
|
||||
},
|
||||
},
|
||||
"chatItem": {
|
||||
"chatDir": {"type": "directRcv"},
|
||||
"content": {
|
||||
"type": "rcvMsgContent",
|
||||
"msgContent": {
|
||||
"type": "text",
|
||||
"text": "what is the next thing on my calendar?",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
message = parse_direct_text_item(item)
|
||||
assert message is not None
|
||||
assert message["text"] == "what is the next thing on my calendar?"
|
||||
assert message["contact_id"] == "6"
|
||||
assert message["display_name"] == "pepper"
|
||||
|
||||
|
||||
def test_parse_accepts_aeson_nested_content_shape():
|
||||
item = direct_item()
|
||||
item["chatItem"]["content"] = {
|
||||
"rcvMsgContent": {"msgContent": {"type": "text", "text": "hi"}}
|
||||
}
|
||||
message = parse_direct_text_item(item)
|
||||
assert message is not None
|
||||
assert message["text"] == "hi"
|
||||
|
||||
|
||||
# ---- send / accept commands ----
|
||||
|
||||
def test_send_command_is_structured_not_shortcut():
|
||||
command = send_text_command("4", "hello")
|
||||
assert command.startswith("/_send @4 json ")
|
||||
payload = json.loads(command.split(" json ", 1)[1])
|
||||
assert payload[0]["msgContent"]["type"] == "text"
|
||||
assert payload[0]["msgContent"]["text"] == "hello"
|
||||
assert command != "/_send @4 hello"
|
||||
|
||||
|
||||
def test_accept_command_uses_v7_request_id():
|
||||
assert accept_command({"contactRequest": {"contactRequestId": 7, "contactId_": 9}}) == "/_accept 7"
|
||||
assert accept_command({"contactRequest": {"contactId": 4}}) == "/_accept 4"
|
||||
assert accept_command({}) is None
|
||||
|
||||
|
||||
def test_contact_link_reads_both_shapes():
|
||||
nested = {"contactLink": {"connLinkContact": {"connShortLink": "simplex:/a"}}}
|
||||
flat = {"connLinkContact": {"connFullLink": "https://a"}}
|
||||
direct = {"connShortLink": "simplex:/b"}
|
||||
assert contact_link(nested)["connShortLink"] == "simplex:/a"
|
||||
assert contact_link(flat)["connFullLink"] == "https://a"
|
||||
assert contact_link(direct)["connShortLink"] == "simplex:/b"
|
||||
assert contact_link({}) == {}
|
||||
|
||||
|
||||
# ---- daemon: accept + round-trips ----
|
||||
|
||||
class FakeWS:
|
||||
"""A fake simplex-chat socket that answers correlated commands."""
|
||||
|
||||
def __init__(self, daemon, responses):
|
||||
self.daemon = daemon
|
||||
self.responses = list(responses)
|
||||
self.sent = []
|
||||
|
||||
async def send(self, raw):
|
||||
message = json.loads(raw)
|
||||
self.sent.append(message)
|
||||
if self.responses:
|
||||
response = self.responses.pop(0)
|
||||
await self.daemon._consume(
|
||||
json.dumps({"corrId": message["corrId"], "resp": response})
|
||||
)
|
||||
|
||||
|
||||
def _contact_request_event(req):
|
||||
return json.dumps(
|
||||
{"resp": {"type": "receivedContactRequest", "contactRequest": req}}
|
||||
)
|
||||
|
||||
|
||||
def test_accept_uses_v7_contact_request_id():
|
||||
daemon = SimplexDaemon("ws://x", auto_accept=True)
|
||||
ws = FakeWS(daemon, [])
|
||||
daemon._ws = ws
|
||||
asyncio.run(daemon._consume(_contact_request_event({"contactRequestId": 7, "contactId_": 9})))
|
||||
assert [m["cmd"] for m in ws.sent] == ["/_accept 7"]
|
||||
|
||||
|
||||
def test_accept_falls_back_to_contact_id_for_legacy_events():
|
||||
daemon = SimplexDaemon("ws://x", auto_accept=True)
|
||||
ws = FakeWS(daemon, [])
|
||||
daemon._ws = ws
|
||||
asyncio.run(daemon._consume(_contact_request_event({"contactId": 4})))
|
||||
assert [m["cmd"] for m in ws.sent] == ["/_accept 4"]
|
||||
|
||||
|
||||
def test_accept_disabled_sends_nothing():
|
||||
daemon = SimplexDaemon("ws://x", auto_accept=False)
|
||||
ws = FakeWS(daemon, [])
|
||||
daemon._ws = ws
|
||||
asyncio.run(daemon._consume(_contact_request_event({"contactRequestId": 7})))
|
||||
assert ws.sent == []
|
||||
|
||||
|
||||
def test_new_chat_items_reach_the_handler():
|
||||
daemon = SimplexDaemon("ws://x")
|
||||
seen = []
|
||||
daemon._on_message = seen.append
|
||||
event = json.dumps(
|
||||
{"resp": {"type": "newChatItems", "chatItems": [direct_item(text="hi")]}}
|
||||
)
|
||||
asyncio.run(daemon._consume(event))
|
||||
assert [m["text"] for m in seen] == ["hi"]
|
||||
|
||||
|
||||
def test_correlated_response_resolves_pending_future():
|
||||
daemon = SimplexDaemon("ws://x")
|
||||
|
||||
async def scenario():
|
||||
daemon._loop = asyncio.get_running_loop()
|
||||
daemon._ws = FakeWS(daemon, [])
|
||||
future = daemon._loop.create_future()
|
||||
daemon._pending["req-9"] = future
|
||||
await daemon._consume(
|
||||
json.dumps({"corrId": "req-9", "resp": {"type": "ok", "value": 1}})
|
||||
)
|
||||
assert "req-9" not in daemon._pending, "a resolved request must be dropped"
|
||||
return future.result()
|
||||
|
||||
assert asyncio.run(scenario()) == {"type": "ok", "value": 1}
|
||||
|
||||
|
||||
def test_address_returns_existing_link():
|
||||
daemon = SimplexDaemon("ws://x", user_id=3)
|
||||
|
||||
async def scenario():
|
||||
daemon._loop = asyncio.get_running_loop()
|
||||
ws = FakeWS(
|
||||
daemon,
|
||||
[
|
||||
{
|
||||
"type": "userContactLink",
|
||||
"user": {"userId": 3},
|
||||
"contactLink": {
|
||||
"userContactLinkId": 1,
|
||||
"connLinkContact": {
|
||||
"connShortLink": "simplex:/a",
|
||||
"connFullLink": "https://a",
|
||||
},
|
||||
},
|
||||
}
|
||||
],
|
||||
)
|
||||
daemon._ws = ws
|
||||
return await daemon.address(timeout=5), ws
|
||||
|
||||
result, ws = asyncio.run(scenario())
|
||||
assert result == {"short_link": "simplex:/a", "full_link": "https://a", "created": False}
|
||||
assert [m["cmd"] for m in ws.sent] == ["/_show_address 3"]
|
||||
|
||||
|
||||
def test_address_creates_when_missing():
|
||||
daemon = SimplexDaemon("ws://x", user_id=1)
|
||||
|
||||
async def scenario():
|
||||
daemon._loop = asyncio.get_running_loop()
|
||||
ws = FakeWS(
|
||||
daemon,
|
||||
[
|
||||
{"type": "userContactLink", "contactLink": None},
|
||||
{
|
||||
"type": "userContactLinkCreated",
|
||||
"connLinkContact": {"connShortLink": "simplex:/new", "connFullLink": ""},
|
||||
},
|
||||
],
|
||||
)
|
||||
daemon._ws = ws
|
||||
return await daemon.address(timeout=5), ws
|
||||
|
||||
result, ws = asyncio.run(scenario())
|
||||
assert result == {"short_link": "simplex:/new", "full_link": "", "created": True}
|
||||
assert [m["cmd"] for m in ws.sent] == ["/_show_address 1", "/_address 1"]
|
||||
|
||||
|
||||
def test_request_address_without_connection_raises():
|
||||
daemon = SimplexDaemon("ws://x")
|
||||
with pytest.raises(RuntimeError):
|
||||
daemon.request_address(timeout=1)
|
||||
Reference in new issue
Block a user