Skip to content

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

fix(chats): a chat joined after the stream opened is followed from the join

raullopez-sandbox17f0b354e3d6
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index 6b20857fd..0a9b64cf9 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -727,6 +727,18 @@ class ChatService:
limit,
)
+ async def read_position(
+ self, session: AsyncSession, user_id: str, room_id: str
+ ) -> int:
+ """How far the user has read the room (set to its head as they joined),
+ or its head when nothing is recorded."""
+ seq = await session.scalar(
+ select(ChatRead.read_through_seq).where(
+ ChatRead.user_id == user_id, ChatRead.room_id == room_id
+ )
+ )
+ return seq if seq is not None else await self.head_seq(session, room_id)
+
async def head_seq(self, session: AsyncSession, room_id: str) -> int:
return await self._message_store.head_seq(session, room_id)
diff --git a/core/switch_core/gateway/chats.py b/core/switch_core/gateway/chats.py
index ffc2bf2e7..313611f9a 100644
--- a/core/switch_core/gateway/chats.py
+++ b/core/switch_core/gateway/chats.py
@@ -693,12 +693,18 @@ class _ChatStream:
self.cursors[room_id] = self.after[room_id]
if room_id in listed:
self.announced.add(room_id)
- elif room_id in listed:
- frames.extend(await self._announce(session, room))
- self.cursors[room_id] = await service.head_seq(session, room_id)
- self.announced.add(room_id)
else:
- self.cursors[room_id] = await service.head_seq(session, room_id)
+ if room_id in listed:
+ frames.extend(await self._announce(session, room))
+ self.announced.add(room_id)
+ # A room joined since the stream opened is followed from
+ # where the caller joined it, so whatever was said before
+ # the stream noticed it is still sent.
+ self.cursors[room_id] = (
+ await service.head_seq(session, room_id)
+ if initial
+ else await service.read_position(session, self.user.id, room_id)
+ )
service.listener.subscribe(room_id, self.on_room)
for room_id, room in listed.items():
if room_id not in self.announced or resummarize:
diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.py
index 798928034..cae64f6b5 100644
--- a/core/tests/switch_core/gateway/test_chats_groups.py
+++ b/core/tests/switch_core/gateway/test_chats_groups.py
@@ -977,3 +977,39 @@ async def test_a_create_cut_off_before_its_people_joined_finishes_on_retry(
async with chats.factory() as session:
assert await session.scalar(select(func.count()).select_from(Room)) == 1
assert await _reads(chats, chats.bob, room_id) == 200
+
+
+async def test_a_chat_noticed_late_is_followed_from_the_join(
+ chats: _Harness, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ room_id = await chats.new_chat(chats.alice, agent, "c1")
+ events = _stream(chats, chats.bob, {}, recheck=0.2)
+ assert (await events.next())[0] == "ready"
+
+ # The membership signal is lost; only the periodic recheck finds the room.
+ monkeypatch.setattr(chats.service, "_memberships_changed", lambda *_: None)
+ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200
+ for index in range(3):
+ sent = await chats.send(chats.alice, room_id, f"s{index}", f"m{index}")
+ assert sent.status_code == 200
+
+ name, summary = await events.next()
+ assert (name, summary["roomId"]) == ("chat", room_id)
+ bodies = [(await events.next())[1]["body"] for _ in range(3)]
+ assert bodies == ["m0", "m1", "m2"]
+ await events.stream.aclose() # type: ignore[attr-defined]
+
+
+async def test_a_reconnect_cursor_still_decides_where_a_chat_resumes(
+ chats: _Harness,
+) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ room_id = await chats.new_chat(chats.alice, agent, "c1")
+ first = (await chats.send(chats.alice, room_id, "s1", "seen")).json()
+ await chats.send(chats.alice, room_id, "s2", "new")
+
+ events = _stream(chats, chats.alice, {room_id: first["messages"][0]["seq"]}, 60.0)
+ name, data = await events.next()
+ assert (name, data["body"]) == ("message", "new")
+ await events.stream.aclose() # type: ignore[attr-defined]