Skip to content

feat(workspace): room messages count as unread in the Inbox (abilityai/trinity-enterprise#959) - #3939

Merged
vybe merged 9 commits into
devfrom
feature/ent959-inbox-room-unread
Oct 31, 2026
Merged

vybe merged 9 commits into
devfrom
feature/ent959-inbox-room-unread

Conversation

@AndriiPasternak31

@AndriiPasternak31 AndriiPasternak31 commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Fixes abilityai/trinity-enterprise#959

Room messages now count as unread in the Workspace Inbox for the room's members, and rooms appear in the Inbox's Unread and All lists with their unread count and a preview. A member's read cursor is per room; a first-ever viewer counts nothing; a non-member gets no entry for the room. The Inbox pane reads a long room to its end before marking it read.

Membership scope. Chat-state emits room rows only after one membership read in the viewer's identity space, and a read cursor is written only for an active member. A removed agent's own key gets the uniform 404 on room fetch and post and no longer lists the room; a reply that was already running when its waker was removed still lands (allow_departed on the engine's re-entry path only).

Admin exemption (decided). A platform admin keeps their own starred rows for rooms they are not in: count 0, no preview, keyed on the resolved role and key scope, never on a request flag. It is a deliberate exception to AC 3 and discloses nothing beyond the admin's own rows.

Validation

Check Result
test_ent959_room_unread.py, seeds 4242 and 90210 28 passed each
12 related room and Inbox files, seed 4242 297 passed
All 161 unit files that reference client_portal or shared_sessions 4732 passed, 0 failed
Frontend npm run test:unit (raw-color and loading-gate ratchets included) 390 files / 6175 passed; check:tokens OK
Backend unit tier, CI's command on Python 3.13.7 (clean snapshot: no .env, no submodules), seed 12345 27894 passed, 0 failed, 0 errors (test_ent959_room_unread 28, test_ent169_shared_sessions 37, test_ent359_portal_chat_state 22)
PostgreSQL 16.13, schema built by Alembic to its single head 28/28 new tests pass; the server log shows 0 errors across the new room queries

Across the cross-branch Python 3.13 run the only red is a pre-existing timing flake on unmodified dev (test_ent879_aauth_resource_route, seed 67890; 8 of 2000 isolated repeats fail), on no branch. The wider PostgreSQL run over the 162 client_portal / shared_sessions files gave 102 reds on this branch; 101 are identical on unmodified dev, and the 102nd is the new round-2 test in test_ent169_shared_sessions.py, whose fixture already cannot build its schema on PostgreSQL (SQLite-only DDL, the same on dev). That file's departed-waker and _require_membership(allow_departed=…) tests are therefore green on SQLite only.

**Mutation (scratch copies; backend set test_ent959 + test_ent359 + test_ent169, 87 tests): stored room-row filter removed → 8 failed / 87; member rows always dropped → 3; read-write membership gate removed → 4; admin exemption ignored → 2; left_at check removed from _require_membership → 3; left_at IS NULL removed from the participant list → 1; allow_departed=True for every post → 2; allow_departed=False → 1; platform-door username wiring removed → 1. Frontend: roomTranscriptComplete always true → 8 failed; the eager markRead on open restored → 1 failed.

Browser sign-off (2026-10-29), done: a real Chrome at 390px, light then dark, against a local stack built from this branch merged with dev 2d8b2c385. Seed: two local:test-echo agents, two rooms with the platform admin as the person, agent posts through each agent's own key (3 and 40, then 2 and 30 for the dark pass). Checked: Unread and All list both rooms with their count and a preview that truncates inside the card; no sideways scroll; opening a room clears it from Unread and keeps it in All; the long room opens at its newest message and is marked read only once the whole transcript is held. The server's read cursors moved once per room per pass (22:56 and 22:58 UTC), matching the clicks. Not covered by the click-through: the non-member cases, which need a second person account; they are held by the unit tests and the mutation runs above. /verify-local was not run; the stack was the dev compose (start.sh), so the production-image checks are CI's on push.

Found in the sign-off, fixed here (9ae95ed52): re-adding an agent a moderator had removed answered added and posted "joined the room" while the participant row kept left_at, so with this PR's membership checks the agent got 404 on fetch and post. The moderator's add now rejoins it (add_participant(..., rejoin=True)); an @mention of a removed agent still does not, so another member cannot undo a removal. Reproduced live before the fix (re-added fetch 404, post 404) and after (200, 200; the mention left it at 404). New test test_a_removed_agent_that_is_added_back_is_a_member_again; without the flag it fails.

Follow-ups filed: abilityai/trinity-enterprise#1010 (a message landing between the last fetch and the read write is cleared unseen); abilityai/trinity-enterprise#1011 (one email in the same room under both identity spaces shares one cursor).

AndriiPasternak31 and others added 9 commits October 21, 2026 23:02
…nity-enterprise#959)

GET /chat-state reported every room as unread 0. A room's unread is now
counted on the viewer's room read cursor (and the ent#557 baseline for a
room never opened): agent messages only, read through the viewer's own
active participant row in the identity space their credential acts in.
A non-member holding a cursor row for a room id gets 0 and no preview.

The rooms list also says whether the caller is in each room (an admin
lists every room), so the Inbox can show only member rooms.
…ty-enterprise#959)

A room the viewer is a member of is a chat row in Unread (one row per
room, ordered with chats by latest arrival) and in All. Opening it shows
the room's new messages in the reading pane, then reads it as a room;
Open in chat opens the room. A room without member === true never
becomes a row, resolves from a deep link, or is fetched.

The open room reads what arrives in it (PortalRoom emits read on open
and on an agent message; the shell marks it read), so the sidebar never
badges the room the person is looking at. All's "Rooms aren't in the
Inbox yet" footer note is gone.
…ading it (Abilityai/trinity-enterprise#959)

GET /api/rooms/{id} returns at most 500 rows from since, oldest first, so a
room past that ended the pane on its 500th message while the new ones sat
beyond it, and the read then cleared what the pane never showed. The card
now pages from since to the first empty batch (bounded) before it says
rendered. Found by the Codex review.
…ten only for an active member (Abilityai/trinity-enterprise#959)

Review fixes: chat-state emits room rows only after one membership read in the viewer's identity space; a read cursor is written only for an active member; a removed agent's own key gets the uniform 404 on fetch and post and no longer lists the room, while a reply already running when its waker was removed still lands; the Inbox card marks a room read only after reading it to its end.
… room (Abilityai/trinity-enterprise#959)

Re-adding an agent a moderator had removed answered `added` and posted
"joined the room", but the INSERT hit the participant row's UNIQUE triple and
the error was swallowed, so `left_at` stayed set. With this PR's membership
checks honouring `left_at`, the agent it said had rejoined got the uniform 404
on fetch and post (and, as on dev, was never woken). Found in the browser
sign-off and reproduced against a live stack.

`add_participant(..., rejoin=True)`, passed only by the moderator's explicit
add, clears `left_at` and takes the new role and join time, keeping the row
(the transcript's sender label and the agent's delta cursor). The @mention
auto-join keeps the old no-op, so another member mentioning a removed agent
cannot undo the removal; `test_departed_agent_is_not_woken` holds that.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw
@AndriiPasternak31
AndriiPasternak31 marked this pull request as ready for review October 29, 2026 23:15
@AndriiPasternak31

Copy link
Copy Markdown
Contributor Author

Ready for review. Since the draft:

  • Merged current dev (60bbdf0be, clean; the PR's own diff is unchanged).
  • Browser sign-off done. Real Chrome at 390px, light and dark, against a local stack of this branch. Details in the body.
  • One bug found in the sign-off, fixed here (9ae95ed52). A moderator re-adding an agent they had removed got "joined the room" while the agent stayed locked out: 404 on fetch and post, because this PR now honours left_at. The moderator's add now rejoins it. An @mention of a removed agent still does not, so another member cannot undo a removal.
  • Follow-ups filed: abilityai/trinity-enterprise#1010, abilityai/trinity-enterprise#1011.

Local evidence on the merged head (CI runs the full suite on this push):

Check Result
The 105 unit files that reach the changed modules (xdist ×4, seed 4242) 2992 passed, 0 failed. The 85 errors are the from conftest import ensure_schema_tables collision that pristine dev shows under the same command (76 and 46 errors on seeds 4242 and 12345); every affected file passes when run alone
Room test files (ent169, ent959, ent359, ent631), seeds 4242 and 90210 121 passed
The new re-add test with rejoin=True removed 1 failed (the new test), 37 passed
Frontend portal specs + raw-color and loading-gate ratchets 260 passed; check:tokens OK
Live stack, re-add before / after the fix fetch 404, post 404 / fetch 200, post 200; the @mention left the removed agent at 404

@webmixgamer @dolho could you take a look?

@dolho dolho left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 9ae95ed52.

Approve. Room unread is scoped by an SQL JOIN through the viewer's own active participant row, in the identity space the credential acts in. The stored room rows go through one batched membership read, and the read-cursor write is gated on active membership. A non-member gets no row, id or count, and an unknown room and a room you are not in return the same 204. Nothing new goes over /ws, there is no new SQL dialect surface, and there is no schema change, so the Alembic single-head check doesn't apply. The branch merges cleanly with current dev (6c7818cb8). The tests run the changed paths, and every guard I removed turned at least one test red. I found two Low items and nothing blocking.

What I ran

All runs were in a detached worktree at 9ae95ed52, diffed against merge-base 2d8b2c385.

  • pytest -q -p no:randomly unit/test_ent959_room_unread.py unit/test_ent359_portal_chat_state.py: 50 passed.
  • test_ent169_shared_sessions.py, filtered to the changed paths: -k "removed or departed or membership or list_rooms" gave 3 passed, and -k "reply_already_running or mention or rejoin or added_back" gave 5 passed. The second run includes the new re-add and departed-waker tests. My wider run over six related room and Inbox files hit my 1700 s timeout on a loaded host (about 25 s per test in this file), so it has no result. CI's pytest (head, seed 12345) ran the full unit tier on this head and passed.
  • Frontend vitest (portalInboxRooms.spec, portalInboxRooms.mount.spec, portalInboxRoomsShell.mount.spec, portalInbox.spec, portalInbox.mount.spec, plus the raw-color, loading-gate and source-text ratchets): 267 passed, 1 failed. The failure is portalInbox.mount.spec.js › the pane header … stacked. It fails the same way at the merge-base with this PR's frontend reverted, so it comes from my local jsdom, not from this diff.
  • git merge-tree --write-tree origin/dev HEAD: clean.
  • Enterprise-docs guard pattern over the added docs/ lines: no hits.

Backend mutations (scratch copy; target set test_ent959 + test_ent359, 50 tests):

Mutation Result
p.left_at IS NULL removed from _UNREAD_ROOM_ARRIVALS 1 failed
stored room-row filter (my_rooms) removed 8 failed
is_active_room_participant gate removed from mark_chat_read 4 failed
platform principal reads as workspace_user+email instead of user+username 4 failed
room_sees_all true for any platform principal (admin check dropped) 3 failed
cursorless member rooms dropped 1 failed
arrivals count system/own lines (sender_kind = 'agent' removed) 1 failed
active_room_ids ignores left_at 1 failed

Frontend mutations (4 Inbox room specs, 134 tests):

Mutation Result
isMemberRoom ignores member 7 failed
openInChatTarget loses the room branch 2 failed
the Inbox reads a room as 'thread' 2 failed

Execution coverage

Changed symbol Executed by Live consumer Verdict
db.unread_room_arrivals / _UNREAD_ROOM_ARRIVALS test_ent959_* (real SQLite tables) service.get_chat_state, chat_previews.get_chat_state_with_previews ✅ executed
db.active_room_ids test_a_non_member_holding_a_cursor_row…, test_a_participant_who_left… service.get_chat_state ✅ executed
db.is_active_room_participant / mark_chat_read(room_reader=) test_a_non_member_cannot_create_a_cursor…, test_a_departed_participant_cannot_write… router.portal_mark_chat_read ✅ executed
room_reader_of / room_sees_all / PortalPrincipal.username route tests + test_the_platform_door_carries_the_username… router.portal_chat_state, portal_auth.get_portal_principal ✅ executed
_require_membership(allow_departed=) / list_rooms_for_participant left_at test_a_removed_agent_*, test_a_reply_already_running_lands… shared_sessions.service.post_message/get_room/list_rooms ✅ executed
db.add_participant(rejoin=) test_a_removed_agent_that_is_added_back… service.add_participant ✅ executed (author's mutation: 1 red)
list_rooms member bit test_the_rooms_list_marks_* portalInbox.isMemberRoom ✅ executed
PortalInboxRoomCard.vue, roomTranscriptComplete, roomItem, isChatItem mount specs (jsdom + test-utils) PortalInboxPane.vue, PortalRoom.vue ✅ executed

The changed specs have no source-text assertions. Every toContain/toMatch hit is on rendered text.

Checks requested

  • Scoping and enumeration. Counts come only through JOIN enterprise_room_participants p ON … p.kind = :pkind AND p.identity = :pid AND p.left_at IS NULL. Stored rows are dropped by if kind == "room" and my_rooms is not None and cid not in my_rooms: continue. mark_chat_read returns the same 204 for an unknown room, a room you are not in, and a departed reader. The admin exemption reads is_platform and is_admin, which is the portal's stricter admin reading. Admin rows still count 0, because the count is the membership JOIN. A platform principal with no username reads no rooms. room_reader_of returns None in that case.
  • WS. No new broadcast. The existing room_message stays {room_id, seq}, and the Workspace picks up counts on its existing refresh.
  • Multi-worker. Every new piece of state is a DB row or a per-request read. There is no process-local cache.
  • N+1. /chat-state adds two statements in total (active_room_ids + unread_room_arrivals), not one per room. list_rooms computes member from the participant map it already batch-loads.
  • PostgreSQL. The query uses COUNT(*) OVER, ROW_NUMBER() OVER, FIRST_VALUE … ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING and aliased derived tables. All of these are portable. The timestamp comparison is TEXT against TEXT (enterprise_room_messages.created_at and last_read_at are both Text in db/tables.py, both written as ISO-Z), the same shape as the existing thread arm. I did not run PostgreSQL myself. The PR body reports 28/28 on PostgreSQL 16.
  • Migrations. None in this diff, so no dual-track or Alembic-head question.
  • Design system. The new PortalInboxRoomCard.vue uses semantic action-primary-* tokens plus gray neutrals, which the ratchet allows. Loading uses viewState. The skeleton keeps the pane's height. The ratchet specs pass.

Low

L1. An @mention of a removed agent still posts "joined the room", while the agent stays removed. (Confidence 8/10)
src/backend/shared_sessions/service.py:991-992, in _join_mentioned_newcomers:

db.add_participant(room_id, "agent", name, "member", utc_now_iso())
_post_system(room_id, f"{name} joined the room.")

present excludes departed agents, so a removed agent is a "newcomer" here. add_participant without rejoin swallows the IntegrityError, and the system line is posted anyway. I reproduced it on this head with test_departed_agent_is_not_woken's setup. The transcript reads ['Room created with agent-a, agent-b.', 'agent-a left the room.', 'agent-a joined the room.'], while left_at stays set and woke == [].

This is the same class 9ae95ed52 fixed for the moderator's add: the room says the agent joined, but it is locked out. The mention path itself is unchanged from dev, but this PR is what makes left_at binding. The false line also lands in every other agent's delta (_format_delta), and the person who mentioned the agent waits for a reply that never comes.

Fix: have db.add_participant report whether it inserted or reactivated a row, and post the line only then. Or skip names that already have a departed participant row before calling it.

L2. The new re-add test has a misleading comment. (Confidence 7/10)
tests/unit/test_ent169_shared_sessions.py:561:

_run(service.post_message(agent_a, room["id"], "back again"))  # 404s while it is out

After the rejoin, the call is expected to succeed. Its success is the proof, because a 404 would raise. The comment says the opposite. Change it to "succeeds now that it is back in" or similar.

Notes (not findings)

  • On the count-only path, get_chat_state calls unread_room_arrivals, which also joins m2.content for the latest message. That content is unused there. It is negligible at room sizes.
  • The follow-ups the PR already files cover the two gaps I would otherwise have raised. One is a message landing between the last fetch and the read write (ent#1010). The other is one email in the same room under both identity spaces sharing a cursor (ent#1011).

@vybe

vybe commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

merge-train: the body now says Fixes abilityai/trinity-enterprise#959; all five criteria are met and no more slices are expected. The operator accepted the admin exception to AC 3 at Gate 1, recorded on the issue. No push to this branch.

Riding with notes, for a follow-up:

  • Three user-doc lines now state the opposite of the behaviour: sharing-and-access/workspace.md:77, collaboration/rooms.md:98, faq/chat-and-sessions.md:131.
  • client_portal/chat_previews.py:128 (room_reader=room_reader) is correct but unpinned: deleting it leaves 187 tests green, while a starred, already-read member room then drops out of /chat-state?previews=true.
  • No test crosses the API-to-store seam for rooms: forcing member to undefined in normalizeRoomRow leaves 272 specs green. An untracked full-chain run passed.
  • An @mention of a removed agent posts "joined the room" while left_at stays set (service.py:991-992).

@vybe
vybe merged commit dfb6b1f into dev Oct 31, 2026
29 checks passed
dolho added a commit that referenced this pull request Nov 2, 2026
…rged to dev); tree is dev + this PR's commits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants