simplex: honest forwarding — verify sends, disambiguate contacts, read persistent unread
The SimpleX forwarding path could report a failed send as success and could
route to the wrong peer:
- contact_entry dropped the daemon's unique localDisplayName, so two peers
sharing a profile name ("pepper" / "pepper_1") were indistinguishable; the
agent's SemIf choice then picked the stale one.
- The bridge's POST /send enqueued the message fire-and-forget and returned
ok:true; the daemon later marked it sndError (auth), yet the agent reported
"sent" and assessed success.
- next_message read only the live buffer, missing messages that arrived before
the bridge started.
Fixes:
- simplex_ws: contact_entry exposes local_name + connected/auth_errors;
parse_chat_item surfaces the agentError; parse_send_response normalizes a
/_send reply; add correlated send()/request_send().
- bridges/simplex: resolve disambiguates by id -> local_name/display_name and
prefers the healthiest peer; send() confirms the real terminal status
(sndSent/sndRcvd ok, sndError with reason) instead of a false ok; /unread
carries cached connection health; catalog documents the new fields/status.
- bridges/inbox: carry local_name/connected/auth_errors through the cache.
- seeds/simplex/next_message: fall back to /unread + /history and prefer the
healthy conversation.
- tests: updated shapes + new coverage for resolution and send verification.
This commit is contained in:
1 parent
0efbf218c5
commit
dff4849947
7 files changed
+639
-61
No files matched your search
@@ -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)
|
||||
@@ -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")
|
||||
|
||||
Reference in new issue
Block a user