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:
1 parent
4e3e3f767c
commit
fc0beb5798
8 files changed
+429
-34
No files matched your search
@@ -1316,22 +1316,25 @@ CLI, unit tests (24) + integration tests (2).
|
||||
localhost-bound, optional shared-secret `X-Semif-Token` header. `SimplexBridge`
|
||||
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
|
||||
read cursor, and serves `GET /health`, `GET /contacts` (the daemon's contact
|
||||
list, refreshed on (re)connect and on demand — best-effort, falling back to
|
||||
the cached/inbound-learned set when the daemon is unavailable), `GET /inbox`
|
||||
(peek), `GET /inbox/next?contact=<id>` (pop oldest), `GET /unread` (the
|
||||
daemon's persistent unread chats via `/_get chats` + `ChatListQuery` unread
|
||||
filter — `chatStats{unreadCount, minUnreadItemId}` plus each previewed
|
||||
`meta.itemStatus`; read-only), `GET /history?contact=<id>&count=<n>` (recent
|
||||
messages for one chat via `/_get chat @<id>`; read-only), `GET /address`
|
||||
(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). `/unread` and `/history` read the daemon's own state
|
||||
(surviving bridge restarts), unlike the live `/inbox` buffer; both are
|
||||
read-only because v7 has no mark-read command (acking is a client-side read
|
||||
receipt).
|
||||
read cursor (each buffered entry keeps the daemon `item_id` so a consumer can
|
||||
consume exactly that item), and serves `GET /health`, `GET /contacts` (the
|
||||
daemon's contact list, refreshed on (re)connect and on demand — best-effort,
|
||||
falling back to the cached/inbound-learned set when the daemon is unavailable),
|
||||
`GET /inbox` (peek), `GET /inbox/next?contact=<id>` (pop oldest), `GET /unread`
|
||||
(the daemon's persistent unread chats via `/_get chats` + `ChatListQuery`
|
||||
unread filter — `chatStats{unreadCount, minUnreadItemId}` plus each previewed
|
||||
`meta.itemStatus`), `GET /history?contact=<id>&count=<n>` (recent messages for
|
||||
one chat via `/_get chat @<id>`), `GET /address` (show/create the forwarding
|
||||
bot's contact link; 503 when the daemon is not connected, 502 when the lookup
|
||||
fails), `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), and `POST /read` `{"contact","item_ids"}`
|
||||
(marks exactly the listed received items read on the daemon via `/_read chat
|
||||
items @<id> <ids>`, so they leave its persistent unread state; `ok` only when
|
||||
the daemon accepted it). `/unread` and `/history` read the daemon's own state
|
||||
(surviving bridge restarts), unlike the live `/inbox` buffer; `/read` is a real
|
||||
local write on the bridge's own profile (v7 `/_read chat` updates the local
|
||||
`item_status` only; no wire read receipt).
|
||||
- **Skill-facing config.** A body calls a bridge at the address derived from that
|
||||
bridge's own `bridges.<name>` block (`host`/`port`/`token`) — the
|
||||
`simplex_bridge_url` / `llm_bridge_url` / `nextcloud_bridge_url` var (+ `_token`)
|
||||
@@ -1443,10 +1446,14 @@ covered. Deferred follow-ups:
|
||||
count)` / `request_chat_history()` query `/_get chat @<id> count=<n>` and
|
||||
parse `apiChat`. `SimplexBridge` exposes `GET /unread` (persistent unread
|
||||
chats, summaries + previewed messages) and `GET /history?contact=<id>&count=<n>`
|
||||
(recent messages with per-item status), both read-only and degrading like
|
||||
`/address` (503 not connected / 502 lookup failure; `/history` 400 without a
|
||||
contact). The live `/inbox` buffer is unchanged. Note: v7 has **no mark-read
|
||||
command**, so acking is via read receipts, not an API call.
|
||||
(recent messages with per-item status), degrading like `/address` (503 not
|
||||
connected / 502 lookup failure; `/history` 400 without a contact), plus
|
||||
`POST /read` `{"contact","item_ids"}` which marks exactly the listed items read
|
||||
on the daemon (`/_read chat items @<id> <ids>`), so a reported message is
|
||||
consumed and not re-reported. The live `/inbox` buffer is unchanged. (The
|
||||
pinned v7.0.3 **does** have `/_read chat @<id>`, `/_read chat items @<id>
|
||||
<ids>`, and `/_read user <uid>`; an earlier note claiming v7 had no mark-read
|
||||
command was wrong.)
|
||||
- [x] **3. `simplex.send_message` seed** (`seeds/simplex/send_message/`). The
|
||||
outbound counterpart to `simplex.next_message`: resolves the recipient with a
|
||||
SemIf sub-decision over the bridge's `/contacts` (falling back to the
|
||||
|
||||
@@ -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)
|
||||
@@ -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")
|
||||
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
+91
-2
@@ -38,6 +38,8 @@ class FakeDaemon:
|
||||
history_error=None,
|
||||
send_response=None,
|
||||
send_error=None,
|
||||
read_response=None,
|
||||
read_error=None,
|
||||
):
|
||||
self.link = link
|
||||
self.error = error
|
||||
@@ -49,9 +51,12 @@ class FakeDaemon:
|
||||
self.history_error = history_error
|
||||
self.send_response = send_response
|
||||
self.send_error = send_error
|
||||
self.read_response = read_response
|
||||
self.read_error = read_error
|
||||
self.refresh_count = 0
|
||||
self.chat_calls = []
|
||||
self.history_calls = []
|
||||
self.read_calls = []
|
||||
self.sent = []
|
||||
self.closed = False
|
||||
self.on_message = None
|
||||
@@ -105,6 +110,14 @@ class FakeDaemon:
|
||||
raise self.history_error
|
||||
return list(self.history_list)
|
||||
|
||||
def request_mark_read(self, chat_id, item_ids=None, timeout=20.0):
|
||||
self.read_calls.append((str(chat_id), list(item_ids or [])))
|
||||
if self.read_error is not None:
|
||||
raise self.read_error
|
||||
if self.read_response is not None:
|
||||
return self.read_response
|
||||
return {"ok": True, "type": "itemsReadForChat", "error": ""}
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
@@ -116,8 +129,13 @@ def start_bridge(daemon=None, **config):
|
||||
return bridge, daemon, f"http://127.0.0.1:{port}"
|
||||
|
||||
|
||||
def inbound(text, contact_id="4", display_name="Alice"):
|
||||
return {"text": text, "contact_id": contact_id, "display_name": display_name}
|
||||
def inbound(text, contact_id="4", display_name="Alice", item_id=""):
|
||||
return {
|
||||
"text": text,
|
||||
"contact_id": contact_id,
|
||||
"display_name": display_name,
|
||||
"item_id": item_id,
|
||||
}
|
||||
|
||||
|
||||
def get(url, token=None):
|
||||
@@ -722,3 +740,74 @@ def test_describe_bridges_renders_service_auth_and_endpoints():
|
||||
assert "/unread" in text
|
||||
assert "/history" in text
|
||||
assert "never speak" in text
|
||||
|
||||
|
||||
def test_read_marks_given_items_only():
|
||||
daemon = FakeDaemon()
|
||||
bridge, _, base = start_bridge(daemon=daemon)
|
||||
try:
|
||||
result = post(f"{base}/read", {"contact": "4", "item_ids": ["8", "9"]})
|
||||
assert result == {
|
||||
"ok": True,
|
||||
"contact_id": "4",
|
||||
"item_ids": ["8", "9"],
|
||||
"status": "read",
|
||||
}
|
||||
assert daemon.read_calls == [("4", ["8", "9"])], "only the listed items"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_read_validates_body():
|
||||
bridge, daemon, base = start_bridge()
|
||||
try:
|
||||
payloads = (
|
||||
{"item_ids": ["8"]},
|
||||
{"contact": "4"},
|
||||
{"contact": "4", "item_ids": []},
|
||||
{"contact": " ", "item_ids": ["8"]},
|
||||
)
|
||||
for payload in payloads:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
post(f"{base}/read", payload)
|
||||
assert exc.value.code == 400
|
||||
assert daemon.read_calls == []
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_read_without_connection_is_unavailable():
|
||||
bridge, _, base = start_bridge(
|
||||
daemon=FakeDaemon(read_error=RuntimeError("not connected"))
|
||||
)
|
||||
try:
|
||||
result = post(f"{base}/read", {"contact": "4", "item_ids": ["8"]})
|
||||
assert result["ok"] is False
|
||||
assert result["status"] == "unavailable"
|
||||
assert "not connected" in result["error"]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_read_reports_a_rejected_read():
|
||||
bridge, _, base = start_bridge(
|
||||
daemon=FakeDaemon(read_response={"ok": False, "error": "agent error"})
|
||||
)
|
||||
try:
|
||||
result = post(f"{base}/read", {"contact": "4", "item_ids": ["8"]})
|
||||
assert result["ok"] is False
|
||||
assert result["status"] == "rejected"
|
||||
assert result["error"] == "agent error"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_inbox_carries_item_id_for_consumption():
|
||||
bridge, _, base = start_bridge()
|
||||
try:
|
||||
bridge._on_message(inbound("hi", contact_id="4", item_id="33"))
|
||||
popped = get(f"{base}/inbox/next")["message"]
|
||||
assert popped["item_id"] == "33"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
@@ -19,13 +19,15 @@ from semif_agent.simplex_ws import (
|
||||
parse_chat,
|
||||
parse_chat_item,
|
||||
parse_direct_text_item,
|
||||
parse_read_response,
|
||||
read_command,
|
||||
send_text_command,
|
||||
)
|
||||
|
||||
|
||||
# ---- parsing ----
|
||||
|
||||
def direct_item(text="hello", contact_id="4", display="alice", direction="directRcv", kind="text"):
|
||||
def direct_item(text="hello", contact_id="4", display="alice", direction="directRcv", kind="text", item_id=7):
|
||||
# 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`.
|
||||
@@ -41,6 +43,7 @@ def direct_item(text="hello", contact_id="4", display="alice", direction="direct
|
||||
},
|
||||
},
|
||||
"chatItem": {
|
||||
"meta": {"itemId": item_id},
|
||||
"chatDir": {"type": direction},
|
||||
"content": {
|
||||
"type": "rcvMsgContent",
|
||||
@@ -56,6 +59,7 @@ def test_parse_direct_text():
|
||||
assert message["text"] == "hello"
|
||||
assert message["contact_id"] == "4"
|
||||
assert message["display_name"] == "alice"
|
||||
assert message["item_id"] == "7"
|
||||
|
||||
|
||||
def test_parse_filters_echo_group_and_non_text():
|
||||
@@ -658,3 +662,61 @@ def test_request_chat_history_without_connection_raises():
|
||||
daemon = SimplexDaemon("ws://x")
|
||||
with pytest.raises(RuntimeError):
|
||||
daemon.request_chat_history("4", timeout=1)
|
||||
|
||||
|
||||
# ---- daemon: read marking ----
|
||||
|
||||
def test_read_command_targets_specific_items():
|
||||
assert read_command("7", ["8", "9"]) == "/_read chat items @7 8,9"
|
||||
|
||||
|
||||
def test_read_command_without_items_reads_the_whole_chat():
|
||||
assert read_command("@7") == "/_read chat @7"
|
||||
|
||||
|
||||
def test_read_command_ignores_blank_item_ids():
|
||||
assert read_command("7", [" ", ""]) == "/_read chat @7"
|
||||
|
||||
|
||||
def test_parse_read_response_ok_and_error():
|
||||
assert parse_read_response({"type": "itemsReadForChat"})["ok"] is True
|
||||
rejected = parse_read_response(
|
||||
{"type": "chatCmdError", "chatError": {"type": "error"}}
|
||||
)
|
||||
assert rejected["ok"] is False
|
||||
assert rejected["error"]
|
||||
assert parse_read_response({})["ok"] is False
|
||||
|
||||
|
||||
def test_mark_read_sends_item_command_and_parses_ok():
|
||||
daemon = SimplexDaemon("ws://x")
|
||||
|
||||
async def scenario():
|
||||
daemon._loop = asyncio.get_running_loop()
|
||||
ws = FakeWS(daemon, [{"type": "itemsReadForChat"}])
|
||||
daemon._ws = ws
|
||||
return await daemon.mark_read("7", ["11", "12"], timeout=5), ws
|
||||
|
||||
result, ws = asyncio.run(scenario())
|
||||
assert result["ok"] is True
|
||||
assert [m["cmd"] for m in ws.sent] == ["/_read chat items @7 11,12"]
|
||||
|
||||
|
||||
def test_mark_read_reports_a_rejected_command():
|
||||
daemon = SimplexDaemon("ws://x")
|
||||
|
||||
async def scenario():
|
||||
daemon._loop = asyncio.get_running_loop()
|
||||
ws = FakeWS(
|
||||
daemon, [{"type": "chatCmdError", "chatError": {"type": "error"}}]
|
||||
)
|
||||
daemon._ws = ws
|
||||
return await daemon.mark_read("7", ["11"], timeout=5)
|
||||
|
||||
assert asyncio.run(scenario())["ok"] is False
|
||||
|
||||
|
||||
def test_request_mark_read_without_connection_raises():
|
||||
daemon = SimplexDaemon("ws://x")
|
||||
with pytest.raises(RuntimeError):
|
||||
daemon.request_mark_read("7", ["1"], timeout=1)
|
||||
Reference in new issue
Block a user