BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into fix/meeting-event-rows

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
158ac9d235e5639157c33c9ab74283362edce444
28 files changed +513 −156
crates/app-state/src/activity/feed.rs +5 −1
@@ -261,7 +261,11 @@ impl Feed {
261 261 }
262 262
263 263 pub fn unread_count(&self) -> usize {
264 self.entries.iter().filter(|entry| !entry.read).count()
264 self.unread_entries().count()
265 }
266
267 pub fn unread_entries(&self) -> impl Iterator<Item = &Entry> {
268 self.entries.iter().filter(|entry| !entry.read)
265 269 }
266 270
267 271 pub fn take_dirty(&mut self) -> Vec<Entry> {
@@ -261,7 +261,11 @@ impl Feed {
261 }
261 }
262
262
263 pub fn unread_count(&self) -> usize {
263 pub fn unread_count(&self) -> usize {
264 self.entries.iter().filter(|entry| !entry.read).count()
264 self.unread_entries().count()
265 }
266
267 pub fn unread_entries(&self) -> impl Iterator<Item = &Entry> {
268 self.entries.iter().filter(|entry| !entry.read)
265 }
269 }
266
270
267 pub fn take_dirty(&mut self) -> Vec<Entry> {
271 pub fn take_dirty(&mut self) -> Vec<Entry> {
crates/app-state/src/notify/mod.rs +2 −0
@@ -3,6 +3,7 @@ pub mod layout;
3 3 pub mod rules;
4 4 pub mod settings;
5 5 pub mod stack;
6 pub mod taskbar;
6 7 pub mod text;
7 8
8 9 pub use app_base::notify::{badge, platform, sound_cache, sounds};
@@ -11,3 +12,4 @@ pub use incoming::{IncomingTracker, LateArrivals, preview_of};
11 12 #[cfg(windows)]
12 13 pub use platform::native_handle;
13 14 pub use rules::{ChatKind, Incoming, Preview, alerts};
15 pub use taskbar::taskbar_badge_count;
@@ -3,6 +3,7 @@ pub mod layout;
3pub mod rules;
3pub mod rules;
4pub mod settings;
4pub mod settings;
5pub mod stack;
5pub mod stack;
6pub mod taskbar;
6pub mod text;
7pub mod text;
7
8
8pub use app_base::notify::{badge, platform, sound_cache, sounds};
9pub use app_base::notify::{badge, platform, sound_cache, sounds};
@@ -11,3 +12,4 @@ pub use incoming::{IncomingTracker, LateArrivals, preview_of};
11#[cfg(windows)]
12#[cfg(windows)]
12pub use platform::native_handle;
13pub use platform::native_handle;
13pub use rules::{ChatKind, Incoming, Preview, alerts};
14pub use rules::{ChatKind, Incoming, Preview, alerts};
15pub use taskbar::taskbar_badge_count;
crates/app-state/src/notify/taskbar.rs added +127 −0
@@ -0,0 +1,127 @@
1 use std::collections::HashSet;
2
3 use store::Sidebar;
4
5 use crate::activity::Kind;
6 use crate::activity::feed::Feed;
7 use crate::sidebar_model::unread_chat_count;
8
9 pub fn taskbar_badge_count(sidebar: &Sidebar, feed: &Feed, adaptive_rail: bool) -> usize {
10 let channel_ids: HashSet<&str> = sidebar
11 .teams
12 .iter()
13 .flat_map(|team| team.channels.iter())
14 .map(|channel| channel.id.as_str())
15 .collect();
16 let is_channel = |conversation_id: &str| channel_ids.contains(conversation_id);
17 let activity = feed
18 .unread_entries()
19 .filter(|entry| entry.kind != Kind::Messages || is_channel(&entry.conversation_id))
20 .count();
21 let channels_with_mentions = if adaptive_rail {
22 feed.unread_entries()
23 .filter(|entry| entry.kind == Kind::Mention && is_channel(&entry.conversation_id))
24 .map(|entry| entry.conversation_id.as_str())
25 .collect::<HashSet<_>>()
26 .len()
27 } else {
28 0
29 };
30 activity + unread_chat_count(&sidebar.chats) as usize + channels_with_mentions
31 }
32
33 #[cfg(test)]
34 mod tests {
35 use chrono::Utc;
36 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
37
38 use super::*;
39 use crate::activity::Entry;
40
41 fn sidebar() -> Sidebar {
42 let chat = |id: &str, unread: bool, muted: bool| ChatRecord {
43 id: id.into(),
44 unread,
45 muted,
46 ..Default::default()
47 };
48 let channel = |id: &str| ChannelRecord {
49 id: id.into(),
50 team_id: "team".into(),
51 name: id.into(),
52 membership_type: None,
53 last_message_at: None,
54 unread: true,
55 };
56 Sidebar {
57 chats: vec![
58 chat("chat-unread", true, false),
59 chat("chat-muted", true, true),
60 chat("chat-read", false, false),
61 ],
62 teams: vec![SidebarTeam {
63 team: TeamRecord {
64 id: "team".into(),
65 name: "Team".into(),
66 },
67 channels: vec![channel("channel-a"), channel("channel-b")],
68 hidden: false,
69 hidden_channel_ids: vec!["channel-b".into()],
70 notifications: Default::default(),
71 }],
72 }
73 }
74
75 fn feed(entries: &[(&str, Kind, bool)]) -> Feed {
76 let mut feed = Feed::load(Vec::new());
77 for (conversation_id, kind, read) in entries {
78 feed.add(Entry {
79 id: 0,
80 conversation_id: (*conversation_id).into(),
81 kind: *kind,
82 message_id: String::new(),
83 actors: Vec::new(),
84 preview: String::new(),
85 glyphs: Vec::new(),
86 count: 1,
87 updated_at: Utc::now(),
88 read: *read,
89 });
90 }
91 feed
92 }
93
94 #[test]
95 fn unread_channel_posts_without_activity_do_not_count() {
96 assert_eq!(taskbar_badge_count(&sidebar(), &feed(&[]), true), 1);
97 }
98
99 #[test]
100 fn muted_chats_never_count_as_chats() {
101 let mentioned = feed(&[("chat-muted", Kind::Mention, false)]);
102 assert_eq!(taskbar_badge_count(&sidebar(), &mentioned, false), 2);
103 }
104
105 #[test]
106 fn chat_message_rows_are_counted_once_by_the_chat() {
107 let rows = feed(&[
108 ("chat-unread", Kind::Messages, false),
109 ("chat-unread", Kind::Reaction, false),
110 ("channel-a", Kind::Messages, false),
111 ("channel-a", Kind::Reaction, true),
112 ]);
113 assert_eq!(taskbar_badge_count(&sidebar(), &rows, false), 3);
114 }
115
116 #[test]
117 fn the_adaptive_rail_adds_one_per_channel_with_an_unread_mention() {
118 let mentions = feed(&[
119 ("channel-a", Kind::Mention, false),
120 ("channel-a", Kind::Mention, false),
121 ("channel-b", Kind::Mention, false),
122 ("chat-unread", Kind::Mention, false),
123 ]);
124 assert_eq!(taskbar_badge_count(&sidebar(), &mentions, false), 5);
125 assert_eq!(taskbar_badge_count(&sidebar(), &mentions, true), 7);
126 }
127 }
@@ -0,0 +1,127 @@
1use std::collections::HashSet;
2
3use store::Sidebar;
4
5use crate::activity::Kind;
6use crate::activity::feed::Feed;
7use crate::sidebar_model::unread_chat_count;
8
9pub fn taskbar_badge_count(sidebar: &Sidebar, feed: &Feed, adaptive_rail: bool) -> usize {
10 let channel_ids: HashSet<&str> = sidebar
11 .teams
12 .iter()
13 .flat_map(|team| team.channels.iter())
14 .map(|channel| channel.id.as_str())
15 .collect();
16 let is_channel = |conversation_id: &str| channel_ids.contains(conversation_id);
17 let activity = feed
18 .unread_entries()
19 .filter(|entry| entry.kind != Kind::Messages || is_channel(&entry.conversation_id))
20 .count();
21 let channels_with_mentions = if adaptive_rail {
22 feed.unread_entries()
23 .filter(|entry| entry.kind == Kind::Mention && is_channel(&entry.conversation_id))
24 .map(|entry| entry.conversation_id.as_str())
25 .collect::<HashSet<_>>()
26 .len()
27 } else {
28 0
29 };
30 activity + unread_chat_count(&sidebar.chats) as usize + channels_with_mentions
31}
32
33#[cfg(test)]
34mod tests {
35 use chrono::Utc;
36 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
37
38 use super::*;
39 use crate::activity::Entry;
40
41 fn sidebar() -> Sidebar {
42 let chat = |id: &str, unread: bool, muted: bool| ChatRecord {
43 id: id.into(),
44 unread,
45 muted,
46 ..Default::default()
47 };
48 let channel = |id: &str| ChannelRecord {
49 id: id.into(),
50 team_id: "team".into(),
51 name: id.into(),
52 membership_type: None,
53 last_message_at: None,
54 unread: true,
55 };
56 Sidebar {
57 chats: vec![
58 chat("chat-unread", true, false),
59 chat("chat-muted", true, true),
60 chat("chat-read", false, false),
61 ],
62 teams: vec![SidebarTeam {
63 team: TeamRecord {
64 id: "team".into(),
65 name: "Team".into(),
66 },
67 channels: vec![channel("channel-a"), channel("channel-b")],
68 hidden: false,
69 hidden_channel_ids: vec!["channel-b".into()],
70 notifications: Default::default(),
71 }],
72 }
73 }
74
75 fn feed(entries: &[(&str, Kind, bool)]) -> Feed {
76 let mut feed = Feed::load(Vec::new());
77 for (conversation_id, kind, read) in entries {
78 feed.add(Entry {
79 id: 0,
80 conversation_id: (*conversation_id).into(),
81 kind: *kind,
82 message_id: String::new(),
83 actors: Vec::new(),
84 preview: String::new(),
85 glyphs: Vec::new(),
86 count: 1,
87 updated_at: Utc::now(),
88 read: *read,
89 });
90 }
91 feed
92 }
93
94 #[test]
95 fn unread_channel_posts_without_activity_do_not_count() {
96 assert_eq!(taskbar_badge_count(&sidebar(), &feed(&[]), true), 1);
97 }
98
99 #[test]
100 fn muted_chats_never_count_as_chats() {
101 let mentioned = feed(&[("chat-muted", Kind::Mention, false)]);
102 assert_eq!(taskbar_badge_count(&sidebar(), &mentioned, false), 2);
103 }
104
105 #[test]
106 fn chat_message_rows_are_counted_once_by_the_chat() {
107 let rows = feed(&[
108 ("chat-unread", Kind::Messages, false),
109 ("chat-unread", Kind::Reaction, false),
110 ("channel-a", Kind::Messages, false),
111 ("channel-a", Kind::Reaction, true),
112 ]);
113 assert_eq!(taskbar_badge_count(&sidebar(), &rows, false), 3);
114 }
115
116 #[test]
117 fn the_adaptive_rail_adds_one_per_channel_with_an_unread_mention() {
118 let mentions = feed(&[
119 ("channel-a", Kind::Mention, false),
120 ("channel-a", Kind::Mention, false),
121 ("channel-b", Kind::Mention, false),
122 ("chat-unread", Kind::Mention, false),
123 ]);
124 assert_eq!(taskbar_badge_count(&sidebar(), &mentions, false), 5);
125 assert_eq!(taskbar_badge_count(&sidebar(), &mentions, true), 7);
126 }
127}
crates/app/src/notify/center.rs +32 −38
@@ -22,8 +22,10 @@ use super::settings_view::{Section, SettingsView};
22 22 use super::stack::{
23 23 AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
24 24 };
25 use super::taskbar::taskbar_badge_count;
25 26 use super::text::describe;
26 27 use super::toast::{PillView, ToastView};
28 use crate::activity::ActivityCenter;
27 29 use crate::agents::{AgentRun, AgentRunsEvent, RunState};
28 30 use crate::app_state::{AppEvent, AppState, selection_for};
29 31 use crate::call::DemoScene;
@@ -65,6 +67,7 @@ impl OpenWindow {
65 67
66 68 pub struct NotificationCenter {
67 69 app: Entity<AppState>,
70 activity: Entity<ActivityCenter>,
68 71 main_window: AnyWindowHandle,
69 72 main_native: Option<NativeHandle>,
70 73 settings: Settings,
@@ -90,11 +93,17 @@ pub struct NotificationCenter {
90 93 shown_badge: Option<Badge>,
91 94 animations: bool,
92 95 _subscription: Subscription,
96 _activity_observation: Subscription,
93 97 _agent_subscription: Option<Subscription>,
94 98 }
95 99
96 100 impl NotificationCenter {
97 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
101 pub fn new(
102 app: Entity<AppState>,
103 activity: Entity<ActivityCenter>,
104 window: &mut Window,
105 cx: &mut Context<Self>,
106 ) -> Self {
98 107 let settings = settings::load(&app.read(cx).store);
99 108 let tray = if app.read(cx).mode.demo {
100 109 None
@@ -104,6 +113,7 @@ impl NotificationCenter {
104 113 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
105 114 this.on_app_event(event, cx);
106 115 });
116 let activity_observation = cx.observe(&activity, |this, _, cx| this.refresh_badge(cx));
107 117 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
108 118 cx.subscribe(&runs, |this, runs, event: &AgentRunsEvent, cx| {
109 119 if let AgentRunsEvent::Finished(run_id) = event
@@ -139,7 +149,9 @@ impl NotificationCenter {
139 149 shown_badge: None,
140 150 animations: platform::animations_enabled(),
141 151 app,
152 activity,
142 153 _subscription: subscription,
154 _activity_observation: activity_observation,
143 155 _agent_subscription: agent_subscription,
144 156 };
145 157 cx.spawn(async move |this, cx| {
@@ -901,10 +913,15 @@ impl NotificationCenter {
901 913 }
902 914
903 915 fn refresh_badge(&mut self, cx: &mut Context<Self>) {
904 let (count, still_unread) =
905 unread_summary(&self.app.read(cx).sidebar, &self.unread_mentions);
916 let state = self.app.read(cx);
917 let count = taskbar_badge_count(
918 &state.sidebar,
919 self.activity.read(cx).feed(),
920 state.directory.section_settings.adaptive_rail(),
921 );
922 let still_unread = unread_conversation_ids(&state.sidebar);
906 923 self.unread_mentions
907 .retain(|conversation_id| still_unread.contains(conversation_id));
924 .retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
908 925 let badge = badge_for(count);
909 926 if badge == self.shown_badge {
910 927 return;
@@ -1268,31 +1285,17 @@ fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions {
1268 1285 }
1269 1286 }
1270 1287
1271 pub fn unread_summary(
1272 sidebar: &Sidebar,
1273 unread_mentions: &HashSet<String>,
1274 ) -> (usize, HashSet<String>) {
1288 pub fn unread_conversation_ids(sidebar: &Sidebar) -> HashSet<&str> {
1275 1289 let chats = sidebar.chats.iter().filter(|chat| chat.unread);
1276 1290 let channels = sidebar
1277 1291 .teams
1278 1292 .iter()
1279 1293 .flat_map(|team| team.channels.iter())
1280 1294 .filter(|channel| channel.unread);
1281 let silenced_chat_ids: HashSet<&str> = sidebar
1282 .chats
1283 .iter()
1284 .filter(|chat| chat.muted && !unread_mentions.contains(&chat.id))
1295 chats
1285 1296 .map(|chat| chat.id.as_str())
1286 .collect();
1287 let ids: HashSet<String> = chats
1288 .map(|chat| chat.id.clone())
1289 .chain(channels.map(|channel| channel.id.clone()))
1290 .collect();
1291 let counted = ids
1292 .iter()
1293 .filter(|id| !silenced_chat_ids.contains(id.as_str()))
1294 .count();
1295 (counted, ids)
1297 .chain(channels.map(|channel| channel.id.as_str()))
1298 .collect()
1296 1299 }
1297 1300
1298 1301 fn demo_incoming() -> Vec<Incoming> {
@@ -1367,7 +1370,7 @@ mod tests {
1367 1370
1368 1371 use std::collections::HashSet;
1369 1372
1370 use super::{preview_lines, unread_summary};
1373 use super::{preview_lines, unread_conversation_ids};
1371 1374 use store::Sidebar;
1372 1375
1373 1376 fn sidebar() -> Sidebar {
@@ -1405,21 +1408,12 @@ mod tests {
1405 1408 }
1406 1409
1407 1410 #[test]
1408 fn unread_summary_counts_chats_and_channels() {
1409 let (count, ids) = unread_summary(&sidebar(), &HashSet::new());
1410 assert_eq!(count, 2);
1411 assert!(ids.contains("a") && ids.contains("ch"));
1412 }
1413
1414 #[test]
1415 fn muted_chats_only_count_with_an_unread_mention() {
1416 let mut quiet = sidebar();
1417 quiet.chats[0].muted = true;
1418 let (count, ids) = unread_summary(&quiet, &HashSet::new());
1419 assert_eq!(count, 1);
1420 assert!(ids.contains("a"));
1421 let (count, _) = unread_summary(&quiet, &HashSet::from(["a".to_owned()]));
1422 assert_eq!(count, 2);
1411 fn unread_conversation_ids_hold_chats_and_channels() {
1412 let sidebar = sidebar();
1413 assert_eq!(
1414 unread_conversation_ids(&sidebar),
1415 HashSet::from(["a", "ch"])
1416 );
1423 1417 }
1424 1418
1425 1419 #[gpui_kit::test]
@@ -22,8 +22,10 @@ use super::settings_view::{Section, SettingsView};
22use super::stack::{
22use super::stack::{
23 AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
23 AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
24};
24};
25use super::taskbar::taskbar_badge_count;
25use super::text::describe;
26use super::text::describe;
26use super::toast::{PillView, ToastView};
27use super::toast::{PillView, ToastView};
28use crate::activity::ActivityCenter;
27use crate::agents::{AgentRun, AgentRunsEvent, RunState};
29use crate::agents::{AgentRun, AgentRunsEvent, RunState};
28use crate::app_state::{AppEvent, AppState, selection_for};
30use crate::app_state::{AppEvent, AppState, selection_for};
29use crate::call::DemoScene;
31use crate::call::DemoScene;
@@ -65,6 +67,7 @@ impl OpenWindow {
65
67
66pub struct NotificationCenter {
68pub struct NotificationCenter {
67 app: Entity<AppState>,
69 app: Entity<AppState>,
70 activity: Entity<ActivityCenter>,
68 main_window: AnyWindowHandle,
71 main_window: AnyWindowHandle,
69 main_native: Option<NativeHandle>,
72 main_native: Option<NativeHandle>,
70 settings: Settings,
73 settings: Settings,
@@ -90,11 +93,17 @@ pub struct NotificationCenter {
90 shown_badge: Option<Badge>,
93 shown_badge: Option<Badge>,
91 animations: bool,
94 animations: bool,
92 _subscription: Subscription,
95 _subscription: Subscription,
96 _activity_observation: Subscription,
93 _agent_subscription: Option<Subscription>,
97 _agent_subscription: Option<Subscription>,
94}
98}
95
99
96impl NotificationCenter {
100impl NotificationCenter {
97 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
101 pub fn new(
102 app: Entity<AppState>,
103 activity: Entity<ActivityCenter>,
104 window: &mut Window,
105 cx: &mut Context<Self>,
106 ) -> Self {
98 let settings = settings::load(&app.read(cx).store);
107 let settings = settings::load(&app.read(cx).store);
99 let tray = if app.read(cx).mode.demo {
108 let tray = if app.read(cx).mode.demo {
100 None
109 None
@@ -104,6 +113,7 @@ impl NotificationCenter {
104 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
113 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
105 this.on_app_event(event, cx);
114 this.on_app_event(event, cx);
106 });
115 });
116 let activity_observation = cx.observe(&activity, |this, _, cx| this.refresh_badge(cx));
107 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
117 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
108 cx.subscribe(&runs, |this, runs, event: &AgentRunsEvent, cx| {
118 cx.subscribe(&runs, |this, runs, event: &AgentRunsEvent, cx| {
109 if let AgentRunsEvent::Finished(run_id) = event
119 if let AgentRunsEvent::Finished(run_id) = event
@@ -139,7 +149,9 @@ impl NotificationCenter {
139 shown_badge: None,
149 shown_badge: None,
140 animations: platform::animations_enabled(),
150 animations: platform::animations_enabled(),
141 app,
151 app,
152 activity,
142 _subscription: subscription,
153 _subscription: subscription,
154 _activity_observation: activity_observation,
143 _agent_subscription: agent_subscription,
155 _agent_subscription: agent_subscription,
144 };
156 };
145 cx.spawn(async move |this, cx| {
157 cx.spawn(async move |this, cx| {
@@ -901,10 +913,15 @@ impl NotificationCenter {
901 }
913 }
902
914
903 fn refresh_badge(&mut self, cx: &mut Context<Self>) {
915 fn refresh_badge(&mut self, cx: &mut Context<Self>) {
904 let (count, still_unread) =
916 let state = self.app.read(cx);
905 unread_summary(&self.app.read(cx).sidebar, &self.unread_mentions);
917 let count = taskbar_badge_count(
918 &state.sidebar,
919 self.activity.read(cx).feed(),
920 state.directory.section_settings.adaptive_rail(),
921 );
922 let still_unread = unread_conversation_ids(&state.sidebar);
906 self.unread_mentions
923 self.unread_mentions
907 .retain(|conversation_id| still_unread.contains(conversation_id));
924 .retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
908 let badge = badge_for(count);
925 let badge = badge_for(count);
909 if badge == self.shown_badge {
926 if badge == self.shown_badge {
910 return;
927 return;
@@ -1268,31 +1285,17 @@ fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions {
1268 }
1285 }
1269}
1286}
1270
1287
1271pub fn unread_summary(
1288pub fn unread_conversation_ids(sidebar: &Sidebar) -> HashSet<&str> {
1272 sidebar: &Sidebar,
1273 unread_mentions: &HashSet<String>,
1274) -> (usize, HashSet<String>) {
1275 let chats = sidebar.chats.iter().filter(|chat| chat.unread);
1289 let chats = sidebar.chats.iter().filter(|chat| chat.unread);
1276 let channels = sidebar
1290 let channels = sidebar
1277 .teams
1291 .teams
1278 .iter()
1292 .iter()
1279 .flat_map(|team| team.channels.iter())
1293 .flat_map(|team| team.channels.iter())
1280 .filter(|channel| channel.unread);
1294 .filter(|channel| channel.unread);
1281 let silenced_chat_ids: HashSet<&str> = sidebar
1295 chats
1282 .chats
1283 .iter()
1284 .filter(|chat| chat.muted && !unread_mentions.contains(&chat.id))
1285 .map(|chat| chat.id.as_str())
1296 .map(|chat| chat.id.as_str())
1286 .collect();
1297 .chain(channels.map(|channel| channel.id.as_str()))
1287 let ids: HashSet<String> = chats
1298 .collect()
1288 .map(|chat| chat.id.clone())
1289 .chain(channels.map(|channel| channel.id.clone()))
1290 .collect();
1291 let counted = ids
1292 .iter()
1293 .filter(|id| !silenced_chat_ids.contains(id.as_str()))
1294 .count();
1295 (counted, ids)
1296}
1299}
1297
1300
1298fn demo_incoming() -> Vec<Incoming> {
1301fn demo_incoming() -> Vec<Incoming> {
@@ -1367,7 +1370,7 @@ mod tests {
1367
1370
1368 use std::collections::HashSet;
1371 use std::collections::HashSet;
1369
1372
1370 use super::{preview_lines, unread_summary};
1373 use super::{preview_lines, unread_conversation_ids};
1371 use store::Sidebar;
1374 use store::Sidebar;
1372
1375
1373 fn sidebar() -> Sidebar {
1376 fn sidebar() -> Sidebar {
@@ -1405,21 +1408,12 @@ mod tests {
1405 }
1408 }
1406
1409
1407 #[test]
1410 #[test]
1408 fn unread_summary_counts_chats_and_channels() {
1411 fn unread_conversation_ids_hold_chats_and_channels() {
1409 let (count, ids) = unread_summary(&sidebar(), &HashSet::new());
1412 let sidebar = sidebar();
1410 assert_eq!(count, 2);
1413 assert_eq!(
1411 assert!(ids.contains("a") && ids.contains("ch"));
1414 unread_conversation_ids(&sidebar),
1412 }
1415 HashSet::from(["a", "ch"])
1413
1416 );
1414 #[test]
1415 fn muted_chats_only_count_with_an_unread_mention() {
1416 let mut quiet = sidebar();
1417 quiet.chats[0].muted = true;
1418 let (count, ids) = unread_summary(&quiet, &HashSet::new());
1419 assert_eq!(count, 1);
1420 assert!(ids.contains("a"));
1421 let (count, _) = unread_summary(&quiet, &HashSet::from(["a".to_owned()]));
1422 assert_eq!(count, 2);
1423 }
1417 }
1424
1418
1425 #[gpui_kit::test]
1419 #[gpui_kit::test]
crates/app/src/views/shell.rs +2 −1
@@ -264,7 +264,8 @@ impl AppShell {
264 264 });
265 265 let focus_handle = cx.focus_handle();
266 266 window.focus(&focus_handle, cx);
267 let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
267 let notifications =
268 cx.new(|cx| NotificationCenter::new(state.clone(), activity.clone(), window, cx));
268 269 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
269 270 let user_input = cx.global::<UserInputHandle>().0.clone();
270 271 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
@@ -264,7 +264,8 @@ impl AppShell {
264 });
264 });
265 let focus_handle = cx.focus_handle();
265 let focus_handle = cx.focus_handle();
266 window.focus(&focus_handle, cx);
266 window.focus(&focus_handle, cx);
267 let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
267 let notifications =
268 cx.new(|cx| NotificationCenter::new(state.clone(), activity.clone(), window, cx));
268 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
269 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
269 let user_input = cx.global::<UserInputHandle>().0.clone();
270 let user_input = cx.global::<UserInputHandle>().0.clone();
270 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
271 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
crates/chatsvc/examples/calendar_probe.rs +12 −3
@@ -31,15 +31,24 @@ async fn main() {
31 31 );
32 32 println!(
33 33 "# with thread: {}",
34 events.iter().filter(|event| event.thread_id.is_some()).count()
34 events
35 .iter()
36 .filter(|event| event.thread_id.is_some())
37 .count()
35 38 );
36 39 println!(
37 40 "# with organizer name: {}",
38 events.iter().filter(|event| event.organizer_name.is_some()).count()
41 events
42 .iter()
43 .filter(|event| event.organizer_name.is_some())
44 .count()
39 45 );
40 46 println!(
41 47 "# not responded: {}, cancelled: {}, all day: {}",
42 events.iter().filter(|event| event.response == chatsvc::ResponseType::NotResponded).count(),
48 events
49 .iter()
50 .filter(|event| event.response == chatsvc::ResponseType::NotResponded)
51 .count(),
43 52 events.iter().filter(|event| event.cancelled).count(),
44 53 events.iter().filter(|event| event.all_day).count()
45 54 );
@@ -31,15 +31,24 @@ async fn main() {
31 );
31 );
32 println!(
32 println!(
33 "# with thread: {}",
33 "# with thread: {}",
34 events.iter().filter(|event| event.thread_id.is_some()).count()
34 events
35 .iter()
36 .filter(|event| event.thread_id.is_some())
37 .count()
35 );
38 );
36 println!(
39 println!(
37 "# with organizer name: {}",
40 "# with organizer name: {}",
38 events.iter().filter(|event| event.organizer_name.is_some()).count()
41 events
42 .iter()
43 .filter(|event| event.organizer_name.is_some())
44 .count()
39 );
45 );
40 println!(
46 println!(
41 "# not responded: {}, cancelled: {}, all day: {}",
47 "# not responded: {}, cancelled: {}, all day: {}",
42 events.iter().filter(|event| event.response == chatsvc::ResponseType::NotResponded).count(),
48 events
49 .iter()
50 .filter(|event| event.response == chatsvc::ResponseType::NotResponded)
51 .count(),
43 events.iter().filter(|event| event.cancelled).count(),
52 events.iter().filter(|event| event.cancelled).count(),
44 events.iter().filter(|event| event.all_day).count()
53 events.iter().filter(|event| event.all_day).count()
45 );
54 );
crates/chatsvc/examples/presence_endpoint_probe.rs +31 −8
@@ -1,6 +1,8 @@
1 1 use std::time::Duration;
2 2
3 use chatsvc::{ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
3 use chatsvc::{
4 ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind,
5 };
4 6 use session::{DEFAULT_ENDPOINT, Session};
5 7
6 8 const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
@@ -8,7 +10,9 @@ const SETTLE: Duration = Duration::from_secs(10);
8 10
9 11 #[tokio::main]
10 12 async fn main() {
11 let user_id = std::env::args().nth(1).expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");
13 let user_id = std::env::args()
14 .nth(1)
15 .expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");
12 16 let inactive_wait = std::env::args()
13 17 .nth(2)
14 18 .and_then(|value| value.parse().ok())
@@ -21,11 +25,20 @@ async fn main() {
21 25 initially_active: true,
22 26 ..RealtimeConfig::default()
23 27 };
24 let mut realtime = Realtime::start_with(&session, config).await.expect("realtime start");
28 let mut realtime = Realtime::start_with(&session, config)
29 .await
30 .expect("realtime start");
25 31 let endpoint_id = wait_for_endpoint(&mut realtime).await;
26 32 println!("# trouter connected");
27 33
28 println!("register: {}", outcome(presence.register_endpoint(&endpoint_id, ActivityReporting::Transport).await));
34 println!(
35 "register: {}",
36 outcome(
37 presence
38 .register_endpoint(&endpoint_id, ActivityReporting::Transport)
39 .await
40 )
41 );
29 42 realtime.resend_activity();
30 43 println!("# sent active");
31 44 tokio::time::sleep(SETTLE).await;
@@ -36,8 +49,14 @@ async fn main() {
36 49 tokio::time::sleep(inactive_wait).await;
37 50 print_own_presence(&presence, &user_id).await;
38 51
39 println!("http report inactive: {}", outcome(presence.report_activity(&endpoint_id, false).await));
40 println!("unregister: {}", outcome(presence.unregister_endpoint(&endpoint_id).await));
52 println!(
53 "http report inactive: {}",
54 outcome(presence.report_activity(&endpoint_id, false).await)
55 );
56 println!(
57 "unregister: {}",
58 outcome(presence.unregister_endpoint(&endpoint_id).await)
59 );
41 60 realtime.stop().await;
42 61 println!("# stopped");
43 62 }
@@ -49,7 +68,9 @@ async fn wait_for_endpoint(realtime: &mut Realtime) -> String {
49 68 while let Some(event) = realtime.recv().await {
50 69 match event {
51 70 RealtimeEvent::Endpoint(endpoint) => endpoint_id = Some(endpoint.endpoint_id),
52 RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => connected = true,
71 RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => {
72 connected = true
73 }
53 74 _ => {}
54 75 }
55 76 if connected && let Some(endpoint_id) = endpoint_id.take() {
@@ -58,7 +79,9 @@ async fn wait_for_endpoint(realtime: &mut Realtime) -> String {
58 79 }
59 80 panic!("realtime closed before connecting");
60 81 };
61 tokio::time::timeout(CONNECT_TIMEOUT, wait).await.expect("trouter did not connect")
82 tokio::time::timeout(CONNECT_TIMEOUT, wait)
83 .await
84 .expect("trouter did not connect")
62 85 }
63 86
64 87 async fn print_own_presence(presence: &PresenceService, user_id: &str) {
@@ -1,6 +1,8 @@
1use std::time::Duration;
1use std::time::Duration;
2
2
3use chatsvc::{ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
3use chatsvc::{
4 ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind,
5};
4use session::{DEFAULT_ENDPOINT, Session};
6use session::{DEFAULT_ENDPOINT, Session};
5
7
6const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
8const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
@@ -8,7 +10,9 @@ const SETTLE: Duration = Duration::from_secs(10);
8
10
9#[tokio::main]
11#[tokio::main]
10async fn main() {
12async fn main() {
11 let user_id = std::env::args().nth(1).expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");
13 let user_id = std::env::args()
14 .nth(1)
15 .expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");
12 let inactive_wait = std::env::args()
16 let inactive_wait = std::env::args()
13 .nth(2)
17 .nth(2)
14 .and_then(|value| value.parse().ok())
18 .and_then(|value| value.parse().ok())
@@ -21,11 +25,20 @@ async fn main() {
21 initially_active: true,
25 initially_active: true,
22 ..RealtimeConfig::default()
26 ..RealtimeConfig::default()
23 };
27 };
24 let mut realtime = Realtime::start_with(&session, config).await.expect("realtime start");
28 let mut realtime = Realtime::start_with(&session, config)
29 .await
30 .expect("realtime start");
25 let endpoint_id = wait_for_endpoint(&mut realtime).await;
31 let endpoint_id = wait_for_endpoint(&mut realtime).await;
26 println!("# trouter connected");
32 println!("# trouter connected");
27
33
28 println!("register: {}", outcome(presence.register_endpoint(&endpoint_id, ActivityReporting::Transport).await));
34 println!(
35 "register: {}",
36 outcome(
37 presence
38 .register_endpoint(&endpoint_id, ActivityReporting::Transport)
39 .await
40 )
41 );
29 realtime.resend_activity();
42 realtime.resend_activity();
30 println!("# sent active");
43 println!("# sent active");
31 tokio::time::sleep(SETTLE).await;
44 tokio::time::sleep(SETTLE).await;
@@ -36,8 +49,14 @@ async fn main() {
36 tokio::time::sleep(inactive_wait).await;
49 tokio::time::sleep(inactive_wait).await;
37 print_own_presence(&presence, &user_id).await;
50 print_own_presence(&presence, &user_id).await;
38
51
39 println!("http report inactive: {}", outcome(presence.report_activity(&endpoint_id, false).await));
52 println!(
40 println!("unregister: {}", outcome(presence.unregister_endpoint(&endpoint_id).await));
53 "http report inactive: {}",
54 outcome(presence.report_activity(&endpoint_id, false).await)
55 );
56 println!(
57 "unregister: {}",
58 outcome(presence.unregister_endpoint(&endpoint_id).await)
59 );
41 realtime.stop().await;
60 realtime.stop().await;
42 println!("# stopped");
61 println!("# stopped");
43}
62}
@@ -49,7 +68,9 @@ async fn wait_for_endpoint(realtime: &mut Realtime) -> String {
49 while let Some(event) = realtime.recv().await {
68 while let Some(event) = realtime.recv().await {
50 match event {
69 match event {
51 RealtimeEvent::Endpoint(endpoint) => endpoint_id = Some(endpoint.endpoint_id),
70 RealtimeEvent::Endpoint(endpoint) => endpoint_id = Some(endpoint.endpoint_id),
52 RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => connected = true,
71 RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => {
72 connected = true
73 }
53 _ => {}
74 _ => {}
54 }
75 }
55 if connected && let Some(endpoint_id) = endpoint_id.take() {
76 if connected && let Some(endpoint_id) = endpoint_id.take() {
@@ -58,7 +79,9 @@ async fn wait_for_endpoint(realtime: &mut Realtime) -> String {
58 }
79 }
59 panic!("realtime closed before connecting");
80 panic!("realtime closed before connecting");
60 };
81 };
61 tokio::time::timeout(CONNECT_TIMEOUT, wait).await.expect("trouter did not connect")
82 tokio::time::timeout(CONNECT_TIMEOUT, wait)
83 .await
84 .expect("trouter did not connect")
62}
85}
63
86
64async fn print_own_presence(presence: &PresenceService, user_id: &str) {
87async fn print_own_presence(presence: &PresenceService, user_id: &str) {
crates/chatsvc/examples/recap_probe.rs +43 −14
@@ -19,10 +19,13 @@ fn host_and_path_shape(url: &str) -> String {
19 19 _ => "*",
20 20 })
21 21 .collect();
22 let host_kind = without_scheme
23 .split('/')
24 .next()
25 .map_or("?", |host| if host.ends_with("-my.sharepoint.com") { "<tenant>-my.sharepoint.com" } else { "other" });
22 let host_kind = without_scheme.split('/').next().map_or("?", |host| {
23 if host.ends_with("-my.sharepoint.com") {
24 "<tenant>-my.sharepoint.com"
25 } else {
26 "other"
27 }
28 });
26 29 format!("{host_kind}/{}", shape.join("/"))
27 30 }
28 31
@@ -30,15 +33,22 @@ fn error_shape(error: &TranscriptError) -> String {
30 33 match error {
31 34 TranscriptError::Request(session::Error::Api { status, body, .. }) => format!(
32 35 "HTTP {status} code {}",
33 body.pointer("/error/code").and_then(serde_json::Value::as_str).unwrap_or("-")
36 body.pointer("/error/code")
37 .and_then(serde_json::Value::as_str)
38 .unwrap_or("-")
39 ),
40 TranscriptError::Request(other) => format!(
41 "request {}",
42 other.to_string().chars().take(60).collect::<String>()
34 43 ),
35 TranscriptError::Request(other) => format!("request {}", other.to_string().chars().take(60).collect::<String>()),
36 44 other => format!("{other:?}"),
37 45 }
38 46 }
39 47
40 48 fn magic(bytes: &[u8]) -> String {
41 let start = bytes.strip_prefix(b"\xEF\xBB\xBF".as_slice()).unwrap_or(bytes);
49 let start = bytes
50 .strip_prefix(b"\xEF\xBB\xBF".as_slice())
51 .unwrap_or(bytes);
42 52 if start.starts_with(b"WEBVTT") {
43 53 format!("WEBVTT (bom {})", start.len() != bytes.len())
44 54 } else if bytes.starts_with(b"PK\x03\x04") {
@@ -51,9 +61,14 @@ fn magic(bytes: &[u8]) -> String {
51 61 #[tokio::main]
52 62 async fn main() {
53 63 let mut arguments = std::env::args().skip(1);
54 let Some(thread_file) = arguments.next() else { usage() };
64 let Some(thread_file) = arguments.next() else {
65 usage()
66 };
55 67 let delete = arguments.any(|argument| argument == "--delete");
56 let thread_id = std::fs::read_to_string(&thread_file).expect("thread file").trim().to_owned();
68 let thread_id = std::fs::read_to_string(&thread_file)
69 .expect("thread file")
70 .trim()
71 .to_owned();
57 72 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
58 73 let session = Session::connect(&endpoint).await.expect("browser");
59 74 let recap = Recap::new(&session);
@@ -76,7 +91,9 @@ async fn main() {
76 91 host_and_path_shape(&occurrence.recording_url)
77 92 );
78 93 }
79 let Some(occurrence) = occurrences.first() else { return };
94 let Some(occurrence) = occurrences.first() else {
95 return;
96 };
80 97
81 98 let details = match recap.details(occurrence).await {
82 99 Ok(details) => details,
@@ -89,7 +106,9 @@ async fn main() {
89 106 "# details: audio only {}, duration {:?}, expires in days {:?}, transcript {}, item {}",
90 107 details.audio_only,
91 108 details.duration_seconds,
92 details.expires_at.map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),
109 details
110 .expires_at
111 .map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),
93 112 details.transcript_id.is_some(),
94 113 host_and_path_shape(&details.item_url)
95 114 );
@@ -99,8 +118,14 @@ async fn main() {
99 118 "# transcript: {} turns, {} with speaker, {} words, spans {:?}",
100 119 turns.len(),
101 120 turns.iter().filter(|turn| !turn.speaker.is_empty()).count(),
102 turns.iter().map(|turn| turn.text.split_whitespace().count()).sum::<usize>(),
103 turns.iter().map(|turn| (turn.start_seconds.round(), turn.end_seconds.round())).collect::<Vec<_>>()
121 turns
122 .iter()
123 .map(|turn| turn.text.split_whitespace().count())
124 .sum::<usize>(),
125 turns
126 .iter()
127 .map(|turn| (turn.start_seconds.round(), turn.end_seconds.round()))
128 .collect::<Vec<_>>()
104 129 ),
105 130 Err(error) => println!("# transcript: error {}", error_shape(&error)),
106 131 }
@@ -123,7 +148,11 @@ async fn main() {
123 148 text.contains("word/document.xml")
124 149 );
125 150 }
126 Err(error) => println!("# transcript file {}: error {}", format.query(), error_shape(&error)),
151 Err(error) => println!(
152 "# transcript file {}: error {}",
153 format.query(),
154 error_shape(&error)
155 ),
127 156 }
128 157 }
129 158 let _ = std::fs::remove_dir_all(&directory);
@@ -19,10 +19,13 @@ fn host_and_path_shape(url: &str) -> String {
19 _ => "*",
19 _ => "*",
20 })
20 })
21 .collect();
21 .collect();
22 let host_kind = without_scheme
22 let host_kind = without_scheme.split('/').next().map_or("?", |host| {
23 .split('/')
23 if host.ends_with("-my.sharepoint.com") {
24 .next()
24 "<tenant>-my.sharepoint.com"
25 .map_or("?", |host| if host.ends_with("-my.sharepoint.com") { "<tenant>-my.sharepoint.com" } else { "other" });
25 } else {
26 "other"
27 }
28 });
26 format!("{host_kind}/{}", shape.join("/"))
29 format!("{host_kind}/{}", shape.join("/"))
27}
30}
28
31
@@ -30,15 +33,22 @@ fn error_shape(error: &TranscriptError) -> String {
30 match error {
33 match error {
31 TranscriptError::Request(session::Error::Api { status, body, .. }) => format!(
34 TranscriptError::Request(session::Error::Api { status, body, .. }) => format!(
32 "HTTP {status} code {}",
35 "HTTP {status} code {}",
33 body.pointer("/error/code").and_then(serde_json::Value::as_str).unwrap_or("-")
36 body.pointer("/error/code")
37 .and_then(serde_json::Value::as_str)
38 .unwrap_or("-")
39 ),
40 TranscriptError::Request(other) => format!(
41 "request {}",
42 other.to_string().chars().take(60).collect::<String>()
34 ),
43 ),
35 TranscriptError::Request(other) => format!("request {}", other.to_string().chars().take(60).collect::<String>()),
36 other => format!("{other:?}"),
44 other => format!("{other:?}"),
37 }
45 }
38}
46}
39
47
40fn magic(bytes: &[u8]) -> String {
48fn magic(bytes: &[u8]) -> String {
41 let start = bytes.strip_prefix(b"\xEF\xBB\xBF".as_slice()).unwrap_or(bytes);
49 let start = bytes
50 .strip_prefix(b"\xEF\xBB\xBF".as_slice())
51 .unwrap_or(bytes);
42 if start.starts_with(b"WEBVTT") {
52 if start.starts_with(b"WEBVTT") {
43 format!("WEBVTT (bom {})", start.len() != bytes.len())
53 format!("WEBVTT (bom {})", start.len() != bytes.len())
44 } else if bytes.starts_with(b"PK\x03\x04") {
54 } else if bytes.starts_with(b"PK\x03\x04") {
@@ -51,9 +61,14 @@ fn magic(bytes: &[u8]) -> String {
51#[tokio::main]
61#[tokio::main]
52async fn main() {
62async fn main() {
53 let mut arguments = std::env::args().skip(1);
63 let mut arguments = std::env::args().skip(1);
54 let Some(thread_file) = arguments.next() else { usage() };
64 let Some(thread_file) = arguments.next() else {
65 usage()
66 };
55 let delete = arguments.any(|argument| argument == "--delete");
67 let delete = arguments.any(|argument| argument == "--delete");
56 let thread_id = std::fs::read_to_string(&thread_file).expect("thread file").trim().to_owned();
68 let thread_id = std::fs::read_to_string(&thread_file)
69 .expect("thread file")
70 .trim()
71 .to_owned();
57 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
72 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
58 let session = Session::connect(&endpoint).await.expect("browser");
73 let session = Session::connect(&endpoint).await.expect("browser");
59 let recap = Recap::new(&session);
74 let recap = Recap::new(&session);
@@ -76,7 +91,9 @@ async fn main() {
76 host_and_path_shape(&occurrence.recording_url)
91 host_and_path_shape(&occurrence.recording_url)
77 );
92 );
78 }
93 }
79 let Some(occurrence) = occurrences.first() else { return };
94 let Some(occurrence) = occurrences.first() else {
95 return;
96 };
80
97
81 let details = match recap.details(occurrence).await {
98 let details = match recap.details(occurrence).await {
82 Ok(details) => details,
99 Ok(details) => details,
@@ -89,7 +106,9 @@ async fn main() {
89 "# details: audio only {}, duration {:?}, expires in days {:?}, transcript {}, item {}",
106 "# details: audio only {}, duration {:?}, expires in days {:?}, transcript {}, item {}",
90 details.audio_only,
107 details.audio_only,
91 details.duration_seconds,
108 details.duration_seconds,
92 details.expires_at.map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),
109 details
110 .expires_at
111 .map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),
93 details.transcript_id.is_some(),
112 details.transcript_id.is_some(),
94 host_and_path_shape(&details.item_url)
113 host_and_path_shape(&details.item_url)
95 );
114 );
@@ -99,8 +118,14 @@ async fn main() {
99 "# transcript: {} turns, {} with speaker, {} words, spans {:?}",
118 "# transcript: {} turns, {} with speaker, {} words, spans {:?}",
100 turns.len(),
119 turns.len(),
101 turns.iter().filter(|turn| !turn.speaker.is_empty()).count(),
120 turns.iter().filter(|turn| !turn.speaker.is_empty()).count(),
102 turns.iter().map(|turn| turn.text.split_whitespace().count()).sum::<usize>(),
121 turns
103 turns.iter().map(|turn| (turn.start_seconds.round(), turn.end_seconds.round())).collect::<Vec<_>>()
122 .iter()
123 .map(|turn| turn.text.split_whitespace().count())
124 .sum::<usize>(),
125 turns
126 .iter()
127 .map(|turn| (turn.start_seconds.round(), turn.end_seconds.round()))
128 .collect::<Vec<_>>()
104 ),
129 ),
105 Err(error) => println!("# transcript: error {}", error_shape(&error)),
130 Err(error) => println!("# transcript: error {}", error_shape(&error)),
106 }
131 }
@@ -123,7 +148,11 @@ async fn main() {
123 text.contains("word/document.xml")
148 text.contains("word/document.xml")
124 );
149 );
125 }
150 }
126 Err(error) => println!("# transcript file {}: error {}", format.query(), error_shape(&error)),
151 Err(error) => println!(
152 "# transcript file {}: error {}",
153 format.query(),
154 error_shape(&error)
155 ),
127 }
156 }
128 }
157 }
129 let _ = std::fs::remove_dir_all(&directory);
158 let _ = std::fs::remove_dir_all(&directory);
crates/chatsvc/examples/tab_raw_probe.rs +43 −8
@@ -4,25 +4,60 @@ use session::{DEFAULT_ENDPOINT, Request, Scope, Session};
4 4 #[tokio::main]
5 5 async fn main() {
6 6 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
7 let needle = std::env::args().nth(1).unwrap_or_else(|| "Lunch".to_owned());
7 let needle = std::env::args()
8 .nth(1)
9 .unwrap_or_else(|| "Lunch".to_owned());
8 10 let session = Session::connect(&endpoint).await.expect("browser");
9 11 let url = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/users/me?isPrefetch=false&enableMembershipSummary=true";
10 let scope = Scope::new("https://chatsvcagg.teams.microsoft.com", "user_impersonation");
11 let answer = session.batch(&[Request::get(url)], &scope).await.expect("csa").remove(0);
12 let scope = Scope::new(
13 "https://chatsvcagg.teams.microsoft.com",
14 "user_impersonation",
15 );
16 let answer = session
17 .batch(&[Request::get(url)], &scope)
18 .await
19 .expect("csa")
20 .remove(0);
12 21 println!("# status {}", answer.status);
13 for team in answer.body.get("teams").and_then(Value::as_array).into_iter().flatten() {
14 for channel in team.get("channels").and_then(Value::as_array).into_iter().flatten() {
15 let name = channel.get("displayName").and_then(Value::as_str).unwrap_or_default();
22 for team in answer
23 .body
24 .get("teams")
25 .and_then(Value::as_array)
26 .into_iter()
27 .flatten()
28 {
29 for channel in team
30 .get("channels")
31 .and_then(Value::as_array)
32 .into_iter()
33 .flatten()
34 {
35 let name = channel
36 .get("displayName")
37 .and_then(Value::as_str)
38 .unwrap_or_default();
16 39 if !name.contains(&needle) {
17 40 continue;
18 41 }
19 42 println!("channel {name}");
20 for tab in channel.get("tabs").and_then(Value::as_array).into_iter().flatten() {
43 for tab in channel
44 .get("tabs")
45 .and_then(Value::as_array)
46 .into_iter()
47 .flatten()
48 {
21 49 let mut shown = tab.clone();
22 50 if let Some(object) = shown.as_object_mut() {
23 51 object.retain(|key, _| key != "replyChainId");
24 52 }
25 println!(" {}", serde_json::to_string(&shown).unwrap_or_default().chars().take(1500).collect::<String>());
53 println!(
54 " {}",
55 serde_json::to_string(&shown)
56 .unwrap_or_default()
57 .chars()
58 .take(1500)
59 .collect::<String>()
60 );
26 61 }
27 62 }
28 63 }
@@ -4,25 +4,60 @@ use session::{DEFAULT_ENDPOINT, Request, Scope, Session};
4#[tokio::main]
4#[tokio::main]
5async fn main() {
5async fn main() {
6 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
6 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
7 let needle = std::env::args().nth(1).unwrap_or_else(|| "Lunch".to_owned());
7 let needle = std::env::args()
8 .nth(1)
9 .unwrap_or_else(|| "Lunch".to_owned());
8 let session = Session::connect(&endpoint).await.expect("browser");
10 let session = Session::connect(&endpoint).await.expect("browser");
9 let url = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/users/me?isPrefetch=false&enableMembershipSummary=true";
11 let url = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/users/me?isPrefetch=false&enableMembershipSummary=true";
10 let scope = Scope::new("https://chatsvcagg.teams.microsoft.com", "user_impersonation");
12 let scope = Scope::new(
11 let answer = session.batch(&[Request::get(url)], &scope).await.expect("csa").remove(0);
13 "https://chatsvcagg.teams.microsoft.com",
14 "user_impersonation",
15 );
16 let answer = session
17 .batch(&[Request::get(url)], &scope)
18 .await
19 .expect("csa")
20 .remove(0);
12 println!("# status {}", answer.status);
21 println!("# status {}", answer.status);
13 for team in answer.body.get("teams").and_then(Value::as_array).into_iter().flatten() {
22 for team in answer
14 for channel in team.get("channels").and_then(Value::as_array).into_iter().flatten() {
23 .body
15 let name = channel.get("displayName").and_then(Value::as_str).unwrap_or_default();
24 .get("teams")
25 .and_then(Value::as_array)
26 .into_iter()
27 .flatten()
28 {
29 for channel in team
30 .get("channels")
31 .and_then(Value::as_array)
32 .into_iter()
33 .flatten()
34 {
35 let name = channel
36 .get("displayName")
37 .and_then(Value::as_str)
38 .unwrap_or_default();
16 if !name.contains(&needle) {
39 if !name.contains(&needle) {
17 continue;
40 continue;
18 }
41 }
19 println!("channel {name}");
42 println!("channel {name}");
20 for tab in channel.get("tabs").and_then(Value::as_array).into_iter().flatten() {
43 for tab in channel
44 .get("tabs")
45 .and_then(Value::as_array)
46 .into_iter()
47 .flatten()
48 {
21 let mut shown = tab.clone();
49 let mut shown = tab.clone();
22 if let Some(object) = shown.as_object_mut() {
50 if let Some(object) = shown.as_object_mut() {
23 object.retain(|key, _| key != "replyChainId");
51 object.retain(|key, _| key != "replyChainId");
24 }
52 }
25 println!(" {}", serde_json::to_string(&shown).unwrap_or_default().chars().take(1500).collect::<String>());
53 println!(
54 " {}",
55 serde_json::to_string(&shown)
56 .unwrap_or_default()
57 .chars()
58 .take(1500)
59 .collect::<String>()
60 );
26 }
61 }
27 }
62 }
28 }
63 }
crates/chatsvc/examples/tabs_probe.rs +21 −4
@@ -8,14 +8,31 @@ async fn main() {
8 8 let pins = Pins::new(&session);
9 9 match pins.folders().await {
10 10 Ok(folders) => println!("# folders ok: {}", folders.folders.len()),
11 Err(error) => println!("# folders failed: {}", error.to_string().chars().take(160).collect::<String>()),
11 Err(error) => println!(
12 "# folders failed: {}",
13 error.to_string().chars().take(160).collect::<String>()
14 ),
12 15 }
13 16 match pins.pinned_channels().await {
14 17 Ok(channels) => println!("# pinned channels ok: {}", channels.channel_ids.len()),
15 Err(error) => println!("# pinned channels failed: {}", error.to_string().chars().take(160).collect::<String>()),
18 Err(error) => println!(
19 "# pinned channels failed: {}",
20 error.to_string().chars().take(160).collect::<String>()
21 ),
16 22 }
17 23 match pins.team_layout().await {
18 Ok(layout) => println!("# team layout ok: {} teams, {} tabs", layout.len(), layout.iter().flat_map(|team| team.channels.iter()).map(|channel| channel.tabs.len()).sum::<usize>()),
19 Err(error) => println!("# team layout failed: {}", error.to_string().chars().take(160).collect::<String>()),
24 Ok(layout) => println!(
25 "# team layout ok: {} teams, {} tabs",
26 layout.len(),
27 layout
28 .iter()
29 .flat_map(|team| team.channels.iter())
30 .map(|channel| channel.tabs.len())
31 .sum::<usize>()
32 ),
33 Err(error) => println!(
34 "# team layout failed: {}",
35 error.to_string().chars().take(160).collect::<String>()
36 ),
20 37 }
21 38 }
@@ -8,14 +8,31 @@ async fn main() {
8 let pins = Pins::new(&session);
8 let pins = Pins::new(&session);
9 match pins.folders().await {
9 match pins.folders().await {
10 Ok(folders) => println!("# folders ok: {}", folders.folders.len()),
10 Ok(folders) => println!("# folders ok: {}", folders.folders.len()),
11 Err(error) => println!("# folders failed: {}", error.to_string().chars().take(160).collect::<String>()),
11 Err(error) => println!(
12 "# folders failed: {}",
13 error.to_string().chars().take(160).collect::<String>()
14 ),
12 }
15 }
13 match pins.pinned_channels().await {
16 match pins.pinned_channels().await {
14 Ok(channels) => println!("# pinned channels ok: {}", channels.channel_ids.len()),
17 Ok(channels) => println!("# pinned channels ok: {}", channels.channel_ids.len()),
15 Err(error) => println!("# pinned channels failed: {}", error.to_string().chars().take(160).collect::<String>()),
18 Err(error) => println!(
19 "# pinned channels failed: {}",
20 error.to_string().chars().take(160).collect::<String>()
21 ),
16 }
22 }
17 match pins.team_layout().await {
23 match pins.team_layout().await {
18 Ok(layout) => println!("# team layout ok: {} teams, {} tabs", layout.len(), layout.iter().flat_map(|team| team.channels.iter()).map(|channel| channel.tabs.len()).sum::<usize>()),
24 Ok(layout) => println!(
19 Err(error) => println!("# team layout failed: {}", error.to_string().chars().take(160).collect::<String>()),
25 "# team layout ok: {} teams, {} tabs",
26 layout.len(),
27 layout
28 .iter()
29 .flat_map(|team| team.channels.iter())
30 .map(|channel| channel.tabs.len())
31 .sum::<usize>()
32 ),
33 Err(error) => println!(
34 "# team layout failed: {}",
35 error.to_string().chars().take(160).collect::<String>()
36 ),
20 }
37 }
21}
38}
crates/chatsvc/src/conversations.rs +8 −1
@@ -304,7 +304,14 @@ mod tests {
304 304 let hidden: Vec<Option<bool>> = states.iter().map(|state| state.hidden).collect();
305 305 assert_eq!(
306 306 hidden,
307 [Some(true), Some(false), Some(true), None, Some(true), Some(true)]
307 [
308 Some(true),
309 Some(false),
310 Some(true),
311 None,
312 Some(true),
313 Some(true)
314 ]
308 315 );
309 316 }
310 317
@@ -304,7 +304,14 @@ mod tests {
304 let hidden: Vec<Option<bool>> = states.iter().map(|state| state.hidden).collect();
304 let hidden: Vec<Option<bool>> = states.iter().map(|state| state.hidden).collect();
305 assert_eq!(
305 assert_eq!(
306 hidden,
306 hidden,
307 [Some(true), Some(false), Some(true), None, Some(true), Some(true)]
307 [
308 Some(true),
309 Some(false),
310 Some(true),
311 None,
312 Some(true),
313 Some(true)
314 ]
308 );
315 );
309 }
316 }
310
317
crates/chatsvc/src/emotions.rs +1 −5
@@ -57,11 +57,7 @@ pub fn parse_message_emotions(body: &Value) -> Vec<MessageEmotions> {
57 57 .into_iter()
58 58 .flatten()
59 59 .filter_map(|message| {
60 let message_id = match message.get("id")? {
61 Value::String(text) if !text.is_empty() => text.clone(),
62 Value::Number(number) => number.to_string(),
63 _ => return None,
64 };
60 let message_id = crate::json_id::id_text(message.get("id")?)?;
65 61 Some(MessageEmotions {
66 62 message_id,
67 63 reactions: reactions(message.pointer("/properties/emotions")),
@@ -57,11 +57,7 @@ pub fn parse_message_emotions(body: &Value) -> Vec<MessageEmotions> {
57 .into_iter()
57 .into_iter()
58 .flatten()
58 .flatten()
59 .filter_map(|message| {
59 .filter_map(|message| {
60 let message_id = match message.get("id")? {
60 let message_id = crate::json_id::id_text(message.get("id")?)?;
61 Value::String(text) if !text.is_empty() => text.clone(),
62 Value::Number(number) => number.to_string(),
63 _ => return None,
64 };
65 Some(MessageEmotions {
61 Some(MessageEmotions {
66 message_id,
62 message_id,
67 reactions: reactions(message.pointer("/properties/emotions")),
63 reactions: reactions(message.pointer("/properties/emotions")),
crates/chatsvc/src/json_id.rs added +42 −0
@@ -0,0 +1,42 @@
1 use serde_json::{Number, Value};
2
3 pub(crate) fn id_text(value: &Value) -> Option<String> {
4 match value {
5 Value::String(text) if !text.is_empty() => Some(text.clone()),
6 Value::Number(number) => Some(integer_text(number)),
7 _ => None,
8 }
9 }
10
11 fn integer_text(number: &Number) -> String {
12 match number.as_f64() {
13 Some(float) if number.is_f64() && float.fract() == 0.0 && float >= 0.0 => {
14 format!("{float:.0}")
15 }
16 _ => number.to_string(),
17 }
18 }
19
20 #[cfg(test)]
21 mod tests {
22 use serde_json::json;
23
24 use super::*;
25
26 #[test]
27 fn float_ids_read_as_integers() {
28 assert_eq!(
29 id_text(&json!(1783430602049.0)).as_deref(),
30 Some("1783430602049")
31 );
32 assert_eq!(
33 id_text(&json!(1783430602049u64)).as_deref(),
34 Some("1783430602049")
35 );
36 assert_eq!(
37 id_text(&json!("1783430602049")).as_deref(),
38 Some("1783430602049")
39 );
40 assert_eq!(id_text(&json!("")), None);
41 }
42 }
@@ -0,0 +1,42 @@
1use serde_json::{Number, Value};
2
3pub(crate) fn id_text(value: &Value) -> Option<String> {
4 match value {
5 Value::String(text) if !text.is_empty() => Some(text.clone()),
6 Value::Number(number) => Some(integer_text(number)),
7 _ => None,
8 }
9}
10
11fn integer_text(number: &Number) -> String {
12 match number.as_f64() {
13 Some(float) if number.is_f64() && float.fract() == 0.0 && float >= 0.0 => {
14 format!("{float:.0}")
15 }
16 _ => number.to_string(),
17 }
18}
19
20#[cfg(test)]
21mod tests {
22 use serde_json::json;
23
24 use super::*;
25
26 #[test]
27 fn float_ids_read_as_integers() {
28 assert_eq!(
29 id_text(&json!(1783430602049.0)).as_deref(),
30 Some("1783430602049")
31 );
32 assert_eq!(
33 id_text(&json!(1783430602049u64)).as_deref(),
34 Some("1783430602049")
35 );
36 assert_eq!(
37 id_text(&json!("1783430602049")).as_deref(),
38 Some("1783430602049")
39 );
40 assert_eq!(id_text(&json!("")), None);
41 }
42}
crates/chatsvc/src/lib.rs +17 −13
@@ -8,6 +8,7 @@ pub mod emotions;
8 8 mod error;
9 9 pub mod forward;
10 10 pub mod gifs;
11 mod json_id;
11 12 pub mod language_settings;
12 13 pub mod links;
13 14 mod mask;
@@ -16,10 +17,10 @@ pub mod pins;
16 17 pub mod presence;
17 18 pub mod reactions;
18 19 pub mod read_horizon;
19 pub mod recap;
20 20 pub mod realtime;
21 pub mod recording_policy;
21 pub mod recap;
22 22 pub mod receipts;
23 pub mod recording_policy;
23 24 pub mod saved;
24 25 pub mod settings;
25 26 pub mod sound_settings;
@@ -29,8 +30,8 @@ pub mod translate;
29 30 pub mod window;
30 31
31 32 pub use calendar::{
32 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply, ResponseType,
33 meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
33 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
34 ResponseType, meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
34 35 };
35 36 pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
36 37 pub use cards::{
@@ -38,8 +39,8 @@ pub use cards::{
38 39 };
39 40 pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
40 41 pub use conversations::{ConversationState, Conversations};
41 pub use read_horizon::ReadHorizon;
42 42 pub use drafts::{ScheduledDraft, ScheduledDrafts};
43 pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
43 44 pub use error::{Error, Result};
44 45 pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
45 46 pub use gifs::{Gif, Gifs};
@@ -47,7 +48,6 @@ pub use language_settings::{
47 48 LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
48 49 parse_language_settings, target_patch,
49 50 };
50 pub use recording_policy::{RecordingPolicy, parse_recording_policy};
51 51 pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
52 52 pub use mask::mask_conversation_id;
53 53 pub use messages::{ConversationRef, Messages};
@@ -56,23 +56,27 @@ pub use pins::{
56 56 PinnedMessage, Pins, TeamLayout,
57 57 };
58 58 pub use presence::{
59 ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
60 WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
59 ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote,
60 WorkLocation, WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
61 61 };
62 pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
63 pub use reactions::{emotion_glyph, insert_skin_tone, reaction_glyph_for_key, emotion_key, emotion_keys, reaction_key, reaction_keys};
62 pub use reactions::{
63 emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,
64 reaction_key, reaction_keys,
65 };
66 pub use read_horizon::ReadHorizon;
64 67 pub use realtime::{
65 68 CallbackReplier, EventKind, InstanceNames, MessageEvent, PresenceUpdate, Realtime,
66 69 RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind, TrouterCallback, TrouterEndpoint,
67 70 TypingEvent,
68 71 };
69 pub use receipts::{MemberHorizon, Receipts};
70 pub use saved::SavedMessage;
71 pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
72 72 pub use recap::{
73 73 Attendance, AttendanceRecord, Occurrence, Recap, RecordingDetails, TranscriptFormat,
74 74 days_until_expiry,
75 75 };
76 pub use receipts::{MemberHorizon, Receipts};
77 pub use recording_policy::{RecordingPolicy, parse_recording_policy};
78 pub use saved::SavedMessage;
79 pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
76 80 pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};
77 81 pub use translate::{
78 82 Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
@@ -8,6 +8,7 @@ pub mod emotions;
8mod error;
8mod error;
9pub mod forward;
9pub mod forward;
10pub mod gifs;
10pub mod gifs;
11mod json_id;
11pub mod language_settings;
12pub mod language_settings;
12pub mod links;
13pub mod links;
13mod mask;
14mod mask;
@@ -16,10 +17,10 @@ pub mod pins;
16pub mod presence;
17pub mod presence;
17pub mod reactions;
18pub mod reactions;
18pub mod read_horizon;
19pub mod read_horizon;
19pub mod recap;
20pub mod realtime;
20pub mod realtime;
21pub mod recording_policy;
21pub mod recap;
22pub mod receipts;
22pub mod receipts;
23pub mod recording_policy;
23pub mod saved;
24pub mod saved;
24pub mod settings;
25pub mod settings;
25pub mod sound_settings;
26pub mod sound_settings;
@@ -29,8 +30,8 @@ pub mod translate;
29pub mod window;
30pub mod window;
30
31
31pub use calendar::{
32pub use calendar::{
32 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply, ResponseType,
33 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
33 meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
34 ResponseType, meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
34};
35};
35pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
36pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
36pub use cards::{
37pub use cards::{
@@ -38,8 +39,8 @@ pub use cards::{
38};
39};
39pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
40pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
40pub use conversations::{ConversationState, Conversations};
41pub use conversations::{ConversationState, Conversations};
41pub use read_horizon::ReadHorizon;
42pub use drafts::{ScheduledDraft, ScheduledDrafts};
42pub use drafts::{ScheduledDraft, ScheduledDrafts};
43pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
43pub use error::{Error, Result};
44pub use error::{Error, Result};
44pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
45pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
45pub use gifs::{Gif, Gifs};
46pub use gifs::{Gif, Gifs};
@@ -47,7 +48,6 @@ pub use language_settings::{
47 LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
48 LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
48 parse_language_settings, target_patch,
49 parse_language_settings, target_patch,
49};
50};
50pub use recording_policy::{RecordingPolicy, parse_recording_policy};
51pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
51pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
52pub use mask::mask_conversation_id;
52pub use mask::mask_conversation_id;
53pub use messages::{ConversationRef, Messages};
53pub use messages::{ConversationRef, Messages};
@@ -56,23 +56,27 @@ pub use pins::{
56 PinnedMessage, Pins, TeamLayout,
56 PinnedMessage, Pins, TeamLayout,
57};
57};
58pub use presence::{
58pub use presence::{
59 ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
59 ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote,
60 WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
60 WorkLocation, WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
61};
61};
62pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
62pub use reactions::{
63pub use reactions::{emotion_glyph, insert_skin_tone, reaction_glyph_for_key, emotion_key, emotion_keys, reaction_key, reaction_keys};
63 emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,
64 reaction_key, reaction_keys,
65};
66pub use read_horizon::ReadHorizon;
64pub use realtime::{
67pub use realtime::{
65 CallbackReplier, EventKind, InstanceNames, MessageEvent, PresenceUpdate, Realtime,
68 CallbackReplier, EventKind, InstanceNames, MessageEvent, PresenceUpdate, Realtime,
66 RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind, TrouterCallback, TrouterEndpoint,
69 RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind, TrouterCallback, TrouterEndpoint,
67 TypingEvent,
70 TypingEvent,
68};
71};
69pub use receipts::{MemberHorizon, Receipts};
70pub use saved::SavedMessage;
71pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
72pub use recap::{
72pub use recap::{
73 Attendance, AttendanceRecord, Occurrence, Recap, RecordingDetails, TranscriptFormat,
73 Attendance, AttendanceRecord, Occurrence, Recap, RecordingDetails, TranscriptFormat,
74 days_until_expiry,
74 days_until_expiry,
75};
75};
76pub use receipts::{MemberHorizon, Receipts};
77pub use recording_policy::{RecordingPolicy, parse_recording_policy};
78pub use saved::SavedMessage;
79pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
76pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};
80pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};
77pub use translate::{
81pub use translate::{
78 Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
82 Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
crates/chatsvc/src/pins/state.rs +1 −3
@@ -24,9 +24,7 @@ pub(super) fn hierarchy_version(body: &Value) -> Result<i64> {
24 24 number
25 25 .as_f64()
26 26 .filter(|float| float.is_finite() && float.fract() == 0.0)
27 .filter(|float| {
28 *float >= i64::MIN as f64 && *float < i64::MAX as f64
29 })
27 .filter(|float| *float >= i64::MIN as f64 && *float < i64::MAX as f64)
30 28 .map(|float| float as i64)
31 29 }),
32 30 Value::String(text) => text.trim().parse::<i64>().ok(),
@@ -24,9 +24,7 @@ pub(super) fn hierarchy_version(body: &Value) -> Result<i64> {
24 number
24 number
25 .as_f64()
25 .as_f64()
26 .filter(|float| float.is_finite() && float.fract() == 0.0)
26 .filter(|float| float.is_finite() && float.fract() == 0.0)
27 .filter(|float| {
27 .filter(|float| *float >= i64::MIN as f64 && *float < i64::MAX as f64)
28 *float >= i64::MIN as f64 && *float < i64::MAX as f64
29 })
30 .map(|float| float as i64)
28 .map(|float| float as i64)
31 }),
29 }),
32 Value::String(text) => text.trim().parse::<i64>().ok(),
30 Value::String(text) => text.trim().parse::<i64>().ok(),
crates/chatsvc/src/pins/teams.rs +5 −1
@@ -297,7 +297,11 @@ mod tests {
297 297 .collect();
298 298 assert_eq!(
299 299 names,
300 ["Lunch Order Board \u{1F37D}\u{FE0F}", "100% done", "Bad%FFbytes"]
300 [
301 "Lunch Order Board \u{1F37D}\u{FE0F}",
302 "100% done",
303 "Bad%FFbytes"
304 ]
301 305 );
302 306 }
303 307
@@ -297,7 +297,11 @@ mod tests {
297 .collect();
297 .collect();
298 assert_eq!(
298 assert_eq!(
299 names,
299 names,
300 ["Lunch Order Board \u{1F37D}\u{FE0F}", "100% done", "Bad%FFbytes"]
300 [
301 "Lunch Order Board \u{1F37D}\u{FE0F}",
302 "100% done",
303 "Bad%FFbytes"
304 ]
301 );
305 );
302 }
306 }
303
307
crates/chatsvc/src/presence.rs +15 −4
@@ -147,9 +147,14 @@ impl<T: CardTransport> PresenceService<T> {
147 147 self.send(request, &url).await.map(drop)
148 148 }
149 149
150 pub async fn register_endpoint(&self, endpoint_id: &str, reporting: ActivityReporting) -> Result<()> {
150 pub async fn register_endpoint(
151 &self,
152 endpoint_id: &str,
153 reporting: ActivityReporting,
154 ) -> Result<()> {
151 155 let url = format!("{BASE_URL}/me/endpoints/");
152 let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
156 let mut request =
157 Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
153 158 request.headers = endpoint_headers(endpoint_id);
154 159 self.send(request, &url).await.map(drop)
155 160 }
@@ -502,7 +507,10 @@ mod tests {
502 507 #[tokio::test]
503 508 async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
504 509 let service = service(200, Value::Null);
505 service.register_endpoint("epid-1", ActivityReporting::Transport).await.unwrap();
510 service
511 .register_endpoint("epid-1", ActivityReporting::Transport)
512 .await
513 .unwrap();
506 514 let (request, scope) = only_request(&service);
507 515 assert_eq!(request.method, Method::Put);
508 516 assert_eq!(
@@ -533,7 +541,10 @@ mod tests {
533 541 #[tokio::test]
534 542 async fn register_endpoint_can_switch_to_direct_reporting() {
535 543 let service = service(200, Value::Null);
536 service.register_endpoint("epid-1", ActivityReporting::Direct).await.unwrap();
544 service
545 .register_endpoint("epid-1", ActivityReporting::Direct)
546 .await
547 .unwrap();
537 548 let (request, _) = only_request(&service);
538 549 assert_eq!(request.body.unwrap()["activityReporting"], "Direct");
539 550 }
@@ -147,9 +147,14 @@ impl<T: CardTransport> PresenceService<T> {
147 self.send(request, &url).await.map(drop)
147 self.send(request, &url).await.map(drop)
148 }
148 }
149
149
150 pub async fn register_endpoint(&self, endpoint_id: &str, reporting: ActivityReporting) -> Result<()> {
150 pub async fn register_endpoint(
151 &self,
152 endpoint_id: &str,
153 reporting: ActivityReporting,
154 ) -> Result<()> {
151 let url = format!("{BASE_URL}/me/endpoints/");
155 let url = format!("{BASE_URL}/me/endpoints/");
152 let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
156 let mut request =
157 Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
153 request.headers = endpoint_headers(endpoint_id);
158 request.headers = endpoint_headers(endpoint_id);
154 self.send(request, &url).await.map(drop)
159 self.send(request, &url).await.map(drop)
155 }
160 }
@@ -502,7 +507,10 @@ mod tests {
502 #[tokio::test]
507 #[tokio::test]
503 async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
508 async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
504 let service = service(200, Value::Null);
509 let service = service(200, Value::Null);
505 service.register_endpoint("epid-1", ActivityReporting::Transport).await.unwrap();
510 service
511 .register_endpoint("epid-1", ActivityReporting::Transport)
512 .await
513 .unwrap();
506 let (request, scope) = only_request(&service);
514 let (request, scope) = only_request(&service);
507 assert_eq!(request.method, Method::Put);
515 assert_eq!(request.method, Method::Put);
508 assert_eq!(
516 assert_eq!(
@@ -533,7 +541,10 @@ mod tests {
533 #[tokio::test]
541 #[tokio::test]
534 async fn register_endpoint_can_switch_to_direct_reporting() {
542 async fn register_endpoint_can_switch_to_direct_reporting() {
535 let service = service(200, Value::Null);
543 let service = service(200, Value::Null);
536 service.register_endpoint("epid-1", ActivityReporting::Direct).await.unwrap();
544 service
545 .register_endpoint("epid-1", ActivityReporting::Direct)
546 .await
547 .unwrap();
537 let (request, _) = only_request(&service);
548 let (request, _) = only_request(&service);
538 assert_eq!(request.body.unwrap()["activityReporting"], "Direct");
549 assert_eq!(request.body.unwrap()["activityReporting"], "Direct");
539 }
550 }
crates/chatsvc/src/realtime/event.rs +4 −1
@@ -180,7 +180,10 @@ pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
180 180 activity: if entry.out_of_office {
181 181 Some(OUT_OF_OFFICE_ACTIVITY.to_owned())
182 182 } else {
183 entry.activity.map(bounded).filter(|value| !value.is_empty())
183 entry
184 .activity
185 .map(bounded)
186 .filter(|value| !value.is_empty())
184 187 },
185 188 })
186 189 })
@@ -180,7 +180,10 @@ pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
180 activity: if entry.out_of_office {
180 activity: if entry.out_of_office {
181 Some(OUT_OF_OFFICE_ACTIVITY.to_owned())
181 Some(OUT_OF_OFFICE_ACTIVITY.to_owned())
182 } else {
182 } else {
183 entry.activity.map(bounded).filter(|value| !value.is_empty())
183 entry
184 .activity
185 .map(bounded)
186 .filter(|value| !value.is_empty())
184 },
187 },
185 })
188 })
186 })
189 })
crates/chatsvc/src/realtime/mod.rs +1 −1
@@ -13,11 +13,11 @@ use session::Session;
13 13 use tokio::sync::{Notify, mpsc, oneshot, watch};
14 14 use tokio::task::JoinHandle;
15 15
16 pub use callback::{CallbackReplier, TrouterCallback};
16 17 pub use event::{
17 18 EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,
18 19 TrouterEndpoint, TypingEvent, decode_payload,
19 20 };
20 pub use callback::{CallbackReplier, TrouterCallback};
21 21 pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
22 22
23 23 use crate::error::Result;
@@ -13,11 +13,11 @@ use session::Session;
13use tokio::sync::{Notify, mpsc, oneshot, watch};
13use tokio::sync::{Notify, mpsc, oneshot, watch};
14use tokio::task::JoinHandle;
14use tokio::task::JoinHandle;
15
15
16pub use callback::{CallbackReplier, TrouterCallback};
16pub use event::{
17pub use event::{
17 EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,
18 EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,
18 TrouterEndpoint, TypingEvent, decode_payload,
19 TrouterEndpoint, TypingEvent, decode_payload,
19};
20};
20pub use callback::{CallbackReplier, TrouterCallback};
21pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
21pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
22
22
23use crate::error::Result;
23use crate::error::Result;
crates/chatsvc/src/realtime/runner.rs +42 −14
@@ -34,9 +34,13 @@ impl PageScript {
34 34 let mut worker_source = WORKER_TEMPLATE
35 35 .replace(&quoted(DEFAULT_GLOBAL_NAME), &quoted(&names.global))
36 36 .replace(&quoted(DEFAULT_BINDING_NAME), &quoted(&names.binding))
37 .replace(&quoted(DEFAULT_EPID_KEY), &quoted(&names.endpoint_storage_key));
37 .replace(
38 &quoted(DEFAULT_EPID_KEY),
39 &quoted(&names.endpoint_storage_key),
40 );
38 41 if config.forward_callbacks {
39 worker_source = worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");
42 worker_source =
43 worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");
40 44 }
41 45 if config.ringable {
42 46 worker_source = worker_source.replace(REGISTRATION_OFF, "const RINGABLE = true;");
@@ -90,7 +94,10 @@ pub(super) struct Attached {
90 94 stop_expression: String,
91 95 }
92 96
93 pub(super) async fn attach(session: &Session, script: &PageScript) -> crate::error::Result<Attached> {
97 pub(super) async fn attach(
98 session: &Session,
99 script: &PageScript,
100 ) -> crate::error::Result<Attached> {
94 101 let (control, events) = session.subscribe(App::Teams).await?;
95 102 control.enable_events().await?;
96 103 control.add_binding(&script.binding_name).await?;
@@ -378,11 +385,9 @@ mod tests {
378 385 fn ensure_body_embeds_the_worker_once_before_the_call() {
379 386 let ensure_body = PageScript::new(&RealtimeConfig::default()).ensure_body();
380 387 assert!(ensure_body.starts_with("(() => {"));
381 assert!(
382 ensure_body
383 .trim_end()
384 .ends_with("window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});")
385 );
388 assert!(ensure_body.trim_end().ends_with(
389 "window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});"
390 ));
386 391 assert_eq!(ensure_body.matches("const VERSION").count(), 1);
387 392 }
388 393
@@ -399,9 +404,20 @@ mod tests {
399 404 };
400 405 let script = PageScript::new(&config);
401 406 assert!(!script.worker_source.contains("__chatsvc"));
402 assert!(script.worker_source.contains("const GLOBAL_NAME = '__callingTrouter';"));
403 assert!(script.worker_source.contains("const FORWARD_CALLBACKS = true;"));
404 assert_eq!(script.stop_expression(), "window.__callingTrouter ? window.__callingTrouter.stop() : null");
407 assert!(
408 script
409 .worker_source
410 .contains("const GLOBAL_NAME = '__callingTrouter';")
411 );
412 assert!(
413 script
414 .worker_source
415 .contains("const FORWARD_CALLBACKS = true;")
416 );
417 assert_eq!(
418 script.stop_expression(),
419 "window.__callingTrouter ? window.__callingTrouter.stop() : null"
420 );
405 421 let default_script = PageScript::new(&RealtimeConfig::default());
406 422 assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF));
407 423 }
@@ -416,9 +432,21 @@ mod tests {
416 432 let quiet = PageScript::new(&RealtimeConfig::default());
417 433 assert!(quiet.worker_source.contains(REGISTRATION_OFF));
418 434 for script in [ringable, quiet] {
419 assert!(script.worker_source.contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}"));
420 assert!(script.worker_source.contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}"));
421 assert!(script.worker_source.contains("RINGABLE ? {productContext: ''} : {}"));
435 assert!(
436 script
437 .worker_source
438 .contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}")
439 );
440 assert!(
441 script
442 .worker_source
443 .contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}")
444 );
445 assert!(
446 script
447 .worker_source
448 .contains("RINGABLE ? {productContext: ''} : {}")
449 );
422 450 }
423 451 }
424 452 }
@@ -34,9 +34,13 @@ impl PageScript {
34 let mut worker_source = WORKER_TEMPLATE
34 let mut worker_source = WORKER_TEMPLATE
35 .replace(&quoted(DEFAULT_GLOBAL_NAME), &quoted(&names.global))
35 .replace(&quoted(DEFAULT_GLOBAL_NAME), &quoted(&names.global))
36 .replace(&quoted(DEFAULT_BINDING_NAME), &quoted(&names.binding))
36 .replace(&quoted(DEFAULT_BINDING_NAME), &quoted(&names.binding))
37 .replace(&quoted(DEFAULT_EPID_KEY), &quoted(&names.endpoint_storage_key));
37 .replace(
38 &quoted(DEFAULT_EPID_KEY),
39 &quoted(&names.endpoint_storage_key),
40 );
38 if config.forward_callbacks {
41 if config.forward_callbacks {
39 worker_source = worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");
42 worker_source =
43 worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");
40 }
44 }
41 if config.ringable {
45 if config.ringable {
42 worker_source = worker_source.replace(REGISTRATION_OFF, "const RINGABLE = true;");
46 worker_source = worker_source.replace(REGISTRATION_OFF, "const RINGABLE = true;");
@@ -90,7 +94,10 @@ pub(super) struct Attached {
90 stop_expression: String,
94 stop_expression: String,
91}
95}
92
96
93pub(super) async fn attach(session: &Session, script: &PageScript) -> crate::error::Result<Attached> {
97pub(super) async fn attach(
98 session: &Session,
99 script: &PageScript,
100) -> crate::error::Result<Attached> {
94 let (control, events) = session.subscribe(App::Teams).await?;
101 let (control, events) = session.subscribe(App::Teams).await?;
95 control.enable_events().await?;
102 control.enable_events().await?;
96 control.add_binding(&script.binding_name).await?;
103 control.add_binding(&script.binding_name).await?;
@@ -378,11 +385,9 @@ mod tests {
378 fn ensure_body_embeds_the_worker_once_before_the_call() {
385 fn ensure_body_embeds_the_worker_once_before_the_call() {
379 let ensure_body = PageScript::new(&RealtimeConfig::default()).ensure_body();
386 let ensure_body = PageScript::new(&RealtimeConfig::default()).ensure_body();
380 assert!(ensure_body.starts_with("(() => {"));
387 assert!(ensure_body.starts_with("(() => {"));
381 assert!(
388 assert!(ensure_body.trim_end().ends_with(
382 ensure_body
389 "window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});"
383 .trim_end()
390 ));
384 .ends_with("window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});")
385 );
386 assert_eq!(ensure_body.matches("const VERSION").count(), 1);
391 assert_eq!(ensure_body.matches("const VERSION").count(), 1);
387 }
392 }
388
393
@@ -399,9 +404,20 @@ mod tests {
399 };
404 };
400 let script = PageScript::new(&config);
405 let script = PageScript::new(&config);
401 assert!(!script.worker_source.contains("__chatsvc"));
406 assert!(!script.worker_source.contains("__chatsvc"));
402 assert!(script.worker_source.contains("const GLOBAL_NAME = '__callingTrouter';"));
407 assert!(
403 assert!(script.worker_source.contains("const FORWARD_CALLBACKS = true;"));
408 script
404 assert_eq!(script.stop_expression(), "window.__callingTrouter ? window.__callingTrouter.stop() : null");
409 .worker_source
410 .contains("const GLOBAL_NAME = '__callingTrouter';")
411 );
412 assert!(
413 script
414 .worker_source
415 .contains("const FORWARD_CALLBACKS = true;")
416 );
417 assert_eq!(
418 script.stop_expression(),
419 "window.__callingTrouter ? window.__callingTrouter.stop() : null"
420 );
405 let default_script = PageScript::new(&RealtimeConfig::default());
421 let default_script = PageScript::new(&RealtimeConfig::default());
406 assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF));
422 assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF));
407 }
423 }
@@ -416,9 +432,21 @@ mod tests {
416 let quiet = PageScript::new(&RealtimeConfig::default());
432 let quiet = PageScript::new(&RealtimeConfig::default());
417 assert!(quiet.worker_source.contains(REGISTRATION_OFF));
433 assert!(quiet.worker_source.contains(REGISTRATION_OFF));
418 for script in [ringable, quiet] {
434 for script in [ringable, quiet] {
419 assert!(script.worker_source.contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}"));
435 assert!(
420 assert!(script.worker_source.contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}"));
436 script
421 assert!(script.worker_source.contains("RINGABLE ? {productContext: ''} : {}"));
437 .worker_source
438 .contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}")
439 );
440 assert!(
441 script
442 .worker_source
443 .contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}")
444 );
445 assert!(
446 script
447 .worker_source
448 .contains("RINGABLE ? {productContext: ''} : {}")
449 );
422 }
450 }
423 }
451 }
424}
452}
crates/chatsvc/src/recap.rs +12 −14
@@ -344,10 +344,7 @@ impl<'a> Recap<'a> {
344 344 }
345 345 Err(error) => return Err(error),
346 346 };
347 let Some(report_id) = reports
348 .pointer("/value/0/id")
349 .and_then(Value::as_str)
350 else {
347 let Some(report_id) = reports.pointer("/value/0/id").and_then(Value::as_str) else {
351 348 return Ok(Attendance::TurnedOff);
352 349 };
353 350 let report = self
@@ -386,7 +383,9 @@ fn item_url(site: &str, item: &Value) -> Option<String> {
386 383 .pointer("/parentReference/driveId")
387 384 .and_then(Value::as_str)?;
388 385 let item_id = item.get("id").and_then(Value::as_str)?;
389 Some(format!("{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"))
386 Some(format!(
387 "{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"
388 ))
390 389 }
391 390
392 391 fn decode_binary(body: &Value) -> Option<Vec<u8>> {
@@ -443,7 +442,8 @@ pub fn parse_audio_only_names(chatsvc_messages_json: &Value) -> HashSet<String>
443 442 .into_iter()
444 443 .flatten()
445 444 .filter(|message| {
446 message.get("messagetype").and_then(Value::as_str) == Some("RichText/Media_CallRecording")
445 message.get("messagetype").and_then(Value::as_str)
446 == Some("RichText/Media_CallRecording")
447 447 })
448 448 .filter_map(|message| message.get("content").and_then(Value::as_str))
449 449 .filter(|content| content.contains(AUDIO_ONLY_MARKER))
@@ -505,9 +505,7 @@ pub fn parse_iso_duration(text: &str) -> Option<u64> {
505 505 }
506 506
507 507 pub fn parse_expiration(listing_json: &Value) -> Option<DateTime<Utc>> {
508 let stamp = listing_json
509 .pointer("/fields/_ExpirationDate")?
510 .as_str()?;
508 let stamp = listing_json.pointer("/fields/_ExpirationDate")?.as_str()?;
511 509 DateTime::parse_from_rfc3339(stamp)
512 510 .ok()
513 511 .map(|stamp| stamp.with_timezone(&Utc))
@@ -589,10 +587,7 @@ mod tests {
589 587 use super::*;
590 588
591 589 fn fixture(name: &str) -> Value {
592 let path = format!(
593 "{}/tests/fixtures/recap/{name}",
594 env!("CARGO_MANIFEST_DIR")
595 );
590 let path = format!("{}/tests/fixtures/recap/{name}", env!("CARGO_MANIFEST_DIR"));
596 591 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
597 592 }
598 593
@@ -602,7 +597,10 @@ mod tests {
602 597 assert_eq!(occurrences.len(), 2);
603 598 assert_eq!(occurrences[0].message_id, "2002");
604 599 assert_eq!(occurrences[0].duration_seconds, Some(1832));
605 assert_eq!(occurrences[0].organizer_id.as_deref(), Some("user-organizer"));
600 assert_eq!(
601 occurrences[0].organizer_id.as_deref(),
602 Some("user-organizer")
603 );
606 604 assert_eq!(occurrences[1].message_id, "2001");
607 605 assert_eq!(occurrences[1].duration_seconds, None);
608 606 }
@@ -344,10 +344,7 @@ impl<'a> Recap<'a> {
344 }
344 }
345 Err(error) => return Err(error),
345 Err(error) => return Err(error),
346 };
346 };
347 let Some(report_id) = reports
347 let Some(report_id) = reports.pointer("/value/0/id").and_then(Value::as_str) else {
348 .pointer("/value/0/id")
349 .and_then(Value::as_str)
350 else {
351 return Ok(Attendance::TurnedOff);
348 return Ok(Attendance::TurnedOff);
352 };
349 };
353 let report = self
350 let report = self
@@ -386,7 +383,9 @@ fn item_url(site: &str, item: &Value) -> Option<String> {
386 .pointer("/parentReference/driveId")
383 .pointer("/parentReference/driveId")
387 .and_then(Value::as_str)?;
384 .and_then(Value::as_str)?;
388 let item_id = item.get("id").and_then(Value::as_str)?;
385 let item_id = item.get("id").and_then(Value::as_str)?;
389 Some(format!("{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"))
386 Some(format!(
387 "{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"
388 ))
390}
389}
391
390
392fn decode_binary(body: &Value) -> Option<Vec<u8>> {
391fn decode_binary(body: &Value) -> Option<Vec<u8>> {
@@ -443,7 +442,8 @@ pub fn parse_audio_only_names(chatsvc_messages_json: &Value) -> HashSet<String>
443 .into_iter()
442 .into_iter()
444 .flatten()
443 .flatten()
445 .filter(|message| {
444 .filter(|message| {
446 message.get("messagetype").and_then(Value::as_str) == Some("RichText/Media_CallRecording")
445 message.get("messagetype").and_then(Value::as_str)
446 == Some("RichText/Media_CallRecording")
447 })
447 })
448 .filter_map(|message| message.get("content").and_then(Value::as_str))
448 .filter_map(|message| message.get("content").and_then(Value::as_str))
449 .filter(|content| content.contains(AUDIO_ONLY_MARKER))
449 .filter(|content| content.contains(AUDIO_ONLY_MARKER))
@@ -505,9 +505,7 @@ pub fn parse_iso_duration(text: &str) -> Option<u64> {
505}
505}
506
506
507pub fn parse_expiration(listing_json: &Value) -> Option<DateTime<Utc>> {
507pub fn parse_expiration(listing_json: &Value) -> Option<DateTime<Utc>> {
508 let stamp = listing_json
508 let stamp = listing_json.pointer("/fields/_ExpirationDate")?.as_str()?;
509 .pointer("/fields/_ExpirationDate")?
510 .as_str()?;
511 DateTime::parse_from_rfc3339(stamp)
509 DateTime::parse_from_rfc3339(stamp)
512 .ok()
510 .ok()
513 .map(|stamp| stamp.with_timezone(&Utc))
511 .map(|stamp| stamp.with_timezone(&Utc))
@@ -589,10 +587,7 @@ mod tests {
589 use super::*;
587 use super::*;
590
588
591 fn fixture(name: &str) -> Value {
589 fn fixture(name: &str) -> Value {
592 let path = format!(
590 let path = format!("{}/tests/fixtures/recap/{name}", env!("CARGO_MANIFEST_DIR"));
593 "{}/tests/fixtures/recap/{name}",
594 env!("CARGO_MANIFEST_DIR")
595 );
596 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
591 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
597 }
592 }
598
593
@@ -602,7 +597,10 @@ mod tests {
602 assert_eq!(occurrences.len(), 2);
597 assert_eq!(occurrences.len(), 2);
603 assert_eq!(occurrences[0].message_id, "2002");
598 assert_eq!(occurrences[0].message_id, "2002");
604 assert_eq!(occurrences[0].duration_seconds, Some(1832));
599 assert_eq!(occurrences[0].duration_seconds, Some(1832));
605 assert_eq!(occurrences[0].organizer_id.as_deref(), Some("user-organizer"));
600 assert_eq!(
601 occurrences[0].organizer_id.as_deref(),
602 Some("user-organizer")
603 );
606 assert_eq!(occurrences[1].message_id, "2001");
604 assert_eq!(occurrences[1].message_id, "2001");
607 assert_eq!(occurrences[1].duration_seconds, None);
605 assert_eq!(occurrences[1].duration_seconds, None);
608 }
606 }
crates/chatsvc/src/saved.rs +1 −5
@@ -24,11 +24,7 @@ pub struct SavedMessage {
24 24 }
25 25
26 26 fn text_or_number(value: &Value, key: &str) -> Option<String> {
27 match value.get(key)? {
28 Value::String(text) if !text.is_empty() => Some(text.clone()),
29 Value::Number(number) => Some(number.to_string()),
30 _ => None,
31 }
27 crate::json_id::id_text(value.get(key)?)
32 28 }
33 29
34 30 fn activity_of(message: &Value) -> Option<Value> {
@@ -24,11 +24,7 @@ pub struct SavedMessage {
24}
24}
25
25
26fn text_or_number(value: &Value, key: &str) -> Option<String> {
26fn text_or_number(value: &Value, key: &str) -> Option<String> {
27 match value.get(key)? {
27 crate::json_id::id_text(value.get(key)?)
28 Value::String(text) if !text.is_empty() => Some(text.clone()),
29 Value::Number(number) => Some(number.to_string()),
30 _ => None,
31 }
32}
28}
33
29
34fn activity_of(message: &Value) -> Option<Value> {
30fn activity_of(message: &Value) -> Option<Value> {
crates/chatsvc/src/settings.rs +21 −5
@@ -12,6 +12,7 @@ const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
12 12 const MAX_SKIN_TONE: u8 = 5;
13 13 const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
14 14 const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
15 const ADAPTIVE_RAIL_FIELD: &str = "hasUserEnabledAdaptiveRailForDesktop";
15 16 const MUTED_DEFAULT: bool = false;
16 17 const MEETING_DEFAULT: bool = false;
17 18
@@ -34,6 +35,7 @@ impl ChatSection {
34 35 pub struct ChatSectionSettings {
35 36 pub muted: Option<bool>,
36 37 pub meeting: Option<bool>,
38 pub adaptive_rail: Option<bool>,
37 39 }
38 40
39 41 impl ChatSectionSettings {
@@ -44,6 +46,10 @@ impl ChatSectionSettings {
44 46 }
45 47 }
46 48
49 pub fn adaptive_rail(&self) -> bool {
50 self.adaptive_rail.unwrap_or(false)
51 }
52
47 53 pub fn set(&mut self, section: ChatSection, enabled: bool) {
48 54 match section {
49 55 ChatSection::Muted => self.muted = Some(enabled),
@@ -128,6 +134,7 @@ pub fn parse_chat_sections(properties: &Value) -> ChatSectionSettings {
128 134 ChatSectionSettings {
129 135 muted: settings.get(MUTED_FIELD).and_then(Value::as_bool),
130 136 meeting: settings.get(MEETING_FIELD).and_then(Value::as_bool),
137 adaptive_rail: settings.get(ADAPTIVE_RAIL_FIELD).and_then(Value::as_bool),
131 138 }
132 139 }
133 140
@@ -210,8 +217,14 @@ mod tests {
210 217
211 218 #[test]
212 219 fn skin_tone_is_read_from_the_string_property() {
213 assert_eq!(parse_skin_tone(&json!({"preferredSkinToneIndex": "2"})), Some(2));
214 assert_eq!(parse_skin_tone(&json!({"preferredSkinToneIndex": "9"})), None);
220 assert_eq!(
221 parse_skin_tone(&json!({"preferredSkinToneIndex": "2"})),
222 Some(2)
223 );
224 assert_eq!(
225 parse_skin_tone(&json!({"preferredSkinToneIndex": "9"})),
226 None
227 );
215 228 assert_eq!(parse_skin_tone(&json!({})), None);
216 229 }
217 230
@@ -221,15 +234,17 @@ mod tests {
221 234 assert_eq!(parsed, ChatSectionSettings::default());
222 235 assert!(!parsed.enabled(ChatSection::Muted));
223 236 assert!(!parsed.enabled(ChatSection::Meeting));
237 assert!(!parsed.adaptive_rail());
224 238 }
225 239
226 240 #[test]
227 fn reads_both_flags_from_the_json_string() {
241 fn reads_every_flag_from_the_json_string() {
228 242 let parsed = parse_chat_sections(&properties(
229 r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMutedChatSection":false,"hasUserEnabledMeetingChatSection":true}"#,
243 r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMutedChatSection":false,"hasUserEnabledMeetingChatSection":true,"hasUserEnabledAdaptiveRailForDesktop":true}"#,
230 244 ));
231 245 assert!(!parsed.enabled(ChatSection::Muted));
232 246 assert!(parsed.enabled(ChatSection::Meeting));
247 assert!(parsed.adaptive_rail());
233 248 }
234 249
235 250 #[test]
@@ -275,7 +290,8 @@ mod tests {
275 290 parse_chat_sections(&json!({SETTINGS_KEY: merged})),
276 291 ChatSectionSettings {
277 292 muted: Some(false),
278 meeting: Some(true)
293 meeting: Some(true),
294 adaptive_rail: None,
279 295 }
280 296 );
281 297 }
@@ -12,6 +12,7 @@ const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
12const MAX_SKIN_TONE: u8 = 5;
12const MAX_SKIN_TONE: u8 = 5;
13const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
13const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
14const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
14const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
15const ADAPTIVE_RAIL_FIELD: &str = "hasUserEnabledAdaptiveRailForDesktop";
15const MUTED_DEFAULT: bool = false;
16const MUTED_DEFAULT: bool = false;
16const MEETING_DEFAULT: bool = false;
17const MEETING_DEFAULT: bool = false;
17
18
@@ -34,6 +35,7 @@ impl ChatSection {
34pub struct ChatSectionSettings {
35pub struct ChatSectionSettings {
35 pub muted: Option<bool>,
36 pub muted: Option<bool>,
36 pub meeting: Option<bool>,
37 pub meeting: Option<bool>,
38 pub adaptive_rail: Option<bool>,
37}
39}
38
40
39impl ChatSectionSettings {
41impl ChatSectionSettings {
@@ -44,6 +46,10 @@ impl ChatSectionSettings {
44 }
46 }
45 }
47 }
46
48
49 pub fn adaptive_rail(&self) -> bool {
50 self.adaptive_rail.unwrap_or(false)
51 }
52
47 pub fn set(&mut self, section: ChatSection, enabled: bool) {
53 pub fn set(&mut self, section: ChatSection, enabled: bool) {
48 match section {
54 match section {
49 ChatSection::Muted => self.muted = Some(enabled),
55 ChatSection::Muted => self.muted = Some(enabled),
@@ -128,6 +134,7 @@ pub fn parse_chat_sections(properties: &Value) -> ChatSectionSettings {
128 ChatSectionSettings {
134 ChatSectionSettings {
129 muted: settings.get(MUTED_FIELD).and_then(Value::as_bool),
135 muted: settings.get(MUTED_FIELD).and_then(Value::as_bool),
130 meeting: settings.get(MEETING_FIELD).and_then(Value::as_bool),
136 meeting: settings.get(MEETING_FIELD).and_then(Value::as_bool),
137 adaptive_rail: settings.get(ADAPTIVE_RAIL_FIELD).and_then(Value::as_bool),
131 }
138 }
132}
139}
133
140
@@ -210,8 +217,14 @@ mod tests {
210
217
211 #[test]
218 #[test]
212 fn skin_tone_is_read_from_the_string_property() {
219 fn skin_tone_is_read_from_the_string_property() {
213 assert_eq!(parse_skin_tone(&json!({"preferredSkinToneIndex": "2"})), Some(2));
220 assert_eq!(
214 assert_eq!(parse_skin_tone(&json!({"preferredSkinToneIndex": "9"})), None);
221 parse_skin_tone(&json!({"preferredSkinToneIndex": "2"})),
222 Some(2)
223 );
224 assert_eq!(
225 parse_skin_tone(&json!({"preferredSkinToneIndex": "9"})),
226 None
227 );
215 assert_eq!(parse_skin_tone(&json!({})), None);
228 assert_eq!(parse_skin_tone(&json!({})), None);
216 }
229 }
217
230
@@ -221,15 +234,17 @@ mod tests {
221 assert_eq!(parsed, ChatSectionSettings::default());
234 assert_eq!(parsed, ChatSectionSettings::default());
222 assert!(!parsed.enabled(ChatSection::Muted));
235 assert!(!parsed.enabled(ChatSection::Muted));
223 assert!(!parsed.enabled(ChatSection::Meeting));
236 assert!(!parsed.enabled(ChatSection::Meeting));
237 assert!(!parsed.adaptive_rail());
224 }
238 }
225
239
226 #[test]
240 #[test]
227 fn reads_both_flags_from_the_json_string() {
241 fn reads_every_flag_from_the_json_string() {
228 let parsed = parse_chat_sections(&properties(
242 let parsed = parse_chat_sections(&properties(
229 r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMutedChatSection":false,"hasUserEnabledMeetingChatSection":true}"#,
243 r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMutedChatSection":false,"hasUserEnabledMeetingChatSection":true,"hasUserEnabledAdaptiveRailForDesktop":true}"#,
230 ));
244 ));
231 assert!(!parsed.enabled(ChatSection::Muted));
245 assert!(!parsed.enabled(ChatSection::Muted));
232 assert!(parsed.enabled(ChatSection::Meeting));
246 assert!(parsed.enabled(ChatSection::Meeting));
247 assert!(parsed.adaptive_rail());
233 }
248 }
234
249
235 #[test]
250 #[test]
@@ -275,7 +290,8 @@ mod tests {
275 parse_chat_sections(&json!({SETTINGS_KEY: merged})),
290 parse_chat_sections(&json!({SETTINGS_KEY: merged})),
276 ChatSectionSettings {
291 ChatSectionSettings {
277 muted: Some(false),
292 muted: Some(false),
278 meeting: Some(true)
293 meeting: Some(true),
294 adaptive_rail: None,
279 }
295 }
280 );
296 );
281 }
297 }
crates/chatsvc/src/sound_settings.rs +15 −6
@@ -148,7 +148,11 @@ pub fn merge_sound_settings(
148 148 ));
149 149 }
150 150 if previous.urgent_sound != updated.urgent_sound {
151 changes.push((TOAST_SETTINGS, URGENT_SOUND, switch_value(updated.urgent_sound)));
151 changes.push((
152 TOAST_SETTINGS,
153 URGENT_SOUND,
154 switch_value(updated.urgent_sound),
155 ));
152 156 }
153 157 if previous.urgent_sound_type != updated.urgent_sound_type {
154 158 changes.push((
@@ -200,8 +204,10 @@ pub fn aggregate_read_body() -> Value {
200 204 json!({"voiceAdminSettings": true})
201 205 }
202 206
203 pub struct SoundSettingsClient<P: MessageTransport = SessionMessageTransport, M: CsaTransport = SessionTransport>
204 {
207 pub struct SoundSettingsClient<
208 P: MessageTransport = SessionMessageTransport,
209 M: CsaTransport = SessionTransport,
210 > {
205 211 properties: UserSettings<P>,
206 212 middle_tier: M,
207 213 middle_tier_url: String,
@@ -356,9 +362,12 @@ mod tests {
356 362 sound_when_busy: false,
357 363 ..previous.clone()
358 364 };
359 let merged: Value =
360 serde_json::from_str(&merge_sound_settings(&properties(personal), &previous, &updated))
361 .unwrap();
365 let merged: Value = serde_json::from_str(&merge_sound_settings(
366 &properties(personal),
367 &previous,
368 &updated,
369 ))
370 .unwrap();
362 371 assert_eq!(
363 372 merged,
364 373 json!({
@@ -148,7 +148,11 @@ pub fn merge_sound_settings(
148 ));
148 ));
149 }
149 }
150 if previous.urgent_sound != updated.urgent_sound {
150 if previous.urgent_sound != updated.urgent_sound {
151 changes.push((TOAST_SETTINGS, URGENT_SOUND, switch_value(updated.urgent_sound)));
151 changes.push((
152 TOAST_SETTINGS,
153 URGENT_SOUND,
154 switch_value(updated.urgent_sound),
155 ));
152 }
156 }
153 if previous.urgent_sound_type != updated.urgent_sound_type {
157 if previous.urgent_sound_type != updated.urgent_sound_type {
154 changes.push((
158 changes.push((
@@ -200,8 +204,10 @@ pub fn aggregate_read_body() -> Value {
200 json!({"voiceAdminSettings": true})
204 json!({"voiceAdminSettings": true})
201}
205}
202
206
203pub struct SoundSettingsClient<P: MessageTransport = SessionMessageTransport, M: CsaTransport = SessionTransport>
207pub struct SoundSettingsClient<
204{
208 P: MessageTransport = SessionMessageTransport,
209 M: CsaTransport = SessionTransport,
210> {
205 properties: UserSettings<P>,
211 properties: UserSettings<P>,
206 middle_tier: M,
212 middle_tier: M,
207 middle_tier_url: String,
213 middle_tier_url: String,
@@ -356,9 +362,12 @@ mod tests {
356 sound_when_busy: false,
362 sound_when_busy: false,
357 ..previous.clone()
363 ..previous.clone()
358 };
364 };
359 let merged: Value =
365 let merged: Value = serde_json::from_str(&merge_sound_settings(
360 serde_json::from_str(&merge_sound_settings(&properties(personal), &previous, &updated))
366 &properties(personal),
361 .unwrap();
367 &previous,
368 &updated,
369 ))
370 .unwrap();
362 assert_eq!(
371 assert_eq!(
363 merged,
372 merged,
364 json!({
373 json!({
crates/chatsvc/src/sounds.rs +4 −1
@@ -315,7 +315,10 @@ mod tests {
315 315 format!("{}.mp3", ringtone.name().to_lowercase())
316 316 );
317 317 }
318 assert_eq!(Ringtone::from_name("wishgranted"), Some(Ringtone::WishGranted));
318 assert_eq!(
319 Ringtone::from_name("wishgranted"),
320 Some(Ringtone::WishGranted)
321 );
319 322 assert_eq!(Ringtone::from_name("Chime"), None);
320 323 assert_eq!(Ringtone::Ring.label(), "Default");
321 324 }
@@ -315,7 +315,10 @@ mod tests {
315 format!("{}.mp3", ringtone.name().to_lowercase())
315 format!("{}.mp3", ringtone.name().to_lowercase())
316 );
316 );
317 }
317 }
318 assert_eq!(Ringtone::from_name("wishgranted"), Some(Ringtone::WishGranted));
318 assert_eq!(
319 Ringtone::from_name("wishgranted"),
320 Some(Ringtone::WishGranted)
321 );
319 assert_eq!(Ringtone::from_name("Chime"), None);
322 assert_eq!(Ringtone::from_name("Chime"), None);
320 assert_eq!(Ringtone::Ring.label(), "Default");
323 assert_eq!(Ringtone::Ring.label(), "Default");
321 }
324 }
crates/chatsvc/src/window.rs +1 −5
@@ -38,11 +38,7 @@ fn is_user_message(message: &Value) -> bool {
38 38 }
39 39
40 40 fn message_id(message: &Value) -> Option<String> {
41 match message.get("id")? {
42 Value::String(text) if !text.is_empty() => Some(text.clone()),
43 Value::Number(number) => Some(number.to_string()),
44 _ => None,
45 }
41 crate::json_id::id_text(message.get("id")?)
46 42 }
47 43
48 44 fn cursor_of(body: &Value, link_key: &str) -> Option<String> {
@@ -38,11 +38,7 @@ fn is_user_message(message: &Value) -> bool {
38}
38}
39
39
40fn message_id(message: &Value) -> Option<String> {
40fn message_id(message: &Value) -> Option<String> {
41 match message.get("id")? {
41 crate::json_id::id_text(message.get("id")?)
42 Value::String(text) if !text.is_empty() => Some(text.clone()),
43 Value::Number(number) => Some(number.to_string()),
44 _ => None,
45 }
46}
42}
47
43
48fn cursor_of(body: &Value, link_key: &str) -> Option<String> {
44fn cursor_of(body: &Value, link_key: &str) -> Option<String> {
crates/core/src/folders.rs +3 −0
@@ -383,6 +383,7 @@ const KIND_MEETING: &str = "MeetingChats";
383 383 const KIND_MUTED: &str = "MutedChats";
384 384 const META_MUTED_SECTION: &str = "chat_section_muted";
385 385 const META_MEETING_SECTION: &str = "chat_section_meeting";
386 const META_ADAPTIVE_RAIL: &str = "adaptive_rail";
386 387
387 388 fn to_record(folder: &ChatFolder) -> FolderRecord {
388 389 FolderRecord {
@@ -428,6 +429,7 @@ pub fn stored_section_settings(store: &Store) -> ChatSectionSettings {
428 429 ChatSectionSettings {
429 430 muted: read(META_MUTED_SECTION),
430 431 meeting: read(META_MEETING_SECTION),
432 adaptive_rail: read(META_ADAPTIVE_RAIL),
431 433 }
432 434 }
433 435
@@ -435,6 +437,7 @@ pub fn store_section_settings(store: &Store, settings: &ChatSectionSettings) ->
435 437 for (key, value) in [
436 438 (META_MUTED_SECTION, settings.muted),
437 439 (META_MEETING_SECTION, settings.meeting),
440 (META_ADAPTIVE_RAIL, settings.adaptive_rail),
438 441 ] {
439 442 let text = value.map(|enabled| enabled.to_string()).unwrap_or_default();
440 443 store.set_meta(key, &text)?;
@@ -383,6 +383,7 @@ const KIND_MEETING: &str = "MeetingChats";
383const KIND_MUTED: &str = "MutedChats";
383const KIND_MUTED: &str = "MutedChats";
384const META_MUTED_SECTION: &str = "chat_section_muted";
384const META_MUTED_SECTION: &str = "chat_section_muted";
385const META_MEETING_SECTION: &str = "chat_section_meeting";
385const META_MEETING_SECTION: &str = "chat_section_meeting";
386const META_ADAPTIVE_RAIL: &str = "adaptive_rail";
386
387
387fn to_record(folder: &ChatFolder) -> FolderRecord {
388fn to_record(folder: &ChatFolder) -> FolderRecord {
388 FolderRecord {
389 FolderRecord {
@@ -428,6 +429,7 @@ pub fn stored_section_settings(store: &Store) -> ChatSectionSettings {
428 ChatSectionSettings {
429 ChatSectionSettings {
429 muted: read(META_MUTED_SECTION),
430 muted: read(META_MUTED_SECTION),
430 meeting: read(META_MEETING_SECTION),
431 meeting: read(META_MEETING_SECTION),
432 adaptive_rail: read(META_ADAPTIVE_RAIL),
431 }
433 }
432}
434}
433
435
@@ -435,6 +437,7 @@ pub fn store_section_settings(store: &Store, settings: &ChatSectionSettings) ->
435 for (key, value) in [
437 for (key, value) in [
436 (META_MUTED_SECTION, settings.muted),
438 (META_MUTED_SECTION, settings.muted),
437 (META_MEETING_SECTION, settings.meeting),
439 (META_MEETING_SECTION, settings.meeting),
440 (META_ADAPTIVE_RAIL, settings.adaptive_rail),
438 ] {
441 ] {
439 let text = value.map(|enabled| enabled.to_string()).unwrap_or_default();
442 let text = value.map(|enabled| enabled.to_string()).unwrap_or_default();
440 store.set_meta(key, &text)?;
443 store.set_meta(key, &text)?;
crates/core/tests/engine.rs +2 −0
@@ -3106,6 +3106,7 @@ async fn collapse_and_section_settings_go_through_the_source() {
3106 3106 Arc::get_mut(&mut source).unwrap().settings = ChatSectionSettings {
3107 3107 muted: Some(false),
3108 3108 meeting: Some(true),
3109 adaptive_rail: Some(true),
3109 3110 };
3110 3111 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
3111 3112 let mut events = engine.subscribe();
@@ -3117,6 +3118,7 @@ async fn collapse_and_section_settings_go_through_the_source() {
3117 3118 ChatSectionSettings {
3118 3119 muted: Some(false),
3119 3120 meeting: Some(true),
3121 adaptive_rail: Some(true),
3120 3122 }
3121 3123 );
3122 3124
@@ -3106,6 +3106,7 @@ async fn collapse_and_section_settings_go_through_the_source() {
3106 Arc::get_mut(&mut source).unwrap().settings = ChatSectionSettings {
3106 Arc::get_mut(&mut source).unwrap().settings = ChatSectionSettings {
3107 muted: Some(false),
3107 muted: Some(false),
3108 meeting: Some(true),
3108 meeting: Some(true),
3109 adaptive_rail: Some(true),
3109 };
3110 };
3110 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
3111 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
3111 let mut events = engine.subscribe();
3112 let mut events = engine.subscribe();
@@ -3117,6 +3118,7 @@ async fn collapse_and_section_settings_go_through_the_source() {
3117 ChatSectionSettings {
3118 ChatSectionSettings {
3118 muted: Some(false),
3119 muted: Some(false),
3119 meeting: Some(true),
3120 meeting: Some(true),
3121 adaptive_rail: Some(true),
3120 }
3122 }
3121 );
3123 );
3122
3124