Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
164 changes: 147 additions & 17 deletions crates/chatd/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3616,9 +3616,11 @@ impl Store {
}

/// `message_id` is the first message that counts as unread. Empty means the newest message
/// stored. The marker becomes the newest stored id strictly before that, which may be older
/// than the marker already held, and the badge is counted from what is stored. When no
/// messages are stored yet, the badge still becomes at least one and the ack target is empty
/// stored. The marker becomes the newest stored id strictly before that, in the order the
/// messages are read: the one the window shows above it. That is time, then the server's
/// sequence, since a Tiny id is a UUID whose text says nothing about time. The marker may
/// be older than the one already held, and the badge is counted from what is stored. When
/// no messages are stored yet, the badge still becomes at least one and the ack target is empty
/// (for networks with a dialog-level unread mark). `None` when the conversation is missing.
/// The pair is the ack target (empty when the first stored message is the one marked or no
/// messages are stored) and how many of the unread messages mention me.
Expand Down Expand Up @@ -3709,25 +3711,45 @@ impl Store {
Ok(found.is_some())
}

/// The newest stored id strictly before `target`. Empty when nothing is.
/// The newest stored id strictly before `target`, in the order the messages are read.
/// Empty when nothing is.
fn message_before(&self, conversation: &Key, target: &str) -> rusqlite::Result<String> {
let before = self.beside_target(conversation, target, "<")?;
Ok(self
.db
.query_row(
"SELECT id FROM message
WHERE network = ?1 AND account = ?2 AND conversation = ?3 AND pending = 0
AND (length(id), id) < (length(?4), ?4)
ORDER BY length(id) DESC, id DESC LIMIT 1",
&format!(
"SELECT id FROM message
WHERE network = ?1 AND account = ?2 AND conversation = ?3 AND pending = 0
AND {before}
{NEWEST_FIRST} LIMIT 1"
),
params![word(&conversation.network), conversation.account, conversation.id, target],
|row| row.get(0),
)
.optional()?
.unwrap_or_default())
}

/// How many stored messages are unread from `anchor`, and how many of those mention me.
/// `inclusive` counts `anchor` itself (it is the first unread). Otherwise `anchor` is the
/// last message still read, and an empty anchor counts every stored message.
/// SQL that is true for a stored message of `conversation` on the `side` of `target`
/// (`<`, `>` or `>=`), in the order the messages are read ([`PLACE`]): time, then the
/// server's sequence, and the id only where both tie. A stored UUID is placed by that
/// order, since its text is no clock. A target the store does not hold has no place: its
/// id is then compared as text, which is the order of an id that carries its own.
fn beside_target(&self, conversation: &Key, target: &str, side: &str) -> rusqlite::Result<String> {
if self.message_place(conversation, target).is_some() {
return Ok(format!(
"{PLACE} {side} (SELECT {PLACE_TERMS} FROM message
WHERE network = ?1 AND account = ?2 AND conversation = ?3 AND id = ?4)"
));
}
Ok(format!("(length(id), id) {side} (length(?4), ?4)"))
}

/// How many stored messages are unread from `anchor`, and how many of those mention me,
/// counted in the order the messages are read. `inclusive` counts `anchor` itself (it is
/// the first unread). Otherwise `anchor` is the last message still read, and an empty
/// anchor counts every stored message.
fn unread_from(&self, conversation: &Key, anchor: &str, inclusive: bool) -> rusqlite::Result<(u32, u32)> {
let (count, mentions): (i64, i64) = if anchor.is_empty() {
self.db.query_row(
Expand All @@ -3739,14 +3761,14 @@ impl Store {
|row| Ok((row.get(0)?, row.get(1)?)),
)?
} else {
let side = if inclusive { ">=" } else { ">" };
let from = self.beside_target(conversation, anchor, if inclusive { ">=" } else { ">" })?;
self.db.query_row(
&format!(
"SELECT COUNT(*),
COALESCE(SUM(CASE WHEN json_extract(body, '$.mentions_me') IN (1, 'true') THEN 1 ELSE 0 END), 0)
FROM message
WHERE network = ?1 AND account = ?2 AND conversation = ?3 AND pending = 0
AND (length(id), id) {side} (length(?4), ?4)"
AND {from}"
),
params![word(&conversation.network), conversation.account, conversation.id, anchor],
|row| Ok((row.get(0)?, row.get(1)?)),
Expand Down Expand Up @@ -4203,8 +4225,8 @@ impl Store {
preview = CASE WHEN ?15 THEN ?4 ELSE preview END,
preview_expires = CASE WHEN ?15 THEN ?14 ELSE preview_expires END,
updated = max(updated, ?5),
hidden = CASE WHEN ?12 AND (?16 OR (last_read != ''
AND (length(last_read), last_read) < (length(?6), ?6))) THEN 0 ELSE hidden END
hidden = CASE WHEN ?12 AND (?16 OR last_read = ''
OR (length(last_read), last_read) < (length(?6), ?6)) THEN 0 ELSE hidden END
WHERE network = ?1 AND account = ?2 AND id = ?3",
params![
network,
Expand All @@ -4223,6 +4245,9 @@ impl Store {
incoming.expires_at,
replace_preview,
// A UUID says nothing about time: any live message brings the row back.
// So does a row with no marker, whatever the network: a chat forgotten
// before anything marked where it was read has nothing to be newer than,
// and its empty marker compared as text kept it hidden for good.
is_uuid(&incoming.id),
],
)?;
Expand Down Expand Up @@ -5865,6 +5890,14 @@ mod tests {
Message::plain(id, "mara", text, sent, false)
}

/// Whether chatd would announce a just-arrived `message`, by the conversation's row as the
/// store keeps it: a hidden row announces nothing.
fn announced(store: &Store, key: &Key, message: &Message) -> bool {
let row = store.conversation(key).unwrap().expect("the conversation is there");
let moment = crate::notify::Moment { now: message.sent, ..Default::default() };
crate::notify::decide(&protocol::settings::Values::default(), &row, message, &moment).is_some()
}

fn ids(page: &MessagePage) -> Vec<&str> {
page.messages.iter().map(|message| message.id.as_str()).collect()
}
Expand Down Expand Up @@ -6262,6 +6295,9 @@ mod tests {
let never = Message { state: SendState::Pending, ..said("3", "world in waiting", 30) };
store.ingest(&key, &never, false).unwrap();
store.ingest(&hidden, &said("4", "world of secrets", 40), true).unwrap();
// A hidden row with no read marker comes back on the next live message, so this one is
// hidden after its message arrived: what it hides behind keeps it hidden now.
store.forget_conversation(&hidden).unwrap();
let request = Key::new(&account, "stranger");
store
.upsert_conversation(&account, &ConversationRow {
Expand Down Expand Up @@ -6656,15 +6692,106 @@ mod tests {
assert!(store.forget_conversation(&dm).unwrap());
assert!(store.conversation(&dm).unwrap().unwrap().hidden);
// The later message has the smaller id.
store.ingest(&dm, &said(low, "are you there?", 20), true).unwrap();
let later = said(low, "are you there?", 20);
store.ingest(&dm, &later, true).unwrap();
assert!(!store.conversation(&dm).unwrap().unwrap().hidden);

assert!(announced(&store, &dm, &later), "back in the Inbox, the message that brought it notifies");

assert!(store.set_seen(&dm, high).unwrap());
assert!(store.set_seen(&dm, low).unwrap(), "the newer receipt names the smaller id");
assert!(!store.set_seen(&dm, low).unwrap());
}

/// A chat forgotten before anything marked where it was read keeps no marker, so the next
/// live message has nothing to be newer than. On a network whose ids carry their order the
/// empty marker, compared as text, kept the chat hidden for good: no Inbox row, and the
/// message was never announced.
#[test]
fn a_forgotten_direct_without_a_marker_comes_back_on_the_next_live_message() {
let (mut store, key) = store();
let account = key.account();
let dm = Key::new(&account, "dm");
store.upsert_conversation(&account, &ConversationRow::new("dm", ConversationKind::Direct, "Mara")).unwrap();
// The network listed the chat with nothing previewed and nothing read.
store.set_counts(&dm, 0, 0, None, NOW).unwrap();
assert!(store.forget_conversation(&dm).unwrap());
let row = store.conversation(&dm).unwrap().unwrap();
assert!(row.hidden && row.last_read.is_none(), "forgotten with no marker");

let live = said("20", "are you there?", NOW + 10);
store.ingest(&dm, &live, true).unwrap();
let row = store.conversation(&dm).unwrap().unwrap();
assert!(!row.hidden, "the next live message brings the chat back");
assert_eq!(row.unread, 1);
assert!(announced(&store, &dm, &live), "back in the Inbox, the message notifies like any other direct message");
}

/// Tiny message ids are UUIDs, so their text is no clock. "Mark unread from here" on the
/// middle of three messages counts it and the newer one, and puts the marker on the oldest:
/// the order the window lists them in. By text the middle one has the smallest id, which
/// left nothing before it and put all three after it.
#[test]
fn marking_unread_from_a_uuid_message_goes_by_time_not_by_the_ids_text() {
let (mut store, key) = store();
let first = "ffffffff-ffff-4fff-8fff-ffffffffffff";
let middle = "00000000-0000-4000-8000-000000000000";
let last = "55555555-5555-4555-8555-555555555555";
store.ingest(&key, &said(first, "one", 10), true).unwrap();
store.ingest(&key, &said(middle, "two", 20), true).unwrap();
store.ingest(&key, &said(last, "three", 30), true).unwrap();
assert!(store.mark_read(&key, "").unwrap(), "read up to the newest message");

let (marker, mentions) = store.mark_unread(&key, middle).unwrap().expect("the conversation is there");
assert_eq!((marker.as_str(), mentions), (first, 0), "the marker is the message shown above the one marked");
let row = store.conversation(&key).unwrap().unwrap();
assert_eq!((row.unread, row.last_read.as_deref()), (2, Some(first)), "the marked message and the newer one are unread");

// From the newest message, as the sidebar's "Mark unread" asks: one unread, and the
// marker on the message shown above it.
let (marker, _) = store.mark_unread(&key, "").unwrap().unwrap();
assert_eq!(marker, middle);
let row = store.conversation(&key).unwrap().unwrap();
assert_eq!((row.unread, row.last_read.as_deref()), (1, Some(middle)));
}

/// Tiny stamps a plaintext message to the second and an encrypted one to the minute, and
/// numbers each post. Inside one stamp that sequence is the order the window shows.
#[test]
fn marking_unread_inside_one_stamp_goes_by_the_post_sequence() {
let (mut store, key) = store();
let post = |id: &str, text: &str, seq: i64| Message { seq, ..said(id, text, NOW) };
let first = "ffffffff-ffff-4fff-8fff-ffffffffffff";
let middle = "00000000-0000-4000-8000-000000000000";
let last = "55555555-5555-4555-8555-555555555555";
store.ingest(&key, &post(first, "one", 1), true).unwrap();
store.ingest(&key, &post(middle, "two", 2), true).unwrap();
store.ingest(&key, &post(last, "three", 3), true).unwrap();
assert!(store.mark_read(&key, "").unwrap(), "read up to the newest message");

let (marker, mentions) = store.mark_unread(&key, middle).unwrap().expect("the conversation is there");
assert_eq!((marker.as_str(), mentions), (first, 0), "the marker is the first post of the stamp");
let row = store.conversation(&key).unwrap().unwrap();
assert_eq!((row.unread, row.last_read.as_deref()), (2, Some(first)), "the marked post and the one after it are unread");
}

/// A marker that names a message the store has not got has no place among the stored ones.
/// Its id is still compared as text, which is the order of an id that carries its own.
#[test]
fn a_marker_for_a_message_the_store_has_not_got_still_compares_ids_as_text() {
let (mut store, key) = store();
store.ingest(&key, &said("8", "one", 10), true).unwrap();
store.ingest(&key, &said("9", "two", 20), true).unwrap();
assert!(store.mark_read(&key, "").unwrap());

let (marker, mentions) = store.mark_unread(&key, "10").unwrap().unwrap();
let unread = store.conversation(&key).unwrap().unwrap().unread;
assert_eq!((marker.as_str(), mentions, unread), ("9", 0, 1), "the newest stored message is before it, and the badge turns on for the one not stored");

assert!(store.apply_manual_ack(&key, "5", None).unwrap(), "another device read up to a message that is not stored");
let row = store.conversation(&key).unwrap().unwrap();
assert_eq!((row.unread, row.mentions, row.last_read.as_deref()), (2, 0, Some("5")), "both stored messages are after it");
}

#[test]
fn unread_marks_of_one_space_do_not_name_another_spaces_rows() {
let (mut store, key) = store();
Expand Down Expand Up @@ -7128,6 +7255,9 @@ mod tests {
for (id, days) in [("old", 40), ("starred-old", 40), ("app", 1), ("archived", 1), ("stranger", 1), ("hidden", 1), ("recent", 2)] {
store.ingest(&at(id), &said(&format!("{id}-1"), "hello", now - days * day), true).unwrap();
}
// A hidden row with no read marker comes back on the next live message, so this one is
// hidden again after the one above; the marker that leaves keeps it hidden.
store.forget_conversation(&at("hidden")).unwrap();
store.set_starred(&at("starred-old"), true).unwrap();
store.mark_read(&at("old"), "old-1").unwrap();
let titles = |store: &Store, filter| -> Vec<String> {
Expand Down
9 changes: 9 additions & 0 deletions e2e/scenarios/tiny-mark-unread-order/drive.linux.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash
# tiny-mark-unread-order on Linux. The lab runs this with bash while ffmpeg films the display.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
if command -v python3 >/dev/null 2>&1; then
exec python3 "$HERE/drive.py"
fi
echo "python3 is not on PATH" >&2
exit 1
9 changes: 9 additions & 0 deletions e2e/scenarios/tiny-mark-unread-order/drive.macos.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash
# tiny-mark-unread-order on macOS. The lab runs this with bash while the helper films the app window.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
if command -v python3 >/dev/null 2>&1; then
exec python3 "$HERE/drive.py"
fi
echo "python3 is not on PATH" >&2
exit 1
Loading
Loading