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
+136
-1
@@ -21,12 +21,28 @@ from semif_agent.bridges.simplex import SimplexBridge
|
||||
class FakeDaemon:
|
||||
"""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.error = error
|
||||
self.contacts_list = contacts or []
|
||||
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.chat_calls = []
|
||||
self.history_calls = []
|
||||
self.sent = []
|
||||
self.closed = False
|
||||
self.on_message = None
|
||||
@@ -55,6 +71,18 @@ class FakeDaemon:
|
||||
async def contacts(self, timeout=20.0):
|
||||
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):
|
||||
self.closed = True
|
||||
|
||||
@@ -309,6 +337,111 @@ def test_stop_closes_the_daemon():
|
||||
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 ----
|
||||
|
||||
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 "simplex_bridge_token" in text
|
||||
assert "/inbox/next" in text
|
||||
assert "/unread" in text
|
||||
assert "/history" in text
|
||||
assert "never speak" in text
|
||||
@@ -16,6 +16,8 @@ from semif_agent.simplex_ws import (
|
||||
accept_command,
|
||||
contact_entry,
|
||||
contact_link,
|
||||
parse_chat,
|
||||
parse_chat_item,
|
||||
parse_direct_text_item,
|
||||
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).
|
||||
asyncio.run(SimplexDaemon("ws://x", on_connected=bad)._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