Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(chats): read positions and unread counts

raullopez-sandboxe9e01e241867
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index 6949d7405..1122990bf 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -62,6 +62,7 @@ from switch_core.db.models import (
ChatHidden,
ChatOperation,
ChatOwnerGrant,
+ ChatRead,
Client,
ClientRoom,
MediaBlob,
@@ -829,6 +830,7 @@ class ChatService:
joined = await self._provisioning.record_join(
session, room.transport_room_id, client.transport_user_id
)
+ await self._start_reading(session, room.id, [target_user_id])
await session.commit()
joined()
await self._make_lasting(tenant_id, target_user_id, room.id)
@@ -944,6 +946,61 @@ class ChatService:
await self._room_service.set_room_archived(room.id, True)
self._memberships_changed(tenant_id, member_ids)
+ async def _start_reading(
+ self, session: AsyncSession, room_id: str, user_ids: list[str]
+ ) -> None:
+ """Mark the room read up to its head for people joining it, so what
+ was said before they arrived is not unread to them."""
+ await self._read_through(
+ session,
+ room_id,
+ user_ids,
+ await self._message_store.head_seq(session, room_id),
+ )
+
+ async def _read_through(
+ self, session: AsyncSession, room_id: str, user_ids: list[str], seq: int
+ ) -> None:
+ if not user_ids:
+ return
+ insert = pg_insert(ChatRead).values(
+ [
+ {
+ "tenant_id": require_tenant_id(),
+ "user_id": user_id,
+ "room_id": room_id,
+ "read_through_seq": seq,
+ }
+ for user_id in user_ids
+ ]
+ )
+ await session.execute(
+ insert.on_conflict_do_update(
+ index_elements=["tenant_id", "user_id", "room_id"],
+ set_={
+ "read_through_seq": func.greatest(
+ ChatRead.read_through_seq, insert.excluded.read_through_seq
+ ),
+ "updated_at": func.now(),
+ },
+ )
+ )
+
+ async def mark_read(
+ self, tenant_id: str, user: User, room_id: str, seq: int
+ ) -> None:
+ """The caller has been shown the room up to `seq`. Never moves their
+ place back; a position past the room's head is refused."""
+ async with tenant_session(self.session_factory, tenant_id) as session:
+ room, _ = await self.require_member(session, tenant_id, user, room_id)
+ if seq < 0 or seq > await self._message_store.head_seq(session, room.id):
+ raise ChatError(
+ 422, "SEQ_OUT_OF_RANGE", "That position is not in this chat."
+ )
+ await self._read_through(session, room.id, [user.id], seq)
+ await session.commit()
+ self._memberships_changed(tenant_id, [user.id])
+
async def set_hidden(
self, tenant_id: str, user: User, room_id: str, hidden: bool
) -> None:
@@ -1225,6 +1282,9 @@ class ChatService:
await self._join(tenant_id, room, client)
await self._make_lasting(tenant_id, joiner.id, room.id)
async with tenant_session(self.session_factory, tenant_id) as session:
+ await self._start_reading(
+ session, room.id, [joiner.id for joiner in [user, *members]]
+ )
await session.execute(
update(ChatOperation)
.where(
diff --git a/core/switch_core/chats/views.py b/core/switch_core/chats/views.py
index 34935c6a8..555821783 100644
--- a/core/switch_core/chats/views.py
+++ b/core/switch_core/chats/views.py
@@ -18,6 +18,7 @@ from switch_core.chats import MEMBER_CLIENT_TYPE
from switch_core.db.models import (
Agent,
AgentDefinition,
+ ChatRead,
Client,
ClientRoom,
CollaborationBridge,
@@ -91,6 +92,8 @@ class ChatSummary(CamelModel):
# The people in the room, sorted, so any membership change re-sends the summary.
member_count: int
member_user_ids: list[str]
+ # Shown messages past the viewer's read position, less their own.
+ unread_count: int
last_message: ChatLastMessage | None
@@ -181,6 +184,26 @@ async def chat_summary(
).scalars()
if user_id is not None
)
+ unread_count = await session.scalar(
+ select(func.count())
+ .select_from(Message)
+ .where(
+ Message.room_id == room.id,
+ Message.event_type.in_(SHOWN_EVENT_TYPES),
+ Message.seq
+ > func.coalesce(
+ select(ChatRead.read_through_seq)
+ .where(ChatRead.user_id == viewer_id, ChatRead.room_id == room.id)
+ .scalar_subquery(),
+ 0,
+ ),
+ Message.sender_client_id.is_distinct_from(
+ select(Client.id)
+ .where(Client.user_id == viewer_id, Client.type == MEMBER_CLIENT_TYPE)
+ .scalar_subquery()
+ ),
+ )
+ )
channel_name: str | None = None
if bridge is not None and room.external_channel_id is not None:
prefix = f"{bridge.display_name}: "
@@ -220,6 +243,7 @@ async def chat_summary(
owns_agent=any(agent.owner_id == viewer_id for agent in agents),
member_count=len(member_user_ids),
member_user_ids=member_user_ids,
+ unread_count=unread_count or 0,
last_message=(
ChatLastMessage(
seq=last.seq,
diff --git a/core/switch_core/gateway/chats.py b/core/switch_core/gateway/chats.py
index d1d8bb0a8..f3dfe12e5 100644
--- a/core/switch_core/gateway/chats.py
+++ b/core/switch_core/gateway/chats.py
@@ -538,6 +538,19 @@ async def remove_agent(
return Response(status_code=204)
+class ReadRequest(CamelModel):
+ seq: int
+
+
[email protected]("/{room_id}/read", status_code=204)
+async def mark_read(
+ room_id: str, req: ReadRequest, user: CurrentUser, service: Service
+) -> Response:
+ """The caller has been shown the chat up to `seq`; never moves back."""
+ await service.mark_read(require_tenant_id(), user, room_id, req.seq)
+ return Response(status_code=204)
+
+
@router.put("/{room_id}/hidden", status_code=204)
async def hide_chat(room_id: str, user: CurrentUser, service: Service) -> Response:
await service.set_hidden(require_tenant_id(), user, room_id, True)
diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.py
index 905973cda..abb7ef909 100644
--- a/core/tests/switch_core/gateway/test_chats_groups.py
+++ b/core/tests/switch_core/gateway/test_chats_groups.py
@@ -764,3 +764,63 @@ async def test_history_stays_readable_once_the_agents_are_gone(
)
assert history.status_code == 200
assert "kept" in [m["body"] for m in history.json()["messages"]]
+
+
+# ── Reading ──────────────────────────────────────────────────────────────────
+
+
+async def _summary_of(chats: _Harness, user: User, room_id: str) -> dict[str, Any]:
+ return (await _listed(chats, user))[room_id]
+
+
+async def _read(chats: _Harness, user: User, room_id: str, seq: int) -> httpx.Response:
+ return await chats.client.put(
+ f"/chats/{room_id}/read", json={"seq": seq}, headers=chats.as_user(user)
+ )
+
+
+async def test_unread_counts_others_messages_past_the_read_position(
+ chats: _Harness,
+) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ room_id = await chats.new_chat(chats.alice, agent, "c1")
+ before = await chats.send(chats.alice, room_id, "s0", "said before bob")
+ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200
+ assert (await _summary_of(chats, chats.bob, room_id))["unreadCount"] == 0
+
+ first = (await chats.send(chats.alice, room_id, "s1", "one")).json()["messages"][0]
+ await chats.send(chats.alice, room_id, "s2", "two")
+ await chats.send(chats.bob, room_id, "s3", "bob's own")
+ assert (await _summary_of(chats, chats.bob, room_id))["unreadCount"] == 2
+ assert (await _summary_of(chats, chats.alice, room_id))["unreadCount"] == 1
+
+ assert (await _read(chats, chats.bob, room_id, first["seq"])).status_code == 204
+ assert (await _summary_of(chats, chats.bob, room_id))["unreadCount"] == 1
+ # Never backwards, and idempotent.
+ older = before.json()["messages"][0]["seq"]
+ assert (await _read(chats, chats.bob, room_id, older)).status_code == 204
+ assert (await _read(chats, chats.bob, room_id, first["seq"])).status_code == 204
+ assert (await _summary_of(chats, chats.bob, room_id))["unreadCount"] == 1
+
+ ahead = await _read(chats, chats.bob, room_id, 10_000)
+ assert ahead.status_code == 422
+ assert _code(ahead) == "SEQ_OUT_OF_RANGE"
+ outsider = await _read(chats, chats.admin, room_id, first["seq"])
+ assert outsider.status_code == 403
+
+
+async def test_reading_re_sends_the_readers_summary(chats: _Harness) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ room_id = await chats.new_chat(chats.alice, agent, "c1")
+ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200
+ sent = (await chats.send(chats.alice, room_id, "s1", "hi")).json()["messages"][0]
+
+ events = _stream(chats, chats.bob, {}, recheck=60.0)
+ name, summary = await events.next()
+ assert (name, summary["unreadCount"]) == ("chat", 1)
+ assert (await events.next())[0] == "ready"
+
+ assert (await _read(chats, chats.bob, room_id, sent["seq"])).status_code == 204
+ name, summary = await events.next()
+ assert (name, summary["unreadCount"]) == ("chat", 0)
+ await events.stream.aclose() # type: ignore[attr-defined]