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
9 changes: 9 additions & 0 deletions crates/chatd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,15 @@ fn main() -> io::Result<()> {
eprintln!("prove-discord-group-members:0");
return Ok(());
}
// The lab's space-mark-all-read driver. A build without this returns to the server below and stays up.
if std::env::var("TINYCLIENT_PROVE").ok().as_deref() == Some("space-mark-all-read") {
if let Err(err) = chatd::server::prove_space_mark_all_read() {
eprintln!("space-mark-all-read: {err}");
std::process::exit(1);
}
eprintln!("prove-space-mark-all-read:0");
return Ok(());
}
// The lab's call-leave-clears driver. A build without this returns to the server below and stays up.
if std::env::var("TINYCLIENT_PROVE").ok().as_deref() == Some("call-leave-clears") {
if let Err(err) = chatd::media::prove_call_leave_clears() {
Expand Down
46 changes: 42 additions & 4 deletions crates/chatd/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1104,9 +1104,10 @@ impl Chat {
}

/// Every badge goes. Discord hears one bulk ack per account; the other networks hear the
/// read they already know. A message request is read here and not announced.
fn mark_all_read(&self, network: Option<Network>) -> Response {
let marks = match self.hub.store().unread_marks(network) {
/// read they already know. A message request is read here and not announced. `network`
/// limits it to one network; `space` to one Space's conversations.
fn mark_all_read(&self, network: Option<Network>, space: Option<Key>) -> Response {
let marks = match self.hub.store().unread_marks(network, space.as_ref()) {
Ok(marks) => marks,
Err(err) => return internal(err),
};
Expand Down Expand Up @@ -2438,7 +2439,7 @@ impl Chat {
Request::Messages { conversation, page, limit } => self.messages(conversation, page, limit),
Request::MarkRead { conversation, message_id } => self.mark_read(conversation, message_id),
Request::MarkUnread { conversation, message_id } => self.mark_unread(conversation, message_id),
Request::MarkAllRead { network } => self.mark_all_read(network),
Request::MarkAllRead { network, space } => self.mark_all_read(network, space),
Request::Forget { conversation } => self.forget_conversation(conversation),
Request::Send { conversation, client_id, text, reply_to, with } => {
let began = std::time::Instant::now();
Expand Down Expand Up @@ -3410,6 +3411,43 @@ pub fn prove_offline_queue() -> Result<(), String> {
Ok(())
}

/// The lab's space-mark-all-read driver. Reading one Space out leaves every other Space's and
/// every direct row's badge alone, and a frame from an older peer without the Space still
/// reads the whole Inbox.
pub fn prove_space_mark_all_read() -> Result<(), String> {
match serde_json::from_value::<Request>(serde_json::json!({"op": "mark_all_read"})) {
Ok(Request::MarkAllRead { network: None, space: None }) => {}
_ => return Err("an older frame without a Space did not read".into()),
}
let mut store = Store::open(std::path::Path::new(":memory:")).map_err(|err| err.to_string())?;
let account = AccountKey { network: Network::Discord, account: "ada".into() };
let mut room = crate::store::ConversationRow::new("general", ConversationKind::Channel, "general");
room.space = Some("4000".into());
store.upsert_conversation(&account, &room).map_err(|err| err.to_string())?;
store
.upsert_conversation(&account, &crate::store::ConversationRow::new("elsewhere", ConversationKind::Channel, "elsewhere"))
.map_err(|err| err.to_string())?;
let general = Key::new(&account, "general");
let elsewhere = Key::new(&account, "elsewhere");
store.ingest(&general, &Message::plain("8", "mara", "for this space", 10, false), true).map_err(|err| err.to_string())?;
store.ingest(&elsewhere, &Message::plain("9", "mara", "for another", 20, false), true).map_err(|err| err.to_string())?;
let chat = Arc::new(Chat::new(store));
let read = chat.handle(Request::MarkAllRead { network: Some(Network::Discord), space: Some(Key::new(&account, "4000")) });
if !matches!(read, Response::Ok) {
return Err(format!("the space-scoped read was refused: {read:?}"));
}
let row = |chat: &Chat, key: &Key| -> Result<Conversation, String> {
chat.hub.store().conversation(key).map_err(|err| err.to_string())?.ok_or_else(|| "the row vanished".into())
};
if row(&chat, &general)?.unread != 0 {
return Err("a conversation of the Space kept its badge".into());
}
if row(&chat, &elsewhere)?.unread != 1 {
return Err("another Space's badge was cleared".into());
}
Ok(())
}

/// Who we are on this conversation's account for a pending outgoing row: a prior message of
/// ours in this chat when one names us (per-chat nick/avatar), else the cached self person.
/// Never the account or workspace label. "You" only while nothing of us is cached.
Expand Down
64 changes: 57 additions & 7 deletions crates/chatd/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2248,14 +2248,20 @@ impl Store {
}

/// Every conversation with a badge. The message id is the newest known, for the ack.
/// The bool is a message request: read here, and not told to the network.
pub fn unread_marks(&self, network: Option<Network>) -> rusqlite::Result<Vec<(Key, String, bool)>> {
/// The bool is a message request: read here, and not told to the network. `network` limits
/// it to one network; `space` to one Space's conversations, which are that Space's account's.
pub fn unread_marks(&self, network: Option<Network>, space: Option<&Key>) -> rusqlite::Result<Vec<(Key, String, bool)>> {
let mut stmt = self.db.prepare(
"SELECT network, account, id, preview_id, last_read, special FROM conversation
WHERE (unread > 0 OR mentions > 0) AND (?1 IS NULL OR network = ?1)",
WHERE (unread > 0 OR mentions > 0) AND (?1 IS NULL OR network = ?1)
AND (?2 IS NULL OR (network = ?3 AND account = ?4 AND space = ?2))",
)?;
let network = network.map(|network| word(&network));
let rows = stmt.query_map(params![network], |row| {
let (space_id, space_network, space_account) = match space {
Some(space) => (Some(space.id.as_str()), Some(word(&space.network)), Some(space.account.as_str())),
None => (None, None, None),
};
let rows = stmt.query_map(params![network, space_id, space_network, space_account], |row| {
let key = Key {
network: from_word(row.get(0)?)?,
account: row.get(1)?,
Expand Down Expand Up @@ -3964,7 +3970,7 @@ mod tests {
store.ingest(&key, &earlier, true).unwrap();
assert!(store.mark_read(&key, &earlier.id).unwrap());
store.ingest(&key, &later, true).unwrap();
let marks = store.unread_marks(Some(Network::Discord)).unwrap();
let marks = store.unread_marks(Some(Network::Discord), None).unwrap();
assert!(marks.iter().any(|(found, marker, _)| found == &key && marker == &later.id));
store.set_counts(&key, 0, 0, None, 20).unwrap();
assert_eq!(store.conversation(&key).unwrap().unwrap().unread, 1);
Expand Down Expand Up @@ -4130,7 +4136,7 @@ mod tests {
let row = store.conversation(&key).unwrap().unwrap();
assert_eq!((row.unread, row.last_read.as_deref()), (1, Some(earlier)));
assert_eq!(store.preview_id(&key).unwrap(), later);
let marks = store.unread_marks(Some(Network::Discord)).unwrap();
let marks = store.unread_marks(Some(Network::Discord), None).unwrap();
assert!(
marks.iter().any(|(found, marker, request)| found == &key && marker == later && !request),
"the ack is the newer message, not the uuid that sorts first"
Expand Down Expand Up @@ -4165,7 +4171,7 @@ mod tests {

// A newer live message is unread again; a stale network count must not invent that.
store.ingest(&dm, &said("30", "again", 30), true).unwrap();
let marks = store.unread_marks(Some(Network::Discord)).unwrap();
let marks = store.unread_marks(Some(Network::Discord), None).unwrap();
assert!(marks.iter().any(|(found, marker, request)| found == &dm && marker == "30" && !request));
assert!(store.forget_conversation(&dm).unwrap());
let row = store.conversation(&dm).unwrap().unwrap();
Expand All @@ -4182,6 +4188,50 @@ mod tests {
let _ = key;
}

#[test]
fn unread_marks_of_one_space_do_not_name_another_spaces_rows() {
let (mut store, key) = store();
let account = key.account();
let mut channel = ConversationRow::new("announcements", ConversationKind::Channel, "#announcements");
channel.space = Some("4000".into());
store.upsert_conversation(&account, &channel).unwrap();
let in_space = Key::new(&account, "announcements");
store.ingest(&in_space, &said("8", "hello", 10), true).unwrap();
store.ingest(&key, &said("9", "dm hello", 20), true).unwrap();

let space = Key::new(&account, "4000");
let marks = store.unread_marks(None, Some(&space)).unwrap();
assert_eq!(marks.len(), 1, "only the space's conversations are named");
assert_eq!(marks[0].0, in_space);
// Without a space everything with a badge is named, as before.
let all = store.unread_marks(None, None).unwrap();
assert!(all.iter().any(|(found, _, _)| found == &in_space));
assert!(all.iter().any(|(found, _, _)| found == &key));
let discord = store.unread_marks(Some(Network::Discord), None).unwrap();
assert_eq!(discord.len(), 2);
}

#[test]
fn a_local_unread_survives_a_stale_count_and_yields_to_a_newer_read() {
let (mut store, key) = store();
store.ingest(&key, &said("8", "one", 10), true).unwrap();
store.ingest(&key, &said("9", "two", 20), true).unwrap();
assert_eq!(
store.mark_unread(&key, "9").unwrap().map(|(marker, _)| marker),
Some("8".to_owned()),
"the marker moves to the message before the one marked"
);
assert_eq!(store.conversation(&key).unwrap().unwrap().unread, 1);
// A network word that is not newer than what is stored cannot undo the mark: nothing
// read it, the list is just stale.
store.set_counts(&key, 0, 0, None, 20).unwrap();
assert!(store.conversation(&key).unwrap().unwrap().unread >= 1, "a stale count cleared a local unread");
// Another device read past the mark for real: the badge goes and the marker follows it.
store.set_counts(&key, 0, 0, Some("9"), 30).unwrap();
let row = store.conversation(&key).unwrap().unwrap();
assert_eq!((row.unread, row.last_read.as_deref()), (0, Some("9")));
}

#[test]
fn the_inbox_holds_what_needs_me_and_leaves_plain_channels_to_their_space() {
let (mut store, key) = store();
Expand Down
37 changes: 36 additions & 1 deletion crates/chatd/tests/discord.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1661,7 +1661,7 @@ fn marking_a_message_unread_moves_the_marker_back_and_a_manual_ack_does_too() {
fn marking_everything_read_tells_discord_in_one_bulk_ack() {
let world = World::start();
assert!(world.conversation("3001").unread > 0);
assert_eq!(world.ask(Request::MarkAllRead { network: None }), Response::Ok);
assert_eq!(world.ask(Request::MarkAllRead { network: None, space: None }), Response::Ok);
assert_eq!(world.conversation("3001").unread, 0);
let bulk = wait("the bulk ack", || {
let found = world.discord.requests_to("POST", "/read-states/ack-bulk");
Expand All @@ -1673,6 +1673,41 @@ fn marking_everything_read_tells_discord_in_one_bulk_ack() {
assert!(named, "channel 3001 is in the bulk ack");
}

#[test]
fn marking_one_space_read_leaves_the_other_spaces_badges_alone() {
let world = World::start();
// The ready state carries badges in guild 4000 (4101, 4104, and muted 4105), in guild
// 5000 (5001) and among the direct messages (3001).
wait("the badges from the ready state", || {
let (four, five, dm) = (world.conversation("4101").unread, world.conversation("5001").unread, world.conversation("3001").unread);
(four > 0 && five > 0 && dm > 0).then_some(())
});
assert_eq!(
world.ask(Request::MarkAllRead { network: Some(Network::Discord), space: Some(world.key("4000")) }),
Response::Ok
);
assert_eq!(world.conversation("4101").unread, 0, "the space's channels are read");
assert_eq!(world.conversation("4104").unread, 0);
assert_eq!(world.conversation("4105").unread, 0, "a muted channel of the space is read too");
assert!(world.conversation("5001").unread > 0, "another space keeps its badge");
assert!(world.conversation("3001").unread > 0, "a direct message keeps its badge");
let bulks = wait("the bulk ack for the space", || {
let found = world.discord.requests_to("POST", "/read-states/ack-bulk");
(!found.is_empty()).then_some(found)
});
assert!(
bulks.iter().any(|seen| seen.body["read_states"].as_array().is_some_and(|rows| rows.iter().any(|row| row["channel_id"] == "4101"))),
"the space's channel is acked"
);
for seen in &bulks {
let named = |channel: &str| {
seen.body["read_states"].as_array().is_some_and(|rows| rows.iter().any(|row| row["channel_id"] == channel))
};
assert!(!named("5001"), "another space's channel is not acked");
assert!(!named("3001"), "a direct message is not acked by a space's read");
}
}

#[test]
fn a_dropped_socket_resumes_and_a_refused_token_expires_the_account() {
let world = World::start();
Expand Down
7 changes: 6 additions & 1 deletion crates/protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1294,10 +1294,15 @@ pub enum Request {
message_id: String,
},
/// Every conversation with a badge is read, here and on the network. `network` limits it to
/// one; `None` is the whole Inbox. Message requests are read here only.
/// one; `space` to one Space's conversations; both `None` is the whole Inbox. Message
/// requests are read here only.
MarkAllRead {
#[serde(default, skip_serializing_if = "Option::is_none")]
network: Option<Network>,
/// The Space to read out, the account it belongs to and the network's own id. An older
/// peer that does not know the field ignores it and hears the wider request.
#[serde(default, skip_serializing_if = "Option::is_none")]
space: Option<Key>,
},
/// Drops this conversation's cached messages and its badge. A direct or group conversation
/// leaves the Inbox until a newer message arrives. The network is not asked to delete
Expand Down
15 changes: 12 additions & 3 deletions crates/tinyclient/src/gui/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -809,13 +809,14 @@ impl Shell {
);
}
}
// CONTRACT: of the Space menu in `02-layout-navigation.md` only pinning has a
// request behind it. Nothing marks a whole Space read or mutes it, and a Space
// carries no link to open it in the network's app, so those items are left out.
// CONTRACT: of the Space menu in `02-layout-navigation.md` pinning and mark-as-read
// have a request behind them. Nothing mutes a whole Space, and a Space carries no
// link to open it in the network's app, so those items are left out.
Menu::Space(space) => {
let pinned = self.sidebar_state.pins.contains(space);
let key = space.clone();
let shown = space.clone();
let read = space.clone();
items.push(
menu_item("details", Some("icons/info.svg"), "Details", None)
.on_click(cx.listener(move |this, _, _, cx| {
Expand All @@ -832,6 +833,14 @@ impl Shell {
}))
.into_any_element(),
);
items.push(
menu_item("space-read", Some("icons/check.svg"), "Mark as read", None)
.on_click(cx.listener(move |this, _, _, cx| {
this.close_menu(cx);
this.mark_space_read(read.clone(), cx);
}))
.into_any_element(),
);
}
Menu::Row(conversation, _) => {
let (key, starred) = (conversation.key.clone(), conversation.starred);
Expand Down
22 changes: 21 additions & 1 deletion crates/tinyclient/src/gui/sidebar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,7 @@ impl Shell {
}

pub(super) fn mark_all_read(&mut self, cx: &mut Context<Self>) {
let request = Request::MarkAllRead { network: None };
let request = Request::MarkAllRead { network: None, space: None };
self.off_thread(cx, move || ask(&request), |this, answer, cx| {
match answer {
Ok(Response::Ok) => {
Expand All @@ -706,6 +706,26 @@ impl Shell {
});
}

/// Everything with a badge in one Space is read, here and where the network keeps a read
/// state. Direct messages and other Spaces are left alone.
pub(super) fn mark_space_read(&mut self, space: Key, cx: &mut Context<Self>) {
let request = Request::MarkAllRead { network: Some(space.network), space: Some(space) };
self.off_thread(cx, move || ask(&request), |this, answer, cx| {
match answer {
Ok(Response::Ok) => {
this.sidebar_state.muted_news.clear();
this.sidebar_state.muted_open = false;
this.toast(Some(("icons/check.svg", theme::text_soft())), "Marked as read", cx);
}
Ok(Response::Error { detail, .. }) => this.toast(Some(("icons/circle-alert.svg", theme::danger())), detail, cx),
Err(err) => this.toast(Some(("icons/circle-alert.svg", theme::danger())), crate::client::trouble_words("inbox", &err), cx),
_ => {}
}
let pages = this.sidebar_state.inbox.stale();
this.load_inbox(pages, cx);
});
}

/// Removes a direct or group conversation from this Inbox. The network keeps the messages.
pub(super) fn forget_conversation(&mut self, conversation: Conversation, cx: &mut Context<Self>) {
let title = conversation.title.clone();
Expand Down
9 changes: 9 additions & 0 deletions e2e/scenarios/space-mark-all-read/drive.linux.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash
# space-mark-all-read 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/space-mark-all-read/drive.macos.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash
# space-mark-all-read on macOS. 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
Loading
Loading