feat(channels): pinned posts, mention badges and mark all as read
- Pinned channel posts over the Teams V1 CSA routes (GET pins, POST/DELETE posts/{id}/pin), root posts only, team thread id from the General channel
- Pin banner and Pin/Unpin for channel root posts; deviation: Teams shows no banner in channels, only a "Pinned" marker and the info pane list
- Pin banner top gap equals its side inset (ROW_PADDING) in chats and channels, layout_guard check added
- Mention badges from the chatsvc activity stream: count, @channel and @team icons, team row sum while collapsed
- Hidden channels with personal mentions are pulled into the list, hidden teams show only those channels
- Mark all as read in the channel list menu writes appConsumptionHorizon like Teams, read state honours it
- Store table channel_mentions (migration 0023), demo data for mentions, a hoisted channel and a pinned post
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -218,6 +218,7 @@ mod tests {
218
218
hidden: false,
219
219
hidden_channel_ids: Vec::new(),
220
220
notifications: Default::default(),
221
mentions: Default::default(),
221
222
});
222
223
let context = build(&state, "19:chat", "reply-2").unwrap();
223
224
let texts: Vec<&str> = context
@@ -218,6 +218,7 @@ mod tests {218
hidden: false,218
hidden: false,219
hidden_channel_ids: Vec::new(),219
hidden_channel_ids: Vec::new(),220
notifications: Default::default(),220
notifications: Default::default(),221
mentions: Default::default(),221
});222
});222
let context = build(&state, "19:chat", "reply-2").unwrap();223
let context = build(&state, "19:chat", "reply-2").unwrap();223
let texts: Vec<&str> = context224
let texts: Vec<&str> = context@@ -765,6 +765,42 @@ impl AppState {
765
765
}
766
766
}
767
767
768
pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) {
769
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
770
return;
771
};
772
let previous_unread: Vec<(String, bool, Option<DateTime<Utc>>)> = self
773
.sidebar
774
.teams
775
.iter()
776
.flat_map(|team| team.channels.iter())
777
.map(|channel| (channel.id.clone(), channel.unread, None))
778
.collect();
779
let previous_mentions: Vec<(String, store::ChannelMentions)> = self
780
.sidebar
781
.teams
782
.iter()
783
.flat_map(|team| team.mentions.iter())
784
.map(|(channel_id, mentions)| (channel_id.clone(), *mentions))
785
.collect();
786
let _ = self.store.mark_all_channels_read();
787
self.reload_sidebar(cx);
788
let Some(engine) = engine_or_demo else {
789
return;
790
};
791
self.run_chat_action(
792
"Mark all as read",
793
async move { engine.mark_all_channels_read().await },
794
move |state, cx| {
795
let _ = state.store.apply_channel_read_states(&previous_unread);
796
let _ = state.store.replace_channel_mentions(&previous_mentions);
797
state.reload_sidebar(cx);
798
},
799
|_, _| {},
800
cx,
801
);
802
}
803
768
804
pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
769
805
self.new_chat = true;
770
806
self.show_call(false, cx);
@@ -1066,6 +1102,7 @@ mod tests {
1066
1102
hidden: false,
1067
1103
hidden_channel_ids: Vec::new(),
1068
1104
notifications: Default::default(),
1105
mentions: Default::default(),
1069
1106
}],
1070
1107
}
1071
1108
}
@@ -765,6 +765,42 @@ impl AppState {765
}765
}766
}766
}767
767
768
pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) {769
let Some(engine_or_demo) = self.chat_action_engine(cx) else {770
return;771
};772
let previous_unread: Vec<(String, bool, Option<DateTime<Utc>>)> = self773
.sidebar774
.teams775
.iter()776
.flat_map(|team| team.channels.iter())777
.map(|channel| (channel.id.clone(), channel.unread, None))778
.collect();779
let previous_mentions: Vec<(String, store::ChannelMentions)> = self780
.sidebar781
.teams782
.iter()783
.flat_map(|team| team.mentions.iter())784
.map(|(channel_id, mentions)| (channel_id.clone(), *mentions))785
.collect();786
let _ = self.store.mark_all_channels_read();787
self.reload_sidebar(cx);788
let Some(engine) = engine_or_demo else {789
return;790
};791
self.run_chat_action(792
"Mark all as read",793
async move { engine.mark_all_channels_read().await },794
move |state, cx| {795
let _ = state.store.apply_channel_read_states(&previous_unread);796
let _ = state.store.replace_channel_mentions(&previous_mentions);797
state.reload_sidebar(cx);798
},799
|_, _| {},800
cx,801
);802
}803
768
pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {804
pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {769
self.new_chat = true;805
self.new_chat = true;770
self.show_call(false, cx);806
self.show_call(false, cx);@@ -1066,6 +1102,7 @@ mod tests {1066
hidden: false,1102
hidden: false,1067
hidden_channel_ids: Vec::new(),1103
hidden_channel_ids: Vec::new(),1068
notifications: Default::default(),1104
notifications: Default::default(),1105
mentions: Default::default(),1069
}],1106
}],1070
}1107
}1071
}1108
}@@ -6,8 +6,9 @@ use std::time::Instant;
6
6
use chrono::{DateTime, Duration, Local, TimeZone, Utc};
7
7
use gpui_kit::{App, Entity, Image};
8
8
use store::{
9
ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
10
ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
9
ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,
10
ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store,
11
TeamLayoutRecord, TeamRecord,
11
12
};
12
13
use teams_core::{
13
14
Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
@@ -133,6 +134,22 @@ const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [
133
134
const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
134
135
const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
135
136
const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
137
const DEMO_CHANNEL_MENTIONS: [(&str, ChannelMentions); 4] = [
138
("demo-channel-1-2", mentions(2, 0, 0)),
139
("demo-channel-2-1", mentions(0, 1, 0)),
140
(DEMO_HIDDEN_CHANNEL, mentions(1, 0, 0)),
141
("demo-channel-4-2", mentions(1, 0, 1)),
142
];
143
const PINNED_CHANNEL: &str = "demo-channel-1-1";
144
const PINNED_POST: &str = "t3";
145
146
const fn mentions(personal: u32, channel: u32, team: u32) -> ChannelMentions {
147
ChannelMentions {
148
personal,
149
channel,
150
team,
151
}
152
}
136
153
const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [
137
154
(
138
155
"demo-channel-1-1",
@@ -797,8 +814,21 @@ pub fn seed(store: &Store) {
797
814
});
798
815
}
799
816
}
817
for channel in channels.iter_mut().filter(|channel| {
818
DEMO_CHANNEL_MENTIONS
819
.iter()
820
.any(|(id, _)| *id == channel.id)
821
}) {
822
channel.unread = true;
823
}
800
824
let _ = store.upsert_channels(&channels);
801
825
let _ = store.replace_team_layout(&demo_team_layout(&channels));
826
let _ = store.replace_channel_mentions(
827
&DEMO_CHANNEL_MENTIONS
828
.iter()
829
.map(|(id, mentions)| ((*id).to_owned(), *mentions))
830
.collect::<Vec<_>>(),
831
);
802
832
let _ = store.set_meta("me_user_id", DEMO_USER_ID);
803
833
let _ = store.set_meta("me_display_name", DEMO_USER_NAME);
804
834
let _ = store.upsert_messages(&release_messages());
@@ -975,6 +1005,14 @@ pub fn seed_directory(state: &mut AppState) {
975
1005
}
976
1006
977
1007
fn seed_message_actions(state: &mut AppState) {
1008
state.pins.insert(
1009
PINNED_CHANNEL.to_owned(),
1010
vec![PinnedMessage {
1011
message_id: PINNED_POST.to_owned(),
1012
pinned_at: Some(at(0, 9, 45)),
1013
parent_id: None,
1014
}],
1015
);
978
1016
state.pins.insert(
979
1017
RELEASE_CHAT.to_owned(),
980
1018
vec![PinnedMessage {
@@ -6,8 +6,9 @@ use std::time::Instant;6
use chrono::{DateTime, Duration, Local, TimeZone, Utc};6
use chrono::{DateTime, Duration, Local, TimeZone, Utc};7
use gpui_kit::{App, Entity, Image};7
use gpui_kit::{App, Entity, Image};8
use store::{8
use store::{9
ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,9
ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,10
ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,10
ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store,11
TeamLayoutRecord, TeamRecord,11
};12
};12
use teams_core::{13
use teams_core::{13
Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,14
Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,@@ -133,6 +134,22 @@ const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [133
const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];134
const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];134
const DEMO_HIDDEN_TEAM: &str = "demo-team-4";135
const DEMO_HIDDEN_TEAM: &str = "demo-team-4";135
const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";136
const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";137
const DEMO_CHANNEL_MENTIONS: [(&str, ChannelMentions); 4] = [138
("demo-channel-1-2", mentions(2, 0, 0)),139
("demo-channel-2-1", mentions(0, 1, 0)),140
(DEMO_HIDDEN_CHANNEL, mentions(1, 0, 0)),141
("demo-channel-4-2", mentions(1, 0, 1)),142
];143
const PINNED_CHANNEL: &str = "demo-channel-1-1";144
const PINNED_POST: &str = "t3";145
146
const fn mentions(personal: u32, channel: u32, team: u32) -> ChannelMentions {147
ChannelMentions {148
personal,149
channel,150
team,151
}152
}136
const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [153
const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [137
(154
(138
"demo-channel-1-1",155
"demo-channel-1-1",@@ -797,8 +814,21 @@ pub fn seed(store: &Store) {797
});814
});798
}815
}799
}816
}817
for channel in channels.iter_mut().filter(|channel| {818
DEMO_CHANNEL_MENTIONS819
.iter()820
.any(|(id, _)| *id == channel.id)821
}) {822
channel.unread = true;823
}800
let _ = store.upsert_channels(&channels);824
let _ = store.upsert_channels(&channels);801
let _ = store.replace_team_layout(&demo_team_layout(&channels));825
let _ = store.replace_team_layout(&demo_team_layout(&channels));826
let _ = store.replace_channel_mentions(827
&DEMO_CHANNEL_MENTIONS828
.iter()829
.map(|(id, mentions)| ((*id).to_owned(), *mentions))830
.collect::<Vec<_>>(),831
);802
let _ = store.set_meta("me_user_id", DEMO_USER_ID);832
let _ = store.set_meta("me_user_id", DEMO_USER_ID);803
let _ = store.set_meta("me_display_name", DEMO_USER_NAME);833
let _ = store.set_meta("me_display_name", DEMO_USER_NAME);804
let _ = store.upsert_messages(&release_messages());834
let _ = store.upsert_messages(&release_messages());@@ -975,6 +1005,14 @@ pub fn seed_directory(state: &mut AppState) {975
}1005
}976
1006
977
fn seed_message_actions(state: &mut AppState) {1007
fn seed_message_actions(state: &mut AppState) {1008
state.pins.insert(1009
PINNED_CHANNEL.to_owned(),1010
vec![PinnedMessage {1011
message_id: PINNED_POST.to_owned(),1012
pinned_at: Some(at(0, 9, 45)),1013
parent_id: None,1014
}],1015
);978
state.pins.insert(1016
state.pins.insert(979
RELEASE_CHAT.to_owned(),1017
RELEASE_CHAT.to_owned(),980
vec![PinnedMessage {1018
vec![PinnedMessage {@@ -347,6 +347,7 @@ mod tests {
347
347
.map(|id| (*id).to_owned())
348
348
.collect(),
349
349
notifications: HashMap::new(),
350
mentions: Default::default(),
350
351
}
351
352
}
352
353
@@ -347,6 +347,7 @@ mod tests {347
.map(|id| (*id).to_owned())347
.map(|id| (*id).to_owned())348
.collect(),348
.collect(),349
notifications: HashMap::new(),349
notifications: HashMap::new(),350
mentions: Default::default(),350
}351
}351
}352
}352
353
@@ -68,6 +68,7 @@ mod tests {
68
68
hidden: false,
69
69
hidden_channel_ids: vec!["channel-b".into()],
70
70
notifications: Default::default(),
71
mentions: Default::default(),
71
72
}],
72
73
}
73
74
}
@@ -68,6 +68,7 @@ mod tests {68
hidden: false,68
hidden: false,69
hidden_channel_ids: vec!["channel-b".into()],69
hidden_channel_ids: vec!["channel-b".into()],70
notifications: Default::default(),70
notifications: Default::default(),71
mentions: Default::default(),71
}],72
}],72
}73
}73
}74
}@@ -1,9 +1,9 @@
1
1
use std::collections::{HashMap, HashSet};
2
2
3
use app_ui_kit::widgets::Unread;
3
4
use chrono::{DateTime, FixedOffset, Utc};
4
5
use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};
5
6
use teams_core::{ChatSection, is_event_preview};
6
use app_ui_kit::widgets::Unread;
7
7
8
8
use crate::app_state::chat_title;
9
9
use crate::data::{
@@ -260,10 +260,82 @@ pub fn channel_name_style(unread: bool, shown: bool, selected: bool) -> NameStyl
260
260
}
261
261
}
262
262
263
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264
pub enum MentionBadge {
265
Count(u32),
266
Channel,
267
Team,
268
}
269
270
/// Teams pulls a hidden channel into the list while it holds personal @mentions.
271
pub fn channel_shown(team: &SidebarTeam, channel_id: &str) -> bool {
272
!team.hidden_channel_ids.iter().any(|id| id == channel_id)
273
|| team.channel_mentions(channel_id).personal > 0
274
}
275
276
pub fn channel_hoisted(team: &SidebarTeam, channel_id: &str) -> bool {
277
team.hidden_channel_ids.iter().any(|id| id == channel_id)
278
&& team.channel_mentions(channel_id).personal > 0
279
}
280
281
pub fn team_hoisted(team: &SidebarTeam) -> bool {
282
team.hidden
283
&& team
284
.channels
285
.iter()
286
.any(|channel| channel_hoisted(team, &channel.id))
287
}
288
289
pub fn channel_badge(team: &SidebarTeam, channel_id: &str) -> Option<MentionBadge> {
290
let mentions = team.channel_mentions(channel_id);
291
if mentions.personal > 0 {
292
Some(MentionBadge::Count(mentions.personal))
293
} else if mentions.channel > 0 {
294
Some(MentionBadge::Channel)
295
} else if mentions.team > 0 {
296
Some(MentionBadge::Team)
297
} else {
298
None
299
}
300
}
301
302
/// The collapsed team row sums personal mentions of every channel, the icons only of shown channels.
303
pub fn team_badge(team: &SidebarTeam, expanded: bool) -> Option<MentionBadge> {
304
if expanded || !team_has_unread(team) {
305
return None;
306
}
307
let personal: u32 = team
308
.mentions
309
.iter()
310
.filter(|(channel_id, _)| {
311
team.channels
312
.iter()
313
.any(|channel| &channel.id == *channel_id)
314
})
315
.map(|(_, mentions)| mentions.personal)
316
.sum();
317
if personal > 0 {
318
return Some(MentionBadge::Count(personal));
319
}
320
let shown = || {
321
team.channels
322
.iter()
323
.filter(|channel| channel_shown(team, &channel.id))
324
.map(|channel| team.channel_mentions(&channel.id))
325
};
326
if shown().any(|mentions| mentions.channel > 0) {
327
Some(MentionBadge::Channel)
328
} else if shown().any(|mentions| mentions.team > 0) {
329
Some(MentionBadge::Team)
330
} else {
331
None
332
}
333
}
334
263
335
pub fn team_has_unread(team: &SidebarTeam) -> bool {
264
336
team.channels
265
337
.iter()
266
.any(|channel| channel.unread && !team.hidden_channel_ids.contains(&channel.id))
338
.any(|channel| channel.unread && channel_shown(team, &channel.id))
267
339
}
268
340
269
341
pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle {
@@ -471,40 +543,89 @@ pub fn visible_channel_ids<'a>(input: &ChannelOrderInput<'a>) -> Vec<&'a str> {
471
543
.teams
472
544
.iter()
473
545
.any(|entry| entry.hidden && holds_selection(entry));
474
let teams = input.teams.iter().filter(|entry| !entry.hidden).chain(
475
input
476
.teams
477
.iter()
478
.filter(|entry| entry.hidden && hidden_teams_shown),
479
);
480
for entry in teams {
546
let main_teams = input
547
.teams
548
.iter()
549
.filter(|entry| !entry.hidden || team_hoisted(entry))
550
.map(|entry| (entry, entry.hidden));
551
let hidden_teams = input
552
.teams
553
.iter()
554
.filter(|entry| entry.hidden && hidden_teams_shown)
555
.map(|entry| (entry, false));
556
for (entry, hoisted_only) in main_teams.chain(hidden_teams) {
481
557
if input.collapsed_teams.contains(&entry.team.id) {
482
558
continue;
483
559
}
484
let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
485
let is_selected =
486
|channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
487
let revealed = input.revealed_channel_teams.contains(&entry.team.id);
488
for channel in entry
489
.channels
490
.iter()
491
.filter(|channel| !is_hidden(channel) || is_selected(channel))
492
{
493
push(&channel.id);
494
}
495
if revealed {
496
for channel in entry
497
.channels
498
.iter()
499
.filter(|channel| is_hidden(channel) && !is_selected(channel))
500
{
501
push(&channel.id);
502
}
560
for channel_id in team_channel_ids(entry, hoisted_only, input) {
561
push(channel_id);
503
562
}
504
563
}
505
564
ids
506
565
}
507
566
567
fn team_channel_ids<'a>(
568
entry: &'a SidebarTeam,
569
hoisted_only: bool,
570
input: &ChannelOrderInput<'_>,
571
) -> Vec<&'a str> {
572
let is_selected = |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
573
let rows = team_channel_rows(
574
entry,
575
hoisted_only,
576
input.revealed_channel_teams.contains(&entry.team.id),
577
is_selected,
578
);
579
rows.shown
580
.into_iter()
581
.chain(rows.revealed)
582
.map(|channel| channel.id.as_str())
583
.collect()
584
}
585
586
pub struct TeamChannelRows<'a> {
587
pub shown: Vec<&'a ChannelRecord>,
588
pub hidden_count: usize,
589
pub revealed: Vec<&'a ChannelRecord>,
590
}
591
592
/// `hoisted_only` is a hidden team pulled into the main list: it shows only its hoisted channels.
593
pub fn team_channel_rows<'a>(
594
entry: &'a SidebarTeam,
595
hoisted_only: bool,
596
revealed: bool,
597
is_selected: impl Fn(&ChannelRecord) -> bool,
598
) -> TeamChannelRows<'a> {
599
let shown: Vec<&ChannelRecord> = entry
600
.channels
601
.iter()
602
.filter(|channel| {
603
if hoisted_only {
604
channel_hoisted(entry, &channel.id)
605
} else {
606
is_selected(channel) || channel_shown(entry, &channel.id)
607
}
608
})
609
.collect();
610
if hoisted_only {
611
return TeamChannelRows {
612
shown,
613
hidden_count: 0,
614
revealed: Vec::new(),
615
};
616
}
617
let hidden: Vec<&ChannelRecord> = entry
618
.channels
619
.iter()
620
.filter(|channel| !shown.iter().any(|row| row.id == channel.id))
621
.collect();
622
TeamChannelRows {
623
shown,
624
hidden_count: hidden.len(),
625
revealed: if revealed { hidden } else { Vec::new() },
626
}
627
}
628
508
629
fn section(
509
630
id: String,
510
631
name: String,
@@ -746,6 +867,7 @@ mod tests {
746
867
.map(|id| (*id).to_owned())
747
868
.collect(),
748
869
notifications: HashMap::new(),
870
mentions: Default::default(),
749
871
}
750
872
}
751
873
@@ -857,6 +979,111 @@ mod tests {
857
979
);
858
980
}
859
981
982
fn with_mentions(mut entry: SidebarTeam, mentions: &[(&str, u32, u32, u32)]) -> SidebarTeam {
983
for (channel_id, personal, channel, team) in mentions {
984
entry.mentions.insert(
985
(*channel_id).to_owned(),
986
store::ChannelMentions {
987
personal: *personal,
988
channel: *channel,
989
team: *team,
990
},
991
);
992
}
993
entry
994
}
995
996
#[test]
997
fn channel_badges_prefer_the_count_then_channel_then_team() {
998
let entry = with_mentions(
999
team("t", false, &["a", "b", "c", "d"], &[]),
1000
&[("a", 2, 1, 1), ("b", 0, 3, 1), ("c", 0, 0, 1)],
1001
);
1002
assert_eq!(channel_badge(&entry, "a"), Some(MentionBadge::Count(2)));
1003
assert_eq!(channel_badge(&entry, "b"), Some(MentionBadge::Channel));
1004
assert_eq!(channel_badge(&entry, "c"), Some(MentionBadge::Team));
1005
assert_eq!(channel_badge(&entry, "d"), None);
1006
}
1007
1008
#[test]
1009
fn the_collapsed_team_sums_counts_of_all_channels_and_icons_of_shown_ones() {
1010
let entry = with_unread(
1011
with_mentions(
1012
team("t", false, &["a", "b", "c"], &["b", "c"]),
1013
&[("a", 1, 0, 0), ("b", 2, 0, 0), ("c", 0, 1, 0)],
1014
),
1015
&["a", "b", "c"],
1016
);
1017
assert_eq!(team_badge(&entry, false), Some(MentionBadge::Count(3)));
1018
assert_eq!(team_badge(&entry, true), None);
1019
let icons_only = with_unread(
1020
with_mentions(
1021
team("t", false, &["a", "c"], &["c"]),
1022
&[("a", 0, 0, 1), ("c", 0, 1, 0)],
1023
),
1024
&["a", "c"],
1025
);
1026
assert_eq!(team_badge(&icons_only, false), Some(MentionBadge::Team));
1027
let read = with_mentions(team("t", false, &["a"], &[]), &[("a", 1, 0, 0)]);
1028
assert_eq!(team_badge(&read, false), None);
1029
}
1030
1031
#[test]
1032
fn a_hidden_channel_with_a_personal_mention_is_pulled_into_the_list() {
1033
let entry = with_unread(
1034
with_mentions(
1035
team("t", false, &["a", "b", "c"], &["b", "c"]),
1036
&[("b", 1, 0, 0), ("c", 0, 1, 0)],
1037
),
1038
&["b", "c"],
1039
);
1040
assert!(channel_shown(&entry, "b"));
1041
assert!(!channel_shown(&entry, "c"));
1042
assert!(team_has_unread(&entry));
1043
let rows = team_channel_rows(&entry, false, false, |_| false);
1044
let shown: Vec<&str> = rows
1045
.shown
1046
.iter()
1047
.map(|channel| channel.id.as_str())
1048
.collect();
1049
assert_eq!(shown, ["a", "b"]);
1050
assert_eq!(rows.hidden_count, 1);
1051
assert!(rows.revealed.is_empty());
1052
}
1053
1054
#[test]
1055
fn a_hidden_team_with_a_hoisted_channel_shows_only_that_channel_in_the_main_list() {
1056
let teams = [
1057
team("t1", false, &["a"], &[]),
1058
with_mentions(team("t2", true, &["b", "c"], &["c"]), &[("c", 1, 0, 0)]),
1059
];
1060
assert!(team_hoisted(&teams[1]));
1061
assert!(!team_hoisted(&teams[0]));
1062
let rows = team_channel_rows(&teams[1], true, true, |_| true);
1063
let shown: Vec<&str> = rows
1064
.shown
1065
.iter()
1066
.map(|channel| channel.id.as_str())
1067
.collect();
1068
assert_eq!(shown, ["c"]);
1069
assert_eq!(rows.hidden_count, 0);
1070
let empty = HashSet::new();
1071
let input = ChannelOrderInput {
1072
teams: &teams,
1073
pinned_ids: &[],
1074
collapsed_teams: &empty,
1075
revealed_channel_teams: &empty,
1076
hidden_teams_open: false,
1077
selected_channel: None,
1078
};
1079
assert_eq!(visible_channel_ids(&input), ["a", "c"]);
1080
let open = ChannelOrderInput {
1081
hidden_teams_open: true,
1082
..input
1083
};
1084
assert_eq!(visible_channel_ids(&open), ["a", "c", "b"]);
1085
}
1086
860
1087
#[test]
861
1088
fn muted_chats_stay_out_of_unread_counts() {
862
1089
let mut quiet = chat("a", "group", true);
@@ -1036,7 +1263,10 @@ mod tests {
1036
1263
let group = chat_item(&chats[1], &context, None);
1037
1264
assert_eq!(group.presence_user, None);
1038
1265
assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
1039
assert_eq!(avatar_for(&meeting_chat("meeting-1"), None), AvatarSpec::Meeting);
1266
assert_eq!(
1267
avatar_for(&meeting_chat("meeting-1"), None),
1268
AvatarSpec::Meeting
1269
);
1040
1270
}
1041
1271
1042
1272
#[test]
@@ -1048,7 +1278,9 @@ mod tests {
1048
1278
let collapsed = HashSet::new();
1049
1279
let mut notes = chat(teams_core::NOTES_CHAT_ID, "oneOnOne", false);
1050
1280
notes.title = "Me Myself (You)".into();
1051
notes.members.retain(|member| member.user_id.as_deref() == Some("me"));
1281
notes
1282
.members
1283
.retain(|member| member.user_id.as_deref() == Some("me"));
1052
1284
let chats = vec![notes];
1053
1285
let context = input(&chats, &directory, &collapsed);
1054
1286
let item = chat_item(&chats[0], &context, None);
@@ -1,9 +1,9 @@1
use std::collections::{HashMap, HashSet};1
use std::collections::{HashMap, HashSet};2
2
3
use app_ui_kit::widgets::Unread;3
use chrono::{DateTime, FixedOffset, Utc};4
use chrono::{DateTime, FixedOffset, Utc};4
use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};5
use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};5
use teams_core::{ChatSection, is_event_preview};6
use teams_core::{ChatSection, is_event_preview};6
use app_ui_kit::widgets::Unread;7
7
8
use crate::app_state::chat_title;8
use crate::app_state::chat_title;9
use crate::data::{9
use crate::data::{@@ -260,10 +260,82 @@ pub fn channel_name_style(unread: bool, shown: bool, selected: bool) -> NameStyl260
}260
}261
}261
}262
262
263
#[derive(Debug, Clone, Copy, PartialEq, Eq)]264
pub enum MentionBadge {265
Count(u32),266
Channel,267
Team,268
}269
270
/// Teams pulls a hidden channel into the list while it holds personal @mentions.271
pub fn channel_shown(team: &SidebarTeam, channel_id: &str) -> bool {272
!team.hidden_channel_ids.iter().any(|id| id == channel_id)273
|| team.channel_mentions(channel_id).personal > 0274
}275
276
pub fn channel_hoisted(team: &SidebarTeam, channel_id: &str) -> bool {277
team.hidden_channel_ids.iter().any(|id| id == channel_id)278
&& team.channel_mentions(channel_id).personal > 0279
}280
281
pub fn team_hoisted(team: &SidebarTeam) -> bool {282
team.hidden283
&& team284
.channels285
.iter()286
.any(|channel| channel_hoisted(team, &channel.id))287
}288
289
pub fn channel_badge(team: &SidebarTeam, channel_id: &str) -> Option<MentionBadge> {290
let mentions = team.channel_mentions(channel_id);291
if mentions.personal > 0 {292
Some(MentionBadge::Count(mentions.personal))293
} else if mentions.channel > 0 {294
Some(MentionBadge::Channel)295
} else if mentions.team > 0 {296
Some(MentionBadge::Team)297
} else {298
None299
}300
}301
302
/// The collapsed team row sums personal mentions of every channel, the icons only of shown channels.303
pub fn team_badge(team: &SidebarTeam, expanded: bool) -> Option<MentionBadge> {304
if expanded || !team_has_unread(team) {305
return None;306
}307
let personal: u32 = team308
.mentions309
.iter()310
.filter(|(channel_id, _)| {311
team.channels312
.iter()313
.any(|channel| &channel.id == *channel_id)314
})315
.map(|(_, mentions)| mentions.personal)316
.sum();317
if personal > 0 {318
return Some(MentionBadge::Count(personal));319
}320
let shown = || {321
team.channels322
.iter()323
.filter(|channel| channel_shown(team, &channel.id))324
.map(|channel| team.channel_mentions(&channel.id))325
};326
if shown().any(|mentions| mentions.channel > 0) {327
Some(MentionBadge::Channel)328
} else if shown().any(|mentions| mentions.team > 0) {329
Some(MentionBadge::Team)330
} else {331
None332
}333
}334
263
pub fn team_has_unread(team: &SidebarTeam) -> bool {335
pub fn team_has_unread(team: &SidebarTeam) -> bool {264
team.channels336
team.channels265
.iter()337
.iter()266
.any(|channel| channel.unread && !team.hidden_channel_ids.contains(&channel.id))338
.any(|channel| channel.unread && channel_shown(team, &channel.id))267
}339
}268
340
269
pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle {341
pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle {@@ -471,40 +543,89 @@ pub fn visible_channel_ids<'a>(input: &ChannelOrderInput<'a>) -> Vec<&'a str> {471
.teams543
.teams472
.iter()544
.iter()473
.any(|entry| entry.hidden && holds_selection(entry));545
.any(|entry| entry.hidden && holds_selection(entry));474
let teams = input.teams.iter().filter(|entry| !entry.hidden).chain(546
let main_teams = input475
input547
.teams476
.teams548
.iter()477
.iter()549
.filter(|entry| !entry.hidden || team_hoisted(entry))478
.filter(|entry| entry.hidden && hidden_teams_shown),550
.map(|entry| (entry, entry.hidden));479
);551
let hidden_teams = input480
for entry in teams {552
.teams553
.iter()554
.filter(|entry| entry.hidden && hidden_teams_shown)555
.map(|entry| (entry, false));556
for (entry, hoisted_only) in main_teams.chain(hidden_teams) {481
if input.collapsed_teams.contains(&entry.team.id) {557
if input.collapsed_teams.contains(&entry.team.id) {482
continue;558
continue;483
}559
}484
let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);560
for channel_id in team_channel_ids(entry, hoisted_only, input) {485
let is_selected =561
push(channel_id);486
|channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;487
let revealed = input.revealed_channel_teams.contains(&entry.team.id);488
for channel in entry489
.channels490
.iter()491
.filter(|channel| !is_hidden(channel) || is_selected(channel))492
{493
push(&channel.id);494
}495
if revealed {496
for channel in entry497
.channels498
.iter()499
.filter(|channel| is_hidden(channel) && !is_selected(channel))500
{501
push(&channel.id);502
}503
}562
}504
}563
}505
ids564
ids506
}565
}507
566
567
fn team_channel_ids<'a>(568
entry: &'a SidebarTeam,569
hoisted_only: bool,570
input: &ChannelOrderInput<'_>,571
) -> Vec<&'a str> {572
let is_selected = |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;573
let rows = team_channel_rows(574
entry,575
hoisted_only,576
input.revealed_channel_teams.contains(&entry.team.id),577
is_selected,578
);579
rows.shown580
.into_iter()581
.chain(rows.revealed)582
.map(|channel| channel.id.as_str())583
.collect()584
}585
586
pub struct TeamChannelRows<'a> {587
pub shown: Vec<&'a ChannelRecord>,588
pub hidden_count: usize,589
pub revealed: Vec<&'a ChannelRecord>,590
}591
592
/// `hoisted_only` is a hidden team pulled into the main list: it shows only its hoisted channels.593
pub fn team_channel_rows<'a>(594
entry: &'a SidebarTeam,595
hoisted_only: bool,596
revealed: bool,597
is_selected: impl Fn(&ChannelRecord) -> bool,598
) -> TeamChannelRows<'a> {599
let shown: Vec<&ChannelRecord> = entry600
.channels601
.iter()602
.filter(|channel| {603
if hoisted_only {604
channel_hoisted(entry, &channel.id)605
} else {606
is_selected(channel) || channel_shown(entry, &channel.id)607
}608
})609
.collect();610
if hoisted_only {611
return TeamChannelRows {612
shown,613
hidden_count: 0,614
revealed: Vec::new(),615
};616
}617
let hidden: Vec<&ChannelRecord> = entry618
.channels619
.iter()620
.filter(|channel| !shown.iter().any(|row| row.id == channel.id))621
.collect();622
TeamChannelRows {623
shown,624
hidden_count: hidden.len(),625
revealed: if revealed { hidden } else { Vec::new() },626
}627
}628
508
fn section(629
fn section(509
id: String,630
id: String,510
name: String,631
name: String,@@ -746,6 +867,7 @@ mod tests {746
.map(|id| (*id).to_owned())867
.map(|id| (*id).to_owned())747
.collect(),868
.collect(),748
notifications: HashMap::new(),869
notifications: HashMap::new(),870
mentions: Default::default(),749
}871
}750
}872
}751
873
@@ -857,6 +979,111 @@ mod tests {857
);979
);858
}980
}859
981
982
fn with_mentions(mut entry: SidebarTeam, mentions: &[(&str, u32, u32, u32)]) -> SidebarTeam {983
for (channel_id, personal, channel, team) in mentions {984
entry.mentions.insert(985
(*channel_id).to_owned(),986
store::ChannelMentions {987
personal: *personal,988
channel: *channel,989
team: *team,990
},991
);992
}993
entry994
}995
996
#[test]997
fn channel_badges_prefer_the_count_then_channel_then_team() {998
let entry = with_mentions(999
team("t", false, &["a", "b", "c", "d"], &[]),1000
&[("a", 2, 1, 1), ("b", 0, 3, 1), ("c", 0, 0, 1)],1001
);1002
assert_eq!(channel_badge(&entry, "a"), Some(MentionBadge::Count(2)));1003
assert_eq!(channel_badge(&entry, "b"), Some(MentionBadge::Channel));1004
assert_eq!(channel_badge(&entry, "c"), Some(MentionBadge::Team));1005
assert_eq!(channel_badge(&entry, "d"), None);1006
}1007
1008
#[test]1009
fn the_collapsed_team_sums_counts_of_all_channels_and_icons_of_shown_ones() {1010
let entry = with_unread(1011
with_mentions(1012
team("t", false, &["a", "b", "c"], &["b", "c"]),1013
&[("a", 1, 0, 0), ("b", 2, 0, 0), ("c", 0, 1, 0)],1014
),1015
&["a", "b", "c"],1016
);1017
assert_eq!(team_badge(&entry, false), Some(MentionBadge::Count(3)));1018
assert_eq!(team_badge(&entry, true), None);1019
let icons_only = with_unread(1020
with_mentions(1021
team("t", false, &["a", "c"], &["c"]),1022
&[("a", 0, 0, 1), ("c", 0, 1, 0)],1023
),1024
&["a", "c"],1025
);1026
assert_eq!(team_badge(&icons_only, false), Some(MentionBadge::Team));1027
let read = with_mentions(team("t", false, &["a"], &[]), &[("a", 1, 0, 0)]);1028
assert_eq!(team_badge(&read, false), None);1029
}1030
1031
#[test]1032
fn a_hidden_channel_with_a_personal_mention_is_pulled_into_the_list() {1033
let entry = with_unread(1034
with_mentions(1035
team("t", false, &["a", "b", "c"], &["b", "c"]),1036
&[("b", 1, 0, 0), ("c", 0, 1, 0)],1037
),1038
&["b", "c"],1039
);1040
assert!(channel_shown(&entry, "b"));1041
assert!(!channel_shown(&entry, "c"));1042
assert!(team_has_unread(&entry));1043
let rows = team_channel_rows(&entry, false, false, |_| false);1044
let shown: Vec<&str> = rows1045
.shown1046
.iter()1047
.map(|channel| channel.id.as_str())1048
.collect();1049
assert_eq!(shown, ["a", "b"]);1050
assert_eq!(rows.hidden_count, 1);1051
assert!(rows.revealed.is_empty());1052
}1053
1054
#[test]1055
fn a_hidden_team_with_a_hoisted_channel_shows_only_that_channel_in_the_main_list() {1056
let teams = [1057
team("t1", false, &["a"], &[]),1058
with_mentions(team("t2", true, &["b", "c"], &["c"]), &[("c", 1, 0, 0)]),1059
];1060
assert!(team_hoisted(&teams[1]));1061
assert!(!team_hoisted(&teams[0]));1062
let rows = team_channel_rows(&teams[1], true, true, |_| true);1063
let shown: Vec<&str> = rows1064
.shown1065
.iter()1066
.map(|channel| channel.id.as_str())1067
.collect();1068
assert_eq!(shown, ["c"]);1069
assert_eq!(rows.hidden_count, 0);1070
let empty = HashSet::new();1071
let input = ChannelOrderInput {1072
teams: &teams,1073
pinned_ids: &[],1074
collapsed_teams: &empty,1075
revealed_channel_teams: &empty,1076
hidden_teams_open: false,1077
selected_channel: None,1078
};1079
assert_eq!(visible_channel_ids(&input), ["a", "c"]);1080
let open = ChannelOrderInput {1081
hidden_teams_open: true,1082
..input1083
};1084
assert_eq!(visible_channel_ids(&open), ["a", "c", "b"]);1085
}1086
860
#[test]1087
#[test]861
fn muted_chats_stay_out_of_unread_counts() {1088
fn muted_chats_stay_out_of_unread_counts() {862
let mut quiet = chat("a", "group", true);1089
let mut quiet = chat("a", "group", true);@@ -1036,7 +1263,10 @@ mod tests {1036
let group = chat_item(&chats[1], &context, None);1263
let group = chat_item(&chats[1], &context, None);1037
assert_eq!(group.presence_user, None);1264
assert_eq!(group.presence_user, None);1038
assert!(matches!(group.avatar, AvatarSpec::Pair(..)));1265
assert!(matches!(group.avatar, AvatarSpec::Pair(..)));1039
assert_eq!(avatar_for(&meeting_chat("meeting-1"), None), AvatarSpec::Meeting);1266
assert_eq!(1267
avatar_for(&meeting_chat("meeting-1"), None),1268
AvatarSpec::Meeting1269
);1040
}1270
}1041
1271
1042
#[test]1272
#[test]@@ -1048,7 +1278,9 @@ mod tests {1048
let collapsed = HashSet::new();1278
let collapsed = HashSet::new();1049
let mut notes = chat(teams_core::NOTES_CHAT_ID, "oneOnOne", false);1279
let mut notes = chat(teams_core::NOTES_CHAT_ID, "oneOnOne", false);1050
notes.title = "Me Myself (You)".into();1280
notes.title = "Me Myself (You)".into();1051
notes.members.retain(|member| member.user_id.as_deref() == Some("me"));1281
notes1282
.members1283
.retain(|member| member.user_id.as_deref() == Some("me"));1052
let chats = vec![notes];1284
let chats = vec![notes];1053
let context = input(&chats, &directory, &collapsed);1285
let context = input(&chats, &directory, &collapsed);1054
let item = chat_item(&chats[0], &context, None);1286
let item = chat_item(&chats[0], &context, None);@@ -180,8 +180,9 @@ mod frames {
180
180
COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
181
181
COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
182
182
};
183
use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON};
183
use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
184
184
use crate::views::message_row::BUBBLE_TAGS;
185
use crate::views::pin_banner::PIN_BANNER_TAG;
185
186
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
186
187
use crate::views::reaction_proposal_pill::REACTION_PILL;
187
188
use crate::views::recap_tab::RECAP_REGION;
@@ -1360,6 +1361,48 @@ mod frames {
1360
1361
}
1361
1362
}
1362
1363
1364
const PINNED_CHAT: &str = "demo-chat-release";
1365
const PINNED_CHANNEL: &str = "demo-channel-1-1";
1366
1367
#[gpui_kit::test]
1368
fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {
1369
let (handle, state) = mount(cx);
1370
let mut visual = VisualTestContext::from_window(handle, cx);
1371
let mut found = Vec::new();
1372
for (width, height) in SIZES {
1373
visual.simulate_resize(size(px(width), px(height)));
1374
for selection in [
1375
Selection::Chat(PINNED_CHAT.to_owned()),
1376
Selection::Channel(PINNED_CHANNEL.to_owned()),
1377
] {
1378
let in_chat = matches!(selection, Selection::Chat(_));
1379
visual.update(|_, cx| state.update(cx, |state, cx| state.select(selection, cx)));
1380
collect(&mut visual, Some(PIN_BANNER_TAG));
1381
let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
1382
let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
1383
let mut gaps = vec![
1384
("top", f32::from(banner.top() - timeline.top())),
1385
("left", f32::from(banner.left() - timeline.left())),
1386
("right", f32::from(timeline.right() - banner.right())),
1387
];
1388
if in_chat {
1389
let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1390
gaps.push(("below divider", f32::from(banner.top() - divider.bottom())));
1391
}
1392
let side = gaps[1].1;
1393
if gaps
1394
.iter()
1395
.any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1396
{
1397
found.push(format!(
1398
"pin banner@{width}x{height} chat={in_chat}: gaps {gaps:?} must match"
1399
));
1400
}
1401
}
1402
}
1403
assert!(found.is_empty(), "{}", found.join("\n"));
1404
}
1405
1363
1406
fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1364
1407
collect(visual, Some(COMPOSER_SEND_TAG));
1365
1408
let mut bounds_of = |path: &'static str| {
@@ -180,8 +180,9 @@ mod frames {180
COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,180
COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,181
COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,181
COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,182
};182
};183
use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON};183
use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};184
use crate::views::message_row::BUBBLE_TAGS;184
use crate::views::message_row::BUBBLE_TAGS;185
use crate::views::pin_banner::PIN_BANNER_TAG;185
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};186
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};186
use crate::views::reaction_proposal_pill::REACTION_PILL;187
use crate::views::reaction_proposal_pill::REACTION_PILL;187
use crate::views::recap_tab::RECAP_REGION;188
use crate::views::recap_tab::RECAP_REGION;@@ -1360,6 +1361,48 @@ mod frames {1360
}1361
}1361
}1362
}1362
1363
1364
const PINNED_CHAT: &str = "demo-chat-release";1365
const PINNED_CHANNEL: &str = "demo-channel-1-1";1366
1367
#[gpui_kit::test]1368
fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {1369
let (handle, state) = mount(cx);1370
let mut visual = VisualTestContext::from_window(handle, cx);1371
let mut found = Vec::new();1372
for (width, height) in SIZES {1373
visual.simulate_resize(size(px(width), px(height)));1374
for selection in [1375
Selection::Chat(PINNED_CHAT.to_owned()),1376
Selection::Channel(PINNED_CHANNEL.to_owned()),1377
] {1378
let in_chat = matches!(selection, Selection::Chat(_));1379
visual.update(|_, cx| state.update(cx, |state, cx| state.select(selection, cx)));1380
collect(&mut visual, Some(PIN_BANNER_TAG));1381
let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");1382
let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");1383
let mut gaps = vec![1384
("top", f32::from(banner.top() - timeline.top())),1385
("left", f32::from(banner.left() - timeline.left())),1386
("right", f32::from(timeline.right() - banner.right())),1387
];1388
if in_chat {1389
let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");1390
gaps.push(("below divider", f32::from(banner.top() - divider.bottom())));1391
}1392
let side = gaps[1].1;1393
if gaps1394
.iter()1395
.any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)1396
{1397
found.push(format!(1398
"pin banner@{width}x{height} chat={in_chat}: gaps {gaps:?} must match"1399
));1400
}1401
}1402
}1403
assert!(found.is_empty(), "{}", found.join("\n"));1404
}1405
1363
fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {1406
fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {1364
collect(visual, Some(COMPOSER_SEND_TAG));1407
collect(visual, Some(COMPOSER_SEND_TAG));1365
let mut bounds_of = |path: &'static str| {1408
let mut bounds_of = |path: &'static str| {@@ -1397,6 +1397,7 @@ mod tests {
1397
1397
hidden: false,
1398
1398
hidden_channel_ids: Vec::new(),
1399
1399
notifications: Default::default(),
1400
mentions: Default::default(),
1400
1401
}],
1401
1402
}
1402
1403
}
@@ -1397,6 +1397,7 @@ mod tests {1397
hidden: false,1397
hidden: false,1398
hidden_channel_ids: Vec::new(),1398
hidden_channel_ids: Vec::new(),1399
notifications: Default::default(),1399
notifications: Default::default(),1400
mentions: Default::default(),1400
}],1401
}],1401
}1402
}1402
}1403
}@@ -50,7 +50,6 @@ use super::reaction_pills::{ReactionControls, ReactionPopover};
50
50
use super::scroll_edge::edge_divider;
51
51
use super::toolbar_placement::{TimelineBounds, record_bounds};
52
52
use super::widgets::{icon, symbol};
53
use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
54
53
use crate::agents::{AgentRun, StartRequest};
55
54
use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_title};
56
55
use crate::backend::Engine;
@@ -81,6 +80,7 @@ use crate::sidebar_model::{AvatarSpec, Face, channel_unread};
81
80
use crate::theme;
82
81
use crate::translation::TranslationLine;
83
82
use crate::typing::typing_tooltip;
83
use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
84
84
use detached::DetachedWindow;
85
85
use feed::{FeedStash, subject_input};
86
86
use mcp::ReactionProposal;
@@ -89,6 +89,7 @@ use shared::SharedState;
89
89
90
90
pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";
91
91
pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
92
pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";
92
93
const HEADER_HEIGHT: f32 = 60.;
93
94
const HEADER_PADDING: f32 = 20.;
94
95
const HEADER_GAP: f32 = 12.;
@@ -881,9 +882,9 @@ impl ConversationView {
881
882
self.start_fetch(cx);
882
883
self.mark_read(ReadTrigger::Open, cx);
883
884
self.refresh_pin_previews(cx);
884
if let Some(chat_id) = self.chat_id() {
885
if let Some(conversation_id) = self.pin_conversation_id() {
885
886
self.app
886
.update(cx, |state, cx| state.refresh_pins(&chat_id, cx));
887
.update(cx, |state, cx| state.refresh_pins(&conversation_id, cx));
887
888
}
888
889
let target = self
889
890
.current
@@ -3039,10 +3040,17 @@ impl ConversationView {
3039
3040
let saved = self
3040
3041
.conversation_id()
3041
3042
.is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3042
let pinned = chat_id
3043
.as_deref()
3044
.is_some_and(|chat_id| state.is_pinned(chat_id, key));
3045
3043
let in_chat = chat_id.is_some();
3044
let pin_conversation_id = self.pin_conversation_id();
3045
let pinned = pin_conversation_id
3046
.as_deref()
3047
.is_some_and(|conversation_id| state.is_pinned(conversation_id, key));
3048
let pinnable = in_chat
3049
|| pin_conversation_id.as_deref().is_some_and(|channel_id| {
3050
state
3051
.message_record(channel_id, key)
3052
.is_some_and(|record| record.reply_to_id.is_none())
3053
});
3046
3054
let (delegate, manage_agents) = self.delegate_entries(key, cx);
3047
3055
MessageMenu {
3048
3056
key: key.to_owned(),
@@ -3057,7 +3065,7 @@ impl ConversationView {
3057
3065
translate_label,
3058
3066
save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3059
3067
saved,
3060
toggle_pinned: in_chat.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
3068
toggle_pinned: pinnable.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
3061
3069
pinned,
3062
3070
edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3063
3071
delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
@@ -3650,6 +3658,7 @@ impl Render for ConversationView {
3650
3658
.children(new_post)
3651
3659
.child(
3652
3660
div()
3661
.debug_selector(|| TIMELINE_TAG.into())
3653
3662
.relative()
3654
3663
.flex_1()
3655
3664
.min_h_0()
@@ -50,7 +50,6 @@ use super::reaction_pills::{ReactionControls, ReactionPopover};50
use super::scroll_edge::edge_divider;50
use super::scroll_edge::edge_divider;51
use super::toolbar_placement::{TimelineBounds, record_bounds};51
use super::toolbar_placement::{TimelineBounds, record_bounds};52
use super::widgets::{icon, symbol};52
use super::widgets::{icon, symbol};53
use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};54
use crate::agents::{AgentRun, StartRequest};53
use crate::agents::{AgentRun, StartRequest};55
use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_title};54
use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_title};56
use crate::backend::Engine;55
use crate::backend::Engine;@@ -81,6 +80,7 @@ use crate::sidebar_model::{AvatarSpec, Face, channel_unread};81
use crate::theme;80
use crate::theme;82
use crate::translation::TranslationLine;81
use crate::translation::TranslationLine;83
use crate::typing::typing_tooltip;82
use crate::typing::typing_tooltip;83
use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};84
use detached::DetachedWindow;84
use detached::DetachedWindow;85
use feed::{FeedStash, subject_input};85
use feed::{FeedStash, subject_input};86
use mcp::ReactionProposal;86
use mcp::ReactionProposal;@@ -89,6 +89,7 @@ use shared::SharedState;89
89
90
pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";90
pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";91
pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";91
pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";92
pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";92
const HEADER_HEIGHT: f32 = 60.;93
const HEADER_HEIGHT: f32 = 60.;93
const HEADER_PADDING: f32 = 20.;94
const HEADER_PADDING: f32 = 20.;94
const HEADER_GAP: f32 = 12.;95
const HEADER_GAP: f32 = 12.;@@ -881,9 +882,9 @@ impl ConversationView {881
self.start_fetch(cx);882
self.start_fetch(cx);882
self.mark_read(ReadTrigger::Open, cx);883
self.mark_read(ReadTrigger::Open, cx);883
self.refresh_pin_previews(cx);884
self.refresh_pin_previews(cx);884
if let Some(chat_id) = self.chat_id() {885
if let Some(conversation_id) = self.pin_conversation_id() {885
self.app886
self.app886
.update(cx, |state, cx| state.refresh_pins(&chat_id, cx));887
.update(cx, |state, cx| state.refresh_pins(&conversation_id, cx));887
}888
}888
let target = self889
let target = self889
.current890
.current@@ -3039,10 +3040,17 @@ impl ConversationView {3039
let saved = self3040
let saved = self3040
.conversation_id()3041
.conversation_id()3041
.is_some_and(|conversation_id| state.is_saved(&conversation_id, key));3042
.is_some_and(|conversation_id| state.is_saved(&conversation_id, key));3042
let pinned = chat_id3043
.as_deref()3044
.is_some_and(|chat_id| state.is_pinned(chat_id, key));3045
let in_chat = chat_id.is_some();3043
let in_chat = chat_id.is_some();3044
let pin_conversation_id = self.pin_conversation_id();3045
let pinned = pin_conversation_id3046
.as_deref()3047
.is_some_and(|conversation_id| state.is_pinned(conversation_id, key));3048
let pinnable = in_chat3049
|| pin_conversation_id.as_deref().is_some_and(|channel_id| {3050
state3051
.message_record(channel_id, key)3052
.is_some_and(|record| record.reply_to_id.is_none())3053
});3046
let (delegate, manage_agents) = self.delegate_entries(key, cx);3054
let (delegate, manage_agents) = self.delegate_entries(key, cx);3047
MessageMenu {3055
MessageMenu {3048
key: key.to_owned(),3056
key: key.to_owned(),@@ -3057,7 +3065,7 @@ impl ConversationView {3057
translate_label,3065
translate_label,3058
save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),3066
save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),3059
saved,3067
saved,3060
toggle_pinned: in_chat.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),3068
toggle_pinned: pinnable.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),3061
pinned,3069
pinned,3062
edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),3070
edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),3063
delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),3071
delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),@@ -3650,6 +3658,7 @@ impl Render for ConversationView {3650
.children(new_post)3658
.children(new_post)3651
.child(3659
.child(3652
div()3660
div()3661
.debug_selector(|| TIMELINE_TAG.into())3653
.relative()3662
.relative()3654
.flex_1()3663
.flex_1()3655
.min_h_0()3664
.min_h_0()@@ -33,36 +33,42 @@ impl ConversationView {
33
33
}
34
34
}
35
35
36
pub(super) fn pin_conversation_id(&self) -> Option<String> {
37
self.current
38
.as_ref()
39
.map(|current| current.selection.conversation_id().to_owned())
40
}
41
36
42
pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {
37
43
self.pin_previews.clear();
38
44
self.pin_fetches.clear();
39
45
self.pin_index = 0;
40
let Some(chat_id) = self.chat_id() else {
46
let Some(conversation_id) = self.pin_conversation_id() else {
41
47
return;
42
48
};
43
self.update_pin_previews(&chat_id, cx);
49
self.update_pin_previews(&conversation_id, cx);
44
50
cx.notify();
45
51
}
46
52
47
pub(super) fn on_pins_changed(&mut self, chat_id: &str, cx: &mut Context<Self>) {
48
if self.chat_id().as_deref() != Some(chat_id) {
53
pub(super) fn on_pins_changed(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
54
if self.pin_conversation_id().as_deref() != Some(conversation_id) {
49
55
return;
50
56
}
51
57
self.pin_index = 0;
52
self.update_pin_previews(chat_id, cx);
58
self.update_pin_previews(conversation_id, cx);
53
59
cx.notify();
54
60
}
55
61
56
fn update_pin_previews(&mut self, chat_id: &str, cx: &mut Context<Self>) {
62
fn update_pin_previews(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
57
63
let state = self.app.read(cx);
58
64
let ids: Vec<String> = state
59
.pinned_messages(chat_id)
65
.pinned_messages(conversation_id)
60
66
.iter()
61
67
.map(|pin| pin.message_id.clone())
62
68
.collect();
63
69
let records = state
64
70
.store
65
.messages_by_id(chat_id, &ids)
71
.messages_by_id(conversation_id, &ids)
66
72
.unwrap_or_default();
67
73
let mut previews: HashMap<String, PinPreview> = records
68
74
.into_iter()
@@ -82,24 +88,29 @@ impl ConversationView {
82
88
}
83
89
for id in ids {
84
90
if !self.pin_previews.contains_key(&id) {
85
self.fetch_pin_preview(chat_id, id, cx);
91
self.fetch_pin_preview(conversation_id, id, cx);
86
92
}
87
93
}
88
94
}
89
95
90
fn fetch_pin_preview(&mut self, chat_id: &str, message_id: String, cx: &mut Context<Self>) {
96
fn fetch_pin_preview(
97
&mut self,
98
conversation_id: &str,
99
message_id: String,
100
cx: &mut Context<Self>,
101
) {
91
102
let Some(engine) = self.app.read(cx).engine.clone() else {
92
103
return;
93
104
};
94
if !self.pin_fetches.insert(message_id.clone()) {
105
if self.chat_id().is_none() || !self.pin_fetches.insert(message_id.clone()) {
95
106
return;
96
107
}
97
let chat_id = chat_id.to_owned();
98
let task_chat_id = chat_id.clone();
108
let conversation_id = conversation_id.to_owned();
109
let task_conversation_id = conversation_id.clone();
99
110
let task_message_id = message_id.clone();
100
111
let receiver = runtime::spawn(async move {
101
112
engine
102
.fetch_chat_message(&task_chat_id, &task_message_id)
113
.fetch_chat_message(&task_conversation_id, &task_message_id)
103
114
.await
104
115
});
105
116
cx.spawn(async move |this, cx| {
@@ -107,8 +118,9 @@ impl ConversationView {
107
118
return;
108
119
};
109
120
this.update(cx, |this, cx| {
110
if this.chat_id().as_deref() == Some(chat_id.as_str()) {
111
this.pin_previews.insert(message_id, PinPreview::of(&record));
121
if this.conversation_id().as_deref() == Some(conversation_id.as_str()) {
122
this.pin_previews
123
.insert(message_id, PinPreview::of(&record));
112
124
cx.notify();
113
125
}
114
126
})
@@ -128,8 +140,8 @@ impl ConversationView {
128
140
}
129
141
130
142
pub(super) fn render_pin_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
131
let chat_id = self.chat_id()?;
132
let pins = self.app.read(cx).pinned_messages(&chat_id);
143
let conversation_id = self.pin_conversation_id()?;
144
let pins = self.app.read(cx).pinned_messages(&conversation_id);
133
145
let pin = pins.get(self.pin_index)?;
134
146
let preview = self.pin_previews.get(&pin.message_id);
135
147
let data = PinBannerData {
@@ -149,36 +161,40 @@ impl ConversationView {
149
161
}
150
162
151
163
fn shown_pin_id(&self, cx: &App) -> Option<String> {
152
let chat_id = self.chat_id()?;
164
let conversation_id = self.pin_conversation_id()?;
153
165
self.app
154
166
.read(cx)
155
.pinned_messages(&chat_id)
167
.pinned_messages(&conversation_id)
156
168
.get(self.pin_index)
157
169
.map(|pin| pin.message_id.clone())
158
170
}
159
171
160
172
fn open_shown_pin(&mut self, cx: &mut Context<Self>) {
161
let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {
173
let (Some(conversation_id), Some(message_id)) =
174
(self.pin_conversation_id(), self.shown_pin_id(cx))
175
else {
162
176
return;
163
177
};
164
self.jump_to_message(&chat_id, &message_id, cx);
178
self.jump_to_message(&conversation_id, &message_id, cx);
165
179
}
166
180
167
181
fn step_pin(&mut self, delta: isize, cx: &mut Context<Self>) {
168
let Some(chat_id) = self.chat_id() else {
182
let Some(conversation_id) = self.pin_conversation_id() else {
169
183
return;
170
184
};
171
let total = self.app.read(cx).pinned_messages(&chat_id).len();
185
let total = self.app.read(cx).pinned_messages(&conversation_id).len();
172
186
self.pin_index = cycle_pin(self.pin_index, total, delta);
173
187
cx.notify();
174
188
}
175
189
176
190
fn unpin_shown_pin(&mut self, cx: &mut Context<Self>) {
177
let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {
191
let (Some(conversation_id), Some(message_id)) =
192
(self.pin_conversation_id(), self.shown_pin_id(cx))
193
else {
178
194
return;
179
195
};
180
196
self.app.update(cx, |state, cx| {
181
state.set_pinned(&chat_id, &message_id, false, cx)
197
state.set_pinned(&conversation_id, &message_id, false, cx)
182
198
});
183
199
}
184
200
@@ -207,9 +223,9 @@ impl ConversationView {
207
223
}
208
224
209
225
pub(super) fn toggle_pinned(&mut self, message_id: &str, cx: &mut Context<Self>) {
210
if let Some(chat_id) = self.chat_id() {
226
if let Some(conversation_id) = self.pin_conversation_id() {
211
227
self.app.update(cx, |state, cx| {
212
state.toggle_pinned(&chat_id, message_id, cx)
228
state.toggle_pinned(&conversation_id, message_id, cx)
213
229
});
214
230
}
215
231
}
@@ -33,36 +33,42 @@ impl ConversationView {33
}33
}34
}34
}35
35
36
pub(super) fn pin_conversation_id(&self) -> Option<String> {37
self.current38
.as_ref()39
.map(|current| current.selection.conversation_id().to_owned())40
}41
36
pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {42
pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {37
self.pin_previews.clear();43
self.pin_previews.clear();38
self.pin_fetches.clear();44
self.pin_fetches.clear();39
self.pin_index = 0;45
self.pin_index = 0;40
let Some(chat_id) = self.chat_id() else {46
let Some(conversation_id) = self.pin_conversation_id() else {41
return;47
return;42
};48
};43
self.update_pin_previews(&chat_id, cx);49
self.update_pin_previews(&conversation_id, cx);44
cx.notify();50
cx.notify();45
}51
}46
52
47
pub(super) fn on_pins_changed(&mut self, chat_id: &str, cx: &mut Context<Self>) {53
pub(super) fn on_pins_changed(&mut self, conversation_id: &str, cx: &mut Context<Self>) {48
if self.chat_id().as_deref() != Some(chat_id) {54
if self.pin_conversation_id().as_deref() != Some(conversation_id) {49
return;55
return;50
}56
}51
self.pin_index = 0;57
self.pin_index = 0;52
self.update_pin_previews(chat_id, cx);58
self.update_pin_previews(conversation_id, cx);53
cx.notify();59
cx.notify();54
}60
}55
61
56
fn update_pin_previews(&mut self, chat_id: &str, cx: &mut Context<Self>) {62
fn update_pin_previews(&mut self, conversation_id: &str, cx: &mut Context<Self>) {57
let state = self.app.read(cx);63
let state = self.app.read(cx);58
let ids: Vec<String> = state64
let ids: Vec<String> = state59
.pinned_messages(chat_id)65
.pinned_messages(conversation_id)60
.iter()66
.iter()61
.map(|pin| pin.message_id.clone())67
.map(|pin| pin.message_id.clone())62
.collect();68
.collect();63
let records = state69
let records = state64
.store70
.store65
.messages_by_id(chat_id, &ids)71
.messages_by_id(conversation_id, &ids)66
.unwrap_or_default();72
.unwrap_or_default();67
let mut previews: HashMap<String, PinPreview> = records73
let mut previews: HashMap<String, PinPreview> = records68
.into_iter()74
.into_iter()@@ -82,24 +88,29 @@ impl ConversationView {82
}88
}83
for id in ids {89
for id in ids {84
if !self.pin_previews.contains_key(&id) {90
if !self.pin_previews.contains_key(&id) {85
self.fetch_pin_preview(chat_id, id, cx);91
self.fetch_pin_preview(conversation_id, id, cx);86
}92
}87
}93
}88
}94
}89
95
90
fn fetch_pin_preview(&mut self, chat_id: &str, message_id: String, cx: &mut Context<Self>) {96
fn fetch_pin_preview(97
&mut self,98
conversation_id: &str,99
message_id: String,100
cx: &mut Context<Self>,101
) {91
let Some(engine) = self.app.read(cx).engine.clone() else {102
let Some(engine) = self.app.read(cx).engine.clone() else {92
return;103
return;93
};104
};94
if !self.pin_fetches.insert(message_id.clone()) {105
if self.chat_id().is_none() || !self.pin_fetches.insert(message_id.clone()) {95
return;106
return;96
}107
}97
let chat_id = chat_id.to_owned();108
let conversation_id = conversation_id.to_owned();98
let task_chat_id = chat_id.clone();109
let task_conversation_id = conversation_id.clone();99
let task_message_id = message_id.clone();110
let task_message_id = message_id.clone();100
let receiver = runtime::spawn(async move {111
let receiver = runtime::spawn(async move {101
engine112
engine102
.fetch_chat_message(&task_chat_id, &task_message_id)113
.fetch_chat_message(&task_conversation_id, &task_message_id)103
.await114
.await104
});115
});105
cx.spawn(async move |this, cx| {116
cx.spawn(async move |this, cx| {@@ -107,8 +118,9 @@ impl ConversationView {107
return;118
return;108
};119
};109
this.update(cx, |this, cx| {120
this.update(cx, |this, cx| {110
if this.chat_id().as_deref() == Some(chat_id.as_str()) {121
if this.conversation_id().as_deref() == Some(conversation_id.as_str()) {111
this.pin_previews.insert(message_id, PinPreview::of(&record));122
this.pin_previews123
.insert(message_id, PinPreview::of(&record));112
cx.notify();124
cx.notify();113
}125
}114
})126
})@@ -128,8 +140,8 @@ impl ConversationView {128
}140
}129
141
130
pub(super) fn render_pin_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {142
pub(super) fn render_pin_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {131
let chat_id = self.chat_id()?;143
let conversation_id = self.pin_conversation_id()?;132
let pins = self.app.read(cx).pinned_messages(&chat_id);144
let pins = self.app.read(cx).pinned_messages(&conversation_id);133
let pin = pins.get(self.pin_index)?;145
let pin = pins.get(self.pin_index)?;134
let preview = self.pin_previews.get(&pin.message_id);146
let preview = self.pin_previews.get(&pin.message_id);135
let data = PinBannerData {147
let data = PinBannerData {@@ -149,36 +161,40 @@ impl ConversationView {149
}161
}150
162
151
fn shown_pin_id(&self, cx: &App) -> Option<String> {163
fn shown_pin_id(&self, cx: &App) -> Option<String> {152
let chat_id = self.chat_id()?;164
let conversation_id = self.pin_conversation_id()?;153
self.app165
self.app154
.read(cx)166
.read(cx)155
.pinned_messages(&chat_id)167
.pinned_messages(&conversation_id)156
.get(self.pin_index)168
.get(self.pin_index)157
.map(|pin| pin.message_id.clone())169
.map(|pin| pin.message_id.clone())158
}170
}159
171
160
fn open_shown_pin(&mut self, cx: &mut Context<Self>) {172
fn open_shown_pin(&mut self, cx: &mut Context<Self>) {161
let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {173
let (Some(conversation_id), Some(message_id)) =174
(self.pin_conversation_id(), self.shown_pin_id(cx))175
else {162
return;176
return;163
};177
};164
self.jump_to_message(&chat_id, &message_id, cx);178
self.jump_to_message(&conversation_id, &message_id, cx);165
}179
}166
180
167
fn step_pin(&mut self, delta: isize, cx: &mut Context<Self>) {181
fn step_pin(&mut self, delta: isize, cx: &mut Context<Self>) {168
let Some(chat_id) = self.chat_id() else {182
let Some(conversation_id) = self.pin_conversation_id() else {169
return;183
return;170
};184
};171
let total = self.app.read(cx).pinned_messages(&chat_id).len();185
let total = self.app.read(cx).pinned_messages(&conversation_id).len();172
self.pin_index = cycle_pin(self.pin_index, total, delta);186
self.pin_index = cycle_pin(self.pin_index, total, delta);173
cx.notify();187
cx.notify();174
}188
}175
189
176
fn unpin_shown_pin(&mut self, cx: &mut Context<Self>) {190
fn unpin_shown_pin(&mut self, cx: &mut Context<Self>) {177
let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {191
let (Some(conversation_id), Some(message_id)) =192
(self.pin_conversation_id(), self.shown_pin_id(cx))193
else {178
return;194
return;179
};195
};180
self.app.update(cx, |state, cx| {196
self.app.update(cx, |state, cx| {181
state.set_pinned(&chat_id, &message_id, false, cx)197
state.set_pinned(&conversation_id, &message_id, false, cx)182
});198
});183
}199
}184
200
@@ -207,9 +223,9 @@ impl ConversationView {207
}223
}208
224
209
pub(super) fn toggle_pinned(&mut self, message_id: &str, cx: &mut Context<Self>) {225
pub(super) fn toggle_pinned(&mut self, message_id: &str, cx: &mut Context<Self>) {210
if let Some(chat_id) = self.chat_id() {226
if let Some(conversation_id) = self.pin_conversation_id() {211
self.app.update(cx, |state, cx| {227
self.app.update(cx, |state, cx| {212
state.toggle_pinned(&chat_id, message_id, cx)228
state.toggle_pinned(&conversation_id, message_id, cx)213
});229
});214
}230
}215
}231
}@@ -3,12 +3,15 @@ use gpui_kit::component::{h_flex, tooltip::Tooltip};
3
3
use gpui_kit::prelude::FluentBuilder as _;
4
4
use gpui_kit::*;
5
5
6
use app_ui_kit::layout::ROW_PADDING;
7
6
8
use super::message_actions::Action;
7
9
use super::widgets::icon;
8
10
use crate::theme;
9
11
10
12
const BANNER_HEIGHT: f32 = 40.;
11
const BANNER_MARGIN: f32 = 20.;
13
const BANNER_INSET: f32 = ROW_PADDING;
14
pub const PIN_BANNER_TAG: &str = "shell/islands/main/pin-banner";
12
15
const BANNER_GAP: f32 = 8.;
13
16
const BANNER_PADDING: f32 = 12.;
14
17
const BUTTON_SIZE: f32 = 28.;
@@ -29,15 +32,19 @@ pub struct PinBannerActions {
29
32
}
30
33
31
34
pub fn pin_banner_inset(shown: bool) -> Pixels {
32
px(if shown { BANNER_HEIGHT + BANNER_GAP } else { 0. })
35
px(if shown {
36
BANNER_INSET + BANNER_HEIGHT + BANNER_GAP
37
} else {
38
0.
39
})
33
40
}
34
41
35
42
pub fn pin_banner_overlay(banner: AnyElement) -> AnyElement {
36
43
div()
37
44
.absolute()
38
.top_0()
39
.left(px(BANNER_MARGIN))
40
.right(px(BANNER_MARGIN))
45
.top(px(BANNER_INSET))
46
.left(px(BANNER_INSET))
47
.right(px(BANNER_INSET))
41
48
.child(banner)
42
49
.into_any_element()
43
50
}
@@ -86,6 +93,7 @@ pub fn render_pin_banner(data: PinBannerData, actions: PinBannerActions) -> AnyE
86
93
} = actions;
87
94
h_flex()
88
95
.id("pin-banner")
96
.debug_selector(|| PIN_BANNER_TAG.into())
89
97
.group("pin-banner")
90
98
.occlude()
91
99
.w_full()
@@ -3,12 +3,15 @@ use gpui_kit::component::{h_flex, tooltip::Tooltip};3
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::*;4
use gpui_kit::*;5
5
6
use app_ui_kit::layout::ROW_PADDING;7
6
use super::message_actions::Action;8
use super::message_actions::Action;7
use super::widgets::icon;9
use super::widgets::icon;8
use crate::theme;10
use crate::theme;9
11
10
const BANNER_HEIGHT: f32 = 40.;12
const BANNER_HEIGHT: f32 = 40.;11
const BANNER_MARGIN: f32 = 20.;13
const BANNER_INSET: f32 = ROW_PADDING;14
pub const PIN_BANNER_TAG: &str = "shell/islands/main/pin-banner";12
const BANNER_GAP: f32 = 8.;15
const BANNER_GAP: f32 = 8.;13
const BANNER_PADDING: f32 = 12.;16
const BANNER_PADDING: f32 = 12.;14
const BUTTON_SIZE: f32 = 28.;17
const BUTTON_SIZE: f32 = 28.;@@ -29,15 +32,19 @@ pub struct PinBannerActions {29
}32
}30
33
31
pub fn pin_banner_inset(shown: bool) -> Pixels {34
pub fn pin_banner_inset(shown: bool) -> Pixels {32
px(if shown { BANNER_HEIGHT + BANNER_GAP } else { 0. })35
px(if shown {36
BANNER_INSET + BANNER_HEIGHT + BANNER_GAP37
} else {38
0.39
})33
}40
}34
41
35
pub fn pin_banner_overlay(banner: AnyElement) -> AnyElement {42
pub fn pin_banner_overlay(banner: AnyElement) -> AnyElement {36
div()43
div()37
.absolute()44
.absolute()38
.top_0()45
.top(px(BANNER_INSET))39
.left(px(BANNER_MARGIN))46
.left(px(BANNER_INSET))40
.right(px(BANNER_MARGIN))47
.right(px(BANNER_INSET))41
.child(banner)48
.child(banner)42
.into_any_element()49
.into_any_element()43
}50
}@@ -86,6 +93,7 @@ pub fn render_pin_banner(data: PinBannerData, actions: PinBannerActions) -> AnyE86
} = actions;93
} = actions;87
h_flex()94
h_flex()88
.id("pin-banner")95
.id("pin-banner")96
.debug_selector(|| PIN_BANNER_TAG.into())89
.group("pin-banner")97
.group("pin-banner")90
.occlude()98
.occlude()91
.w_full()99
.w_full()@@ -30,9 +30,10 @@ use crate::format;
30
30
use crate::local_previews::LocalPreview;
31
31
use crate::notice::truncated;
32
32
use crate::sidebar_model::{
33
AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, NameStyle,
34
NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,
35
channel_name_style, older_chats_trigger_resets, step_id, team_name_style, visible_channel_ids,
33
AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, MentionBadge,
34
NameStyle, NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,
35
channel_badge, channel_name_style, channel_shown, older_chats_trigger_resets, step_id,
36
team_badge, team_channel_rows, team_hoisted, team_name_style, visible_channel_ids,
36
37
wants_older_chats,
37
38
};
38
39
use crate::theme;
@@ -54,12 +55,14 @@ const VIEWPORT_MARGIN: f32 = 300.;
54
55
const AVATAR_SIZE: f32 = 36.;
55
56
const PINNED_LABEL: &str = "Pinned";
56
57
const TEAMS_LABEL: &str = "Teams";
58
const MARK_ALL_READ_LABEL: &str = "Mark all as read";
57
59
const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
58
60
const TEAM_ROW_HEIGHT: f32 = 40.;
59
61
const REVEAL_ROW_HEIGHT: f32 = 32.;
60
62
const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
61
63
const MENU_ICON_SIZE: f32 = 15.;
62
64
const NOTIFICATION_ICON_SIZE: f32 = 13.;
65
const MENTION_ICON_SIZE: f32 = 15.;
63
66
64
67
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65
68
pub enum SidebarTab {
@@ -747,6 +750,28 @@ impl SidebarView {
747
750
.dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))
748
751
}
749
752
753
fn channel_list_menu_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
754
let state = self.state.clone();
755
let read_only = self.state.read(cx).mode.read_only;
756
Button::new("channel-list-more")
757
.icon(IconName::Ellipsis)
758
.ghost()
759
.size(px(NEW_CHAT_BUTTON_SIZE))
760
.rounded(px(8.))
761
.tooltip("More options")
762
.dropdown_menu(move |menu, _, _| {
763
let state = state.clone();
764
menu.item(
765
PopupMenuItem::new(MARK_ALL_READ_LABEL)
766
.icon(menu_icon(IconName::CheckCheck))
767
.disabled(read_only)
768
.on_click(move |_, _, cx| {
769
state.update(cx, |state, cx| state.mark_all_channels_read(cx));
770
}),
771
)
772
})
773
}
774
750
775
fn draft_row(&self) -> impl IntoElement {
751
776
h_flex()
752
777
.id("new-chat-draft")
@@ -1218,6 +1243,7 @@ impl SidebarView {
1218
1243
channel: &ChannelRecord,
1219
1244
selected: bool,
1220
1245
notifications: ChannelNotifications,
1246
badge: Option<MentionBadge>,
1221
1247
) -> AnyElement {
1222
1248
let unread = channel.unread;
1223
1249
let name_style = channel_name_style(unread, true, selected);
@@ -1278,15 +1304,19 @@ impl SidebarView {
1278
1304
),
1279
1305
)
1280
1306
.child(
1281
h_flex().gap(px(8.)).items_center().child(
1282
div()
1283
.flex_1()
1284
.min_w_0()
1285
.truncate()
1286
.text_size(px(12.))
1287
.text_color(theme::text_muted())
1288
.child(team.name.clone()),
1289
),
1307
h_flex()
1308
.gap(px(8.))
1309
.items_center()
1310
.child(
1311
div()
1312
.flex_1()
1313
.min_w_0()
1314
.truncate()
1315
.text_size(px(12.))
1316
.text_color(theme::text_muted())
1317
.child(team.name.clone()),
1318
)
1319
.children(badge.map(mention_badge)),
1290
1320
),
1291
1321
)
1292
1322
.on_click(move |_, _, cx| {
@@ -1323,12 +1353,14 @@ impl SidebarView {
1323
1353
&self,
1324
1354
mut list: Div,
1325
1355
entry: &SidebarTeam,
1356
hoisted_only: bool,
1326
1357
selected: Option<&Selection>,
1327
1358
cx: &mut Context<Self>,
1328
1359
) -> Div {
1329
1360
let team_id = entry.team.id.clone();
1330
1361
let expanded = team_expanded(&team_id, &self.collapsed_teams);
1331
1362
let name_style = team_name_style(entry, expanded);
1363
let badge = team_badge(entry, expanded);
1332
1364
let toggle_id = team_id.clone();
1333
1365
list = list.child(
1334
1366
h_flex()
@@ -1362,6 +1394,7 @@ impl SidebarView {
1362
1394
.text_color(name_color(name_style))
1363
1395
.child(entry.team.name.clone()),
1364
1396
)
1397
.children(badge.map(mention_badge))
1365
1398
.on_click(cx.listener(move |this, _, _, cx| {
1366
1399
if !this.collapsed_teams.remove(&toggle_id) {
1367
1400
this.collapsed_teams.insert(toggle_id.clone());
@@ -1373,34 +1406,30 @@ impl SidebarView {
1373
1406
if !expanded {
1374
1407
return list;
1375
1408
}
1376
let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
1377
1409
let is_selected =
1378
1410
|channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));
1379
for channel in entry
1380
.channels
1381
.iter()
1382
.filter(|channel| !is_hidden(channel) || is_selected(channel))
1383
{
1411
let revealed = self.revealed_channel_teams.contains(&team_id);
1412
let rows = team_channel_rows(entry, hoisted_only, revealed, is_selected);
1413
for channel in &rows.shown {
1384
1414
list = list.child(self.team_channel_row(
1385
1415
channel,
1386
1416
is_selected(channel),
1387
channel_name_style(channel.unread, !is_hidden(channel), is_selected(channel)),
1417
channel_name_style(
1418
channel.unread,
1419
channel_shown(entry, &channel.id),
1420
is_selected(channel),
1421
),
1388
1422
entry.channel_notifications(&channel.id),
1423
channel_badge(entry, &channel.id),
1389
1424
));
1390
1425
}
1391
let hidden: Vec<&ChannelRecord> = entry
1392
.channels
1393
.iter()
1394
.filter(|channel| is_hidden(channel) && !is_selected(channel))
1395
.collect();
1396
if hidden.is_empty() {
1426
if rows.hidden_count == 0 {
1397
1427
return list;
1398
1428
}
1399
let revealed = self.revealed_channel_teams.contains(&team_id);
1400
1429
let toggle_id = team_id.clone();
1401
1430
list = list.child(self.reveal_row(
1402
1431
SharedString::from(format!("hidden-channels-{team_id}")),
1403
hidden_channels_label(hidden.len()),
1432
hidden_channels_label(rows.hidden_count),
1404
1433
revealed,
1405
1434
40.,
1406
1435
cx.listener(move |this, _, _, cx| {
@@ -1410,15 +1439,14 @@ impl SidebarView {
1410
1439
cx.notify();
1411
1440
}),
1412
1441
));
1413
if revealed {
1414
for channel in hidden {
1415
list = list.child(self.team_channel_row(
1416
channel,
1417
false,
1418
channel_name_style(channel.unread, false, false),
1419
entry.channel_notifications(&channel.id),
1420
));
1421
}
1442
for channel in rows.revealed {
1443
list = list.child(self.team_channel_row(
1444
channel,
1445
false,
1446
channel_name_style(channel.unread, false, false),
1447
entry.channel_notifications(&channel.id),
1448
channel_badge(entry, &channel.id),
1449
));
1422
1450
}
1423
1451
list
1424
1452
}
@@ -1467,6 +1495,7 @@ impl SidebarView {
1467
1495
is_selected: bool,
1468
1496
name_style: NameStyle,
1469
1497
notifications: ChannelNotifications,
1498
badge: Option<MentionBadge>,
1470
1499
) -> impl IntoElement {
1471
1500
let state = self.state.clone();
1472
1501
let menu_state = self.state.clone();
@@ -1507,6 +1536,7 @@ impl SidebarView {
1507
1536
.child(channel.name.clone()),
1508
1537
)
1509
1538
.children(notification_badge(notifications.level))
1539
.children(badge.map(mention_badge))
1510
1540
.on_click(move |_, _, cx| {
1511
1541
let selection = selection.clone();
1512
1542
state.update(cx, |state, cx| state.select(selection, cx));
@@ -1555,14 +1585,19 @@ impl SidebarView {
1555
1585
channel,
1556
1586
is_selected,
1557
1587
entry.channel_notifications(&channel.id),
1588
channel_badge(entry, &channel.id),
1558
1589
));
1559
1590
}
1560
1591
}
1561
1592
list = list.child(self.plain_header(TEAMS_LABEL));
1562
let (shown_teams, hidden_teams): (Vec<&SidebarTeam>, Vec<&SidebarTeam>) =
1563
sidebar.teams.iter().partition(|entry| !entry.hidden);
1564
for entry in shown_teams {
1565
list = self.team_block(list, entry, selected.as_ref(), cx);
1593
let hidden_teams: Vec<&SidebarTeam> =
1594
sidebar.teams.iter().filter(|entry| entry.hidden).collect();
1595
for entry in sidebar
1596
.teams
1597
.iter()
1598
.filter(|entry| !entry.hidden || team_hoisted(entry))
1599
{
1600
list = self.team_block(list, entry, entry.hidden, selected.as_ref(), cx);
1566
1601
}
1567
1602
if !hidden_teams.is_empty() {
1568
1603
let holds_selection = hidden_teams
@@ -1581,7 +1616,7 @@ impl SidebarView {
1581
1616
));
1582
1617
if open {
1583
1618
for entry in hidden_teams {
1584
list = self.team_block(list, entry, selected.as_ref(), cx);
1619
list = self.team_block(list, entry, false, selected.as_ref(), cx);
1585
1620
}
1586
1621
}
1587
1622
}
@@ -1612,6 +1647,18 @@ fn name_color(style: NameStyle) -> Hsla {
1612
1647
}
1613
1648
}
1614
1649
1650
fn mention_badge(badge: MentionBadge) -> AnyElement {
1651
match badge {
1652
MentionBadge::Count(count) => count_badge(count, false).into_any_element(),
1653
MentionBadge::Channel => {
1654
icon(IconName::Hash, MENTION_ICON_SIZE, theme::accent_text()).into_any_element()
1655
}
1656
MentionBadge::Team => {
1657
icon(IconName::Users, MENTION_ICON_SIZE, theme::accent_text()).into_any_element()
1658
}
1659
}
1660
}
1661
1615
1662
fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1616
1663
let name = match level {
1617
1664
ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
@@ -1763,9 +1810,10 @@ impl Render for SidebarView {
1763
1810
.child(self.chat_list_menu_button(cx))
1764
1811
.child(self.new_chat_button(cx)),
1765
1812
),
1766
SidebarTab::Channels | SidebarTab::Calls | SidebarTab::Agents => {
1767
Some(page_header(self.tab.title()))
1813
SidebarTab::Channels => {
1814
Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))
1768
1815
}
1816
SidebarTab::Calls | SidebarTab::Agents => Some(page_header(self.tab.title())),
1769
1817
SidebarTab::Activity | SidebarTab::Saved => None,
1770
1818
};
1771
1819
v_flex()
@@ -30,9 +30,10 @@ use crate::format;30
use crate::local_previews::LocalPreview;30
use crate::local_previews::LocalPreview;31
use crate::notice::truncated;31
use crate::notice::truncated;32
use crate::sidebar_model::{32
use crate::sidebar_model::{33
AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, NameStyle,33
AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, MentionBadge,34
NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,34
NameStyle, NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,35
channel_name_style, older_chats_trigger_resets, step_id, team_name_style, visible_channel_ids,35
channel_badge, channel_name_style, channel_shown, older_chats_trigger_resets, step_id,36
team_badge, team_channel_rows, team_hoisted, team_name_style, visible_channel_ids,36
wants_older_chats,37
wants_older_chats,37
};38
};38
use crate::theme;39
use crate::theme;@@ -54,12 +55,14 @@ const VIEWPORT_MARGIN: f32 = 300.;54
const AVATAR_SIZE: f32 = 36.;55
const AVATAR_SIZE: f32 = 36.;55
const PINNED_LABEL: &str = "Pinned";56
const PINNED_LABEL: &str = "Pinned";56
const TEAMS_LABEL: &str = "Teams";57
const TEAMS_LABEL: &str = "Teams";58
const MARK_ALL_READ_LABEL: &str = "Mark all as read";57
const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";59
const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";58
const TEAM_ROW_HEIGHT: f32 = 40.;60
const TEAM_ROW_HEIGHT: f32 = 40.;59
const REVEAL_ROW_HEIGHT: f32 = 32.;61
const REVEAL_ROW_HEIGHT: f32 = 32.;60
const NEW_CHAT_BUTTON_SIZE: f32 = 32.;62
const NEW_CHAT_BUTTON_SIZE: f32 = 32.;61
const MENU_ICON_SIZE: f32 = 15.;63
const MENU_ICON_SIZE: f32 = 15.;62
const NOTIFICATION_ICON_SIZE: f32 = 13.;64
const NOTIFICATION_ICON_SIZE: f32 = 13.;65
const MENTION_ICON_SIZE: f32 = 15.;63
66
64
#[derive(Debug, Clone, Copy, PartialEq, Eq)]67
#[derive(Debug, Clone, Copy, PartialEq, Eq)]65
pub enum SidebarTab {68
pub enum SidebarTab {@@ -747,6 +750,28 @@ impl SidebarView {747
.dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))750
.dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))748
}751
}749
752
753
fn channel_list_menu_button(&self, cx: &mut Context<Self>) -> impl IntoElement {754
let state = self.state.clone();755
let read_only = self.state.read(cx).mode.read_only;756
Button::new("channel-list-more")757
.icon(IconName::Ellipsis)758
.ghost()759
.size(px(NEW_CHAT_BUTTON_SIZE))760
.rounded(px(8.))761
.tooltip("More options")762
.dropdown_menu(move |menu, _, _| {763
let state = state.clone();764
menu.item(765
PopupMenuItem::new(MARK_ALL_READ_LABEL)766
.icon(menu_icon(IconName::CheckCheck))767
.disabled(read_only)768
.on_click(move |_, _, cx| {769
state.update(cx, |state, cx| state.mark_all_channels_read(cx));770
}),771
)772
})773
}774
750
fn draft_row(&self) -> impl IntoElement {775
fn draft_row(&self) -> impl IntoElement {751
h_flex()776
h_flex()752
.id("new-chat-draft")777
.id("new-chat-draft")@@ -1218,6 +1243,7 @@ impl SidebarView {1218
channel: &ChannelRecord,1243
channel: &ChannelRecord,1219
selected: bool,1244
selected: bool,1220
notifications: ChannelNotifications,1245
notifications: ChannelNotifications,1246
badge: Option<MentionBadge>,1221
) -> AnyElement {1247
) -> AnyElement {1222
let unread = channel.unread;1248
let unread = channel.unread;1223
let name_style = channel_name_style(unread, true, selected);1249
let name_style = channel_name_style(unread, true, selected);@@ -1278,15 +1304,19 @@ impl SidebarView {1278
),1304
),1279
)1305
)1280
.child(1306
.child(1281
h_flex().gap(px(8.)).items_center().child(1307
h_flex()1282
div()1308
.gap(px(8.))1283
.flex_1()1309
.items_center()1284
.min_w_0()1310
.child(1285
.truncate()1311
div()1286
.text_size(px(12.))1312
.flex_1()1287
.text_color(theme::text_muted())1313
.min_w_0()1288
.child(team.name.clone()),1314
.truncate()1289
),1315
.text_size(px(12.))1316
.text_color(theme::text_muted())1317
.child(team.name.clone()),1318
)1319
.children(badge.map(mention_badge)),1290
),1320
),1291
)1321
)1292
.on_click(move |_, _, cx| {1322
.on_click(move |_, _, cx| {@@ -1323,12 +1353,14 @@ impl SidebarView {1323
&self,1353
&self,1324
mut list: Div,1354
mut list: Div,1325
entry: &SidebarTeam,1355
entry: &SidebarTeam,1356
hoisted_only: bool,1326
selected: Option<&Selection>,1357
selected: Option<&Selection>,1327
cx: &mut Context<Self>,1358
cx: &mut Context<Self>,1328
) -> Div {1359
) -> Div {1329
let team_id = entry.team.id.clone();1360
let team_id = entry.team.id.clone();1330
let expanded = team_expanded(&team_id, &self.collapsed_teams);1361
let expanded = team_expanded(&team_id, &self.collapsed_teams);1331
let name_style = team_name_style(entry, expanded);1362
let name_style = team_name_style(entry, expanded);1363
let badge = team_badge(entry, expanded);1332
let toggle_id = team_id.clone();1364
let toggle_id = team_id.clone();1333
list = list.child(1365
list = list.child(1334
h_flex()1366
h_flex()@@ -1362,6 +1394,7 @@ impl SidebarView {1362
.text_color(name_color(name_style))1394
.text_color(name_color(name_style))1363
.child(entry.team.name.clone()),1395
.child(entry.team.name.clone()),1364
)1396
)1397
.children(badge.map(mention_badge))1365
.on_click(cx.listener(move |this, _, _, cx| {1398
.on_click(cx.listener(move |this, _, _, cx| {1366
if !this.collapsed_teams.remove(&toggle_id) {1399
if !this.collapsed_teams.remove(&toggle_id) {1367
this.collapsed_teams.insert(toggle_id.clone());1400
this.collapsed_teams.insert(toggle_id.clone());@@ -1373,34 +1406,30 @@ impl SidebarView {1373
if !expanded {1406
if !expanded {1374
return list;1407
return list;1375
}1408
}1376
let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);1377
let is_selected =1409
let is_selected =1378
|channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));1410
|channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));1379
for channel in entry1411
let revealed = self.revealed_channel_teams.contains(&team_id);1380
.channels1412
let rows = team_channel_rows(entry, hoisted_only, revealed, is_selected);1381
.iter()1413
for channel in &rows.shown {1382
.filter(|channel| !is_hidden(channel) || is_selected(channel))1383
{1384
list = list.child(self.team_channel_row(1414
list = list.child(self.team_channel_row(1385
channel,1415
channel,1386
is_selected(channel),1416
is_selected(channel),1387
channel_name_style(channel.unread, !is_hidden(channel), is_selected(channel)),1417
channel_name_style(1418
channel.unread,1419
channel_shown(entry, &channel.id),1420
is_selected(channel),1421
),1388
entry.channel_notifications(&channel.id),1422
entry.channel_notifications(&channel.id),1423
channel_badge(entry, &channel.id),1389
));1424
));1390
}1425
}1391
let hidden: Vec<&ChannelRecord> = entry1426
if rows.hidden_count == 0 {1392
.channels1393
.iter()1394
.filter(|channel| is_hidden(channel) && !is_selected(channel))1395
.collect();1396
if hidden.is_empty() {1397
return list;1427
return list;1398
}1428
}1399
let revealed = self.revealed_channel_teams.contains(&team_id);1400
let toggle_id = team_id.clone();1429
let toggle_id = team_id.clone();1401
list = list.child(self.reveal_row(1430
list = list.child(self.reveal_row(1402
SharedString::from(format!("hidden-channels-{team_id}")),1431
SharedString::from(format!("hidden-channels-{team_id}")),1403
hidden_channels_label(hidden.len()),1432
hidden_channels_label(rows.hidden_count),1404
revealed,1433
revealed,1405
40.,1434
40.,1406
cx.listener(move |this, _, _, cx| {1435
cx.listener(move |this, _, _, cx| {@@ -1410,15 +1439,14 @@ impl SidebarView {1410
cx.notify();1439
cx.notify();1411
}),1440
}),1412
));1441
));1413
if revealed {1442
for channel in rows.revealed {1414
for channel in hidden {1443
list = list.child(self.team_channel_row(1415
list = list.child(self.team_channel_row(1444
channel,1416
channel,1445
false,1417
false,1446
channel_name_style(channel.unread, false, false),1418
channel_name_style(channel.unread, false, false),1447
entry.channel_notifications(&channel.id),1419
entry.channel_notifications(&channel.id),1448
channel_badge(entry, &channel.id),1420
));1449
));1421
}1422
}1450
}1423
list1451
list1424
}1452
}@@ -1467,6 +1495,7 @@ impl SidebarView {1467
is_selected: bool,1495
is_selected: bool,1468
name_style: NameStyle,1496
name_style: NameStyle,1469
notifications: ChannelNotifications,1497
notifications: ChannelNotifications,1498
badge: Option<MentionBadge>,1470
) -> impl IntoElement {1499
) -> impl IntoElement {1471
let state = self.state.clone();1500
let state = self.state.clone();1472
let menu_state = self.state.clone();1501
let menu_state = self.state.clone();@@ -1507,6 +1536,7 @@ impl SidebarView {1507
.child(channel.name.clone()),1536
.child(channel.name.clone()),1508
)1537
)1509
.children(notification_badge(notifications.level))1538
.children(notification_badge(notifications.level))1539
.children(badge.map(mention_badge))1510
.on_click(move |_, _, cx| {1540
.on_click(move |_, _, cx| {1511
let selection = selection.clone();1541
let selection = selection.clone();1512
state.update(cx, |state, cx| state.select(selection, cx));1542
state.update(cx, |state, cx| state.select(selection, cx));@@ -1555,14 +1585,19 @@ impl SidebarView {1555
channel,1585
channel,1556
is_selected,1586
is_selected,1557
entry.channel_notifications(&channel.id),1587
entry.channel_notifications(&channel.id),1588
channel_badge(entry, &channel.id),1558
));1589
));1559
}1590
}1560
}1591
}1561
list = list.child(self.plain_header(TEAMS_LABEL));1592
list = list.child(self.plain_header(TEAMS_LABEL));1562
let (shown_teams, hidden_teams): (Vec<&SidebarTeam>, Vec<&SidebarTeam>) =1593
let hidden_teams: Vec<&SidebarTeam> =1563
sidebar.teams.iter().partition(|entry| !entry.hidden);1594
sidebar.teams.iter().filter(|entry| entry.hidden).collect();1564
for entry in shown_teams {1595
for entry in sidebar1565
list = self.team_block(list, entry, selected.as_ref(), cx);1596
.teams1597
.iter()1598
.filter(|entry| !entry.hidden || team_hoisted(entry))1599
{1600
list = self.team_block(list, entry, entry.hidden, selected.as_ref(), cx);1566
}1601
}1567
if !hidden_teams.is_empty() {1602
if !hidden_teams.is_empty() {1568
let holds_selection = hidden_teams1603
let holds_selection = hidden_teams@@ -1581,7 +1616,7 @@ impl SidebarView {1581
));1616
));1582
if open {1617
if open {1583
for entry in hidden_teams {1618
for entry in hidden_teams {1584
list = self.team_block(list, entry, selected.as_ref(), cx);1619
list = self.team_block(list, entry, false, selected.as_ref(), cx);1585
}1620
}1586
}1621
}1587
}1622
}@@ -1612,6 +1647,18 @@ fn name_color(style: NameStyle) -> Hsla {1612
}1647
}1613
}1648
}1614
1649
1650
fn mention_badge(badge: MentionBadge) -> AnyElement {1651
match badge {1652
MentionBadge::Count(count) => count_badge(count, false).into_any_element(),1653
MentionBadge::Channel => {1654
icon(IconName::Hash, MENTION_ICON_SIZE, theme::accent_text()).into_any_element()1655
}1656
MentionBadge::Team => {1657
icon(IconName::Users, MENTION_ICON_SIZE, theme::accent_text()).into_any_element()1658
}1659
}1660
}1661
1615
fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {1662
fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {1616
let name = match level {1663
let name = match level {1617
ChannelNotificationLevel::BannerAndFeed => IconName::Bell,1664
ChannelNotificationLevel::BannerAndFeed => IconName::Bell,@@ -1763,9 +1810,10 @@ impl Render for SidebarView {1763
.child(self.chat_list_menu_button(cx))1810
.child(self.chat_list_menu_button(cx))1764
.child(self.new_chat_button(cx)),1811
.child(self.new_chat_button(cx)),1765
),1812
),1766
SidebarTab::Channels | SidebarTab::Calls | SidebarTab::Agents => {1813
SidebarTab::Channels => {1767
Some(page_header(self.tab.title()))1814
Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))1768
}1815
}1816
SidebarTab::Calls | SidebarTab::Agents => Some(page_header(self.tab.title())),1769
SidebarTab::Activity | SidebarTab::Saved => None,1817
SidebarTab::Activity | SidebarTab::Saved => None,1770
};1818
};1771
v_flex()1819
v_flex()@@ -0,0 +1,294 @@
1
use chrono::DateTime;
2
use serde_json::Value;
3
use session::{Request, Session};
4
5
use crate::error::{Error, Result};
6
use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success};
7
use crate::pins::DEFAULT_REGION;
8
9
const PAGE_SIZE: usize = 200;
10
const MAX_PAGES: usize = 3;
11
const MENTION_TYPES: [&str; 2] = ["mention", "mentionInCommunity"];
12
13
/// Who an @mention addressed, as Teams splits them in `ChannelActivitiesPublisher`.
14
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15
pub enum MentionKind {
16
Personal,
17
Channel,
18
Team,
19
}
20
21
#[derive(Debug, Clone, PartialEq, Eq)]
22
pub struct MentionActivity {
23
pub activity_id: String,
24
pub kind: MentionKind,
25
pub source_thread_id: String,
26
pub source_message_id: Option<String>,
27
pub timestamp_ms: i64,
28
pub is_read: bool,
29
}
30
31
pub struct ActivityFeed<T: MessageTransport = SessionMessageTransport> {
32
transport: T,
33
stream_url: String,
34
}
35
36
impl ActivityFeed<SessionMessageTransport> {
37
pub fn new(session: &Session) -> Self {
38
ActivityFeed::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
39
}
40
}
41
42
impl<T: MessageTransport> ActivityFeed<T> {
43
pub fn with_transport(transport: T, region: &str) -> Self {
44
ActivityFeed {
45
transport,
46
stream_url: format!(
47
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/streams/notifications/messages"
48
),
49
}
50
}
51
52
pub fn first_page_url(&self) -> String {
53
format!(
54
"{}?view=msnp24Equivalent|supportsMessageProperties&pageSize={PAGE_SIZE}&startTime=1",
55
self.stream_url
56
)
57
}
58
59
/// Newest activity pages, mentions only.
60
pub async fn mentions(&self) -> Result<Vec<MentionActivity>> {
61
let mut mentions = Vec::new();
62
let mut next_url = Some(self.first_page_url());
63
for _ in 0..MAX_PAGES {
64
let Some(url) = next_url.take() else {
65
break;
66
};
67
let answer = self.transport.send(Request::get(&url)).await?;
68
ensure_success(&answer)?;
69
mentions.extend(parse_mention_page(&answer.body)?);
70
next_url = answer
71
.body
72
.pointer("/_metadata/backwardLink")
73
.and_then(Value::as_str)
74
.filter(|link| !link.is_empty() && *link != url)
75
.map(str::to_owned);
76
}
77
Ok(mentions)
78
}
79
}
80
81
pub fn parse_mention_page(body: &Value) -> Result<Vec<MentionActivity>> {
82
let messages = body
83
.get("messages")
84
.and_then(Value::as_array)
85
.ok_or_else(|| Error::UnexpectedAnswer("activity messages missing".into()))?;
86
Ok(messages.iter().filter_map(mention_activity).collect())
87
}
88
89
fn object_property(properties: &Value, key: &str) -> Option<Value> {
90
match properties.get(key)? {
91
Value::String(text) => serde_json::from_str::<Value>(text)
92
.ok()
93
.filter(Value::is_object),
94
other if other.is_object() => Some(other.clone()),
95
_ => None,
96
}
97
}
98
99
fn text_of(value: &Value) -> Option<String> {
100
match value {
101
Value::String(text) if !text.is_empty() => Some(text.clone()),
102
Value::Number(number) => Some(number.to_string()),
103
_ => None,
104
}
105
}
106
107
fn flag(value: Option<&Value>) -> bool {
108
match value {
109
Some(Value::Bool(flag)) => *flag,
110
Some(Value::String(text)) => text.eq_ignore_ascii_case("true"),
111
_ => false,
112
}
113
}
114
115
fn timestamp_ms(value: &Value) -> Option<i64> {
116
match value {
117
Value::Number(number) => number.as_i64(),
118
Value::String(text) => text.parse::<i64>().ok().or_else(|| {
119
DateTime::parse_from_rfc3339(text)
120
.ok()
121
.map(|time| time.timestamp_millis())
122
}),
123
_ => None,
124
}
125
}
126
127
fn mention_kind(subtype: &str) -> Option<MentionKind> {
128
match subtype.to_ascii_lowercase().as_str() {
129
"person" | "tag" => Some(MentionKind::Personal),
130
"channel" => Some(MentionKind::Channel),
131
"team" => Some(MentionKind::Team),
132
_ => None,
133
}
134
}
135
136
fn mention_activity(message: &Value) -> Option<MentionActivity> {
137
let properties = message.get("properties")?;
138
let activity = object_property(properties, "activity")?;
139
let activity_type = activity.get("activityType")?.as_str()?;
140
if !MENTION_TYPES.contains(&activity_type) {
141
return None;
142
}
143
let kind = mention_kind(activity.get("activitySubtype")?.as_str()?)?;
144
Some(MentionActivity {
145
activity_id: activity
146
.get("activityId")
147
.and_then(text_of)
148
.or_else(|| message.get("id").and_then(text_of))?,
149
kind,
150
source_thread_id: activity.get("sourceThreadId")?.as_str()?.to_owned(),
151
source_message_id: activity.get("sourceMessageId").and_then(text_of),
152
timestamp_ms: activity
153
.get("activityTimestamp")
154
.and_then(timestamp_ms)
155
.unwrap_or(0),
156
is_read: flag(properties.get("isread")),
157
})
158
}
159
160
#[cfg(test)]
161
mod tests {
162
use std::collections::VecDeque;
163
use std::sync::Mutex;
164
165
use serde_json::json;
166
use session::ApiResponse;
167
168
use super::*;
169
170
struct Canned {
171
answers: Mutex<VecDeque<(u16, Value)>>,
172
requests: Mutex<Vec<Request>>,
173
}
174
175
impl MessageTransport for &Canned {
176
async fn send(&self, request: Request) -> Result<ApiResponse> {
177
self.requests.lock().unwrap().push(request);
178
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
179
Ok(ApiResponse {
180
status,
181
body,
182
retry_after: None,
183
})
184
}
185
}
186
187
fn activity_message(id: &str, activity: Value, isread: Option<&str>) -> Value {
188
let mut properties = json!({"activity": activity});
189
if let Some(isread) = isread {
190
properties["isread"] = json!(isread);
191
}
192
json!({"id": id, "messagetype": "Text", "properties": properties})
193
}
194
195
#[test]
196
fn keeps_mentions_and_maps_the_subtypes() {
197
let body = json!({"messages": [
198
activity_message("m1", json!({
199
"activityId": 101, "activityType": "mention", "activitySubtype": "person",
200
"sourceThreadId": "19:a@thread.tacv2", "sourceMessageId": 1791368000000_i64,
201
"activityTimestamp": "2026-10-17T08:00:00.000Z"
202
}), Some("true")),
203
activity_message("m2", json!({
204
"activityType": "mention", "activitySubtype": "tag",
205
"sourceThreadId": "19:a@thread.tacv2", "activityTimestamp": 1791368100000_i64
206
}), None),
207
activity_message("m3", json!({
208
"activityId": "103", "activityType": "mention", "activitySubtype": "channel",
209
"sourceThreadId": "19:b@thread.tacv2"
210
}), Some("false")),
211
activity_message("m4", json!({
212
"activityId": "104", "activityType": "mentionInCommunity", "activitySubtype": "team",
213
"sourceThreadId": "19:b@thread.tacv2"
214
}), None),
215
activity_message("m5", json!({
216
"activityId": "105", "activityType": "reply", "activitySubtype": "person",
217
"sourceThreadId": "19:b@thread.tacv2"
218
}), None),
219
activity_message("m6", json!({
220
"activityId": "106", "activityType": "mention", "activitySubtype": "everyone",
221
"sourceThreadId": "19:b@thread.tacv2"
222
}), None),
223
{"id": "m7", "properties": {}}
224
]});
225
let mentions = parse_mention_page(&body).unwrap();
226
let kinds: Vec<(&str, MentionKind)> = mentions
227
.iter()
228
.map(|mention| (mention.activity_id.as_str(), mention.kind))
229
.collect();
230
assert_eq!(
231
kinds,
232
[
233
("101", MentionKind::Personal),
234
("m2", MentionKind::Personal),
235
("103", MentionKind::Channel),
236
("104", MentionKind::Team),
237
]
238
);
239
assert!(mentions[0].is_read);
240
assert!(!mentions[1].is_read);
241
assert_eq!(
242
mentions[0].source_message_id.as_deref(),
243
Some("1791368000000")
244
);
245
assert_eq!(mentions[0].timestamp_ms, 1792224000000);
246
assert_eq!(mentions[1].timestamp_ms, 1791368100000);
247
assert_eq!(mentions[2].timestamp_ms, 0);
248
}
249
250
#[test]
251
fn reads_the_activity_when_it_is_a_json_string() {
252
let activity = json!({
253
"activityId": "7", "activityType": "mention", "activitySubtype": "person",
254
"sourceThreadId": "19:a@thread.tacv2"
255
});
256
let body = json!({"messages": [
257
activity_message("m1", Value::String(activity.to_string()), Some("True"))
258
]});
259
let mentions = parse_mention_page(&body).unwrap();
260
assert_eq!(mentions.len(), 1);
261
assert!(mentions[0].is_read);
262
}
263
264
#[test]
265
fn an_answer_without_messages_is_unexpected() {
266
assert!(parse_mention_page(&json!({})).is_err());
267
}
268
269
#[tokio::test]
270
async fn pages_backward_through_the_stream() {
271
let transport = Canned {
272
answers: Mutex::new(
273
vec![
274
(
275
200,
276
json!({"messages": [], "_metadata": {"backwardLink": "https://next"}}),
277
),
278
(200, json!({"messages": [], "_metadata": {"backwardLink": ""}})),
279
]
280
.into(),
281
),
282
requests: Mutex::new(Vec::new()),
283
};
284
let feed = ActivityFeed::with_transport(&transport, "emea");
285
assert!(feed.mentions().await.unwrap().is_empty());
286
let requests = transport.requests.lock().unwrap();
287
assert_eq!(
288
requests[0].url,
289
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/streams/notifications/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=200&startTime=1"
290
);
291
assert_eq!(requests[1].url, "https://next");
292
assert_eq!(requests.len(), 2);
293
}
294
}
@@ -0,0 +1,294 @@1
use chrono::DateTime;2
use serde_json::Value;3
use session::{Request, Session};4
5
use crate::error::{Error, Result};6
use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success};7
use crate::pins::DEFAULT_REGION;8
9
const PAGE_SIZE: usize = 200;10
const MAX_PAGES: usize = 3;11
const MENTION_TYPES: [&str; 2] = ["mention", "mentionInCommunity"];12
13
/// Who an @mention addressed, as Teams splits them in `ChannelActivitiesPublisher`.14
#[derive(Debug, Clone, Copy, PartialEq, Eq)]15
pub enum MentionKind {16
Personal,17
Channel,18
Team,19
}20
21
#[derive(Debug, Clone, PartialEq, Eq)]22
pub struct MentionActivity {23
pub activity_id: String,24
pub kind: MentionKind,25
pub source_thread_id: String,26
pub source_message_id: Option<String>,27
pub timestamp_ms: i64,28
pub is_read: bool,29
}30
31
pub struct ActivityFeed<T: MessageTransport = SessionMessageTransport> {32
transport: T,33
stream_url: String,34
}35
36
impl ActivityFeed<SessionMessageTransport> {37
pub fn new(session: &Session) -> Self {38
ActivityFeed::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)39
}40
}41
42
impl<T: MessageTransport> ActivityFeed<T> {43
pub fn with_transport(transport: T, region: &str) -> Self {44
ActivityFeed {45
transport,46
stream_url: format!(47
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/streams/notifications/messages"48
),49
}50
}51
52
pub fn first_page_url(&self) -> String {53
format!(54
"{}?view=msnp24Equivalent|supportsMessageProperties&pageSize={PAGE_SIZE}&startTime=1",55
self.stream_url56
)57
}58
59
/// Newest activity pages, mentions only.60
pub async fn mentions(&self) -> Result<Vec<MentionActivity>> {61
let mut mentions = Vec::new();62
let mut next_url = Some(self.first_page_url());63
for _ in 0..MAX_PAGES {64
let Some(url) = next_url.take() else {65
break;66
};67
let answer = self.transport.send(Request::get(&url)).await?;68
ensure_success(&answer)?;69
mentions.extend(parse_mention_page(&answer.body)?);70
next_url = answer71
.body72
.pointer("/_metadata/backwardLink")73
.and_then(Value::as_str)74
.filter(|link| !link.is_empty() && *link != url)75
.map(str::to_owned);76
}77
Ok(mentions)78
}79
}80
81
pub fn parse_mention_page(body: &Value) -> Result<Vec<MentionActivity>> {82
let messages = body83
.get("messages")84
.and_then(Value::as_array)85
.ok_or_else(|| Error::UnexpectedAnswer("activity messages missing".into()))?;86
Ok(messages.iter().filter_map(mention_activity).collect())87
}88
89
fn object_property(properties: &Value, key: &str) -> Option<Value> {90
match properties.get(key)? {91
Value::String(text) => serde_json::from_str::<Value>(text)92
.ok()93
.filter(Value::is_object),94
other if other.is_object() => Some(other.clone()),95
_ => None,96
}97
}98
99
fn text_of(value: &Value) -> Option<String> {100
match value {101
Value::String(text) if !text.is_empty() => Some(text.clone()),102
Value::Number(number) => Some(number.to_string()),103
_ => None,104
}105
}106
107
fn flag(value: Option<&Value>) -> bool {108
match value {109
Some(Value::Bool(flag)) => *flag,110
Some(Value::String(text)) => text.eq_ignore_ascii_case("true"),111
_ => false,112
}113
}114
115
fn timestamp_ms(value: &Value) -> Option<i64> {116
match value {117
Value::Number(number) => number.as_i64(),118
Value::String(text) => text.parse::<i64>().ok().or_else(|| {119
DateTime::parse_from_rfc3339(text)120
.ok()121
.map(|time| time.timestamp_millis())122
}),123
_ => None,124
}125
}126
127
fn mention_kind(subtype: &str) -> Option<MentionKind> {128
match subtype.to_ascii_lowercase().as_str() {129
"person" | "tag" => Some(MentionKind::Personal),130
"channel" => Some(MentionKind::Channel),131
"team" => Some(MentionKind::Team),132
_ => None,133
}134
}135
136
fn mention_activity(message: &Value) -> Option<MentionActivity> {137
let properties = message.get("properties")?;138
let activity = object_property(properties, "activity")?;139
let activity_type = activity.get("activityType")?.as_str()?;140
if !MENTION_TYPES.contains(&activity_type) {141
return None;142
}143
let kind = mention_kind(activity.get("activitySubtype")?.as_str()?)?;144
Some(MentionActivity {145
activity_id: activity146
.get("activityId")147
.and_then(text_of)148
.or_else(|| message.get("id").and_then(text_of))?,149
kind,150
source_thread_id: activity.get("sourceThreadId")?.as_str()?.to_owned(),151
source_message_id: activity.get("sourceMessageId").and_then(text_of),152
timestamp_ms: activity153
.get("activityTimestamp")154
.and_then(timestamp_ms)155
.unwrap_or(0),156
is_read: flag(properties.get("isread")),157
})158
}159
160
#[cfg(test)]161
mod tests {162
use std::collections::VecDeque;163
use std::sync::Mutex;164
165
use serde_json::json;166
use session::ApiResponse;167
168
use super::*;169
170
struct Canned {171
answers: Mutex<VecDeque<(u16, Value)>>,172
requests: Mutex<Vec<Request>>,173
}174
175
impl MessageTransport for &Canned {176
async fn send(&self, request: Request) -> Result<ApiResponse> {177
self.requests.lock().unwrap().push(request);178
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");179
Ok(ApiResponse {180
status,181
body,182
retry_after: None,183
})184
}185
}186
187
fn activity_message(id: &str, activity: Value, isread: Option<&str>) -> Value {188
let mut properties = json!({"activity": activity});189
if let Some(isread) = isread {190
properties["isread"] = json!(isread);191
}192
json!({"id": id, "messagetype": "Text", "properties": properties})193
}194
195
#[test]196
fn keeps_mentions_and_maps_the_subtypes() {197
let body = json!({"messages": [198
activity_message("m1", json!({199
"activityId": 101, "activityType": "mention", "activitySubtype": "person",200
"sourceThreadId": "19:a@thread.tacv2", "sourceMessageId": 1791368000000_i64,201
"activityTimestamp": "2026-10-17T08:00:00.000Z"202
}), Some("true")),203
activity_message("m2", json!({204
"activityType": "mention", "activitySubtype": "tag",205
"sourceThreadId": "19:a@thread.tacv2", "activityTimestamp": 1791368100000_i64206
}), None),207
activity_message("m3", json!({208
"activityId": "103", "activityType": "mention", "activitySubtype": "channel",209
"sourceThreadId": "19:b@thread.tacv2"210
}), Some("false")),211
activity_message("m4", json!({212
"activityId": "104", "activityType": "mentionInCommunity", "activitySubtype": "team",213
"sourceThreadId": "19:b@thread.tacv2"214
}), None),215
activity_message("m5", json!({216
"activityId": "105", "activityType": "reply", "activitySubtype": "person",217
"sourceThreadId": "19:b@thread.tacv2"218
}), None),219
activity_message("m6", json!({220
"activityId": "106", "activityType": "mention", "activitySubtype": "everyone",221
"sourceThreadId": "19:b@thread.tacv2"222
}), None),223
{"id": "m7", "properties": {}}224
]});225
let mentions = parse_mention_page(&body).unwrap();226
let kinds: Vec<(&str, MentionKind)> = mentions227
.iter()228
.map(|mention| (mention.activity_id.as_str(), mention.kind))229
.collect();230
assert_eq!(231
kinds,232
[233
("101", MentionKind::Personal),234
("m2", MentionKind::Personal),235
("103", MentionKind::Channel),236
("104", MentionKind::Team),237
]238
);239
assert!(mentions[0].is_read);240
assert!(!mentions[1].is_read);241
assert_eq!(242
mentions[0].source_message_id.as_deref(),243
Some("1791368000000")244
);245
assert_eq!(mentions[0].timestamp_ms, 1792224000000);246
assert_eq!(mentions[1].timestamp_ms, 1791368100000);247
assert_eq!(mentions[2].timestamp_ms, 0);248
}249
250
#[test]251
fn reads_the_activity_when_it_is_a_json_string() {252
let activity = json!({253
"activityId": "7", "activityType": "mention", "activitySubtype": "person",254
"sourceThreadId": "19:a@thread.tacv2"255
});256
let body = json!({"messages": [257
activity_message("m1", Value::String(activity.to_string()), Some("True"))258
]});259
let mentions = parse_mention_page(&body).unwrap();260
assert_eq!(mentions.len(), 1);261
assert!(mentions[0].is_read);262
}263
264
#[test]265
fn an_answer_without_messages_is_unexpected() {266
assert!(parse_mention_page(&json!({})).is_err());267
}268
269
#[tokio::test]270
async fn pages_backward_through_the_stream() {271
let transport = Canned {272
answers: Mutex::new(273
vec![274
(275
200,276
json!({"messages": [], "_metadata": {"backwardLink": "https://next"}}),277
),278
(200, json!({"messages": [], "_metadata": {"backwardLink": ""}})),279
]280
.into(),281
),282
requests: Mutex::new(Vec::new()),283
};284
let feed = ActivityFeed::with_transport(&transport, "emea");285
assert!(feed.mentions().await.unwrap().is_empty());286
let requests = transport.requests.lock().unwrap();287
assert_eq!(288
requests[0].url,289
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/streams/notifications/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=200&startTime=1"290
);291
assert_eq!(requests[1].url, "https://next");292
assert_eq!(requests.len(), 2);293
}294
}@@ -1,3 +1,4 @@
1
pub mod activity_mentions;
1
2
pub mod bot_profiles;
2
3
pub mod calendar;
3
4
pub mod calllog;
@@ -32,6 +33,7 @@ pub mod transcripts;
32
33
pub mod translate;
33
34
pub mod window;
34
35
36
pub use activity_mentions::{ActivityFeed, MentionActivity, MentionKind};
35
37
pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
36
38
pub use calendar::{
37
39
Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
@@ -81,7 +83,10 @@ pub use recap::{
81
83
pub use receipts::{MemberHorizon, Receipts};
82
84
pub use recording_policy::{RecordingPolicy, parse_recording_policy};
83
85
pub use saved::SavedMessage;
84
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
86
pub use settings::{
87
AppConsumptionHorizon, ChatSection, ChatSectionSettings, UserSettings,
88
parse_app_consumption_horizon,
89
};
85
90
pub use substrate_search::{
86
91
QueryRequest, QueryResults, QueryScope, SearchIdentity, SearchSession, SubstrateSearch,
87
92
Suggestions,
@@ -1,3 +1,4 @@1
pub mod activity_mentions;1
pub mod bot_profiles;2
pub mod bot_profiles;2
pub mod calendar;3
pub mod calendar;3
pub mod calllog;4
pub mod calllog;@@ -32,6 +33,7 @@ pub mod transcripts;32
pub mod translate;33
pub mod translate;33
pub mod window;34
pub mod window;34
35
36
pub use activity_mentions::{ActivityFeed, MentionActivity, MentionKind};35
pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};37
pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};36
pub use calendar::{38
pub use calendar::{37
Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,39
Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,@@ -81,7 +83,10 @@ pub use recap::{81
pub use receipts::{MemberHorizon, Receipts};83
pub use receipts::{MemberHorizon, Receipts};82
pub use recording_policy::{RecordingPolicy, parse_recording_policy};84
pub use recording_policy::{RecordingPolicy, parse_recording_policy};83
pub use saved::SavedMessage;85
pub use saved::SavedMessage;84
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};86
pub use settings::{87
AppConsumptionHorizon, ChatSection, ChatSectionSettings, UserSettings,88
parse_app_consumption_horizon,89
};85
pub use substrate_search::{90
pub use substrate_search::{86
QueryRequest, QueryResults, QueryScope, SearchIdentity, SearchSession, SubstrateSearch,91
QueryRequest, QueryResults, QueryScope, SearchIdentity, SearchSession, SubstrateSearch,87
Suggestions,92
Suggestions,@@ -2,6 +2,7 @@ mod channels;
2
2
mod chats;
3
3
mod folders;
4
4
mod pinbar;
5
mod posts;
5
6
mod state;
6
7
mod teams;
7
8
mod transport;
@@ -10,6 +11,7 @@ use session::Session;
10
11
11
12
pub use folders::{Folder, FolderKind, Folders};
12
13
pub use pinbar::PinnedMessage;
14
pub use posts::{PINNED_POSTS_PAGE_SIZE, PinnedPostsPage, parse_pinned_posts};
13
15
pub use state::{PinnedChannels, PinnedChats};
14
16
pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};
15
17
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};
@@ -2,6 +2,7 @@ mod channels;2
mod chats;2
mod chats;3
mod folders;3
mod folders;4
mod pinbar;4
mod pinbar;5
mod posts;5
mod state;6
mod state;6
mod teams;7
mod teams;7
mod transport;8
mod transport;@@ -10,6 +11,7 @@ use session::Session;10
11
11
pub use folders::{Folder, FolderKind, Folders};12
pub use folders::{Folder, FolderKind, Folders};12
pub use pinbar::PinnedMessage;13
pub use pinbar::PinnedMessage;14
pub use posts::{PINNED_POSTS_PAGE_SIZE, PinnedPostsPage, parse_pinned_posts};13
pub use state::{PinnedChannels, PinnedChats};15
pub use state::{PinnedChannels, PinnedChats};14
pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};16
pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};15
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};17
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};@@ -0,0 +1,291 @@
1
use chrono::{DateTime, Utc};
2
use serde_json::Value;
3
use session::{Method, Request};
4
5
use super::Pins;
6
use super::chats::{api_error, ensure_success};
7
use super::pinbar::PinnedMessage;
8
use super::transport::CsaTransport;
9
use crate::error::{Error, Result};
10
use crate::messages::encode;
11
12
pub const PINNED_POSTS_PAGE_SIZE: usize = 20;
13
const MAX_PINNED_POST_PAGES: usize = 10;
14
const CONTINUATION_HEADER: &str = "x-ms-continuation";
15
16
#[derive(Debug, Clone, PartialEq, Eq)]
17
pub struct PinnedPostsPage {
18
pub pins: Vec<PinnedMessage>,
19
pub continuation_token: Option<String>,
20
}
21
22
fn pinned_time(message: &Value) -> Option<DateTime<Utc>> {
23
let pinned = message.pointer("/properties/pinned")?;
24
let parsed;
25
let pinned = match pinned {
26
Value::String(text) => {
27
parsed = serde_json::from_str::<Value>(text).ok()?;
28
&parsed
29
}
30
other => other,
31
};
32
let millis = match pinned.get("pinnedTime")? {
33
Value::String(text) => text.parse::<i64>().ok()?,
34
other => other.as_i64()?,
35
};
36
DateTime::from_timestamp_millis(millis)
37
}
38
39
fn pinned_post(message: &Value) -> Option<PinnedMessage> {
40
let message_id = match message.get("id")? {
41
Value::String(text) => text.clone(),
42
Value::Number(number) => number.to_string(),
43
_ => return None,
44
};
45
Some(PinnedMessage {
46
message_id,
47
pinned_at: pinned_time(message),
48
parent_id: None,
49
})
50
}
51
52
pub fn parse_pinned_posts(body: &Value) -> Result<PinnedPostsPage> {
53
let messages = body
54
.get("messages")
55
.and_then(Value::as_array)
56
.ok_or_else(|| Error::UnexpectedAnswer("pinned posts messages missing".into()))?;
57
Ok(PinnedPostsPage {
58
pins: messages.iter().filter_map(pinned_post).collect(),
59
continuation_token: body
60
.get("continuationToken")
61
.and_then(Value::as_str)
62
.filter(|token| !token.is_empty())
63
.map(str::to_owned),
64
})
65
}
66
67
impl<T: CsaTransport> Pins<T> {
68
pub fn channel_url(&self, team_thread_id: &str, channel_id: &str) -> String {
69
format!(
70
"{}/teams/{}/channels/{}",
71
self.api_url,
72
encode(team_thread_id),
73
encode(channel_id)
74
)
75
}
76
77
pub fn pinned_posts_request(
78
&self,
79
team_thread_id: &str,
80
channel_id: &str,
81
continuation_token: Option<&str>,
82
) -> Request {
83
let mut request = Request::get(format!(
84
"{}/pins?pageSize={PINNED_POSTS_PAGE_SIZE}",
85
self.channel_url(team_thread_id, channel_id)
86
));
87
if let Some(token) = continuation_token {
88
request
89
.headers
90
.push((CONTINUATION_HEADER.to_owned(), token.to_owned()));
91
}
92
request
93
}
94
95
pub fn post_pin_request(
96
&self,
97
team_thread_id: &str,
98
channel_id: &str,
99
post_id: &str,
100
pinned: bool,
101
) -> Request {
102
let url = format!(
103
"{}/posts/{post_id}/pin",
104
self.channel_url(team_thread_id, channel_id)
105
);
106
if pinned {
107
Request {
108
method: Method::Post,
109
..Request::get(url)
110
}
111
} else {
112
Request::delete(url)
113
}
114
}
115
116
/// Pinned root posts in service order; only roots can be pinned while `enablePinMessageV2` is off.
117
pub async fn channel_pinned_posts(
118
&self,
119
team_thread_id: &str,
120
channel_id: &str,
121
) -> Result<Vec<PinnedMessage>> {
122
let mut pins = Vec::new();
123
let mut continuation_token: Option<String> = None;
124
for _ in 0..MAX_PINNED_POST_PAGES {
125
let request =
126
self.pinned_posts_request(team_thread_id, channel_id, continuation_token.as_deref());
127
let answer = self.transport.send(request).await?;
128
ensure_success(&answer)?;
129
let page = parse_pinned_posts(&answer.body)?;
130
pins.extend(page.pins);
131
match page.continuation_token {
132
Some(token) if Some(&token) != continuation_token.as_ref() => {
133
continuation_token = Some(token)
134
}
135
_ => break,
136
}
137
}
138
Ok(pins)
139
}
140
141
pub async fn set_post_pinned(
142
&self,
143
team_thread_id: &str,
144
channel_id: &str,
145
post_id: &str,
146
pinned: bool,
147
) -> Result<()> {
148
let request = self.post_pin_request(team_thread_id, channel_id, post_id, pinned);
149
let answer = self.transport.send(request).await?;
150
if answer.is_success() {
151
Ok(())
152
} else {
153
Err(api_error(&answer))
154
}
155
}
156
}
157
158
#[cfg(test)]
159
mod tests {
160
use std::collections::VecDeque;
161
use std::sync::Mutex;
162
163
use serde_json::json;
164
use session::ApiResponse;
165
166
use super::*;
167
168
const TEAM: &str = "19:team@thread.tacv2";
169
const CHANNEL: &str = "19:channel@thread.tacv2";
170
const CHANNEL_URL: &str = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/19%3Ateam%40thread.tacv2/channels/19%3Achannel%40thread.tacv2";
171
172
struct Canned {
173
answers: Mutex<VecDeque<(u16, Value)>>,
174
requests: Mutex<Vec<Request>>,
175
}
176
177
impl CsaTransport for Canned {
178
async fn send(&self, request: Request) -> Result<ApiResponse> {
179
self.requests.lock().unwrap().push(request);
180
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
181
Ok(ApiResponse {
182
status,
183
body,
184
retry_after: None,
185
})
186
}
187
}
188
189
fn canned(answers: Vec<(u16, Value)>) -> Pins<Canned> {
190
Pins::with_transport(
191
Canned {
192
answers: Mutex::new(answers.into()),
193
requests: Mutex::new(Vec::new()),
194
},
195
"emea",
196
)
197
}
198
199
#[test]
200
fn parses_ids_pinned_time_and_the_continuation() {
201
let body = json!({
202
"messages": [
203
{"id": "1791368000000", "parentMessageId": "1791368000000",
204
"properties": {"pinned": "{\"pinnedTime\":1791368500000}"}},
205
{"id": 1791367000000_i64, "properties": {"pinned": {"pinnedTime": "1791367500000"}}},
206
{"id": "1791366000000"},
207
{"content": "no id"}
208
],
209
"continuationToken": "next-page"
210
});
211
let page = parse_pinned_posts(&body).unwrap();
212
let ids: Vec<&str> = page.pins.iter().map(|pin| pin.message_id.as_str()).collect();
213
assert_eq!(ids, ["1791368000000", "1791367000000", "1791366000000"]);
214
assert_eq!(
215
page.pins[0].pinned_at.map(|time| time.timestamp_millis()),
216
Some(1791368500000)
217
);
218
assert_eq!(
219
page.pins[1].pinned_at.map(|time| time.timestamp_millis()),
220
Some(1791367500000)
221
);
222
assert_eq!(page.pins[2].pinned_at, None);
223
assert_eq!(page.continuation_token.as_deref(), Some("next-page"));
224
}
225
226
#[test]
227
fn an_answer_without_messages_is_unexpected() {
228
assert!(matches!(
229
parse_pinned_posts(&json!({"continuationToken": "x"})),
230
Err(Error::UnexpectedAnswer(_))
231
));
232
}
233
234
#[test]
235
fn pin_and_unpin_hit_the_post_pin_url_without_a_body() {
236
let pins = canned(Vec::new());
237
let pin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", true);
238
assert_eq!(pin.method, Method::Post);
239
assert_eq!(pin.url, format!("{CHANNEL_URL}/posts/1791368000000/pin"));
240
assert_eq!(pin.body, None);
241
let unpin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", false);
242
assert_eq!(unpin.method, Method::Delete);
243
assert_eq!(unpin.url, pin.url);
244
assert_eq!(unpin.body, None);
245
}
246
247
#[tokio::test]
248
async fn pinned_posts_follow_the_continuation_header() {
249
let pins = canned(vec![
250
(
251
200,
252
json!({"messages": [{"id": "3"}, {"id": "2"}], "continuationToken": "page-2"}),
253
),
254
(200, json!({"messages": [{"id": "1"}]})),
255
]);
256
let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();
257
let ids: Vec<&str> = found.iter().map(|pin| pin.message_id.as_str()).collect();
258
assert_eq!(ids, ["3", "2", "1"]);
259
let requests = pins.transport.requests.lock().unwrap();
260
assert_eq!(requests[0].url, format!("{CHANNEL_URL}/pins?pageSize=20"));
261
assert!(requests[0].headers.is_empty());
262
assert_eq!(
263
requests[1].headers,
264
[("x-ms-continuation".to_owned(), "page-2".to_owned())]
265
);
266
}
267
268
#[tokio::test]
269
async fn a_repeated_continuation_stops_paging() {
270
let pins = canned(vec![
271
(200, json!({"messages": [{"id": "2"}], "continuationToken": "same"})),
272
(200, json!({"messages": [{"id": "1"}], "continuationToken": "same"})),
273
]);
274
let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();
275
assert_eq!(found.len(), 2);
276
assert_eq!(pins.transport.requests.lock().unwrap().len(), 2);
277
}
278
279
#[tokio::test]
280
async fn failures_are_errors() {
281
let pins = canned(vec![(403, json!({})), (412, json!({}))]);
282
assert!(pins.channel_pinned_posts(TEAM, CHANNEL).await.is_err());
283
assert!(pins.set_post_pinned(TEAM, CHANNEL, "1", true).await.is_err());
284
}
285
286
#[tokio::test]
287
async fn unpin_accepts_no_content() {
288
let pins = canned(vec![(204, Value::Null)]);
289
pins.set_post_pinned(TEAM, CHANNEL, "1", false).await.unwrap();
290
}
291
}
@@ -0,0 +1,291 @@1
use chrono::{DateTime, Utc};2
use serde_json::Value;3
use session::{Method, Request};4
5
use super::Pins;6
use super::chats::{api_error, ensure_success};7
use super::pinbar::PinnedMessage;8
use super::transport::CsaTransport;9
use crate::error::{Error, Result};10
use crate::messages::encode;11
12
pub const PINNED_POSTS_PAGE_SIZE: usize = 20;13
const MAX_PINNED_POST_PAGES: usize = 10;14
const CONTINUATION_HEADER: &str = "x-ms-continuation";15
16
#[derive(Debug, Clone, PartialEq, Eq)]17
pub struct PinnedPostsPage {18
pub pins: Vec<PinnedMessage>,19
pub continuation_token: Option<String>,20
}21
22
fn pinned_time(message: &Value) -> Option<DateTime<Utc>> {23
let pinned = message.pointer("/properties/pinned")?;24
let parsed;25
let pinned = match pinned {26
Value::String(text) => {27
parsed = serde_json::from_str::<Value>(text).ok()?;28
&parsed29
}30
other => other,31
};32
let millis = match pinned.get("pinnedTime")? {33
Value::String(text) => text.parse::<i64>().ok()?,34
other => other.as_i64()?,35
};36
DateTime::from_timestamp_millis(millis)37
}38
39
fn pinned_post(message: &Value) -> Option<PinnedMessage> {40
let message_id = match message.get("id")? {41
Value::String(text) => text.clone(),42
Value::Number(number) => number.to_string(),43
_ => return None,44
};45
Some(PinnedMessage {46
message_id,47
pinned_at: pinned_time(message),48
parent_id: None,49
})50
}51
52
pub fn parse_pinned_posts(body: &Value) -> Result<PinnedPostsPage> {53
let messages = body54
.get("messages")55
.and_then(Value::as_array)56
.ok_or_else(|| Error::UnexpectedAnswer("pinned posts messages missing".into()))?;57
Ok(PinnedPostsPage {58
pins: messages.iter().filter_map(pinned_post).collect(),59
continuation_token: body60
.get("continuationToken")61
.and_then(Value::as_str)62
.filter(|token| !token.is_empty())63
.map(str::to_owned),64
})65
}66
67
impl<T: CsaTransport> Pins<T> {68
pub fn channel_url(&self, team_thread_id: &str, channel_id: &str) -> String {69
format!(70
"{}/teams/{}/channels/{}",71
self.api_url,72
encode(team_thread_id),73
encode(channel_id)74
)75
}76
77
pub fn pinned_posts_request(78
&self,79
team_thread_id: &str,80
channel_id: &str,81
continuation_token: Option<&str>,82
) -> Request {83
let mut request = Request::get(format!(84
"{}/pins?pageSize={PINNED_POSTS_PAGE_SIZE}",85
self.channel_url(team_thread_id, channel_id)86
));87
if let Some(token) = continuation_token {88
request89
.headers90
.push((CONTINUATION_HEADER.to_owned(), token.to_owned()));91
}92
request93
}94
95
pub fn post_pin_request(96
&self,97
team_thread_id: &str,98
channel_id: &str,99
post_id: &str,100
pinned: bool,101
) -> Request {102
let url = format!(103
"{}/posts/{post_id}/pin",104
self.channel_url(team_thread_id, channel_id)105
);106
if pinned {107
Request {108
method: Method::Post,109
..Request::get(url)110
}111
} else {112
Request::delete(url)113
}114
}115
116
/// Pinned root posts in service order; only roots can be pinned while `enablePinMessageV2` is off.117
pub async fn channel_pinned_posts(118
&self,119
team_thread_id: &str,120
channel_id: &str,121
) -> Result<Vec<PinnedMessage>> {122
let mut pins = Vec::new();123
let mut continuation_token: Option<String> = None;124
for _ in 0..MAX_PINNED_POST_PAGES {125
let request =126
self.pinned_posts_request(team_thread_id, channel_id, continuation_token.as_deref());127
let answer = self.transport.send(request).await?;128
ensure_success(&answer)?;129
let page = parse_pinned_posts(&answer.body)?;130
pins.extend(page.pins);131
match page.continuation_token {132
Some(token) if Some(&token) != continuation_token.as_ref() => {133
continuation_token = Some(token)134
}135
_ => break,136
}137
}138
Ok(pins)139
}140
141
pub async fn set_post_pinned(142
&self,143
team_thread_id: &str,144
channel_id: &str,145
post_id: &str,146
pinned: bool,147
) -> Result<()> {148
let request = self.post_pin_request(team_thread_id, channel_id, post_id, pinned);149
let answer = self.transport.send(request).await?;150
if answer.is_success() {151
Ok(())152
} else {153
Err(api_error(&answer))154
}155
}156
}157
158
#[cfg(test)]159
mod tests {160
use std::collections::VecDeque;161
use std::sync::Mutex;162
163
use serde_json::json;164
use session::ApiResponse;165
166
use super::*;167
168
const TEAM: &str = "19:team@thread.tacv2";169
const CHANNEL: &str = "19:channel@thread.tacv2";170
const CHANNEL_URL: &str = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/19%3Ateam%40thread.tacv2/channels/19%3Achannel%40thread.tacv2";171
172
struct Canned {173
answers: Mutex<VecDeque<(u16, Value)>>,174
requests: Mutex<Vec<Request>>,175
}176
177
impl CsaTransport for Canned {178
async fn send(&self, request: Request) -> Result<ApiResponse> {179
self.requests.lock().unwrap().push(request);180
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");181
Ok(ApiResponse {182
status,183
body,184
retry_after: None,185
})186
}187
}188
189
fn canned(answers: Vec<(u16, Value)>) -> Pins<Canned> {190
Pins::with_transport(191
Canned {192
answers: Mutex::new(answers.into()),193
requests: Mutex::new(Vec::new()),194
},195
"emea",196
)197
}198
199
#[test]200
fn parses_ids_pinned_time_and_the_continuation() {201
let body = json!({202
"messages": [203
{"id": "1791368000000", "parentMessageId": "1791368000000",204
"properties": {"pinned": "{\"pinnedTime\":1791368500000}"}},205
{"id": 1791367000000_i64, "properties": {"pinned": {"pinnedTime": "1791367500000"}}},206
{"id": "1791366000000"},207
{"content": "no id"}208
],209
"continuationToken": "next-page"210
});211
let page = parse_pinned_posts(&body).unwrap();212
let ids: Vec<&str> = page.pins.iter().map(|pin| pin.message_id.as_str()).collect();213
assert_eq!(ids, ["1791368000000", "1791367000000", "1791366000000"]);214
assert_eq!(215
page.pins[0].pinned_at.map(|time| time.timestamp_millis()),216
Some(1791368500000)217
);218
assert_eq!(219
page.pins[1].pinned_at.map(|time| time.timestamp_millis()),220
Some(1791367500000)221
);222
assert_eq!(page.pins[2].pinned_at, None);223
assert_eq!(page.continuation_token.as_deref(), Some("next-page"));224
}225
226
#[test]227
fn an_answer_without_messages_is_unexpected() {228
assert!(matches!(229
parse_pinned_posts(&json!({"continuationToken": "x"})),230
Err(Error::UnexpectedAnswer(_))231
));232
}233
234
#[test]235
fn pin_and_unpin_hit_the_post_pin_url_without_a_body() {236
let pins = canned(Vec::new());237
let pin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", true);238
assert_eq!(pin.method, Method::Post);239
assert_eq!(pin.url, format!("{CHANNEL_URL}/posts/1791368000000/pin"));240
assert_eq!(pin.body, None);241
let unpin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", false);242
assert_eq!(unpin.method, Method::Delete);243
assert_eq!(unpin.url, pin.url);244
assert_eq!(unpin.body, None);245
}246
247
#[tokio::test]248
async fn pinned_posts_follow_the_continuation_header() {249
let pins = canned(vec![250
(251
200,252
json!({"messages": [{"id": "3"}, {"id": "2"}], "continuationToken": "page-2"}),253
),254
(200, json!({"messages": [{"id": "1"}]})),255
]);256
let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();257
let ids: Vec<&str> = found.iter().map(|pin| pin.message_id.as_str()).collect();258
assert_eq!(ids, ["3", "2", "1"]);259
let requests = pins.transport.requests.lock().unwrap();260
assert_eq!(requests[0].url, format!("{CHANNEL_URL}/pins?pageSize=20"));261
assert!(requests[0].headers.is_empty());262
assert_eq!(263
requests[1].headers,264
[("x-ms-continuation".to_owned(), "page-2".to_owned())]265
);266
}267
268
#[tokio::test]269
async fn a_repeated_continuation_stops_paging() {270
let pins = canned(vec![271
(200, json!({"messages": [{"id": "2"}], "continuationToken": "same"})),272
(200, json!({"messages": [{"id": "1"}], "continuationToken": "same"})),273
]);274
let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();275
assert_eq!(found.len(), 2);276
assert_eq!(pins.transport.requests.lock().unwrap().len(), 2);277
}278
279
#[tokio::test]280
async fn failures_are_errors() {281
let pins = canned(vec![(403, json!({})), (412, json!({}))]);282
assert!(pins.channel_pinned_posts(TEAM, CHANNEL).await.is_err());283
assert!(pins.set_post_pinned(TEAM, CHANNEL, "1", true).await.is_err());284
}285
286
#[tokio::test]287
async fn unpin_accepts_no_content() {288
let pins = canned(vec![(204, Value::Null)]);289
pins.set_post_pinned(TEAM, CHANNEL, "1", false).await.unwrap();290
}291
}@@ -8,6 +8,7 @@ pub const PROPERTY_NAME: &str = "consumptionhorizon";
8
8
pub struct ReadHorizon {
9
9
pub consumed_until_ms: i64,
10
10
pub bookmark_ms: i64,
11
pub bookmark_timestamp_ms: i64,
11
12
pub bookmark_message_set: bool,
12
13
pub last_message_ms: i64,
13
14
pub last_message_from: Option<String>,
@@ -22,6 +23,7 @@ impl ReadHorizon {
22
23
ReadHorizon {
23
24
consumed_until_ms: horizon.arrival_ms,
24
25
bookmark_ms: bookmark.arrival_ms,
26
bookmark_timestamp_ms: bookmark.timestamp_ms,
25
27
bookmark_message_set: bookmark.message_set,
26
28
last_message_ms: last_message_ms(conversation),
27
29
last_message_from: last_message["from"]
@@ -33,10 +35,19 @@ impl ReadHorizon {
33
35
}
34
36
35
37
pub fn is_unread(&self, my_user_id: &str) -> bool {
36
if self.bookmark_ms != 0 && self.bookmark_message_set {
38
self.is_unread_after(my_user_id, 0)
39
}
40
41
/// `app_horizon_ms` is the `appConsumptionHorizon` entry of the conversation's app ("Mark all as read").
42
pub fn is_unread_after(&self, my_user_id: &str, app_horizon_ms: i64) -> bool {
43
let app_horizon_set = app_horizon_ms > 0;
44
let bookmark_cleared = app_horizon_set && app_horizon_ms >= self.bookmark_timestamp_ms;
45
let bookmark_ms = if bookmark_cleared { 0 } else { self.bookmark_ms };
46
if bookmark_ms != 0 && self.bookmark_message_set {
37
47
return true;
38
48
}
39
let unread = self.bookmark_ms != 0 || self.last_message_ms > self.consumed_until_ms;
49
let consumed_until_ms = self.consumed_until_ms.max(app_horizon_ms);
50
let unread = bookmark_ms != 0 || self.last_message_ms > consumed_until_ms;
40
51
let from_me = self
41
52
.last_message_from
42
53
.as_deref()
@@ -62,6 +73,7 @@ pub fn read_up_to(last_message_at: DateTime<Utc>, now: DateTime<Utc>) -> String
62
73
63
74
struct ParsedHorizon {
64
75
arrival_ms: i64,
76
timestamp_ms: i64,
65
77
message_set: bool,
66
78
}
67
79
@@ -70,6 +82,7 @@ fn parse_horizon(text: Option<&str>) -> ParsedHorizon {
70
82
let number = |part: &str| part.trim().parse::<i64>().ok();
71
83
let unset = ParsedHorizon {
72
84
arrival_ms: 0,
85
timestamp_ms: 0,
73
86
message_set: false,
74
87
};
75
88
let [arrival, timestamp, message_id] = parts.as_slice() else {
@@ -77,8 +90,9 @@ fn parse_horizon(text: Option<&str>) -> ParsedHorizon {
77
90
};
78
91
let message_id = message_id.trim();
79
92
match (number(arrival), number(timestamp)) {
80
(Some(arrival_ms), Some(_)) if !message_id.is_empty() => ParsedHorizon {
93
(Some(arrival_ms), Some(timestamp_ms)) if !message_id.is_empty() => ParsedHorizon {
81
94
arrival_ms,
95
timestamp_ms,
82
96
message_set: message_id != "0",
83
97
},
84
98
_ => unset,
@@ -192,6 +206,31 @@ mod tests {
192
206
assert!(unread(&value));
193
207
}
194
208
209
#[test]
210
fn app_horizon_reads_everything_that_arrived_before_it() {
211
let value = conversation(
212
Some("1791884440747;1791885752824;1"),
213
None,
214
Some(("2026-10-16T09:42:25.6780000Z", "8:orgid:other")),
215
);
216
let horizon = ReadHorizon::from_conversation(&value);
217
assert!(horizon.is_unread_after(ME, 0));
218
assert!(horizon.is_unread_after(ME, horizon.last_message_ms - 1));
219
assert!(!horizon.is_unread_after(ME, horizon.last_message_ms));
220
}
221
222
#[test]
223
fn app_horizon_clears_an_older_bookmark_only() {
224
let value = conversation(
225
Some("1792171970947;1792171971513;1"),
226
Some("1792171970000;1792171971513;42"),
227
Some(("2026-10-16T17:32:50.9470000Z", "8:orgid:other")),
228
);
229
let horizon = ReadHorizon::from_conversation(&value);
230
assert!(horizon.is_unread_after(ME, 1792171971512));
231
assert!(!horizon.is_unread_after(ME, 1792171971513));
232
}
233
195
234
#[test]
196
235
fn read_value_carries_the_last_arrival_and_now() {
197
236
let last = DateTime::from_timestamp_millis(1792182658901).unwrap();
@@ -8,6 +8,7 @@ pub const PROPERTY_NAME: &str = "consumptionhorizon";8
pub struct ReadHorizon {8
pub struct ReadHorizon {9
pub consumed_until_ms: i64,9
pub consumed_until_ms: i64,10
pub bookmark_ms: i64,10
pub bookmark_ms: i64,11
pub bookmark_timestamp_ms: i64,11
pub bookmark_message_set: bool,12
pub bookmark_message_set: bool,12
pub last_message_ms: i64,13
pub last_message_ms: i64,13
pub last_message_from: Option<String>,14
pub last_message_from: Option<String>,@@ -22,6 +23,7 @@ impl ReadHorizon {22
ReadHorizon {23
ReadHorizon {23
consumed_until_ms: horizon.arrival_ms,24
consumed_until_ms: horizon.arrival_ms,24
bookmark_ms: bookmark.arrival_ms,25
bookmark_ms: bookmark.arrival_ms,26
bookmark_timestamp_ms: bookmark.timestamp_ms,25
bookmark_message_set: bookmark.message_set,27
bookmark_message_set: bookmark.message_set,26
last_message_ms: last_message_ms(conversation),28
last_message_ms: last_message_ms(conversation),27
last_message_from: last_message["from"]29
last_message_from: last_message["from"]@@ -33,10 +35,19 @@ impl ReadHorizon {33
}35
}34
36
35
pub fn is_unread(&self, my_user_id: &str) -> bool {37
pub fn is_unread(&self, my_user_id: &str) -> bool {36
if self.bookmark_ms != 0 && self.bookmark_message_set {38
self.is_unread_after(my_user_id, 0)39
}40
41
/// `app_horizon_ms` is the `appConsumptionHorizon` entry of the conversation's app ("Mark all as read").42
pub fn is_unread_after(&self, my_user_id: &str, app_horizon_ms: i64) -> bool {43
let app_horizon_set = app_horizon_ms > 0;44
let bookmark_cleared = app_horizon_set && app_horizon_ms >= self.bookmark_timestamp_ms;45
let bookmark_ms = if bookmark_cleared { 0 } else { self.bookmark_ms };46
if bookmark_ms != 0 && self.bookmark_message_set {37
return true;47
return true;38
}48
}39
let unread = self.bookmark_ms != 0 || self.last_message_ms > self.consumed_until_ms;49
let consumed_until_ms = self.consumed_until_ms.max(app_horizon_ms);50
let unread = bookmark_ms != 0 || self.last_message_ms > consumed_until_ms;40
let from_me = self51
let from_me = self41
.last_message_from52
.last_message_from42
.as_deref()53
.as_deref()@@ -62,6 +73,7 @@ pub fn read_up_to(last_message_at: DateTime<Utc>, now: DateTime<Utc>) -> String62
73
63
struct ParsedHorizon {74
struct ParsedHorizon {64
arrival_ms: i64,75
arrival_ms: i64,76
timestamp_ms: i64,65
message_set: bool,77
message_set: bool,66
}78
}67
79
@@ -70,6 +82,7 @@ fn parse_horizon(text: Option<&str>) -> ParsedHorizon {70
let number = |part: &str| part.trim().parse::<i64>().ok();82
let number = |part: &str| part.trim().parse::<i64>().ok();71
let unset = ParsedHorizon {83
let unset = ParsedHorizon {72
arrival_ms: 0,84
arrival_ms: 0,85
timestamp_ms: 0,73
message_set: false,86
message_set: false,74
};87
};75
let [arrival, timestamp, message_id] = parts.as_slice() else {88
let [arrival, timestamp, message_id] = parts.as_slice() else {@@ -77,8 +90,9 @@ fn parse_horizon(text: Option<&str>) -> ParsedHorizon {77
};90
};78
let message_id = message_id.trim();91
let message_id = message_id.trim();79
match (number(arrival), number(timestamp)) {92
match (number(arrival), number(timestamp)) {80
(Some(arrival_ms), Some(_)) if !message_id.is_empty() => ParsedHorizon {93
(Some(arrival_ms), Some(timestamp_ms)) if !message_id.is_empty() => ParsedHorizon {81
arrival_ms,94
arrival_ms,95
timestamp_ms,82
message_set: message_id != "0",96
message_set: message_id != "0",83
},97
},84
_ => unset,98
_ => unset,@@ -192,6 +206,31 @@ mod tests {192
assert!(unread(&value));206
assert!(unread(&value));193
}207
}194
208
209
#[test]210
fn app_horizon_reads_everything_that_arrived_before_it() {211
let value = conversation(212
Some("1791884440747;1791885752824;1"),213
None,214
Some(("2026-10-16T09:42:25.6780000Z", "8:orgid:other")),215
);216
let horizon = ReadHorizon::from_conversation(&value);217
assert!(horizon.is_unread_after(ME, 0));218
assert!(horizon.is_unread_after(ME, horizon.last_message_ms - 1));219
assert!(!horizon.is_unread_after(ME, horizon.last_message_ms));220
}221
222
#[test]223
fn app_horizon_clears_an_older_bookmark_only() {224
let value = conversation(225
Some("1792171970947;1792171971513;1"),226
Some("1792171970000;1792171971513;42"),227
Some(("2026-10-16T17:32:50.9470000Z", "8:orgid:other")),228
);229
let horizon = ReadHorizon::from_conversation(&value);230
assert!(horizon.is_unread_after(ME, 1792171971512));231
assert!(!horizon.is_unread_after(ME, 1792171971513));232
}233
195
#[test]234
#[test]196
fn read_value_carries_the_last_arrival_and_now() {235
fn read_value_carries_the_last_arrival_and_now() {197
let last = DateTime::from_timestamp_millis(1792182658901).unwrap();236
let last = DateTime::from_timestamp_millis(1792182658901).unwrap();@@ -9,6 +9,8 @@ const SETTINGS_KEY: &str = "simpleCollabUserSettings";
9
9
const SETTINGS_ID: &str = "simpleCollabUserSettingsId";
10
10
const TEAMS_ORDER_KEY: &str = "teamsOrder";
11
11
const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
12
const APP_HORIZON_KEY: &str = "appConsumptionHorizon";
13
const APP_HORIZON_APPS: [&str; 3] = ["chat", "channel", "engage_community"];
12
14
const MAX_SKIN_TONE: u8 = 5;
13
15
const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
14
16
const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
@@ -98,6 +100,18 @@ impl<T: MessageTransport> UserSettings<T> {
98
100
.await
99
101
}
100
102
103
/// Teams' "Mark all as read" for channels: one write, the channel entry of `appConsumptionHorizon` moves to now.
104
pub async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {
105
let properties = self.properties().await?;
106
let horizon = AppConsumptionHorizon {
107
channel_ms: now_ms,
108
..parse_app_consumption_horizon(&properties)
109
};
110
self.set_property(APP_HORIZON_KEY, Value::String(horizon.property_value()))
111
.await?;
112
Ok(horizon)
113
}
114
101
115
pub async fn set_property(&self, name: &str, value: Value) -> Result<()> {
102
116
let url = format!("{}?name={name}", self.base_url);
103
117
let mut body = Map::new();
@@ -175,6 +189,54 @@ pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {
175
189
order
176
190
}
177
191
192
/// Per app "read everything before" times in ms; Teams treats a conversation of that app as read up to it.
193
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
194
pub struct AppConsumptionHorizon {
195
pub chat_ms: i64,
196
pub channel_ms: i64,
197
pub engage_community_ms: i64,
198
}
199
200
impl AppConsumptionHorizon {
201
pub fn property_value(&self) -> String {
202
let values = [self.chat_ms, self.channel_ms, self.engage_community_ms];
203
let mut fields = Map::new();
204
for (app, value) in APP_HORIZON_APPS.iter().zip(values) {
205
fields.insert((*app).to_owned(), Value::from(value));
206
}
207
Value::Object(fields).to_string()
208
}
209
}
210
211
pub fn parse_app_consumption_horizon(properties: &Value) -> AppConsumptionHorizon {
212
let parsed = match properties.get(APP_HORIZON_KEY) {
213
Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
214
Some(other) => Some(other.clone()),
215
None => None,
216
};
217
let Some(fields) = parsed.as_ref().and_then(Value::as_object) else {
218
return AppConsumptionHorizon::default();
219
};
220
let valid = (fields.contains_key("chat") || fields.contains_key("channel"))
221
&& fields
222
.values()
223
.all(|value| value.as_f64().is_some_and(|number| number >= 0.0));
224
if !valid {
225
return AppConsumptionHorizon::default();
226
}
227
let read = |app: &str| {
228
fields
229
.get(app)
230
.and_then(Value::as_f64)
231
.map_or(0, |number| number as i64)
232
};
233
AppConsumptionHorizon {
234
chat_ms: read("chat"),
235
channel_ms: read("channel"),
236
engage_community_ms: read("engage_community"),
237
}
238
}
239
178
240
pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {
179
241
let mut settings = stored_settings(properties);
180
242
settings
@@ -334,4 +396,63 @@ mod tests {
334
396
assert_eq!(value["keep"], json!(1));
335
397
assert_eq!(value["hasUserEnabledMutedChatSection"], json!(false));
336
398
}
399
400
#[test]
401
fn app_horizon_reads_the_string_and_ignores_invalid_values() {
402
let parsed = parse_app_consumption_horizon(&json!({
403
"appConsumptionHorizon": "{\"chat\":1791368000000,\"channel\":1791369000000,\"engage_community\":0}"
404
}));
405
assert_eq!(
406
parsed,
407
AppConsumptionHorizon {
408
chat_ms: 1791368000000,
409
channel_ms: 1791369000000,
410
engage_community_ms: 0,
411
}
412
);
413
let object = parse_app_consumption_horizon(&json!({"appConsumptionHorizon": {"channel": 5}}));
414
assert_eq!(object.channel_ms, 5);
415
for broken in [
416
json!({}),
417
json!({"appConsumptionHorizon": "not json"}),
418
json!({"appConsumptionHorizon": "{\"engage_community\":5}"}),
419
json!({"appConsumptionHorizon": "{\"channel\":-1}"}),
420
json!({"appConsumptionHorizon": "{\"channel\":\"5\"}"}),
421
] {
422
assert_eq!(
423
parse_app_consumption_horizon(&broken),
424
AppConsumptionHorizon::default()
425
);
426
}
427
}
428
429
#[tokio::test]
430
async fn mark_all_channels_read_moves_only_the_channel_entry() {
431
let stored = json!({
432
"appConsumptionHorizon": "{\"chat\":100,\"channel\":200,\"engage_community\":300}"
433
});
434
let transport = Canned {
435
answers: Mutex::new(vec![(200, stored), (200, Value::Null)].into()),
436
requests: Mutex::new(Vec::new()),
437
};
438
let horizon = UserSettings::with_transport(&transport, "emea")
439
.mark_all_channels_read(1791368000000)
440
.await
441
.unwrap();
442
assert_eq!(horizon.channel_ms, 1791368000000);
443
let requests = transport.requests.lock().unwrap();
444
assert_eq!(requests[1].method, Method::Put);
445
assert_eq!(
446
requests[1].url,
447
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=appConsumptionHorizon"
448
);
449
let sent = requests[1].body.as_ref().unwrap()["appConsumptionHorizon"]
450
.as_str()
451
.unwrap();
452
let value: Value = serde_json::from_str(sent).unwrap();
453
assert_eq!(
454
value,
455
json!({"chat": 100, "channel": 1791368000000_i64, "engage_community": 300})
456
);
457
}
337
458
}
@@ -9,6 +9,8 @@ const SETTINGS_KEY: &str = "simpleCollabUserSettings";9
const SETTINGS_ID: &str = "simpleCollabUserSettingsId";9
const SETTINGS_ID: &str = "simpleCollabUserSettingsId";10
const TEAMS_ORDER_KEY: &str = "teamsOrder";10
const TEAMS_ORDER_KEY: &str = "teamsOrder";11
const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";11
const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";12
const APP_HORIZON_KEY: &str = "appConsumptionHorizon";13
const APP_HORIZON_APPS: [&str; 3] = ["chat", "channel", "engage_community"];12
const MAX_SKIN_TONE: u8 = 5;14
const MAX_SKIN_TONE: u8 = 5;13
const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";15
const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";14
const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";16
const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";@@ -98,6 +100,18 @@ impl<T: MessageTransport> UserSettings<T> {98
.await100
.await99
}101
}100
102
103
/// Teams' "Mark all as read" for channels: one write, the channel entry of `appConsumptionHorizon` moves to now.104
pub async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {105
let properties = self.properties().await?;106
let horizon = AppConsumptionHorizon {107
channel_ms: now_ms,108
..parse_app_consumption_horizon(&properties)109
};110
self.set_property(APP_HORIZON_KEY, Value::String(horizon.property_value()))111
.await?;112
Ok(horizon)113
}114
101
pub async fn set_property(&self, name: &str, value: Value) -> Result<()> {115
pub async fn set_property(&self, name: &str, value: Value) -> Result<()> {102
let url = format!("{}?name={name}", self.base_url);116
let url = format!("{}?name={name}", self.base_url);103
let mut body = Map::new();117
let mut body = Map::new();@@ -175,6 +189,54 @@ pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {175
order189
order176
}190
}177
191
192
/// Per app "read everything before" times in ms; Teams treats a conversation of that app as read up to it.193
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]194
pub struct AppConsumptionHorizon {195
pub chat_ms: i64,196
pub channel_ms: i64,197
pub engage_community_ms: i64,198
}199
200
impl AppConsumptionHorizon {201
pub fn property_value(&self) -> String {202
let values = [self.chat_ms, self.channel_ms, self.engage_community_ms];203
let mut fields = Map::new();204
for (app, value) in APP_HORIZON_APPS.iter().zip(values) {205
fields.insert((*app).to_owned(), Value::from(value));206
}207
Value::Object(fields).to_string()208
}209
}210
211
pub fn parse_app_consumption_horizon(properties: &Value) -> AppConsumptionHorizon {212
let parsed = match properties.get(APP_HORIZON_KEY) {213
Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),214
Some(other) => Some(other.clone()),215
None => None,216
};217
let Some(fields) = parsed.as_ref().and_then(Value::as_object) else {218
return AppConsumptionHorizon::default();219
};220
let valid = (fields.contains_key("chat") || fields.contains_key("channel"))221
&& fields222
.values()223
.all(|value| value.as_f64().is_some_and(|number| number >= 0.0));224
if !valid {225
return AppConsumptionHorizon::default();226
}227
let read = |app: &str| {228
fields229
.get(app)230
.and_then(Value::as_f64)231
.map_or(0, |number| number as i64)232
};233
AppConsumptionHorizon {234
chat_ms: read("chat"),235
channel_ms: read("channel"),236
engage_community_ms: read("engage_community"),237
}238
}239
178
pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {240
pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {179
let mut settings = stored_settings(properties);241
let mut settings = stored_settings(properties);180
settings242
settings@@ -334,4 +396,63 @@ mod tests {334
assert_eq!(value["keep"], json!(1));396
assert_eq!(value["keep"], json!(1));335
assert_eq!(value["hasUserEnabledMutedChatSection"], json!(false));397
assert_eq!(value["hasUserEnabledMutedChatSection"], json!(false));336
}398
}399
400
#[test]401
fn app_horizon_reads_the_string_and_ignores_invalid_values() {402
let parsed = parse_app_consumption_horizon(&json!({403
"appConsumptionHorizon": "{\"chat\":1791368000000,\"channel\":1791369000000,\"engage_community\":0}"404
}));405
assert_eq!(406
parsed,407
AppConsumptionHorizon {408
chat_ms: 1791368000000,409
channel_ms: 1791369000000,410
engage_community_ms: 0,411
}412
);413
let object = parse_app_consumption_horizon(&json!({"appConsumptionHorizon": {"channel": 5}}));414
assert_eq!(object.channel_ms, 5);415
for broken in [416
json!({}),417
json!({"appConsumptionHorizon": "not json"}),418
json!({"appConsumptionHorizon": "{\"engage_community\":5}"}),419
json!({"appConsumptionHorizon": "{\"channel\":-1}"}),420
json!({"appConsumptionHorizon": "{\"channel\":\"5\"}"}),421
] {422
assert_eq!(423
parse_app_consumption_horizon(&broken),424
AppConsumptionHorizon::default()425
);426
}427
}428
429
#[tokio::test]430
async fn mark_all_channels_read_moves_only_the_channel_entry() {431
let stored = json!({432
"appConsumptionHorizon": "{\"chat\":100,\"channel\":200,\"engage_community\":300}"433
});434
let transport = Canned {435
answers: Mutex::new(vec![(200, stored), (200, Value::Null)].into()),436
requests: Mutex::new(Vec::new()),437
};438
let horizon = UserSettings::with_transport(&transport, "emea")439
.mark_all_channels_read(1791368000000)440
.await441
.unwrap();442
assert_eq!(horizon.channel_ms, 1791368000000);443
let requests = transport.requests.lock().unwrap();444
assert_eq!(requests[1].method, Method::Put);445
assert_eq!(446
requests[1].url,447
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=appConsumptionHorizon"448
);449
let sent = requests[1].body.as_ref().unwrap()["appConsumptionHorizon"]450
.as_str()451
.unwrap();452
let value: Value = serde_json::from_str(sent).unwrap();453
assert_eq!(454
value,455
json!({"chat": 100, "channel": 1791368000000_i64, "engage_community": 300})456
);457
}337
}458
}@@ -391,6 +391,18 @@ impl<R: Remote> SyncEngine<R> {
391
391
)
392
392
.await?;
393
393
self.store.mark_channel_read(channel_id)?;
394
self.store.clear_channel_mentions(channel_id)?;
395
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
396
Ok(())
397
}
398
399
pub async fn mark_all_channels_read(&self) -> Result<()> {
400
let horizon = self
401
.remote
402
.mark_all_channels_read(Utc::now().timestamp_millis())
403
.await?;
404
*self.app_channel_horizon_ms.lock().unwrap() = horizon.channel_ms;
405
self.store.mark_all_channels_read()?;
394
406
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
395
407
Ok(())
396
408
}
@@ -391,6 +391,18 @@ impl<R: Remote> SyncEngine<R> {391
)391
)392
.await?;392
.await?;393
self.store.mark_channel_read(channel_id)?;393
self.store.mark_channel_read(channel_id)?;394
self.store.clear_channel_mentions(channel_id)?;395
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);396
Ok(())397
}398
399
pub async fn mark_all_channels_read(&self) -> Result<()> {400
let horizon = self401
.remote402
.mark_all_channels_read(Utc::now().timestamp_millis())403
.await?;404
*self.app_channel_horizon_ms.lock().unwrap() = horizon.channel_ms;405
self.store.mark_all_channels_read()?;394
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);406
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);395
Ok(())407
Ok(())396
}408
}@@ -0,0 +1,132 @@
1
use std::collections::{HashMap, HashSet};
2
3
use chatsvc::{ConversationState, MentionActivity, MentionKind};
4
use store::ChannelMentions;
5
6
/// Teams counts a mention only while its channel is unread, it is newer than the read horizon and not read.
7
pub fn channel_mentions(
8
activities: &[MentionActivity],
9
states: &[ConversationState],
10
my_user_id: &str,
11
app_horizon_ms: i64,
12
) -> Vec<(String, ChannelMentions)> {
13
let states: HashMap<&str, &ConversationState> = states
14
.iter()
15
.map(|state| (state.id.as_str(), state))
16
.collect();
17
let mut counted_activity_ids = HashSet::new();
18
let mut mentions: HashMap<String, ChannelMentions> = HashMap::new();
19
for activity in activities {
20
if activity.is_read || !counted_activity_ids.insert(activity.activity_id.as_str()) {
21
continue;
22
}
23
let Some(state) = states.get(activity.source_thread_id.as_str()) else {
24
continue;
25
};
26
let horizon_ms = state.read.consumed_until_ms.max(app_horizon_ms);
27
if activity.timestamp_ms <= horizon_ms
28
|| !state.read.is_unread_after(my_user_id, app_horizon_ms)
29
{
30
continue;
31
}
32
let counts = mentions
33
.entry(activity.source_thread_id.clone())
34
.or_default();
35
match activity.kind {
36
MentionKind::Personal => counts.personal += 1,
37
MentionKind::Channel => counts.channel += 1,
38
MentionKind::Team => counts.team += 1,
39
}
40
}
41
let mut mentions: Vec<(String, ChannelMentions)> = mentions.into_iter().collect();
42
mentions.sort_by(|left, right| left.0.cmp(&right.0));
43
mentions
44
}
45
46
#[cfg(test)]
47
mod tests {
48
use chatsvc::ReadHorizon;
49
50
use super::*;
51
52
const ME: &str = "8:orgid:me";
53
54
fn state(id: &str, consumed_until_ms: i64, last_message_ms: i64) -> ConversationState {
55
ConversationState {
56
id: id.to_owned(),
57
muted: false,
58
hidden: None,
59
read: ReadHorizon {
60
consumed_until_ms,
61
last_message_ms,
62
last_message_from: Some("8:orgid:someone".to_owned()),
63
..ReadHorizon::default()
64
},
65
}
66
}
67
68
fn activity(id: &str, thread: &str, kind: MentionKind, timestamp_ms: i64) -> MentionActivity {
69
MentionActivity {
70
activity_id: id.to_owned(),
71
kind,
72
source_thread_id: thread.to_owned(),
73
source_message_id: None,
74
timestamp_ms,
75
is_read: false,
76
}
77
}
78
79
fn counts(personal: u32, channel: u32, team: u32) -> ChannelMentions {
80
ChannelMentions {
81
personal,
82
channel,
83
team,
84
}
85
}
86
87
#[test]
88
fn counts_unread_mentions_after_the_horizon_per_kind() {
89
let states = [state("19:a", 100, 500), state("19:b", 100, 500)];
90
let activities = [
91
activity("1", "19:a", MentionKind::Personal, 200),
92
activity("2", "19:a", MentionKind::Personal, 300),
93
activity("2", "19:a", MentionKind::Personal, 300),
94
activity("3", "19:a", MentionKind::Channel, 300),
95
activity("4", "19:b", MentionKind::Team, 400),
96
activity("5", "19:a", MentionKind::Personal, 50),
97
MentionActivity {
98
is_read: true,
99
..activity("6", "19:b", MentionKind::Personal, 400)
100
},
101
activity("7", "19:unknown", MentionKind::Personal, 400),
102
];
103
assert_eq!(
104
channel_mentions(&activities, &states, ME, 0),
105
[
106
("19:a".to_owned(), counts(2, 1, 0)),
107
("19:b".to_owned(), counts(0, 0, 1)),
108
]
109
);
110
}
111
112
#[test]
113
fn a_read_channel_has_no_mentions() {
114
let states = [state("19:a", 600, 500)];
115
let activities = [activity("1", "19:a", MentionKind::Personal, 550)];
116
assert!(channel_mentions(&activities, &states, ME, 0).is_empty());
117
}
118
119
#[test]
120
fn mark_all_as_read_hides_older_mentions() {
121
let states = [state("19:a", 100, 900)];
122
let activities = [
123
activity("1", "19:a", MentionKind::Personal, 300),
124
activity("2", "19:a", MentionKind::Personal, 800),
125
];
126
assert_eq!(
127
channel_mentions(&activities, &states, ME, 500),
128
[("19:a".to_owned(), counts(1, 0, 0))]
129
);
130
assert!(channel_mentions(&activities, &states, ME, 950).is_empty());
131
}
132
}
@@ -0,0 +1,132 @@1
use std::collections::{HashMap, HashSet};2
3
use chatsvc::{ConversationState, MentionActivity, MentionKind};4
use store::ChannelMentions;5
6
/// Teams counts a mention only while its channel is unread, it is newer than the read horizon and not read.7
pub fn channel_mentions(8
activities: &[MentionActivity],9
states: &[ConversationState],10
my_user_id: &str,11
app_horizon_ms: i64,12
) -> Vec<(String, ChannelMentions)> {13
let states: HashMap<&str, &ConversationState> = states14
.iter()15
.map(|state| (state.id.as_str(), state))16
.collect();17
let mut counted_activity_ids = HashSet::new();18
let mut mentions: HashMap<String, ChannelMentions> = HashMap::new();19
for activity in activities {20
if activity.is_read || !counted_activity_ids.insert(activity.activity_id.as_str()) {21
continue;22
}23
let Some(state) = states.get(activity.source_thread_id.as_str()) else {24
continue;25
};26
let horizon_ms = state.read.consumed_until_ms.max(app_horizon_ms);27
if activity.timestamp_ms <= horizon_ms28
|| !state.read.is_unread_after(my_user_id, app_horizon_ms)29
{30
continue;31
}32
let counts = mentions33
.entry(activity.source_thread_id.clone())34
.or_default();35
match activity.kind {36
MentionKind::Personal => counts.personal += 1,37
MentionKind::Channel => counts.channel += 1,38
MentionKind::Team => counts.team += 1,39
}40
}41
let mut mentions: Vec<(String, ChannelMentions)> = mentions.into_iter().collect();42
mentions.sort_by(|left, right| left.0.cmp(&right.0));43
mentions44
}45
46
#[cfg(test)]47
mod tests {48
use chatsvc::ReadHorizon;49
50
use super::*;51
52
const ME: &str = "8:orgid:me";53
54
fn state(id: &str, consumed_until_ms: i64, last_message_ms: i64) -> ConversationState {55
ConversationState {56
id: id.to_owned(),57
muted: false,58
hidden: None,59
read: ReadHorizon {60
consumed_until_ms,61
last_message_ms,62
last_message_from: Some("8:orgid:someone".to_owned()),63
..ReadHorizon::default()64
},65
}66
}67
68
fn activity(id: &str, thread: &str, kind: MentionKind, timestamp_ms: i64) -> MentionActivity {69
MentionActivity {70
activity_id: id.to_owned(),71
kind,72
source_thread_id: thread.to_owned(),73
source_message_id: None,74
timestamp_ms,75
is_read: false,76
}77
}78
79
fn counts(personal: u32, channel: u32, team: u32) -> ChannelMentions {80
ChannelMentions {81
personal,82
channel,83
team,84
}85
}86
87
#[test]88
fn counts_unread_mentions_after_the_horizon_per_kind() {89
let states = [state("19:a", 100, 500), state("19:b", 100, 500)];90
let activities = [91
activity("1", "19:a", MentionKind::Personal, 200),92
activity("2", "19:a", MentionKind::Personal, 300),93
activity("2", "19:a", MentionKind::Personal, 300),94
activity("3", "19:a", MentionKind::Channel, 300),95
activity("4", "19:b", MentionKind::Team, 400),96
activity("5", "19:a", MentionKind::Personal, 50),97
MentionActivity {98
is_read: true,99
..activity("6", "19:b", MentionKind::Personal, 400)100
},101
activity("7", "19:unknown", MentionKind::Personal, 400),102
];103
assert_eq!(104
channel_mentions(&activities, &states, ME, 0),105
[106
("19:a".to_owned(), counts(2, 1, 0)),107
("19:b".to_owned(), counts(0, 0, 1)),108
]109
);110
}111
112
#[test]113
fn a_read_channel_has_no_mentions() {114
let states = [state("19:a", 600, 500)];115
let activities = [activity("1", "19:a", MentionKind::Personal, 550)];116
assert!(channel_mentions(&activities, &states, ME, 0).is_empty());117
}118
119
#[test]120
fn mark_all_as_read_hides_older_mentions() {121
let states = [state("19:a", 100, 900)];122
let activities = [123
activity("1", "19:a", MentionKind::Personal, 300),124
activity("2", "19:a", MentionKind::Personal, 800),125
];126
assert_eq!(127
channel_mentions(&activities, &states, ME, 500),128
[("19:a".to_owned(), counts(1, 0, 0))]129
);130
assert!(channel_mentions(&activities, &states, ME, 950).is_empty());131
}132
}@@ -131,6 +131,7 @@ pub struct SyncEngine<R: Remote = Graph> {
131
131
pub(crate) links_backfilled: Mutex<HashSet<String>>,
132
132
pub(crate) forwards_healed: Mutex<HashSet<String>>,
133
133
pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
134
pub(crate) app_channel_horizon_ms: Mutex<i64>,
134
135
pub(crate) chat_paging: Mutex<ChatPaging>,
135
136
pub(crate) locally_hidden_lock: Mutex<()>,
136
137
pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,
@@ -167,6 +168,7 @@ impl<R: Remote> SyncEngine<R> {
167
168
links_backfilled: Mutex::new(HashSet::new()),
168
169
forwards_healed: Mutex::new(HashSet::new()),
169
170
chat_states: Mutex::new(HashMap::new()),
171
app_channel_horizon_ms: Mutex::new(0),
170
172
chat_paging,
171
173
locally_hidden_lock: Mutex::new(()),
172
174
bot_partners: Mutex::default(),
@@ -131,6 +131,7 @@ pub struct SyncEngine<R: Remote = Graph> {131
pub(crate) links_backfilled: Mutex<HashSet<String>>,131
pub(crate) links_backfilled: Mutex<HashSet<String>>,132
pub(crate) forwards_healed: Mutex<HashSet<String>>,132
pub(crate) forwards_healed: Mutex<HashSet<String>>,133
pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,133
pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,134
pub(crate) app_channel_horizon_ms: Mutex<i64>,134
pub(crate) chat_paging: Mutex<ChatPaging>,135
pub(crate) chat_paging: Mutex<ChatPaging>,135
pub(crate) locally_hidden_lock: Mutex<()>,136
pub(crate) locally_hidden_lock: Mutex<()>,136
pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,137
pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,@@ -167,6 +168,7 @@ impl<R: Remote> SyncEngine<R> {167
links_backfilled: Mutex::new(HashSet::new()),168
links_backfilled: Mutex::new(HashSet::new()),168
forwards_healed: Mutex::new(HashSet::new()),169
forwards_healed: Mutex::new(HashSet::new()),169
chat_states: Mutex::new(HashMap::new()),170
chat_states: Mutex::new(HashMap::new()),171
app_channel_horizon_ms: Mutex::new(0),170
chat_paging,172
chat_paging,171
locally_hidden_lock: Mutex::new(()),173
locally_hidden_lock: Mutex::new(()),172
bot_partners: Mutex::default(),174
bot_partners: Mutex::default(),@@ -11,6 +11,7 @@ mod card_layout;
11
11
mod card_table;
12
12
mod card_widgets;
13
13
mod card_width;
14
mod channel_mentions;
14
15
mod channel_sync;
15
16
mod chat_paging;
16
17
mod download;
@@ -11,6 +11,7 @@ mod card_layout;11
mod card_table;11
mod card_table;12
mod card_widgets;12
mod card_widgets;13
mod card_width;13
mod card_width;14
mod channel_mentions;14
mod channel_sync;15
mod channel_sync;15
mod chat_paging;16
mod chat_paging;16
mod download;17
mod download;@@ -68,32 +68,78 @@ impl<R: Remote> SyncEngine<R> {
68
68
self.remote.list_call_logs().await
69
69
}
70
70
71
pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
72
self.ensure_chat(chat_id)?;
73
self.remote.chat_pins(chat_id).await
71
pub async fn chat_pins(&self, conversation_id: &str) -> Result<Vec<PinnedMessage>> {
72
match self.resolve_stored(conversation_id)? {
73
Conversation::Chat => self.remote.chat_pins(conversation_id).await,
74
Conversation::Channel { team_id } => {
75
let team_thread_id = self.team_thread_id(&team_id)?;
76
self.remote
77
.channel_pinned_posts(&team_thread_id, conversation_id)
78
.await
79
}
80
}
74
81
}
75
82
76
pub async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
77
self.ensure_chat(chat_id)?;
78
self.remote.pin_message(chat_id, message_id).await?;
79
self.announce_pins(chat_id);
83
pub async fn pin_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {
84
match self.resolve_stored(conversation_id)? {
85
Conversation::Chat => self.remote.pin_message(conversation_id, message_id).await?,
86
Conversation::Channel { team_id } => {
87
self.set_post_pinned(&team_id, conversation_id, message_id, true)
88
.await?
89
}
90
}
91
self.announce_pins(conversation_id);
80
92
Ok(())
81
93
}
82
94
83
95
pub async fn unpin_message(
84
96
&self,
85
chat_id: &str,
97
conversation_id: &str,
86
98
message_id: &str,
87
99
parent_id: Option<&str>,
88
100
) -> Result<()> {
89
self.ensure_chat(chat_id)?;
90
self.remote
91
.unpin_message(chat_id, message_id, parent_id)
92
.await?;
93
self.announce_pins(chat_id);
101
match self.resolve_stored(conversation_id)? {
102
Conversation::Chat => {
103
self.remote
104
.unpin_message(conversation_id, message_id, parent_id)
105
.await?
106
}
107
Conversation::Channel { team_id } => {
108
self.set_post_pinned(&team_id, conversation_id, message_id, false)
109
.await?
110
}
111
}
112
self.announce_pins(conversation_id);
94
113
Ok(())
95
114
}
96
115
116
async fn set_post_pinned(
117
&self,
118
team_id: &str,
119
channel_id: &str,
120
post_id: &str,
121
pinned: bool,
122
) -> Result<()> {
123
let is_reply = self
124
.store
125
.messages_by_id(channel_id, &[post_id.to_owned()])?
126
.get(post_id)
127
.is_some_and(|record| record.reply_to_id.is_some());
128
if is_reply {
129
return Err(Error::Unsupported("pinning a channel reply"));
130
}
131
let team_thread_id = self.team_thread_id(team_id)?;
132
self.remote
133
.set_post_pinned(&team_thread_id, channel_id, post_id, pinned)
134
.await
135
}
136
137
fn team_thread_id(&self, team_id: &str) -> Result<String> {
138
self.store
139
.team_thread_id(team_id)?
140
.ok_or_else(|| Error::UnknownConversation(team_id.to_owned()))
141
}
142
97
143
pub async fn message_link(&self, conversation_id: &str, message_id: &str) -> Result<String> {
98
144
let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {
99
145
let notes_oid = if conversation_id == NOTES_CHAT_ID {
@@ -153,13 +199,6 @@ impl<R: Remote> SyncEngine<R> {
153
199
}
154
200
}
155
201
156
fn ensure_chat(&self, conversation_id: &str) -> Result<()> {
157
match self.resolve_stored(conversation_id)? {
158
Conversation::Chat => Ok(()),
159
Conversation::Channel { .. } => Err(Error::Unsupported("pinned messages in a channel")),
160
}
161
}
162
163
202
fn announce_pins(&self, conversation_id: &str) {
164
203
let _ = self.events.send(CoreEvent::PinsChanged {
165
204
conversation_id: conversation_id.to_owned(),
@@ -68,32 +68,78 @@ impl<R: Remote> SyncEngine<R> {68
self.remote.list_call_logs().await68
self.remote.list_call_logs().await69
}69
}70
70
71
pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {71
pub async fn chat_pins(&self, conversation_id: &str) -> Result<Vec<PinnedMessage>> {72
self.ensure_chat(chat_id)?;72
match self.resolve_stored(conversation_id)? {73
self.remote.chat_pins(chat_id).await73
Conversation::Chat => self.remote.chat_pins(conversation_id).await,74
Conversation::Channel { team_id } => {75
let team_thread_id = self.team_thread_id(&team_id)?;76
self.remote77
.channel_pinned_posts(&team_thread_id, conversation_id)78
.await79
}80
}74
}81
}75
82
76
pub async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {83
pub async fn pin_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {77
self.ensure_chat(chat_id)?;84
match self.resolve_stored(conversation_id)? {78
self.remote.pin_message(chat_id, message_id).await?;85
Conversation::Chat => self.remote.pin_message(conversation_id, message_id).await?,79
self.announce_pins(chat_id);86
Conversation::Channel { team_id } => {87
self.set_post_pinned(&team_id, conversation_id, message_id, true)88
.await?89
}90
}91
self.announce_pins(conversation_id);80
Ok(())92
Ok(())81
}93
}82
94
83
pub async fn unpin_message(95
pub async fn unpin_message(84
&self,96
&self,85
chat_id: &str,97
conversation_id: &str,86
message_id: &str,98
message_id: &str,87
parent_id: Option<&str>,99
parent_id: Option<&str>,88
) -> Result<()> {100
) -> Result<()> {89
self.ensure_chat(chat_id)?;101
match self.resolve_stored(conversation_id)? {90
self.remote102
Conversation::Chat => {91
.unpin_message(chat_id, message_id, parent_id)103
self.remote92
.await?;104
.unpin_message(conversation_id, message_id, parent_id)93
self.announce_pins(chat_id);105
.await?106
}107
Conversation::Channel { team_id } => {108
self.set_post_pinned(&team_id, conversation_id, message_id, false)109
.await?110
}111
}112
self.announce_pins(conversation_id);94
Ok(())113
Ok(())95
}114
}96
115
116
async fn set_post_pinned(117
&self,118
team_id: &str,119
channel_id: &str,120
post_id: &str,121
pinned: bool,122
) -> Result<()> {123
let is_reply = self124
.store125
.messages_by_id(channel_id, &[post_id.to_owned()])?126
.get(post_id)127
.is_some_and(|record| record.reply_to_id.is_some());128
if is_reply {129
return Err(Error::Unsupported("pinning a channel reply"));130
}131
let team_thread_id = self.team_thread_id(team_id)?;132
self.remote133
.set_post_pinned(&team_thread_id, channel_id, post_id, pinned)134
.await135
}136
137
fn team_thread_id(&self, team_id: &str) -> Result<String> {138
self.store139
.team_thread_id(team_id)?140
.ok_or_else(|| Error::UnknownConversation(team_id.to_owned()))141
}142
97
pub async fn message_link(&self, conversation_id: &str, message_id: &str) -> Result<String> {143
pub async fn message_link(&self, conversation_id: &str, message_id: &str) -> Result<String> {98
let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {144
let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {99
let notes_oid = if conversation_id == NOTES_CHAT_ID {145
let notes_oid = if conversation_id == NOTES_CHAT_ID {@@ -153,13 +199,6 @@ impl<R: Remote> SyncEngine<R> {153
}199
}154
}200
}155
201
156
fn ensure_chat(&self, conversation_id: &str) -> Result<()> {157
match self.resolve_stored(conversation_id)? {158
Conversation::Chat => Ok(()),159
Conversation::Channel { .. } => Err(Error::Unsupported("pinned messages in a channel")),160
}161
}162
163
fn announce_pins(&self, conversation_id: &str) {202
fn announce_pins(&self, conversation_id: &str) {164
let _ = self.events.send(CoreEvent::PinsChanged {203
let _ = self.events.send(CoreEvent::PinsChanged {165
conversation_id: conversation_id.to_owned(),204
conversation_id: conversation_id.to_owned(),@@ -2,6 +2,10 @@ use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
2
2
use chatsvc::substrate_search::{
3
3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
4
4
};
5
use chatsvc::{
6
ActivityFeed, AppConsumptionHorizon, MentionActivity, UserSettings,
7
parse_app_consumption_horizon,
8
};
5
9
use chatsvc::{
6
10
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
7
11
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest,
@@ -345,6 +349,36 @@ pub trait Remote {
345
349
Err(Error::Unsupported("pinning messages"))
346
350
}
347
351
352
async fn channel_pinned_posts(
353
&self,
354
_team_thread_id: &str,
355
_channel_id: &str,
356
) -> Result<Vec<PinnedMessage>> {
357
Err(Error::Unsupported("pinned channel posts"))
358
}
359
360
async fn set_post_pinned(
361
&self,
362
_team_thread_id: &str,
363
_channel_id: &str,
364
_post_id: &str,
365
_pinned: bool,
366
) -> Result<()> {
367
Err(Error::Unsupported("pinning channel posts"))
368
}
369
370
async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {
371
Err(Error::Unsupported("the activity feed"))
372
}
373
374
async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
375
Ok(AppConsumptionHorizon::default())
376
}
377
378
async fn mark_all_channels_read(&self, _now_ms: i64) -> Result<AppConsumptionHorizon> {
379
Err(Error::Unsupported("marking all channels as read"))
380
}
381
348
382
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {
349
383
Err(Error::Unsupported("chat apps"))
350
384
}
@@ -1019,6 +1053,43 @@ impl Remote for Graph {
1019
1053
.await?)
1020
1054
}
1021
1055
1056
async fn channel_pinned_posts(
1057
&self,
1058
team_thread_id: &str,
1059
channel_id: &str,
1060
) -> Result<Vec<PinnedMessage>> {
1061
Ok(Pins::new(self.session())
1062
.channel_pinned_posts(team_thread_id, channel_id)
1063
.await?)
1064
}
1065
1066
async fn set_post_pinned(
1067
&self,
1068
team_thread_id: &str,
1069
channel_id: &str,
1070
post_id: &str,
1071
pinned: bool,
1072
) -> Result<()> {
1073
Ok(Pins::new(self.session())
1074
.set_post_pinned(team_thread_id, channel_id, post_id, pinned)
1075
.await?)
1076
}
1077
1078
async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {
1079
Ok(ActivityFeed::new(self.session()).mentions().await?)
1080
}
1081
1082
async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
1083
let properties = UserSettings::new(self.session()).properties().await?;
1084
Ok(parse_app_consumption_horizon(&properties))
1085
}
1086
1087
async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {
1088
Ok(UserSettings::new(self.session())
1089
.mark_all_channels_read(now_ms)
1090
.await?)
1091
}
1092
1022
1093
async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {
1023
1094
Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)
1024
1095
}
@@ -2,6 +2,10 @@ use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};2
use chatsvc::substrate_search::{2
use chatsvc::substrate_search::{3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,4
};4
};5
use chatsvc::{6
ActivityFeed, AppConsumptionHorizon, MentionActivity, UserSettings,7
parse_app_consumption_horizon,8
};5
use chatsvc::{9
use chatsvc::{6
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,10
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,7
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest,11
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest,@@ -345,6 +349,36 @@ pub trait Remote {345
Err(Error::Unsupported("pinning messages"))349
Err(Error::Unsupported("pinning messages"))346
}350
}347
351
352
async fn channel_pinned_posts(353
&self,354
_team_thread_id: &str,355
_channel_id: &str,356
) -> Result<Vec<PinnedMessage>> {357
Err(Error::Unsupported("pinned channel posts"))358
}359
360
async fn set_post_pinned(361
&self,362
_team_thread_id: &str,363
_channel_id: &str,364
_post_id: &str,365
_pinned: bool,366
) -> Result<()> {367
Err(Error::Unsupported("pinning channel posts"))368
}369
370
async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {371
Err(Error::Unsupported("the activity feed"))372
}373
374
async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {375
Ok(AppConsumptionHorizon::default())376
}377
378
async fn mark_all_channels_read(&self, _now_ms: i64) -> Result<AppConsumptionHorizon> {379
Err(Error::Unsupported("marking all channels as read"))380
}381
348
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {382
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {349
Err(Error::Unsupported("chat apps"))383
Err(Error::Unsupported("chat apps"))350
}384
}@@ -1019,6 +1053,43 @@ impl Remote for Graph {1019
.await?)1053
.await?)1020
}1054
}1021
1055
1056
async fn channel_pinned_posts(1057
&self,1058
team_thread_id: &str,1059
channel_id: &str,1060
) -> Result<Vec<PinnedMessage>> {1061
Ok(Pins::new(self.session())1062
.channel_pinned_posts(team_thread_id, channel_id)1063
.await?)1064
}1065
1066
async fn set_post_pinned(1067
&self,1068
team_thread_id: &str,1069
channel_id: &str,1070
post_id: &str,1071
pinned: bool,1072
) -> Result<()> {1073
Ok(Pins::new(self.session())1074
.set_post_pinned(team_thread_id, channel_id, post_id, pinned)1075
.await?)1076
}1077
1078
async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {1079
Ok(ActivityFeed::new(self.session()).mentions().await?)1080
}1081
1082
async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {1083
let properties = UserSettings::new(self.session()).properties().await?;1084
Ok(parse_app_consumption_horizon(&properties))1085
}1086
1087
async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {1088
Ok(UserSettings::new(self.session())1089
.mark_all_channels_read(now_ms)1090
.await?)1091
}1092
1022
async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {1093
async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {1023
Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)1094
Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)1024
}1095
}@@ -1,13 +1,14 @@
1
1
use std::collections::HashMap;
2
2
3
use chatsvc::ConversationState;
3
use chatsvc::{ConversationState, MentionActivity};
4
4
use chrono::{DateTime, Duration, Utc};
5
5
use store::{ChatRecord, Store};
6
6
7
7
use crate::bot_partners::BotPartners;
8
use crate::channel_mentions::channel_mentions;
8
9
use crate::chat_paging::ChatPaging;
9
10
use crate::engine::{SidebarSummary, SyncEngine};
10
use crate::error::Result;
11
use crate::error::{Error, Result};
11
12
use crate::events::CoreEvent;
12
13
use crate::hidden_chats::{LocallyHidden, resolve_hidden};
13
14
use crate::mapping::{channel_record, team_record};
@@ -69,7 +70,11 @@ impl<R: Remote> SyncEngine<R> {
69
70
let mut hidden_ids = Vec::new();
70
71
let mut complete = false;
71
72
let mut continuation = None;
72
let states = self.refresh_chat_states().await;
73
let (states, app_horizon_ms, mentions) = tokio::join!(
74
self.refresh_chat_states(),
75
self.refresh_app_channel_horizon(),
76
self.remote.mention_activities()
77
);
73
78
self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
74
79
let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
75
80
loop {
@@ -98,7 +103,8 @@ impl<R: Remote> SyncEngine<R> {
98
103
self.refresh_notes_chat(states.as_deref(), &my_user_id)
99
104
.await,
100
105
);
101
self.apply_channel_read_states(states.as_deref(), &my_user_id);
106
self.apply_channel_read_states(states.as_deref(), &my_user_id, app_horizon_ms);
107
self.apply_channel_mentions(states.as_deref(), mentions, &my_user_id, app_horizon_ms);
102
108
self.apply_muted_chats(states);
103
109
if full {
104
110
if complete {
@@ -145,7 +151,49 @@ impl<R: Remote> SyncEngine<R> {
145
151
Ok(())
146
152
}
147
153
148
fn apply_channel_read_states(&self, states: Option<&[ConversationState]>, my_user_id: &str) {
154
async fn refresh_app_channel_horizon(&self) -> i64 {
155
match self.remote.app_consumption_horizon().await {
156
Ok(horizon) => {
157
let mut known = self.app_channel_horizon_ms.lock().unwrap();
158
*known = horizon.channel_ms.max(*known);
159
*known
160
}
161
Err(error) => {
162
self.report(format!("cannot read the mark all as read horizon: {error}"));
163
*self.app_channel_horizon_ms.lock().unwrap()
164
}
165
}
166
}
167
168
fn apply_channel_mentions(
169
&self,
170
states: Option<&[ConversationState]>,
171
mentions: Result<Vec<MentionActivity>>,
172
my_user_id: &str,
173
app_horizon_ms: i64,
174
) {
175
let (Some(states), Ok(mentions)) = (
176
states,
177
mentions.inspect_err(|error| {
178
if !matches!(error, Error::Unsupported(_)) {
179
self.report(format!("cannot refresh channel mentions: {error}"));
180
}
181
}),
182
) else {
183
return;
184
};
185
let counts = channel_mentions(&mentions, states, my_user_id, app_horizon_ms);
186
if let Err(error) = self.store.replace_channel_mentions(&counts) {
187
self.report(format!("cannot store channel mentions: {error}"));
188
}
189
}
190
191
fn apply_channel_read_states(
192
&self,
193
states: Option<&[ConversationState]>,
194
my_user_id: &str,
195
app_horizon_ms: i64,
196
) {
149
197
let Some(states) = states else {
150
198
return;
151
199
};
@@ -154,7 +202,7 @@ impl<R: Remote> SyncEngine<R> {
154
202
.map(|state| {
155
203
(
156
204
state.id.clone(),
157
state.read.is_unread(my_user_id),
205
state.read.is_unread_after(my_user_id, app_horizon_ms),
158
206
state.read.last_message_at(),
159
207
)
160
208
})
@@ -1,13 +1,14 @@1
use std::collections::HashMap;1
use std::collections::HashMap;2
2
3
use chatsvc::ConversationState;3
use chatsvc::{ConversationState, MentionActivity};4
use chrono::{DateTime, Duration, Utc};4
use chrono::{DateTime, Duration, Utc};5
use store::{ChatRecord, Store};5
use store::{ChatRecord, Store};6
6
7
use crate::bot_partners::BotPartners;7
use crate::bot_partners::BotPartners;8
use crate::channel_mentions::channel_mentions;8
use crate::chat_paging::ChatPaging;9
use crate::chat_paging::ChatPaging;9
use crate::engine::{SidebarSummary, SyncEngine};10
use crate::engine::{SidebarSummary, SyncEngine};10
use crate::error::Result;11
use crate::error::{Error, Result};11
use crate::events::CoreEvent;12
use crate::events::CoreEvent;12
use crate::hidden_chats::{LocallyHidden, resolve_hidden};13
use crate::hidden_chats::{LocallyHidden, resolve_hidden};13
use crate::mapping::{channel_record, team_record};14
use crate::mapping::{channel_record, team_record};@@ -69,7 +70,11 @@ impl<R: Remote> SyncEngine<R> {69
let mut hidden_ids = Vec::new();70
let mut hidden_ids = Vec::new();70
let mut complete = false;71
let mut complete = false;71
let mut continuation = None;72
let mut continuation = None;72
let states = self.refresh_chat_states().await;73
let (states, app_horizon_ms, mentions) = tokio::join!(74
self.refresh_chat_states(),75
self.refresh_app_channel_horizon(),76
self.remote.mention_activities()77
);73
self.drop_chats_hidden_by_chatsvc(states.as_deref())?;78
self.drop_chats_hidden_by_chatsvc(states.as_deref())?;74
let mut page = self.remote.chats_page(self.config.chat_page_size).await?;79
let mut page = self.remote.chats_page(self.config.chat_page_size).await?;75
loop {80
loop {@@ -98,7 +103,8 @@ impl<R: Remote> SyncEngine<R> {98
self.refresh_notes_chat(states.as_deref(), &my_user_id)103
self.refresh_notes_chat(states.as_deref(), &my_user_id)99
.await,104
.await,100
);105
);101
self.apply_channel_read_states(states.as_deref(), &my_user_id);106
self.apply_channel_read_states(states.as_deref(), &my_user_id, app_horizon_ms);107
self.apply_channel_mentions(states.as_deref(), mentions, &my_user_id, app_horizon_ms);102
self.apply_muted_chats(states);108
self.apply_muted_chats(states);103
if full {109
if full {104
if complete {110
if complete {@@ -145,7 +151,49 @@ impl<R: Remote> SyncEngine<R> {145
Ok(())151
Ok(())146
}152
}147
153
148
fn apply_channel_read_states(&self, states: Option<&[ConversationState]>, my_user_id: &str) {154
async fn refresh_app_channel_horizon(&self) -> i64 {155
match self.remote.app_consumption_horizon().await {156
Ok(horizon) => {157
let mut known = self.app_channel_horizon_ms.lock().unwrap();158
*known = horizon.channel_ms.max(*known);159
*known160
}161
Err(error) => {162
self.report(format!("cannot read the mark all as read horizon: {error}"));163
*self.app_channel_horizon_ms.lock().unwrap()164
}165
}166
}167
168
fn apply_channel_mentions(169
&self,170
states: Option<&[ConversationState]>,171
mentions: Result<Vec<MentionActivity>>,172
my_user_id: &str,173
app_horizon_ms: i64,174
) {175
let (Some(states), Ok(mentions)) = (176
states,177
mentions.inspect_err(|error| {178
if !matches!(error, Error::Unsupported(_)) {179
self.report(format!("cannot refresh channel mentions: {error}"));180
}181
}),182
) else {183
return;184
};185
let counts = channel_mentions(&mentions, states, my_user_id, app_horizon_ms);186
if let Err(error) = self.store.replace_channel_mentions(&counts) {187
self.report(format!("cannot store channel mentions: {error}"));188
}189
}190
191
fn apply_channel_read_states(192
&self,193
states: Option<&[ConversationState]>,194
my_user_id: &str,195
app_horizon_ms: i64,196
) {149
let Some(states) = states else {197
let Some(states) = states else {150
return;198
return;151
};199
};@@ -154,7 +202,7 @@ impl<R: Remote> SyncEngine<R> {154
.map(|state| {202
.map(|state| {155
(203
(156
state.id.clone(),204
state.id.clone(),157
state.read.is_unread(my_user_id),205
state.read.is_unread_after(my_user_id, app_horizon_ms),158
state.read.last_message_at(),206
state.read.last_message_at(),159
)207
)160
})208
})@@ -135,6 +135,8 @@ struct Fake {
135
135
window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
136
136
search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,
137
137
member_requests: Mutex<Vec<String>>,
138
mention_activities: Mutex<Vec<chatsvc::MentionActivity>>,
139
app_channel_horizon_ms: Mutex<i64>,
138
140
}
139
141
140
142
impl Fake {
@@ -860,6 +862,49 @@ impl Remote for Handle {
860
862
Ok(())
861
863
}
862
864
865
async fn channel_pinned_posts(
866
&self,
867
team_thread_id: &str,
868
channel_id: &str,
869
) -> Result<Vec<chatsvc::PinnedMessage>> {
870
self.record(format!("channel pins {team_thread_id} {channel_id}"));
871
Ok(vec![chatsvc::PinnedMessage {
872
message_id: "30".to_owned(),
873
pinned_at: None,
874
parent_id: None,
875
}])
876
}
877
878
async fn set_post_pinned(
879
&self,
880
team_thread_id: &str,
881
channel_id: &str,
882
post_id: &str,
883
pinned: bool,
884
) -> Result<()> {
885
self.record(format!(
886
"post pin {team_thread_id} {channel_id} {post_id} {pinned}"
887
));
888
Ok(())
889
}
890
891
async fn mention_activities(&self) -> Result<Vec<chatsvc::MentionActivity>> {
892
Ok(self.mention_activities.lock().unwrap().clone())
893
}
894
895
async fn app_consumption_horizon(&self) -> Result<chatsvc::AppConsumptionHorizon> {
896
Ok(chatsvc::AppConsumptionHorizon {
897
channel_ms: *self.app_channel_horizon_ms.lock().unwrap(),
898
..chatsvc::AppConsumptionHorizon::default()
899
})
900
}
901
902
async fn mark_all_channels_read(&self, now_ms: i64) -> Result<chatsvc::AppConsumptionHorizon> {
903
self.record("mark all channels read".to_owned());
904
*self.app_channel_horizon_ms.lock().unwrap() = now_ms;
905
self.app_consumption_horizon().await
906
}
907
863
908
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {
864
909
*self.app_calls.lock().unwrap() += 1;
865
910
Ok(self.apps.lock().unwrap().clone())
@@ -4626,7 +4671,7 @@ async fn save_uses_the_message_id_as_root_in_chats() {
4626
4671
}
4627
4672
4628
4673
#[tokio::test]
4629
async fn pinning_announces_and_is_refused_in_channels() {
4674
async fn pinning_announces_in_chats() {
4630
4675
let fake = Arc::new(Fake::default());
4631
4676
let engine = channel_engine(&fake).await;
4632
4677
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
@@ -4647,10 +4692,83 @@ async fn pinning_announces_and_is_refused_in_channels() {
4647
4692
fake.calls().last().unwrap(),
4648
4693
&format!("unpin {CHAT} 5 Some(\"folder-1\")")
4649
4694
);
4650
assert!(matches!(
4651
engine.pin_message(CHANNEL, "5").await,
4652
Err(Error::Unsupported(_))
4695
}
4696
4697
#[tokio::test]
4698
async fn channel_pins_use_the_post_pin_routes_of_the_team_thread() {
4699
let fake = Arc::new(Fake::default());
4700
let engine = channel_engine(&fake).await;
4701
engine.fetch_newer(CHANNEL).await.unwrap();
4702
let pins = engine.chat_pins(CHANNEL).await.unwrap();
4703
assert_eq!(pins[0].message_id, "30");
4704
assert_eq!(
4705
fake.calls().last().unwrap(),
4706
&format!("channel pins {CHANNEL} {CHANNEL}")
4707
);
4708
let mut events = engine.subscribe();
4709
engine.pin_message(CHANNEL, "30").await.unwrap();
4710
assert_eq!(
4711
fake.calls().last().unwrap(),
4712
&format!("post pin {CHANNEL} {CHANNEL} 30 true")
4713
);
4714
assert_eq!(
4715
events.try_recv().unwrap(),
4716
CoreEvent::PinsChanged {
4717
conversation_id: CHANNEL.to_owned()
4718
}
4719
);
4720
engine.unpin_message(CHANNEL, "30", None).await.unwrap();
4721
assert_eq!(
4722
fake.calls().last().unwrap(),
4723
&format!("post pin {CHANNEL} {CHANNEL} 30 false")
4724
);
4725
}
4726
4727
#[tokio::test]
4728
async fn channel_mentions_follow_the_activity_feed_and_mark_all_as_read() {
4729
let fake = Arc::new(Fake::default());
4730
fake.read_states.lock().unwrap().push((
4731
CHANNEL.to_owned(),
4732
chatsvc::ReadHorizon {
4733
consumed_until_ms: 5,
4734
last_message_ms: 9,
4735
last_message_from: Some("8:orgid:user-ada".to_owned()),
4736
..chatsvc::ReadHorizon::default()
4737
},
4653
4738
));
4739
let mention = |activity_id: &str, kind: chatsvc::MentionKind| chatsvc::MentionActivity {
4740
activity_id: activity_id.to_owned(),
4741
kind,
4742
source_thread_id: CHANNEL.to_owned(),
4743
source_message_id: None,
4744
timestamp_ms: 8,
4745
is_read: false,
4746
};
4747
*fake.mention_activities.lock().unwrap() = vec![
4748
mention("1", chatsvc::MentionKind::Personal),
4749
mention("2", chatsvc::MentionKind::Team),
4750
];
4751
let engine = channel_engine(&fake).await;
4752
engine.refresh_sidebar().await.unwrap();
4753
let mentions = engine.store().sidebar().unwrap().teams[0].channel_mentions(CHANNEL);
4754
assert_eq!((mentions.personal, mentions.team), (1, 1));
4755
4756
engine.mark_all_channels_read().await.unwrap();
4757
4758
assert_eq!(fake.calls().last().unwrap(), "mark all channels read");
4759
assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);
4760
assert!(
4761
engine.store().sidebar().unwrap().teams[0]
4762
.mentions
4763
.is_empty()
4764
);
4765
engine.refresh_sidebar().await.unwrap();
4766
assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);
4767
assert!(
4768
engine.store().sidebar().unwrap().teams[0]
4769
.mentions
4770
.is_empty()
4771
);
4654
4772
}
4655
4773
4656
4774
#[tokio::test]
@@ -135,6 +135,8 @@ struct Fake {135
window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,135
window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,136
search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,136
search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,137
member_requests: Mutex<Vec<String>>,137
member_requests: Mutex<Vec<String>>,138
mention_activities: Mutex<Vec<chatsvc::MentionActivity>>,139
app_channel_horizon_ms: Mutex<i64>,138
}140
}139
141
140
impl Fake {142
impl Fake {@@ -860,6 +862,49 @@ impl Remote for Handle {860
Ok(())862
Ok(())861
}863
}862
864
865
async fn channel_pinned_posts(866
&self,867
team_thread_id: &str,868
channel_id: &str,869
) -> Result<Vec<chatsvc::PinnedMessage>> {870
self.record(format!("channel pins {team_thread_id} {channel_id}"));871
Ok(vec![chatsvc::PinnedMessage {872
message_id: "30".to_owned(),873
pinned_at: None,874
parent_id: None,875
}])876
}877
878
async fn set_post_pinned(879
&self,880
team_thread_id: &str,881
channel_id: &str,882
post_id: &str,883
pinned: bool,884
) -> Result<()> {885
self.record(format!(886
"post pin {team_thread_id} {channel_id} {post_id} {pinned}"887
));888
Ok(())889
}890
891
async fn mention_activities(&self) -> Result<Vec<chatsvc::MentionActivity>> {892
Ok(self.mention_activities.lock().unwrap().clone())893
}894
895
async fn app_consumption_horizon(&self) -> Result<chatsvc::AppConsumptionHorizon> {896
Ok(chatsvc::AppConsumptionHorizon {897
channel_ms: *self.app_channel_horizon_ms.lock().unwrap(),898
..chatsvc::AppConsumptionHorizon::default()899
})900
}901
902
async fn mark_all_channels_read(&self, now_ms: i64) -> Result<chatsvc::AppConsumptionHorizon> {903
self.record("mark all channels read".to_owned());904
*self.app_channel_horizon_ms.lock().unwrap() = now_ms;905
self.app_consumption_horizon().await906
}907
863
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {908
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {864
*self.app_calls.lock().unwrap() += 1;909
*self.app_calls.lock().unwrap() += 1;865
Ok(self.apps.lock().unwrap().clone())910
Ok(self.apps.lock().unwrap().clone())@@ -4626,7 +4671,7 @@ async fn save_uses_the_message_id_as_root_in_chats() {4626
}4671
}4627
4672
4628
#[tokio::test]4673
#[tokio::test]4629
async fn pinning_announces_and_is_refused_in_channels() {4674
async fn pinning_announces_in_chats() {4630
let fake = Arc::new(Fake::default());4675
let fake = Arc::new(Fake::default());4631
let engine = channel_engine(&fake).await;4676
let engine = channel_engine(&fake).await;4632
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];4677
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];@@ -4647,10 +4692,83 @@ async fn pinning_announces_and_is_refused_in_channels() {4647
fake.calls().last().unwrap(),4692
fake.calls().last().unwrap(),4648
&format!("unpin {CHAT} 5 Some(\"folder-1\")")4693
&format!("unpin {CHAT} 5 Some(\"folder-1\")")4649
);4694
);4650
assert!(matches!(4695
}4651
engine.pin_message(CHANNEL, "5").await,4696
4652
Err(Error::Unsupported(_))4697
#[tokio::test]4698
async fn channel_pins_use_the_post_pin_routes_of_the_team_thread() {4699
let fake = Arc::new(Fake::default());4700
let engine = channel_engine(&fake).await;4701
engine.fetch_newer(CHANNEL).await.unwrap();4702
let pins = engine.chat_pins(CHANNEL).await.unwrap();4703
assert_eq!(pins[0].message_id, "30");4704
assert_eq!(4705
fake.calls().last().unwrap(),4706
&format!("channel pins {CHANNEL} {CHANNEL}")4707
);4708
let mut events = engine.subscribe();4709
engine.pin_message(CHANNEL, "30").await.unwrap();4710
assert_eq!(4711
fake.calls().last().unwrap(),4712
&format!("post pin {CHANNEL} {CHANNEL} 30 true")4713
);4714
assert_eq!(4715
events.try_recv().unwrap(),4716
CoreEvent::PinsChanged {4717
conversation_id: CHANNEL.to_owned()4718
}4719
);4720
engine.unpin_message(CHANNEL, "30", None).await.unwrap();4721
assert_eq!(4722
fake.calls().last().unwrap(),4723
&format!("post pin {CHANNEL} {CHANNEL} 30 false")4724
);4725
}4726
4727
#[tokio::test]4728
async fn channel_mentions_follow_the_activity_feed_and_mark_all_as_read() {4729
let fake = Arc::new(Fake::default());4730
fake.read_states.lock().unwrap().push((4731
CHANNEL.to_owned(),4732
chatsvc::ReadHorizon {4733
consumed_until_ms: 5,4734
last_message_ms: 9,4735
last_message_from: Some("8:orgid:user-ada".to_owned()),4736
..chatsvc::ReadHorizon::default()4737
},4653
));4738
));4739
let mention = |activity_id: &str, kind: chatsvc::MentionKind| chatsvc::MentionActivity {4740
activity_id: activity_id.to_owned(),4741
kind,4742
source_thread_id: CHANNEL.to_owned(),4743
source_message_id: None,4744
timestamp_ms: 8,4745
is_read: false,4746
};4747
*fake.mention_activities.lock().unwrap() = vec![4748
mention("1", chatsvc::MentionKind::Personal),4749
mention("2", chatsvc::MentionKind::Team),4750
];4751
let engine = channel_engine(&fake).await;4752
engine.refresh_sidebar().await.unwrap();4753
let mentions = engine.store().sidebar().unwrap().teams[0].channel_mentions(CHANNEL);4754
assert_eq!((mentions.personal, mentions.team), (1, 1));4755
4756
engine.mark_all_channels_read().await.unwrap();4757
4758
assert_eq!(fake.calls().last().unwrap(), "mark all channels read");4759
assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);4760
assert!(4761
engine.store().sidebar().unwrap().teams[0]4762
.mentions4763
.is_empty()4764
);4765
engine.refresh_sidebar().await.unwrap();4766
assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);4767
assert!(4768
engine.store().sidebar().unwrap().teams[0]4769
.mentions4770
.is_empty()4771
);4654
}4772
}4655
4773
4656
#[tokio::test]4774
#[tokio::test]@@ -27,7 +27,7 @@ pub use error::{Error, Result};
27
27
pub use image_files::ImageFileCache;
28
28
pub use models::{
29
29
ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,
30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelNotificationLevel,
30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
31
31
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
32
32
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
33
33
OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,
@@ -27,7 +27,7 @@ pub use error::{Error, Result};27
pub use image_files::ImageFileCache;27
pub use image_files::ImageFileCache;28
pub use models::{28
pub use models::{29
ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,29
ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelNotificationLevel,30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,31
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,31
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,32
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,32
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,33
OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,33
OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,@@ -97,6 +97,10 @@ const MIGRATIONS: &[Migration] = &[
97
97
script: include_str!("migrations/0022_read_horizons.sql"),
98
98
after: None,
99
99
},
100
Migration {
101
script: include_str!("migrations/0023_channel_mentions.sql"),
102
after: None,
103
},
100
104
];
101
105
102
106
pub fn latest_version() -> i64 {
@@ -97,6 +97,10 @@ const MIGRATIONS: &[Migration] = &[97
script: include_str!("migrations/0022_read_horizons.sql"),97
script: include_str!("migrations/0022_read_horizons.sql"),98
after: None,98
after: None,99
},99
},100
Migration {101
script: include_str!("migrations/0023_channel_mentions.sql"),102
after: None,103
},100
];104
];101
105
102
pub fn latest_version() -> i64 {106
pub fn latest_version() -> i64 {@@ -0,0 +1,6 @@
1
CREATE TABLE IF NOT EXISTS channel_mentions (
2
channel_id TEXT PRIMARY KEY NOT NULL,
3
personal INTEGER NOT NULL DEFAULT 0,
4
channel INTEGER NOT NULL DEFAULT 0,
5
team INTEGER NOT NULL DEFAULT 0
6
);
@@ -0,0 +1,6 @@1
CREATE TABLE IF NOT EXISTS channel_mentions (2
channel_id TEXT PRIMARY KEY NOT NULL,3
personal INTEGER NOT NULL DEFAULT 0,4
channel INTEGER NOT NULL DEFAULT 0,5
team INTEGER NOT NULL DEFAULT 06
);@@ -147,6 +147,7 @@ pub struct SidebarTeam {
147
147
pub hidden: bool,
148
148
pub hidden_channel_ids: Vec<String>,
149
149
pub notifications: HashMap<String, ChannelNotifications>,
150
pub mentions: HashMap<String, ChannelMentions>,
150
151
}
151
152
152
153
impl SidebarTeam {
@@ -156,6 +157,24 @@ impl SidebarTeam {
156
157
.copied()
157
158
.unwrap_or_default()
158
159
}
160
161
pub fn channel_mentions(&self, channel_id: &str) -> ChannelMentions {
162
self.mentions.get(channel_id).copied().unwrap_or_default()
163
}
164
}
165
166
/// Unread @mentions of one channel: personal (person or tag), @channel, @team.
167
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
168
pub struct ChannelMentions {
169
pub personal: u32,
170
pub channel: u32,
171
pub team: u32,
172
}
173
174
impl ChannelMentions {
175
pub fn is_empty(&self) -> bool {
176
*self == ChannelMentions::default()
177
}
159
178
}
160
179
161
180
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -147,6 +147,7 @@ pub struct SidebarTeam {147
pub hidden: bool,147
pub hidden: bool,148
pub hidden_channel_ids: Vec<String>,148
pub hidden_channel_ids: Vec<String>,149
pub notifications: HashMap<String, ChannelNotifications>,149
pub notifications: HashMap<String, ChannelNotifications>,150
pub mentions: HashMap<String, ChannelMentions>,150
}151
}151
152
152
impl SidebarTeam {153
impl SidebarTeam {@@ -156,6 +157,24 @@ impl SidebarTeam {156
.copied()157
.copied()157
.unwrap_or_default()158
.unwrap_or_default()158
}159
}160
161
pub fn channel_mentions(&self, channel_id: &str) -> ChannelMentions {162
self.mentions.get(channel_id).copied().unwrap_or_default()163
}164
}165
166
/// Unread @mentions of one channel: personal (person or tag), @channel, @team.167
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]168
pub struct ChannelMentions {169
pub personal: u32,170
pub channel: u32,171
pub team: u32,172
}173
174
impl ChannelMentions {175
pub fn is_empty(&self) -> bool {176
*self == ChannelMentions::default()177
}159
}178
}160
179
161
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]180
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]@@ -5,8 +5,8 @@ use rusqlite::params;
5
5
6
6
use crate::error::Result;
7
7
use crate::models::{
8
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, Sidebar,
9
SidebarTeam, TeamLayoutRecord, TeamRecord,
8
ChannelMentions, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
9
ChannelTabRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord,
10
10
};
11
11
use crate::store::Store;
12
12
use crate::teams::channel_from_row;
@@ -83,6 +83,19 @@ impl Store {
83
83
.then_with(|| compare_names(&left.channel.name, &right.channel.name))
84
84
.then_with(|| left.channel.id.cmp(&right.channel.id))
85
85
});
86
let mut mentions: HashMap<String, ChannelMentions> = connection
87
.prepare_cached("SELECT channel_id, personal, channel, team FROM channel_mentions")?
88
.query_map([], |row| {
89
Ok((
90
row.get::<_, String>(0)?,
91
ChannelMentions {
92
personal: row.get(1)?,
93
channel: row.get(2)?,
94
team: row.get(3)?,
95
},
96
))
97
})?
98
.collect::<rusqlite::Result<_>>()?;
86
99
let mut teams: Vec<SidebarTeam> = team_rows
87
100
.into_iter()
88
101
.map(|row| SidebarTeam {
@@ -91,6 +104,7 @@ impl Store {
91
104
hidden: row.hidden,
92
105
hidden_channel_ids: Vec::new(),
93
106
notifications: HashMap::new(),
107
mentions: HashMap::new(),
94
108
})
95
109
.collect();
96
110
for row in channel_rows {
@@ -105,6 +119,9 @@ impl Store {
105
119
team.notifications
106
120
.insert(row.channel.id.clone(), row.notifications);
107
121
}
122
if let Some(found) = mentions.remove(&row.channel.id) {
123
team.mentions.insert(row.channel.id.clone(), found);
124
}
108
125
team.channels.push(row.channel);
109
126
}
110
127
}
@@ -156,6 +173,47 @@ impl Store {
156
173
Ok(transaction.commit()?)
157
174
}
158
175
176
/// Replaces every stored mention count; channels left out have none.
177
pub fn replace_channel_mentions(&self, mentions: &[(String, ChannelMentions)]) -> Result<()> {
178
let mut connection = self.lock()?;
179
let transaction = connection.transaction()?;
180
transaction.execute("DELETE FROM channel_mentions", [])?;
181
{
182
let mut insert = transaction.prepare_cached(
183
"INSERT OR REPLACE INTO channel_mentions (channel_id, personal, channel, team)
184
VALUES (?1, ?2, ?3, ?4)",
185
)?;
186
for (channel_id, counts) in mentions.iter().filter(|(_, counts)| !counts.is_empty()) {
187
insert.execute(params![channel_id, counts.personal, counts.channel, counts.team])?;
188
}
189
}
190
Ok(transaction.commit()?)
191
}
192
193
pub fn clear_channel_mentions(&self, channel_id: &str) -> Result<()> {
194
self.lock()?.execute(
195
"DELETE FROM channel_mentions WHERE channel_id = ?1",
196
[channel_id],
197
)?;
198
Ok(())
199
}
200
201
/// The team's own thread id, which Teams' CSA routes take: the id of its General channel.
202
pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {
203
let connection = self.lock()?;
204
Ok(connection
205
.prepare_cached(
206
"SELECT channels.id FROM channels
207
LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id
208
WHERE channels.team_id = ?1
209
AND COALESCE(channel_layout.general, channels.name = ?2)
210
ORDER BY channels.id LIMIT 1",
211
)?
212
.query_map(params![team_id, GENERAL_FALLBACK_NAME], |row| row.get(0))?
213
.next()
214
.transpose()?)
215
}
216
159
217
pub fn set_channel_notifications(
160
218
&self,
161
219
channel_id: &str,
@@ -5,8 +5,8 @@ use rusqlite::params;5
5
6
use crate::error::Result;6
use crate::error::Result;7
use crate::models::{7
use crate::models::{8
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, Sidebar,8
ChannelMentions, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,9
SidebarTeam, TeamLayoutRecord, TeamRecord,9
ChannelTabRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord,10
};10
};11
use crate::store::Store;11
use crate::store::Store;12
use crate::teams::channel_from_row;12
use crate::teams::channel_from_row;@@ -83,6 +83,19 @@ impl Store {83
.then_with(|| compare_names(&left.channel.name, &right.channel.name))83
.then_with(|| compare_names(&left.channel.name, &right.channel.name))84
.then_with(|| left.channel.id.cmp(&right.channel.id))84
.then_with(|| left.channel.id.cmp(&right.channel.id))85
});85
});86
let mut mentions: HashMap<String, ChannelMentions> = connection87
.prepare_cached("SELECT channel_id, personal, channel, team FROM channel_mentions")?88
.query_map([], |row| {89
Ok((90
row.get::<_, String>(0)?,91
ChannelMentions {92
personal: row.get(1)?,93
channel: row.get(2)?,94
team: row.get(3)?,95
},96
))97
})?98
.collect::<rusqlite::Result<_>>()?;86
let mut teams: Vec<SidebarTeam> = team_rows99
let mut teams: Vec<SidebarTeam> = team_rows87
.into_iter()100
.into_iter()88
.map(|row| SidebarTeam {101
.map(|row| SidebarTeam {@@ -91,6 +104,7 @@ impl Store {91
hidden: row.hidden,104
hidden: row.hidden,92
hidden_channel_ids: Vec::new(),105
hidden_channel_ids: Vec::new(),93
notifications: HashMap::new(),106
notifications: HashMap::new(),107
mentions: HashMap::new(),94
})108
})95
.collect();109
.collect();96
for row in channel_rows {110
for row in channel_rows {@@ -105,6 +119,9 @@ impl Store {105
team.notifications119
team.notifications106
.insert(row.channel.id.clone(), row.notifications);120
.insert(row.channel.id.clone(), row.notifications);107
}121
}122
if let Some(found) = mentions.remove(&row.channel.id) {123
team.mentions.insert(row.channel.id.clone(), found);124
}108
team.channels.push(row.channel);125
team.channels.push(row.channel);109
}126
}110
}127
}@@ -156,6 +173,47 @@ impl Store {156
Ok(transaction.commit()?)173
Ok(transaction.commit()?)157
}174
}158
175
176
/// Replaces every stored mention count; channels left out have none.177
pub fn replace_channel_mentions(&self, mentions: &[(String, ChannelMentions)]) -> Result<()> {178
let mut connection = self.lock()?;179
let transaction = connection.transaction()?;180
transaction.execute("DELETE FROM channel_mentions", [])?;181
{182
let mut insert = transaction.prepare_cached(183
"INSERT OR REPLACE INTO channel_mentions (channel_id, personal, channel, team)184
VALUES (?1, ?2, ?3, ?4)",185
)?;186
for (channel_id, counts) in mentions.iter().filter(|(_, counts)| !counts.is_empty()) {187
insert.execute(params![channel_id, counts.personal, counts.channel, counts.team])?;188
}189
}190
Ok(transaction.commit()?)191
}192
193
pub fn clear_channel_mentions(&self, channel_id: &str) -> Result<()> {194
self.lock()?.execute(195
"DELETE FROM channel_mentions WHERE channel_id = ?1",196
[channel_id],197
)?;198
Ok(())199
}200
201
/// The team's own thread id, which Teams' CSA routes take: the id of its General channel.202
pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {203
let connection = self.lock()?;204
Ok(connection205
.prepare_cached(206
"SELECT channels.id FROM channels207
LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id208
WHERE channels.team_id = ?1209
AND COALESCE(channel_layout.general, channels.name = ?2)210
ORDER BY channels.id LIMIT 1",211
)?212
.query_map(params![team_id, GENERAL_FALLBACK_NAME], |row| row.get(0))?213
.next()214
.transpose()?)215
}216
159
pub fn set_channel_notifications(217
pub fn set_channel_notifications(160
&self,218
&self,161
channel_id: &str,219
channel_id: &str,@@ -78,6 +78,14 @@ impl Store {
78
78
Ok(())
79
79
}
80
80
81
pub fn mark_all_channels_read(&self) -> Result<()> {
82
let mut connection = self.lock()?;
83
let transaction = connection.transaction()?;
84
transaction.execute("UPDATE channels SET unread = 0 WHERE unread != 0", [])?;
85
transaction.execute("DELETE FROM channel_mentions", [])?;
86
Ok(transaction.commit()?)
87
}
88
81
89
pub fn remove_teams_except(&self, kept_team_ids: &[String]) -> Result<usize> {
82
90
let mut connection = self.lock()?;
83
91
let transaction = connection.transaction()?;
@@ -78,6 +78,14 @@ impl Store {78
Ok(())78
Ok(())79
}79
}80
80
81
pub fn mark_all_channels_read(&self) -> Result<()> {82
let mut connection = self.lock()?;83
let transaction = connection.transaction()?;84
transaction.execute("UPDATE channels SET unread = 0 WHERE unread != 0", [])?;85
transaction.execute("DELETE FROM channel_mentions", [])?;86
Ok(transaction.commit()?)87
}88
81
pub fn remove_teams_except(&self, kept_team_ids: &[String]) -> Result<usize> {89
pub fn remove_teams_except(&self, kept_team_ids: &[String]) -> Result<usize> {82
let mut connection = self.lock()?;90
let mut connection = self.lock()?;83
let transaction = connection.transaction()?;91
let transaction = connection.transaction()?;@@ -1,10 +1,10 @@
1
1
use chrono::{DateTime, TimeZone, Utc};
2
2
use rusqlite::Connection;
3
3
use store::{
4
AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,
5
ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
6
MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,
7
TeamRecord, UNKNOWN_USER_NAME,
4
AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
5
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,
6
MemberRecord, MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState,
7
TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,
8
8
};
9
9
10
10
#[test]
@@ -546,11 +546,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
546
546
let path = directory.path().join("nested").join("cache.sqlite3");
547
547
{
548
548
let store = Store::open(&path).unwrap();
549
assert_eq!(store.schema_version().unwrap(), 22);
549
assert_eq!(store.schema_version().unwrap(), 23);
550
550
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
551
551
}
552
552
let reopened = Store::open(&path).unwrap();
553
assert_eq!(reopened.schema_version().unwrap(), 22);
553
assert_eq!(reopened.schema_version().unwrap(), 23);
554
554
assert_eq!(reopened.message_count("c").unwrap(), 1);
555
555
drop(reopened);
556
556
let mode: String = rusqlite_open(&path)
@@ -582,7 +582,7 @@ fn old_schema_is_upgraded_in_place() {
582
582
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
583
583
drop(connection);
584
584
let store = Store::open(&path).unwrap();
585
assert_eq!(store.schema_version().unwrap(), 22);
585
assert_eq!(store.schema_version().unwrap(), 23);
586
586
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
587
587
}
588
588
@@ -648,7 +648,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
648
648
let store = Store::open(&path).unwrap();
649
649
let state = store.sync_state("c").unwrap().unwrap();
650
650
assert_eq!(state.delta_link, None);
651
assert_eq!(store.schema_version().unwrap(), 22);
651
assert_eq!(store.schema_version().unwrap(), 23);
652
652
}
653
653
654
654
#[test]
@@ -677,7 +677,10 @@ fn migration_to_v13_clears_channel_delta_links_only() {
677
677
}
678
678
let store = Store::open(&path).unwrap();
679
679
assert_eq!(
680
store.sync_state("ch").unwrap().and_then(|state| state.delta_link),
680
store
681
.sync_state("ch")
682
.unwrap()
683
.and_then(|state| state.delta_link),
681
684
None
682
685
);
683
686
assert_eq!(
@@ -1302,6 +1305,98 @@ fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {
1302
1305
assert_eq!(team().channel_notifications("c2"), off);
1303
1306
}
1304
1307
1308
#[test]
1309
fn channel_mentions_are_replaced_whole_and_cleared_per_channel() {
1310
let store = Store::open_in_memory().unwrap();
1311
store
1312
.upsert_teams(&[TeamRecord {
1313
id: "t1".to_owned(),
1314
name: "Alpha".to_owned(),
1315
}])
1316
.unwrap();
1317
let channel = |id: &str, name: &str| ChannelRecord {
1318
id: id.to_owned(),
1319
team_id: "t1".to_owned(),
1320
name: name.to_owned(),
1321
membership_type: None,
1322
last_message_at: None,
1323
unread: true,
1324
};
1325
store
1326
.upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1327
.unwrap();
1328
let counts = |personal, channel, team| ChannelMentions {
1329
personal,
1330
channel,
1331
team,
1332
};
1333
store
1334
.replace_channel_mentions(&[
1335
("c1".to_owned(), counts(2, 0, 1)),
1336
("c2".to_owned(), counts(0, 0, 0)),
1337
])
1338
.unwrap();
1339
let team = || store.sidebar().unwrap().teams.remove(0);
1340
assert_eq!(team().channel_mentions("c1"), counts(2, 0, 1));
1341
assert!(!team().mentions.contains_key("c2"));
1342
store
1343
.replace_channel_mentions(&[("c2".to_owned(), counts(0, 1, 0))])
1344
.unwrap();
1345
assert_eq!(team().channel_mentions("c1"), ChannelMentions::default());
1346
assert_eq!(team().channel_mentions("c2"), counts(0, 1, 0));
1347
store.clear_channel_mentions("c2").unwrap();
1348
assert!(team().mentions.is_empty());
1349
}
1350
1351
#[test]
1352
fn the_team_thread_id_is_the_general_channel_id() {
1353
let store = Store::open_in_memory().unwrap();
1354
store
1355
.upsert_teams(&["group-a", "group-b"].map(|id| TeamRecord {
1356
id: id.to_owned(),
1357
name: id.to_owned(),
1358
}))
1359
.unwrap();
1360
let channel = |id: &str, team_id: &str, name: &str| ChannelRecord {
1361
id: id.to_owned(),
1362
team_id: team_id.to_owned(),
1363
name: name.to_owned(),
1364
membership_type: None,
1365
last_message_at: None,
1366
unread: false,
1367
};
1368
store
1369
.upsert_channels(&[
1370
channel("19:a-random", "group-a", "Random"),
1371
channel("19:a-general", "group-a", "General"),
1372
channel("19:b-renamed", "group-b", "Allgemein"),
1373
channel("19:b-other", "group-b", "Other"),
1374
])
1375
.unwrap();
1376
store
1377
.replace_team_layout(&[TeamLayoutRecord {
1378
team_id: "group-b".to_owned(),
1379
hidden: false,
1380
channels: vec![ChannelLayoutRecord {
1381
channel_id: "19:b-renamed".to_owned(),
1382
general: true,
1383
hidden: false,
1384
tabs: Vec::new(),
1385
notifications: ChannelNotifications::default(),
1386
}],
1387
}])
1388
.unwrap();
1389
assert_eq!(
1390
store.team_thread_id("group-a").unwrap().as_deref(),
1391
Some("19:a-general")
1392
);
1393
assert_eq!(
1394
store.team_thread_id("group-b").unwrap().as_deref(),
1395
Some("19:b-renamed")
1396
);
1397
assert_eq!(store.team_thread_id("group-c").unwrap(), None);
1398
}
1399
1305
1400
#[test]
1306
1401
fn recent_messages_run_newest_first_across_scopes_with_a_cursor() {
1307
1402
let store = Store::open_in_memory().unwrap();
@@ -1411,23 +1506,33 @@ fn migration_to_v20_adds_the_call_event_column() {
1411
1506
{
1412
1507
let store = Store::open(&path).unwrap();
1413
1508
store.upsert_messages(&[message("c", "old", 1)]).unwrap();
1414
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1509
store
1510
.upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1511
.unwrap();
1415
1512
store.set_sync_state("c", &SyncState::default()).unwrap();
1416
store.set_sync_state("channel", &SyncState::default()).unwrap();
1513
store
1514
.set_sync_state("channel", &SyncState::default())
1515
.unwrap();
1417
1516
drop(store);
1418
1517
Connection::open(&path)
1419
1518
.unwrap()
1420
.execute_batch("ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19")
1519
.execute_batch(
1520
"ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19",
1521
)
1421
1522
.unwrap();
1422
1523
}
1423
1524
let store = Store::open(&path).unwrap();
1424
assert_eq!(store.schema_version().unwrap(), 22);
1525
assert_eq!(store.schema_version().unwrap(), 23);
1425
1526
let old = store.messages("c", None, 10).unwrap();
1426
1527
assert_eq!(old[0].call_event_json, None);
1427
1528
assert!(store.sync_state("c").unwrap().is_none());
1428
1529
assert!(store.sync_state("channel").unwrap().is_some());
1429
1530
store.upsert_messages(&[call_message("call", 2)]).unwrap();
1430
assert!(store.messages("c", None, 10).unwrap()[1].call_event_json.is_some());
1531
assert!(
1532
store.messages("c", None, 10).unwrap()[1]
1533
.call_event_json
1534
.is_some()
1535
);
1431
1536
}
1432
1537
1433
1538
#[test]
@@ -1436,7 +1541,9 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1436
1541
let path = directory.path().join("old.sqlite3");
1437
1542
{
1438
1543
let store = Store::open(&path).unwrap();
1439
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1544
store
1545
.upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1546
.unwrap();
1440
1547
store
1441
1548
.upsert_teams(&[TeamRecord {
1442
1549
id: "team".to_owned(),
@@ -1465,7 +1572,7 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1465
1572
.unwrap();
1466
1573
}
1467
1574
let store = Store::open(&path).unwrap();
1468
assert_eq!(store.schema_version().unwrap(), 22);
1575
assert_eq!(store.schema_version().unwrap(), 23);
1469
1576
assert!(store.sync_state("c").unwrap().is_none());
1470
1577
assert!(store.sync_state("channel").unwrap().is_none());
1471
1578
assert!(store.sync_state("other").unwrap().is_some());
@@ -1485,7 +1592,9 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1485
1592
let path = directory.path().join("old.sqlite3");
1486
1593
{
1487
1594
let store = Store::open(&path).unwrap();
1488
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1595
store
1596
.upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1597
.unwrap();
1489
1598
drop(store);
1490
1599
Connection::open(&path)
1491
1600
.unwrap()
@@ -1493,9 +1602,12 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1493
1602
.unwrap();
1494
1603
}
1495
1604
let store = Store::open(&path).unwrap();
1496
assert_eq!(store.schema_version().unwrap(), 22);
1605
assert_eq!(store.schema_version().unwrap(), 23);
1497
1606
assert!(store.read_horizons("c").unwrap().is_empty());
1498
let horizons = [horizon("8:orgid:ada", 3, Some(4)), horizon("8:orgid:bob", 2, None)];
1607
let horizons = [
1608
horizon("8:orgid:ada", 3, Some(4)),
1609
horizon("8:orgid:bob", 2, None),
1610
];
1499
1611
store.set_read_horizons("c", &horizons).unwrap();
1500
1612
drop(store);
1501
1613
let reopened = Store::open(&path).unwrap();
@@ -1505,9 +1617,14 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1505
1617
#[test]
1506
1618
fn setting_read_horizons_replaces_the_conversation_only() {
1507
1619
let store = Store::open_in_memory().unwrap();
1508
let first = [horizon("8:orgid:ada", 3, None), horizon("8:orgid:bob", 2, None)];
1620
let first = [
1621
horizon("8:orgid:ada", 3, None),
1622
horizon("8:orgid:bob", 2, None),
1623
];
1509
1624
store.set_read_horizons("c", &first).unwrap();
1510
store.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)]).unwrap();
1625
store
1626
.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)])
1627
.unwrap();
1511
1628
let second = [horizon("8:orgid:ada", 5, Some(6))];
1512
1629
store.set_read_horizons("c", &second).unwrap();
1513
1630
assert_eq!(store.read_horizons("c").unwrap(), second);
@@ -1,10 +1,10 @@1
use chrono::{DateTime, TimeZone, Utc};1
use chrono::{DateTime, TimeZone, Utc};2
use rusqlite::Connection;2
use rusqlite::Connection;3
use store::{3
use store::{4
AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,4
AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,5
ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,5
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,6
MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,6
MemberRecord, MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState,7
TeamRecord, UNKNOWN_USER_NAME,7
TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,8
};8
};9
9
10
#[test]10
#[test]@@ -546,11 +546,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {546
let path = directory.path().join("nested").join("cache.sqlite3");546
let path = directory.path().join("nested").join("cache.sqlite3");547
{547
{548
let store = Store::open(&path).unwrap();548
let store = Store::open(&path).unwrap();549
assert_eq!(store.schema_version().unwrap(), 22);549
assert_eq!(store.schema_version().unwrap(), 23);550
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();550
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();551
}551
}552
let reopened = Store::open(&path).unwrap();552
let reopened = Store::open(&path).unwrap();553
assert_eq!(reopened.schema_version().unwrap(), 22);553
assert_eq!(reopened.schema_version().unwrap(), 23);554
assert_eq!(reopened.message_count("c").unwrap(), 1);554
assert_eq!(reopened.message_count("c").unwrap(), 1);555
drop(reopened);555
drop(reopened);556
let mode: String = rusqlite_open(&path)556
let mode: String = rusqlite_open(&path)@@ -582,7 +582,7 @@ fn old_schema_is_upgraded_in_place() {582
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();582
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();583
drop(connection);583
drop(connection);584
let store = Store::open(&path).unwrap();584
let store = Store::open(&path).unwrap();585
assert_eq!(store.schema_version().unwrap(), 22);585
assert_eq!(store.schema_version().unwrap(), 23);586
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();586
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();587
}587
}588
588
@@ -648,7 +648,7 @@ fn migration_to_v2_keeps_existing_sync_state() {648
let store = Store::open(&path).unwrap();648
let store = Store::open(&path).unwrap();649
let state = store.sync_state("c").unwrap().unwrap();649
let state = store.sync_state("c").unwrap().unwrap();650
assert_eq!(state.delta_link, None);650
assert_eq!(state.delta_link, None);651
assert_eq!(store.schema_version().unwrap(), 22);651
assert_eq!(store.schema_version().unwrap(), 23);652
}652
}653
653
654
#[test]654
#[test]@@ -677,7 +677,10 @@ fn migration_to_v13_clears_channel_delta_links_only() {677
}677
}678
let store = Store::open(&path).unwrap();678
let store = Store::open(&path).unwrap();679
assert_eq!(679
assert_eq!(680
store.sync_state("ch").unwrap().and_then(|state| state.delta_link),680
store681
.sync_state("ch")682
.unwrap()683
.and_then(|state| state.delta_link),681
None684
None682
);685
);683
assert_eq!(686
assert_eq!(@@ -1302,6 +1305,98 @@ fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {1302
assert_eq!(team().channel_notifications("c2"), off);1305
assert_eq!(team().channel_notifications("c2"), off);1303
}1306
}1304
1307
1308
#[test]1309
fn channel_mentions_are_replaced_whole_and_cleared_per_channel() {1310
let store = Store::open_in_memory().unwrap();1311
store1312
.upsert_teams(&[TeamRecord {1313
id: "t1".to_owned(),1314
name: "Alpha".to_owned(),1315
}])1316
.unwrap();1317
let channel = |id: &str, name: &str| ChannelRecord {1318
id: id.to_owned(),1319
team_id: "t1".to_owned(),1320
name: name.to_owned(),1321
membership_type: None,1322
last_message_at: None,1323
unread: true,1324
};1325
store1326
.upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])1327
.unwrap();1328
let counts = |personal, channel, team| ChannelMentions {1329
personal,1330
channel,1331
team,1332
};1333
store1334
.replace_channel_mentions(&[1335
("c1".to_owned(), counts(2, 0, 1)),1336
("c2".to_owned(), counts(0, 0, 0)),1337
])1338
.unwrap();1339
let team = || store.sidebar().unwrap().teams.remove(0);1340
assert_eq!(team().channel_mentions("c1"), counts(2, 0, 1));1341
assert!(!team().mentions.contains_key("c2"));1342
store1343
.replace_channel_mentions(&[("c2".to_owned(), counts(0, 1, 0))])1344
.unwrap();1345
assert_eq!(team().channel_mentions("c1"), ChannelMentions::default());1346
assert_eq!(team().channel_mentions("c2"), counts(0, 1, 0));1347
store.clear_channel_mentions("c2").unwrap();1348
assert!(team().mentions.is_empty());1349
}1350
1351
#[test]1352
fn the_team_thread_id_is_the_general_channel_id() {1353
let store = Store::open_in_memory().unwrap();1354
store1355
.upsert_teams(&["group-a", "group-b"].map(|id| TeamRecord {1356
id: id.to_owned(),1357
name: id.to_owned(),1358
}))1359
.unwrap();1360
let channel = |id: &str, team_id: &str, name: &str| ChannelRecord {1361
id: id.to_owned(),1362
team_id: team_id.to_owned(),1363
name: name.to_owned(),1364
membership_type: None,1365
last_message_at: None,1366
unread: false,1367
};1368
store1369
.upsert_channels(&[1370
channel("19:a-random", "group-a", "Random"),1371
channel("19:a-general", "group-a", "General"),1372
channel("19:b-renamed", "group-b", "Allgemein"),1373
channel("19:b-other", "group-b", "Other"),1374
])1375
.unwrap();1376
store1377
.replace_team_layout(&[TeamLayoutRecord {1378
team_id: "group-b".to_owned(),1379
hidden: false,1380
channels: vec![ChannelLayoutRecord {1381
channel_id: "19:b-renamed".to_owned(),1382
general: true,1383
hidden: false,1384
tabs: Vec::new(),1385
notifications: ChannelNotifications::default(),1386
}],1387
}])1388
.unwrap();1389
assert_eq!(1390
store.team_thread_id("group-a").unwrap().as_deref(),1391
Some("19:a-general")1392
);1393
assert_eq!(1394
store.team_thread_id("group-b").unwrap().as_deref(),1395
Some("19:b-renamed")1396
);1397
assert_eq!(store.team_thread_id("group-c").unwrap(), None);1398
}1399
1305
#[test]1400
#[test]1306
fn recent_messages_run_newest_first_across_scopes_with_a_cursor() {1401
fn recent_messages_run_newest_first_across_scopes_with_a_cursor() {1307
let store = Store::open_in_memory().unwrap();1402
let store = Store::open_in_memory().unwrap();@@ -1411,23 +1506,33 @@ fn migration_to_v20_adds_the_call_event_column() {1411
{1506
{1412
let store = Store::open(&path).unwrap();1507
let store = Store::open(&path).unwrap();1413
store.upsert_messages(&[message("c", "old", 1)]).unwrap();1508
store.upsert_messages(&[message("c", "old", 1)]).unwrap();1414
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();1509
store1510
.upsert_chats(&[chat("c", "Chat", Some(at(1)))])1511
.unwrap();1415
store.set_sync_state("c", &SyncState::default()).unwrap();1512
store.set_sync_state("c", &SyncState::default()).unwrap();1416
store.set_sync_state("channel", &SyncState::default()).unwrap();1513
store1514
.set_sync_state("channel", &SyncState::default())1515
.unwrap();1417
drop(store);1516
drop(store);1418
Connection::open(&path)1517
Connection::open(&path)1419
.unwrap()1518
.unwrap()1420
.execute_batch("ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19")1519
.execute_batch(1520
"ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19",1521
)1421
.unwrap();1522
.unwrap();1422
}1523
}1423
let store = Store::open(&path).unwrap();1524
let store = Store::open(&path).unwrap();1424
assert_eq!(store.schema_version().unwrap(), 22);1525
assert_eq!(store.schema_version().unwrap(), 23);1425
let old = store.messages("c", None, 10).unwrap();1526
let old = store.messages("c", None, 10).unwrap();1426
assert_eq!(old[0].call_event_json, None);1527
assert_eq!(old[0].call_event_json, None);1427
assert!(store.sync_state("c").unwrap().is_none());1528
assert!(store.sync_state("c").unwrap().is_none());1428
assert!(store.sync_state("channel").unwrap().is_some());1529
assert!(store.sync_state("channel").unwrap().is_some());1429
store.upsert_messages(&[call_message("call", 2)]).unwrap();1530
store.upsert_messages(&[call_message("call", 2)]).unwrap();1430
assert!(store.messages("c", None, 10).unwrap()[1].call_event_json.is_some());1531
assert!(1532
store.messages("c", None, 10).unwrap()[1]1533
.call_event_json1534
.is_some()1535
);1431
}1536
}1432
1537
1433
#[test]1538
#[test]@@ -1436,7 +1541,9 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {1436
let path = directory.path().join("old.sqlite3");1541
let path = directory.path().join("old.sqlite3");1437
{1542
{1438
let store = Store::open(&path).unwrap();1543
let store = Store::open(&path).unwrap();1439
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();1544
store1545
.upsert_chats(&[chat("c", "Chat", Some(at(1)))])1546
.unwrap();1440
store1547
store1441
.upsert_teams(&[TeamRecord {1548
.upsert_teams(&[TeamRecord {1442
id: "team".to_owned(),1549
id: "team".to_owned(),@@ -1465,7 +1572,7 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {1465
.unwrap();1572
.unwrap();1466
}1573
}1467
let store = Store::open(&path).unwrap();1574
let store = Store::open(&path).unwrap();1468
assert_eq!(store.schema_version().unwrap(), 22);1575
assert_eq!(store.schema_version().unwrap(), 23);1469
assert!(store.sync_state("c").unwrap().is_none());1576
assert!(store.sync_state("c").unwrap().is_none());1470
assert!(store.sync_state("channel").unwrap().is_none());1577
assert!(store.sync_state("channel").unwrap().is_none());1471
assert!(store.sync_state("other").unwrap().is_some());1578
assert!(store.sync_state("other").unwrap().is_some());@@ -1485,7 +1592,9 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {1485
let path = directory.path().join("old.sqlite3");1592
let path = directory.path().join("old.sqlite3");1486
{1593
{1487
let store = Store::open(&path).unwrap();1594
let store = Store::open(&path).unwrap();1488
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();1595
store1596
.upsert_chats(&[chat("c", "Chat", Some(at(1)))])1597
.unwrap();1489
drop(store);1598
drop(store);1490
Connection::open(&path)1599
Connection::open(&path)1491
.unwrap()1600
.unwrap()@@ -1493,9 +1602,12 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {1493
.unwrap();1602
.unwrap();1494
}1603
}1495
let store = Store::open(&path).unwrap();1604
let store = Store::open(&path).unwrap();1496
assert_eq!(store.schema_version().unwrap(), 22);1605
assert_eq!(store.schema_version().unwrap(), 23);1497
assert!(store.read_horizons("c").unwrap().is_empty());1606
assert!(store.read_horizons("c").unwrap().is_empty());1498
let horizons = [horizon("8:orgid:ada", 3, Some(4)), horizon("8:orgid:bob", 2, None)];1607
let horizons = [1608
horizon("8:orgid:ada", 3, Some(4)),1609
horizon("8:orgid:bob", 2, None),1610
];1499
store.set_read_horizons("c", &horizons).unwrap();1611
store.set_read_horizons("c", &horizons).unwrap();1500
drop(store);1612
drop(store);1501
let reopened = Store::open(&path).unwrap();1613
let reopened = Store::open(&path).unwrap();@@ -1505,9 +1617,14 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {1505
#[test]1617
#[test]1506
fn setting_read_horizons_replaces_the_conversation_only() {1618
fn setting_read_horizons_replaces_the_conversation_only() {1507
let store = Store::open_in_memory().unwrap();1619
let store = Store::open_in_memory().unwrap();1508
let first = [horizon("8:orgid:ada", 3, None), horizon("8:orgid:bob", 2, None)];1620
let first = [1621
horizon("8:orgid:ada", 3, None),1622
horizon("8:orgid:bob", 2, None),1623
];1509
store.set_read_horizons("c", &first).unwrap();1624
store.set_read_horizons("c", &first).unwrap();1510
store.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)]).unwrap();1625
store1626
.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)])1627
.unwrap();1511
let second = [horizon("8:orgid:ada", 5, Some(6))];1628
let second = [horizon("8:orgid:ada", 5, Some(6))];1512
store.set_read_horizons("c", &second).unwrap();1629
store.set_read_horizons("c", &second).unwrap();1513
assert_eq!(store.read_horizons("c").unwrap(), second);1630
assert_eq!(store.read_horizons("c").unwrap(), second);