bridges: daemon-backed message history + true unread
The in-memory inbox is a receive buffer, not the daemon's read state, so
the bridge could not see messages that arrived while it was down. Query
/_get chats <userId> count=<n> with a ChatListQuery unread filter
(chatStats{unreadCount, minUnreadItemId} + chatItem.meta.itemStatus
rcvNew/rcvRead) and /_get chat @<id> count=<n> over the existing
corrId->Future path, and expose GET /unread and GET /history?contact=<id>.
Both are read-only (v7 has no mark-read command) and degrade like
/address: 503 not connected, 502 lookup failure, 400 without a contact.
The live /inbox buffer is unchanged.
This commit is contained in:
1 parent
4a4fe850e0
commit
e93db6ec09
6 files changed
+564
-17
No files matched your search
@@ -165,14 +165,16 @@ bridges/ standalone third-party API bridges (SimpleX first). base.py:
|
|||||||
owns its OWN simplex-chat daemon/profile (separate from the
|
owns its OWN simplex-chat daemon/profile (separate from the
|
||||||
gateway's), buffers every inbound DM, refreshes the daemon
|
gateway's), buffers every inbound DM, refreshes the daemon
|
||||||
contact list on (re)connect + on demand, serves invite-link/
|
contact list on (re)connect + on demand, serves invite-link/
|
||||||
read/send. registry.py: CATALOG, describe_bridges() (catalog injected
|
read/send plus daemon-backed unread + per-chat history.
|
||||||
|
registry.py: CATALOG, describe_bridges() (catalog injected
|
||||||
into the codegen prompts), run_bridges(). Run with `python -m
|
into the codegen prompts), run_bridges(). Run with `python -m
|
||||||
semif_agent.cli bridge [--name NAME]`; config under `bridges`.
|
semif_agent.cli bridge [--name NAME]`; config under `bridges`.
|
||||||
simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway
|
simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway
|
||||||
adapter and the bridge (parse direct text across v7 shapes,
|
adapter and the bridge (parse direct text across v7 shapes,
|
||||||
structured `/_send`, corrId→Future round-trips, contact-address
|
structured `/_send`, corrId→Future round-trips, contact-address
|
||||||
`/_show_address`/`/_address`, contact-request accept). Knows
|
`/_show_address`/`/_address`, contact-request accept, contact
|
||||||
nothing about the scheduler or either front end.
|
list + chat previews/history). Knows nothing about the
|
||||||
|
scheduler or either front end.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Run / verify
|
## Run / verify
|
||||||
@@ -838,12 +840,19 @@ CLI, unit tests (24) + box integration tests (2).
|
|||||||
read cursor, and serves `GET /health`, `GET /contacts` (the daemon's contact
|
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
|
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`
|
the cached/inbound-learned set when the daemon is unavailable), `GET /inbox`
|
||||||
(peek), `GET /inbox/next?contact=<id>` (pop oldest), `GET /address`
|
(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
|
(show/create the forwarding bot's contact link; 503 when the daemon is not
|
||||||
connected, 502 when the lookup fails), and `POST /send`
|
connected, 502 when the lookup fails), and `POST /send`
|
||||||
`{"recipient","text"}` (resolves a numeric id or a known display name —
|
`{"recipient","text"}` (resolves a numeric id or a known display name —
|
||||||
refreshing the daemon contact list once on a miss — and enqueues on the
|
refreshing the daemon contact list once on a miss — and enqueues on the
|
||||||
bridge's own daemon).
|
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).
|
||||||
- **Skill-facing config.** The top-level `simplex_bridge_url` is the address a
|
- **Skill-facing config.** The top-level `simplex_bridge_url` is the address a
|
||||||
body calls (the data-contract config search auto-populates it); bootstrap keeps
|
body calls (the data-contract config search auto-populates it); bootstrap keeps
|
||||||
it in sync with the bridge port. Skills reach a bridge with the ordinary `http`
|
it in sync with the bridge port. Skills reach a bridge with the ordinary `http`
|
||||||
@@ -864,13 +873,19 @@ The bridge read path (`simplex.next_message`) and contact-link lookup
|
|||||||
/contacts`, and a send-resolution miss), so `/send` can address a contact it
|
/contacts`, and a send-resolution miss), so `/send` can address a contact it
|
||||||
has never received from. Best-effort: a disconnected daemon keeps the cached
|
has never received from. Best-effort: a disconnected daemon keeps the cached
|
||||||
set.
|
set.
|
||||||
- [ ] **2. Message history + true unread** (`bridges/simplex.py`). The in-memory
|
- [x] **2. Message history + true unread** (`bridges/simplex.py`,
|
||||||
inbox is a receive buffer, not the daemon's read state. Use `/_get chats
|
`simplex_ws.py`). Shipped: `SimplexDaemon.chats(unread_only, count)` /
|
||||||
<userId> count=<n> <json(PaginationByTime)>` with a `ChatListQuery` unread
|
`request_chats()` query `/_get chats <userId> count=<n>
|
||||||
filter and `AChat.chatStats{unreadCount, minUnreadItemId}` +
|
{"type":"filters","favorite":false,"unread":true}` and parse
|
||||||
`chatItem.meta.itemStatus` (`rcvNew`/`rcvRead`) to expose real unread history.
|
`apiChats` (`AChat.chatStats{unreadCount, minUnreadItemId, unreadChat}` +
|
||||||
Note: v7 has **no mark-read command**, so acking is via read receipts, not an
|
`chatItem.meta.itemStatus` `rcvNew`/`rcvRead`); `chat_history(contact_id,
|
||||||
API call.
|
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.
|
||||||
- [ ] **3. `simplex.send_message` seed** (`seeds/simplex/send_message/`). The
|
- [ ] **3. `simplex.send_message` seed** (`seeds/simplex/send_message/`). The
|
||||||
outbound counterpart to `simplex.next_message`: resolve the recipient with a
|
outbound counterpart to `simplex.next_message`: resolve the recipient with a
|
||||||
SemIf sub-decision over `/contacts`, send only on explicit user intent, and
|
SemIf sub-decision over `/contacts`, send only on explicit user intent, and
|
||||||
|
|||||||
@@ -503,10 +503,17 @@ GET /health
|
|||||||
GET /contacts
|
GET /contacts
|
||||||
GET /inbox # peek buffered inbound DMs
|
GET /inbox # peek buffered inbound DMs
|
||||||
GET /inbox/next?contact=<id> # pop oldest unread
|
GET /inbox/next?contact=<id> # pop oldest unread
|
||||||
|
GET /unread # daemon's persistent unread chats (read-only; 503/502)
|
||||||
|
GET /history?contact=<id>&count=<n> # recent messages for one chat (read-only; 503/502)
|
||||||
GET /address # show/create the contact link (503 not connected, 502 failure)
|
GET /address # show/create the contact link (503 not connected, 502 failure)
|
||||||
POST /send {"recipient": "<id|display_name>", "text": "..."}
|
POST /send {"recipient": "<id|display_name>", "text": "..."}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`/unread` and `/history` read the daemon's own state (`/_get chats` / `/_get chat`),
|
||||||
|
so they see messages that arrived while the bridge was down — unlike the live
|
||||||
|
`/inbox` receive buffer. Both are read-only: v7 has no mark-read command, so
|
||||||
|
acking is a client-side read receipt, not an API call.
|
||||||
|
|
||||||
`simplex_bridge_url` (top-level config) is what skills call; the bridge catalog
|
`simplex_bridge_url` (top-level config) is what skills call; the bridge catalog
|
||||||
is injected into every codegen prompt via `describe_bridges()`, so it is the
|
is injected into every codegen prompt via `describe_bridges()`, so it is the
|
||||||
single source of bridge specifics. Adding a bridge = a class + a config block +
|
single source of bridge specifics. Adding a bridge = a class + a config block +
|
||||||
@@ -589,11 +596,11 @@ logging, `dream` cost pass, REPL + JSONL CLI; live `create_category` /
|
|||||||
contract → test → auto-run → re-dispatch); tiered config + first-fire
|
contract → test → auto-run → re-dispatch); tiered config + first-fire
|
||||||
collection; runtime repair loop; the closed `response` canned tree; real
|
collection; runtime repair loop; the closed `response` canned tree; real
|
||||||
integrations with `INTEGRATION` declarations; the SimpleX command gateway and the
|
integrations with `INTEGRATION` declarations; the SimpleX command gateway and the
|
||||||
standalone SimpleX bridge + seeds.
|
standalone SimpleX bridge + seeds (contact-list refresh, daemon-backed message
|
||||||
|
history / true unread).
|
||||||
|
|
||||||
**Next.** Real fine-tuning from grounded decision rows ("dreaming") with
|
**Next.** Real fine-tuning from grounded decision rows ("dreaming") with
|
||||||
validation + pinned-revision swap; queue persistence; more intake sources
|
validation + pinned-revision swap; queue persistence; more intake sources
|
||||||
(events/timers); dashboard run-requeue cross-linking; per-decision thresholds and
|
(events/timers); dashboard run-requeue cross-linking; per-decision thresholds and
|
||||||
calibration; more bridges; a richer SimpleX read path (message history / true
|
calibration; more bridges; a `simplex.send_message` seed. See `AGENTS.md` for the
|
||||||
unread, contact-list refresh, a `simplex.send_message` seed). See `AGENTS.md` for
|
detailed backlog and known gotchas.
|
||||||
the detailed backlog and known gotchas.
|
|
||||||
@@ -43,6 +43,17 @@ class SimplexBridge(BridgeService):
|
|||||||
"GET /inbox/next?contact=<id> -> 200 {\"message\": {...}|null} — pop "
|
"GET /inbox/next?contact=<id> -> 200 {\"message\": {...}|null} — pop "
|
||||||
"the oldest unread message (optionally from one contact); null means "
|
"the oldest unread message (optionally from one contact); null means "
|
||||||
"none buffered. The bridge owns the read cursor",
|
"none buffered. The bridge owns the read cursor",
|
||||||
|
"GET /unread -> 200 {\"chats\": [{\"contact_id\", \"display_name\", "
|
||||||
|
"\"unread_count\", \"min_unread_item_id\", \"unread\", \"messages\": "
|
||||||
|
"[{item_id, text, status, unread, direction, sent_at}]}]} — the "
|
||||||
|
"daemon's persistent unread chats (survives bridge restarts), not "
|
||||||
|
"just what arrived while connected. Read-only; 503 when the daemon "
|
||||||
|
"is not connected, 502 when the lookup fails",
|
||||||
|
"GET /history?contact=<id>&count=<n> -> 200 {\"contact_id\", "
|
||||||
|
"\"messages\": [{item_id, text, status, unread, direction, "
|
||||||
|
"sent_at}]} — recent message history for one contact (count default "
|
||||||
|
"20); status is rcvNew (unread) or rcvRead. Read-only; 503/502 as "
|
||||||
|
"/unread, 400 without a contact",
|
||||||
"GET /address -> 200 {\"short_link\", \"full_link\", \"created\"} — "
|
"GET /address -> 200 {\"short_link\", \"full_link\", \"created\"} — "
|
||||||
"the agent's contact link; creates it on first call. 503 when the "
|
"the agent's contact link; creates it on first call. 503 when the "
|
||||||
"daemon is not connected, 502 when the lookup fails",
|
"daemon is not connected, 502 when the lookup fails",
|
||||||
@@ -139,6 +150,12 @@ class SimplexBridge(BridgeService):
|
|||||||
if path == "/inbox/next":
|
if path == "/inbox/next":
|
||||||
contact = (query.get("contact") or [None])[0]
|
contact = (query.get("contact") or [None])[0]
|
||||||
return 200, {"message": self.inbox.pop(contact)}
|
return 200, {"message": self.inbox.pop(contact)}
|
||||||
|
if path == "/unread":
|
||||||
|
return self._unread(query)
|
||||||
|
if path == "/history":
|
||||||
|
contact = (query.get("contact") or [None])[0]
|
||||||
|
count = (query.get("count") or [None])[0]
|
||||||
|
return self._history(contact, count)
|
||||||
if path == "/address":
|
if path == "/address":
|
||||||
return self._address()
|
return self._address()
|
||||||
return 404, {"error": "not found"}
|
return 404, {"error": "not found"}
|
||||||
@@ -176,6 +193,49 @@ class SimplexBridge(BridgeService):
|
|||||||
self._event("contacts_refreshed", count=len(contacts))
|
self._event("contacts_refreshed", count=len(contacts))
|
||||||
return self.inbox.contacts()
|
return self.inbox.contacts()
|
||||||
|
|
||||||
|
def _unread(self, query: dict) -> tuple[int, dict]:
|
||||||
|
"""The daemon's persistent unread chats (not the live receive buffer).
|
||||||
|
|
||||||
|
Read-only: there is no mark-read command in v7, so this never consumes.
|
||||||
|
Best-effort like `/address` — 503 when the daemon is not connected, 502
|
||||||
|
when the lookup fails, never a fabricated chat.
|
||||||
|
"""
|
||||||
|
count = self._count((query.get("count") or [None])[0])
|
||||||
|
try:
|
||||||
|
chats = self.daemon.request_chats(unread_only=True, count=count)
|
||||||
|
except RuntimeError as exc:
|
||||||
|
return 503, {"error": f"unread lookup is not available: {exc}"[:300]}
|
||||||
|
except Exception as exc: # TimeoutError, daemon error
|
||||||
|
return 502, {"error": f"unread lookup failed: {exc}"[:300]}
|
||||||
|
return 200, {"chats": chats}
|
||||||
|
|
||||||
|
def _history(self, contact: str | None, count: str | None) -> tuple[int, dict]:
|
||||||
|
"""Recent message history for one contact, straight from the daemon.
|
||||||
|
|
||||||
|
Read-only. A missing contact is a client error; a disconnected or
|
||||||
|
failing daemon degrades like `/unread`.
|
||||||
|
"""
|
||||||
|
contact = str(contact or "").strip()
|
||||||
|
if not contact:
|
||||||
|
return 400, {"error": "contact is required"}
|
||||||
|
try:
|
||||||
|
messages = self.daemon.request_chat_history(
|
||||||
|
contact, count=self._count(count)
|
||||||
|
)
|
||||||
|
except RuntimeError as exc:
|
||||||
|
return 503, {"error": f"history lookup is not available: {exc}"[:300]}
|
||||||
|
except Exception as exc: # TimeoutError, daemon error
|
||||||
|
return 502, {"error": f"history lookup failed: {exc}"[:300]}
|
||||||
|
return 200, {"contact_id": contact, "messages": messages}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _count(raw: str | None, default: int = 20, maximum: int = 100) -> int:
|
||||||
|
try:
|
||||||
|
value = int(raw) if raw is not None else default
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
value = default
|
||||||
|
return max(1, min(value, maximum))
|
||||||
|
|
||||||
def _address(self) -> tuple[int, dict]:
|
def _address(self) -> tuple[int, dict]:
|
||||||
try:
|
try:
|
||||||
link = self.daemon.request_address()
|
link = self.daemon.request_address()
|
||||||
|
|||||||
@@ -76,6 +76,86 @@ def contact_link(resp: dict) -> dict:
|
|||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _text_from_content(content: dict) -> str | None:
|
||||||
|
"""Extract the text of a text message from a `CIContent` union, or None.
|
||||||
|
|
||||||
|
Handles the same two shapes as `parse_direct_text_item`: the API form
|
||||||
|
(`{"type": "rcvMsgContent", "msgContent": {...}}`) and the DB/Aeson form
|
||||||
|
(`{"rcvMsgContent": {"msgContent": {...}}}`), for both received and sent
|
||||||
|
messages. Non-text content (files, calls, events) yields None.
|
||||||
|
"""
|
||||||
|
for key in ("rcvMsgContent", "sndMsgContent"):
|
||||||
|
if content.get("type") == key:
|
||||||
|
msg_content = content.get("msgContent") or {}
|
||||||
|
elif isinstance(content.get(key), dict):
|
||||||
|
msg_content = content[key].get("msgContent") or {}
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
if msg_content.get("type") == "text":
|
||||||
|
return str(msg_content.get("text", "")).strip()
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_chat_item(item: dict) -> dict | None:
|
||||||
|
"""Normalize one `ChatItem` into a history entry, or None.
|
||||||
|
|
||||||
|
Returns `{item_id, text, status, unread, direction, sent_at}`. `status` is
|
||||||
|
the raw `meta.itemStatus.type` (`rcvNew` / `rcvRead` / `snd*`), and `unread`
|
||||||
|
is True only for an unread received message. Items without an id are
|
||||||
|
dropped rather than fabricated.
|
||||||
|
"""
|
||||||
|
meta = item.get("meta") or {}
|
||||||
|
item_id = meta.get("itemId")
|
||||||
|
if item_id is None:
|
||||||
|
return None
|
||||||
|
text = _text_from_content(item.get("content") or {})
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
status = (meta.get("itemStatus") or {}).get("type") or ""
|
||||||
|
return {
|
||||||
|
"item_id": str(item_id),
|
||||||
|
"text": text,
|
||||||
|
"status": status,
|
||||||
|
"unread": status == "rcvNew",
|
||||||
|
"direction": (item.get("chatDir") or {}).get("type") or "",
|
||||||
|
"sent_at": meta.get("itemTs") or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_chat(achat: dict) -> dict | None:
|
||||||
|
"""Normalize one `AChat` into a chat summary, or None for a non-direct chat.
|
||||||
|
|
||||||
|
Returns `{contact_id, display_name, unread_count, min_unread_item_id,
|
||||||
|
unread, messages}` from `chatInfo` + `chatStats` + `chatItems`. A group or
|
||||||
|
local chat (no direct contact) yields None.
|
||||||
|
"""
|
||||||
|
info = achat.get("chatInfo") or {}
|
||||||
|
if info.get("type") != "direct":
|
||||||
|
return None
|
||||||
|
entry = contact_entry(info.get("contact") or {})
|
||||||
|
if entry is None:
|
||||||
|
return None
|
||||||
|
stats = achat.get("chatStats") or {}
|
||||||
|
try:
|
||||||
|
unread_count = int(stats.get("unreadCount") or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
unread_count = 0
|
||||||
|
messages: list[dict] = []
|
||||||
|
for item in achat.get("chatItems") or []:
|
||||||
|
parsed = parse_chat_item(item)
|
||||||
|
if parsed is not None:
|
||||||
|
messages.append(parsed)
|
||||||
|
min_unread = stats.get("minUnreadItemId")
|
||||||
|
return {
|
||||||
|
"contact_id": entry["id"],
|
||||||
|
"display_name": entry["display_name"],
|
||||||
|
"unread_count": unread_count,
|
||||||
|
"min_unread_item_id": str(min_unread) if min_unread is not None else "",
|
||||||
|
"unread": bool(stats.get("unreadChat")) or unread_count > 0,
|
||||||
|
"messages": messages,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def parse_direct_text_item(item: dict) -> InboundDict | None:
|
def parse_direct_text_item(item: dict) -> InboundDict | None:
|
||||||
"""Normalize one `newChatItems` entry into a message dict, or None.
|
"""Normalize one `newChatItems` entry into a message dict, or None.
|
||||||
|
|
||||||
@@ -396,6 +476,89 @@ class SimplexDaemon:
|
|||||||
future.cancel()
|
future.cancel()
|
||||||
raise TimeoutError("simplex contacts request timed out") from exc
|
raise TimeoutError("simplex contacts request timed out") from exc
|
||||||
|
|
||||||
|
# ---- chats / history ----
|
||||||
|
|
||||||
|
async def chats(
|
||||||
|
self, unread_only: bool = True, count: int = 20, timeout: float = 20.0
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Chat previews from the daemon, optionally only those with unread.
|
||||||
|
|
||||||
|
`/_get chats <userId> count=<n> {"type":"filters","favorite":false,
|
||||||
|
"unread":<bool>}` returns `apiChats`. This reads the daemon's persistent
|
||||||
|
state, unlike the bridge's in-memory receive buffer. A `chatCmdError`
|
||||||
|
or malformed reply yields an empty list rather than fabricated chats.
|
||||||
|
"""
|
||||||
|
user_id = await self.active_user(timeout)
|
||||||
|
query = {"type": "filters", "favorite": False, "unread": bool(unread_only)}
|
||||||
|
command = f"/_get chats {user_id} count={max(1, int(count))} {json.dumps(query)}"
|
||||||
|
resp = await self._roundtrip(command, timeout)
|
||||||
|
if resp.get("type") != "apiChats":
|
||||||
|
return []
|
||||||
|
chats: list[dict] = []
|
||||||
|
for achat in resp.get("chats") or []:
|
||||||
|
parsed = parse_chat(achat)
|
||||||
|
if parsed is not None:
|
||||||
|
chats.append(parsed)
|
||||||
|
return chats
|
||||||
|
|
||||||
|
async def chat_history(
|
||||||
|
self, contact_id: str, count: int = 20, timeout: float = 20.0
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Recent messages of one direct chat, newest-aware, from the daemon.
|
||||||
|
|
||||||
|
`/_get chat @<contactId> count=<n>` returns `apiChat`; each message
|
||||||
|
carries `meta.itemStatus` (`rcvNew`/`rcvRead`), so callers can tell
|
||||||
|
unread from read. A malformed reply yields an empty list.
|
||||||
|
"""
|
||||||
|
chat_ref = str(contact_id).strip().lstrip("@")
|
||||||
|
command = f"/_get chat @{chat_ref} count={max(1, int(count))}"
|
||||||
|
resp = await self._roundtrip(command, timeout)
|
||||||
|
if resp.get("type") != "apiChat":
|
||||||
|
return []
|
||||||
|
chat = resp.get("chat")
|
||||||
|
parsed = parse_chat(chat) if isinstance(chat, dict) else None
|
||||||
|
return parsed["messages"] if parsed is not None else []
|
||||||
|
|
||||||
|
def request_chats(
|
||||||
|
self, unread_only: bool = True, count: int = 20, timeout: float = 20.0
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Thread-safe chat-preview lookup 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 list.
|
||||||
|
"""
|
||||||
|
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.chats(unread_only=unread_only, count=count, timeout=timeout), loop
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return future.result(timeout=timeout + 5.0)
|
||||||
|
except concurrent.futures.TimeoutError as exc:
|
||||||
|
future.cancel()
|
||||||
|
raise TimeoutError("simplex chats request timed out") from exc
|
||||||
|
|
||||||
|
def request_chat_history(
|
||||||
|
self, contact_id: str, count: int = 20, timeout: float = 20.0
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Thread-safe per-chat history lookup 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 list.
|
||||||
|
"""
|
||||||
|
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.chat_history(contact_id, count=count, timeout=timeout), loop
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return future.result(timeout=timeout + 5.0)
|
||||||
|
except concurrent.futures.TimeoutError as exc:
|
||||||
|
future.cancel()
|
||||||
|
raise TimeoutError("simplex chat history request timed out") from exc
|
||||||
|
|
||||||
# ---- inbound ----
|
# ---- inbound ----
|
||||||
|
|
||||||
async def _consume(self, raw: Any) -> None:
|
async def _consume(self, raw: Any) -> None:
|
||||||
|
|||||||
+136
-1
@@ -21,12 +21,28 @@ from semif_agent.bridges.simplex import SimplexBridge
|
|||||||
class FakeDaemon:
|
class FakeDaemon:
|
||||||
"""Stands in for the bridge's own simplex-chat connection."""
|
"""Stands in for the bridge's own simplex-chat connection."""
|
||||||
|
|
||||||
def __init__(self, link=None, error=None, contacts=None, contacts_error=None):
|
def __init__(
|
||||||
|
self,
|
||||||
|
link=None,
|
||||||
|
error=None,
|
||||||
|
contacts=None,
|
||||||
|
contacts_error=None,
|
||||||
|
chats=None,
|
||||||
|
chats_error=None,
|
||||||
|
history=None,
|
||||||
|
history_error=None,
|
||||||
|
):
|
||||||
self.link = link
|
self.link = link
|
||||||
self.error = error
|
self.error = error
|
||||||
self.contacts_list = contacts or []
|
self.contacts_list = contacts or []
|
||||||
self.contacts_error = contacts_error
|
self.contacts_error = contacts_error
|
||||||
|
self.chats_list = chats or []
|
||||||
|
self.chats_error = chats_error
|
||||||
|
self.history_list = history or []
|
||||||
|
self.history_error = history_error
|
||||||
self.refresh_count = 0
|
self.refresh_count = 0
|
||||||
|
self.chat_calls = []
|
||||||
|
self.history_calls = []
|
||||||
self.sent = []
|
self.sent = []
|
||||||
self.closed = False
|
self.closed = False
|
||||||
self.on_message = None
|
self.on_message = None
|
||||||
@@ -55,6 +71,18 @@ class FakeDaemon:
|
|||||||
async def contacts(self, timeout=20.0):
|
async def contacts(self, timeout=20.0):
|
||||||
return self.request_contacts(timeout)
|
return self.request_contacts(timeout)
|
||||||
|
|
||||||
|
def request_chats(self, unread_only=True, count=20, timeout=20.0):
|
||||||
|
self.chat_calls.append((unread_only, count))
|
||||||
|
if self.chats_error is not None:
|
||||||
|
raise self.chats_error
|
||||||
|
return list(self.chats_list)
|
||||||
|
|
||||||
|
def request_chat_history(self, contact_id, count=20, timeout=20.0):
|
||||||
|
self.history_calls.append((contact_id, count))
|
||||||
|
if self.history_error is not None:
|
||||||
|
raise self.history_error
|
||||||
|
return list(self.history_list)
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
self.closed = True
|
self.closed = True
|
||||||
|
|
||||||
@@ -309,6 +337,111 @@ def test_stop_closes_the_daemon():
|
|||||||
assert daemon.closed is True
|
assert daemon.closed is True
|
||||||
|
|
||||||
|
|
||||||
|
# ---- daemon-backed unread / history ----
|
||||||
|
|
||||||
|
def chat_summary(contact_id="4", display_name="Alice", unread_count=2):
|
||||||
|
return {
|
||||||
|
"contact_id": contact_id,
|
||||||
|
"display_name": display_name,
|
||||||
|
"unread_count": unread_count,
|
||||||
|
"min_unread_item_id": "10",
|
||||||
|
"unread": True,
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"item_id": "10",
|
||||||
|
"text": "hello there",
|
||||||
|
"status": "rcvNew",
|
||||||
|
"unread": True,
|
||||||
|
"direction": "directRcv",
|
||||||
|
"sent_at": "2026-01-01T00:00:00Z",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_unread_returns_daemon_chats():
|
||||||
|
daemon = FakeDaemon(chats=[chat_summary()])
|
||||||
|
bridge, _, base = start_bridge(daemon=daemon)
|
||||||
|
try:
|
||||||
|
assert get(f"{base}/unread") == {"chats": [chat_summary()]}
|
||||||
|
assert daemon.chat_calls == [(True, 20)], "must ask the daemon for unread"
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_unread_honours_count_query():
|
||||||
|
daemon = FakeDaemon(chats=[])
|
||||||
|
bridge, _, base = start_bridge(daemon=daemon)
|
||||||
|
try:
|
||||||
|
get(f"{base}/unread?count=5")
|
||||||
|
assert daemon.chat_calls == [(True, 5)]
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_unread_without_connection_is_unavailable():
|
||||||
|
bridge, _, base = start_bridge(daemon=FakeDaemon(chats_error=RuntimeError("not connected")))
|
||||||
|
try:
|
||||||
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
|
get(f"{base}/unread")
|
||||||
|
assert exc.value.code == 503
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_unread_lookup_failure_is_reported():
|
||||||
|
bridge, _, base = start_bridge(daemon=FakeDaemon(chats_error=TimeoutError("slow")))
|
||||||
|
try:
|
||||||
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
|
get(f"{base}/unread")
|
||||||
|
assert exc.value.code == 502
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_history_returns_messages_for_contact():
|
||||||
|
messages = [{"item_id": "11", "text": "hi", "status": "rcvRead", "unread": False,
|
||||||
|
"direction": "directRcv", "sent_at": ""}]
|
||||||
|
daemon = FakeDaemon(history=messages)
|
||||||
|
bridge, _, base = start_bridge(daemon=daemon)
|
||||||
|
try:
|
||||||
|
assert get(f"{base}/history?contact=7") == {"contact_id": "7", "messages": messages}
|
||||||
|
assert daemon.history_calls == [("7", 20)]
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_history_requires_a_contact():
|
||||||
|
bridge, daemon, base = start_bridge()
|
||||||
|
try:
|
||||||
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
|
get(f"{base}/history")
|
||||||
|
assert exc.value.code == 400
|
||||||
|
assert daemon.history_calls == []
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_history_without_connection_is_unavailable():
|
||||||
|
bridge, _, base = start_bridge(daemon=FakeDaemon(history_error=RuntimeError("not connected")))
|
||||||
|
try:
|
||||||
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
|
get(f"{base}/history?contact=4")
|
||||||
|
assert exc.value.code == 503
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_history_lookup_failure_is_reported():
|
||||||
|
bridge, _, base = start_bridge(daemon=FakeDaemon(history_error=TimeoutError("slow")))
|
||||||
|
try:
|
||||||
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
|
get(f"{base}/history?contact=4")
|
||||||
|
assert exc.value.code == 502
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
# ---- catalog / codegen surface ----
|
# ---- catalog / codegen surface ----
|
||||||
|
|
||||||
def test_known_infos_include_simplex():
|
def test_known_infos_include_simplex():
|
||||||
@@ -339,4 +472,6 @@ def test_describe_bridges_renders_service_auth_and_endpoints():
|
|||||||
assert "X-Semif-Token" in text
|
assert "X-Semif-Token" in text
|
||||||
assert "simplex_bridge_token" in text
|
assert "simplex_bridge_token" in text
|
||||||
assert "/inbox/next" in text
|
assert "/inbox/next" in text
|
||||||
|
assert "/unread" in text
|
||||||
|
assert "/history" in text
|
||||||
assert "never speak" in text
|
assert "never speak" in text
|
||||||
@@ -16,6 +16,8 @@ from semif_agent.simplex_ws import (
|
|||||||
accept_command,
|
accept_command,
|
||||||
contact_entry,
|
contact_entry,
|
||||||
contact_link,
|
contact_link,
|
||||||
|
parse_chat,
|
||||||
|
parse_chat_item,
|
||||||
parse_direct_text_item,
|
parse_direct_text_item,
|
||||||
send_text_command,
|
send_text_command,
|
||||||
)
|
)
|
||||||
@@ -400,3 +402,168 @@ def test_on_connected_hook_runs_and_failures_are_swallowed():
|
|||||||
# A hook failure must not propagate (it would tear down the connection).
|
# A hook failure must not propagate (it would tear down the connection).
|
||||||
asyncio.run(SimplexDaemon("ws://x", on_connected=bad)._notify_connected())
|
asyncio.run(SimplexDaemon("ws://x", on_connected=bad)._notify_connected())
|
||||||
asyncio.run(SimplexDaemon("ws://x")._notify_connected())
|
asyncio.run(SimplexDaemon("ws://x")._notify_connected())
|
||||||
|
|
||||||
|
|
||||||
|
# ---- chat previews / history (true unread) ----
|
||||||
|
|
||||||
|
def chat_item(item_id=10, text="hello", status="rcvNew", direction="directRcv", shape="api"):
|
||||||
|
meta = {"itemId": item_id, "itemTs": "2026-01-01T00:00:00Z", "itemStatus": {"type": status}}
|
||||||
|
if shape == "api":
|
||||||
|
content = {"type": "rcvMsgContent", "msgContent": {"type": "text", "text": text}}
|
||||||
|
else:
|
||||||
|
content = {"rcvMsgContent": {"msgContent": {"type": "text", "text": text}}}
|
||||||
|
return {"chatDir": {"type": direction}, "meta": meta, "content": content}
|
||||||
|
|
||||||
|
|
||||||
|
def api_chat(contact_id="4", display="Alice", unread_count=2, min_unread="10",
|
||||||
|
unread_chat=True, items=None):
|
||||||
|
return {
|
||||||
|
"chatInfo": {
|
||||||
|
"type": "direct",
|
||||||
|
"contact": {"contactId": contact_id, "profile": {"displayName": display}},
|
||||||
|
},
|
||||||
|
"chatStats": {
|
||||||
|
"unreadCount": unread_count,
|
||||||
|
"unreadMentions": 0,
|
||||||
|
"reportsCount": 0,
|
||||||
|
"minUnreadItemId": min_unread,
|
||||||
|
"unreadChat": unread_chat,
|
||||||
|
},
|
||||||
|
"chatItems": items if items is not None else [chat_item()],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_chat_item_reads_status_and_text():
|
||||||
|
parsed = parse_chat_item(chat_item(item_id=12, text="hi", status="rcvNew"))
|
||||||
|
assert parsed == {
|
||||||
|
"item_id": "12",
|
||||||
|
"text": "hi",
|
||||||
|
"status": "rcvNew",
|
||||||
|
"unread": True,
|
||||||
|
"direction": "directRcv",
|
||||||
|
"sent_at": "2026-01-01T00:00:00Z",
|
||||||
|
}
|
||||||
|
read = parse_chat_item(chat_item(item_id=11, text="old", status="rcvRead"))
|
||||||
|
assert read["unread"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_chat_item_accepts_aeson_shape_and_drops_non_text():
|
||||||
|
assert parse_chat_item(chat_item(shape="aeson"))["text"] == "hello"
|
||||||
|
assert parse_chat_item(chat_item(text="")) is None
|
||||||
|
file_item = chat_item()
|
||||||
|
file_item["content"] = {"type": "rcvFile", "file": {}}
|
||||||
|
assert parse_chat_item(file_item) is None
|
||||||
|
assert parse_chat_item({"meta": {}, "content": {}}) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_chat_reads_stats_and_skips_non_direct():
|
||||||
|
parsed = parse_chat(api_chat(contact_id="7", display="Bob", unread_count=3, min_unread="42"))
|
||||||
|
assert parsed["contact_id"] == "7"
|
||||||
|
assert parsed["display_name"] == "Bob"
|
||||||
|
assert parsed["unread_count"] == 3
|
||||||
|
assert parsed["min_unread_item_id"] == "42"
|
||||||
|
assert parsed["unread"] is True
|
||||||
|
assert [m["item_id"] for m in parsed["messages"]] == ["10"]
|
||||||
|
|
||||||
|
group = api_chat()
|
||||||
|
group["chatInfo"] = {"type": "group", "groupInfo": {}}
|
||||||
|
assert parse_chat(group) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_chat_unread_false_when_no_unread():
|
||||||
|
parsed = parse_chat(api_chat(unread_count=0, min_unread=None, unread_chat=False))
|
||||||
|
assert parsed["unread"] is False
|
||||||
|
assert parsed["min_unread_item_id"] == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_chats_sends_unread_filter_and_parses_previews():
|
||||||
|
daemon = SimplexDaemon("ws://x", user_id=1)
|
||||||
|
|
||||||
|
async def scenario():
|
||||||
|
daemon._loop = asyncio.get_running_loop()
|
||||||
|
ws = FakeWS(
|
||||||
|
daemon,
|
||||||
|
[
|
||||||
|
{"type": "activeUser", "user": {"userId": 3}},
|
||||||
|
{"type": "apiChats", "chats": [api_chat()]},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
daemon._ws = ws
|
||||||
|
return await daemon.chats(unread_only=True, count=5, timeout=5), ws
|
||||||
|
|
||||||
|
result, ws = asyncio.run(scenario())
|
||||||
|
assert [m["cmd"] for m in ws.sent] == [
|
||||||
|
"/user",
|
||||||
|
'/_get chats 3 count=5 {"type": "filters", "favorite": false, "unread": true}',
|
||||||
|
]
|
||||||
|
assert result[0]["contact_id"] == "4"
|
||||||
|
assert result[0]["unread_count"] == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_chats_returns_empty_on_error_response():
|
||||||
|
daemon = SimplexDaemon("ws://x", user_id=1)
|
||||||
|
|
||||||
|
async def scenario():
|
||||||
|
daemon._loop = asyncio.get_running_loop()
|
||||||
|
ws = FakeWS(
|
||||||
|
daemon,
|
||||||
|
[
|
||||||
|
{"type": "activeUser", "user": {"userId": 1}},
|
||||||
|
{"type": "chatCmdError", "chatError": {"type": "error"}},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
daemon._ws = ws
|
||||||
|
return await daemon.chats(timeout=5)
|
||||||
|
|
||||||
|
assert asyncio.run(scenario()) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_chat_history_uses_chat_ref_and_parses_items():
|
||||||
|
daemon = SimplexDaemon("ws://x")
|
||||||
|
|
||||||
|
async def scenario():
|
||||||
|
daemon._loop = asyncio.get_running_loop()
|
||||||
|
ws = FakeWS(
|
||||||
|
daemon,
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"type": "apiChat",
|
||||||
|
"chat": api_chat(
|
||||||
|
items=[
|
||||||
|
chat_item(item_id=10, text="first", status="rcvRead"),
|
||||||
|
chat_item(item_id=11, text="second", status="rcvNew"),
|
||||||
|
]
|
||||||
|
),
|
||||||
|
}
|
||||||
|
],
|
||||||
|
)
|
||||||
|
daemon._ws = ws
|
||||||
|
return await daemon.chat_history("@7", count=9, timeout=5), ws
|
||||||
|
|
||||||
|
result, ws = asyncio.run(scenario())
|
||||||
|
assert [m["cmd"] for m in ws.sent] == ["/_get chat @7 count=9"]
|
||||||
|
assert [(m["item_id"], m["unread"]) for m in result] == [("10", False), ("11", True)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_chat_history_returns_empty_on_error_response():
|
||||||
|
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.chat_history("4", timeout=5)
|
||||||
|
|
||||||
|
assert asyncio.run(scenario()) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_chats_without_connection_raises():
|
||||||
|
daemon = SimplexDaemon("ws://x")
|
||||||
|
with pytest.raises(RuntimeError):
|
||||||
|
daemon.request_chats(timeout=1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_chat_history_without_connection_raises():
|
||||||
|
daemon = SimplexDaemon("ws://x")
|
||||||
|
with pytest.raises(RuntimeError):
|
||||||
|
daemon.request_chat_history("4", timeout=1)
|
||||||
Reference in new issue
Block a user