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

+4 -1
View File
@@ -2,7 +2,7 @@
The bridge owns the read cursor so a read skill stays stateless. Generic over
transports: entries are normalized message dicts (`contact_id`, `display_name`,
`text`), which is exactly what `semif_agent.simplex_ws` yields.
`text`, `item_id`), which is exactly what `semif_agent.simplex_ws` yields.
"""
from __future__ import annotations
@@ -28,6 +28,9 @@ class MessagingInbox:
"contact_id": contact_id,
"display_name": display_name,
"text": message.get("text") or "",
# The transport's per-item id (SimpleX `itemId`), when known: lets a
# consumer mark exactly this message read on the daemon.
"item_id": str(message.get("item_id") or ""),
"received_at": time.time(),
}
with self._lock:
+66
View File
@@ -80,6 +80,13 @@ class SimplexBridge(BridgeService):
"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",
"POST /read {\"contact\": \"<id>\", \"item_ids\": [\"<id>\", ...]} -> "
"200 {\"ok\": bool, \"contact_id\": \"<id>\", \"item_ids\": [...], "
"\"status\": \"read|rejected|error|unavailable\", \"error\": "
"\"...\"?} — mark the given received items read on the daemon so they "
"leave its persistent unread state; only the listed ids are consumed. "
"`ok` is true only when the daemon accepted it — never a fabricated "
"success. 400 on a missing contact or empty item_ids",
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
"configured and the auth header is missing or wrong",
),
@@ -181,6 +188,8 @@ class SimplexBridge(BridgeService):
return 404, {"error": "not found"}
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
if path == "/read":
return self._read(payload)
if path != "/send":
return 404, {"error": "not found"}
recipient = payload.get("recipient")
@@ -197,6 +206,63 @@ class SimplexBridge(BridgeService):
# ---- actions ----
def _read(self, payload: dict) -> tuple[int, dict]:
contact = payload.get("contact")
item_ids = payload.get("item_ids")
if not isinstance(contact, str) or not contact.strip():
return 400, {"error": "contact is required"}
if not isinstance(item_ids, list) or not item_ids:
return 400, {"error": "item_ids is required"}
try:
result = self.mark_read(contact, item_ids)
except ValueError as exc:
return 400, {"error": str(exc)}
return 200, result
def mark_read(self, contact: str, item_ids) -> dict:
"""Mark the given received items read on the bridge's own daemon.
Returns `{ok, contact_id, item_ids, status, error?}`. `ok` is True only
when the daemon accepted the command; a disconnected or failing daemon
reports the reason (never a false success). Reading is precise: only the
listed item ids are consumed, so the rest of the chat stays unread.
"""
contact_id = str(contact or "").strip()
ids = [str(i).strip() for i in (item_ids or []) if str(i).strip()]
if not contact_id:
raise ValueError("contact is required")
if not ids:
raise ValueError("item_ids is required")
try:
response = self.daemon.request_mark_read(contact_id, ids)
except RuntimeError as exc:
return {
"ok": False,
"contact_id": contact_id,
"item_ids": ids,
"status": "unavailable",
"error": str(exc)[:300],
}
except Exception as exc: # TimeoutError, daemon error
return {
"ok": False,
"contact_id": contact_id,
"item_ids": ids,
"status": "error",
"error": str(exc)[:300],
}
ok = bool(response.get("ok")) if isinstance(response, dict) else False
result = {
"ok": ok,
"contact_id": contact_id,
"item_ids": ids,
"status": "read" if ok else "rejected",
}
if not ok:
detail = response.get("error") if isinstance(response, dict) else ""
result["error"] = detail or "the daemon did not mark the items read"
return result
def refresh_contacts(self) -> list[dict]:
"""Best-effort refresh of the daemon's contact list into the inbox.
+77 -4
View File
@@ -186,10 +186,10 @@ def parse_chat(achat: dict) -> dict | None:
def parse_direct_text_item(item: dict) -> InboundDict | None:
"""Normalize one `newChatItems` entry into a message dict, or None.
Returns `{text, contact_id, display_name, raw}` for a received direct text
message. Drops group chats, own echoes, non-text content, and items with no
resolvable contact id. Authorization is the caller's job — this layer is
deliberately policy-free.
Returns `{text, contact_id, display_name, item_id, raw}` for a received
direct text message. Drops group chats, own echoes, non-text content, and
items with no resolvable contact id. Authorization is the caller's job —
this layer is deliberately policy-free.
"""
chat_info = item.get("chatInfo") or {}
if chat_info.get("type") != "direct":
@@ -221,11 +221,15 @@ def parse_direct_text_item(item: dict) -> InboundDict | None:
entry = contact_entry(contact)
if entry is None:
return None
item_id = (chat_item.get("meta") or {}).get("itemId")
return {
"text": text,
"contact_id": entry["id"],
"display_name": entry["display_name"],
"local_name": entry.get("local_name", ""),
# Carried so a consumer can mark exactly this item read (the bridge's
# live inbox keeps it; the command gateway ignores it).
"item_id": str(item_id) if item_id is not None else "",
"raw": item,
}
@@ -281,6 +285,39 @@ def parse_send_response(resp: dict) -> dict:
return {"item_id": None, "status": "", "error": "daemon returned no message id"}
def read_command(chat_id: str, item_ids=None) -> str:
"""Structured command that marks a chat, or specific items, read.
v7 exposes `/_read chat @<id>` (the whole chat) and `/_read chat items @<id>
<comma-separated item ids>` (a precise subset). The item form is used so
consuming the next unread message clears exactly that message and leaves the
rest of the chat untouched. With no usable item ids it falls back to the
whole-chat form.
"""
chat_ref = f"@{str(chat_id).strip().lstrip('@')}"
if item_ids:
ids = ",".join(str(i).strip() for i in item_ids if str(i).strip())
if ids:
return f"/_read chat items {chat_ref} {ids}"
return f"/_read chat {chat_ref}"
def parse_read_response(resp: dict) -> dict:
"""Normalize a `/_read chat` response into `{ok, type, error}`.
A successful item read comes back as `itemsReadForChat` and a whole-chat
read as the chat's `ok`; a rejected command comes back as `chatCmdError`.
`ok` is True only when the daemon did not report an error, so a caller never
treats a rejected (or empty) response as a consumed message.
"""
if not isinstance(resp, dict) or not resp:
return {"ok": False, "type": "", "error": "empty daemon response"}
if resp.get("type") == "chatCmdError" or resp.get("error"):
detail = resp.get("chatError") or resp.get("error") or "read command failed"
return {"ok": False, "type": "chatCmdError", "error": str(detail)[:300]}
return {"ok": True, "type": resp.get("type") or "", "error": ""}
class SimplexDaemon:
"""One WebSocket connection to a `simplex-chat` daemon.
@@ -518,6 +555,42 @@ class SimplexDaemon:
future.cancel()
raise TimeoutError("simplex send request timed out") from exc
# ---- read ----
async def mark_read(
self, chat_id: str, item_ids=None, timeout: float = 20.0
) -> dict:
"""Mark a direct chat, or specific items, read on the daemon.
`/_read chat items @<id> <ids>` clears exactly the reported items'
`rcv_new` status (leaving other unread messages intact);
`/_read chat @<id>` clears the whole chat. Returns `{ok, type, error}`.
A transport failure raises (via `_roundtrip`) — never a fabricated
success.
"""
resp = await self._roundtrip(read_command(chat_id, item_ids), timeout)
return parse_read_response(resp)
def request_mark_read(
self, chat_id: str, item_ids=None, timeout: float = 20.0
) -> dict:
"""Thread-safe read-mark 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.mark_read(chat_id, item_ids, timeout=timeout), loop
)
try:
return future.result(timeout=timeout + 5.0)
except concurrent.futures.TimeoutError as exc:
future.cancel()
raise TimeoutError("simplex read request timed out") from exc
# ---- contacts ----
async def active_user(self, timeout: float = 20.0) -> int: