BlueGit

ict rusty-teams

fix(sidebar): team order from Teams, hidden chats from chatsvc, load older chats on scroll

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
316e678b5c34cbbee6267d0cd0b35b3c83d25047
Parent
d8591484
19 files changed +780 −120
crates/app/src/app_state.rs +20 −0
@@ -274,6 +274,26 @@ impl AppState {
274 274 cx.notify();
275 275 }
276 276
277 pub fn older_chats(&self) -> (bool, bool) {
278 self.engine.as_ref().map_or((false, false), |engine| {
279 (engine.has_older_chats(), engine.is_loading_older_chats())
280 })
281 }
282
283 pub fn request_older_chats(&self) {
284 let Some(engine) = self.engine.clone() else {
285 return;
286 };
287 if !engine.has_older_chats() || engine.is_loading_older_chats() {
288 return;
289 }
290 drop(crate::runtime::spawn(async move {
291 if let Err(error) = engine.load_older_chats().await {
292 crate::diagnostics::record(format!("sync: older chats not loaded: {error}"));
293 }
294 }));
295 }
296
277 297 pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) {
278 298 if !self.expanded_lists.remove(section_id) {
279 299 self.expanded_lists.insert(section_id.to_owned());
@@ -274,6 +274,26 @@ impl AppState {
274 cx.notify();
274 cx.notify();
275 }
275 }
276
276
277 pub fn older_chats(&self) -> (bool, bool) {
278 self.engine.as_ref().map_or((false, false), |engine| {
279 (engine.has_older_chats(), engine.is_loading_older_chats())
280 })
281 }
282
283 pub fn request_older_chats(&self) {
284 let Some(engine) = self.engine.clone() else {
285 return;
286 };
287 if !engine.has_older_chats() || engine.is_loading_older_chats() {
288 return;
289 }
290 drop(crate::runtime::spawn(async move {
291 if let Err(error) = engine.load_older_chats().await {
292 crate::diagnostics::record(format!("sync: older chats not loaded: {error}"));
293 }
294 }));
295 }
296
277 pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) {
297 pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) {
278 if !self.expanded_lists.remove(section_id) {
298 if !self.expanded_lists.remove(section_id) {
279 self.expanded_lists.insert(section_id.to_owned());
299 self.expanded_lists.insert(section_id.to_owned());
crates/app/src/demo.rs +1 −5
@@ -10,7 +10,7 @@ use store::{
10 10 ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
11 11 };
12 12 use teams_core::{
13 Activity, CardActionOutcome, ChatApp, ChatSection, Gif, Language, LanguageSettings,
13 Activity, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,
14 14 LinkPreview, MentionCandidate, PersonCandidate, PersonSource, PinnedMessage, SavedMessage,
15 15 TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
16 16 };
@@ -905,10 +905,6 @@ pub fn seed_directory(state: &mut AppState) {
905 905 Instant::now(),
906 906 Utc::now(),
907 907 );
908 state
909 .directory
910 .section_settings
911 .set(ChatSection::Meeting, true);
912 908 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
913 909 state.last_sync = Some(Utc::now());
914 910 state.apply_bot_titles();
@@ -10,7 +10,7 @@ use store::{
10 ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
10 ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
11};
11};
12use teams_core::{
12use teams_core::{
13 Activity, CardActionOutcome, ChatApp, ChatSection, Gif, Language, LanguageSettings,
13 Activity, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,
14 LinkPreview, MentionCandidate, PersonCandidate, PersonSource, PinnedMessage, SavedMessage,
14 LinkPreview, MentionCandidate, PersonCandidate, PersonSource, PinnedMessage, SavedMessage,
15 TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
15 TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
16};
16};
@@ -905,10 +905,6 @@ pub fn seed_directory(state: &mut AppState) {
905 Instant::now(),
905 Instant::now(),
906 Utc::now(),
906 Utc::now(),
907 );
907 );
908 state
909 .directory
910 .section_settings
911 .set(ChatSection::Meeting, true);
912 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
908 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
913 state.last_sync = Some(Utc::now());
909 state.last_sync = Some(Utc::now());
914 state.apply_bot_titles();
910 state.apply_bot_titles();
crates/app/src/sidebar_model.rs +18 −46
@@ -14,8 +14,6 @@ use crate::typing::{TypingState, preview_label};
14 14 pub const FAVORITES_FALLBACK_NAME: &str = "Pinned";
15 15 pub const OTHERS_NAME: &str = "Other chats";
16 16 pub const OTHERS_ID: &str = "others";
17 pub const MEETING_NAME: &str = "Meeting chats";
18 pub const MEETING_ID: &str = "meeting_chats";
19 17 pub const MUTED_NAME: &str = "Muted";
20 18 pub const MUTED_ID: &str = "muted_chats";
21 19 pub const SECTION_PAGE_SIZE: usize = 5;
@@ -23,7 +21,6 @@ pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";
23 21 pub const DELETED_PREVIEW: &str = "Message deleted";
24 22 const OWN_PREFIX: &str = "You";
25 23 const GROUP_KIND: &str = "group";
26 const MEETING_KIND: &str = "meeting";
27 24
28 25 #[derive(Debug, Clone, PartialEq, Eq)]
29 26 pub enum Preview {
@@ -82,7 +79,6 @@ pub enum SectionKind {
82 79 Favorites,
83 80 Folder,
84 81 Others,
85 Meeting,
86 82 Muted,
87 83 }
88 84
@@ -261,7 +257,6 @@ pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
261 257 .collect();
262 258 let settings = &input.directory.section_settings;
263 259 let mut muted = Vec::new();
264 let mut meeting = Vec::new();
265 260 let mut rest = Vec::new();
266 261 for chat in input
267 262 .chats
@@ -271,9 +266,6 @@ pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
271 266 let item = chat_item(chat, input, None);
272 267 if chat.muted && settings.enabled(ChatSection::Muted) {
273 268 muted.push(item);
274 } else if !chat.muted && chat.kind == MEETING_KIND && settings.enabled(ChatSection::Meeting)
275 {
276 meeting.push(item);
277 269 } else {
278 270 rest.push(item);
279 271 }
@@ -293,15 +285,6 @@ pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
293 285 rest,
294 286 input,
295 287 ));
296 let mut meeting = (!meeting.is_empty()).then(|| {
297 section(
298 folder_id(FolderKind::Meeting, MEETING_ID),
299 MEETING_NAME.to_owned(),
300 SectionKind::Meeting,
301 meeting,
302 input,
303 )
304 });
305 288 let mut muted = (!muted.is_empty()).then(|| {
306 289 section(
307 290 folder_id(FolderKind::Muted, MUTED_ID),
@@ -316,11 +299,10 @@ pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
316 299 match folder.kind {
317 300 FolderKind::Favorites | FolderKind::UserCreated => sections.extend(section.take()),
318 301 FolderKind::Recent => sections.extend(others.take()),
319 FolderKind::Meeting => sections.extend(meeting.take()),
302 FolderKind::Meeting => {}
320 303 FolderKind::Muted => sections.extend(muted.take()),
321 304 }
322 305 }
323 sections.extend(meeting);
324 306 sections.extend(others);
325 307 sections.extend(muted);
326 308 sections
@@ -443,7 +425,7 @@ fn section(
443 425 .iter()
444 426 .filter(|item| item.unread.is_unread() && !item.muted)
445 427 .count() as u32;
446 let paged = matches!(kind, SectionKind::Meeting | SectionKind::Muted);
428 let paged = kind == SectionKind::Muted;
447 429 let list_expanded = paged && count > SECTION_PAGE_SIZE && input.expanded_lists.contains(&id);
448 430 let hidden_count = if paged && !list_expanded {
449 431 count.saturating_sub(SECTION_PAGE_SIZE)
@@ -535,16 +517,13 @@ mod tests {
535 517 chat(id, "meeting", false)
536 518 }
537 519
538 fn sectioned_directory(muted: bool, meeting: bool, folders: Vec<FolderInfo>) -> Directory {
520 fn sectioned_directory(muted: bool, folders: Vec<FolderInfo>) -> Directory {
539 521 let mut directory = Directory {
540 522 folders,
541 523 ..Default::default()
542 524 };
543 525 directory.section_settings.set(ChatSection::Muted, muted);
544 526 directory
545 .section_settings
546 .set(ChatSection::Meeting, meeting);
547 directory
548 527 }
549 528
550 529 fn section_ids(sections: &[Section]) -> Vec<&str> {
@@ -622,7 +601,6 @@ mod tests {
622 601 chats.extend((0..7).map(|index| muted_chat(&format!("m{index}"))));
623 602 chats.push(chat("other", "group", false));
624 603 let directory = sectioned_directory(
625 true,
626 604 true,
627 605 vec![
628 606 folder("fav-folder", FolderKind::Favorites, &["fav"]),
@@ -921,7 +899,7 @@ mod tests {
921 899 }
922 900
923 901 #[test]
924 fn muted_and_meeting_chats_leave_others_unless_pinned_or_in_a_custom_section() {
902 fn muted_chats_leave_others_unless_pinned_or_in_a_custom_section_and_meeting_chats_stay() {
925 903 let chats = vec![
926 904 chat("plain", "group", false),
927 905 muted_chat("quiet"),
@@ -934,7 +912,6 @@ mod tests {
934 912 },
935 913 ];
936 914 let directory = sectioned_directory(
937 true,
938 915 true,
939 916 vec![
940 917 folder("fav", FolderKind::Favorites, &["pinned-quiet"]),
@@ -944,28 +921,27 @@ mod tests {
944 921 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
945 922 assert_eq!(
946 923 section_ids(&sections),
947 vec!["fav", "work", MEETING_ID, OTHERS_ID, MUTED_ID]
924 vec!["fav", "work", OTHERS_ID, MUTED_ID]
948 925 );
949 926 assert_eq!(item_ids(&sections[0]), vec!["pinned-quiet"]);
950 927 assert_eq!(item_ids(&sections[1]), vec!["custom-sync"]);
951 assert_eq!(item_ids(&sections[2]), vec!["sync"]);
952 assert_eq!(item_ids(&sections[3]), vec!["plain"]);
953 assert_eq!(item_ids(&sections[4]), vec!["quiet", "quiet-sync"]);
954 assert_eq!(sections[4].kind, SectionKind::Muted);
955 assert_eq!(sections[4].count, 2);
928 assert_eq!(item_ids(&sections[2]), vec!["plain", "sync"]);
929 assert_eq!(item_ids(&sections[3]), vec!["quiet", "quiet-sync"]);
930 assert_eq!(sections[3].kind, SectionKind::Muted);
931 assert_eq!(sections[3].count, 2);
956 932 }
957 933
958 934 #[test]
959 fn turning_a_section_off_puts_its_chats_back_in_others() {
935 fn turning_the_muted_section_off_puts_its_chats_back_in_others() {
960 936 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
961 let directory = sectioned_directory(false, false, Vec::new());
937 let directory = sectioned_directory(false, Vec::new());
962 938 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
963 939 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
964 940 assert_eq!(item_ids(&sections[0]), vec!["quiet", "sync"]);
965 941 }
966 942
967 943 #[test]
968 fn muted_is_on_and_meeting_is_off_until_the_user_chooses() {
944 fn muted_is_on_until_the_user_chooses_and_meeting_chats_stay_in_others() {
969 945 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
970 946 let directory = Directory::default();
971 947 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
@@ -976,7 +952,7 @@ mod tests {
976 952 #[test]
977 953 fn empty_system_sections_are_hidden() {
978 954 let chats = vec![chat("a", "group", false)];
979 let directory = sectioned_directory(true, true, Vec::new());
955 let directory = sectioned_directory(true, Vec::new());
980 956 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
981 957 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
982 958 }
@@ -989,7 +965,6 @@ mod tests {
989 965 meeting_chat("sync"),
990 966 ];
991 967 let directory = sectioned_directory(
992 true,
993 968 true,
994 969 vec![
995 970 folder("muted-id", FolderKind::Muted, &[]),
@@ -1000,13 +975,10 @@ mod tests {
1000 975 );
1001 976 let collapsed: HashSet<String> = ["muted-id".to_owned()].into();
1002 977 let sections = build_sections(&input(&chats, &directory, &collapsed));
1003 assert_eq!(
1004 section_ids(&sections),
1005 vec!["muted-id", "fav", "recent-id", "meeting-id"]
1006 );
978 assert_eq!(section_ids(&sections), vec!["muted-id", "fav", "recent-id"]);
1007 979 assert!(sections[0].collapsed);
1008 980 assert_eq!(sections[0].name, MUTED_NAME);
1009 assert_eq!(sections[3].name, MEETING_NAME);
981 assert_eq!(item_ids(&sections[2]), vec!["a", "sync"]);
1010 982 }
1011 983
1012 984 #[test]
@@ -1070,14 +1042,14 @@ mod tests {
1070 1042 }
1071 1043
1072 1044 #[test]
1073 fn meeting_chats_keep_their_unread_count() {
1045 fn meeting_chats_keep_their_unread_count_in_others() {
1074 1046 let mut sync = meeting_chat("sync");
1075 1047 sync.unread = true;
1076 1048 let chats = vec![sync];
1077 let mut directory = sectioned_directory(true, true, Vec::new());
1049 let mut directory = sectioned_directory(true, Vec::new());
1078 1050 directory.unread_counts.insert("sync".into(), 3);
1079 1051 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1080 assert_eq!(sections[0].id, MEETING_ID);
1052 assert_eq!(sections[0].id, OTHERS_ID);
1081 1053 assert_eq!(sections[0].items[0].unread, Unread::Count(3));
1082 1054 assert_eq!(sections[0].unread_chats, 1);
1083 1055 }
@@ -14,8 +14,6 @@ use crate::typing::{TypingState, preview_label};
14pub const FAVORITES_FALLBACK_NAME: &str = "Pinned";
14pub const FAVORITES_FALLBACK_NAME: &str = "Pinned";
15pub const OTHERS_NAME: &str = "Other chats";
15pub const OTHERS_NAME: &str = "Other chats";
16pub const OTHERS_ID: &str = "others";
16pub const OTHERS_ID: &str = "others";
17pub const MEETING_NAME: &str = "Meeting chats";
18pub const MEETING_ID: &str = "meeting_chats";
19pub const MUTED_NAME: &str = "Muted";
17pub const MUTED_NAME: &str = "Muted";
20pub const MUTED_ID: &str = "muted_chats";
18pub const MUTED_ID: &str = "muted_chats";
21pub const SECTION_PAGE_SIZE: usize = 5;
19pub const SECTION_PAGE_SIZE: usize = 5;
@@ -23,7 +21,6 @@ pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";
23pub const DELETED_PREVIEW: &str = "Message deleted";
21pub const DELETED_PREVIEW: &str = "Message deleted";
24const OWN_PREFIX: &str = "You";
22const OWN_PREFIX: &str = "You";
25const GROUP_KIND: &str = "group";
23const GROUP_KIND: &str = "group";
26const MEETING_KIND: &str = "meeting";
27
24
28#[derive(Debug, Clone, PartialEq, Eq)]
25#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum Preview {
26pub enum Preview {
@@ -82,7 +79,6 @@ pub enum SectionKind {
82 Favorites,
79 Favorites,
83 Folder,
80 Folder,
84 Others,
81 Others,
85 Meeting,
86 Muted,
82 Muted,
87}
83}
88
84
@@ -261,7 +257,6 @@ pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
261 .collect();
257 .collect();
262 let settings = &input.directory.section_settings;
258 let settings = &input.directory.section_settings;
263 let mut muted = Vec::new();
259 let mut muted = Vec::new();
264 let mut meeting = Vec::new();
265 let mut rest = Vec::new();
260 let mut rest = Vec::new();
266 for chat in input
261 for chat in input
267 .chats
262 .chats
@@ -271,9 +266,6 @@ pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
271 let item = chat_item(chat, input, None);
266 let item = chat_item(chat, input, None);
272 if chat.muted && settings.enabled(ChatSection::Muted) {
267 if chat.muted && settings.enabled(ChatSection::Muted) {
273 muted.push(item);
268 muted.push(item);
274 } else if !chat.muted && chat.kind == MEETING_KIND && settings.enabled(ChatSection::Meeting)
275 {
276 meeting.push(item);
277 } else {
269 } else {
278 rest.push(item);
270 rest.push(item);
279 }
271 }
@@ -293,15 +285,6 @@ pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
293 rest,
285 rest,
294 input,
286 input,
295 ));
287 ));
296 let mut meeting = (!meeting.is_empty()).then(|| {
297 section(
298 folder_id(FolderKind::Meeting, MEETING_ID),
299 MEETING_NAME.to_owned(),
300 SectionKind::Meeting,
301 meeting,
302 input,
303 )
304 });
305 let mut muted = (!muted.is_empty()).then(|| {
288 let mut muted = (!muted.is_empty()).then(|| {
306 section(
289 section(
307 folder_id(FolderKind::Muted, MUTED_ID),
290 folder_id(FolderKind::Muted, MUTED_ID),
@@ -316,11 +299,10 @@ pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
316 match folder.kind {
299 match folder.kind {
317 FolderKind::Favorites | FolderKind::UserCreated => sections.extend(section.take()),
300 FolderKind::Favorites | FolderKind::UserCreated => sections.extend(section.take()),
318 FolderKind::Recent => sections.extend(others.take()),
301 FolderKind::Recent => sections.extend(others.take()),
319 FolderKind::Meeting => sections.extend(meeting.take()),
302 FolderKind::Meeting => {}
320 FolderKind::Muted => sections.extend(muted.take()),
303 FolderKind::Muted => sections.extend(muted.take()),
321 }
304 }
322 }
305 }
323 sections.extend(meeting);
324 sections.extend(others);
306 sections.extend(others);
325 sections.extend(muted);
307 sections.extend(muted);
326 sections
308 sections
@@ -443,7 +425,7 @@ fn section(
443 .iter()
425 .iter()
444 .filter(|item| item.unread.is_unread() && !item.muted)
426 .filter(|item| item.unread.is_unread() && !item.muted)
445 .count() as u32;
427 .count() as u32;
446 let paged = matches!(kind, SectionKind::Meeting | SectionKind::Muted);
428 let paged = kind == SectionKind::Muted;
447 let list_expanded = paged && count > SECTION_PAGE_SIZE && input.expanded_lists.contains(&id);
429 let list_expanded = paged && count > SECTION_PAGE_SIZE && input.expanded_lists.contains(&id);
448 let hidden_count = if paged && !list_expanded {
430 let hidden_count = if paged && !list_expanded {
449 count.saturating_sub(SECTION_PAGE_SIZE)
431 count.saturating_sub(SECTION_PAGE_SIZE)
@@ -535,16 +517,13 @@ mod tests {
535 chat(id, "meeting", false)
517 chat(id, "meeting", false)
536 }
518 }
537
519
538 fn sectioned_directory(muted: bool, meeting: bool, folders: Vec<FolderInfo>) -> Directory {
520 fn sectioned_directory(muted: bool, folders: Vec<FolderInfo>) -> Directory {
539 let mut directory = Directory {
521 let mut directory = Directory {
540 folders,
522 folders,
541 ..Default::default()
523 ..Default::default()
542 };
524 };
543 directory.section_settings.set(ChatSection::Muted, muted);
525 directory.section_settings.set(ChatSection::Muted, muted);
544 directory
526 directory
545 .section_settings
546 .set(ChatSection::Meeting, meeting);
547 directory
548 }
527 }
549
528
550 fn section_ids(sections: &[Section]) -> Vec<&str> {
529 fn section_ids(sections: &[Section]) -> Vec<&str> {
@@ -622,7 +601,6 @@ mod tests {
622 chats.extend((0..7).map(|index| muted_chat(&format!("m{index}"))));
601 chats.extend((0..7).map(|index| muted_chat(&format!("m{index}"))));
623 chats.push(chat("other", "group", false));
602 chats.push(chat("other", "group", false));
624 let directory = sectioned_directory(
603 let directory = sectioned_directory(
625 true,
626 true,
604 true,
627 vec![
605 vec![
628 folder("fav-folder", FolderKind::Favorites, &["fav"]),
606 folder("fav-folder", FolderKind::Favorites, &["fav"]),
@@ -921,7 +899,7 @@ mod tests {
921 }
899 }
922
900
923 #[test]
901 #[test]
924 fn muted_and_meeting_chats_leave_others_unless_pinned_or_in_a_custom_section() {
902 fn muted_chats_leave_others_unless_pinned_or_in_a_custom_section_and_meeting_chats_stay() {
925 let chats = vec![
903 let chats = vec![
926 chat("plain", "group", false),
904 chat("plain", "group", false),
927 muted_chat("quiet"),
905 muted_chat("quiet"),
@@ -934,7 +912,6 @@ mod tests {
934 },
912 },
935 ];
913 ];
936 let directory = sectioned_directory(
914 let directory = sectioned_directory(
937 true,
938 true,
915 true,
939 vec![
916 vec![
940 folder("fav", FolderKind::Favorites, &["pinned-quiet"]),
917 folder("fav", FolderKind::Favorites, &["pinned-quiet"]),
@@ -944,28 +921,27 @@ mod tests {
944 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
921 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
945 assert_eq!(
922 assert_eq!(
946 section_ids(&sections),
923 section_ids(&sections),
947 vec!["fav", "work", MEETING_ID, OTHERS_ID, MUTED_ID]
924 vec!["fav", "work", OTHERS_ID, MUTED_ID]
948 );
925 );
949 assert_eq!(item_ids(&sections[0]), vec!["pinned-quiet"]);
926 assert_eq!(item_ids(&sections[0]), vec!["pinned-quiet"]);
950 assert_eq!(item_ids(&sections[1]), vec!["custom-sync"]);
927 assert_eq!(item_ids(&sections[1]), vec!["custom-sync"]);
951 assert_eq!(item_ids(&sections[2]), vec!["sync"]);
928 assert_eq!(item_ids(&sections[2]), vec!["plain", "sync"]);
952 assert_eq!(item_ids(&sections[3]), vec!["plain"]);
929 assert_eq!(item_ids(&sections[3]), vec!["quiet", "quiet-sync"]);
953 assert_eq!(item_ids(&sections[4]), vec!["quiet", "quiet-sync"]);
930 assert_eq!(sections[3].kind, SectionKind::Muted);
954 assert_eq!(sections[4].kind, SectionKind::Muted);
931 assert_eq!(sections[3].count, 2);
955 assert_eq!(sections[4].count, 2);
956 }
932 }
957
933
958 #[test]
934 #[test]
959 fn turning_a_section_off_puts_its_chats_back_in_others() {
935 fn turning_the_muted_section_off_puts_its_chats_back_in_others() {
960 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
936 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
961 let directory = sectioned_directory(false, false, Vec::new());
937 let directory = sectioned_directory(false, Vec::new());
962 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
938 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
963 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
939 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
964 assert_eq!(item_ids(&sections[0]), vec!["quiet", "sync"]);
940 assert_eq!(item_ids(&sections[0]), vec!["quiet", "sync"]);
965 }
941 }
966
942
967 #[test]
943 #[test]
968 fn muted_is_on_and_meeting_is_off_until_the_user_chooses() {
944 fn muted_is_on_until_the_user_chooses_and_meeting_chats_stay_in_others() {
969 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
945 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
970 let directory = Directory::default();
946 let directory = Directory::default();
971 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
947 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
@@ -976,7 +952,7 @@ mod tests {
976 #[test]
952 #[test]
977 fn empty_system_sections_are_hidden() {
953 fn empty_system_sections_are_hidden() {
978 let chats = vec![chat("a", "group", false)];
954 let chats = vec![chat("a", "group", false)];
979 let directory = sectioned_directory(true, true, Vec::new());
955 let directory = sectioned_directory(true, Vec::new());
980 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
956 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
981 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
957 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
982 }
958 }
@@ -989,7 +965,6 @@ mod tests {
989 meeting_chat("sync"),
965 meeting_chat("sync"),
990 ];
966 ];
991 let directory = sectioned_directory(
967 let directory = sectioned_directory(
992 true,
993 true,
968 true,
994 vec![
969 vec![
995 folder("muted-id", FolderKind::Muted, &[]),
970 folder("muted-id", FolderKind::Muted, &[]),
@@ -1000,13 +975,10 @@ mod tests {
1000 );
975 );
1001 let collapsed: HashSet<String> = ["muted-id".to_owned()].into();
976 let collapsed: HashSet<String> = ["muted-id".to_owned()].into();
1002 let sections = build_sections(&input(&chats, &directory, &collapsed));
977 let sections = build_sections(&input(&chats, &directory, &collapsed));
1003 assert_eq!(
978 assert_eq!(section_ids(&sections), vec!["muted-id", "fav", "recent-id"]);
1004 section_ids(&sections),
1005 vec!["muted-id", "fav", "recent-id", "meeting-id"]
1006 );
1007 assert!(sections[0].collapsed);
979 assert!(sections[0].collapsed);
1008 assert_eq!(sections[0].name, MUTED_NAME);
980 assert_eq!(sections[0].name, MUTED_NAME);
1009 assert_eq!(sections[3].name, MEETING_NAME);
981 assert_eq!(item_ids(&sections[2]), vec!["a", "sync"]);
1010 }
982 }
1011
983
1012 #[test]
984 #[test]
@@ -1070,14 +1042,14 @@ mod tests {
1070 }
1042 }
1071
1043
1072 #[test]
1044 #[test]
1073 fn meeting_chats_keep_their_unread_count() {
1045 fn meeting_chats_keep_their_unread_count_in_others() {
1074 let mut sync = meeting_chat("sync");
1046 let mut sync = meeting_chat("sync");
1075 sync.unread = true;
1047 sync.unread = true;
1076 let chats = vec![sync];
1048 let chats = vec![sync];
1077 let mut directory = sectioned_directory(true, true, Vec::new());
1049 let mut directory = sectioned_directory(true, Vec::new());
1078 directory.unread_counts.insert("sync".into(), 3);
1050 directory.unread_counts.insert("sync".into(), 3);
1079 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1051 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1080 assert_eq!(sections[0].id, MEETING_ID);
1052 assert_eq!(sections[0].id, OTHERS_ID);
1081 assert_eq!(sections[0].items[0].unread, Unread::Count(3));
1053 assert_eq!(sections[0].items[0].unread, Unread::Count(3));
1082 assert_eq!(sections[0].unread_chats, 1);
1054 assert_eq!(sections[0].unread_chats, 1);
1083 }
1055 }
crates/app/src/views/sidebar.rs +20 −0
@@ -40,6 +40,7 @@ const SECTION_HEIGHT: f32 = 30.;
40 40 const SECTION_GAP: f32 = 4.;
41 41 const HINT_HEIGHT: f32 = 26.;
42 42 const SEE_MORE_HEIGHT: f32 = 28.;
43 const LOADING_OLDER_LABEL: &str = "Loading older chats";
43 44 const FALLBACK_VIEWPORT: f32 = 900.;
44 45 const CALLS_REFRESH: Duration = Duration::from_secs(30);
45 46 const VIEWPORT_MARGIN: f32 = 300.;
@@ -929,6 +930,25 @@ impl SidebarView {
929 930 y += HINT_HEIGHT;
930 931 }
931 932 }
933 let (has_older, loading_older) = self.state.read(cx).older_chats();
934 if has_older && y <= visible_to {
935 let state = self.state.clone();
936 cx.defer(move |cx| state.read(cx).request_older_chats());
937 }
938 if loading_older {
939 list = with_spacer(list, &mut skipped_height);
940 list = list.child(
941 div()
942 .pl(px(16. + AVATAR_SIZE + 12.))
943 .h(px(SEE_MORE_HEIGHT))
944 .flex()
945 .items_center()
946 .text_size(px(12.5))
947 .italic()
948 .text_color(theme::text_faint())
949 .child(LOADING_OLDER_LABEL),
950 );
951 }
932 952 list = with_spacer(list, &mut skipped_height);
933 953 self.request_lazy_data(faces, presence_users, cx);
934 954 div()
@@ -40,6 +40,7 @@ const SECTION_HEIGHT: f32 = 30.;
40const SECTION_GAP: f32 = 4.;
40const SECTION_GAP: f32 = 4.;
41const HINT_HEIGHT: f32 = 26.;
41const HINT_HEIGHT: f32 = 26.;
42const SEE_MORE_HEIGHT: f32 = 28.;
42const SEE_MORE_HEIGHT: f32 = 28.;
43const LOADING_OLDER_LABEL: &str = "Loading older chats";
43const FALLBACK_VIEWPORT: f32 = 900.;
44const FALLBACK_VIEWPORT: f32 = 900.;
44const CALLS_REFRESH: Duration = Duration::from_secs(30);
45const CALLS_REFRESH: Duration = Duration::from_secs(30);
45const VIEWPORT_MARGIN: f32 = 300.;
46const VIEWPORT_MARGIN: f32 = 300.;
@@ -929,6 +930,25 @@ impl SidebarView {
929 y += HINT_HEIGHT;
930 y += HINT_HEIGHT;
930 }
931 }
931 }
932 }
933 let (has_older, loading_older) = self.state.read(cx).older_chats();
934 if has_older && y <= visible_to {
935 let state = self.state.clone();
936 cx.defer(move |cx| state.read(cx).request_older_chats());
937 }
938 if loading_older {
939 list = with_spacer(list, &mut skipped_height);
940 list = list.child(
941 div()
942 .pl(px(16. + AVATAR_SIZE + 12.))
943 .h(px(SEE_MORE_HEIGHT))
944 .flex()
945 .items_center()
946 .text_size(px(12.5))
947 .italic()
948 .text_color(theme::text_faint())
949 .child(LOADING_OLDER_LABEL),
950 );
951 }
932 list = with_spacer(list, &mut skipped_height);
952 list = with_spacer(list, &mut skipped_height);
933 self.request_lazy_data(faces, presence_users, cx);
953 self.request_lazy_data(faces, presence_users, cx);
934 div()
954 div()
crates/app/src/views/status_menu.rs +0 −6
@@ -249,12 +249,6 @@ fn chat_list_item(
249 249 "Show muted chats in own section",
250 250 settings.enabled(ChatSection::Muted),
251 251 ))
252 .item(section_toggle(
253 &app,
254 ChatSection::Meeting,
255 "Show meeting chats in own section",
256 settings.enabled(ChatSection::Meeting),
257 ))
258 252 });
259 253 PopupMenuItem::submenu("Chat list", submenu).icon(menu_icon(IconName::LayoutList))
260 254 }
@@ -249,12 +249,6 @@ fn chat_list_item(
249 "Show muted chats in own section",
249 "Show muted chats in own section",
250 settings.enabled(ChatSection::Muted),
250 settings.enabled(ChatSection::Muted),
251 ))
251 ))
252 .item(section_toggle(
253 &app,
254 ChatSection::Meeting,
255 "Show meeting chats in own section",
256 settings.enabled(ChatSection::Meeting),
257 ))
258 });
252 });
259 PopupMenuItem::submenu("Chat list", submenu).icon(menu_icon(IconName::LayoutList))
253 PopupMenuItem::submenu("Chat list", submenu).icon(menu_icon(IconName::LayoutList))
260}
254}
crates/chatsvc/src/conversations.rs +67 −14
@@ -10,6 +10,13 @@ const PAGE_SIZE: usize = 200;
10 10 const MAX_PAGES: usize = 100;
11 11 const ALERTS_OFF: &str = "false";
12 12
13 #[derive(Debug, Clone, PartialEq, Eq)]
14 pub struct ConversationState {
15 pub id: String,
16 pub muted: bool,
17 pub hidden: Option<bool>,
18 }
19
13 20 pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
14 21 transport: T,
15 22 base_url: String,
@@ -43,7 +50,7 @@ impl<T: MessageTransport> Conversations<T> {
43 50 )
44 51 }
45 52
46 pub async fn conversation_mute_states(&self) -> Result<Vec<(String, bool)>> {
53 pub async fn conversation_states(&self) -> Result<Vec<ConversationState>> {
47 54 let url = format!(
48 55 "{}?view=msnp24Equivalent&pageSize={PAGE_SIZE}",
49 56 self.base_url
@@ -56,7 +63,7 @@ impl<T: MessageTransport> Conversations<T> {
56 63 };
57 64 let answer = self.transport.send(Request::get(&url)).await?;
58 65 ensure_success(&answer)?;
59 states.extend(mute_states_in_page(&answer.body)?);
66 states.extend(states_in_page(&answer.body)?);
60 67 next_url = backward_link(&answer.body).filter(|link| *link != url);
61 68 }
62 69 Ok(states)
@@ -101,7 +108,20 @@ fn backward_link(body: &Value) -> Option<String> {
101 108 .map(str::to_owned)
102 109 }
103 110
104 fn mute_states_in_page(body: &Value) -> Result<Vec<(String, bool)>> {
111 fn hidden_flag(conversation: &Value) -> Option<bool> {
112 [
113 &conversation["threadProperties"]["hidden"],
114 &conversation["properties"]["hidden"],
115 ]
116 .into_iter()
117 .find_map(|value| match value {
118 Value::Bool(flag) => Some(*flag),
119 Value::String(text) => text.parse().ok(),
120 _ => None,
121 })
122 }
123
124 fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
105 125 let conversations = body
106 126 .get("conversations")
107 127 .and_then(Value::as_array)
@@ -111,7 +131,11 @@ fn mute_states_in_page(body: &Value) -> Result<Vec<(String, bool)>> {
111 131 .filter_map(|conversation| {
112 132 let id = conversation["id"].as_str()?;
113 133 let muted = conversation["properties"]["alerts"].as_str() == Some(ALERTS_OFF);
114 Some((id.to_owned(), muted))
134 Some(ConversationState {
135 id: id.to_owned(),
136 muted,
137 hidden: hidden_flag(conversation),
138 })
115 139 })
116 140 .collect())
117 141 }
@@ -149,6 +173,14 @@ mod tests {
149 173 }
150 174 }
151 175
176 fn state(id: &str, muted: bool) -> ConversationState {
177 ConversationState {
178 id: id.to_owned(),
179 muted,
180 hidden: None,
181 }
182 }
183
152 184 const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations";
153 185
154 186 #[tokio::test]
@@ -165,16 +197,16 @@ mod tests {
165 197 }),
166 198 )]);
167 199 let states = Conversations::with_transport(&transport, "emea")
168 .conversation_mute_states()
200 .conversation_states()
169 201 .await
170 202 .unwrap();
171 203 assert_eq!(
172 204 states,
173 205 vec![
174 ("19:a".to_owned(), true),
175 ("19:b".to_owned(), false),
176 ("19:c".to_owned(), false),
177 ("19:d".to_owned(), false),
206 state("19:a", true),
207 state("19:b", false),
208 state("19:c", false),
209 state("19:d", false),
178 210 ]
179 211 );
180 212 let requests = transport.requests.lock().unwrap();
@@ -205,15 +237,15 @@ mod tests {
205 237 (200, json!({"conversations": [{"id": "19:oldest"}]})),
206 238 ]);
207 239 let states = Conversations::with_transport(&transport, "emea")
208 .conversation_mute_states()
240 .conversation_states()
209 241 .await
210 242 .unwrap();
211 243 assert_eq!(
212 244 states,
213 245 vec![
214 ("19:a".to_owned(), false),
215 ("19:old".to_owned(), true),
216 ("19:oldest".to_owned(), false),
246 state("19:a", false),
247 state("19:old", true),
248 state("19:oldest", false),
217 249 ]
218 250 );
219 251 let requests = transport.requests.lock().unwrap();
@@ -225,11 +257,32 @@ mod tests {
225 257 assert_eq!(urls[2], "https://example.test/page3");
226 258 }
227 259
260 #[tokio::test]
261 async fn hidden_flag_is_read_from_the_thread_properties_as_text_or_bool() {
262 let transport = canned(vec![(
263 200,
264 json!({
265 "conversations": [
266 {"id": "19:a", "threadProperties": {"hidden": "true"}},
267 {"id": "19:b", "threadProperties": {"hidden": "false"}},
268 {"id": "19:c", "properties": {"hidden": true}},
269 {"id": "19:d", "properties": {}},
270 ],
271 }),
272 )]);
273 let states = Conversations::with_transport(&transport, "emea")
274 .conversation_states()
275 .await
276 .unwrap();
277 let hidden: Vec<Option<bool>> = states.iter().map(|state| state.hidden).collect();
278 assert_eq!(hidden, [Some(true), Some(false), Some(true), None]);
279 }
280
228 281 #[tokio::test]
229 282 async fn mute_states_fail_on_an_error_status() {
230 283 let transport = canned(vec![(500, Value::Null)]);
231 284 let outcome = Conversations::with_transport(&transport, "emea")
232 .conversation_mute_states()
285 .conversation_states()
233 286 .await;
234 287 assert!(outcome.is_err());
235 288 }
@@ -10,6 +10,13 @@ const PAGE_SIZE: usize = 200;
10const MAX_PAGES: usize = 100;
10const MAX_PAGES: usize = 100;
11const ALERTS_OFF: &str = "false";
11const ALERTS_OFF: &str = "false";
12
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct ConversationState {
15 pub id: String,
16 pub muted: bool,
17 pub hidden: Option<bool>,
18}
19
13pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
20pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
14 transport: T,
21 transport: T,
15 base_url: String,
22 base_url: String,
@@ -43,7 +50,7 @@ impl<T: MessageTransport> Conversations<T> {
43 )
50 )
44 }
51 }
45
52
46 pub async fn conversation_mute_states(&self) -> Result<Vec<(String, bool)>> {
53 pub async fn conversation_states(&self) -> Result<Vec<ConversationState>> {
47 let url = format!(
54 let url = format!(
48 "{}?view=msnp24Equivalent&pageSize={PAGE_SIZE}",
55 "{}?view=msnp24Equivalent&pageSize={PAGE_SIZE}",
49 self.base_url
56 self.base_url
@@ -56,7 +63,7 @@ impl<T: MessageTransport> Conversations<T> {
56 };
63 };
57 let answer = self.transport.send(Request::get(&url)).await?;
64 let answer = self.transport.send(Request::get(&url)).await?;
58 ensure_success(&answer)?;
65 ensure_success(&answer)?;
59 states.extend(mute_states_in_page(&answer.body)?);
66 states.extend(states_in_page(&answer.body)?);
60 next_url = backward_link(&answer.body).filter(|link| *link != url);
67 next_url = backward_link(&answer.body).filter(|link| *link != url);
61 }
68 }
62 Ok(states)
69 Ok(states)
@@ -101,7 +108,20 @@ fn backward_link(body: &Value) -> Option<String> {
101 .map(str::to_owned)
108 .map(str::to_owned)
102}
109}
103
110
104fn mute_states_in_page(body: &Value) -> Result<Vec<(String, bool)>> {
111fn hidden_flag(conversation: &Value) -> Option<bool> {
112 [
113 &conversation["threadProperties"]["hidden"],
114 &conversation["properties"]["hidden"],
115 ]
116 .into_iter()
117 .find_map(|value| match value {
118 Value::Bool(flag) => Some(*flag),
119 Value::String(text) => text.parse().ok(),
120 _ => None,
121 })
122}
123
124fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
105 let conversations = body
125 let conversations = body
106 .get("conversations")
126 .get("conversations")
107 .and_then(Value::as_array)
127 .and_then(Value::as_array)
@@ -111,7 +131,11 @@ fn mute_states_in_page(body: &Value) -> Result<Vec<(String, bool)>> {
111 .filter_map(|conversation| {
131 .filter_map(|conversation| {
112 let id = conversation["id"].as_str()?;
132 let id = conversation["id"].as_str()?;
113 let muted = conversation["properties"]["alerts"].as_str() == Some(ALERTS_OFF);
133 let muted = conversation["properties"]["alerts"].as_str() == Some(ALERTS_OFF);
114 Some((id.to_owned(), muted))
134 Some(ConversationState {
135 id: id.to_owned(),
136 muted,
137 hidden: hidden_flag(conversation),
138 })
115 })
139 })
116 .collect())
140 .collect())
117}
141}
@@ -149,6 +173,14 @@ mod tests {
149 }
173 }
150 }
174 }
151
175
176 fn state(id: &str, muted: bool) -> ConversationState {
177 ConversationState {
178 id: id.to_owned(),
179 muted,
180 hidden: None,
181 }
182 }
183
152 const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations";
184 const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations";
153
185
154 #[tokio::test]
186 #[tokio::test]
@@ -165,16 +197,16 @@ mod tests {
165 }),
197 }),
166 )]);
198 )]);
167 let states = Conversations::with_transport(&transport, "emea")
199 let states = Conversations::with_transport(&transport, "emea")
168 .conversation_mute_states()
200 .conversation_states()
169 .await
201 .await
170 .unwrap();
202 .unwrap();
171 assert_eq!(
203 assert_eq!(
172 states,
204 states,
173 vec![
205 vec![
174 ("19:a".to_owned(), true),
206 state("19:a", true),
175 ("19:b".to_owned(), false),
207 state("19:b", false),
176 ("19:c".to_owned(), false),
208 state("19:c", false),
177 ("19:d".to_owned(), false),
209 state("19:d", false),
178 ]
210 ]
179 );
211 );
180 let requests = transport.requests.lock().unwrap();
212 let requests = transport.requests.lock().unwrap();
@@ -205,15 +237,15 @@ mod tests {
205 (200, json!({"conversations": [{"id": "19:oldest"}]})),
237 (200, json!({"conversations": [{"id": "19:oldest"}]})),
206 ]);
238 ]);
207 let states = Conversations::with_transport(&transport, "emea")
239 let states = Conversations::with_transport(&transport, "emea")
208 .conversation_mute_states()
240 .conversation_states()
209 .await
241 .await
210 .unwrap();
242 .unwrap();
211 assert_eq!(
243 assert_eq!(
212 states,
244 states,
213 vec![
245 vec![
214 ("19:a".to_owned(), false),
246 state("19:a", false),
215 ("19:old".to_owned(), true),
247 state("19:old", true),
216 ("19:oldest".to_owned(), false),
248 state("19:oldest", false),
217 ]
249 ]
218 );
250 );
219 let requests = transport.requests.lock().unwrap();
251 let requests = transport.requests.lock().unwrap();
@@ -225,11 +257,32 @@ mod tests {
225 assert_eq!(urls[2], "https://example.test/page3");
257 assert_eq!(urls[2], "https://example.test/page3");
226 }
258 }
227
259
260 #[tokio::test]
261 async fn hidden_flag_is_read_from_the_thread_properties_as_text_or_bool() {
262 let transport = canned(vec![(
263 200,
264 json!({
265 "conversations": [
266 {"id": "19:a", "threadProperties": {"hidden": "true"}},
267 {"id": "19:b", "threadProperties": {"hidden": "false"}},
268 {"id": "19:c", "properties": {"hidden": true}},
269 {"id": "19:d", "properties": {}},
270 ],
271 }),
272 )]);
273 let states = Conversations::with_transport(&transport, "emea")
274 .conversation_states()
275 .await
276 .unwrap();
277 let hidden: Vec<Option<bool>> = states.iter().map(|state| state.hidden).collect();
278 assert_eq!(hidden, [Some(true), Some(false), Some(true), None]);
279 }
280
228 #[tokio::test]
281 #[tokio::test]
229 async fn mute_states_fail_on_an_error_status() {
282 async fn mute_states_fail_on_an_error_status() {
230 let transport = canned(vec![(500, Value::Null)]);
283 let transport = canned(vec![(500, Value::Null)]);
231 let outcome = Conversations::with_transport(&transport, "emea")
284 let outcome = Conversations::with_transport(&transport, "emea")
232 .conversation_mute_states()
285 .conversation_states()
233 .await;
286 .await;
234 assert!(outcome.is_err());
287 assert!(outcome.is_err());
235 }
288 }
crates/chatsvc/src/lib.rs +1 −1
@@ -27,7 +27,7 @@ pub use cards::{
27 27 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
28 28 };
29 29 pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
30 pub use conversations::Conversations;
30 pub use conversations::{ConversationState, Conversations};
31 31 pub use drafts::{ScheduledDraft, ScheduledDrafts};
32 32 pub use error::{Error, Result};
33 33 pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
@@ -27,7 +27,7 @@ pub use cards::{
27 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
27 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
28};
28};
29pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
29pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
30pub use conversations::Conversations;
30pub use conversations::{ConversationState, Conversations};
31pub use drafts::{ScheduledDraft, ScheduledDrafts};
31pub use drafts::{ScheduledDraft, ScheduledDrafts};
32pub use error::{Error, Result};
32pub use error::{Error, Result};
33pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
33pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
crates/chatsvc/src/pins/chats.rs +76 −2
@@ -59,7 +59,7 @@ impl<T: CsaTransport> Pins<T> {
59 59 let url = format!("{}/conversationFolders?{FOLDER_QUERY}", self.base_url);
60 60 let answer = self.transport.send(Request::get(url)).await?;
61 61 ensure_success(&answer)?;
62 parse_pinned_chats(&answer.body)
62 with_answer_context(parse_pinned_chats(&answer.body), &answer)
63 63 }
64 64
65 65 pub async fn pin_chat(&self, chat_id: &str, index: Option<usize>) -> Result<PinnedChats> {
@@ -110,13 +110,37 @@ impl<T: CsaTransport> Pins<T> {
110 110 }
111 111
112 112 pub(super) fn ensure_success(answer: &ApiResponse) -> Result<()> {
113 if answer.is_success() {
113 if (200..300).contains(&answer.status) {
114 114 Ok(())
115 115 } else {
116 116 Err(api_error(answer))
117 117 }
118 118 }
119 119
120 pub(super) fn describe_answer(answer: &ApiResponse) -> String {
121 let shape = match &answer.body {
122 Value::Object(fields) => {
123 let keys: Vec<&str> = fields.keys().map(String::as_str).collect();
124 format!("object with keys [{}]", keys.join(", "))
125 }
126 Value::Array(items) => format!("array of {} items", items.len()),
127 Value::String(text) => format!("string of {} characters", text.chars().count()),
128 Value::Null => "null".to_owned(),
129 Value::Bool(_) => "boolean".to_owned(),
130 Value::Number(_) => "number".to_owned(),
131 };
132 format!("HTTP {}, {shape}", answer.status)
133 }
134
135 pub(super) fn with_answer_context<T>(parsed: Result<T>, answer: &ApiResponse) -> Result<T> {
136 parsed.map_err(|error| match error {
137 Error::UnexpectedAnswer(reason) => {
138 Error::UnexpectedAnswer(format!("{reason} ({})", describe_answer(answer)))
139 }
140 other => other,
141 })
142 }
143
120 144 pub(super) fn api_error(answer: &ApiResponse) -> Error {
121 145 Error::Session(session::Error::api(
122 146 answer.status,
@@ -124,3 +148,53 @@ pub(super) fn api_error(answer: &ApiResponse) -> Error {
124 148 answer.body.clone(),
125 149 ))
126 150 }
151
152 #[cfg(test)]
153 mod tests {
154 use super::*;
155
156 fn answer(status: u16, body: Value) -> ApiResponse {
157 ApiResponse {
158 status,
159 body,
160 retry_after: None,
161 }
162 }
163
164 #[test]
165 fn describes_an_object_by_status_and_key_names_only() {
166 let described = describe_answer(&answer(200, json!({"secret": "value", "other": 1})));
167 assert_eq!(described, "HTTP 200, object with keys [other, secret]");
168 assert!(!described.contains("value"));
169 }
170
171 #[test]
172 fn describes_other_bodies_by_type_and_length() {
173 assert_eq!(
174 describe_answer(&answer(200, json!([1, 2, 3]))),
175 "HTTP 200, array of 3 items"
176 );
177 assert_eq!(
178 describe_answer(&answer(200, json!("abcd"))),
179 "HTTP 200, string of 4 characters"
180 );
181 assert_eq!(describe_answer(&answer(204, Value::Null)), "HTTP 204, null");
182 }
183
184 #[test]
185 fn a_parse_failure_carries_the_answer_description() {
186 let response = answer(200, json!({"conversationFolders": []}));
187 let error = with_answer_context(parse_pinned_chats(&response.body), &response)
188 .unwrap_err()
189 .to_string();
190 assert!(error.contains("folderHierarchyVersion missing"));
191 assert!(error.contains("HTTP 200, object with keys [conversationFolders]"));
192 }
193
194 #[test]
195 fn redirects_are_not_a_success() {
196 assert!(ensure_success(&answer(200, Value::Null)).is_ok());
197 assert!(ensure_success(&answer(204, Value::Null)).is_ok());
198 assert!(ensure_success(&answer(302, Value::Null)).is_err());
199 }
200 }
@@ -59,7 +59,7 @@ impl<T: CsaTransport> Pins<T> {
59 let url = format!("{}/conversationFolders?{FOLDER_QUERY}", self.base_url);
59 let url = format!("{}/conversationFolders?{FOLDER_QUERY}", self.base_url);
60 let answer = self.transport.send(Request::get(url)).await?;
60 let answer = self.transport.send(Request::get(url)).await?;
61 ensure_success(&answer)?;
61 ensure_success(&answer)?;
62 parse_pinned_chats(&answer.body)
62 with_answer_context(parse_pinned_chats(&answer.body), &answer)
63 }
63 }
64
64
65 pub async fn pin_chat(&self, chat_id: &str, index: Option<usize>) -> Result<PinnedChats> {
65 pub async fn pin_chat(&self, chat_id: &str, index: Option<usize>) -> Result<PinnedChats> {
@@ -110,13 +110,37 @@ impl<T: CsaTransport> Pins<T> {
110}
110}
111
111
112pub(super) fn ensure_success(answer: &ApiResponse) -> Result<()> {
112pub(super) fn ensure_success(answer: &ApiResponse) -> Result<()> {
113 if answer.is_success() {
113 if (200..300).contains(&answer.status) {
114 Ok(())
114 Ok(())
115 } else {
115 } else {
116 Err(api_error(answer))
116 Err(api_error(answer))
117 }
117 }
118}
118}
119
119
120pub(super) fn describe_answer(answer: &ApiResponse) -> String {
121 let shape = match &answer.body {
122 Value::Object(fields) => {
123 let keys: Vec<&str> = fields.keys().map(String::as_str).collect();
124 format!("object with keys [{}]", keys.join(", "))
125 }
126 Value::Array(items) => format!("array of {} items", items.len()),
127 Value::String(text) => format!("string of {} characters", text.chars().count()),
128 Value::Null => "null".to_owned(),
129 Value::Bool(_) => "boolean".to_owned(),
130 Value::Number(_) => "number".to_owned(),
131 };
132 format!("HTTP {}, {shape}", answer.status)
133}
134
135pub(super) fn with_answer_context<T>(parsed: Result<T>, answer: &ApiResponse) -> Result<T> {
136 parsed.map_err(|error| match error {
137 Error::UnexpectedAnswer(reason) => {
138 Error::UnexpectedAnswer(format!("{reason} ({})", describe_answer(answer)))
139 }
140 other => other,
141 })
142}
143
120pub(super) fn api_error(answer: &ApiResponse) -> Error {
144pub(super) fn api_error(answer: &ApiResponse) -> Error {
121 Error::Session(session::Error::api(
145 Error::Session(session::Error::api(
122 answer.status,
146 answer.status,
@@ -124,3 +148,53 @@ pub(super) fn api_error(answer: &ApiResponse) -> Error {
124 answer.body.clone(),
148 answer.body.clone(),
125 ))
149 ))
126}
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155
156 fn answer(status: u16, body: Value) -> ApiResponse {
157 ApiResponse {
158 status,
159 body,
160 retry_after: None,
161 }
162 }
163
164 #[test]
165 fn describes_an_object_by_status_and_key_names_only() {
166 let described = describe_answer(&answer(200, json!({"secret": "value", "other": 1})));
167 assert_eq!(described, "HTTP 200, object with keys [other, secret]");
168 assert!(!described.contains("value"));
169 }
170
171 #[test]
172 fn describes_other_bodies_by_type_and_length() {
173 assert_eq!(
174 describe_answer(&answer(200, json!([1, 2, 3]))),
175 "HTTP 200, array of 3 items"
176 );
177 assert_eq!(
178 describe_answer(&answer(200, json!("abcd"))),
179 "HTTP 200, string of 4 characters"
180 );
181 assert_eq!(describe_answer(&answer(204, Value::Null)), "HTTP 204, null");
182 }
183
184 #[test]
185 fn a_parse_failure_carries_the_answer_description() {
186 let response = answer(200, json!({"conversationFolders": []}));
187 let error = with_answer_context(parse_pinned_chats(&response.body), &response)
188 .unwrap_err()
189 .to_string();
190 assert!(error.contains("folderHierarchyVersion missing"));
191 assert!(error.contains("HTTP 200, object with keys [conversationFolders]"));
192 }
193
194 #[test]
195 fn redirects_are_not_a_success() {
196 assert!(ensure_success(&answer(200, Value::Null)).is_ok());
197 assert!(ensure_success(&answer(204, Value::Null)).is_ok());
198 assert!(ensure_success(&answer(302, Value::Null)).is_err());
199 }
200}
crates/chatsvc/src/pins/folders.rs +2 −2
@@ -2,7 +2,7 @@ use serde_json::{Value, json};
2 2 use session::{Method, Request};
3 3
4 4 use super::Pins;
5 use super::chats::{FOLDER_QUERY, NO_OP_CODES, api_error, ensure_success};
5 use super::chats::{FOLDER_QUERY, NO_OP_CODES, api_error, ensure_success, with_answer_context};
6 6 use super::state::error_code;
7 7 use super::transport::CsaTransport;
8 8 use crate::error::{Error, Result};
@@ -132,7 +132,7 @@ impl<T: CsaTransport> Pins<T> {
132 132 let url = format!("{}/conversationFolders?{FOLDER_QUERY}", self.base_url);
133 133 let answer = self.transport.send(Request::get(url)).await?;
134 134 ensure_success(&answer)?;
135 parse_folders(&answer.body)
135 with_answer_context(parse_folders(&answer.body), &answer)
136 136 }
137 137
138 138 pub async fn move_to_folder(
@@ -2,7 +2,7 @@ use serde_json::{Value, json};
2use session::{Method, Request};
2use session::{Method, Request};
3
3
4use super::Pins;
4use super::Pins;
5use super::chats::{FOLDER_QUERY, NO_OP_CODES, api_error, ensure_success};
5use super::chats::{FOLDER_QUERY, NO_OP_CODES, api_error, ensure_success, with_answer_context};
6use super::state::error_code;
6use super::state::error_code;
7use super::transport::CsaTransport;
7use super::transport::CsaTransport;
8use crate::error::{Error, Result};
8use crate::error::{Error, Result};
@@ -132,7 +132,7 @@ impl<T: CsaTransport> Pins<T> {
132 let url = format!("{}/conversationFolders?{FOLDER_QUERY}", self.base_url);
132 let url = format!("{}/conversationFolders?{FOLDER_QUERY}", self.base_url);
133 let answer = self.transport.send(Request::get(url)).await?;
133 let answer = self.transport.send(Request::get(url)).await?;
134 ensure_success(&answer)?;
134 ensure_success(&answer)?;
135 parse_folders(&answer.body)
135 with_answer_context(parse_folders(&answer.body), &answer)
136 }
136 }
137
137
138 pub async fn move_to_folder(
138 pub async fn move_to_folder(
crates/chatsvc/src/settings.rs +47 −0
@@ -7,6 +7,7 @@ use crate::pins::DEFAULT_REGION;
7 7
8 8 const SETTINGS_KEY: &str = "simpleCollabUserSettings";
9 9 const SETTINGS_ID: &str = "simpleCollabUserSettingsId";
10 const TEAMS_ORDER_KEY: &str = "teamsOrder";
10 11 const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
11 12 const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
12 13 const MUTED_DEFAULT: bool = true;
@@ -78,6 +79,10 @@ impl<T: MessageTransport> UserSettings<T> {
78 79 Ok(parse_chat_sections(&self.properties().await?))
79 80 }
80 81
82 pub async fn teams_order(&self) -> Result<Vec<(String, i64)>> {
83 Ok(parse_teams_order(&self.properties().await?))
84 }
85
81 86 pub async fn set_chat_section(&self, section: ChatSection, enabled: bool) -> Result<()> {
82 87 let properties = self.properties().await?;
83 88 let merged = merge_chat_section(&properties, section, enabled);
@@ -118,6 +123,33 @@ pub fn parse_chat_sections(properties: &Value) -> ChatSectionSettings {
118 123 }
119 124 }
120 125
126 pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {
127 let entries = match properties.get(TEAMS_ORDER_KEY) {
128 Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
129 Some(other) => Some(other.clone()),
130 None => None,
131 };
132 let mut order: Vec<(String, i64)> = entries
133 .as_ref()
134 .and_then(Value::as_array)
135 .map(|entries| {
136 entries
137 .iter()
138 .filter_map(|entry| {
139 let team_id = entry.get("teamId")?.as_str()?.to_owned();
140 let position = entry.get("order")?;
141 let position = position
142 .as_i64()
143 .or_else(|| position.as_str()?.parse().ok())?;
144 Some((team_id, position))
145 })
146 .collect()
147 })
148 .unwrap_or_default();
149 order.sort_by_key(|(_, position)| *position);
150 order
151 }
152
121 153 pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {
122 154 let mut settings = stored_settings(properties);
123 155 settings
@@ -174,6 +206,21 @@ mod tests {
174 206 assert!(parsed.enabled(ChatSection::Meeting));
175 207 }
176 208
209 #[test]
210 fn teams_order_is_read_from_the_json_string_sorted_by_order() {
211 let parsed = parse_teams_order(&json!({
212 TEAMS_ORDER_KEY: r#"[{"teamId":"19:b","order":1},{"teamId":"19:a","order":"0"},{"teamId":"19:c"},{"order":2}]"#,
213 }));
214 assert_eq!(parsed, vec![("19:a".to_owned(), 0), ("19:b".to_owned(), 1)]);
215 }
216
217 #[test]
218 fn teams_order_is_empty_when_missing_or_malformed() {
219 assert!(parse_teams_order(&json!({})).is_empty());
220 assert!(parse_teams_order(&json!({TEAMS_ORDER_KEY: "not json"})).is_empty());
221 assert!(parse_teams_order(&json!({TEAMS_ORDER_KEY: "{}"})).is_empty());
222 }
223
177 224 #[test]
178 225 fn merge_keeps_every_unknown_field_and_the_other_flag() {
179 226 let existing = properties(
@@ -7,6 +7,7 @@ use crate::pins::DEFAULT_REGION;
7
7
8const SETTINGS_KEY: &str = "simpleCollabUserSettings";
8const SETTINGS_KEY: &str = "simpleCollabUserSettings";
9const SETTINGS_ID: &str = "simpleCollabUserSettingsId";
9const SETTINGS_ID: &str = "simpleCollabUserSettingsId";
10const TEAMS_ORDER_KEY: &str = "teamsOrder";
10const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
11const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
11const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
12const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
12const MUTED_DEFAULT: bool = true;
13const MUTED_DEFAULT: bool = true;
@@ -78,6 +79,10 @@ impl<T: MessageTransport> UserSettings<T> {
78 Ok(parse_chat_sections(&self.properties().await?))
79 Ok(parse_chat_sections(&self.properties().await?))
79 }
80 }
80
81
82 pub async fn teams_order(&self) -> Result<Vec<(String, i64)>> {
83 Ok(parse_teams_order(&self.properties().await?))
84 }
85
81 pub async fn set_chat_section(&self, section: ChatSection, enabled: bool) -> Result<()> {
86 pub async fn set_chat_section(&self, section: ChatSection, enabled: bool) -> Result<()> {
82 let properties = self.properties().await?;
87 let properties = self.properties().await?;
83 let merged = merge_chat_section(&properties, section, enabled);
88 let merged = merge_chat_section(&properties, section, enabled);
@@ -118,6 +123,33 @@ pub fn parse_chat_sections(properties: &Value) -> ChatSectionSettings {
118 }
123 }
119}
124}
120
125
126pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {
127 let entries = match properties.get(TEAMS_ORDER_KEY) {
128 Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
129 Some(other) => Some(other.clone()),
130 None => None,
131 };
132 let mut order: Vec<(String, i64)> = entries
133 .as_ref()
134 .and_then(Value::as_array)
135 .map(|entries| {
136 entries
137 .iter()
138 .filter_map(|entry| {
139 let team_id = entry.get("teamId")?.as_str()?.to_owned();
140 let position = entry.get("order")?;
141 let position = position
142 .as_i64()
143 .or_else(|| position.as_str()?.parse().ok())?;
144 Some((team_id, position))
145 })
146 .collect()
147 })
148 .unwrap_or_default();
149 order.sort_by_key(|(_, position)| *position);
150 order
151}
152
121pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {
153pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {
122 let mut settings = stored_settings(properties);
154 let mut settings = stored_settings(properties);
123 settings
155 settings
@@ -174,6 +206,21 @@ mod tests {
174 assert!(parsed.enabled(ChatSection::Meeting));
206 assert!(parsed.enabled(ChatSection::Meeting));
175 }
207 }
176
208
209 #[test]
210 fn teams_order_is_read_from_the_json_string_sorted_by_order() {
211 let parsed = parse_teams_order(&json!({
212 TEAMS_ORDER_KEY: r#"[{"teamId":"19:b","order":1},{"teamId":"19:a","order":"0"},{"teamId":"19:c"},{"order":2}]"#,
213 }));
214 assert_eq!(parsed, vec![("19:a".to_owned(), 0), ("19:b".to_owned(), 1)]);
215 }
216
217 #[test]
218 fn teams_order_is_empty_when_missing_or_malformed() {
219 assert!(parse_teams_order(&json!({})).is_empty());
220 assert!(parse_teams_order(&json!({TEAMS_ORDER_KEY: "not json"})).is_empty());
221 assert!(parse_teams_order(&json!({TEAMS_ORDER_KEY: "{}"})).is_empty());
222 }
223
177 #[test]
224 #[test]
178 fn merge_keeps_every_unknown_field_and_the_other_flag() {
225 fn merge_keeps_every_unknown_field_and_the_other_flag() {
179 let existing = properties(
226 let existing = properties(
crates/core/src/actions.rs +2 −4
@@ -575,10 +575,8 @@ impl<R: Remote> SyncEngine<R> {
575 575 }
576 576
577 577 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
578 if let Some(record) = chat_record(chat, my_user_id) {
579 self.store.upsert_chats(&[record])?;
580 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
581 }
578 self.store.upsert_chats(&[chat_record(chat, my_user_id)])?;
579 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
582 580 Ok(chat.id.clone())
583 581 }
584 582
@@ -575,10 +575,8 @@ impl<R: Remote> SyncEngine<R> {
575 }
575 }
576
576
577 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
577 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
578 if let Some(record) = chat_record(chat, my_user_id) {
578 self.store.upsert_chats(&[chat_record(chat, my_user_id)])?;
579 self.store.upsert_chats(&[record])?;
579 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
580 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
581 }
582 Ok(chat.id.clone())
580 Ok(chat.id.clone())
583 }
581 }
584
582
crates/core/src/chat_paging.rs added +152 −0
@@ -0,0 +1,152 @@
1 #[derive(Debug, Clone, Default, PartialEq, Eq)]
2 pub struct ChatPaging {
3 next_link: Option<String>,
4 exhausted: bool,
5 loading: bool,
6 stalled: bool,
7 }
8
9 impl ChatPaging {
10 pub fn restored(next_link: Option<String>, exhausted: bool) -> Self {
11 ChatPaging {
12 next_link,
13 exhausted,
14 ..ChatPaging::default()
15 }
16 }
17
18 pub fn is_known(&self) -> bool {
19 self.next_link.is_some() || self.exhausted
20 }
21
22 pub fn has_more(&self) -> bool {
23 self.next_link.is_some()
24 }
25
26 pub fn is_loading(&self) -> bool {
27 self.loading
28 }
29
30 pub fn next_link(&self) -> Option<&str> {
31 self.next_link.as_deref()
32 }
33
34 pub fn is_exhausted(&self) -> bool {
35 self.exhausted
36 }
37
38 pub fn begin(&mut self) -> Option<String> {
39 if self.loading || self.stalled {
40 return None;
41 }
42 let link = self.next_link.clone()?;
43 self.loading = true;
44 Some(link)
45 }
46
47 pub fn finish(&mut self, next_link: Option<String>) {
48 self.loading = false;
49 self.exhausted = next_link.is_none();
50 self.next_link = next_link;
51 }
52
53 pub fn fail(&mut self) {
54 self.loading = false;
55 self.stalled = true;
56 }
57
58 pub fn retry(&mut self) {
59 self.stalled = false;
60 }
61
62 pub fn adopt_continuation(&mut self, next_link: Option<String>) {
63 match next_link {
64 Some(link) if self.next_link.is_none() => {
65 self.next_link = Some(link);
66 self.exhausted = false;
67 }
68 Some(_) => {}
69 None => {
70 self.next_link = None;
71 self.exhausted = true;
72 }
73 }
74 }
75 }
76
77 #[cfg(test)]
78 mod tests {
79 use super::*;
80
81 fn with_link(link: &str) -> ChatPaging {
82 ChatPaging::restored(Some(link.to_owned()), false)
83 }
84
85 #[test]
86 fn a_fresh_state_knows_nothing_and_loads_nothing() {
87 let mut paging = ChatPaging::default();
88 assert!(!paging.is_known());
89 assert!(!paging.has_more());
90 assert_eq!(paging.begin(), None);
91 }
92
93 #[test]
94 fn begin_hands_out_the_link_once_while_a_page_is_in_flight() {
95 let mut paging = with_link("page2");
96 assert_eq!(paging.begin(), Some("page2".to_owned()));
97 assert!(paging.is_loading());
98 assert_eq!(paging.begin(), None);
99 }
100
101 #[test]
102 fn finish_with_a_link_allows_the_next_page() {
103 let mut paging = with_link("page2");
104 paging.begin();
105 paging.finish(Some("page3".to_owned()));
106 assert!(!paging.is_loading());
107 assert!(paging.has_more());
108 assert_eq!(paging.begin(), Some("page3".to_owned()));
109 }
110
111 #[test]
112 fn finish_without_a_link_is_done_for_good() {
113 let mut paging = with_link("page2");
114 paging.begin();
115 paging.finish(None);
116 assert!(!paging.has_more());
117 assert!(paging.is_exhausted());
118 assert!(paging.is_known());
119 assert_eq!(paging.begin(), None);
120 }
121
122 #[test]
123 fn a_failed_page_stalls_until_the_next_refresh_retries() {
124 let mut paging = with_link("page2");
125 paging.begin();
126 paging.fail();
127 assert!(!paging.is_loading());
128 assert!(paging.has_more());
129 assert_eq!(paging.begin(), None);
130 paging.retry();
131 assert_eq!(paging.begin(), Some("page2".to_owned()));
132 }
133
134 #[test]
135 fn adopting_a_continuation_keeps_deeper_progress() {
136 let mut paging = with_link("deep");
137 paging.adopt_continuation(Some("shallow".to_owned()));
138 assert_eq!(paging.next_link(), Some("deep"));
139
140 let mut fresh = ChatPaging::default();
141 fresh.adopt_continuation(Some("shallow".to_owned()));
142 assert_eq!(fresh.next_link(), Some("shallow"));
143 }
144
145 #[test]
146 fn adopting_a_complete_walk_marks_everything_loaded() {
147 let mut paging = with_link("deep");
148 paging.adopt_continuation(None);
149 assert!(!paging.has_more());
150 assert!(paging.is_exhausted());
151 }
152 }
@@ -0,0 +1,152 @@
1#[derive(Debug, Clone, Default, PartialEq, Eq)]
2pub struct ChatPaging {
3 next_link: Option<String>,
4 exhausted: bool,
5 loading: bool,
6 stalled: bool,
7}
8
9impl ChatPaging {
10 pub fn restored(next_link: Option<String>, exhausted: bool) -> Self {
11 ChatPaging {
12 next_link,
13 exhausted,
14 ..ChatPaging::default()
15 }
16 }
17
18 pub fn is_known(&self) -> bool {
19 self.next_link.is_some() || self.exhausted
20 }
21
22 pub fn has_more(&self) -> bool {
23 self.next_link.is_some()
24 }
25
26 pub fn is_loading(&self) -> bool {
27 self.loading
28 }
29
30 pub fn next_link(&self) -> Option<&str> {
31 self.next_link.as_deref()
32 }
33
34 pub fn is_exhausted(&self) -> bool {
35 self.exhausted
36 }
37
38 pub fn begin(&mut self) -> Option<String> {
39 if self.loading || self.stalled {
40 return None;
41 }
42 let link = self.next_link.clone()?;
43 self.loading = true;
44 Some(link)
45 }
46
47 pub fn finish(&mut self, next_link: Option<String>) {
48 self.loading = false;
49 self.exhausted = next_link.is_none();
50 self.next_link = next_link;
51 }
52
53 pub fn fail(&mut self) {
54 self.loading = false;
55 self.stalled = true;
56 }
57
58 pub fn retry(&mut self) {
59 self.stalled = false;
60 }
61
62 pub fn adopt_continuation(&mut self, next_link: Option<String>) {
63 match next_link {
64 Some(link) if self.next_link.is_none() => {
65 self.next_link = Some(link);
66 self.exhausted = false;
67 }
68 Some(_) => {}
69 None => {
70 self.next_link = None;
71 self.exhausted = true;
72 }
73 }
74 }
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 fn with_link(link: &str) -> ChatPaging {
82 ChatPaging::restored(Some(link.to_owned()), false)
83 }
84
85 #[test]
86 fn a_fresh_state_knows_nothing_and_loads_nothing() {
87 let mut paging = ChatPaging::default();
88 assert!(!paging.is_known());
89 assert!(!paging.has_more());
90 assert_eq!(paging.begin(), None);
91 }
92
93 #[test]
94 fn begin_hands_out_the_link_once_while_a_page_is_in_flight() {
95 let mut paging = with_link("page2");
96 assert_eq!(paging.begin(), Some("page2".to_owned()));
97 assert!(paging.is_loading());
98 assert_eq!(paging.begin(), None);
99 }
100
101 #[test]
102 fn finish_with_a_link_allows_the_next_page() {
103 let mut paging = with_link("page2");
104 paging.begin();
105 paging.finish(Some("page3".to_owned()));
106 assert!(!paging.is_loading());
107 assert!(paging.has_more());
108 assert_eq!(paging.begin(), Some("page3".to_owned()));
109 }
110
111 #[test]
112 fn finish_without_a_link_is_done_for_good() {
113 let mut paging = with_link("page2");
114 paging.begin();
115 paging.finish(None);
116 assert!(!paging.has_more());
117 assert!(paging.is_exhausted());
118 assert!(paging.is_known());
119 assert_eq!(paging.begin(), None);
120 }
121
122 #[test]
123 fn a_failed_page_stalls_until_the_next_refresh_retries() {
124 let mut paging = with_link("page2");
125 paging.begin();
126 paging.fail();
127 assert!(!paging.is_loading());
128 assert!(paging.has_more());
129 assert_eq!(paging.begin(), None);
130 paging.retry();
131 assert_eq!(paging.begin(), Some("page2".to_owned()));
132 }
133
134 #[test]
135 fn adopting_a_continuation_keeps_deeper_progress() {
136 let mut paging = with_link("deep");
137 paging.adopt_continuation(Some("shallow".to_owned()));
138 assert_eq!(paging.next_link(), Some("deep"));
139
140 let mut fresh = ChatPaging::default();
141 fresh.adopt_continuation(Some("shallow".to_owned()));
142 assert_eq!(fresh.next_link(), Some("shallow"));
143 }
144
145 #[test]
146 fn adopting_a_complete_walk_marks_everything_loaded() {
147 let mut paging = with_link("deep");
148 paging.adopt_continuation(None);
149 assert!(!paging.has_more());
150 assert!(paging.is_exhausted());
151 }
152}
crates/core/src/engine.rs +8 −2
@@ -2,12 +2,13 @@ use std::collections::{HashMap, HashSet};
2 2 use std::sync::atomic::{AtomicBool, Ordering};
3 3 use std::sync::{Arc, Mutex};
4 4
5 use chatsvc::{ChatApp, TrouterEndpoint};
5 use chatsvc::{ChatApp, ConversationState, TrouterEndpoint};
6 6 use chrono::{DateTime, Duration, Utc};
7 7 use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};
8 8 use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};
9 9 use tokio::sync::{OnceCell, broadcast};
10 10
11 use crate::chat_paging::ChatPaging;
11 12 use crate::error::{Error, Result};
12 13 use crate::events::CoreEvent;
13 14 use crate::folders::FolderSource;
@@ -42,7 +43,7 @@ impl Default for SyncConfig {
42 43 fn default() -> Self {
43 44 SyncConfig {
44 45 chat_limit: 200,
45 chat_page_size: 25,
46 chat_page_size: 50,
46 47 page_size: MESSAGE_PAGE_SIZE,
47 48 open_limit: MESSAGE_PAGE_SIZE,
48 49 max_catch_up_pages: 10,
@@ -127,6 +128,8 @@ pub struct SyncEngine<R: Remote = Graph> {
127 128 pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,
128 129 pub(crate) link_previews: Mutex<HashMap<String, Option<LinkPreview>>>,
129 130 pub(crate) links_backfilled: Mutex<HashSet<String>>,
131 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
132 pub(crate) chat_paging: Mutex<ChatPaging>,
130 133 }
131 134
132 135 impl<R: Remote> SyncEngine<R> {
@@ -135,6 +138,7 @@ impl<R: Remote> SyncEngine<R> {
135 138 }
136 139
137 140 pub fn with_config(remote: R, store: Arc<Store>, config: SyncConfig) -> Self {
141 let chat_paging = Mutex::new(crate::sidebar_sync::stored_chat_paging(&store));
138 142 SyncEngine {
139 143 remote,
140 144 store,
@@ -157,6 +161,8 @@ impl<R: Remote> SyncEngine<R> {
157 161 chat_apps: Mutex::new(HashMap::new()),
158 162 link_previews: Mutex::new(HashMap::new()),
159 163 links_backfilled: Mutex::new(HashSet::new()),
164 chat_states: Mutex::new(HashMap::new()),
165 chat_paging,
160 166 }
161 167 }
162 168
@@ -2,12 +2,13 @@ use std::collections::{HashMap, HashSet};
2use std::sync::atomic::{AtomicBool, Ordering};
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::sync::{Arc, Mutex};
3use std::sync::{Arc, Mutex};
4
4
5use chatsvc::{ChatApp, TrouterEndpoint};
5use chatsvc::{ChatApp, ConversationState, TrouterEndpoint};
6use chrono::{DateTime, Duration, Utc};
6use chrono::{DateTime, Duration, Utc};
7use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};
7use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};
8use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};
8use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};
9use tokio::sync::{OnceCell, broadcast};
9use tokio::sync::{OnceCell, broadcast};
10
10
11use crate::chat_paging::ChatPaging;
11use crate::error::{Error, Result};
12use crate::error::{Error, Result};
12use crate::events::CoreEvent;
13use crate::events::CoreEvent;
13use crate::folders::FolderSource;
14use crate::folders::FolderSource;
@@ -42,7 +43,7 @@ impl Default for SyncConfig {
42 fn default() -> Self {
43 fn default() -> Self {
43 SyncConfig {
44 SyncConfig {
44 chat_limit: 200,
45 chat_limit: 200,
45 chat_page_size: 25,
46 chat_page_size: 50,
46 page_size: MESSAGE_PAGE_SIZE,
47 page_size: MESSAGE_PAGE_SIZE,
47 open_limit: MESSAGE_PAGE_SIZE,
48 open_limit: MESSAGE_PAGE_SIZE,
48 max_catch_up_pages: 10,
49 max_catch_up_pages: 10,
@@ -127,6 +128,8 @@ pub struct SyncEngine<R: Remote = Graph> {
127 pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,
128 pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,
128 pub(crate) link_previews: Mutex<HashMap<String, Option<LinkPreview>>>,
129 pub(crate) link_previews: Mutex<HashMap<String, Option<LinkPreview>>>,
129 pub(crate) links_backfilled: Mutex<HashSet<String>>,
130 pub(crate) links_backfilled: Mutex<HashSet<String>>,
131 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
132 pub(crate) chat_paging: Mutex<ChatPaging>,
130}
133}
131
134
132impl<R: Remote> SyncEngine<R> {
135impl<R: Remote> SyncEngine<R> {
@@ -135,6 +138,7 @@ impl<R: Remote> SyncEngine<R> {
135 }
138 }
136
139
137 pub fn with_config(remote: R, store: Arc<Store>, config: SyncConfig) -> Self {
140 pub fn with_config(remote: R, store: Arc<Store>, config: SyncConfig) -> Self {
141 let chat_paging = Mutex::new(crate::sidebar_sync::stored_chat_paging(&store));
138 SyncEngine {
142 SyncEngine {
139 remote,
143 remote,
140 store,
144 store,
@@ -157,6 +161,8 @@ impl<R: Remote> SyncEngine<R> {
157 chat_apps: Mutex::new(HashMap::new()),
161 chat_apps: Mutex::new(HashMap::new()),
158 link_previews: Mutex::new(HashMap::new()),
162 link_previews: Mutex::new(HashMap::new()),
159 links_backfilled: Mutex::new(HashSet::new()),
163 links_backfilled: Mutex::new(HashSet::new()),
164 chat_states: Mutex::new(HashMap::new()),
165 chat_paging,
160 }
166 }
161 }
167 }
162
168
crates/core/src/folders.rs +49 −2
@@ -102,10 +102,13 @@ impl FolderSource for ChatsvcFolderSource {
102 102 .await
103 103 .unwrap_or_default()
104 104 };
105 Ok(layout
105 let order = self.settings.teams_order().await.unwrap_or_default();
106 let mut records: Vec<TeamLayoutRecord> = layout
106 107 .into_iter()
107 108 .map(|team| layout_record(team, &fallback))
108 .collect())
109 .collect();
110 sort_teams_by_order(&mut records, &order);
111 Ok(records)
109 112 })
110 113 }
111 114
@@ -178,6 +181,19 @@ fn convert(folders: chatsvc::Folders) -> Vec<ChatFolder> {
178 181 .collect()
179 182 }
180 183
184 fn sort_teams_by_order(teams: &mut [TeamLayoutRecord], order: &[(String, i64)]) {
185 let positions: HashMap<&str, i64> = order
186 .iter()
187 .map(|(team_id, position)| (team_id.as_str(), *position))
188 .collect();
189 teams.sort_by_key(|team| {
190 positions
191 .get(team.team_id.as_str())
192 .copied()
193 .unwrap_or(i64::MAX)
194 });
195 }
196
181 197 fn resolve_notifications(
182 198 channel: &chatsvc::ChannelLayout,
183 199 fallback: &HashMap<String, ChannelNotifications>,
@@ -451,6 +467,37 @@ mod tests {
451 467 }
452 468 }
453 469
470 fn team(team_id: &str) -> TeamLayoutRecord {
471 TeamLayoutRecord {
472 team_id: team_id.into(),
473 hidden: false,
474 channels: Vec::new(),
475 }
476 }
477
478 fn team_ids(teams: &[TeamLayoutRecord]) -> Vec<&str> {
479 teams.iter().map(|team| team.team_id.as_str()).collect()
480 }
481
482 #[test]
483 fn listed_teams_come_first_by_order_and_unlisted_follow_in_server_order() {
484 let mut teams = vec![team("x"), team("b"), team("y"), team("a"), team("z")];
485 let order = vec![
486 ("a".to_owned(), 0),
487 ("b".to_owned(), 1),
488 ("gone".to_owned(), 2),
489 ];
490 sort_teams_by_order(&mut teams, &order);
491 assert_eq!(team_ids(&teams), ["a", "b", "x", "y", "z"]);
492 }
493
494 #[test]
495 fn an_empty_order_keeps_the_server_order() {
496 let mut teams = vec![team("c"), team("a"), team("b")];
497 sort_teams_by_order(&mut teams, &[]);
498 assert_eq!(team_ids(&teams), ["c", "a", "b"]);
499 }
500
454 501 #[test]
455 502 fn channel_value_beats_the_notification_service_beats_the_followed_flag() {
456 503 let off = level(ChannelNotificationLevel::Off, false);
@@ -102,10 +102,13 @@ impl FolderSource for ChatsvcFolderSource {
102 .await
102 .await
103 .unwrap_or_default()
103 .unwrap_or_default()
104 };
104 };
105 Ok(layout
105 let order = self.settings.teams_order().await.unwrap_or_default();
106 let mut records: Vec<TeamLayoutRecord> = layout
106 .into_iter()
107 .into_iter()
107 .map(|team| layout_record(team, &fallback))
108 .map(|team| layout_record(team, &fallback))
108 .collect())
109 .collect();
110 sort_teams_by_order(&mut records, &order);
111 Ok(records)
109 })
112 })
110 }
113 }
111
114
@@ -178,6 +181,19 @@ fn convert(folders: chatsvc::Folders) -> Vec<ChatFolder> {
178 .collect()
181 .collect()
179}
182}
180
183
184fn sort_teams_by_order(teams: &mut [TeamLayoutRecord], order: &[(String, i64)]) {
185 let positions: HashMap<&str, i64> = order
186 .iter()
187 .map(|(team_id, position)| (team_id.as_str(), *position))
188 .collect();
189 teams.sort_by_key(|team| {
190 positions
191 .get(team.team_id.as_str())
192 .copied()
193 .unwrap_or(i64::MAX)
194 });
195}
196
181fn resolve_notifications(
197fn resolve_notifications(
182 channel: &chatsvc::ChannelLayout,
198 channel: &chatsvc::ChannelLayout,
183 fallback: &HashMap<String, ChannelNotifications>,
199 fallback: &HashMap<String, ChannelNotifications>,
@@ -451,6 +467,37 @@ mod tests {
451 }
467 }
452 }
468 }
453
469
470 fn team(team_id: &str) -> TeamLayoutRecord {
471 TeamLayoutRecord {
472 team_id: team_id.into(),
473 hidden: false,
474 channels: Vec::new(),
475 }
476 }
477
478 fn team_ids(teams: &[TeamLayoutRecord]) -> Vec<&str> {
479 teams.iter().map(|team| team.team_id.as_str()).collect()
480 }
481
482 #[test]
483 fn listed_teams_come_first_by_order_and_unlisted_follow_in_server_order() {
484 let mut teams = vec![team("x"), team("b"), team("y"), team("a"), team("z")];
485 let order = vec![
486 ("a".to_owned(), 0),
487 ("b".to_owned(), 1),
488 ("gone".to_owned(), 2),
489 ];
490 sort_teams_by_order(&mut teams, &order);
491 assert_eq!(team_ids(&teams), ["a", "b", "x", "y", "z"]);
492 }
493
494 #[test]
495 fn an_empty_order_keeps_the_server_order() {
496 let mut teams = vec![team("c"), team("a"), team("b")];
497 sort_teams_by_order(&mut teams, &[]);
498 assert_eq!(team_ids(&teams), ["c", "a", "b"]);
499 }
500
454 #[test]
501 #[test]
455 fn channel_value_beats_the_notification_service_beats_the_followed_flag() {
502 fn channel_value_beats_the_notification_service_beats_the_followed_flag() {
456 let off = level(ChannelNotificationLevel::Off, false);
503 let off = level(ChannelNotificationLevel::Off, false);
crates/core/src/lib.rs +1 −0
@@ -10,6 +10,7 @@ mod card_table;
10 10 mod card_widgets;
11 11 mod card_width;
12 12 mod channel_sync;
13 mod chat_paging;
13 14 mod download;
14 15 mod draft;
15 16 mod engine;
@@ -10,6 +10,7 @@ mod card_table;
10mod card_widgets;
10mod card_widgets;
11mod card_width;
11mod card_width;
12mod channel_sync;
12mod channel_sync;
13mod chat_paging;
13mod download;
14mod download;
14mod draft;
15mod draft;
15mod engine;
16mod engine;
crates/core/src/mapping.rs +9 −10
@@ -10,15 +10,14 @@ use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
10 10
11 11 const NO_NAME: &str = "?";
12 12
13 pub fn chat_record(chat: &Chat, my_user_id: &str) -> Option<ChatRecord> {
14 if chat
15 .viewpoint
13 pub fn graph_hidden(chat: &Chat) -> bool {
14 chat.viewpoint
16 15 .as_ref()
17 16 .and_then(|viewpoint| viewpoint.is_hidden)
18 17 == Some(true)
19 {
20 return None;
21 }
18 }
19
20 pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
22 21 let others: Vec<&graph::Member> = chat
23 22 .members
24 23 .iter()
@@ -40,7 +39,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> Option<ChatRecord> {
40 39 .as_ref()
41 40 .map(OwnedPreview::from_graph);
42 41 let last_event_system = preview.as_ref().is_some_and(|preview| preview.system);
43 Some(ChatRecord {
42 ChatRecord {
44 43 id: chat.id.clone(),
45 44 kind: chat.chat_type.clone(),
46 45 title: chat.title(my_user_id),
@@ -71,7 +70,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> Option<ChatRecord> {
71 70 .as_ref()
72 71 .and_then(|preview| preview.sender_name.clone()),
73 72 last_event_system,
74 })
73 }
75 74 }
76 75
77 76 fn member_name(member: &graph::Member) -> &str {
@@ -314,7 +313,7 @@ mod tests {
314 313 "createdDateTime": "2026-10-06T10:00:00Z",
315 314 "from": null,
316 315 }));
317 let record = chat_record(&chat, "me").unwrap();
316 let record = chat_record(&chat, "me");
318 317 assert!(!record.unread);
319 318 assert!(record.last_event_system);
320 319 }
@@ -327,7 +326,7 @@ mod tests {
327 326 "createdDateTime": "2026-10-06T10:00:00Z",
328 327 "from": {"user": {"id": "other"}},
329 328 }));
330 let record = chat_record(&chat, "me").unwrap();
329 let record = chat_record(&chat, "me");
331 330 assert!(record.unread);
332 331 assert!(!record.last_event_system);
333 332 }
@@ -10,15 +10,14 @@ use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
10
10
11const NO_NAME: &str = "?";
11const NO_NAME: &str = "?";
12
12
13pub fn chat_record(chat: &Chat, my_user_id: &str) -> Option<ChatRecord> {
13pub fn graph_hidden(chat: &Chat) -> bool {
14 if chat
14 chat.viewpoint
15 .viewpoint
16 .as_ref()
15 .as_ref()
17 .and_then(|viewpoint| viewpoint.is_hidden)
16 .and_then(|viewpoint| viewpoint.is_hidden)
18 == Some(true)
17 == Some(true)
19 {
18}
20 return None;
19
21 }
20pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
22 let others: Vec<&graph::Member> = chat
21 let others: Vec<&graph::Member> = chat
23 .members
22 .members
24 .iter()
23 .iter()
@@ -40,7 +39,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> Option<ChatRecord> {
40 .as_ref()
39 .as_ref()
41 .map(OwnedPreview::from_graph);
40 .map(OwnedPreview::from_graph);
42 let last_event_system = preview.as_ref().is_some_and(|preview| preview.system);
41 let last_event_system = preview.as_ref().is_some_and(|preview| preview.system);
43 Some(ChatRecord {
42 ChatRecord {
44 id: chat.id.clone(),
43 id: chat.id.clone(),
45 kind: chat.chat_type.clone(),
44 kind: chat.chat_type.clone(),
46 title: chat.title(my_user_id),
45 title: chat.title(my_user_id),
@@ -71,7 +70,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> Option<ChatRecord> {
71 .as_ref()
70 .as_ref()
72 .and_then(|preview| preview.sender_name.clone()),
71 .and_then(|preview| preview.sender_name.clone()),
73 last_event_system,
72 last_event_system,
74 })
73 }
75}
74}
76
75
77fn member_name(member: &graph::Member) -> &str {
76fn member_name(member: &graph::Member) -> &str {
@@ -314,7 +313,7 @@ mod tests {
314 "createdDateTime": "2026-10-06T10:00:00Z",
313 "createdDateTime": "2026-10-06T10:00:00Z",
315 "from": null,
314 "from": null,
316 }));
315 }));
317 let record = chat_record(&chat, "me").unwrap();
316 let record = chat_record(&chat, "me");
318 assert!(!record.unread);
317 assert!(!record.unread);
319 assert!(record.last_event_system);
318 assert!(record.last_event_system);
320 }
319 }
@@ -327,7 +326,7 @@ mod tests {
327 "createdDateTime": "2026-10-06T10:00:00Z",
326 "createdDateTime": "2026-10-06T10:00:00Z",
328 "from": {"user": {"id": "other"}},
327 "from": {"user": {"id": "other"}},
329 }));
328 }));
330 let record = chat_record(&chat, "me").unwrap();
329 let record = chat_record(&chat, "me");
331 assert!(record.unread);
330 assert!(record.unread);
332 assert!(!record.last_event_system);
331 assert!(!record.last_event_system);
333 }
332 }
crates/core/src/remote.rs +9 −8
@@ -1,9 +1,10 @@
1 1 use chatsvc::{
2 CallLogEntry, CardActions, ChatApp, ConversationRef, Conversations, ForcedAvailability, ForwardResult, Gif,
3 Gifs, InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient,
4 LinkInfo, MemberHorizon, MessageLanguage, MessageLinks, Messages, PinnedMessage, Pins,
5 PresenceService, PresenceStatus, Receipts, SavedMessage, ScheduledDraft, ScheduledDrafts,
6 StatusNote, TranslateRequest, Translation, TranslationTrigger, Translator, WorkLocationKind,
2 CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState, Conversations,
3 ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,
4 LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,
5 MessageLinks, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus, Receipts,
6 SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest, Translation,
7 TranslationTrigger, Translator, WorkLocationKind,
7 8 };
8 9 use chrono::{DateTime, Utc};
9 10 use graph::{
@@ -120,7 +121,7 @@ pub trait Remote {
120 121 async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
121 122 async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
122 123 async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
123 async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>>;
124 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
124 125 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
125 126 async fn set_channel_notifications(
126 127 &self,
@@ -592,9 +593,9 @@ impl Remote for Graph {
592 593 Ok(Graph::leave_chat(self, chat_id, user_id).await?)
593 594 }
594 595
595 async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>> {
596 async fn chat_states(&self) -> Result<Vec<ConversationState>> {
596 597 Ok(Conversations::new(self.session())
597 .conversation_mute_states()
598 .conversation_states()
598 599 .await?)
599 600 }
600 601
@@ -1,9 +1,10 @@
1use chatsvc::{
1use chatsvc::{
2 CallLogEntry, CardActions, ChatApp, ConversationRef, Conversations, ForcedAvailability, ForwardResult, Gif,
2 CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState, Conversations,
3 Gifs, InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient,
3 ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,
4 LinkInfo, MemberHorizon, MessageLanguage, MessageLinks, Messages, PinnedMessage, Pins,
4 LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,
5 PresenceService, PresenceStatus, Receipts, SavedMessage, ScheduledDraft, ScheduledDrafts,
5 MessageLinks, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus, Receipts,
6 StatusNote, TranslateRequest, Translation, TranslationTrigger, Translator, WorkLocationKind,
6 SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest, Translation,
7 TranslationTrigger, Translator, WorkLocationKind,
7};
8};
8use chrono::{DateTime, Utc};
9use chrono::{DateTime, Utc};
9use graph::{
10use graph::{
@@ -120,7 +121,7 @@ pub trait Remote {
120 async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
121 async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
121 async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
122 async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
122 async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
123 async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
123 async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>>;
124 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
124 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
125 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
125 async fn set_channel_notifications(
126 async fn set_channel_notifications(
126 &self,
127 &self,
@@ -592,9 +593,9 @@ impl Remote for Graph {
592 Ok(Graph::leave_chat(self, chat_id, user_id).await?)
593 Ok(Graph::leave_chat(self, chat_id, user_id).await?)
593 }
594 }
594
595
595 async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>> {
596 async fn chat_states(&self) -> Result<Vec<ConversationState>> {
596 Ok(Conversations::new(self.session())
597 Ok(Conversations::new(self.session())
597 .conversation_mute_states()
598 .conversation_states()
598 .await?)
599 .await?)
599 }
600 }
600
601
crates/core/src/sidebar_sync.rs +132 −14
@@ -1,14 +1,21 @@
1 use std::collections::HashMap;
2
3 use chatsvc::ConversationState;
1 4 use chrono::{DateTime, Duration, Utc};
2 use store::ChatRecord;
5 use graph::Chat;
6 use store::{ChatRecord, Store};
3 7
8 use crate::chat_paging::ChatPaging;
4 9 use crate::engine::{SidebarSummary, SyncEngine};
5 use crate::error::{Error, Result};
10 use crate::error::Result;
6 11 use crate::events::CoreEvent;
7 use crate::mapping::{channel_record, chat_record, team_record};
12 use crate::mapping::{channel_record, chat_record, graph_hidden, team_record};
8 13 use crate::remote::{ChatsPage, Remote};
9 14
10 15 const META_CHATS_FULL_AT: &str = "chats_full_refreshed_at";
11 16 const META_TEAMS_AT: &str = "teams_refreshed_at";
17 const META_CHATS_NEXT_LINK: &str = "chats_next_link";
18 const META_CHATS_EXHAUSTED: &str = "chats_exhausted";
12 19
13 20 #[derive(Default)]
14 21 struct ChatRefresh {
@@ -60,11 +67,13 @@ impl<R: Remote> SyncEngine<R> {
60 67 let mut kept_ids = Vec::new();
61 68 let mut hidden_ids = Vec::new();
62 69 let mut complete = false;
70 let mut continuation = None;
71 let states = self.refresh_chat_states().await;
63 72 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
64 73 loop {
65 74 refresh.pages += 1;
66 75 refresh.fetched += page.items.len();
67 let (records, hidden) = split_hidden(&page, &my_user_id);
76 let (records, hidden) = self.split_hidden(&page, &my_user_id);
68 77 let any_changed = self.any_chat_changed(&records)?;
69 78 self.store.upsert_chats(&records)?;
70 79 kept_ids.extend(records.iter().map(|record| record.id.clone()));
@@ -76,27 +85,49 @@ impl<R: Remote> SyncEngine<R> {
76 85 break;
77 86 };
78 87 if !wants_more || !within_limit {
88 continuation = Some(link);
79 89 break;
80 90 }
81 91 page = self.remote.chats_at(&link).await?;
82 92 }
83 93 self.store.remove_chats(&hidden_ids)?;
84 self.refresh_muted_chats().await;
94 self.apply_muted_chats(states);
85 95 if full {
86 96 if complete {
87 97 self.store.remove_chats_except(&kept_ids)?;
88 98 }
89 99 self.store.set_meta_time(META_CHATS_FULL_AT, Utc::now())?;
100 self.remember_chat_continuation(continuation.filter(|_| !complete))?;
90 101 }
102 self.chat_paging.lock().unwrap().retry();
91 103 Ok(refresh)
92 104 }
93 105
94 async fn refresh_muted_chats(&self) {
95 let outcome = match self.remote.muted_chat_states().await {
96 Ok(states) => self.store.apply_muted_states(&states).map_err(Error::from),
97 Err(error) => Err(error),
106 async fn refresh_chat_states(&self) -> Option<Vec<ConversationState>> {
107 match self.remote.chat_states().await {
108 Ok(states) => {
109 *self.chat_states.lock().unwrap() = states
110 .iter()
111 .map(|state| (state.id.clone(), state.clone()))
112 .collect();
113 Some(states)
114 }
115 Err(error) => {
116 self.report(format!("cannot refresh muted chats: {error}"));
117 None
118 }
119 }
120 }
121
122 fn apply_muted_chats(&self, states: Option<Vec<ConversationState>>) {
123 let Some(states) = states else {
124 return;
98 125 };
99 if let Err(error) = outcome {
126 let muted: Vec<(String, bool)> = states
127 .into_iter()
128 .map(|state| (state.id, state.muted))
129 .collect();
130 if let Err(error) = self.store.apply_muted_states(&muted) {
100 131 self.report(format!("cannot refresh muted chats: {error}"));
101 132 }
102 133 }
@@ -104,9 +135,68 @@ impl<R: Remote> SyncEngine<R> {
104 135 fn chat_refresh_is_full(&self) -> Result<bool> {
105 136 let last_full = self.store.meta_time(META_CHATS_FULL_AT)?;
106 137 Ok(self.store.chat_count()? == 0
138 || !self.chat_paging.lock().unwrap().is_known()
107 139 || is_due(last_full, self.config.full_chat_refresh_interval))
108 140 }
109 141
142 fn remember_chat_continuation(&self, continuation: Option<String>) -> Result<()> {
143 let mut paging = self.chat_paging.lock().unwrap();
144 paging.adopt_continuation(continuation);
145 store_chat_paging(&self.store, &paging)
146 }
147
148 pub fn has_older_chats(&self) -> bool {
149 self.chat_paging.lock().unwrap().has_more()
150 }
151
152 pub fn is_loading_older_chats(&self) -> bool {
153 self.chat_paging.lock().unwrap().is_loading()
154 }
155
156 pub async fn load_older_chats(&self) -> Result<usize> {
157 let Some(link) = self.chat_paging.lock().unwrap().begin() else {
158 return Ok(0);
159 };
160 let _ = self.events.send(CoreEvent::SidebarChanged);
161 let outcome = self.load_chats_page(&link).await;
162 let mut paging = self.chat_paging.lock().unwrap();
163 let loaded = match outcome {
164 Ok((loaded, next_link)) => {
165 paging.finish(next_link);
166 store_chat_paging(&self.store, &paging).map(|()| loaded)
167 }
168 Err(error) => {
169 paging.fail();
170 Err(error)
171 }
172 };
173 drop(paging);
174 let _ = self.events.send(CoreEvent::SidebarChanged);
175 loaded
176 }
177
178 async fn load_chats_page(&self, link: &str) -> Result<(usize, Option<String>)> {
179 let my_user_id = self.my_user_id().await?;
180 let page = self.remote.chats_at(link).await?;
181 let (records, hidden) = self.split_hidden(&page, &my_user_id);
182 self.store.upsert_chats(&records)?;
183 self.store.remove_chats(&hidden)?;
184 let muted: Vec<(String, bool)> = {
185 let states = self.chat_states.lock().unwrap();
186 records
187 .iter()
188 .filter_map(|record| states.get(&record.id))
189 .map(|state| (state.id.clone(), state.muted))
190 .collect()
191 };
192 self.store.apply_muted_states(&muted)?;
193 Ok((page.items.len(), page.next_link))
194 }
195
196 fn split_hidden(&self, page: &ChatsPage, my_user_id: &str) -> (Vec<ChatRecord>, Vec<String>) {
197 split_hidden(page, my_user_id, &self.chat_states.lock().unwrap())
198 }
199
110 200 fn any_chat_changed(&self, records: &[ChatRecord]) -> Result<bool> {
111 201 let ids: Vec<String> = records.iter().map(|record| record.id.clone()).collect();
112 202 let cached = self.store.chat_last_message_times(&ids)?;
@@ -178,14 +268,42 @@ fn is_due(last: Option<DateTime<Utc>>, interval: Duration) -> bool {
178 268 last.is_none_or(|last| Utc::now() - last >= interval)
179 269 }
180 270
181 fn split_hidden(page: &ChatsPage, my_user_id: &str) -> (Vec<ChatRecord>, Vec<String>) {
271 fn is_hidden(chat: &Chat, states: &HashMap<String, ConversationState>) -> bool {
272 states
273 .get(&chat.id)
274 .and_then(|state| state.hidden)
275 .unwrap_or_else(|| graph_hidden(chat))
276 }
277
278 fn split_hidden(
279 page: &ChatsPage,
280 my_user_id: &str,
281 states: &HashMap<String, ConversationState>,
282 ) -> (Vec<ChatRecord>, Vec<String>) {
182 283 let mut records = Vec::new();
183 284 let mut hidden = Vec::new();
184 285 for chat in &page.items {
185 match chat_record(chat, my_user_id) {
186 Some(record) => records.push(record),
187 None => hidden.push(chat.id.clone()),
286 if is_hidden(chat, states) {
287 hidden.push(chat.id.clone());
288 } else {
289 records.push(chat_record(chat, my_user_id));
188 290 }
189 291 }
190 292 (records, hidden)
191 293 }
294
295 pub(crate) fn stored_chat_paging(store: &Store) -> ChatPaging {
296 let next_link = store
297 .meta(META_CHATS_NEXT_LINK)
298 .ok()
299 .flatten()
300 .filter(|link| !link.is_empty());
301 let exhausted = store.meta(META_CHATS_EXHAUSTED).ok().flatten().as_deref() == Some("true");
302 ChatPaging::restored(next_link, exhausted)
303 }
304
305 fn store_chat_paging(store: &Store, paging: &ChatPaging) -> Result<()> {
306 store.set_meta(META_CHATS_NEXT_LINK, paging.next_link().unwrap_or_default())?;
307 store.set_meta(META_CHATS_EXHAUSTED, &paging.is_exhausted().to_string())?;
308 Ok(())
309 }
@@ -1,14 +1,21 @@
1use std::collections::HashMap;
2
3use chatsvc::ConversationState;
1use chrono::{DateTime, Duration, Utc};
4use chrono::{DateTime, Duration, Utc};
2use store::ChatRecord;
5use graph::Chat;
6use store::{ChatRecord, Store};
3
7
8use crate::chat_paging::ChatPaging;
4use crate::engine::{SidebarSummary, SyncEngine};
9use crate::engine::{SidebarSummary, SyncEngine};
5use crate::error::{Error, Result};
10use crate::error::Result;
6use crate::events::CoreEvent;
11use crate::events::CoreEvent;
7use crate::mapping::{channel_record, chat_record, team_record};
12use crate::mapping::{channel_record, chat_record, graph_hidden, team_record};
8use crate::remote::{ChatsPage, Remote};
13use crate::remote::{ChatsPage, Remote};
9
14
10const META_CHATS_FULL_AT: &str = "chats_full_refreshed_at";
15const META_CHATS_FULL_AT: &str = "chats_full_refreshed_at";
11const META_TEAMS_AT: &str = "teams_refreshed_at";
16const META_TEAMS_AT: &str = "teams_refreshed_at";
17const META_CHATS_NEXT_LINK: &str = "chats_next_link";
18const META_CHATS_EXHAUSTED: &str = "chats_exhausted";
12
19
13#[derive(Default)]
20#[derive(Default)]
14struct ChatRefresh {
21struct ChatRefresh {
@@ -60,11 +67,13 @@ impl<R: Remote> SyncEngine<R> {
60 let mut kept_ids = Vec::new();
67 let mut kept_ids = Vec::new();
61 let mut hidden_ids = Vec::new();
68 let mut hidden_ids = Vec::new();
62 let mut complete = false;
69 let mut complete = false;
70 let mut continuation = None;
71 let states = self.refresh_chat_states().await;
63 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
72 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
64 loop {
73 loop {
65 refresh.pages += 1;
74 refresh.pages += 1;
66 refresh.fetched += page.items.len();
75 refresh.fetched += page.items.len();
67 let (records, hidden) = split_hidden(&page, &my_user_id);
76 let (records, hidden) = self.split_hidden(&page, &my_user_id);
68 let any_changed = self.any_chat_changed(&records)?;
77 let any_changed = self.any_chat_changed(&records)?;
69 self.store.upsert_chats(&records)?;
78 self.store.upsert_chats(&records)?;
70 kept_ids.extend(records.iter().map(|record| record.id.clone()));
79 kept_ids.extend(records.iter().map(|record| record.id.clone()));
@@ -76,27 +85,49 @@ impl<R: Remote> SyncEngine<R> {
76 break;
85 break;
77 };
86 };
78 if !wants_more || !within_limit {
87 if !wants_more || !within_limit {
88 continuation = Some(link);
79 break;
89 break;
80 }
90 }
81 page = self.remote.chats_at(&link).await?;
91 page = self.remote.chats_at(&link).await?;
82 }
92 }
83 self.store.remove_chats(&hidden_ids)?;
93 self.store.remove_chats(&hidden_ids)?;
84 self.refresh_muted_chats().await;
94 self.apply_muted_chats(states);
85 if full {
95 if full {
86 if complete {
96 if complete {
87 self.store.remove_chats_except(&kept_ids)?;
97 self.store.remove_chats_except(&kept_ids)?;
88 }
98 }
89 self.store.set_meta_time(META_CHATS_FULL_AT, Utc::now())?;
99 self.store.set_meta_time(META_CHATS_FULL_AT, Utc::now())?;
100 self.remember_chat_continuation(continuation.filter(|_| !complete))?;
90 }
101 }
102 self.chat_paging.lock().unwrap().retry();
91 Ok(refresh)
103 Ok(refresh)
92 }
104 }
93
105
94 async fn refresh_muted_chats(&self) {
106 async fn refresh_chat_states(&self) -> Option<Vec<ConversationState>> {
95 let outcome = match self.remote.muted_chat_states().await {
107 match self.remote.chat_states().await {
96 Ok(states) => self.store.apply_muted_states(&states).map_err(Error::from),
108 Ok(states) => {
97 Err(error) => Err(error),
109 *self.chat_states.lock().unwrap() = states
110 .iter()
111 .map(|state| (state.id.clone(), state.clone()))
112 .collect();
113 Some(states)
114 }
115 Err(error) => {
116 self.report(format!("cannot refresh muted chats: {error}"));
117 None
118 }
119 }
120 }
121
122 fn apply_muted_chats(&self, states: Option<Vec<ConversationState>>) {
123 let Some(states) = states else {
124 return;
98 };
125 };
99 if let Err(error) = outcome {
126 let muted: Vec<(String, bool)> = states
127 .into_iter()
128 .map(|state| (state.id, state.muted))
129 .collect();
130 if let Err(error) = self.store.apply_muted_states(&muted) {
100 self.report(format!("cannot refresh muted chats: {error}"));
131 self.report(format!("cannot refresh muted chats: {error}"));
101 }
132 }
102 }
133 }
@@ -104,9 +135,68 @@ impl<R: Remote> SyncEngine<R> {
104 fn chat_refresh_is_full(&self) -> Result<bool> {
135 fn chat_refresh_is_full(&self) -> Result<bool> {
105 let last_full = self.store.meta_time(META_CHATS_FULL_AT)?;
136 let last_full = self.store.meta_time(META_CHATS_FULL_AT)?;
106 Ok(self.store.chat_count()? == 0
137 Ok(self.store.chat_count()? == 0
138 || !self.chat_paging.lock().unwrap().is_known()
107 || is_due(last_full, self.config.full_chat_refresh_interval))
139 || is_due(last_full, self.config.full_chat_refresh_interval))
108 }
140 }
109
141
142 fn remember_chat_continuation(&self, continuation: Option<String>) -> Result<()> {
143 let mut paging = self.chat_paging.lock().unwrap();
144 paging.adopt_continuation(continuation);
145 store_chat_paging(&self.store, &paging)
146 }
147
148 pub fn has_older_chats(&self) -> bool {
149 self.chat_paging.lock().unwrap().has_more()
150 }
151
152 pub fn is_loading_older_chats(&self) -> bool {
153 self.chat_paging.lock().unwrap().is_loading()
154 }
155
156 pub async fn load_older_chats(&self) -> Result<usize> {
157 let Some(link) = self.chat_paging.lock().unwrap().begin() else {
158 return Ok(0);
159 };
160 let _ = self.events.send(CoreEvent::SidebarChanged);
161 let outcome = self.load_chats_page(&link).await;
162 let mut paging = self.chat_paging.lock().unwrap();
163 let loaded = match outcome {
164 Ok((loaded, next_link)) => {
165 paging.finish(next_link);
166 store_chat_paging(&self.store, &paging).map(|()| loaded)
167 }
168 Err(error) => {
169 paging.fail();
170 Err(error)
171 }
172 };
173 drop(paging);
174 let _ = self.events.send(CoreEvent::SidebarChanged);
175 loaded
176 }
177
178 async fn load_chats_page(&self, link: &str) -> Result<(usize, Option<String>)> {
179 let my_user_id = self.my_user_id().await?;
180 let page = self.remote.chats_at(link).await?;
181 let (records, hidden) = self.split_hidden(&page, &my_user_id);
182 self.store.upsert_chats(&records)?;
183 self.store.remove_chats(&hidden)?;
184 let muted: Vec<(String, bool)> = {
185 let states = self.chat_states.lock().unwrap();
186 records
187 .iter()
188 .filter_map(|record| states.get(&record.id))
189 .map(|state| (state.id.clone(), state.muted))
190 .collect()
191 };
192 self.store.apply_muted_states(&muted)?;
193 Ok((page.items.len(), page.next_link))
194 }
195
196 fn split_hidden(&self, page: &ChatsPage, my_user_id: &str) -> (Vec<ChatRecord>, Vec<String>) {
197 split_hidden(page, my_user_id, &self.chat_states.lock().unwrap())
198 }
199
110 fn any_chat_changed(&self, records: &[ChatRecord]) -> Result<bool> {
200 fn any_chat_changed(&self, records: &[ChatRecord]) -> Result<bool> {
111 let ids: Vec<String> = records.iter().map(|record| record.id.clone()).collect();
201 let ids: Vec<String> = records.iter().map(|record| record.id.clone()).collect();
112 let cached = self.store.chat_last_message_times(&ids)?;
202 let cached = self.store.chat_last_message_times(&ids)?;
@@ -178,14 +268,42 @@ fn is_due(last: Option<DateTime<Utc>>, interval: Duration) -> bool {
178 last.is_none_or(|last| Utc::now() - last >= interval)
268 last.is_none_or(|last| Utc::now() - last >= interval)
179}
269}
180
270
181fn split_hidden(page: &ChatsPage, my_user_id: &str) -> (Vec<ChatRecord>, Vec<String>) {
271fn is_hidden(chat: &Chat, states: &HashMap<String, ConversationState>) -> bool {
272 states
273 .get(&chat.id)
274 .and_then(|state| state.hidden)
275 .unwrap_or_else(|| graph_hidden(chat))
276}
277
278fn split_hidden(
279 page: &ChatsPage,
280 my_user_id: &str,
281 states: &HashMap<String, ConversationState>,
282) -> (Vec<ChatRecord>, Vec<String>) {
182 let mut records = Vec::new();
283 let mut records = Vec::new();
183 let mut hidden = Vec::new();
284 let mut hidden = Vec::new();
184 for chat in &page.items {
285 for chat in &page.items {
185 match chat_record(chat, my_user_id) {
286 if is_hidden(chat, states) {
186 Some(record) => records.push(record),
287 hidden.push(chat.id.clone());
187 None => hidden.push(chat.id.clone()),
288 } else {
289 records.push(chat_record(chat, my_user_id));
188 }
290 }
189 }
291 }
190 (records, hidden)
292 (records, hidden)
191}
293}
294
295pub(crate) fn stored_chat_paging(store: &Store) -> ChatPaging {
296 let next_link = store
297 .meta(META_CHATS_NEXT_LINK)
298 .ok()
299 .flatten()
300 .filter(|link| !link.is_empty());
301 let exhausted = store.meta(META_CHATS_EXHAUSTED).ok().flatten().as_deref() == Some("true");
302 ChatPaging::restored(next_link, exhausted)
303}
304
305fn store_chat_paging(store: &Store, paging: &ChatPaging) -> Result<()> {
306 store.set_meta(META_CHATS_NEXT_LINK, paging.next_link().unwrap_or_default())?;
307 store.set_meta(META_CHATS_EXHAUSTED, &paging.is_exhausted().to_string())?;
308 Ok(())
309}
crates/core/tests/engine.rs +166 −4
@@ -111,6 +111,8 @@ struct Fake {
111 111 invokes: Mutex<Vec<chatsvc::InvokeRequest>>,
112 112 invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,
113 113 muted_states: Mutex<Vec<(String, bool)>>,
114 hidden_states: Mutex<Vec<(String, bool)>>,
115 chats_fail: Mutex<bool>,
114 116 muted_fails: Mutex<bool>,
115 117 link_pages: Mutex<Vec<chatsvc::MessageLinks>>,
116 118 link_page_calls: Mutex<Vec<String>>,
@@ -193,6 +195,9 @@ impl Remote for Handle {
193 195 }
194 196
195 197 async fn chats_at(&self, next_link: &str) -> Result<ChatsPage> {
198 if *self.chats_fail.lock().unwrap() {
199 return Err(Error::Unsupported("forced failure"));
200 }
196 201 let mut parts = next_link.trim_start_matches("chats:").split(':');
197 202 let offset = parts.next().unwrap().parse().unwrap();
198 203 let top = parts.next().unwrap().parse().unwrap();
@@ -451,11 +456,30 @@ impl Remote for Handle {
451 456 Ok(())
452 457 }
453 458
454 async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>> {
459 async fn chat_states(&self) -> Result<Vec<chatsvc::ConversationState>> {
455 460 if *self.muted_fails.lock().unwrap() {
456 461 return Err(Error::Unsupported("forced failure"));
457 462 }
458 Ok(self.muted_states.lock().unwrap().clone())
463 let muted = self.muted_states.lock().unwrap().clone();
464 let hidden = self.hidden_states.lock().unwrap().clone();
465 let mut states: Vec<chatsvc::ConversationState> = muted
466 .into_iter()
467 .map(|(id, muted)| chatsvc::ConversationState {
468 id,
469 muted,
470 hidden: None,
471 })
472 .collect();
473 states.extend(
474 hidden
475 .into_iter()
476 .map(|(id, hidden)| chatsvc::ConversationState {
477 id,
478 muted: false,
479 hidden: Some(hidden),
480 }),
481 );
482 Ok(states)
459 483 }
460 484
461 485 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
@@ -973,6 +997,132 @@ async fn refresh_sidebar_marks_muted_chats_and_keeps_flags_when_the_lookup_fails
973 997 assert!(!engine.sidebar().unwrap().chats[0].muted);
974 998 }
975 999
1000 #[tokio::test]
1001 async fn chatsvc_visibility_beats_the_graph_hidden_flag_and_graph_is_the_fallback() {
1002 let fake = Arc::new(Fake::default());
1003 *fake.chats.lock().unwrap() = vec![
1004 chat("19:graph-hidden@thread.v2", Some("Kept"), 30, 30, ME, true),
1005 chat(
1006 "19:chatsvc-hidden@thread.v2",
1007 Some("Dropped"),
1008 20,
1009 20,
1010 ME,
1011 false,
1012 ),
1013 chat(
1014 "19:unknown-hidden@thread.v2",
1015 Some("Unknown"),
1016 10,
1017 10,
1018 ME,
1019 true,
1020 ),
1021 chat("19:plain@thread.v2", Some("Plain"), 5, 5, ME, false),
1022 ];
1023 fake.hidden_states.lock().unwrap().extend([
1024 ("19:graph-hidden@thread.v2".to_owned(), false),
1025 ("19:chatsvc-hidden@thread.v2".to_owned(), true),
1026 ]);
1027 let engine = engine_with(&fake, SyncConfig::default());
1028 engine.refresh_sidebar().await.unwrap();
1029 let titles: Vec<String> = engine
1030 .sidebar()
1031 .unwrap()
1032 .chats
1033 .iter()
1034 .map(|chat| chat.title.clone())
1035 .collect();
1036 assert_eq!(titles, ["Kept", "Plain"]);
1037 }
1038
1039 fn numbered_chats(count: usize) -> Vec<Chat> {
1040 (0..count)
1041 .map(|index| {
1042 chat(
1043 &format!("19:c{index:03}@thread.v2"),
1044 Some(&format!("Chat {index:03}")),
1045 (count - index) as i64,
1046 0,
1047 ME,
1048 false,
1049 )
1050 })
1051 .collect()
1052 }
1053
1054 #[tokio::test]
1055 async fn older_chats_load_page_by_page_until_the_list_ends() {
1056 let fake = Arc::new(Fake::default());
1057 *fake.chats.lock().unwrap() = numbered_chats(25);
1058 let engine = engine_with(
1059 &fake,
1060 SyncConfig {
1061 chat_limit: 10,
1062 chat_page_size: 5,
1063 ..SyncConfig::default()
1064 },
1065 );
1066 engine.refresh_sidebar().await.unwrap();
1067 assert_eq!(engine.sidebar().unwrap().chats.len(), 10);
1068 assert!(engine.has_older_chats());
1069 assert!(!engine.is_loading_older_chats());
1070
1071 let mut loaded = Vec::new();
1072 while engine.has_older_chats() {
1073 loaded.push(engine.load_older_chats().await.unwrap());
1074 }
1075 assert_eq!(loaded, [5, 5, 5]);
1076 assert_eq!(engine.sidebar().unwrap().chats.len(), 25);
1077 assert_eq!(engine.load_older_chats().await.unwrap(), 0);
1078 }
1079
1080 #[tokio::test]
1081 async fn the_older_chat_continuation_survives_a_restart() {
1082 let fake = Arc::new(Fake::default());
1083 *fake.chats.lock().unwrap() = numbered_chats(12);
1084 let store = Arc::new(Store::open_in_memory().unwrap());
1085 let config = SyncConfig {
1086 chat_limit: 4,
1087 chat_page_size: 4,
1088 ..SyncConfig::default()
1089 };
1090 let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), config.clone());
1091 engine.refresh_sidebar().await.unwrap();
1092 engine.load_older_chats().await.unwrap();
1093 assert_eq!(store.chat_count().unwrap(), 8);
1094
1095 let restarted = SyncEngine::with_config(Handle(fake.clone()), store.clone(), config);
1096 assert!(restarted.has_older_chats());
1097 assert_eq!(restarted.load_older_chats().await.unwrap(), 4);
1098 assert!(!restarted.has_older_chats());
1099 assert_eq!(store.chat_count().unwrap(), 12);
1100 }
1101
1102 #[tokio::test]
1103 async fn a_failed_older_page_stalls_until_the_next_refresh() {
1104 let fake = Arc::new(Fake::default());
1105 *fake.chats.lock().unwrap() = numbered_chats(8);
1106 let engine = engine_with(
1107 &fake,
1108 SyncConfig {
1109 chat_limit: 4,
1110 chat_page_size: 4,
1111 ..SyncConfig::default()
1112 },
1113 );
1114 engine.refresh_sidebar().await.unwrap();
1115 *fake.chats_fail.lock().unwrap() = true;
1116 assert!(engine.load_older_chats().await.is_err());
1117 assert!(!engine.is_loading_older_chats());
1118 assert!(engine.has_older_chats());
1119 assert_eq!(engine.load_older_chats().await.unwrap(), 0);
1120
1121 *fake.chats_fail.lock().unwrap() = false;
1122 engine.refresh_sidebar().await.unwrap();
1123 assert_eq!(engine.load_older_chats().await.unwrap(), 4);
1124 }
1125
976 1126 #[tokio::test]
977 1127 async fn chat_state_actions_call_remote_and_update_the_store() {
978 1128 let fake = Arc::new(Fake::default());
@@ -1311,7 +1461,13 @@ fn many_chats(count: i64) -> Vec<Chat> {
1311 1461 async fn warm_refresh_stops_after_the_first_unchanged_page() {
1312 1462 let fake = Arc::new(Fake::default());
1313 1463 *fake.chats.lock().unwrap() = many_chats(120);
1314 let engine = engine_with(&fake, SyncConfig::default());
1464 let engine = engine_with(
1465 &fake,
1466 SyncConfig {
1467 chat_page_size: 25,
1468 ..SyncConfig::default()
1469 },
1470 );
1315 1471 let cold = engine.refresh_sidebar().await.unwrap();
1316 1472 assert!(cold.full_chat_refresh);
1317 1473 assert_eq!(cold.chat_pages, 5);
@@ -1331,7 +1487,13 @@ async fn warm_refresh_stops_after_the_first_unchanged_page() {
1331 1487 async fn warm_refresh_walks_on_while_pages_hold_new_activity() {
1332 1488 let fake = Arc::new(Fake::default());
1333 1489 *fake.chats.lock().unwrap() = many_chats(120);
1334 let engine = engine_with(&fake, SyncConfig::default());
1490 let engine = engine_with(
1491 &fake,
1492 SyncConfig {
1493 chat_page_size: 25,
1494 ..SyncConfig::default()
1495 },
1496 );
1335 1497 engine.refresh_sidebar().await.unwrap();
1336 1498
1337 1499 let mut chats = many_chats(120);
@@ -111,6 +111,8 @@ struct Fake {
111 invokes: Mutex<Vec<chatsvc::InvokeRequest>>,
111 invokes: Mutex<Vec<chatsvc::InvokeRequest>>,
112 invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,
112 invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,
113 muted_states: Mutex<Vec<(String, bool)>>,
113 muted_states: Mutex<Vec<(String, bool)>>,
114 hidden_states: Mutex<Vec<(String, bool)>>,
115 chats_fail: Mutex<bool>,
114 muted_fails: Mutex<bool>,
116 muted_fails: Mutex<bool>,
115 link_pages: Mutex<Vec<chatsvc::MessageLinks>>,
117 link_pages: Mutex<Vec<chatsvc::MessageLinks>>,
116 link_page_calls: Mutex<Vec<String>>,
118 link_page_calls: Mutex<Vec<String>>,
@@ -193,6 +195,9 @@ impl Remote for Handle {
193 }
195 }
194
196
195 async fn chats_at(&self, next_link: &str) -> Result<ChatsPage> {
197 async fn chats_at(&self, next_link: &str) -> Result<ChatsPage> {
198 if *self.chats_fail.lock().unwrap() {
199 return Err(Error::Unsupported("forced failure"));
200 }
196 let mut parts = next_link.trim_start_matches("chats:").split(':');
201 let mut parts = next_link.trim_start_matches("chats:").split(':');
197 let offset = parts.next().unwrap().parse().unwrap();
202 let offset = parts.next().unwrap().parse().unwrap();
198 let top = parts.next().unwrap().parse().unwrap();
203 let top = parts.next().unwrap().parse().unwrap();
@@ -451,11 +456,30 @@ impl Remote for Handle {
451 Ok(())
456 Ok(())
452 }
457 }
453
458
454 async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>> {
459 async fn chat_states(&self) -> Result<Vec<chatsvc::ConversationState>> {
455 if *self.muted_fails.lock().unwrap() {
460 if *self.muted_fails.lock().unwrap() {
456 return Err(Error::Unsupported("forced failure"));
461 return Err(Error::Unsupported("forced failure"));
457 }
462 }
458 Ok(self.muted_states.lock().unwrap().clone())
463 let muted = self.muted_states.lock().unwrap().clone();
464 let hidden = self.hidden_states.lock().unwrap().clone();
465 let mut states: Vec<chatsvc::ConversationState> = muted
466 .into_iter()
467 .map(|(id, muted)| chatsvc::ConversationState {
468 id,
469 muted,
470 hidden: None,
471 })
472 .collect();
473 states.extend(
474 hidden
475 .into_iter()
476 .map(|(id, hidden)| chatsvc::ConversationState {
477 id,
478 muted: false,
479 hidden: Some(hidden),
480 }),
481 );
482 Ok(states)
459 }
483 }
460
484
461 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
485 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
@@ -973,6 +997,132 @@ async fn refresh_sidebar_marks_muted_chats_and_keeps_flags_when_the_lookup_fails
973 assert!(!engine.sidebar().unwrap().chats[0].muted);
997 assert!(!engine.sidebar().unwrap().chats[0].muted);
974}
998}
975
999
1000#[tokio::test]
1001async fn chatsvc_visibility_beats_the_graph_hidden_flag_and_graph_is_the_fallback() {
1002 let fake = Arc::new(Fake::default());
1003 *fake.chats.lock().unwrap() = vec![
1004 chat("19:graph-hidden@thread.v2", Some("Kept"), 30, 30, ME, true),
1005 chat(
1006 "19:chatsvc-hidden@thread.v2",
1007 Some("Dropped"),
1008 20,
1009 20,
1010 ME,
1011 false,
1012 ),
1013 chat(
1014 "19:unknown-hidden@thread.v2",
1015 Some("Unknown"),
1016 10,
1017 10,
1018 ME,
1019 true,
1020 ),
1021 chat("19:plain@thread.v2", Some("Plain"), 5, 5, ME, false),
1022 ];
1023 fake.hidden_states.lock().unwrap().extend([
1024 ("19:graph-hidden@thread.v2".to_owned(), false),
1025 ("19:chatsvc-hidden@thread.v2".to_owned(), true),
1026 ]);
1027 let engine = engine_with(&fake, SyncConfig::default());
1028 engine.refresh_sidebar().await.unwrap();
1029 let titles: Vec<String> = engine
1030 .sidebar()
1031 .unwrap()
1032 .chats
1033 .iter()
1034 .map(|chat| chat.title.clone())
1035 .collect();
1036 assert_eq!(titles, ["Kept", "Plain"]);
1037}
1038
1039fn numbered_chats(count: usize) -> Vec<Chat> {
1040 (0..count)
1041 .map(|index| {
1042 chat(
1043 &format!("19:c{index:03}@thread.v2"),
1044 Some(&format!("Chat {index:03}")),
1045 (count - index) as i64,
1046 0,
1047 ME,
1048 false,
1049 )
1050 })
1051 .collect()
1052}
1053
1054#[tokio::test]
1055async fn older_chats_load_page_by_page_until_the_list_ends() {
1056 let fake = Arc::new(Fake::default());
1057 *fake.chats.lock().unwrap() = numbered_chats(25);
1058 let engine = engine_with(
1059 &fake,
1060 SyncConfig {
1061 chat_limit: 10,
1062 chat_page_size: 5,
1063 ..SyncConfig::default()
1064 },
1065 );
1066 engine.refresh_sidebar().await.unwrap();
1067 assert_eq!(engine.sidebar().unwrap().chats.len(), 10);
1068 assert!(engine.has_older_chats());
1069 assert!(!engine.is_loading_older_chats());
1070
1071 let mut loaded = Vec::new();
1072 while engine.has_older_chats() {
1073 loaded.push(engine.load_older_chats().await.unwrap());
1074 }
1075 assert_eq!(loaded, [5, 5, 5]);
1076 assert_eq!(engine.sidebar().unwrap().chats.len(), 25);
1077 assert_eq!(engine.load_older_chats().await.unwrap(), 0);
1078}
1079
1080#[tokio::test]
1081async fn the_older_chat_continuation_survives_a_restart() {
1082 let fake = Arc::new(Fake::default());
1083 *fake.chats.lock().unwrap() = numbered_chats(12);
1084 let store = Arc::new(Store::open_in_memory().unwrap());
1085 let config = SyncConfig {
1086 chat_limit: 4,
1087 chat_page_size: 4,
1088 ..SyncConfig::default()
1089 };
1090 let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), config.clone());
1091 engine.refresh_sidebar().await.unwrap();
1092 engine.load_older_chats().await.unwrap();
1093 assert_eq!(store.chat_count().unwrap(), 8);
1094
1095 let restarted = SyncEngine::with_config(Handle(fake.clone()), store.clone(), config);
1096 assert!(restarted.has_older_chats());
1097 assert_eq!(restarted.load_older_chats().await.unwrap(), 4);
1098 assert!(!restarted.has_older_chats());
1099 assert_eq!(store.chat_count().unwrap(), 12);
1100}
1101
1102#[tokio::test]
1103async fn a_failed_older_page_stalls_until_the_next_refresh() {
1104 let fake = Arc::new(Fake::default());
1105 *fake.chats.lock().unwrap() = numbered_chats(8);
1106 let engine = engine_with(
1107 &fake,
1108 SyncConfig {
1109 chat_limit: 4,
1110 chat_page_size: 4,
1111 ..SyncConfig::default()
1112 },
1113 );
1114 engine.refresh_sidebar().await.unwrap();
1115 *fake.chats_fail.lock().unwrap() = true;
1116 assert!(engine.load_older_chats().await.is_err());
1117 assert!(!engine.is_loading_older_chats());
1118 assert!(engine.has_older_chats());
1119 assert_eq!(engine.load_older_chats().await.unwrap(), 0);
1120
1121 *fake.chats_fail.lock().unwrap() = false;
1122 engine.refresh_sidebar().await.unwrap();
1123 assert_eq!(engine.load_older_chats().await.unwrap(), 4);
1124}
1125
976#[tokio::test]
1126#[tokio::test]
977async fn chat_state_actions_call_remote_and_update_the_store() {
1127async fn chat_state_actions_call_remote_and_update_the_store() {
978 let fake = Arc::new(Fake::default());
1128 let fake = Arc::new(Fake::default());
@@ -1311,7 +1461,13 @@ fn many_chats(count: i64) -> Vec<Chat> {
1311async fn warm_refresh_stops_after_the_first_unchanged_page() {
1461async fn warm_refresh_stops_after_the_first_unchanged_page() {
1312 let fake = Arc::new(Fake::default());
1462 let fake = Arc::new(Fake::default());
1313 *fake.chats.lock().unwrap() = many_chats(120);
1463 *fake.chats.lock().unwrap() = many_chats(120);
1314 let engine = engine_with(&fake, SyncConfig::default());
1464 let engine = engine_with(
1465 &fake,
1466 SyncConfig {
1467 chat_page_size: 25,
1468 ..SyncConfig::default()
1469 },
1470 );
1315 let cold = engine.refresh_sidebar().await.unwrap();
1471 let cold = engine.refresh_sidebar().await.unwrap();
1316 assert!(cold.full_chat_refresh);
1472 assert!(cold.full_chat_refresh);
1317 assert_eq!(cold.chat_pages, 5);
1473 assert_eq!(cold.chat_pages, 5);
@@ -1331,7 +1487,13 @@ async fn warm_refresh_stops_after_the_first_unchanged_page() {
1331async fn warm_refresh_walks_on_while_pages_hold_new_activity() {
1487async fn warm_refresh_walks_on_while_pages_hold_new_activity() {
1332 let fake = Arc::new(Fake::default());
1488 let fake = Arc::new(Fake::default());
1333 *fake.chats.lock().unwrap() = many_chats(120);
1489 *fake.chats.lock().unwrap() = many_chats(120);
1334 let engine = engine_with(&fake, SyncConfig::default());
1490 let engine = engine_with(
1491 &fake,
1492 SyncConfig {
1493 chat_page_size: 25,
1494 ..SyncConfig::default()
1495 },
1496 );
1335 engine.refresh_sidebar().await.unwrap();
1497 engine.refresh_sidebar().await.unwrap();
1336
1498
1337 let mut chats = many_chats(120);
1499 let mut chats = many_chats(120);