simplex: mark the reported message read so next_message advances

The bridge only read the daemon's unread state (/_get chats, /_get chat);
nothing wrote the read state, so a persistent-unread message was re-reported
on every call and simplex.next_message never advanced.

v7.0.3 does expose /_read chat @<id> and /_read chat items @<id> <ids>
(the earlier "v7 has no mark-read command" note was wrong). Added:

- SimplexDaemon.mark_read / request_mark_read plus read_command /
  parse_read_response; parse_direct_text_item now carries item_id.
- SimpleX bridge POST /read {"contact","item_ids"} marks exactly the listed
  items read on the bridge's own daemon, reporting ok/error honestly.
- The live inbox entry keeps item_id so /inbox/next hands back the
  consumable id.
- simplex.next_message consumes exactly the item it reported (a failed
  consume is surfaced as an honest note, never a fabricated read failure).

Precise per-item reading leaves the rest of the chat unread.
This commit is contained in:
gabby committed 2026-10-09 11:16:21 +00:00
1 parent 4e3e3f767c
commit fc0beb5798
8 files changed
+429 -34

No files matched your search

+50 -5
View File
@@ -11,8 +11,9 @@ 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.)
still reported. After reporting a message, that single item is marked read on
the daemon through the bridge (`POST /read`), so the next call advances to the
next unread message instead of re-reporting the same one.
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
@@ -84,6 +85,41 @@ def _get(ctx, path):
raise BridgeError(f"GET {path}: {exc}") from exc
def _post(ctx, path, payload):
data = json.dumps(payload).encode("utf-8")
headers = {**_headers(ctx), "Content-Type": "application/json"}
request = urllib.request.Request(
_base(ctx) + path, data=data, headers=headers, method="POST"
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"POST {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"POST {path}: {exc}") from exc
def _mark_read(ctx, contact, item_id):
"""Mark one just-reported item read via the bridge.
Returns None on success, or a short honest reason string on failure. The
message was still reported, so a failed consume is surfaced as a note rather
than fabricated into a read failure.
"""
item = str(item_id or "").strip()
if not item:
return None
try:
payload = _post(ctx, "/read", {"contact": contact, "item_ids": [item]})
except BridgeError as exc:
return str(exc)
if not payload.get("ok"):
return payload.get("error") or "the bridge did not mark it read"
return None
# ---- conversation resolution ----
@@ -189,7 +225,13 @@ def _read_live(ctx, request, senders):
new_state="no unread SimpleX messages",
decisions=decisions,
)
return _report(message.get("display_name") or contact, message.get("text"), decisions)
read_note = _mark_read(ctx, contact, message.get("item_id"))
return _report(
message.get("display_name") or contact,
message.get("text"),
decisions,
read_note,
)
def _read_persistent(ctx, request):
@@ -250,9 +292,12 @@ def _read_persistent(ctx, request):
sender = next(
(s["display_name"] for s in senders if s["id"] == str(contact)), str(contact)
)
return _report(sender, messages[0].get("text"), decisions)
read_note = _mark_read(ctx, contact, messages[0].get("item_id"))
return _report(sender, messages[0].get("text"), decisions, read_note)
def _report(sender, body, decisions):
def _report(sender, body, decisions, read_note=None):
report = f"SimpleX message from {sender}: {str(body or '')}"
if read_note:
report += f" (could not mark it read: {read_note})"
return ActionResult(action_log=report, new_state=report, decisions=decisions)
+51 -1
View File
@@ -55,6 +55,8 @@ class BridgeHandler(BaseHTTPRequestHandler):
history = {}
requests = []
tokens = []
read_calls = []
read_ok = True
def _send(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
@@ -88,11 +90,31 @@ class BridgeHandler(BaseHTTPRequestHandler):
else:
self._send({"error": "not found"}, 404)
def do_POST(self):
url = urllib.parse.urlparse(self.path)
length = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(length).decode("utf-8") or "{}")
if url.path != "/read":
self._send({"error": "not found"}, 404)
return
self.read_calls.append(payload)
if self.read_ok:
self._send(
{
"ok": True,
"contact_id": payload.get("contact"),
"item_ids": payload.get("item_ids"),
"status": "read",
}
)
else:
self._send({"ok": False, "error": "the daemon rejected the read"})
def log_message(self, *args):
pass
def start_server(messages, unread_chats=None, history=None):
def start_server(messages, unread_chats=None, history=None, read_ok=True):
handler = type(
"Handler",
(BridgeHandler,),
@@ -102,6 +124,8 @@ def start_server(messages, unread_chats=None, history=None):
"history": dict(history or {}),
"requests": [],
"tokens": [],
"read_calls": [],
"read_ok": read_ok,
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
@@ -112,6 +136,7 @@ def start_server(messages, unread_chats=None, history=None):
def message(identifier, contact, name, text):
return {
"id": identifier,
"item_id": str(identifier),
"contact_id": contact,
"display_name": name,
"text": text,
@@ -148,6 +173,9 @@ def test_multiple_senders_uses_semif_decision():
assert handler.requests[0] == "/inbox", handler.requests
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
assert [m["id"] for m in handler.messages] == ["m1"], "the popped message must be consumed"
assert handler.read_calls == [{"contact": "7", "item_ids": ["m2"]}], (
"the reported item must be marked read, and only it"
)
print(action.action_log)
finally:
server.shutdown()
@@ -226,6 +254,7 @@ def test_single_sender_needs_no_decision():
action = skill.act(ctx, request)
assert engine.decisions == []
assert "hi" in action.action_log, action.action_log
assert handler.read_calls == [{"contact": "4", "item_ids": ["m1"]}]
print(action.action_log)
finally:
server.shutdown()
@@ -279,6 +308,7 @@ def test_empty_live_inbox_falls_back_to_persistent_unread():
assert handler.requests == ["/inbox", "/unread", "/history?contact=3&count=50"], (
handler.requests
)
assert handler.read_calls == [{"contact": "3", "item_ids": ["8"]}]
print(action.action_log)
finally:
server.shutdown()
@@ -322,6 +352,7 @@ def test_persistent_unread_prefers_a_healthy_conversation():
assert handler.requests == ["/inbox", "/unread", "/history?contact=4&count=50"], (
handler.requests
)
assert handler.read_calls == [{"contact": "4", "item_ids": ["20"]}]
print(action.action_log)
finally:
server.shutdown()
@@ -353,6 +384,24 @@ def test_auth_token_is_sent_when_configured():
server.server_close()
def test_failed_read_marking_is_surfaced_honestly():
"""A message is still reported when consuming it fails, with an honest note
instead of a fabricated failure of the read."""
server, handler, url = start_server(
[message("m1", "4", "Alice", "hi")], read_ok=False
)
try:
ctx = ActionContext(engine=FakeEngine(), config=config(url))
action = skill.act(ctx, Request("read my next simplex message"))
assert "hi" in action.action_log, action.action_log
assert "could not mark it read" in action.action_log, action.action_log
assert handler.read_calls == [{"contact": "4", "item_ids": ["m1"]}]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_multiple_senders_uses_semif_decision()
test_strong_winner_overrides_default_contact()
@@ -364,6 +413,7 @@ def main():
test_persistent_unread_prefers_a_healthy_conversation()
test_unreachable_bridge_fails_honestly()
test_auth_token_is_sent_when_configured()
test_failed_read_marking_is_surfaced_honestly()
print("ok")