owned this note
owned this note
Published
Linked with GitHub
# Read receipts for threads
## Problem statement
In order for [notifications in threads](https://github.com/vector-im/element-meta/issues/196) to be accurate clients need to able to synchronize whether threads have been read or not. This is done using read receipts in the main timeline.
Tracking of whether a user has read a thread needs to be performed as the single read receipt for a room is not enough information to know whether messages in a thread have been viewed.
### Requirements
* For each thread in a room:
* Sync the read status of a thread across clients.
* Let the user know if there are unread messages in threads the user has participated in.
* Do not consider threaded messages in the notification counts.
## Background
### Receipts
Matrix uses "receipts" to note which part of a room has been read by a user. It considers the history for a room to be split into three sections[^1]:
1. Messages the user has read (or indicated they aren’t interested in them).
2. Messages the user might have read some but not others.
3. Messages the user hasn’t seen yet.
The **fully read marker** is between 1 & 2 while the **read receipt** is between 2 & 3. Note that fully read markers are not shared with other users while read receipts are.
Another way to consider this is[^2]:
1. **Fully read marker**: a private bookmark to indicate the point which has been processed in the discussion. This allows a user to go back to it later.
2. **Read receipts**: public indicators of what a user has seen to inform other participants that the user has seen it.
3. **Hidden read receipts**: a private mechanism to synchronize "unread messages" indicators between a user's devices (while still retaining the ability from 1 as a separate concept).
#### [Fully read markers](https://spec.matrix.org/latest/client-server-api/#fully-read-markers)
They are stored in the room account data for the user (but modified via a separate API).
API is:
`POST /_matrix/client/v3/rooms/{roomId}/read_markers`
The read receipt can optionally be updated at the same time.
In Element Web your fully read marker is displayed as the green line across the conversation.
#### [Read receipts](https://spec.matrix.org/latest/client-server-api/#receipts)
Only `m.read` is defined at the moment, but it is meant to be generic infrastructure.
Updating a read receipt updates a "marker" which causes any notifications prior to and including the event to be marked as read.[^3] A user has a single read receipt "marker" per room.
Passed to clients as an `m.receipt` event under the `ephemeral` array for each room in the `/sync` response. The event includes a map of event ID -> receipt type -> user ID -> data (currently just a timestamp). Note that the event is a delta from previous events. An example:
```json
{
"content": {
"$1435641916114394fHBLK:matrix.org": {
"m.read": {
"@rikj:jki.re": {
"ts": 1436451550453
}
}
}
},
"room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt"
}
```
API is:
`POST /_matrix/client/v3/rooms/{roomId}/receipt/{receiptType}/{eventId}`
In Element Web read receipts are the small avatars on the right hand side of the conversation. Note that your own read receipt is not shown.
#### [Hidden read receipts (MSC2285)](https://github.com/matrix-org/matrix-spec-proposals/pull/2285)
A new receipt type (`m.read.hidden`) to set a read receipt without sharing it with other users. It also modifies the `/read_markers` API to accept the new receipt type.
This is useful to synchronize notifications across devices while keeping read status private.
### [Push rules](https://spec.matrix.org/v1.2/client-server-api/#push-rules)
A user's push rules determine one or more user-specific actions on each event. They are customizable, but the homeserver provides default rules. They can result in an action to:
1. Do nothing
2. Notify the user (`notify` action), which can have additional actions:
1. Highlight the message (`highlight` action)
2. Play a sound (`sound` action)
By default, all new `m.room.message` and `m.room.encrypted` events generate a notification, events with a user's username in them or `@room` generate highlights, etc.
#### [Push rules for relations (MSC3664)](https://github.com/matrix-org/matrix-spec-proposals/pull/3664)
Augments push rules to allow applying them to the target of an event relationship and defines a default push rule for replies (not using the reply fallback).
#### [Event notification attributes and actions (MSC2785)](https://github.com/matrix-org/matrix-spec-proposals/pull/2785)
A proposed replacement for push rules, the results are essentially the same actions (and presumedly would not change how the data relates to `/sync`, see below).
### [Notification counts in `/sync`](https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3sync)
The number of notification events and highlight events since the user's last read receipt are both returned on a per room basis as part of a `/sync` response (for joined room).
Notification and highlight events are any messages where the push rules resulted in an action of `notify` or `highlight`, respectively. (Note that a `highlight` action must be a `nofity` action, thus `highlight_count <= notification_count`.)
An example:
```json
{
"account_data": [...],
"ephemeral": [...],
"state": [...],
"summary": {...},
"timeline": {...},
"unread_notifications": {
"highlight_count": 0,
"notification_count": 0
}
}
```
#### [Unread messages count (MSC2654)](https://github.com/matrix-org/matrix-spec-proposals/pull/2654)
A new field is added under the `unread_notifications` field (`unread_count`) which is the total number of events matching particular criteria since the user's last read receipt.
This replaces [MSC2625](https://github.com/matrix-org/matrix-spec-proposals/pull/2625), which adds a new push rule action (`mark_unread`) to perform the same task. In this rendition, `notify` implies `mark_unread` and thus `highlight_count <= notification_count <= unread_count`.
### [Push notifications](https://spec.matrix.org/v1.2/push-gateway-api/#post_matrixpushv1notify)
Push notifications receive either the number of unread messages (across all rooms) or the number of rooms with unread messages (depending on the value of `push.group_unread_count_by_room` in the Synapse configuration). Unread messages
are any messages where the push rules resulted in an action of `notify`.
This information is sent from the homeserver to the push gateway as part of every notification:
```json
{
"notifications": {
"counts": {
"unread": 1,
...
},
...
}
}
```
## Potential solution
A new receipt type will be added (`m.thread_read`), this will behave slightly differently to `m.read` in that multiple must exist per user per room. (One per thread would exist.) This would be achieved by including a `key` field in the receipt, set to the the thread ID (the event ID of the root event, the same as what is used for the `m.thread` relation from [MSC3440](https://github.com/matrix-org/matrix-spec-proposals/pull/3440)).
For this, we use the following API:
```
/_matrix/client/v3/rooms/{roomId}/receipt/m.thread_read/{eventId}
{
"key": "{threadId}"
}
```
Each receipt then would be unique over `(roomId, userId, receiptType, key)` instead of `(roomId, userId, receiptType)`.
This could then be returned from sync as a map of event ID -> receipt type -> user ID -> {key, timestamp}, as part of the standard `ephemeral` events key for joined rooms.
```json
{
"content": {
"$1435641916114394fHBLK:matrix.org": {
"m.read_thread": {
"@rikj:jki.re": {
"key": "$aaaaaaaaaa:matrix.org",
"ts": 1436451550453
}
}
}
},
"room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"type": "m.receipt"
}
```
This seems to match the expectations that clients generally wish to query what the read status of an event is, although Element Web stores this information twice:
1. A mapping of receipt type -> user ID -> event ID + timestamp
2. A map of event ID -> list of (user, receipt type, timestamp)
Additionally, threaded events (any event with a `rel_type` set to `m.thread`) should no longer be considered when calculating the notification count for a room as a whole.
TODO Default push rule to ignore threaded messages
To control notification counts for a specific thread, a client can configure a push rule per thread:
`PUT /_matrix/client/v3/pushrules/global/underride/{ruleId}`
```json
{
"kind": "underride", // TBD If this makes sense.
"conditions": [
// Maybe also match the room?
{
"kind": "event_match",
"key": "content.relates_to.rel_type",
"pattern": "m.thread"
},
{
"kind": "event_match",
"key": "content.relates_to.event_id",
"pattern": "$abcd" // The event ID of the thread root.
}
],
"actions": [
"notify",
{
"set_tweak": "thread",
"value": "$abcd" // The event ID of the thread root.
},
]
}
```
These would then come down `/sync`...? Somehow? How do we avoid making individual queries for every thread?
Note that no changes to push notifications will be necessary at this time.
### Technical Questions
* How do we make this compatible with clients that don't support viewing threads separately?
* How (if at all) does this interact with the fully read marker?
* Should that API be modified to also push the `m.thread_read` receipt forward or does that not make sense?
## Implementation notes
### Synapse
Synapse [stores receipts twice](https://github.com/matrix-org/synapse/blob/41cf4c2cf6432336cc7477f130a2847449cff99a/synapse/storage/databases/main/receipts.py#L593-L667):
1. Linearized
2. As a graph
A missing key can likely be treated as a null value of sorts in the database (as long as we can ensure uniqueness there).
### Element Web
matrix-js-sdk [stores the read receipts as two maps](https://github.com/matrix-org/matrix-js-sdk/blob/2910e62bb68db2e9bdf9eeb5b5d13d5bb269c424/src/models/room.ts#L149-L154):
* A map of receipt type -> user ID -> a pair of IWrappedReceipt (which encapsulates the event ID and IReceipt, which encapsulates the timestamp)
* A map of event ID -> list of ICachedReceipt (which encapsulates the user, receipt type, and data)
There's two ways to look up data for a room:
* Where has this user read up to?
* Who has read up to this message?
[^1]: From [the fully read marker](https://spec.matrix.org/latest/client-server-api/#fully-read-markers) specification.
[^2]: See [a discussion on MSC2285](https://github.com/matrix-org/matrix-spec-proposals/pull/2285#discussion_r436383889).
[^3]: [Spec on receiving notifications](https://spec.matrix.org/latest/client-server-api/#receiving-notifications)