BlueGit

ict rusty-teams

fix(sidebar): second review findings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-12 · 7 weeks ago

Hash
924c1353851c407925b5fc939949689c82ed8ac5
Parent
6d166892
9 files changed +296 −83
crates/app/src/app_state.rs +1 −1
@@ -787,7 +787,7 @@ impl AppState {
787 787 self.refresh_own_status(cx);
788 788 cx.emit(AppEvent::Status);
789 789 }
790 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx),
790 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
791 791 BackendEvent::Core(
792 792 CoreEvent::MessagesChanged { conversation_id }
793 793 | CoreEvent::ReceiptsChanged { conversation_id },
@@ -787,7 +787,7 @@ impl AppState {
787 self.refresh_own_status(cx);
787 self.refresh_own_status(cx);
788 cx.emit(AppEvent::Status);
788 cx.emit(AppEvent::Status);
789 }
789 }
790 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx),
790 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
791 BackendEvent::Core(
791 BackendEvent::Core(
792 CoreEvent::MessagesChanged { conversation_id }
792 CoreEvent::MessagesChanged { conversation_id }
793 | CoreEvent::ReceiptsChanged { conversation_id },
793 | CoreEvent::ReceiptsChanged { conversation_id },
crates/app/src/chat_actions.rs +37 −8
@@ -238,18 +238,47 @@ impl AppState {
238 238 let _ = self.store.remove_chats(&[chat_id.to_owned()]);
239 239 self.reload_sidebar(cx);
240 240 if was_selected {
241 match next {
242 Some(next_id) => self.select(Selection::Chat(next_id), cx),
243 None => {
244 self.selection = None;
245 self.keep_unread = None;
246 cx.emit(crate::app_state::AppEvent::Selection);
247 cx.notify();
248 }
241 self.leave_removed_selection(next, cx);
242 }
243 }
244
245 fn leave_removed_selection(&mut self, next: Option<String>, cx: &mut Context<Self>) {
246 match next {
247 Some(next_id) => self.select(Selection::Chat(next_id), cx),
248 None => {
249 self.selection = None;
250 self.keep_unread = None;
251 cx.emit(crate::app_state::AppEvent::Selection);
252 cx.notify();
249 253 }
250 254 }
251 255 }
252 256
257 pub(crate) fn reload_sidebar_after_sync(&mut self, cx: &mut Context<Self>) {
258 let selected = match &self.selection {
259 Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
260 _ => None,
261 };
262 let is_listed = |state: &Self, chat_id: &str| {
263 state.sidebar.chats.iter().any(|chat| chat.id == chat_id)
264 };
265 let was_listed = selected
266 .as_deref()
267 .is_some_and(|chat_id| is_listed(self, chat_id));
268 let next = selected
269 .as_deref()
270 .filter(|_| was_listed)
271 .and_then(|chat_id| self.next_chat_after(chat_id));
272 self.reload_sidebar(cx);
273 let removed = was_listed
274 && selected
275 .as_deref()
276 .is_some_and(|chat_id| !is_listed(self, chat_id));
277 if removed {
278 self.leave_removed_selection(next, cx);
279 }
280 }
281
253 282 fn restore_chat_locally(&mut self, chat: &ChatRecord, cx: &mut Context<Self>) {
254 283 let _ = self.store.upsert_chats(std::slice::from_ref(chat));
255 284 let _ = self.store.set_chat_muted(&chat.id, chat.muted);
@@ -238,18 +238,47 @@ impl AppState {
238 let _ = self.store.remove_chats(&[chat_id.to_owned()]);
238 let _ = self.store.remove_chats(&[chat_id.to_owned()]);
239 self.reload_sidebar(cx);
239 self.reload_sidebar(cx);
240 if was_selected {
240 if was_selected {
241 match next {
241 self.leave_removed_selection(next, cx);
242 Some(next_id) => self.select(Selection::Chat(next_id), cx),
242 }
243 None => {
243 }
244 self.selection = None;
244
245 self.keep_unread = None;
245 fn leave_removed_selection(&mut self, next: Option<String>, cx: &mut Context<Self>) {
246 cx.emit(crate::app_state::AppEvent::Selection);
246 match next {
247 cx.notify();
247 Some(next_id) => self.select(Selection::Chat(next_id), cx),
248 }
248 None => {
249 self.selection = None;
250 self.keep_unread = None;
251 cx.emit(crate::app_state::AppEvent::Selection);
252 cx.notify();
249 }
253 }
250 }
254 }
251 }
255 }
252
256
257 pub(crate) fn reload_sidebar_after_sync(&mut self, cx: &mut Context<Self>) {
258 let selected = match &self.selection {
259 Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
260 _ => None,
261 };
262 let is_listed = |state: &Self, chat_id: &str| {
263 state.sidebar.chats.iter().any(|chat| chat.id == chat_id)
264 };
265 let was_listed = selected
266 .as_deref()
267 .is_some_and(|chat_id| is_listed(self, chat_id));
268 let next = selected
269 .as_deref()
270 .filter(|_| was_listed)
271 .and_then(|chat_id| self.next_chat_after(chat_id));
272 self.reload_sidebar(cx);
273 let removed = was_listed
274 && selected
275 .as_deref()
276 .is_some_and(|chat_id| !is_listed(self, chat_id));
277 if removed {
278 self.leave_removed_selection(next, cx);
279 }
280 }
281
253 fn restore_chat_locally(&mut self, chat: &ChatRecord, cx: &mut Context<Self>) {
282 fn restore_chat_locally(&mut self, chat: &ChatRecord, cx: &mut Context<Self>) {
254 let _ = self.store.upsert_chats(std::slice::from_ref(chat));
283 let _ = self.store.upsert_chats(std::slice::from_ref(chat));
255 let _ = self.store.set_chat_muted(&chat.id, chat.muted);
284 let _ = self.store.set_chat_muted(&chat.id, chat.muted);
crates/app/src/sidebar_model.rs +29 −6
@@ -313,8 +313,16 @@ pub fn wants_older_chats(
313 313 viewport_bottom: f32,
314 314 scroll_top: f32,
315 315 last_trigger_top: Option<f32>,
316 loading: bool,
316 317 ) -> bool {
317 others_end.is_some_and(|end| end <= viewport_bottom) && last_trigger_top != Some(scroll_top)
318 !loading
319 && others_end.is_some_and(|end| end <= viewport_bottom)
320 && last_trigger_top != Some(scroll_top)
321 }
322
323 pub fn older_chats_trigger_resets(previous: (bool, bool), current: (bool, bool)) -> bool {
324 let ((had_more, was_loading), (has_more, is_loading)) = (previous, current);
325 (was_loading && !is_loading) || (!had_more && has_more)
318 326 }
319 327
320 328 pub fn visible_chat_ids(sections: &[Section]) -> Vec<&str> {
@@ -960,11 +968,26 @@ mod tests {
960 968
961 969 #[test]
962 970 fn older_chats_load_only_when_the_end_of_other_chats_is_on_screen_once_per_scroll_position() {
963 assert!(wants_older_chats(Some(900.), 1000., 0., None));
964 assert!(!wants_older_chats(Some(1500.), 1000., 0., None));
965 assert!(!wants_older_chats(None, 1000., 0., None));
966 assert!(!wants_older_chats(Some(900.), 1000., 0., Some(0.)));
967 assert!(wants_older_chats(Some(900.), 1000., 120., Some(0.)));
971 assert!(wants_older_chats(Some(900.), 1000., 0., None, false));
972 assert!(!wants_older_chats(Some(1500.), 1000., 0., None, false));
973 assert!(!wants_older_chats(None, 1000., 0., None, false));
974 assert!(!wants_older_chats(Some(900.), 1000., 0., Some(0.), false));
975 assert!(wants_older_chats(Some(900.), 1000., 120., Some(0.), false));
976 }
977
978 #[test]
979 fn a_running_load_never_consumes_the_trigger() {
980 assert!(!wants_older_chats(Some(900.), 1000., 0., None, true));
981 }
982
983 #[test]
984 fn the_trigger_resets_when_a_load_ends_or_more_chats_appear_but_not_while_idle() {
985 assert!(older_chats_trigger_resets((true, true), (true, false)));
986 assert!(older_chats_trigger_resets((true, true), (false, false)));
987 assert!(older_chats_trigger_resets((false, false), (true, false)));
988 assert!(!older_chats_trigger_resets((true, false), (true, false)));
989 assert!(!older_chats_trigger_resets((true, false), (true, true)));
990 assert!(!older_chats_trigger_resets((false, false), (false, false)));
968 991 }
969 992
970 993 #[test]
@@ -313,8 +313,16 @@ pub fn wants_older_chats(
313 viewport_bottom: f32,
313 viewport_bottom: f32,
314 scroll_top: f32,
314 scroll_top: f32,
315 last_trigger_top: Option<f32>,
315 last_trigger_top: Option<f32>,
316 loading: bool,
316) -> bool {
317) -> bool {
317 others_end.is_some_and(|end| end <= viewport_bottom) && last_trigger_top != Some(scroll_top)
318 !loading
319 && others_end.is_some_and(|end| end <= viewport_bottom)
320 && last_trigger_top != Some(scroll_top)
321}
322
323pub fn older_chats_trigger_resets(previous: (bool, bool), current: (bool, bool)) -> bool {
324 let ((had_more, was_loading), (has_more, is_loading)) = (previous, current);
325 (was_loading && !is_loading) || (!had_more && has_more)
318}
326}
319
327
320pub fn visible_chat_ids(sections: &[Section]) -> Vec<&str> {
328pub fn visible_chat_ids(sections: &[Section]) -> Vec<&str> {
@@ -960,11 +968,26 @@ mod tests {
960
968
961 #[test]
969 #[test]
962 fn older_chats_load_only_when_the_end_of_other_chats_is_on_screen_once_per_scroll_position() {
970 fn older_chats_load_only_when_the_end_of_other_chats_is_on_screen_once_per_scroll_position() {
963 assert!(wants_older_chats(Some(900.), 1000., 0., None));
971 assert!(wants_older_chats(Some(900.), 1000., 0., None, false));
964 assert!(!wants_older_chats(Some(1500.), 1000., 0., None));
972 assert!(!wants_older_chats(Some(1500.), 1000., 0., None, false));
965 assert!(!wants_older_chats(None, 1000., 0., None));
973 assert!(!wants_older_chats(None, 1000., 0., None, false));
966 assert!(!wants_older_chats(Some(900.), 1000., 0., Some(0.)));
974 assert!(!wants_older_chats(Some(900.), 1000., 0., Some(0.), false));
967 assert!(wants_older_chats(Some(900.), 1000., 120., Some(0.)));
975 assert!(wants_older_chats(Some(900.), 1000., 120., Some(0.), false));
976 }
977
978 #[test]
979 fn a_running_load_never_consumes_the_trigger() {
980 assert!(!wants_older_chats(Some(900.), 1000., 0., None, true));
981 }
982
983 #[test]
984 fn the_trigger_resets_when_a_load_ends_or_more_chats_appear_but_not_while_idle() {
985 assert!(older_chats_trigger_resets((true, true), (true, false)));
986 assert!(older_chats_trigger_resets((true, true), (false, false)));
987 assert!(older_chats_trigger_resets((false, false), (true, false)));
988 assert!(!older_chats_trigger_resets((true, false), (true, false)));
989 assert!(!older_chats_trigger_resets((true, false), (true, true)));
990 assert!(!older_chats_trigger_resets((false, false), (false, false)));
968 }
991 }
969
992
970 #[test]
993 #[test]
crates/app/src/views/sidebar.rs +8 −1
@@ -28,7 +28,7 @@ use crate::notice::truncated;
28 28 use crate::sidebar_model::{
29 29 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section,
30 30 SectionInput, SectionKind, Step, build_sections, step_id,
31 visible_channel_ids, wants_older_chats,
31 older_chats_trigger_resets, visible_channel_ids, wants_older_chats,
32 32 };
33 33 use crate::theme;
34 34
@@ -293,6 +293,7 @@ pub struct SidebarView {
293 293 hidden_teams_open: bool,
294 294 chats_scroll: ScrollHandle,
295 295 older_chats_trigger_top: Cell<Option<f32>>,
296 older_chats_seen: Cell<(bool, bool)>,
296 297 channels_scroll: ScrollHandle,
297 298 calls_scroll: ScrollHandle,
298 299 _subscription: Subscription,
@@ -407,6 +408,7 @@ impl SidebarView {
407 408 hidden_teams_open: false,
408 409 chats_scroll: ScrollHandle::new(),
409 410 older_chats_trigger_top: Cell::new(None),
411 older_chats_seen: Cell::new((false, false)),
410 412 channels_scroll: ScrollHandle::new(),
411 413 calls_scroll: ScrollHandle::new(),
412 414 _subscription: subscription,
@@ -938,12 +940,17 @@ impl SidebarView {
938 940 }
939 941 }
940 942 let (has_older, loading_older) = self.state.read(cx).older_chats();
943 let previous = self.older_chats_seen.replace((has_older, loading_older));
944 if older_chats_trigger_resets(previous, (has_older, loading_older)) {
945 self.older_chats_trigger_top.set(None);
946 }
941 947 if has_older
942 948 && wants_older_chats(
943 949 others_end,
944 950 top + height,
945 951 top,
946 952 self.older_chats_trigger_top.get(),
953 loading_older,
947 954 )
948 955 {
949 956 self.older_chats_trigger_top.set(Some(top));
@@ -28,7 +28,7 @@ use crate::notice::truncated;
28use crate::sidebar_model::{
28use crate::sidebar_model::{
29 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section,
29 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section,
30 SectionInput, SectionKind, Step, build_sections, step_id,
30 SectionInput, SectionKind, Step, build_sections, step_id,
31 visible_channel_ids, wants_older_chats,
31 older_chats_trigger_resets, visible_channel_ids, wants_older_chats,
32};
32};
33use crate::theme;
33use crate::theme;
34
34
@@ -293,6 +293,7 @@ pub struct SidebarView {
293 hidden_teams_open: bool,
293 hidden_teams_open: bool,
294 chats_scroll: ScrollHandle,
294 chats_scroll: ScrollHandle,
295 older_chats_trigger_top: Cell<Option<f32>>,
295 older_chats_trigger_top: Cell<Option<f32>>,
296 older_chats_seen: Cell<(bool, bool)>,
296 channels_scroll: ScrollHandle,
297 channels_scroll: ScrollHandle,
297 calls_scroll: ScrollHandle,
298 calls_scroll: ScrollHandle,
298 _subscription: Subscription,
299 _subscription: Subscription,
@@ -407,6 +408,7 @@ impl SidebarView {
407 hidden_teams_open: false,
408 hidden_teams_open: false,
408 chats_scroll: ScrollHandle::new(),
409 chats_scroll: ScrollHandle::new(),
409 older_chats_trigger_top: Cell::new(None),
410 older_chats_trigger_top: Cell::new(None),
411 older_chats_seen: Cell::new((false, false)),
410 channels_scroll: ScrollHandle::new(),
412 channels_scroll: ScrollHandle::new(),
411 calls_scroll: ScrollHandle::new(),
413 calls_scroll: ScrollHandle::new(),
412 _subscription: subscription,
414 _subscription: subscription,
@@ -938,12 +940,17 @@ impl SidebarView {
938 }
940 }
939 }
941 }
940 let (has_older, loading_older) = self.state.read(cx).older_chats();
942 let (has_older, loading_older) = self.state.read(cx).older_chats();
943 let previous = self.older_chats_seen.replace((has_older, loading_older));
944 if older_chats_trigger_resets(previous, (has_older, loading_older)) {
945 self.older_chats_trigger_top.set(None);
946 }
941 if has_older
947 if has_older
942 && wants_older_chats(
948 && wants_older_chats(
943 others_end,
949 others_end,
944 top + height,
950 top + height,
945 top,
951 top,
946 self.older_chats_trigger_top.get(),
952 self.older_chats_trigger_top.get(),
953 loading_older,
947 )
954 )
948 {
955 {
949 self.older_chats_trigger_top.set(Some(top));
956 self.older_chats_trigger_top.set(Some(top));
crates/core/src/actions.rs +8 −8
@@ -7,7 +7,6 @@ use store::MessageRecord;
7 7
8 8 use crate::engine::{Conversation, META_USER_ID, SyncEngine};
9 9 use crate::error::{Error, Result};
10 use crate::hidden_chats::LocallyHidden;
11 10 use crate::links::LinkPreview;
12 11 use crate::mapping::{chat_record, message_record};
13 12 use crate::markdown::markdown_to_html;
@@ -421,9 +420,12 @@ impl<R: Remote> SyncEngine<R> {
421 420 let user_id = self.my_user_id().await?;
422 421 let tenant_id = self.my_tenant_id(chat_id).await?;
423 422 self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
424 let mut locally = LocallyHidden::load(&self.store);
425 locally.insert(chat_id, Utc::now());
426 locally.save(&self.store)?;
423 let hidden_after = self
424 .store
425 .chat(chat_id)?
426 .and_then(|chat| chat.last_message_at)
427 .unwrap_or_else(Utc::now);
428 self.with_locally_hidden(|locally| locally.hide(chat_id, hidden_after))?;
427 429 self.store.remove_chats(&[chat_id.to_owned()])?;
428 430 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
429 431 Ok(())
@@ -435,10 +437,8 @@ impl<R: Remote> SyncEngine<R> {
435 437 self.remote
436 438 .unhide_chat(chat_id, &user_id, &tenant_id)
437 439 .await?;
438 let mut locally = LocallyHidden::load(&self.store);
439 if locally.remove(chat_id) {
440 locally.save(&self.store)?;
441 }
440 let now = Utc::now();
441 self.with_locally_hidden(|locally| locally.unhide(chat_id, now))?;
442 442 self.refresh_sidebar_full().await?;
443 443 Ok(())
444 444 }
@@ -7,7 +7,6 @@ use store::MessageRecord;
7
7
8use crate::engine::{Conversation, META_USER_ID, SyncEngine};
8use crate::engine::{Conversation, META_USER_ID, SyncEngine};
9use crate::error::{Error, Result};
9use crate::error::{Error, Result};
10use crate::hidden_chats::LocallyHidden;
11use crate::links::LinkPreview;
10use crate::links::LinkPreview;
12use crate::mapping::{chat_record, message_record};
11use crate::mapping::{chat_record, message_record};
13use crate::markdown::markdown_to_html;
12use crate::markdown::markdown_to_html;
@@ -421,9 +420,12 @@ impl<R: Remote> SyncEngine<R> {
421 let user_id = self.my_user_id().await?;
420 let user_id = self.my_user_id().await?;
422 let tenant_id = self.my_tenant_id(chat_id).await?;
421 let tenant_id = self.my_tenant_id(chat_id).await?;
423 self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
422 self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
424 let mut locally = LocallyHidden::load(&self.store);
423 let hidden_after = self
425 locally.insert(chat_id, Utc::now());
424 .store
426 locally.save(&self.store)?;
425 .chat(chat_id)?
426 .and_then(|chat| chat.last_message_at)
427 .unwrap_or_else(Utc::now);
428 self.with_locally_hidden(|locally| locally.hide(chat_id, hidden_after))?;
427 self.store.remove_chats(&[chat_id.to_owned()])?;
429 self.store.remove_chats(&[chat_id.to_owned()])?;
428 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
430 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
429 Ok(())
431 Ok(())
@@ -435,10 +437,8 @@ impl<R: Remote> SyncEngine<R> {
435 self.remote
437 self.remote
436 .unhide_chat(chat_id, &user_id, &tenant_id)
438 .unhide_chat(chat_id, &user_id, &tenant_id)
437 .await?;
439 .await?;
438 let mut locally = LocallyHidden::load(&self.store);
440 let now = Utc::now();
439 if locally.remove(chat_id) {
441 self.with_locally_hidden(|locally| locally.unhide(chat_id, now))?;
440 locally.save(&self.store)?;
441 }
442 self.refresh_sidebar_full().await?;
442 self.refresh_sidebar_full().await?;
443 Ok(())
443 Ok(())
444 }
444 }
crates/core/src/engine.rs +2 −0
@@ -130,6 +130,7 @@ pub struct SyncEngine<R: Remote = Graph> {
130 130 pub(crate) links_backfilled: Mutex<HashSet<String>>,
131 131 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
132 132 pub(crate) chat_paging: Mutex<ChatPaging>,
133 pub(crate) locally_hidden_lock: Mutex<()>,
133 134 }
134 135
135 136 impl<R: Remote> SyncEngine<R> {
@@ -163,6 +164,7 @@ impl<R: Remote> SyncEngine<R> {
163 164 links_backfilled: Mutex::new(HashSet::new()),
164 165 chat_states: Mutex::new(HashMap::new()),
165 166 chat_paging,
167 locally_hidden_lock: Mutex::new(()),
166 168 }
167 169 }
168 170
@@ -130,6 +130,7 @@ pub struct SyncEngine<R: Remote = Graph> {
130 pub(crate) links_backfilled: Mutex<HashSet<String>>,
130 pub(crate) links_backfilled: Mutex<HashSet<String>>,
131 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
131 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
132 pub(crate) chat_paging: Mutex<ChatPaging>,
132 pub(crate) chat_paging: Mutex<ChatPaging>,
133 pub(crate) locally_hidden_lock: Mutex<()>,
133}
134}
134
135
135impl<R: Remote> SyncEngine<R> {
136impl<R: Remote> SyncEngine<R> {
@@ -163,6 +164,7 @@ impl<R: Remote> SyncEngine<R> {
163 links_backfilled: Mutex::new(HashSet::new()),
164 links_backfilled: Mutex::new(HashSet::new()),
164 chat_states: Mutex::new(HashMap::new()),
165 chat_states: Mutex::new(HashMap::new()),
165 chat_paging,
166 chat_paging,
167 locally_hidden_lock: Mutex::new(()),
166 }
168 }
167 }
169 }
168
170
crates/core/src/hidden_chats.rs +162 −39
@@ -1,18 +1,27 @@
1 1 use std::collections::HashMap;
2 2
3 3 use chatsvc::ConversationState;
4 use chrono::{DateTime, TimeZone, Utc};
4 use chrono::{DateTime, Duration, TimeZone, Utc};
5 5 use graph::Chat;
6 6 use store::Store;
7 7
8 use crate::engine::SyncEngine;
8 9 use crate::error::Result;
9 10 use crate::mapping::graph_hidden;
11 use crate::remote::Remote;
10 12
11 13 const META_LOCALLY_HIDDEN: &str = "locally_hidden_chats";
14 const HIDE_PREFIX: &str = "hide";
15 const UNHIDE_PREFIX: &str = "unhide";
16
17 fn unhide_override_window() -> Duration {
18 Duration::minutes(10)
19 }
12 20
13 21 #[derive(Debug, Clone, Default, PartialEq, Eq)]
14 22 pub(crate) struct LocallyHidden {
15 hidden_at: HashMap<String, DateTime<Utc>>,
23 hidden_after: HashMap<String, DateTime<Utc>>,
24 unhidden_at: HashMap<String, DateTime<Utc>>,
16 25 }
17 26
18 27 impl LocallyHidden {
@@ -22,34 +31,69 @@ impl LocallyHidden {
22 31 .ok()
23 32 .flatten()
24 33 .unwrap_or_default();
25 let hidden_at = text
26 .lines()
27 .filter_map(|line| {
28 let (chat_id, millis) = line.rsplit_once('\t')?;
29 let at = Utc.timestamp_millis_opt(millis.parse().ok()?).single()?;
30 Some((chat_id.to_owned(), at))
31 })
32 .collect();
33 LocallyHidden { hidden_at }
34 let mut locally = LocallyHidden::default();
35 for line in text.lines() {
36 let mut fields = line.splitn(3, '\t');
37 let (Some(prefix), Some(chat_id), Some(millis)) =
38 (fields.next(), fields.next(), fields.next())
39 else {
40 continue;
41 };
42 let Some(at) = millis
43 .parse()
44 .ok()
45 .and_then(|millis| Utc.timestamp_millis_opt(millis).single())
46 else {
47 continue;
48 };
49 match prefix {
50 HIDE_PREFIX => locally.hidden_after.insert(chat_id.to_owned(), at),
51 UNHIDE_PREFIX => locally.unhidden_at.insert(chat_id.to_owned(), at),
52 _ => None,
53 };
54 }
55 locally
34 56 }
35 57
36 58 pub(crate) fn save(&self, store: &Store) -> Result<()> {
37 let mut lines: Vec<String> = self
38 .hidden_at
39 .iter()
40 .map(|(chat_id, at)| format!("{chat_id}\t{}", at.timestamp_millis()))
41 .collect();
59 let mut lines: Vec<String> = [
60 (HIDE_PREFIX, &self.hidden_after),
61 (UNHIDE_PREFIX, &self.unhidden_at),
62 ]
63 .into_iter()
64 .flat_map(|(prefix, entries)| {
65 entries
66 .iter()
67 .map(move |(chat_id, at)| format!("{prefix}\t{chat_id}\t{}", at.timestamp_millis()))
68 })
69 .collect();
42 70 lines.sort_unstable();
43 71 store.set_meta(META_LOCALLY_HIDDEN, &lines.join("\n"))?;
44 72 Ok(())
45 73 }
46 74
47 pub(crate) fn insert(&mut self, chat_id: &str, at: DateTime<Utc>) {
48 self.hidden_at.insert(chat_id.to_owned(), at);
75 pub(crate) fn hide(&mut self, chat_id: &str, last_message_at: DateTime<Utc>) {
76 self.unhidden_at.remove(chat_id);
77 self.hidden_after.insert(chat_id.to_owned(), last_message_at);
49 78 }
50 79
51 pub(crate) fn remove(&mut self, chat_id: &str) -> bool {
52 self.hidden_at.remove(chat_id).is_some()
80 pub(crate) fn unhide(&mut self, chat_id: &str, now: DateTime<Utc>) {
81 self.hidden_after.remove(chat_id);
82 self.unhidden_at.insert(chat_id.to_owned(), now);
83 }
84
85 fn unhide_override_active(&self, chat_id: &str, now: DateTime<Utc>) -> bool {
86 self.unhidden_at
87 .get(chat_id)
88 .is_some_and(|at| now - *at < unhide_override_window())
89 }
90
91 pub(crate) fn reported_hidden(&mut self, chat_id: &str, now: DateTime<Utc>) -> bool {
92 if self.unhide_override_active(chat_id, now) {
93 return false;
94 }
95 self.hidden_after.remove(chat_id);
96 true
53 97 }
54 98 }
55 99
@@ -57,18 +101,26 @@ pub(crate) fn resolve_hidden(
57 101 chat: &Chat,
58 102 states: &HashMap<String, ConversationState>,
59 103 locally: &mut LocallyHidden,
104 now: DateTime<Utc>,
60 105 ) -> bool {
61 106 let reported = states.get(&chat.id).and_then(|state| state.hidden);
107 if locally.unhidden_at.contains_key(&chat.id) {
108 if reported == Some(false) || !locally.unhide_override_active(&chat.id, now) {
109 locally.unhidden_at.remove(&chat.id);
110 } else {
111 return false;
112 }
113 }
62 114 if reported == Some(true) {
63 locally.remove(&chat.id);
115 locally.hidden_after.remove(&chat.id);
64 116 return true;
65 117 }
66 if let Some(hidden_at) = locally.hidden_at.get(&chat.id).copied() {
118 if let Some(hidden_after) = locally.hidden_after.get(&chat.id).copied() {
67 119 if chat
68 120 .last_message_time()
69 .is_some_and(|newest| newest > hidden_at)
121 .is_some_and(|newest| newest > hidden_after)
70 122 {
71 locally.remove(&chat.id);
123 locally.hidden_after.remove(&chat.id);
72 124 return false;
73 125 }
74 126 return true;
@@ -76,12 +128,32 @@ pub(crate) fn resolve_hidden(
76 128 reported.unwrap_or_else(|| graph_hidden(chat))
77 129 }
78 130
131 impl<R: Remote> SyncEngine<R> {
132 pub(crate) fn with_locally_hidden<T>(
133 &self,
134 change: impl FnOnce(&mut LocallyHidden) -> T,
135 ) -> Result<T> {
136 let _guard = self.locally_hidden_lock.lock().unwrap();
137 let mut locally = LocallyHidden::load(&self.store);
138 let before = locally.clone();
139 let result = change(&mut locally);
140 if locally != before {
141 locally.save(&self.store)?;
142 }
143 Ok(result)
144 }
145 }
146
79 147 #[cfg(test)]
80 148 mod tests {
81 149 use serde_json::json;
82 150
83 151 use super::*;
84 152
153 fn at(text: &str) -> DateTime<Utc> {
154 text.parse().unwrap()
155 }
156
85 157 fn chat(last_message: Option<&str>, graph_hidden: bool) -> Chat {
86 158 serde_json::from_value(json!({
87 159 "id": "19:a",
@@ -103,48 +175,99 @@ mod tests {
103 175 )])
104 176 }
105 177
106 fn hidden_at(at: &str) -> LocallyHidden {
178 fn hidden_after(text: &str) -> LocallyHidden {
107 179 let mut locally = LocallyHidden::default();
108 locally.insert("19:a", at.parse().unwrap());
180 locally.hide("19:a", at(text));
109 181 locally
110 182 }
111 183
184 fn now() -> DateTime<Utc> {
185 at("2030-01-01T12:00:00Z")
186 }
187
112 188 #[test]
113 189 fn chatsvc_visible_beats_the_graph_hidden_flag() {
114 190 let mut locally = LocallyHidden::default();
115 191 let chat = chat(None, true);
116 assert!(!resolve_hidden(&chat, &states(Some(false)), &mut locally));
117 assert!(resolve_hidden(&chat, &HashMap::new(), &mut locally));
192 assert!(!resolve_hidden(&chat, &states(Some(false)), &mut locally, now()));
193 assert!(resolve_hidden(&chat, &HashMap::new(), &mut locally, now()));
118 194 }
119 195
120 196 #[test]
121 197 fn a_local_hide_survives_a_chatsvc_that_still_says_visible() {
122 let mut locally = hidden_at("2026-10-10T10:00:00Z");
198 let mut locally = hidden_after("2026-10-10T10:00:00Z");
123 199 let chat = chat(Some("2026-10-10T09:00:00Z"), false);
124 assert!(resolve_hidden(&chat, &states(Some(false)), &mut locally));
125 assert_eq!(locally, hidden_at("2026-10-10T10:00:00Z"));
200 assert!(resolve_hidden(&chat, &states(Some(false)), &mut locally, now()));
201 assert_eq!(locally, hidden_after("2026-10-10T10:00:00Z"));
126 202 }
127 203
128 204 #[test]
129 fn a_newer_message_unhides_and_drops_the_local_entry() {
130 let mut locally = hidden_at("2026-10-10T10:00:00Z");
131 let chat = chat(Some("2026-10-10T11:00:00Z"), false);
132 assert!(!resolve_hidden(&chat, &states(Some(false)), &mut locally));
205 fn only_a_strictly_newer_message_unhides() {
206 let mut locally = hidden_after("2026-10-10T10:00:00Z");
207 let same = chat(Some("2026-10-10T10:00:00Z"), false);
208 assert!(resolve_hidden(&same, &states(Some(false)), &mut locally, now()));
209 let newer = chat(Some("2026-10-10T10:00:01Z"), false);
210 assert!(!resolve_hidden(&newer, &states(Some(false)), &mut locally, now()));
133 211 assert_eq!(locally, LocallyHidden::default());
134 212 }
135 213
214 #[test]
215 fn the_hide_marker_is_the_servers_message_time_so_clock_skew_does_not_matter() {
216 let mut locally = hidden_after("2026-10-10T10:00:00Z");
217 let chat = chat(Some("2026-10-10T10:00:30Z"), false);
218 let skewed_now = at("2026-10-10T09:00:00Z");
219 assert!(!resolve_hidden(&chat, &states(Some(false)), &mut locally, skewed_now));
220 }
221
136 222 #[test]
137 223 fn chatsvc_reporting_hidden_takes_over_and_drops_the_local_entry() {
138 let mut locally = hidden_at("2026-10-10T10:00:00Z");
224 let mut locally = hidden_after("2026-10-10T10:00:00Z");
139 225 let chat = chat(Some("2026-10-10T11:00:00Z"), false);
140 assert!(resolve_hidden(&chat, &states(Some(true)), &mut locally));
226 assert!(resolve_hidden(&chat, &states(Some(true)), &mut locally, now()));
141 227 assert_eq!(locally, LocallyHidden::default());
142 228 }
143 229
144 230 #[test]
145 fn local_hides_round_trip_through_the_store() {
231 fn a_local_unhide_overrides_a_reported_hide_until_chatsvc_catches_up_or_time_runs_out() {
232 let chat = chat(None, false);
233 let mut locally = LocallyHidden::default();
234 locally.unhide("19:a", now());
235 assert!(!resolve_hidden(&chat, &states(Some(true)), &mut locally, now()));
236 assert!(!resolve_hidden(
237 &chat,
238 &states(Some(true)),
239 &mut locally,
240 now() + Duration::minutes(9)
241 ));
242 assert!(resolve_hidden(
243 &chat,
244 &states(Some(true)),
245 &mut locally,
246 now() + Duration::minutes(11)
247 ));
248 assert_eq!(locally, LocallyHidden::default());
249
250 locally.unhide("19:a", now());
251 assert!(!resolve_hidden(&chat, &states(Some(false)), &mut locally, now()));
252 assert_eq!(locally, LocallyHidden::default());
253 }
254
255 #[test]
256 fn a_reported_hide_for_any_chat_drops_its_local_entry_unless_an_unhide_is_fresh() {
257 let mut locally = hidden_after("2026-10-10T10:00:00Z");
258 assert!(locally.reported_hidden("19:a", now()));
259 assert_eq!(locally, LocallyHidden::default());
260
261 locally.unhide("19:a", now());
262 assert!(!locally.reported_hidden("19:a", now()));
263 assert!(locally.reported_hidden("19:a", now() + Duration::minutes(11)));
264 }
265
266 #[test]
267 fn entries_round_trip_through_the_store() {
146 268 let store = Store::open_in_memory().unwrap();
147 let locally = hidden_at("2026-10-10T10:00:00Z");
269 let mut locally = hidden_after("2026-10-10T10:00:00Z");
270 locally.unhide("19:b", at("2026-10-10T11:00:00Z"));
148 271 locally.save(&store).unwrap();
149 272 assert_eq!(LocallyHidden::load(&store), locally);
150 273 }
@@ -1,18 +1,27 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2
2
3use chatsvc::ConversationState;
3use chatsvc::ConversationState;
4use chrono::{DateTime, TimeZone, Utc};
4use chrono::{DateTime, Duration, TimeZone, Utc};
5use graph::Chat;
5use graph::Chat;
6use store::Store;
6use store::Store;
7
7
8use crate::engine::SyncEngine;
8use crate::error::Result;
9use crate::error::Result;
9use crate::mapping::graph_hidden;
10use crate::mapping::graph_hidden;
11use crate::remote::Remote;
10
12
11const META_LOCALLY_HIDDEN: &str = "locally_hidden_chats";
13const META_LOCALLY_HIDDEN: &str = "locally_hidden_chats";
14const HIDE_PREFIX: &str = "hide";
15const UNHIDE_PREFIX: &str = "unhide";
16
17fn unhide_override_window() -> Duration {
18 Duration::minutes(10)
19}
12
20
13#[derive(Debug, Clone, Default, PartialEq, Eq)]
21#[derive(Debug, Clone, Default, PartialEq, Eq)]
14pub(crate) struct LocallyHidden {
22pub(crate) struct LocallyHidden {
15 hidden_at: HashMap<String, DateTime<Utc>>,
23 hidden_after: HashMap<String, DateTime<Utc>>,
24 unhidden_at: HashMap<String, DateTime<Utc>>,
16}
25}
17
26
18impl LocallyHidden {
27impl LocallyHidden {
@@ -22,34 +31,69 @@ impl LocallyHidden {
22 .ok()
31 .ok()
23 .flatten()
32 .flatten()
24 .unwrap_or_default();
33 .unwrap_or_default();
25 let hidden_at = text
34 let mut locally = LocallyHidden::default();
26 .lines()
35 for line in text.lines() {
27 .filter_map(|line| {
36 let mut fields = line.splitn(3, '\t');
28 let (chat_id, millis) = line.rsplit_once('\t')?;
37 let (Some(prefix), Some(chat_id), Some(millis)) =
29 let at = Utc.timestamp_millis_opt(millis.parse().ok()?).single()?;
38 (fields.next(), fields.next(), fields.next())
30 Some((chat_id.to_owned(), at))
39 else {
31 })
40 continue;
32 .collect();
41 };
33 LocallyHidden { hidden_at }
42 let Some(at) = millis
43 .parse()
44 .ok()
45 .and_then(|millis| Utc.timestamp_millis_opt(millis).single())
46 else {
47 continue;
48 };
49 match prefix {
50 HIDE_PREFIX => locally.hidden_after.insert(chat_id.to_owned(), at),
51 UNHIDE_PREFIX => locally.unhidden_at.insert(chat_id.to_owned(), at),
52 _ => None,
53 };
54 }
55 locally
34 }
56 }
35
57
36 pub(crate) fn save(&self, store: &Store) -> Result<()> {
58 pub(crate) fn save(&self, store: &Store) -> Result<()> {
37 let mut lines: Vec<String> = self
59 let mut lines: Vec<String> = [
38 .hidden_at
60 (HIDE_PREFIX, &self.hidden_after),
39 .iter()
61 (UNHIDE_PREFIX, &self.unhidden_at),
40 .map(|(chat_id, at)| format!("{chat_id}\t{}", at.timestamp_millis()))
62 ]
41 .collect();
63 .into_iter()
64 .flat_map(|(prefix, entries)| {
65 entries
66 .iter()
67 .map(move |(chat_id, at)| format!("{prefix}\t{chat_id}\t{}", at.timestamp_millis()))
68 })
69 .collect();
42 lines.sort_unstable();
70 lines.sort_unstable();
43 store.set_meta(META_LOCALLY_HIDDEN, &lines.join("\n"))?;
71 store.set_meta(META_LOCALLY_HIDDEN, &lines.join("\n"))?;
44 Ok(())
72 Ok(())
45 }
73 }
46
74
47 pub(crate) fn insert(&mut self, chat_id: &str, at: DateTime<Utc>) {
75 pub(crate) fn hide(&mut self, chat_id: &str, last_message_at: DateTime<Utc>) {
48 self.hidden_at.insert(chat_id.to_owned(), at);
76 self.unhidden_at.remove(chat_id);
77 self.hidden_after.insert(chat_id.to_owned(), last_message_at);
49 }
78 }
50
79
51 pub(crate) fn remove(&mut self, chat_id: &str) -> bool {
80 pub(crate) fn unhide(&mut self, chat_id: &str, now: DateTime<Utc>) {
52 self.hidden_at.remove(chat_id).is_some()
81 self.hidden_after.remove(chat_id);
82 self.unhidden_at.insert(chat_id.to_owned(), now);
83 }
84
85 fn unhide_override_active(&self, chat_id: &str, now: DateTime<Utc>) -> bool {
86 self.unhidden_at
87 .get(chat_id)
88 .is_some_and(|at| now - *at < unhide_override_window())
89 }
90
91 pub(crate) fn reported_hidden(&mut self, chat_id: &str, now: DateTime<Utc>) -> bool {
92 if self.unhide_override_active(chat_id, now) {
93 return false;
94 }
95 self.hidden_after.remove(chat_id);
96 true
53 }
97 }
54}
98}
55
99
@@ -57,18 +101,26 @@ pub(crate) fn resolve_hidden(
57 chat: &Chat,
101 chat: &Chat,
58 states: &HashMap<String, ConversationState>,
102 states: &HashMap<String, ConversationState>,
59 locally: &mut LocallyHidden,
103 locally: &mut LocallyHidden,
104 now: DateTime<Utc>,
60) -> bool {
105) -> bool {
61 let reported = states.get(&chat.id).and_then(|state| state.hidden);
106 let reported = states.get(&chat.id).and_then(|state| state.hidden);
107 if locally.unhidden_at.contains_key(&chat.id) {
108 if reported == Some(false) || !locally.unhide_override_active(&chat.id, now) {
109 locally.unhidden_at.remove(&chat.id);
110 } else {
111 return false;
112 }
113 }
62 if reported == Some(true) {
114 if reported == Some(true) {
63 locally.remove(&chat.id);
115 locally.hidden_after.remove(&chat.id);
64 return true;
116 return true;
65 }
117 }
66 if let Some(hidden_at) = locally.hidden_at.get(&chat.id).copied() {
118 if let Some(hidden_after) = locally.hidden_after.get(&chat.id).copied() {
67 if chat
119 if chat
68 .last_message_time()
120 .last_message_time()
69 .is_some_and(|newest| newest > hidden_at)
121 .is_some_and(|newest| newest > hidden_after)
70 {
122 {
71 locally.remove(&chat.id);
123 locally.hidden_after.remove(&chat.id);
72 return false;
124 return false;
73 }
125 }
74 return true;
126 return true;
@@ -76,12 +128,32 @@ pub(crate) fn resolve_hidden(
76 reported.unwrap_or_else(|| graph_hidden(chat))
128 reported.unwrap_or_else(|| graph_hidden(chat))
77}
129}
78
130
131impl<R: Remote> SyncEngine<R> {
132 pub(crate) fn with_locally_hidden<T>(
133 &self,
134 change: impl FnOnce(&mut LocallyHidden) -> T,
135 ) -> Result<T> {
136 let _guard = self.locally_hidden_lock.lock().unwrap();
137 let mut locally = LocallyHidden::load(&self.store);
138 let before = locally.clone();
139 let result = change(&mut locally);
140 if locally != before {
141 locally.save(&self.store)?;
142 }
143 Ok(result)
144 }
145}
146
79#[cfg(test)]
147#[cfg(test)]
80mod tests {
148mod tests {
81 use serde_json::json;
149 use serde_json::json;
82
150
83 use super::*;
151 use super::*;
84
152
153 fn at(text: &str) -> DateTime<Utc> {
154 text.parse().unwrap()
155 }
156
85 fn chat(last_message: Option<&str>, graph_hidden: bool) -> Chat {
157 fn chat(last_message: Option<&str>, graph_hidden: bool) -> Chat {
86 serde_json::from_value(json!({
158 serde_json::from_value(json!({
87 "id": "19:a",
159 "id": "19:a",
@@ -103,48 +175,99 @@ mod tests {
103 )])
175 )])
104 }
176 }
105
177
106 fn hidden_at(at: &str) -> LocallyHidden {
178 fn hidden_after(text: &str) -> LocallyHidden {
107 let mut locally = LocallyHidden::default();
179 let mut locally = LocallyHidden::default();
108 locally.insert("19:a", at.parse().unwrap());
180 locally.hide("19:a", at(text));
109 locally
181 locally
110 }
182 }
111
183
184 fn now() -> DateTime<Utc> {
185 at("2030-01-01T12:00:00Z")
186 }
187
112 #[test]
188 #[test]
113 fn chatsvc_visible_beats_the_graph_hidden_flag() {
189 fn chatsvc_visible_beats_the_graph_hidden_flag() {
114 let mut locally = LocallyHidden::default();
190 let mut locally = LocallyHidden::default();
115 let chat = chat(None, true);
191 let chat = chat(None, true);
116 assert!(!resolve_hidden(&chat, &states(Some(false)), &mut locally));
192 assert!(!resolve_hidden(&chat, &states(Some(false)), &mut locally, now()));
117 assert!(resolve_hidden(&chat, &HashMap::new(), &mut locally));
193 assert!(resolve_hidden(&chat, &HashMap::new(), &mut locally, now()));
118 }
194 }
119
195
120 #[test]
196 #[test]
121 fn a_local_hide_survives_a_chatsvc_that_still_says_visible() {
197 fn a_local_hide_survives_a_chatsvc_that_still_says_visible() {
122 let mut locally = hidden_at("2026-10-10T10:00:00Z");
198 let mut locally = hidden_after("2026-10-10T10:00:00Z");
123 let chat = chat(Some("2026-10-10T09:00:00Z"), false);
199 let chat = chat(Some("2026-10-10T09:00:00Z"), false);
124 assert!(resolve_hidden(&chat, &states(Some(false)), &mut locally));
200 assert!(resolve_hidden(&chat, &states(Some(false)), &mut locally, now()));
125 assert_eq!(locally, hidden_at("2026-10-10T10:00:00Z"));
201 assert_eq!(locally, hidden_after("2026-10-10T10:00:00Z"));
126 }
202 }
127
203
128 #[test]
204 #[test]
129 fn a_newer_message_unhides_and_drops_the_local_entry() {
205 fn only_a_strictly_newer_message_unhides() {
130 let mut locally = hidden_at("2026-10-10T10:00:00Z");
206 let mut locally = hidden_after("2026-10-10T10:00:00Z");
131 let chat = chat(Some("2026-10-10T11:00:00Z"), false);
207 let same = chat(Some("2026-10-10T10:00:00Z"), false);
132 assert!(!resolve_hidden(&chat, &states(Some(false)), &mut locally));
208 assert!(resolve_hidden(&same, &states(Some(false)), &mut locally, now()));
209 let newer = chat(Some("2026-10-10T10:00:01Z"), false);
210 assert!(!resolve_hidden(&newer, &states(Some(false)), &mut locally, now()));
133 assert_eq!(locally, LocallyHidden::default());
211 assert_eq!(locally, LocallyHidden::default());
134 }
212 }
135
213
214 #[test]
215 fn the_hide_marker_is_the_servers_message_time_so_clock_skew_does_not_matter() {
216 let mut locally = hidden_after("2026-10-10T10:00:00Z");
217 let chat = chat(Some("2026-10-10T10:00:30Z"), false);
218 let skewed_now = at("2026-10-10T09:00:00Z");
219 assert!(!resolve_hidden(&chat, &states(Some(false)), &mut locally, skewed_now));
220 }
221
136 #[test]
222 #[test]
137 fn chatsvc_reporting_hidden_takes_over_and_drops_the_local_entry() {
223 fn chatsvc_reporting_hidden_takes_over_and_drops_the_local_entry() {
138 let mut locally = hidden_at("2026-10-10T10:00:00Z");
224 let mut locally = hidden_after("2026-10-10T10:00:00Z");
139 let chat = chat(Some("2026-10-10T11:00:00Z"), false);
225 let chat = chat(Some("2026-10-10T11:00:00Z"), false);
140 assert!(resolve_hidden(&chat, &states(Some(true)), &mut locally));
226 assert!(resolve_hidden(&chat, &states(Some(true)), &mut locally, now()));
141 assert_eq!(locally, LocallyHidden::default());
227 assert_eq!(locally, LocallyHidden::default());
142 }
228 }
143
229
144 #[test]
230 #[test]
145 fn local_hides_round_trip_through_the_store() {
231 fn a_local_unhide_overrides_a_reported_hide_until_chatsvc_catches_up_or_time_runs_out() {
232 let chat = chat(None, false);
233 let mut locally = LocallyHidden::default();
234 locally.unhide("19:a", now());
235 assert!(!resolve_hidden(&chat, &states(Some(true)), &mut locally, now()));
236 assert!(!resolve_hidden(
237 &chat,
238 &states(Some(true)),
239 &mut locally,
240 now() + Duration::minutes(9)
241 ));
242 assert!(resolve_hidden(
243 &chat,
244 &states(Some(true)),
245 &mut locally,
246 now() + Duration::minutes(11)
247 ));
248 assert_eq!(locally, LocallyHidden::default());
249
250 locally.unhide("19:a", now());
251 assert!(!resolve_hidden(&chat, &states(Some(false)), &mut locally, now()));
252 assert_eq!(locally, LocallyHidden::default());
253 }
254
255 #[test]
256 fn a_reported_hide_for_any_chat_drops_its_local_entry_unless_an_unhide_is_fresh() {
257 let mut locally = hidden_after("2026-10-10T10:00:00Z");
258 assert!(locally.reported_hidden("19:a", now()));
259 assert_eq!(locally, LocallyHidden::default());
260
261 locally.unhide("19:a", now());
262 assert!(!locally.reported_hidden("19:a", now()));
263 assert!(locally.reported_hidden("19:a", now() + Duration::minutes(11)));
264 }
265
266 #[test]
267 fn entries_round_trip_through_the_store() {
146 let store = Store::open_in_memory().unwrap();
268 let store = Store::open_in_memory().unwrap();
147 let locally = hidden_at("2026-10-10T10:00:00Z");
269 let mut locally = hidden_after("2026-10-10T10:00:00Z");
270 locally.unhide("19:b", at("2026-10-10T11:00:00Z"));
148 locally.save(&store).unwrap();
271 locally.save(&store).unwrap();
149 assert_eq!(LocallyHidden::load(&store), locally);
272 assert_eq!(LocallyHidden::load(&store), locally);
150 }
273 }
crates/core/src/sidebar_sync.rs +31 −20
@@ -70,13 +70,11 @@ impl<R: Remote> SyncEngine<R> {
70 70 let mut continuation = None;
71 71 let states = self.refresh_chat_states().await;
72 72 self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
73 let mut locally = LocallyHidden::load(&self.store);
74 let locally_before = locally.clone();
75 73 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
76 74 loop {
77 75 refresh.pages += 1;
78 76 refresh.fetched += page.items.len();
79 let (records, hidden) = split_hidden(&page, &my_user_id, &self.chat_states.lock().unwrap(), &mut locally);
77 let (records, hidden) = self.split_page(&page, &my_user_id)?;
80 78 let any_changed = self.any_chat_changed(&records)?;
81 79 self.store.upsert_chats(&records)?;
82 80 kept_ids.extend(records.iter().map(|record| record.id.clone()));
@@ -94,9 +92,6 @@ impl<R: Remote> SyncEngine<R> {
94 92 page = self.remote.chats_at(&link).await?;
95 93 }
96 94 self.store.remove_chats(&hidden_ids)?;
97 if locally != locally_before {
98 locally.save(&self.store)?;
99 }
100 95 self.apply_muted_chats(states);
101 96 if full {
102 97 if complete {
@@ -125,12 +120,20 @@ impl<R: Remote> SyncEngine<R> {
125 120 }
126 121
127 122 fn drop_chats_hidden_by_chatsvc(&self, states: Option<&[ConversationState]>) -> Result<()> {
128 let hidden: Vec<String> = states
123 let reported: Vec<&str> = states
129 124 .unwrap_or_default()
130 125 .iter()
131 126 .filter(|state| state.hidden == Some(true))
132 .map(|state| state.id.clone())
127 .map(|state| state.id.as_str())
133 128 .collect();
129 let now = Utc::now();
130 let hidden: Vec<String> = self.with_locally_hidden(|locally| {
131 reported
132 .iter()
133 .filter(|chat_id| locally.reported_hidden(chat_id, now))
134 .map(|chat_id| (*chat_id).to_owned())
135 .collect()
136 })?;
134 137 self.store.remove_chats(&hidden)?;
135 138 Ok(())
136 139 }
@@ -222,19 +225,9 @@ impl<R: Remote> SyncEngine<R> {
222 225 }
223 226
224 227 fn store_older_page(&self, my_user_id: &str, page: &ChatsPage) -> Result<()> {
225 let mut locally = LocallyHidden::load(&self.store);
226 let locally_before = locally.clone();
227 let (records, hidden) = split_hidden(
228 page,
229 my_user_id,
230 &self.chat_states.lock().unwrap(),
231 &mut locally,
232 );
228 let (records, hidden) = self.split_page(page, my_user_id)?;
233 229 self.store.upsert_chats(&records)?;
234 230 self.store.remove_chats(&hidden)?;
235 if locally != locally_before {
236 locally.save(&self.store)?;
237 }
238 231 let muted: Vec<(String, bool)> = {
239 232 let states = self.chat_states.lock().unwrap();
240 233 records
@@ -247,6 +240,23 @@ impl<R: Remote> SyncEngine<R> {
247 240 Ok(())
248 241 }
249 242
243 fn split_page(
244 &self,
245 page: &ChatsPage,
246 my_user_id: &str,
247 ) -> Result<(Vec<ChatRecord>, Vec<String>)> {
248 let now = Utc::now();
249 self.with_locally_hidden(|locally| {
250 split_hidden(
251 page,
252 my_user_id,
253 &self.chat_states.lock().unwrap(),
254 locally,
255 now,
256 )
257 })
258 }
259
250 260 fn any_chat_changed(&self, records: &[ChatRecord]) -> Result<bool> {
251 261 let ids: Vec<String> = records.iter().map(|record| record.id.clone()).collect();
252 262 let cached = self.store.chat_last_message_times(&ids)?;
@@ -323,11 +333,12 @@ fn split_hidden(
323 333 my_user_id: &str,
324 334 states: &HashMap<String, ConversationState>,
325 335 locally: &mut LocallyHidden,
336 now: DateTime<Utc>,
326 337 ) -> (Vec<ChatRecord>, Vec<String>) {
327 338 let mut records = Vec::new();
328 339 let mut hidden = Vec::new();
329 340 for chat in &page.items {
330 if resolve_hidden(chat, states, locally) {
341 if resolve_hidden(chat, states, locally, now) {
331 342 hidden.push(chat.id.clone());
332 343 } else {
333 344 records.push(chat_record(chat, my_user_id));
@@ -70,13 +70,11 @@ impl<R: Remote> SyncEngine<R> {
70 let mut continuation = None;
70 let mut continuation = None;
71 let states = self.refresh_chat_states().await;
71 let states = self.refresh_chat_states().await;
72 self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
72 self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
73 let mut locally = LocallyHidden::load(&self.store);
74 let locally_before = locally.clone();
75 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
73 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
76 loop {
74 loop {
77 refresh.pages += 1;
75 refresh.pages += 1;
78 refresh.fetched += page.items.len();
76 refresh.fetched += page.items.len();
79 let (records, hidden) = split_hidden(&page, &my_user_id, &self.chat_states.lock().unwrap(), &mut locally);
77 let (records, hidden) = self.split_page(&page, &my_user_id)?;
80 let any_changed = self.any_chat_changed(&records)?;
78 let any_changed = self.any_chat_changed(&records)?;
81 self.store.upsert_chats(&records)?;
79 self.store.upsert_chats(&records)?;
82 kept_ids.extend(records.iter().map(|record| record.id.clone()));
80 kept_ids.extend(records.iter().map(|record| record.id.clone()));
@@ -94,9 +92,6 @@ impl<R: Remote> SyncEngine<R> {
94 page = self.remote.chats_at(&link).await?;
92 page = self.remote.chats_at(&link).await?;
95 }
93 }
96 self.store.remove_chats(&hidden_ids)?;
94 self.store.remove_chats(&hidden_ids)?;
97 if locally != locally_before {
98 locally.save(&self.store)?;
99 }
100 self.apply_muted_chats(states);
95 self.apply_muted_chats(states);
101 if full {
96 if full {
102 if complete {
97 if complete {
@@ -125,12 +120,20 @@ impl<R: Remote> SyncEngine<R> {
125 }
120 }
126
121
127 fn drop_chats_hidden_by_chatsvc(&self, states: Option<&[ConversationState]>) -> Result<()> {
122 fn drop_chats_hidden_by_chatsvc(&self, states: Option<&[ConversationState]>) -> Result<()> {
128 let hidden: Vec<String> = states
123 let reported: Vec<&str> = states
129 .unwrap_or_default()
124 .unwrap_or_default()
130 .iter()
125 .iter()
131 .filter(|state| state.hidden == Some(true))
126 .filter(|state| state.hidden == Some(true))
132 .map(|state| state.id.clone())
127 .map(|state| state.id.as_str())
133 .collect();
128 .collect();
129 let now = Utc::now();
130 let hidden: Vec<String> = self.with_locally_hidden(|locally| {
131 reported
132 .iter()
133 .filter(|chat_id| locally.reported_hidden(chat_id, now))
134 .map(|chat_id| (*chat_id).to_owned())
135 .collect()
136 })?;
134 self.store.remove_chats(&hidden)?;
137 self.store.remove_chats(&hidden)?;
135 Ok(())
138 Ok(())
136 }
139 }
@@ -222,19 +225,9 @@ impl<R: Remote> SyncEngine<R> {
222 }
225 }
223
226
224 fn store_older_page(&self, my_user_id: &str, page: &ChatsPage) -> Result<()> {
227 fn store_older_page(&self, my_user_id: &str, page: &ChatsPage) -> Result<()> {
225 let mut locally = LocallyHidden::load(&self.store);
228 let (records, hidden) = self.split_page(page, my_user_id)?;
226 let locally_before = locally.clone();
227 let (records, hidden) = split_hidden(
228 page,
229 my_user_id,
230 &self.chat_states.lock().unwrap(),
231 &mut locally,
232 );
233 self.store.upsert_chats(&records)?;
229 self.store.upsert_chats(&records)?;
234 self.store.remove_chats(&hidden)?;
230 self.store.remove_chats(&hidden)?;
235 if locally != locally_before {
236 locally.save(&self.store)?;
237 }
238 let muted: Vec<(String, bool)> = {
231 let muted: Vec<(String, bool)> = {
239 let states = self.chat_states.lock().unwrap();
232 let states = self.chat_states.lock().unwrap();
240 records
233 records
@@ -247,6 +240,23 @@ impl<R: Remote> SyncEngine<R> {
247 Ok(())
240 Ok(())
248 }
241 }
249
242
243 fn split_page(
244 &self,
245 page: &ChatsPage,
246 my_user_id: &str,
247 ) -> Result<(Vec<ChatRecord>, Vec<String>)> {
248 let now = Utc::now();
249 self.with_locally_hidden(|locally| {
250 split_hidden(
251 page,
252 my_user_id,
253 &self.chat_states.lock().unwrap(),
254 locally,
255 now,
256 )
257 })
258 }
259
250 fn any_chat_changed(&self, records: &[ChatRecord]) -> Result<bool> {
260 fn any_chat_changed(&self, records: &[ChatRecord]) -> Result<bool> {
251 let ids: Vec<String> = records.iter().map(|record| record.id.clone()).collect();
261 let ids: Vec<String> = records.iter().map(|record| record.id.clone()).collect();
252 let cached = self.store.chat_last_message_times(&ids)?;
262 let cached = self.store.chat_last_message_times(&ids)?;
@@ -323,11 +333,12 @@ fn split_hidden(
323 my_user_id: &str,
333 my_user_id: &str,
324 states: &HashMap<String, ConversationState>,
334 states: &HashMap<String, ConversationState>,
325 locally: &mut LocallyHidden,
335 locally: &mut LocallyHidden,
336 now: DateTime<Utc>,
326) -> (Vec<ChatRecord>, Vec<String>) {
337) -> (Vec<ChatRecord>, Vec<String>) {
327 let mut records = Vec::new();
338 let mut records = Vec::new();
328 let mut hidden = Vec::new();
339 let mut hidden = Vec::new();
329 for chat in &page.items {
340 for chat in &page.items {
330 if resolve_hidden(chat, states, locally) {
341 if resolve_hidden(chat, states, locally, now) {
331 hidden.push(chat.id.clone());
342 hidden.push(chat.id.clone());
332 } else {
343 } else {
333 records.push(chat_record(chat, my_user_id));
344 records.push(chat_record(chat, my_user_id));
crates/core/tests/engine.rs +18 −0
@@ -1144,6 +1144,24 @@ async fn a_chat_hidden_in_the_app_stays_hidden_until_a_newer_message_arrives() {
1144 1144 assert_eq!(engine.sidebar().unwrap().chats.len(), 1);
1145 1145 }
1146 1146
1147 #[tokio::test]
1148 async fn undo_after_chatsvc_reported_the_hide_keeps_the_chat_visible() {
1149 let fake = Arc::new(Fake::default());
1150 let engine = chat_engine(&fake, small_pages()).await;
1151 engine.hide_chat(CHAT).await.unwrap();
1152 fake.hidden_states
1153 .lock()
1154 .unwrap()
1155 .push((CHAT.to_owned(), true));
1156 engine.refresh_sidebar().await.unwrap();
1157 assert!(engine.sidebar().unwrap().chats.is_empty());
1158
1159 engine.unhide_chat(CHAT).await.unwrap();
1160 assert_eq!(engine.sidebar().unwrap().chats.len(), 1);
1161 engine.refresh_sidebar().await.unwrap();
1162 assert_eq!(engine.sidebar().unwrap().chats.len(), 1);
1163 }
1164
1147 1165 #[tokio::test]
1148 1166 async fn deep_chats_that_chatsvc_reports_hidden_are_removed_on_refresh() {
1149 1167 let fake = Arc::new(Fake::default());
@@ -1144,6 +1144,24 @@ async fn a_chat_hidden_in_the_app_stays_hidden_until_a_newer_message_arrives() {
1144 assert_eq!(engine.sidebar().unwrap().chats.len(), 1);
1144 assert_eq!(engine.sidebar().unwrap().chats.len(), 1);
1145}
1145}
1146
1146
1147#[tokio::test]
1148async fn undo_after_chatsvc_reported_the_hide_keeps_the_chat_visible() {
1149 let fake = Arc::new(Fake::default());
1150 let engine = chat_engine(&fake, small_pages()).await;
1151 engine.hide_chat(CHAT).await.unwrap();
1152 fake.hidden_states
1153 .lock()
1154 .unwrap()
1155 .push((CHAT.to_owned(), true));
1156 engine.refresh_sidebar().await.unwrap();
1157 assert!(engine.sidebar().unwrap().chats.is_empty());
1158
1159 engine.unhide_chat(CHAT).await.unwrap();
1160 assert_eq!(engine.sidebar().unwrap().chats.len(), 1);
1161 engine.refresh_sidebar().await.unwrap();
1162 assert_eq!(engine.sidebar().unwrap().chats.len(), 1);
1163}
1164
1147#[tokio::test]
1165#[tokio::test]
1148async fn deep_chats_that_chatsvc_reports_hidden_are_removed_on_refresh() {
1166async fn deep_chats_that_chatsvc_reports_hidden_are_removed_on_refresh() {
1149 let fake = Arc::new(Fake::default());
1167 let fake = Arc::new(Fake::default());