BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into feat/chat-batch2

# Conflicts:
#	crates/app/src/views/conversation.rs
#	crates/chatsvc/src/settings.rs

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
7bc118d893728cbc8c05d77d44d996044ad60a72
68 files changed +4240 −380
GUARDRAILS.md +1 −0
@@ -24,6 +24,7 @@ Rules for every change, by people and by agents. If a rule here and a habit else
24 24 | Local bugs | Fix Teams bugs that are purely local (rendering, scroll, focus). Anything touching server data or other people stays as Teams does it. |
25 25 | Performance | Faster, less memory, offline reading from the cache. |
26 26 | Platform | OS-native toasts, tray, title bar and sounds. |
27 | Call windows | Daniel-approved (2026-10-17): a call stays in the main window with the sidebar, Teams opens its own meeting window. A window share leaves the main window as it is (side by side), Teams minimizes it. Only our own window behaviour, nothing others see changes. |
27 28 | Own features | MCP, agents, session inbox: allowed when nobody else can tell. Nothing sent automatically, no own message formats. |
28 29 | Own settings | Settings Teams does not know stay in the local DB, never in Teams account properties. |
29 30
@@ -24,6 +24,7 @@ Rules for every change, by people and by agents. If a rule here and a habit else
24| Local bugs | Fix Teams bugs that are purely local (rendering, scroll, focus). Anything touching server data or other people stays as Teams does it. |
24| Local bugs | Fix Teams bugs that are purely local (rendering, scroll, focus). Anything touching server data or other people stays as Teams does it. |
25| Performance | Faster, less memory, offline reading from the cache. |
25| Performance | Faster, less memory, offline reading from the cache. |
26| Platform | OS-native toasts, tray, title bar and sounds. |
26| Platform | OS-native toasts, tray, title bar and sounds. |
27| Call windows | Daniel-approved (2026-10-17): a call stays in the main window with the sidebar, Teams opens its own meeting window. A window share leaves the main window as it is (side by side), Teams minimizes it. Only our own window behaviour, nothing others see changes. |
27| Own features | MCP, agents, session inbox: allowed when nobody else can tell. Nothing sent automatically, no own message formats. |
28| Own features | MCP, agents, session inbox: allowed when nobody else can tell. Nothing sent automatically, no own message formats. |
28| Own settings | Settings Teams does not know stay in the local DB, never in Teams account properties. |
29| Own settings | Settings Teams does not know stay in the local DB, never in Teams account properties. |
29
30
crates/app-base/src/notify/platform/stub.rs +2 −0
@@ -34,6 +34,8 @@ pub fn show_window_inactive(_handle: NativeHandle) {}
34 34
35 35 pub fn exclude_from_capture(_handle: NativeHandle) {}
36 36
37 pub fn include_in_capture(_handle: NativeHandle) {}
38
37 39 #[cfg(target_os = "linux")]
38 40 pub fn make_window_click_through(window: &Window) {
39 41 super::x11_input::make_input_transparent(window);
@@ -34,6 +34,8 @@ pub fn show_window_inactive(_handle: NativeHandle) {}
34
34
35pub fn exclude_from_capture(_handle: NativeHandle) {}
35pub fn exclude_from_capture(_handle: NativeHandle) {}
36
36
37pub fn include_in_capture(_handle: NativeHandle) {}
38
37#[cfg(target_os = "linux")]
39#[cfg(target_os = "linux")]
38pub fn make_window_click_through(window: &Window) {
40pub fn make_window_click_through(window: &Window) {
39 super::x11_input::make_input_transparent(window);
41 super::x11_input::make_input_transparent(window);
crates/app-base/src/notify/platform/windows_impl.rs +7 −1
@@ -34,7 +34,7 @@ use windows::Win32::UI::WindowsAndMessaging::{
34 34 SW_SHOWNOACTIVATE, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE,
35 35 SWP_NOZORDER, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SendMessageW, SetForegroundWindow,
36 36 SetLayeredWindowAttributes, SetWindowDisplayAffinity, SetWindowLongPtrW, SetWindowPos,
37 ShowWindow, SystemParametersInfoW, WDA_EXCLUDEFROMCAPTURE, WM_SETICON, WS_CAPTION,
37 ShowWindow, SystemParametersInfoW, WDA_EXCLUDEFROMCAPTURE, WDA_NONE, WM_SETICON, WS_CAPTION,
38 38 WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_POPUP, WS_THICKFRAME,
39 39 };
40 40 use windows::core::{BOOL, PCWSTR, w};
@@ -272,6 +272,12 @@ pub fn exclude_from_capture(handle: NativeHandle) {
272 272 }
273 273 }
274 274
275 pub fn include_in_capture(handle: NativeHandle) {
276 unsafe {
277 let _ = SetWindowDisplayAffinity(hwnd(handle), WDA_NONE);
278 }
279 }
280
275 281 pub fn make_window_click_through(window: &Window) {
276 282 if let Some(handle) = native_handle(window) {
277 283 make_click_through(handle);
@@ -34,7 +34,7 @@ use windows::Win32::UI::WindowsAndMessaging::{
34 SW_SHOWNOACTIVATE, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE,
34 SW_SHOWNOACTIVATE, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE,
35 SWP_NOZORDER, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SendMessageW, SetForegroundWindow,
35 SWP_NOZORDER, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SendMessageW, SetForegroundWindow,
36 SetLayeredWindowAttributes, SetWindowDisplayAffinity, SetWindowLongPtrW, SetWindowPos,
36 SetLayeredWindowAttributes, SetWindowDisplayAffinity, SetWindowLongPtrW, SetWindowPos,
37 ShowWindow, SystemParametersInfoW, WDA_EXCLUDEFROMCAPTURE, WM_SETICON, WS_CAPTION,
37 ShowWindow, SystemParametersInfoW, WDA_EXCLUDEFROMCAPTURE, WDA_NONE, WM_SETICON, WS_CAPTION,
38 WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_POPUP, WS_THICKFRAME,
38 WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_POPUP, WS_THICKFRAME,
39};
39};
40use windows::core::{BOOL, PCWSTR, w};
40use windows::core::{BOOL, PCWSTR, w};
@@ -272,6 +272,12 @@ pub fn exclude_from_capture(handle: NativeHandle) {
272 }
272 }
273}
273}
274
274
275pub fn include_in_capture(handle: NativeHandle) {
276 unsafe {
277 let _ = SetWindowDisplayAffinity(hwnd(handle), WDA_NONE);
278 }
279}
280
275pub fn make_window_click_through(window: &Window) {
281pub fn make_window_click_through(window: &Window) {
276 if let Some(handle) = native_handle(window) {
282 if let Some(handle) = native_handle(window) {
277 make_click_through(handle);
283 make_click_through(handle);
crates/app-base/src/read_state.rs +28 −0
@@ -19,12 +19,40 @@ pub fn plan_read(window_active: bool, chat_unread: bool, trigger: ReadTrigger) -
19 19 })
20 20 }
21 21
22 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
23 pub enum JumpTarget {
24 LastRead(usize),
25 Newest,
26 }
27
28 pub fn jump_target(
29 last_read_index: Option<usize>,
30 top_item: usize,
31 scrolled_up: bool,
32 ) -> Option<JumpTarget> {
33 match last_read_index {
34 _ if scrolled_up => Some(JumpTarget::Newest),
35 Some(index) if index < top_item => Some(JumpTarget::LastRead(index)),
36 _ => None,
37 }
38 }
39
22 40 #[cfg(test)]
23 41 mod tests {
24 42 use std::collections::HashMap;
25 43
26 44 use super::*;
27 45
46 #[test]
47 fn jump_goes_to_last_read_from_the_newest_and_to_the_newest_from_anywhere_else() {
48 assert_eq!(jump_target(Some(4), 10, false), Some(JumpTarget::LastRead(4)));
49 assert_eq!(jump_target(Some(4), 2, true), Some(JumpTarget::Newest));
50 assert_eq!(jump_target(Some(4), 3, true), Some(JumpTarget::Newest));
51 assert_eq!(jump_target(None, 3, true), Some(JumpTarget::Newest));
52 assert_eq!(jump_target(Some(4), 4, false), None);
53 assert_eq!(jump_target(None, 0, false), None);
54 }
55
28 56 struct LocalState {
29 57 unread_counts: HashMap<String, u32>,
30 58 unread: bool,
@@ -19,12 +19,40 @@ pub fn plan_read(window_active: bool, chat_unread: bool, trigger: ReadTrigger) -
19 })
19 })
20}
20}
21
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum JumpTarget {
24 LastRead(usize),
25 Newest,
26}
27
28pub fn jump_target(
29 last_read_index: Option<usize>,
30 top_item: usize,
31 scrolled_up: bool,
32) -> Option<JumpTarget> {
33 match last_read_index {
34 _ if scrolled_up => Some(JumpTarget::Newest),
35 Some(index) if index < top_item => Some(JumpTarget::LastRead(index)),
36 _ => None,
37 }
38}
39
22#[cfg(test)]
40#[cfg(test)]
23mod tests {
41mod tests {
24 use std::collections::HashMap;
42 use std::collections::HashMap;
25
43
26 use super::*;
44 use super::*;
27
45
46 #[test]
47 fn jump_goes_to_last_read_from_the_newest_and_to_the_newest_from_anywhere_else() {
48 assert_eq!(jump_target(Some(4), 10, false), Some(JumpTarget::LastRead(4)));
49 assert_eq!(jump_target(Some(4), 2, true), Some(JumpTarget::Newest));
50 assert_eq!(jump_target(Some(4), 3, true), Some(JumpTarget::Newest));
51 assert_eq!(jump_target(None, 3, true), Some(JumpTarget::Newest));
52 assert_eq!(jump_target(Some(4), 4, false), None);
53 assert_eq!(jump_target(None, 0, false), None);
54 }
55
28 struct LocalState {
56 struct LocalState {
29 unread_counts: HashMap<String, u32>,
57 unread_counts: HashMap<String, u32>,
30 unread: bool,
58 unread: bool,
crates/app-call-model/src/demo.rs +13 −3
@@ -104,6 +104,8 @@ pub enum DemoScene {
104 104 Mini,
105 105 MiniOff,
106 106 MiniShare,
107 GalleryShare,
108 WindowShare,
107 109 Blocked,
108 110 Removed,
109 111 Dropped,
@@ -126,6 +128,8 @@ impl DemoScene {
126 128 "mini" => DemoScene::Mini,
127 129 "mini-off" => DemoScene::MiniOff,
128 130 "mini-share" => DemoScene::MiniShare,
131 "gallery-share" => DemoScene::GalleryShare,
132 "window-share" => DemoScene::WindowShare,
129 133 "blocked" => DemoScene::Blocked,
130 134 "removed" => DemoScene::Removed,
131 135 "dropped" => DemoScene::Dropped,
@@ -163,7 +167,9 @@ impl DemoScene {
163 167 pub fn guests(self) -> Option<usize> {
164 168 match self {
165 169 DemoScene::Gallery => Some(DEMO_GALLERY_GUESTS),
166 DemoScene::Sharing => Some(DEMO_SHARING_GUESTS),
170 DemoScene::Sharing | DemoScene::GalleryShare | DemoScene::WindowShare => {
171 Some(DEMO_SHARING_GUESTS)
172 }
167 173 _ => None,
168 174 }
169 175 }
@@ -186,6 +192,7 @@ impl DemoScene {
186 192
187 193 pub const DEMO_GALLERY_GUESTS: usize = 12;
188 194 const DEMO_SHARING_GUESTS: usize = 9;
195 const DEMO_SHARED_WINDOW: &str = "Standup board";
189 196 const BREAKOUT_AT_TICKS: u32 = 20;
190 197 const WHITEBOARD_AT_TICKS: u32 = 5;
191 198 const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";
@@ -269,7 +276,7 @@ fn demo_share_sources() -> Vec<ShareSource> {
269 276 title: String::new(),
270 277 },
271 278 window(2, "Release notes - Docs"),
272 window(3, "Standup board"),
279 window(3, DEMO_SHARED_WINDOW),
273 280 window(4, "Terminal"),
274 281 ]
275 282 }
@@ -451,9 +458,12 @@ fn start_scene(control: &CallControl, scene: DemoScene) {
451 458 DemoScene::Hold => control.send(CallUpdate::Hold(HoldState::Local)),
452 459 DemoScene::Held => control.send(CallUpdate::Hold(HoldState::Remote)),
453 460 DemoScene::Network => control.send(CallUpdate::Health(poor_network_health())),
454 DemoScene::MiniShare => {
461 DemoScene::MiniShare | DemoScene::GalleryShare => {
455 462 control.send(CallUpdate::LocalShare(Some("Entire screen".to_owned())))
456 463 }
464 DemoScene::WindowShare => {
465 control.send(CallUpdate::LocalShare(Some(DEMO_SHARED_WINDOW.to_owned())))
466 }
457 467 DemoScene::Call
458 468 | DemoScene::Mini
459 469 | DemoScene::MiniOff
@@ -104,6 +104,8 @@ pub enum DemoScene {
104 Mini,
104 Mini,
105 MiniOff,
105 MiniOff,
106 MiniShare,
106 MiniShare,
107 GalleryShare,
108 WindowShare,
107 Blocked,
109 Blocked,
108 Removed,
110 Removed,
109 Dropped,
111 Dropped,
@@ -126,6 +128,8 @@ impl DemoScene {
126 "mini" => DemoScene::Mini,
128 "mini" => DemoScene::Mini,
127 "mini-off" => DemoScene::MiniOff,
129 "mini-off" => DemoScene::MiniOff,
128 "mini-share" => DemoScene::MiniShare,
130 "mini-share" => DemoScene::MiniShare,
131 "gallery-share" => DemoScene::GalleryShare,
132 "window-share" => DemoScene::WindowShare,
129 "blocked" => DemoScene::Blocked,
133 "blocked" => DemoScene::Blocked,
130 "removed" => DemoScene::Removed,
134 "removed" => DemoScene::Removed,
131 "dropped" => DemoScene::Dropped,
135 "dropped" => DemoScene::Dropped,
@@ -163,7 +167,9 @@ impl DemoScene {
163 pub fn guests(self) -> Option<usize> {
167 pub fn guests(self) -> Option<usize> {
164 match self {
168 match self {
165 DemoScene::Gallery => Some(DEMO_GALLERY_GUESTS),
169 DemoScene::Gallery => Some(DEMO_GALLERY_GUESTS),
166 DemoScene::Sharing => Some(DEMO_SHARING_GUESTS),
170 DemoScene::Sharing | DemoScene::GalleryShare | DemoScene::WindowShare => {
171 Some(DEMO_SHARING_GUESTS)
172 }
167 _ => None,
173 _ => None,
168 }
174 }
169 }
175 }
@@ -186,6 +192,7 @@ impl DemoScene {
186
192
187pub const DEMO_GALLERY_GUESTS: usize = 12;
193pub const DEMO_GALLERY_GUESTS: usize = 12;
188const DEMO_SHARING_GUESTS: usize = 9;
194const DEMO_SHARING_GUESTS: usize = 9;
195const DEMO_SHARED_WINDOW: &str = "Standup board";
189const BREAKOUT_AT_TICKS: u32 = 20;
196const BREAKOUT_AT_TICKS: u32 = 20;
190const WHITEBOARD_AT_TICKS: u32 = 5;
197const WHITEBOARD_AT_TICKS: u32 = 5;
191const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";
198const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";
@@ -269,7 +276,7 @@ fn demo_share_sources() -> Vec<ShareSource> {
269 title: String::new(),
276 title: String::new(),
270 },
277 },
271 window(2, "Release notes - Docs"),
278 window(2, "Release notes - Docs"),
272 window(3, "Standup board"),
279 window(3, DEMO_SHARED_WINDOW),
273 window(4, "Terminal"),
280 window(4, "Terminal"),
274 ]
281 ]
275}
282}
@@ -451,9 +458,12 @@ fn start_scene(control: &CallControl, scene: DemoScene) {
451 DemoScene::Hold => control.send(CallUpdate::Hold(HoldState::Local)),
458 DemoScene::Hold => control.send(CallUpdate::Hold(HoldState::Local)),
452 DemoScene::Held => control.send(CallUpdate::Hold(HoldState::Remote)),
459 DemoScene::Held => control.send(CallUpdate::Hold(HoldState::Remote)),
453 DemoScene::Network => control.send(CallUpdate::Health(poor_network_health())),
460 DemoScene::Network => control.send(CallUpdate::Health(poor_network_health())),
454 DemoScene::MiniShare => {
461 DemoScene::MiniShare | DemoScene::GalleryShare => {
455 control.send(CallUpdate::LocalShare(Some("Entire screen".to_owned())))
462 control.send(CallUpdate::LocalShare(Some("Entire screen".to_owned())))
456 }
463 }
464 DemoScene::WindowShare => {
465 control.send(CallUpdate::LocalShare(Some(DEMO_SHARED_WINDOW.to_owned())))
466 }
457 DemoScene::Call
467 DemoScene::Call
458 | DemoScene::Mini
468 | DemoScene::Mini
459 | DemoScene::MiniOff
469 | DemoScene::MiniOff
crates/app-state/src/agents/message_context.rs +1 −0
@@ -218,6 +218,7 @@ mod tests {
218 218 hidden: false,
219 219 hidden_channel_ids: Vec::new(),
220 220 notifications: Default::default(),
221 mentions: Default::default(),
221 222 });
222 223 let context = build(&state, "19:chat", "reply-2").unwrap();
223 224 let texts: Vec<&str> = context
@@ -218,6 +218,7 @@ mod tests {
218 hidden: false,
218 hidden: false,
219 hidden_channel_ids: Vec::new(),
219 hidden_channel_ids: Vec::new(),
220 notifications: Default::default(),
220 notifications: Default::default(),
221 mentions: Default::default(),
221 });
222 });
222 let context = build(&state, "19:chat", "reply-2").unwrap();
223 let context = build(&state, "19:chat", "reply-2").unwrap();
223 let texts: Vec<&str> = context
224 let texts: Vec<&str> = context
crates/app-state/src/app_state.rs +72 −4
@@ -109,6 +109,7 @@ pub struct AppState {
109 109 pub live_retry: Option<Arc<tokio::sync::Notify>>,
110 110 pub notice_count: u64,
111 111 pub keep_unread: Option<String>,
112 pub restorable_deletes: crate::restorable_deletes::RestorableDeletes,
112 113 pub typing: TypingState,
113 114 typing_timer_running: bool,
114 115 pub local_previews: HashMap<String, LocalPreview>,
@@ -261,6 +262,7 @@ impl AppState {
261 262 live_retry: None,
262 263 notice_count: 0,
263 264 keep_unread: None,
265 restorable_deletes: Default::default(),
264 266 typing: TypingState::default(),
265 267 typing_timer_running: false,
266 268 local_previews: HashMap::new(),
@@ -685,6 +687,32 @@ impl AppState {
685 687 conversation_id: &str,
686 688 folder_id: Option<&str>,
687 689 cx: &mut Context<Self>,
690 ) {
691 self.place_chat(conversation_id, folder_id, None, cx);
692 }
693
694 pub fn drop_chat_on(
695 &mut self,
696 conversation_id: &str,
697 target_conversation_id: &str,
698 folder_id: &str,
699 cx: &mut Context<Self>,
700 ) {
701 if conversation_id == target_conversation_id {
702 return;
703 }
704 let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else {
705 return;
706 };
707 self.place_chat(conversation_id, Some(folder_id), Some(slot), cx);
708 }
709
710 pub fn place_chat(
711 &mut self,
712 conversation_id: &str,
713 folder_id: Option<&str>,
714 index: Option<usize>,
715 cx: &mut Context<Self>,
688 716 ) {
689 717 if self.mode.read_only {
690 718 return;
@@ -693,13 +721,16 @@ impl AppState {
693 721 .directory
694 722 .folder_of(conversation_id)
695 723 .map(|folder| folder.id.clone());
696 self.directory.assign(conversation_id, folder_id);
724 self.directory.place(conversation_id, folder_id, index);
697 725 if let Some(engine) = self.engine.clone() {
698 726 let previous = previous_folder.clone();
699 727 let done = match (folder_id, previous.as_deref()) {
700 (Some(folder_id), _) => {
701 Some(data::move_to_folder(&engine, conversation_id, folder_id))
702 }
728 (Some(folder_id), _) => Some(data::move_to_folder(
729 &engine,
730 conversation_id,
731 folder_id,
732 index,
733 )),
703 734 (None, Some(previous)) => {
704 735 Some(data::remove_from_folder(&engine, conversation_id, previous))
705 736 }
@@ -767,6 +798,42 @@ impl AppState {
767 798 }
768 799 }
769 800
801 pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) {
802 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
803 return;
804 };
805 let previous_unread: Vec<(String, bool, Option<DateTime<Utc>>)> = self
806 .sidebar
807 .teams
808 .iter()
809 .flat_map(|team| team.channels.iter())
810 .map(|channel| (channel.id.clone(), channel.unread, None))
811 .collect();
812 let previous_mentions: Vec<(String, store::ChannelMentions)> = self
813 .sidebar
814 .teams
815 .iter()
816 .flat_map(|team| team.mentions.iter())
817 .map(|(channel_id, mentions)| (channel_id.clone(), *mentions))
818 .collect();
819 let _ = self.store.mark_all_channels_read();
820 self.reload_sidebar(cx);
821 let Some(engine) = engine_or_demo else {
822 return;
823 };
824 self.run_chat_action(
825 "Mark all as read",
826 async move { engine.mark_all_channels_read().await },
827 move |state, cx| {
828 let _ = state.store.apply_channel_read_states(&previous_unread);
829 let _ = state.store.replace_channel_mentions(&previous_mentions);
830 state.reload_sidebar(cx);
831 },
832 |_, _| {},
833 cx,
834 );
835 }
836
770 837 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
771 838 self.new_chat = true;
772 839 self.show_call(false, cx);
@@ -1068,6 +1135,7 @@ mod tests {
1068 1135 hidden: false,
1069 1136 hidden_channel_ids: Vec::new(),
1070 1137 notifications: Default::default(),
1138 mentions: Default::default(),
1071 1139 }],
1072 1140 }
1073 1141 }
@@ -109,6 +109,7 @@ pub struct AppState {
109 pub live_retry: Option<Arc<tokio::sync::Notify>>,
109 pub live_retry: Option<Arc<tokio::sync::Notify>>,
110 pub notice_count: u64,
110 pub notice_count: u64,
111 pub keep_unread: Option<String>,
111 pub keep_unread: Option<String>,
112 pub restorable_deletes: crate::restorable_deletes::RestorableDeletes,
112 pub typing: TypingState,
113 pub typing: TypingState,
113 typing_timer_running: bool,
114 typing_timer_running: bool,
114 pub local_previews: HashMap<String, LocalPreview>,
115 pub local_previews: HashMap<String, LocalPreview>,
@@ -261,6 +262,7 @@ impl AppState {
261 live_retry: None,
262 live_retry: None,
262 notice_count: 0,
263 notice_count: 0,
263 keep_unread: None,
264 keep_unread: None,
265 restorable_deletes: Default::default(),
264 typing: TypingState::default(),
266 typing: TypingState::default(),
265 typing_timer_running: false,
267 typing_timer_running: false,
266 local_previews: HashMap::new(),
268 local_previews: HashMap::new(),
@@ -685,6 +687,32 @@ impl AppState {
685 conversation_id: &str,
687 conversation_id: &str,
686 folder_id: Option<&str>,
688 folder_id: Option<&str>,
687 cx: &mut Context<Self>,
689 cx: &mut Context<Self>,
690 ) {
691 self.place_chat(conversation_id, folder_id, None, cx);
692 }
693
694 pub fn drop_chat_on(
695 &mut self,
696 conversation_id: &str,
697 target_conversation_id: &str,
698 folder_id: &str,
699 cx: &mut Context<Self>,
700 ) {
701 if conversation_id == target_conversation_id {
702 return;
703 }
704 let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else {
705 return;
706 };
707 self.place_chat(conversation_id, Some(folder_id), Some(slot), cx);
708 }
709
710 pub fn place_chat(
711 &mut self,
712 conversation_id: &str,
713 folder_id: Option<&str>,
714 index: Option<usize>,
715 cx: &mut Context<Self>,
688 ) {
716 ) {
689 if self.mode.read_only {
717 if self.mode.read_only {
690 return;
718 return;
@@ -693,13 +721,16 @@ impl AppState {
693 .directory
721 .directory
694 .folder_of(conversation_id)
722 .folder_of(conversation_id)
695 .map(|folder| folder.id.clone());
723 .map(|folder| folder.id.clone());
696 self.directory.assign(conversation_id, folder_id);
724 self.directory.place(conversation_id, folder_id, index);
697 if let Some(engine) = self.engine.clone() {
725 if let Some(engine) = self.engine.clone() {
698 let previous = previous_folder.clone();
726 let previous = previous_folder.clone();
699 let done = match (folder_id, previous.as_deref()) {
727 let done = match (folder_id, previous.as_deref()) {
700 (Some(folder_id), _) => {
728 (Some(folder_id), _) => Some(data::move_to_folder(
701 Some(data::move_to_folder(&engine, conversation_id, folder_id))
729 &engine,
702 }
730 conversation_id,
731 folder_id,
732 index,
733 )),
703 (None, Some(previous)) => {
734 (None, Some(previous)) => {
704 Some(data::remove_from_folder(&engine, conversation_id, previous))
735 Some(data::remove_from_folder(&engine, conversation_id, previous))
705 }
736 }
@@ -767,6 +798,42 @@ impl AppState {
767 }
798 }
768 }
799 }
769
800
801 pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) {
802 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
803 return;
804 };
805 let previous_unread: Vec<(String, bool, Option<DateTime<Utc>>)> = self
806 .sidebar
807 .teams
808 .iter()
809 .flat_map(|team| team.channels.iter())
810 .map(|channel| (channel.id.clone(), channel.unread, None))
811 .collect();
812 let previous_mentions: Vec<(String, store::ChannelMentions)> = self
813 .sidebar
814 .teams
815 .iter()
816 .flat_map(|team| team.mentions.iter())
817 .map(|(channel_id, mentions)| (channel_id.clone(), *mentions))
818 .collect();
819 let _ = self.store.mark_all_channels_read();
820 self.reload_sidebar(cx);
821 let Some(engine) = engine_or_demo else {
822 return;
823 };
824 self.run_chat_action(
825 "Mark all as read",
826 async move { engine.mark_all_channels_read().await },
827 move |state, cx| {
828 let _ = state.store.apply_channel_read_states(&previous_unread);
829 let _ = state.store.replace_channel_mentions(&previous_mentions);
830 state.reload_sidebar(cx);
831 },
832 |_, _| {},
833 cx,
834 );
835 }
836
770 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
837 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
771 self.new_chat = true;
838 self.new_chat = true;
772 self.show_call(false, cx);
839 self.show_call(false, cx);
@@ -1068,6 +1135,7 @@ mod tests {
1068 hidden: false,
1135 hidden: false,
1069 hidden_channel_ids: Vec::new(),
1136 hidden_channel_ids: Vec::new(),
1070 notifications: Default::default(),
1137 notifications: Default::default(),
1138 mentions: Default::default(),
1071 }],
1139 }],
1072 }
1140 }
1073 }
1141 }
crates/app-state/src/call/mod.rs +1 −0
@@ -14,6 +14,7 @@ pub mod prejoin;
14 14 pub mod record_load;
15 15 pub mod reminder;
16 16 pub mod share_actions;
17 pub mod share_overlay;
17 18 pub mod schedule;
18 19 pub mod target;
19 20 pub mod view_actions;
@@ -14,6 +14,7 @@ pub mod prejoin;
14pub mod record_load;
14pub mod record_load;
15pub mod reminder;
15pub mod reminder;
16pub mod share_actions;
16pub mod share_actions;
17pub mod share_overlay;
17pub mod schedule;
18pub mod schedule;
18pub mod target;
19pub mod target;
19pub mod view_actions;
20pub mod view_actions;
crates/app-state/src/call/overlay_layout.rs +0 −11
@@ -117,10 +117,6 @@ pub fn mini_work_area(
117 117 .unwrap_or(main)
118 118 }
119 119
120 pub fn mini_wanted(call_active: bool, main_minimized: bool) -> bool {
121 call_active && main_minimized
122 }
123
124 120 pub fn parse_position(text: &str) -> Option<(i32, i32)> {
125 121 let (left, top) = text.split_once(',')?;
126 122 Some((left.trim().parse().ok()?, top.trim().parse().ok()?))
@@ -276,13 +272,6 @@ mod tests {
276 272 assert_eq!((rect.width(), rect.height()), (640, 360));
277 273 }
278 274
279 #[test]
280 fn mini_shows_only_in_a_call_with_the_main_window_minimized() {
281 assert!(mini_wanted(true, true));
282 assert!(!mini_wanted(true, false));
283 assert!(!mini_wanted(false, true));
284 }
285
286 275 #[test]
287 276 fn position_round_trips() {
288 277 assert_eq!(
@@ -117,10 +117,6 @@ pub fn mini_work_area(
117 .unwrap_or(main)
117 .unwrap_or(main)
118}
118}
119
119
120pub fn mini_wanted(call_active: bool, main_minimized: bool) -> bool {
121 call_active && main_minimized
122}
123
124pub fn parse_position(text: &str) -> Option<(i32, i32)> {
120pub fn parse_position(text: &str) -> Option<(i32, i32)> {
125 let (left, top) = text.split_once(',')?;
121 let (left, top) = text.split_once(',')?;
126 Some((left.trim().parse().ok()?, top.trim().parse().ok()?))
122 Some((left.trim().parse().ok()?, top.trim().parse().ok()?))
@@ -276,13 +272,6 @@ mod tests {
276 assert_eq!((rect.width(), rect.height()), (640, 360));
272 assert_eq!((rect.width(), rect.height()), (640, 360));
277 }
273 }
278
274
279 #[test]
280 fn mini_shows_only_in_a_call_with_the_main_window_minimized() {
281 assert!(mini_wanted(true, true));
282 assert!(!mini_wanted(true, false));
283 assert!(!mini_wanted(false, true));
284 }
285
286 #[test]
275 #[test]
287 fn position_round_trips() {
276 fn position_round_trips() {
288 assert_eq!(
277 assert_eq!(
crates/app-state/src/call/share_overlay.rs added +434 −0
@@ -0,0 +1,434 @@
1 use calling::ShareKind;
2
3 use super::model::{CallModel, Tile, TileState};
4 use crate::notify::platform::{ScreenRect, WorkArea};
5
6 pub const GALLERY_WIDTH: f32 = 192.;
7 pub const GALLERY_INSET: f32 = 3.;
8 pub const GALLERY_TILE_WIDTH: f32 = GALLERY_WIDTH - 2. * GALLERY_INSET;
9 pub const GALLERY_TILE_HEIGHT: f32 = GALLERY_TILE_WIDTH * 9. / 16.;
10 pub const GALLERY_TITLE_HEIGHT: f32 = 32.;
11 pub const GALLERY_CONTROLS_HEIGHT: f32 = 40.;
12 pub const GALLERY_DIVIDER_HEIGHT: f32 = 20.;
13 pub const GALLERY_MAX_TILES: usize = 4;
14 pub const GALLERY_MARGIN: f32 = 30.;
15 pub const GALLERY_POSITION_KEY: &str = "call_gallery_position";
16 pub const MINIMIZE_OVERLAP_PERCENT: i64 = 5;
17
18 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
19 pub enum LocalShare {
20 None,
21 Screen,
22 Window,
23 }
24
25 impl LocalShare {
26 pub fn of(kind: Option<ShareKind>, sharing: bool) -> LocalShare {
27 match (sharing, kind) {
28 (false, _) => LocalShare::None,
29 (true, Some(ShareKind::Window)) => LocalShare::Window,
30 (true, _) => LocalShare::Screen,
31 }
32 }
33 }
34
35 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
36 pub enum Monitor {
37 None,
38 Mini,
39 Gallery,
40 }
41
42 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
43 pub enum Surface {
44 Main,
45 ShareBar,
46 Border,
47 Mini,
48 Gallery,
49 }
50
51 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
52 pub struct OverlayPlan {
53 pub monitor: Monitor,
54 pub share_bar: bool,
55 pub exclude_main: bool,
56 }
57
58 pub fn overlay_plan(
59 in_call: bool,
60 share: LocalShare,
61 main_minimized: bool,
62 speaker_only: bool,
63 ) -> OverlayPlan {
64 let monitor = match (in_call && main_minimized, share) {
65 (false, _) => Monitor::None,
66 (true, LocalShare::None) => Monitor::Mini,
67 (true, _) if speaker_only => Monitor::Mini,
68 (true, _) => Monitor::Gallery,
69 };
70 OverlayPlan {
71 monitor,
72 share_bar: in_call && share != LocalShare::None,
73 exclude_main: excluded_from_capture(Surface::Main, share),
74 }
75 }
76
77 pub fn excluded_from_capture(surface: Surface, share: LocalShare) -> bool {
78 match surface {
79 Surface::Main => share == LocalShare::Screen,
80 Surface::ShareBar | Surface::Border | Surface::Mini | Surface::Gallery => true,
81 }
82 }
83
84 fn overlap_area(first: ScreenRect, second: ScreenRect) -> i64 {
85 let width = (first.right.min(second.right) - first.left.max(second.left)).max(0);
86 let height = (first.bottom.min(second.bottom) - first.top.max(second.top)).max(0);
87 i64::from(width) * i64::from(height)
88 }
89
90 pub fn minimize_on_share_start(
91 share: LocalShare,
92 main: Option<ScreenRect>,
93 shared: Option<ScreenRect>,
94 ) -> bool {
95 if share != LocalShare::Screen {
96 return false;
97 }
98 let (Some(main), Some(shared)) = (main, shared) else {
99 return true;
100 };
101 let main_area = i64::from(main.width().max(0)) * i64::from(main.height().max(0));
102 if main_area == 0 {
103 return true;
104 }
105 overlap_area(main, shared) * 100 >= MINIMIZE_OVERLAP_PERCENT * main_area
106 }
107
108 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
109 pub struct GalleryLayout {
110 pub tiles: usize,
111 pub overflow: usize,
112 pub divider: bool,
113 pub self_tile: bool,
114 }
115
116 impl GalleryLayout {
117 pub fn height(&self) -> f32 {
118 let segments = self.tiles + usize::from(self.self_tile);
119 let gaps = (segments + usize::from(self.divider)).saturating_sub(1);
120 GALLERY_TITLE_HEIGHT
121 + GALLERY_INSET
122 + segments as f32 * GALLERY_TILE_HEIGHT
123 + if self.divider {
124 GALLERY_DIVIDER_HEIGHT
125 } else {
126 0.
127 }
128 + gaps as f32 * GALLERY_INSET
129 + GALLERY_INSET
130 + GALLERY_CONTROLS_HEIGHT
131 }
132 }
133
134 pub fn gallery_layout(others: usize, self_tile: bool, available_height: f32) -> GalleryLayout {
135 let build = |tiles: usize| GalleryLayout {
136 tiles,
137 overflow: others - tiles,
138 divider: others > 0 && self_tile,
139 self_tile,
140 };
141 let mut layout = build(others.min(GALLERY_MAX_TILES));
142 while layout.tiles > 1 && layout.height() > available_height {
143 layout = build(layout.tiles - 1);
144 }
145 layout
146 }
147
148 pub fn gallery_available_height(work: WorkArea) -> f32 {
149 (work.bottom - work.top) as f32 / work.scale - 2. * GALLERY_MARGIN
150 }
151
152 pub fn gallery_rect(
153 work: WorkArea,
154 layout: GalleryLayout,
155 origin: Option<(i32, i32)>,
156 ) -> ScreenRect {
157 let scaled = |logical: f32| (logical * work.scale).round() as i32;
158 let width = scaled(GALLERY_WIDTH);
159 let height = scaled(layout.height());
160 let margin = scaled(GALLERY_MARGIN);
161 let (left, top) =
162 origin.unwrap_or((work.right - width - margin, work.bottom - height - margin));
163 let left = left.clamp(work.left, (work.right - width).max(work.left));
164 let top = top.clamp(work.top, (work.bottom - height).max(work.top));
165 ScreenRect {
166 left,
167 top,
168 right: left + width,
169 bottom: top + height,
170 }
171 }
172
173 fn prioritized(model: &CallModel, tile: &Tile) -> bool {
174 model.is_pinned(&tile.mri) || tile.spotlight.is_some() || tile.hand.is_some()
175 }
176
177 pub fn gallery_candidates(model: &CallModel) -> Vec<&Tile> {
178 let mut tiles: Vec<&Tile> = model
179 .layout_tiles()
180 .into_iter()
181 .filter(|tile| tile.state == TileState::Present)
182 .collect();
183 tiles.sort_by_key(|tile| {
184 (
185 !prioritized(model, tile),
186 !(model.tile_speaking(tile) || model.is_recent_speaker(&tile.mri)),
187 )
188 });
189 tiles
190 }
191
192 #[cfg(test)]
193 mod tests {
194 use super::*;
195
196 fn work(scale: f32) -> WorkArea {
197 WorkArea {
198 left: 0,
199 top: 0,
200 right: 1920,
201 bottom: 1040,
202 scale,
203 }
204 }
205
206 fn rect(left: i32, top: i32, right: i32, bottom: i32) -> ScreenRect {
207 ScreenRect {
208 left,
209 top,
210 right,
211 bottom,
212 }
213 }
214
215 #[test]
216 fn decision_table() {
217 use LocalShare::*;
218 use Monitor as M;
219 let rows = [
220 (None, false, M::None, false, false),
221 (None, true, M::Mini, false, false),
222 (Screen, false, M::None, true, true),
223 (Screen, true, M::Gallery, true, true),
224 (Window, false, M::None, true, false),
225 (Window, true, M::Gallery, true, false),
226 ];
227 for (share, minimized, monitor, share_bar, exclude_main) in rows {
228 assert_eq!(
229 overlay_plan(true, share, minimized, false),
230 OverlayPlan {
231 monitor,
232 share_bar,
233 exclude_main
234 },
235 "{share:?} minimized={minimized}"
236 );
237 }
238 }
239
240 #[test]
241 fn speaker_only_swaps_the_gallery_for_the_mini_tile() {
242 let plan = overlay_plan(true, LocalShare::Screen, true, true);
243 assert_eq!(plan.monitor, Monitor::Mini);
244 assert!(plan.exclude_main);
245 assert_eq!(
246 overlay_plan(true, LocalShare::None, true, true).monitor,
247 Monitor::Mini
248 );
249 }
250
251 #[test]
252 fn nothing_shows_outside_a_call() {
253 let plan = overlay_plan(false, LocalShare::None, true, false);
254 assert_eq!(plan.monitor, Monitor::None);
255 assert!(!plan.share_bar);
256 }
257
258 #[test]
259 fn overlays_are_always_excluded_and_main_only_for_a_screen() {
260 for share in [LocalShare::None, LocalShare::Screen, LocalShare::Window] {
261 for surface in [
262 Surface::ShareBar,
263 Surface::Border,
264 Surface::Mini,
265 Surface::Gallery,
266 ] {
267 assert!(excluded_from_capture(surface, share));
268 }
269 }
270 assert!(excluded_from_capture(Surface::Main, LocalShare::Screen));
271 assert!(!excluded_from_capture(Surface::Main, LocalShare::Window));
272 assert!(!excluded_from_capture(Surface::Main, LocalShare::None));
273 }
274
275 #[test]
276 fn unknown_source_kind_counts_as_a_screen() {
277 assert_eq!(LocalShare::of(None, true), LocalShare::Screen);
278 assert_eq!(
279 LocalShare::of(Some(ShareKind::Window), true),
280 LocalShare::Window
281 );
282 assert_eq!(
283 LocalShare::of(Some(ShareKind::Screen), false),
284 LocalShare::None
285 );
286 }
287
288 #[test]
289 fn screen_share_minimizes_only_when_the_main_window_is_on_the_shared_monitor() {
290 let monitor = rect(0, 0, 1920, 1080);
291 let on_monitor = Some(rect(100, 100, 1100, 800));
292 let other_monitor = Some(rect(2000, 100, 3000, 800));
293 let edge = Some(rect(1880, 0, 2880, 1000));
294 assert!(minimize_on_share_start(
295 LocalShare::Screen,
296 on_monitor,
297 Some(monitor)
298 ));
299 assert!(!minimize_on_share_start(
300 LocalShare::Screen,
301 other_monitor,
302 Some(monitor)
303 ));
304 assert!(!minimize_on_share_start(
305 LocalShare::Screen,
306 edge,
307 Some(monitor)
308 ));
309 assert!(minimize_on_share_start(
310 LocalShare::Screen,
311 None,
312 Some(monitor)
313 ));
314 assert!(minimize_on_share_start(
315 LocalShare::Screen,
316 on_monitor,
317 None
318 ));
319 }
320
321 #[test]
322 fn window_share_and_no_share_never_minimize() {
323 let monitor = Some(rect(0, 0, 1920, 1080));
324 assert!(!minimize_on_share_start(
325 LocalShare::Window,
326 monitor,
327 monitor
328 ));
329 assert!(!minimize_on_share_start(LocalShare::None, monitor, monitor));
330 }
331
332 #[test]
333 fn gallery_stacks_four_tiles_a_divider_and_the_own_tile() {
334 let layout = gallery_layout(9, true, 2000.);
335 assert_eq!(
336 layout,
337 GalleryLayout {
338 tiles: 4,
339 overflow: 5,
340 divider: true,
341 self_tile: true
342 }
343 );
344 let expected = GALLERY_TITLE_HEIGHT
345 + 5. * GALLERY_TILE_HEIGHT
346 + GALLERY_DIVIDER_HEIGHT
347 + 7. * GALLERY_INSET
348 + GALLERY_CONTROLS_HEIGHT;
349 assert!((layout.height() - expected).abs() < 0.01);
350 }
351
352 #[test]
353 fn gallery_chrome_matches_teams() {
354 let chrome = GalleryLayout {
355 tiles: 0,
356 overflow: 0,
357 divider: false,
358 self_tile: false,
359 }
360 .height();
361 assert_eq!(chrome, 78.);
362 assert_eq!(GALLERY_TILE_WIDTH, 186.);
363 }
364
365 #[test]
366 fn gallery_drops_tiles_to_fit_a_short_screen() {
367 let layout = gallery_layout(9, true, 500.);
368 assert!(layout.height() <= 500.);
369 assert_eq!(layout.tiles, 2);
370 assert_eq!(layout.overflow, 7);
371 assert_eq!(gallery_layout(9, true, 10.).tiles, 1);
372 }
373
374 #[test]
375 fn gallery_without_others_has_no_divider() {
376 let layout = gallery_layout(0, true, 2000.);
377 assert_eq!(
378 (layout.tiles, layout.divider, layout.self_tile),
379 (0, false, true)
380 );
381 let hidden_self = gallery_layout(3, false, 2000.);
382 assert_eq!((hidden_self.tiles, hidden_self.divider), (3, false));
383 }
384
385 #[test]
386 fn gallery_defaults_to_the_bottom_right_with_the_teams_margin() {
387 let layout = gallery_layout(2, true, 2000.);
388 let placed = gallery_rect(work(1.), layout, None);
389 assert_eq!(placed.width(), 192);
390 assert_eq!((placed.right, placed.bottom), (1920 - 30, 1040 - 30));
391 assert_eq!(placed.height(), layout.height().round() as i32);
392 }
393
394 #[test]
395 fn gallery_keeps_a_dragged_origin_inside_the_work_area() {
396 let layout = gallery_layout(4, true, 2000.);
397 assert_eq!(gallery_rect(work(1.), layout, Some((200, 100))).left, 200);
398 let pushed = gallery_rect(work(1.), layout, Some((5000, 900)));
399 assert_eq!((pushed.right, pushed.bottom), (1920, 1040));
400 }
401
402 #[test]
403 fn gallery_scales_with_the_monitor() {
404 let layout = gallery_layout(1, false, 2000.);
405 let placed = gallery_rect(work(2.), layout, None);
406 assert_eq!(placed.width(), 384);
407 assert_eq!(gallery_available_height(work(2.)), 520. - 60.);
408 }
409
410 fn present(mri: &str, name: &str) -> Tile {
411 Tile {
412 state: TileState::Present,
413 ..Tile::invited(mri, name)
414 }
415 }
416
417 #[test]
418 fn candidates_put_pinned_then_speakers_first() {
419 let mut model = CallModel::test();
420 model.tiles = vec![
421 present("8:a", "Ada"),
422 present("8:b", "Bo"),
423 present("8:c", "Cy"),
424 Tile::invited("8:d", "Dee"),
425 ];
426 model.speaking_mris = vec!["8:c".to_owned()];
427 model.toggle_pin("8:b");
428 let names: Vec<&str> = gallery_candidates(&model)
429 .iter()
430 .map(|tile| tile.name.as_str())
431 .collect();
432 assert_eq!(names, ["Bo", "Cy", "Ada"]);
433 }
434 }
@@ -0,0 +1,434 @@
1use calling::ShareKind;
2
3use super::model::{CallModel, Tile, TileState};
4use crate::notify::platform::{ScreenRect, WorkArea};
5
6pub const GALLERY_WIDTH: f32 = 192.;
7pub const GALLERY_INSET: f32 = 3.;
8pub const GALLERY_TILE_WIDTH: f32 = GALLERY_WIDTH - 2. * GALLERY_INSET;
9pub const GALLERY_TILE_HEIGHT: f32 = GALLERY_TILE_WIDTH * 9. / 16.;
10pub const GALLERY_TITLE_HEIGHT: f32 = 32.;
11pub const GALLERY_CONTROLS_HEIGHT: f32 = 40.;
12pub const GALLERY_DIVIDER_HEIGHT: f32 = 20.;
13pub const GALLERY_MAX_TILES: usize = 4;
14pub const GALLERY_MARGIN: f32 = 30.;
15pub const GALLERY_POSITION_KEY: &str = "call_gallery_position";
16pub const MINIMIZE_OVERLAP_PERCENT: i64 = 5;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum LocalShare {
20 None,
21 Screen,
22 Window,
23}
24
25impl LocalShare {
26 pub fn of(kind: Option<ShareKind>, sharing: bool) -> LocalShare {
27 match (sharing, kind) {
28 (false, _) => LocalShare::None,
29 (true, Some(ShareKind::Window)) => LocalShare::Window,
30 (true, _) => LocalShare::Screen,
31 }
32 }
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Monitor {
37 None,
38 Mini,
39 Gallery,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum Surface {
44 Main,
45 ShareBar,
46 Border,
47 Mini,
48 Gallery,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct OverlayPlan {
53 pub monitor: Monitor,
54 pub share_bar: bool,
55 pub exclude_main: bool,
56}
57
58pub fn overlay_plan(
59 in_call: bool,
60 share: LocalShare,
61 main_minimized: bool,
62 speaker_only: bool,
63) -> OverlayPlan {
64 let monitor = match (in_call && main_minimized, share) {
65 (false, _) => Monitor::None,
66 (true, LocalShare::None) => Monitor::Mini,
67 (true, _) if speaker_only => Monitor::Mini,
68 (true, _) => Monitor::Gallery,
69 };
70 OverlayPlan {
71 monitor,
72 share_bar: in_call && share != LocalShare::None,
73 exclude_main: excluded_from_capture(Surface::Main, share),
74 }
75}
76
77pub fn excluded_from_capture(surface: Surface, share: LocalShare) -> bool {
78 match surface {
79 Surface::Main => share == LocalShare::Screen,
80 Surface::ShareBar | Surface::Border | Surface::Mini | Surface::Gallery => true,
81 }
82}
83
84fn overlap_area(first: ScreenRect, second: ScreenRect) -> i64 {
85 let width = (first.right.min(second.right) - first.left.max(second.left)).max(0);
86 let height = (first.bottom.min(second.bottom) - first.top.max(second.top)).max(0);
87 i64::from(width) * i64::from(height)
88}
89
90pub fn minimize_on_share_start(
91 share: LocalShare,
92 main: Option<ScreenRect>,
93 shared: Option<ScreenRect>,
94) -> bool {
95 if share != LocalShare::Screen {
96 return false;
97 }
98 let (Some(main), Some(shared)) = (main, shared) else {
99 return true;
100 };
101 let main_area = i64::from(main.width().max(0)) * i64::from(main.height().max(0));
102 if main_area == 0 {
103 return true;
104 }
105 overlap_area(main, shared) * 100 >= MINIMIZE_OVERLAP_PERCENT * main_area
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub struct GalleryLayout {
110 pub tiles: usize,
111 pub overflow: usize,
112 pub divider: bool,
113 pub self_tile: bool,
114}
115
116impl GalleryLayout {
117 pub fn height(&self) -> f32 {
118 let segments = self.tiles + usize::from(self.self_tile);
119 let gaps = (segments + usize::from(self.divider)).saturating_sub(1);
120 GALLERY_TITLE_HEIGHT
121 + GALLERY_INSET
122 + segments as f32 * GALLERY_TILE_HEIGHT
123 + if self.divider {
124 GALLERY_DIVIDER_HEIGHT
125 } else {
126 0.
127 }
128 + gaps as f32 * GALLERY_INSET
129 + GALLERY_INSET
130 + GALLERY_CONTROLS_HEIGHT
131 }
132}
133
134pub fn gallery_layout(others: usize, self_tile: bool, available_height: f32) -> GalleryLayout {
135 let build = |tiles: usize| GalleryLayout {
136 tiles,
137 overflow: others - tiles,
138 divider: others > 0 && self_tile,
139 self_tile,
140 };
141 let mut layout = build(others.min(GALLERY_MAX_TILES));
142 while layout.tiles > 1 && layout.height() > available_height {
143 layout = build(layout.tiles - 1);
144 }
145 layout
146}
147
148pub fn gallery_available_height(work: WorkArea) -> f32 {
149 (work.bottom - work.top) as f32 / work.scale - 2. * GALLERY_MARGIN
150}
151
152pub fn gallery_rect(
153 work: WorkArea,
154 layout: GalleryLayout,
155 origin: Option<(i32, i32)>,
156) -> ScreenRect {
157 let scaled = |logical: f32| (logical * work.scale).round() as i32;
158 let width = scaled(GALLERY_WIDTH);
159 let height = scaled(layout.height());
160 let margin = scaled(GALLERY_MARGIN);
161 let (left, top) =
162 origin.unwrap_or((work.right - width - margin, work.bottom - height - margin));
163 let left = left.clamp(work.left, (work.right - width).max(work.left));
164 let top = top.clamp(work.top, (work.bottom - height).max(work.top));
165 ScreenRect {
166 left,
167 top,
168 right: left + width,
169 bottom: top + height,
170 }
171}
172
173fn prioritized(model: &CallModel, tile: &Tile) -> bool {
174 model.is_pinned(&tile.mri) || tile.spotlight.is_some() || tile.hand.is_some()
175}
176
177pub fn gallery_candidates(model: &CallModel) -> Vec<&Tile> {
178 let mut tiles: Vec<&Tile> = model
179 .layout_tiles()
180 .into_iter()
181 .filter(|tile| tile.state == TileState::Present)
182 .collect();
183 tiles.sort_by_key(|tile| {
184 (
185 !prioritized(model, tile),
186 !(model.tile_speaking(tile) || model.is_recent_speaker(&tile.mri)),
187 )
188 });
189 tiles
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 fn work(scale: f32) -> WorkArea {
197 WorkArea {
198 left: 0,
199 top: 0,
200 right: 1920,
201 bottom: 1040,
202 scale,
203 }
204 }
205
206 fn rect(left: i32, top: i32, right: i32, bottom: i32) -> ScreenRect {
207 ScreenRect {
208 left,
209 top,
210 right,
211 bottom,
212 }
213 }
214
215 #[test]
216 fn decision_table() {
217 use LocalShare::*;
218 use Monitor as M;
219 let rows = [
220 (None, false, M::None, false, false),
221 (None, true, M::Mini, false, false),
222 (Screen, false, M::None, true, true),
223 (Screen, true, M::Gallery, true, true),
224 (Window, false, M::None, true, false),
225 (Window, true, M::Gallery, true, false),
226 ];
227 for (share, minimized, monitor, share_bar, exclude_main) in rows {
228 assert_eq!(
229 overlay_plan(true, share, minimized, false),
230 OverlayPlan {
231 monitor,
232 share_bar,
233 exclude_main
234 },
235 "{share:?} minimized={minimized}"
236 );
237 }
238 }
239
240 #[test]
241 fn speaker_only_swaps_the_gallery_for_the_mini_tile() {
242 let plan = overlay_plan(true, LocalShare::Screen, true, true);
243 assert_eq!(plan.monitor, Monitor::Mini);
244 assert!(plan.exclude_main);
245 assert_eq!(
246 overlay_plan(true, LocalShare::None, true, true).monitor,
247 Monitor::Mini
248 );
249 }
250
251 #[test]
252 fn nothing_shows_outside_a_call() {
253 let plan = overlay_plan(false, LocalShare::None, true, false);
254 assert_eq!(plan.monitor, Monitor::None);
255 assert!(!plan.share_bar);
256 }
257
258 #[test]
259 fn overlays_are_always_excluded_and_main_only_for_a_screen() {
260 for share in [LocalShare::None, LocalShare::Screen, LocalShare::Window] {
261 for surface in [
262 Surface::ShareBar,
263 Surface::Border,
264 Surface::Mini,
265 Surface::Gallery,
266 ] {
267 assert!(excluded_from_capture(surface, share));
268 }
269 }
270 assert!(excluded_from_capture(Surface::Main, LocalShare::Screen));
271 assert!(!excluded_from_capture(Surface::Main, LocalShare::Window));
272 assert!(!excluded_from_capture(Surface::Main, LocalShare::None));
273 }
274
275 #[test]
276 fn unknown_source_kind_counts_as_a_screen() {
277 assert_eq!(LocalShare::of(None, true), LocalShare::Screen);
278 assert_eq!(
279 LocalShare::of(Some(ShareKind::Window), true),
280 LocalShare::Window
281 );
282 assert_eq!(
283 LocalShare::of(Some(ShareKind::Screen), false),
284 LocalShare::None
285 );
286 }
287
288 #[test]
289 fn screen_share_minimizes_only_when_the_main_window_is_on_the_shared_monitor() {
290 let monitor = rect(0, 0, 1920, 1080);
291 let on_monitor = Some(rect(100, 100, 1100, 800));
292 let other_monitor = Some(rect(2000, 100, 3000, 800));
293 let edge = Some(rect(1880, 0, 2880, 1000));
294 assert!(minimize_on_share_start(
295 LocalShare::Screen,
296 on_monitor,
297 Some(monitor)
298 ));
299 assert!(!minimize_on_share_start(
300 LocalShare::Screen,
301 other_monitor,
302 Some(monitor)
303 ));
304 assert!(!minimize_on_share_start(
305 LocalShare::Screen,
306 edge,
307 Some(monitor)
308 ));
309 assert!(minimize_on_share_start(
310 LocalShare::Screen,
311 None,
312 Some(monitor)
313 ));
314 assert!(minimize_on_share_start(
315 LocalShare::Screen,
316 on_monitor,
317 None
318 ));
319 }
320
321 #[test]
322 fn window_share_and_no_share_never_minimize() {
323 let monitor = Some(rect(0, 0, 1920, 1080));
324 assert!(!minimize_on_share_start(
325 LocalShare::Window,
326 monitor,
327 monitor
328 ));
329 assert!(!minimize_on_share_start(LocalShare::None, monitor, monitor));
330 }
331
332 #[test]
333 fn gallery_stacks_four_tiles_a_divider_and_the_own_tile() {
334 let layout = gallery_layout(9, true, 2000.);
335 assert_eq!(
336 layout,
337 GalleryLayout {
338 tiles: 4,
339 overflow: 5,
340 divider: true,
341 self_tile: true
342 }
343 );
344 let expected = GALLERY_TITLE_HEIGHT
345 + 5. * GALLERY_TILE_HEIGHT
346 + GALLERY_DIVIDER_HEIGHT
347 + 7. * GALLERY_INSET
348 + GALLERY_CONTROLS_HEIGHT;
349 assert!((layout.height() - expected).abs() < 0.01);
350 }
351
352 #[test]
353 fn gallery_chrome_matches_teams() {
354 let chrome = GalleryLayout {
355 tiles: 0,
356 overflow: 0,
357 divider: false,
358 self_tile: false,
359 }
360 .height();
361 assert_eq!(chrome, 78.);
362 assert_eq!(GALLERY_TILE_WIDTH, 186.);
363 }
364
365 #[test]
366 fn gallery_drops_tiles_to_fit_a_short_screen() {
367 let layout = gallery_layout(9, true, 500.);
368 assert!(layout.height() <= 500.);
369 assert_eq!(layout.tiles, 2);
370 assert_eq!(layout.overflow, 7);
371 assert_eq!(gallery_layout(9, true, 10.).tiles, 1);
372 }
373
374 #[test]
375 fn gallery_without_others_has_no_divider() {
376 let layout = gallery_layout(0, true, 2000.);
377 assert_eq!(
378 (layout.tiles, layout.divider, layout.self_tile),
379 (0, false, true)
380 );
381 let hidden_self = gallery_layout(3, false, 2000.);
382 assert_eq!((hidden_self.tiles, hidden_self.divider), (3, false));
383 }
384
385 #[test]
386 fn gallery_defaults_to_the_bottom_right_with_the_teams_margin() {
387 let layout = gallery_layout(2, true, 2000.);
388 let placed = gallery_rect(work(1.), layout, None);
389 assert_eq!(placed.width(), 192);
390 assert_eq!((placed.right, placed.bottom), (1920 - 30, 1040 - 30));
391 assert_eq!(placed.height(), layout.height().round() as i32);
392 }
393
394 #[test]
395 fn gallery_keeps_a_dragged_origin_inside_the_work_area() {
396 let layout = gallery_layout(4, true, 2000.);
397 assert_eq!(gallery_rect(work(1.), layout, Some((200, 100))).left, 200);
398 let pushed = gallery_rect(work(1.), layout, Some((5000, 900)));
399 assert_eq!((pushed.right, pushed.bottom), (1920, 1040));
400 }
401
402 #[test]
403 fn gallery_scales_with_the_monitor() {
404 let layout = gallery_layout(1, false, 2000.);
405 let placed = gallery_rect(work(2.), layout, None);
406 assert_eq!(placed.width(), 384);
407 assert_eq!(gallery_available_height(work(2.)), 520. - 60.);
408 }
409
410 fn present(mri: &str, name: &str) -> Tile {
411 Tile {
412 state: TileState::Present,
413 ..Tile::invited(mri, name)
414 }
415 }
416
417 #[test]
418 fn candidates_put_pinned_then_speakers_first() {
419 let mut model = CallModel::test();
420 model.tiles = vec![
421 present("8:a", "Ada"),
422 present("8:b", "Bo"),
423 present("8:c", "Cy"),
424 Tile::invited("8:d", "Dee"),
425 ];
426 model.speaking_mris = vec!["8:c".to_owned()];
427 model.toggle_pin("8:b");
428 let names: Vec<&str> = gallery_candidates(&model)
429 .iter()
430 .map(|tile| tile.name.as_str())
431 .collect();
432 assert_eq!(names, ["Bo", "Cy", "Ada"]);
433 }
434}
crates/app-state/src/data.rs +53 −3
@@ -331,16 +331,34 @@ impl Directory {
331 331 }
332 332
333 333 pub fn assign(&mut self, conversation_id: &str, folder_id: Option<&str>) {
334 self.place(conversation_id, folder_id, None);
335 }
336
337 pub fn place(&mut self, conversation_id: &str, folder_id: Option<&str>, index: Option<usize>) {
334 338 for folder in &mut self.folders {
335 339 folder.conversation_ids.retain(|id| id != conversation_id);
336 340 }
337 341 if let Some(folder) =
338 342 folder_id.and_then(|id| self.folders.iter_mut().find(|folder| folder.id == id))
339 343 {
340 folder.conversation_ids.push(conversation_id.to_owned());
344 let position = index.map_or(folder.conversation_ids.len(), |index| {
345 index.min(folder.conversation_ids.len())
346 });
347 folder
348 .conversation_ids
349 .insert(position, conversation_id.to_owned());
341 350 }
342 351 }
343 352
353 pub fn slot_of(&self, folder_id: &str, conversation_id: &str) -> Option<usize> {
354 self.folders
355 .iter()
356 .find(|folder| folder.id == folder_id)?
357 .conversation_ids
358 .iter()
359 .position(|id| id == conversation_id)
360 }
361
344 362 pub fn move_targets(&self) -> Vec<(String, String)> {
345 363 let favorites = self.favorites().map(|folder| {
346 364 let name = folder.name.trim();
@@ -647,13 +665,22 @@ pub fn watch_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
647 665 run(async move { engine.watch_presence(&user_ids).await })
648 666 }
649 667
650 pub fn move_to_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
668 pub fn move_to_folder(
669 engine: &Arc<Engine>,
670 conversation_id: &str,
671 folder_id: &str,
672 index: Option<usize>,
673 ) -> Done {
651 674 let (engine, conversation_id, folder_id) = (
652 675 engine.clone(),
653 676 conversation_id.to_owned(),
654 677 folder_id.to_owned(),
655 678 );
656 run(async move { engine.move_to_folder(&conversation_id, &folder_id).await })
679 run(async move {
680 engine
681 .move_to_folder(&conversation_id, &folder_id, index)
682 .await
683 })
657 684 }
658 685
659 686 pub fn remove_from_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
@@ -719,6 +746,29 @@ mod tests {
719 746 }
720 747 }
721 748
749 #[test]
750 fn place_puts_a_chat_at_the_slot_inside_and_across_folders() {
751 let mut directory = Directory {
752 folders: vec![
753 folder("fav", FolderKind::Favorites, &["a", "b", "c"]),
754 folder("work", FolderKind::UserCreated, &["d"]),
755 ],
756 ..Default::default()
757 };
758 directory.place("a", Some("fav"), Some(2));
759 assert_eq!(directory.folders[0].conversation_ids, vec!["b", "c", "a"]);
760 directory.place("d", Some("fav"), Some(0));
761 assert_eq!(
762 directory.folders[0].conversation_ids,
763 vec!["d", "b", "c", "a"]
764 );
765 assert!(directory.folders[1].conversation_ids.is_empty());
766 directory.place("b", Some("work"), Some(9));
767 assert_eq!(directory.folders[1].conversation_ids, vec!["b"]);
768 assert_eq!(directory.slot_of("fav", "c"), Some(1));
769 assert_eq!(directory.slot_of("work", "c"), None);
770 }
771
722 772 #[test]
723 773 fn assign_moves_a_chat_between_folders() {
724 774 let mut directory = Directory {
@@ -331,16 +331,34 @@ impl Directory {
331 }
331 }
332
332
333 pub fn assign(&mut self, conversation_id: &str, folder_id: Option<&str>) {
333 pub fn assign(&mut self, conversation_id: &str, folder_id: Option<&str>) {
334 self.place(conversation_id, folder_id, None);
335 }
336
337 pub fn place(&mut self, conversation_id: &str, folder_id: Option<&str>, index: Option<usize>) {
334 for folder in &mut self.folders {
338 for folder in &mut self.folders {
335 folder.conversation_ids.retain(|id| id != conversation_id);
339 folder.conversation_ids.retain(|id| id != conversation_id);
336 }
340 }
337 if let Some(folder) =
341 if let Some(folder) =
338 folder_id.and_then(|id| self.folders.iter_mut().find(|folder| folder.id == id))
342 folder_id.and_then(|id| self.folders.iter_mut().find(|folder| folder.id == id))
339 {
343 {
340 folder.conversation_ids.push(conversation_id.to_owned());
344 let position = index.map_or(folder.conversation_ids.len(), |index| {
345 index.min(folder.conversation_ids.len())
346 });
347 folder
348 .conversation_ids
349 .insert(position, conversation_id.to_owned());
341 }
350 }
342 }
351 }
343
352
353 pub fn slot_of(&self, folder_id: &str, conversation_id: &str) -> Option<usize> {
354 self.folders
355 .iter()
356 .find(|folder| folder.id == folder_id)?
357 .conversation_ids
358 .iter()
359 .position(|id| id == conversation_id)
360 }
361
344 pub fn move_targets(&self) -> Vec<(String, String)> {
362 pub fn move_targets(&self) -> Vec<(String, String)> {
345 let favorites = self.favorites().map(|folder| {
363 let favorites = self.favorites().map(|folder| {
346 let name = folder.name.trim();
364 let name = folder.name.trim();
@@ -647,13 +665,22 @@ pub fn watch_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
647 run(async move { engine.watch_presence(&user_ids).await })
665 run(async move { engine.watch_presence(&user_ids).await })
648}
666}
649
667
650pub fn move_to_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
668pub fn move_to_folder(
669 engine: &Arc<Engine>,
670 conversation_id: &str,
671 folder_id: &str,
672 index: Option<usize>,
673) -> Done {
651 let (engine, conversation_id, folder_id) = (
674 let (engine, conversation_id, folder_id) = (
652 engine.clone(),
675 engine.clone(),
653 conversation_id.to_owned(),
676 conversation_id.to_owned(),
654 folder_id.to_owned(),
677 folder_id.to_owned(),
655 );
678 );
656 run(async move { engine.move_to_folder(&conversation_id, &folder_id).await })
679 run(async move {
680 engine
681 .move_to_folder(&conversation_id, &folder_id, index)
682 .await
683 })
657}
684}
658
685
659pub fn remove_from_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
686pub fn remove_from_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
@@ -719,6 +746,29 @@ mod tests {
719 }
746 }
720 }
747 }
721
748
749 #[test]
750 fn place_puts_a_chat_at_the_slot_inside_and_across_folders() {
751 let mut directory = Directory {
752 folders: vec![
753 folder("fav", FolderKind::Favorites, &["a", "b", "c"]),
754 folder("work", FolderKind::UserCreated, &["d"]),
755 ],
756 ..Default::default()
757 };
758 directory.place("a", Some("fav"), Some(2));
759 assert_eq!(directory.folders[0].conversation_ids, vec!["b", "c", "a"]);
760 directory.place("d", Some("fav"), Some(0));
761 assert_eq!(
762 directory.folders[0].conversation_ids,
763 vec!["d", "b", "c", "a"]
764 );
765 assert!(directory.folders[1].conversation_ids.is_empty());
766 directory.place("b", Some("work"), Some(9));
767 assert_eq!(directory.folders[1].conversation_ids, vec!["b"]);
768 assert_eq!(directory.slot_of("fav", "c"), Some(1));
769 assert_eq!(directory.slot_of("work", "c"), None);
770 }
771
722 #[test]
772 #[test]
723 fn assign_moves_a_chat_between_folders() {
773 fn assign_moves_a_chat_between_folders() {
724 let mut directory = Directory {
774 let mut directory = Directory {
crates/app-state/src/demo.rs +40 −2
@@ -6,8 +6,9 @@ use std::time::Instant;
6 6 use chrono::{DateTime, Duration, Local, TimeZone, Utc};
7 7 use gpui_kit::{App, Entity};
8 8 use store::{
9 ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
10 ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
9 ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,
10 ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store,
11 TeamLayoutRecord, TeamRecord,
11 12 };
12 13 use teams_core::{
13 14 Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
@@ -134,6 +135,22 @@ const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [
134 135 const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
135 136 const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
136 137 const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
138 const DEMO_CHANNEL_MENTIONS: [(&str, ChannelMentions); 4] = [
139 ("demo-channel-1-2", mentions(2, 0, 0)),
140 ("demo-channel-2-1", mentions(0, 1, 0)),
141 (DEMO_HIDDEN_CHANNEL, mentions(1, 0, 0)),
142 ("demo-channel-4-2", mentions(1, 0, 1)),
143 ];
144 const PINNED_CHANNEL: &str = "demo-channel-1-1";
145 const PINNED_POST: &str = "t3";
146
147 const fn mentions(personal: u32, channel: u32, team: u32) -> ChannelMentions {
148 ChannelMentions {
149 personal,
150 channel,
151 team,
152 }
153 }
137 154 const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [
138 155 (
139 156 "demo-channel-1-1",
@@ -798,8 +815,21 @@ pub fn seed(store: &Store) {
798 815 });
799 816 }
800 817 }
818 for channel in channels.iter_mut().filter(|channel| {
819 DEMO_CHANNEL_MENTIONS
820 .iter()
821 .any(|(id, _)| *id == channel.id)
822 }) {
823 channel.unread = true;
824 }
801 825 let _ = store.upsert_channels(&channels);
802 826 let _ = store.replace_team_layout(&demo_team_layout(&channels));
827 let _ = store.replace_channel_mentions(
828 &DEMO_CHANNEL_MENTIONS
829 .iter()
830 .map(|(id, mentions)| ((*id).to_owned(), *mentions))
831 .collect::<Vec<_>>(),
832 );
803 833 let _ = store.set_meta("me_user_id", DEMO_USER_ID);
804 834 let _ = store.set_meta("me_display_name", DEMO_USER_NAME);
805 835 let _ = store.upsert_messages(&release_messages());
@@ -976,6 +1006,14 @@ pub fn seed_directory(state: &mut AppState) {
976 1006 }
977 1007
978 1008 fn seed_message_actions(state: &mut AppState) {
1009 state.pins.insert(
1010 PINNED_CHANNEL.to_owned(),
1011 vec![PinnedMessage {
1012 message_id: PINNED_POST.to_owned(),
1013 pinned_at: Some(at(0, 9, 45)),
1014 parent_id: None,
1015 }],
1016 );
979 1017 state.pins.insert(
980 1018 RELEASE_CHAT.to_owned(),
981 1019 vec![PinnedMessage {
@@ -6,8 +6,9 @@ use std::time::Instant;
6use chrono::{DateTime, Duration, Local, TimeZone, Utc};
6use chrono::{DateTime, Duration, Local, TimeZone, Utc};
7use gpui_kit::{App, Entity};
7use gpui_kit::{App, Entity};
8use store::{
8use store::{
9 ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
9 ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,
10 ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
10 ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store,
11 TeamLayoutRecord, TeamRecord,
11};
12};
12use teams_core::{
13use teams_core::{
13 Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
14 Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
@@ -134,6 +135,22 @@ const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [
134const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
135const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
135const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
136const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
136const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
137const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
138const DEMO_CHANNEL_MENTIONS: [(&str, ChannelMentions); 4] = [
139 ("demo-channel-1-2", mentions(2, 0, 0)),
140 ("demo-channel-2-1", mentions(0, 1, 0)),
141 (DEMO_HIDDEN_CHANNEL, mentions(1, 0, 0)),
142 ("demo-channel-4-2", mentions(1, 0, 1)),
143];
144const PINNED_CHANNEL: &str = "demo-channel-1-1";
145const PINNED_POST: &str = "t3";
146
147const fn mentions(personal: u32, channel: u32, team: u32) -> ChannelMentions {
148 ChannelMentions {
149 personal,
150 channel,
151 team,
152 }
153}
137const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [
154const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [
138 (
155 (
139 "demo-channel-1-1",
156 "demo-channel-1-1",
@@ -798,8 +815,21 @@ pub fn seed(store: &Store) {
798 });
815 });
799 }
816 }
800 }
817 }
818 for channel in channels.iter_mut().filter(|channel| {
819 DEMO_CHANNEL_MENTIONS
820 .iter()
821 .any(|(id, _)| *id == channel.id)
822 }) {
823 channel.unread = true;
824 }
801 let _ = store.upsert_channels(&channels);
825 let _ = store.upsert_channels(&channels);
802 let _ = store.replace_team_layout(&demo_team_layout(&channels));
826 let _ = store.replace_team_layout(&demo_team_layout(&channels));
827 let _ = store.replace_channel_mentions(
828 &DEMO_CHANNEL_MENTIONS
829 .iter()
830 .map(|(id, mentions)| ((*id).to_owned(), *mentions))
831 .collect::<Vec<_>>(),
832 );
803 let _ = store.set_meta("me_user_id", DEMO_USER_ID);
833 let _ = store.set_meta("me_user_id", DEMO_USER_ID);
804 let _ = store.set_meta("me_display_name", DEMO_USER_NAME);
834 let _ = store.set_meta("me_display_name", DEMO_USER_NAME);
805 let _ = store.upsert_messages(&release_messages());
835 let _ = store.upsert_messages(&release_messages());
@@ -976,6 +1006,14 @@ pub fn seed_directory(state: &mut AppState) {
976}
1006}
977
1007
978fn seed_message_actions(state: &mut AppState) {
1008fn seed_message_actions(state: &mut AppState) {
1009 state.pins.insert(
1010 PINNED_CHANNEL.to_owned(),
1011 vec![PinnedMessage {
1012 message_id: PINNED_POST.to_owned(),
1013 pinned_at: Some(at(0, 9, 45)),
1014 parent_id: None,
1015 }],
1016 );
979 state.pins.insert(
1017 state.pins.insert(
980 RELEASE_CHAT.to_owned(),
1018 RELEASE_CHAT.to_owned(),
981 vec![PinnedMessage {
1019 vec![PinnedMessage {
crates/app-state/src/lib.rs +1 −0
@@ -32,6 +32,7 @@ pub mod people;
32 32 pub mod profile_model;
33 33 pub mod profile_state;
34 34 pub mod reaction_model;
35 pub mod restorable_deletes;
35 36 pub mod rows;
36 37 pub mod scheduled;
37 38 pub mod scheduled_rows;
@@ -32,6 +32,7 @@ pub mod people;
32pub mod profile_model;
32pub mod profile_model;
33pub mod profile_state;
33pub mod profile_state;
34pub mod reaction_model;
34pub mod reaction_model;
35pub mod restorable_deletes;
35pub mod rows;
36pub mod rows;
36pub mod scheduled;
37pub mod scheduled;
37pub mod scheduled_rows;
38pub mod scheduled_rows;
crates/app-state/src/notify/incoming.rs +1 −0
@@ -347,6 +347,7 @@ mod tests {
347 347 .map(|id| (*id).to_owned())
348 348 .collect(),
349 349 notifications: HashMap::new(),
350 mentions: Default::default(),
350 351 }
351 352 }
352 353
@@ -347,6 +347,7 @@ mod tests {
347 .map(|id| (*id).to_owned())
347 .map(|id| (*id).to_owned())
348 .collect(),
348 .collect(),
349 notifications: HashMap::new(),
349 notifications: HashMap::new(),
350 mentions: Default::default(),
350 }
351 }
351 }
352 }
352
353
crates/app-state/src/notify/taskbar.rs +1 −0
@@ -68,6 +68,7 @@ mod tests {
68 68 hidden: false,
69 69 hidden_channel_ids: vec!["channel-b".into()],
70 70 notifications: Default::default(),
71 mentions: Default::default(),
71 72 }],
72 73 }
73 74 }
@@ -68,6 +68,7 @@ mod tests {
68 hidden: false,
68 hidden: false,
69 hidden_channel_ids: vec!["channel-b".into()],
69 hidden_channel_ids: vec!["channel-b".into()],
70 notifications: Default::default(),
70 notifications: Default::default(),
71 mentions: Default::default(),
71 }],
72 }],
72 }
73 }
73 }
74 }
crates/app-state/src/restorable_deletes.rs added +53 −0
@@ -0,0 +1,53 @@
1 use std::collections::HashSet;
2
3 pub const DELETED_TOMBSTONE: &str = "This message has been deleted.";
4 pub const UNDO_DELETE_LABEL: &str = "Undo";
5 pub const RESTORE_FAILED_NOTICE: &str = "Message restore failed. Please try again";
6
7 #[derive(Debug, Default, Clone)]
8 pub struct RestorableDeletes {
9 messages: HashSet<(String, String)>,
10 }
11
12 impl RestorableDeletes {
13 pub fn remember(&mut self, conversation_id: &str, message_id: &str) {
14 self.messages
15 .insert((conversation_id.to_owned(), message_id.to_owned()));
16 }
17
18 pub fn forget(&mut self, conversation_id: &str, message_id: &str) -> bool {
19 self.messages
20 .remove(&(conversation_id.to_owned(), message_id.to_owned()))
21 }
22
23 pub fn can_undo(
24 &self,
25 conversation_id: &str,
26 message_id: &str,
27 own: bool,
28 deleted: bool,
29 ) -> bool {
30 own && deleted
31 && self
32 .messages
33 .contains(&(conversation_id.to_owned(), message_id.to_owned()))
34 }
35 }
36
37 #[cfg(test)]
38 mod tests {
39 use super::*;
40
41 #[test]
42 fn only_own_messages_deleted_in_this_session_can_be_undone() {
43 let mut deletes = RestorableDeletes::default();
44 deletes.remember("19:a", "m1");
45 assert!(deletes.can_undo("19:a", "m1", true, true));
46 assert!(!deletes.can_undo("19:a", "m1", false, true));
47 assert!(!deletes.can_undo("19:a", "m1", true, false));
48 assert!(!deletes.can_undo("19:b", "m1", true, true));
49 assert!(deletes.forget("19:a", "m1"));
50 assert!(!deletes.can_undo("19:a", "m1", true, true));
51 assert!(!deletes.forget("19:a", "m1"));
52 }
53 }
@@ -0,0 +1,53 @@
1use std::collections::HashSet;
2
3pub const DELETED_TOMBSTONE: &str = "This message has been deleted.";
4pub const UNDO_DELETE_LABEL: &str = "Undo";
5pub const RESTORE_FAILED_NOTICE: &str = "Message restore failed. Please try again";
6
7#[derive(Debug, Default, Clone)]
8pub struct RestorableDeletes {
9 messages: HashSet<(String, String)>,
10}
11
12impl RestorableDeletes {
13 pub fn remember(&mut self, conversation_id: &str, message_id: &str) {
14 self.messages
15 .insert((conversation_id.to_owned(), message_id.to_owned()));
16 }
17
18 pub fn forget(&mut self, conversation_id: &str, message_id: &str) -> bool {
19 self.messages
20 .remove(&(conversation_id.to_owned(), message_id.to_owned()))
21 }
22
23 pub fn can_undo(
24 &self,
25 conversation_id: &str,
26 message_id: &str,
27 own: bool,
28 deleted: bool,
29 ) -> bool {
30 own && deleted
31 && self
32 .messages
33 .contains(&(conversation_id.to_owned(), message_id.to_owned()))
34 }
35}
36
37#[cfg(test)]
38mod tests {
39 use super::*;
40
41 #[test]
42 fn only_own_messages_deleted_in_this_session_can_be_undone() {
43 let mut deletes = RestorableDeletes::default();
44 deletes.remember("19:a", "m1");
45 assert!(deletes.can_undo("19:a", "m1", true, true));
46 assert!(!deletes.can_undo("19:a", "m1", false, true));
47 assert!(!deletes.can_undo("19:a", "m1", true, false));
48 assert!(!deletes.can_undo("19:b", "m1", true, true));
49 assert!(deletes.forget("19:a", "m1"));
50 assert!(!deletes.can_undo("19:a", "m1", true, true));
51 assert!(!deletes.forget("19:a", "m1"));
52 }
53}
crates/app-state/src/sidebar_model.rs +262 −30
@@ -1,9 +1,9 @@
1 1 use std::collections::{HashMap, HashSet};
2 2
3 use app_ui_kit::widgets::Unread;
3 4 use chrono::{DateTime, FixedOffset, Utc};
4 5 use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};
5 6 use teams_core::{ChatSection, is_event_preview};
6 use app_ui_kit::widgets::Unread;
7 7
8 8 use crate::app_state::chat_title;
9 9 use crate::data::{
@@ -260,10 +260,82 @@ pub fn channel_name_style(unread: bool, shown: bool, selected: bool) -> NameStyl
260 260 }
261 261 }
262 262
263 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
264 pub enum MentionBadge {
265 Count(u32),
266 Channel,
267 Team,
268 }
269
270 /// Teams pulls a hidden channel into the list while it holds personal @mentions.
271 pub fn channel_shown(team: &SidebarTeam, channel_id: &str) -> bool {
272 !team.hidden_channel_ids.iter().any(|id| id == channel_id)
273 || team.channel_mentions(channel_id).personal > 0
274 }
275
276 pub fn channel_hoisted(team: &SidebarTeam, channel_id: &str) -> bool {
277 team.hidden_channel_ids.iter().any(|id| id == channel_id)
278 && team.channel_mentions(channel_id).personal > 0
279 }
280
281 pub fn team_hoisted(team: &SidebarTeam) -> bool {
282 team.hidden
283 && team
284 .channels
285 .iter()
286 .any(|channel| channel_hoisted(team, &channel.id))
287 }
288
289 pub fn channel_badge(team: &SidebarTeam, channel_id: &str) -> Option<MentionBadge> {
290 let mentions = team.channel_mentions(channel_id);
291 if mentions.personal > 0 {
292 Some(MentionBadge::Count(mentions.personal))
293 } else if mentions.channel > 0 {
294 Some(MentionBadge::Channel)
295 } else if mentions.team > 0 {
296 Some(MentionBadge::Team)
297 } else {
298 None
299 }
300 }
301
302 /// The collapsed team row sums personal mentions of every channel, the icons only of shown channels.
303 pub fn team_badge(team: &SidebarTeam, expanded: bool) -> Option<MentionBadge> {
304 if expanded || !team_has_unread(team) {
305 return None;
306 }
307 let personal: u32 = team
308 .mentions
309 .iter()
310 .filter(|(channel_id, _)| {
311 team.channels
312 .iter()
313 .any(|channel| &channel.id == *channel_id)
314 })
315 .map(|(_, mentions)| mentions.personal)
316 .sum();
317 if personal > 0 {
318 return Some(MentionBadge::Count(personal));
319 }
320 let shown = || {
321 team.channels
322 .iter()
323 .filter(|channel| channel_shown(team, &channel.id))
324 .map(|channel| team.channel_mentions(&channel.id))
325 };
326 if shown().any(|mentions| mentions.channel > 0) {
327 Some(MentionBadge::Channel)
328 } else if shown().any(|mentions| mentions.team > 0) {
329 Some(MentionBadge::Team)
330 } else {
331 None
332 }
333 }
334
263 335 pub fn team_has_unread(team: &SidebarTeam) -> bool {
264 336 team.channels
265 337 .iter()
266 .any(|channel| channel.unread && !team.hidden_channel_ids.contains(&channel.id))
338 .any(|channel| channel.unread && channel_shown(team, &channel.id))
267 339 }
268 340
269 341 pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle {
@@ -471,40 +543,89 @@ pub fn visible_channel_ids<'a>(input: &ChannelOrderInput<'a>) -> Vec<&'a str> {
471 543 .teams
472 544 .iter()
473 545 .any(|entry| entry.hidden && holds_selection(entry));
474 let teams = input.teams.iter().filter(|entry| !entry.hidden).chain(
475 input
476 .teams
477 .iter()
478 .filter(|entry| entry.hidden && hidden_teams_shown),
479 );
480 for entry in teams {
546 let main_teams = input
547 .teams
548 .iter()
549 .filter(|entry| !entry.hidden || team_hoisted(entry))
550 .map(|entry| (entry, entry.hidden));
551 let hidden_teams = input
552 .teams
553 .iter()
554 .filter(|entry| entry.hidden && hidden_teams_shown)
555 .map(|entry| (entry, false));
556 for (entry, hoisted_only) in main_teams.chain(hidden_teams) {
481 557 if input.collapsed_teams.contains(&entry.team.id) {
482 558 continue;
483 559 }
484 let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
485 let is_selected =
486 |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
487 let revealed = input.revealed_channel_teams.contains(&entry.team.id);
488 for channel in entry
489 .channels
490 .iter()
491 .filter(|channel| !is_hidden(channel) || is_selected(channel))
492 {
493 push(&channel.id);
494 }
495 if revealed {
496 for channel in entry
497 .channels
498 .iter()
499 .filter(|channel| is_hidden(channel) && !is_selected(channel))
500 {
501 push(&channel.id);
502 }
560 for channel_id in team_channel_ids(entry, hoisted_only, input) {
561 push(channel_id);
503 562 }
504 563 }
505 564 ids
506 565 }
507 566
567 fn team_channel_ids<'a>(
568 entry: &'a SidebarTeam,
569 hoisted_only: bool,
570 input: &ChannelOrderInput<'_>,
571 ) -> Vec<&'a str> {
572 let is_selected = |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
573 let rows = team_channel_rows(
574 entry,
575 hoisted_only,
576 input.revealed_channel_teams.contains(&entry.team.id),
577 is_selected,
578 );
579 rows.shown
580 .into_iter()
581 .chain(rows.revealed)
582 .map(|channel| channel.id.as_str())
583 .collect()
584 }
585
586 pub struct TeamChannelRows<'a> {
587 pub shown: Vec<&'a ChannelRecord>,
588 pub hidden_count: usize,
589 pub revealed: Vec<&'a ChannelRecord>,
590 }
591
592 /// `hoisted_only` is a hidden team pulled into the main list: it shows only its hoisted channels.
593 pub fn team_channel_rows<'a>(
594 entry: &'a SidebarTeam,
595 hoisted_only: bool,
596 revealed: bool,
597 is_selected: impl Fn(&ChannelRecord) -> bool,
598 ) -> TeamChannelRows<'a> {
599 let shown: Vec<&ChannelRecord> = entry
600 .channels
601 .iter()
602 .filter(|channel| {
603 if hoisted_only {
604 channel_hoisted(entry, &channel.id)
605 } else {
606 is_selected(channel) || channel_shown(entry, &channel.id)
607 }
608 })
609 .collect();
610 if hoisted_only {
611 return TeamChannelRows {
612 shown,
613 hidden_count: 0,
614 revealed: Vec::new(),
615 };
616 }
617 let hidden: Vec<&ChannelRecord> = entry
618 .channels
619 .iter()
620 .filter(|channel| !shown.iter().any(|row| row.id == channel.id))
621 .collect();
622 TeamChannelRows {
623 shown,
624 hidden_count: hidden.len(),
625 revealed: if revealed { hidden } else { Vec::new() },
626 }
627 }
628
508 629 fn section(
509 630 id: String,
510 631 name: String,
@@ -746,6 +867,7 @@ mod tests {
746 867 .map(|id| (*id).to_owned())
747 868 .collect(),
748 869 notifications: HashMap::new(),
870 mentions: Default::default(),
749 871 }
750 872 }
751 873
@@ -857,6 +979,111 @@ mod tests {
857 979 );
858 980 }
859 981
982 fn with_mentions(mut entry: SidebarTeam, mentions: &[(&str, u32, u32, u32)]) -> SidebarTeam {
983 for (channel_id, personal, channel, team) in mentions {
984 entry.mentions.insert(
985 (*channel_id).to_owned(),
986 store::ChannelMentions {
987 personal: *personal,
988 channel: *channel,
989 team: *team,
990 },
991 );
992 }
993 entry
994 }
995
996 #[test]
997 fn channel_badges_prefer_the_count_then_channel_then_team() {
998 let entry = with_mentions(
999 team("t", false, &["a", "b", "c", "d"], &[]),
1000 &[("a", 2, 1, 1), ("b", 0, 3, 1), ("c", 0, 0, 1)],
1001 );
1002 assert_eq!(channel_badge(&entry, "a"), Some(MentionBadge::Count(2)));
1003 assert_eq!(channel_badge(&entry, "b"), Some(MentionBadge::Channel));
1004 assert_eq!(channel_badge(&entry, "c"), Some(MentionBadge::Team));
1005 assert_eq!(channel_badge(&entry, "d"), None);
1006 }
1007
1008 #[test]
1009 fn the_collapsed_team_sums_counts_of_all_channels_and_icons_of_shown_ones() {
1010 let entry = with_unread(
1011 with_mentions(
1012 team("t", false, &["a", "b", "c"], &["b", "c"]),
1013 &[("a", 1, 0, 0), ("b", 2, 0, 0), ("c", 0, 1, 0)],
1014 ),
1015 &["a", "b", "c"],
1016 );
1017 assert_eq!(team_badge(&entry, false), Some(MentionBadge::Count(3)));
1018 assert_eq!(team_badge(&entry, true), None);
1019 let icons_only = with_unread(
1020 with_mentions(
1021 team("t", false, &["a", "c"], &["c"]),
1022 &[("a", 0, 0, 1), ("c", 0, 1, 0)],
1023 ),
1024 &["a", "c"],
1025 );
1026 assert_eq!(team_badge(&icons_only, false), Some(MentionBadge::Team));
1027 let read = with_mentions(team("t", false, &["a"], &[]), &[("a", 1, 0, 0)]);
1028 assert_eq!(team_badge(&read, false), None);
1029 }
1030
1031 #[test]
1032 fn a_hidden_channel_with_a_personal_mention_is_pulled_into_the_list() {
1033 let entry = with_unread(
1034 with_mentions(
1035 team("t", false, &["a", "b", "c"], &["b", "c"]),
1036 &[("b", 1, 0, 0), ("c", 0, 1, 0)],
1037 ),
1038 &["b", "c"],
1039 );
1040 assert!(channel_shown(&entry, "b"));
1041 assert!(!channel_shown(&entry, "c"));
1042 assert!(team_has_unread(&entry));
1043 let rows = team_channel_rows(&entry, false, false, |_| false);
1044 let shown: Vec<&str> = rows
1045 .shown
1046 .iter()
1047 .map(|channel| channel.id.as_str())
1048 .collect();
1049 assert_eq!(shown, ["a", "b"]);
1050 assert_eq!(rows.hidden_count, 1);
1051 assert!(rows.revealed.is_empty());
1052 }
1053
1054 #[test]
1055 fn a_hidden_team_with_a_hoisted_channel_shows_only_that_channel_in_the_main_list() {
1056 let teams = [
1057 team("t1", false, &["a"], &[]),
1058 with_mentions(team("t2", true, &["b", "c"], &["c"]), &[("c", 1, 0, 0)]),
1059 ];
1060 assert!(team_hoisted(&teams[1]));
1061 assert!(!team_hoisted(&teams[0]));
1062 let rows = team_channel_rows(&teams[1], true, true, |_| true);
1063 let shown: Vec<&str> = rows
1064 .shown
1065 .iter()
1066 .map(|channel| channel.id.as_str())
1067 .collect();
1068 assert_eq!(shown, ["c"]);
1069 assert_eq!(rows.hidden_count, 0);
1070 let empty = HashSet::new();
1071 let input = ChannelOrderInput {
1072 teams: &teams,
1073 pinned_ids: &[],
1074 collapsed_teams: &empty,
1075 revealed_channel_teams: &empty,
1076 hidden_teams_open: false,
1077 selected_channel: None,
1078 };
1079 assert_eq!(visible_channel_ids(&input), ["a", "c"]);
1080 let open = ChannelOrderInput {
1081 hidden_teams_open: true,
1082 ..input
1083 };
1084 assert_eq!(visible_channel_ids(&open), ["a", "c", "b"]);
1085 }
1086
860 1087 #[test]
861 1088 fn muted_chats_stay_out_of_unread_counts() {
862 1089 let mut quiet = chat("a", "group", true);
@@ -1036,7 +1263,10 @@ mod tests {
1036 1263 let group = chat_item(&chats[1], &context, None);
1037 1264 assert_eq!(group.presence_user, None);
1038 1265 assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
1039 assert_eq!(avatar_for(&meeting_chat("meeting-1"), None), AvatarSpec::Meeting);
1266 assert_eq!(
1267 avatar_for(&meeting_chat("meeting-1"), None),
1268 AvatarSpec::Meeting
1269 );
1040 1270 }
1041 1271
1042 1272 #[test]
@@ -1048,7 +1278,9 @@ mod tests {
1048 1278 let collapsed = HashSet::new();
1049 1279 let mut notes = chat(teams_core::NOTES_CHAT_ID, "oneOnOne", false);
1050 1280 notes.title = "Me Myself (You)".into();
1051 notes.members.retain(|member| member.user_id.as_deref() == Some("me"));
1281 notes
1282 .members
1283 .retain(|member| member.user_id.as_deref() == Some("me"));
1052 1284 let chats = vec![notes];
1053 1285 let context = input(&chats, &directory, &collapsed);
1054 1286 let item = chat_item(&chats[0], &context, None);
@@ -1,9 +1,9 @@
1use std::collections::{HashMap, HashSet};
1use std::collections::{HashMap, HashSet};
2
2
3use app_ui_kit::widgets::Unread;
3use chrono::{DateTime, FixedOffset, Utc};
4use chrono::{DateTime, FixedOffset, Utc};
4use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};
5use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};
5use teams_core::{ChatSection, is_event_preview};
6use teams_core::{ChatSection, is_event_preview};
6use app_ui_kit::widgets::Unread;
7
7
8use crate::app_state::chat_title;
8use crate::app_state::chat_title;
9use crate::data::{
9use crate::data::{
@@ -260,10 +260,82 @@ pub fn channel_name_style(unread: bool, shown: bool, selected: bool) -> NameStyl
260 }
260 }
261}
261}
262
262
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub enum MentionBadge {
265 Count(u32),
266 Channel,
267 Team,
268}
269
270/// Teams pulls a hidden channel into the list while it holds personal @mentions.
271pub fn channel_shown(team: &SidebarTeam, channel_id: &str) -> bool {
272 !team.hidden_channel_ids.iter().any(|id| id == channel_id)
273 || team.channel_mentions(channel_id).personal > 0
274}
275
276pub fn channel_hoisted(team: &SidebarTeam, channel_id: &str) -> bool {
277 team.hidden_channel_ids.iter().any(|id| id == channel_id)
278 && team.channel_mentions(channel_id).personal > 0
279}
280
281pub fn team_hoisted(team: &SidebarTeam) -> bool {
282 team.hidden
283 && team
284 .channels
285 .iter()
286 .any(|channel| channel_hoisted(team, &channel.id))
287}
288
289pub fn channel_badge(team: &SidebarTeam, channel_id: &str) -> Option<MentionBadge> {
290 let mentions = team.channel_mentions(channel_id);
291 if mentions.personal > 0 {
292 Some(MentionBadge::Count(mentions.personal))
293 } else if mentions.channel > 0 {
294 Some(MentionBadge::Channel)
295 } else if mentions.team > 0 {
296 Some(MentionBadge::Team)
297 } else {
298 None
299 }
300}
301
302/// The collapsed team row sums personal mentions of every channel, the icons only of shown channels.
303pub fn team_badge(team: &SidebarTeam, expanded: bool) -> Option<MentionBadge> {
304 if expanded || !team_has_unread(team) {
305 return None;
306 }
307 let personal: u32 = team
308 .mentions
309 .iter()
310 .filter(|(channel_id, _)| {
311 team.channels
312 .iter()
313 .any(|channel| &channel.id == *channel_id)
314 })
315 .map(|(_, mentions)| mentions.personal)
316 .sum();
317 if personal > 0 {
318 return Some(MentionBadge::Count(personal));
319 }
320 let shown = || {
321 team.channels
322 .iter()
323 .filter(|channel| channel_shown(team, &channel.id))
324 .map(|channel| team.channel_mentions(&channel.id))
325 };
326 if shown().any(|mentions| mentions.channel > 0) {
327 Some(MentionBadge::Channel)
328 } else if shown().any(|mentions| mentions.team > 0) {
329 Some(MentionBadge::Team)
330 } else {
331 None
332 }
333}
334
263pub fn team_has_unread(team: &SidebarTeam) -> bool {
335pub fn team_has_unread(team: &SidebarTeam) -> bool {
264 team.channels
336 team.channels
265 .iter()
337 .iter()
266 .any(|channel| channel.unread && !team.hidden_channel_ids.contains(&channel.id))
338 .any(|channel| channel.unread && channel_shown(team, &channel.id))
267}
339}
268
340
269pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle {
341pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle {
@@ -471,40 +543,89 @@ pub fn visible_channel_ids<'a>(input: &ChannelOrderInput<'a>) -> Vec<&'a str> {
471 .teams
543 .teams
472 .iter()
544 .iter()
473 .any(|entry| entry.hidden && holds_selection(entry));
545 .any(|entry| entry.hidden && holds_selection(entry));
474 let teams = input.teams.iter().filter(|entry| !entry.hidden).chain(
546 let main_teams = input
475 input
547 .teams
476 .teams
548 .iter()
477 .iter()
549 .filter(|entry| !entry.hidden || team_hoisted(entry))
478 .filter(|entry| entry.hidden && hidden_teams_shown),
550 .map(|entry| (entry, entry.hidden));
479 );
551 let hidden_teams = input
480 for entry in teams {
552 .teams
553 .iter()
554 .filter(|entry| entry.hidden && hidden_teams_shown)
555 .map(|entry| (entry, false));
556 for (entry, hoisted_only) in main_teams.chain(hidden_teams) {
481 if input.collapsed_teams.contains(&entry.team.id) {
557 if input.collapsed_teams.contains(&entry.team.id) {
482 continue;
558 continue;
483 }
559 }
484 let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
560 for channel_id in team_channel_ids(entry, hoisted_only, input) {
485 let is_selected =
561 push(channel_id);
486 |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
487 let revealed = input.revealed_channel_teams.contains(&entry.team.id);
488 for channel in entry
489 .channels
490 .iter()
491 .filter(|channel| !is_hidden(channel) || is_selected(channel))
492 {
493 push(&channel.id);
494 }
495 if revealed {
496 for channel in entry
497 .channels
498 .iter()
499 .filter(|channel| is_hidden(channel) && !is_selected(channel))
500 {
501 push(&channel.id);
502 }
503 }
562 }
504 }
563 }
505 ids
564 ids
506}
565}
507
566
567fn team_channel_ids<'a>(
568 entry: &'a SidebarTeam,
569 hoisted_only: bool,
570 input: &ChannelOrderInput<'_>,
571) -> Vec<&'a str> {
572 let is_selected = |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
573 let rows = team_channel_rows(
574 entry,
575 hoisted_only,
576 input.revealed_channel_teams.contains(&entry.team.id),
577 is_selected,
578 );
579 rows.shown
580 .into_iter()
581 .chain(rows.revealed)
582 .map(|channel| channel.id.as_str())
583 .collect()
584}
585
586pub struct TeamChannelRows<'a> {
587 pub shown: Vec<&'a ChannelRecord>,
588 pub hidden_count: usize,
589 pub revealed: Vec<&'a ChannelRecord>,
590}
591
592/// `hoisted_only` is a hidden team pulled into the main list: it shows only its hoisted channels.
593pub fn team_channel_rows<'a>(
594 entry: &'a SidebarTeam,
595 hoisted_only: bool,
596 revealed: bool,
597 is_selected: impl Fn(&ChannelRecord) -> bool,
598) -> TeamChannelRows<'a> {
599 let shown: Vec<&ChannelRecord> = entry
600 .channels
601 .iter()
602 .filter(|channel| {
603 if hoisted_only {
604 channel_hoisted(entry, &channel.id)
605 } else {
606 is_selected(channel) || channel_shown(entry, &channel.id)
607 }
608 })
609 .collect();
610 if hoisted_only {
611 return TeamChannelRows {
612 shown,
613 hidden_count: 0,
614 revealed: Vec::new(),
615 };
616 }
617 let hidden: Vec<&ChannelRecord> = entry
618 .channels
619 .iter()
620 .filter(|channel| !shown.iter().any(|row| row.id == channel.id))
621 .collect();
622 TeamChannelRows {
623 shown,
624 hidden_count: hidden.len(),
625 revealed: if revealed { hidden } else { Vec::new() },
626 }
627}
628
508fn section(
629fn section(
509 id: String,
630 id: String,
510 name: String,
631 name: String,
@@ -746,6 +867,7 @@ mod tests {
746 .map(|id| (*id).to_owned())
867 .map(|id| (*id).to_owned())
747 .collect(),
868 .collect(),
748 notifications: HashMap::new(),
869 notifications: HashMap::new(),
870 mentions: Default::default(),
749 }
871 }
750 }
872 }
751
873
@@ -857,6 +979,111 @@ mod tests {
857 );
979 );
858 }
980 }
859
981
982 fn with_mentions(mut entry: SidebarTeam, mentions: &[(&str, u32, u32, u32)]) -> SidebarTeam {
983 for (channel_id, personal, channel, team) in mentions {
984 entry.mentions.insert(
985 (*channel_id).to_owned(),
986 store::ChannelMentions {
987 personal: *personal,
988 channel: *channel,
989 team: *team,
990 },
991 );
992 }
993 entry
994 }
995
996 #[test]
997 fn channel_badges_prefer_the_count_then_channel_then_team() {
998 let entry = with_mentions(
999 team("t", false, &["a", "b", "c", "d"], &[]),
1000 &[("a", 2, 1, 1), ("b", 0, 3, 1), ("c", 0, 0, 1)],
1001 );
1002 assert_eq!(channel_badge(&entry, "a"), Some(MentionBadge::Count(2)));
1003 assert_eq!(channel_badge(&entry, "b"), Some(MentionBadge::Channel));
1004 assert_eq!(channel_badge(&entry, "c"), Some(MentionBadge::Team));
1005 assert_eq!(channel_badge(&entry, "d"), None);
1006 }
1007
1008 #[test]
1009 fn the_collapsed_team_sums_counts_of_all_channels_and_icons_of_shown_ones() {
1010 let entry = with_unread(
1011 with_mentions(
1012 team("t", false, &["a", "b", "c"], &["b", "c"]),
1013 &[("a", 1, 0, 0), ("b", 2, 0, 0), ("c", 0, 1, 0)],
1014 ),
1015 &["a", "b", "c"],
1016 );
1017 assert_eq!(team_badge(&entry, false), Some(MentionBadge::Count(3)));
1018 assert_eq!(team_badge(&entry, true), None);
1019 let icons_only = with_unread(
1020 with_mentions(
1021 team("t", false, &["a", "c"], &["c"]),
1022 &[("a", 0, 0, 1), ("c", 0, 1, 0)],
1023 ),
1024 &["a", "c"],
1025 );
1026 assert_eq!(team_badge(&icons_only, false), Some(MentionBadge::Team));
1027 let read = with_mentions(team("t", false, &["a"], &[]), &[("a", 1, 0, 0)]);
1028 assert_eq!(team_badge(&read, false), None);
1029 }
1030
1031 #[test]
1032 fn a_hidden_channel_with_a_personal_mention_is_pulled_into_the_list() {
1033 let entry = with_unread(
1034 with_mentions(
1035 team("t", false, &["a", "b", "c"], &["b", "c"]),
1036 &[("b", 1, 0, 0), ("c", 0, 1, 0)],
1037 ),
1038 &["b", "c"],
1039 );
1040 assert!(channel_shown(&entry, "b"));
1041 assert!(!channel_shown(&entry, "c"));
1042 assert!(team_has_unread(&entry));
1043 let rows = team_channel_rows(&entry, false, false, |_| false);
1044 let shown: Vec<&str> = rows
1045 .shown
1046 .iter()
1047 .map(|channel| channel.id.as_str())
1048 .collect();
1049 assert_eq!(shown, ["a", "b"]);
1050 assert_eq!(rows.hidden_count, 1);
1051 assert!(rows.revealed.is_empty());
1052 }
1053
1054 #[test]
1055 fn a_hidden_team_with_a_hoisted_channel_shows_only_that_channel_in_the_main_list() {
1056 let teams = [
1057 team("t1", false, &["a"], &[]),
1058 with_mentions(team("t2", true, &["b", "c"], &["c"]), &[("c", 1, 0, 0)]),
1059 ];
1060 assert!(team_hoisted(&teams[1]));
1061 assert!(!team_hoisted(&teams[0]));
1062 let rows = team_channel_rows(&teams[1], true, true, |_| true);
1063 let shown: Vec<&str> = rows
1064 .shown
1065 .iter()
1066 .map(|channel| channel.id.as_str())
1067 .collect();
1068 assert_eq!(shown, ["c"]);
1069 assert_eq!(rows.hidden_count, 0);
1070 let empty = HashSet::new();
1071 let input = ChannelOrderInput {
1072 teams: &teams,
1073 pinned_ids: &[],
1074 collapsed_teams: &empty,
1075 revealed_channel_teams: &empty,
1076 hidden_teams_open: false,
1077 selected_channel: None,
1078 };
1079 assert_eq!(visible_channel_ids(&input), ["a", "c"]);
1080 let open = ChannelOrderInput {
1081 hidden_teams_open: true,
1082 ..input
1083 };
1084 assert_eq!(visible_channel_ids(&open), ["a", "c", "b"]);
1085 }
1086
860 #[test]
1087 #[test]
861 fn muted_chats_stay_out_of_unread_counts() {
1088 fn muted_chats_stay_out_of_unread_counts() {
862 let mut quiet = chat("a", "group", true);
1089 let mut quiet = chat("a", "group", true);
@@ -1036,7 +1263,10 @@ mod tests {
1036 let group = chat_item(&chats[1], &context, None);
1263 let group = chat_item(&chats[1], &context, None);
1037 assert_eq!(group.presence_user, None);
1264 assert_eq!(group.presence_user, None);
1038 assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
1265 assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
1039 assert_eq!(avatar_for(&meeting_chat("meeting-1"), None), AvatarSpec::Meeting);
1266 assert_eq!(
1267 avatar_for(&meeting_chat("meeting-1"), None),
1268 AvatarSpec::Meeting
1269 );
1040 }
1270 }
1041
1271
1042 #[test]
1272 #[test]
@@ -1048,7 +1278,9 @@ mod tests {
1048 let collapsed = HashSet::new();
1278 let collapsed = HashSet::new();
1049 let mut notes = chat(teams_core::NOTES_CHAT_ID, "oneOnOne", false);
1279 let mut notes = chat(teams_core::NOTES_CHAT_ID, "oneOnOne", false);
1050 notes.title = "Me Myself (You)".into();
1280 notes.title = "Me Myself (You)".into();
1051 notes.members.retain(|member| member.user_id.as_deref() == Some("me"));
1281 notes
1282 .members
1283 .retain(|member| member.user_id.as_deref() == Some("me"));
1052 let chats = vec![notes];
1284 let chats = vec![notes];
1053 let context = input(&chats, &directory, &collapsed);
1285 let context = input(&chats, &directory, &collapsed);
1054 let item = chat_item(&chats[0], &context, None);
1286 let item = chat_item(&chats[0], &context, None);
crates/app/src/call/overlay.rs +173 −26
@@ -7,12 +7,18 @@ use gpui_kit::*;
7 7 use super::model::format_elapsed;
8 8 use super::overlay_layout::{
9 9 BorderVisibility, MINI_POSITION_KEY, bar_collapsed, bar_rect, border_rects, border_thickness,
10 border_visibility, format_position, mini_rect, mini_wanted, mini_work_area, parse_position,
10 border_visibility, format_position, mini_rect, mini_work_area, parse_position,
11 };
12 use super::share_overlay::{
13 GALLERY_POSITION_KEY, GalleryLayout, LocalShare, Monitor, Surface, excluded_from_capture,
14 gallery_available_height, gallery_candidates, gallery_layout, gallery_rect,
15 minimize_on_share_start, overlay_plan,
11 16 };
12 17 use crate::app_state::AppState;
13 18 use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};
14 19 use crate::views::call_mini_window::MiniWindowView;
15 20 use crate::views::call_pop_out::{POP_OUT_SIZE, POP_OUT_TITLE, SharePopOutView};
21 use crate::views::call_share_gallery::ShareGalleryView;
16 22 use crate::views::share_bar::{ShareBarView, ShareBorderView};
17 23
18 24 const TICK: Duration = Duration::from_millis(100);
@@ -24,6 +30,7 @@ const BORDER_SIDES: usize = 4;
24 30 enum Role {
25 31 Bar,
26 32 Mini,
33 Gallery,
27 34 Border(usize),
28 35 }
29 36
@@ -76,6 +83,7 @@ struct ShareSession {
76 83 started: Instant,
77 84 source: Option<ShareSource>,
78 85 geometry: Option<ShareGeometry>,
86 minimize_checked: bool,
79 87 }
80 88
81 89 pub struct CallWindows {
@@ -95,6 +103,12 @@ pub struct CallWindows {
95 103 shown_second: u64,
96 104 mini_saved: Option<(i32, i32)>,
97 105 mini_seen: Option<(i32, i32)>,
106 gallery_saved: Option<(i32, i32)>,
107 gallery_seen: Option<(i32, i32)>,
108 gallery_layout: GalleryLayout,
109 speaker_only: bool,
110 main_excluded: bool,
111 minimized_for_share: bool,
98 112 ticks: u32,
99 113 }
100 114
@@ -125,12 +139,12 @@ fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
125 139 focus: false,
126 140 show: true,
127 141 kind: WindowKind::PopUp,
128 is_movable: role == Role::Mini,
142 is_movable: matches!(role, Role::Mini | Role::Gallery),
129 143 is_resizable: false,
130 144 is_minimizable: false,
131 145 window_background: match role {
132 146 Role::Border(_) => WindowBackgroundAppearance::Opaque,
133 Role::Bar | Role::Mini => WindowBackgroundAppearance::Transparent,
147 Role::Bar | Role::Mini | Role::Gallery => WindowBackgroundAppearance::Transparent,
134 148 },
135 149 ..Default::default()
136 150 }
@@ -138,13 +152,16 @@ fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
138 152
139 153 impl CallWindows {
140 154 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
141 let mini_saved = app
142 .read(cx)
143 .store
144 .meta(MINI_POSITION_KEY)
145 .ok()
146 .flatten()
147 .and_then(|text| parse_position(&text));
155 let saved_position = |key: &str, cx: &App| {
156 app.read(cx)
157 .store
158 .meta(key)
159 .ok()
160 .flatten()
161 .and_then(|text| parse_position(&text))
162 };
163 let mini_saved = saved_position(MINI_POSITION_KEY, cx);
164 let gallery_saved = saved_position(GALLERY_POSITION_KEY, cx);
148 165 let windows = CallWindows {
149 166 app,
150 167 main_window: window.window_handle(),
@@ -162,6 +179,12 @@ impl CallWindows {
162 179 shown_second: 0,
163 180 mini_saved,
164 181 mini_seen: None,
182 gallery_saved,
183 gallery_seen: None,
184 gallery_layout: gallery_layout(0, true, f32::MAX),
185 speaker_only: false,
186 main_excluded: false,
187 minimized_for_share: false,
165 188 ticks: 0,
166 189 };
167 190 cx.spawn(async move |this, cx| {
@@ -190,6 +213,19 @@ impl CallWindows {
190 213 self.bar_collapsed
191 214 }
192 215
216 pub fn gallery_layout(&self) -> GalleryLayout {
217 self.gallery_layout
218 }
219
220 pub fn sharing(&self) -> bool {
221 self.share.is_some()
222 }
223
224 pub fn toggle_speaker_only(&mut self, cx: &mut Context<Self>) {
225 self.speaker_only = !self.speaker_only;
226 cx.notify();
227 }
228
193 229 pub fn share_text(&self) -> String {
194 230 let Some(session) = &self.share else {
195 231 return String::new();
@@ -233,6 +269,7 @@ impl CallWindows {
233 269 && self.share.is_none()
234 270 && self.windows.is_empty()
235 271 && self.opening.is_empty()
272 && !self.main_excluded
236 273 }
237 274
238 275 fn tick(&mut self, cx: &mut Context<Self>) -> Duration {
@@ -243,10 +280,12 @@ impl CallWindows {
243 280 let slow = self.ticks % SLOW_TICK_EVERY == 0;
244 281 self.refresh_main_window();
245 282 self.sync_share(slow, cx);
283 self.sync_capture_exclusion();
246 284 self.sync_pop_out(cx);
247 self.sync_mini(cx);
285 self.sync_monitor(cx);
248 286 if slow {
249 self.track_mini_position(cx);
287 self.track_position(Role::Mini, cx);
288 self.track_position(Role::Gallery, cx);
250 289 }
251 290 TICK
252 291 }
@@ -255,7 +294,11 @@ impl CallWindows {
255 294 let Some(native) = self.main_native else {
256 295 return;
257 296 };
258 self.minimized = platform::window_minimized(native);
297 let minimized = platform::window_minimized(native);
298 if self.minimized && !minimized {
299 self.minimized_for_share = false;
300 }
301 self.minimized = minimized;
259 302 if !self.minimized {
260 303 self.work_area = platform::work_area(native).or(self.work_area);
261 304 }
@@ -285,6 +328,7 @@ impl CallWindows {
285 328 started: Instant::now(),
286 329 source: None,
287 330 geometry: None,
331 minimize_checked: false,
288 332 });
289 333 refresh_geometry = true;
290 334 }
@@ -305,6 +349,10 @@ impl CallWindows {
305 349 }
306 350 let geometry = session.geometry;
307 351 let elapsed_seconds = session.started.elapsed().as_secs();
352 let check_minimize = !std::mem::replace(&mut session.minimize_checked, true);
353 if check_minimize {
354 self.minimize_for_share(geometry.map(|geometry| geometry.target), cx);
355 }
308 356 let Some(work) = geometry
309 357 .map(|geometry| geometry.work)
310 358 .or(self.work_area)
@@ -347,10 +395,55 @@ impl CallWindows {
347 395 }
348 396 }
349 397
398 fn local_share_mode(&self) -> LocalShare {
399 let kind = self
400 .share
401 .as_ref()
402 .and_then(|session| session.source.as_ref())
403 .map(|source| source.kind);
404 LocalShare::of(kind, self.share.is_some())
405 }
406
407 fn minimize_for_share(&mut self, shared: Option<ScreenRect>, cx: &mut Context<Self>) {
408 let Some(native) = self.main_native.filter(|_| !self.minimized) else {
409 return;
410 };
411 if !minimize_on_share_start(
412 self.local_share_mode(),
413 platform::window_rect(native),
414 shared,
415 ) {
416 return;
417 }
418 self.minimized_for_share = true;
419 self.main_window
420 .update(cx, |_, window, _| window.minimize_window())
421 .ok();
422 }
423
424 fn sync_capture_exclusion(&mut self) {
425 let Some(native) = self.main_native else {
426 return;
427 };
428 let wanted = excluded_from_capture(Surface::Main, self.local_share_mode());
429 if wanted == self.main_excluded {
430 return;
431 }
432 self.main_excluded = wanted;
433 if wanted {
434 platform::exclude_from_capture(native);
435 } else {
436 platform::include_in_capture(native);
437 }
438 }
439
350 440 fn end_share(&mut self, cx: &mut Context<Self>) {
351 441 if self.share.take().is_none() {
352 442 return;
353 443 }
444 if std::mem::take(&mut self.minimized_for_share) && self.minimized {
445 self.return_to_call(cx);
446 }
354 447 self.bar_collapsed = false;
355 448 self.close(Role::Bar, cx);
356 449 self.close_borders(cx);
@@ -419,40 +512,91 @@ impl CallWindows {
419 512 });
420 513 }
421 514
422 fn sync_mini(&mut self, cx: &mut Context<Self>) {
515 fn sync_monitor(&mut self, cx: &mut Context<Self>) {
423 516 let in_call = self.app.read(cx).call.is_some();
517 let plan = overlay_plan(
518 in_call,
519 self.local_share_mode(),
520 self.minimized,
521 self.speaker_only,
522 );
424 523 let work = self.work_area.or_else(|| display_work_area(cx));
425 match work.filter(|_| mini_wanted(in_call, self.minimized)) {
426 Some(main_work) => {
524 match (plan.monitor, work) {
525 (Monitor::Mini, Some(main_work)) => {
526 self.close(Role::Gallery, cx);
427 527 let work = mini_work_area(main_work, self.mini_saved, platform::work_area_at);
428 528 let rect = mini_rect(work, self.mini_saved);
429 529 self.ensure_window(Role::Mini, rect, work.scale, false, cx);
430 530 }
431 None => self.close(Role::Mini, cx),
531 (Monitor::Gallery, Some(main_work)) => {
532 self.close(Role::Mini, cx);
533 self.place_gallery(main_work, cx);
534 }
535 _ => {
536 self.close(Role::Mini, cx);
537 self.close(Role::Gallery, cx);
538 }
432 539 }
433 540 }
434 541
435 fn track_mini_position(&mut self, cx: &mut Context<Self>) {
436 let Some(native) = self
542 fn place_gallery(&mut self, main_work: WorkArea, cx: &mut Context<Self>) {
543 let work = mini_work_area(main_work, self.gallery_saved, platform::work_area_at);
544 let (others, self_tile) = self.app.read(cx).call.as_ref().map_or((0, true), |call| {
545 (
546 gallery_candidates(&call.model).len(),
547 !call.model.view.hide_me,
548 )
549 });
550 let layout = gallery_layout(others, self_tile, gallery_available_height(work));
551 if layout != self.gallery_layout {
552 self.gallery_layout = layout;
553 cx.notify();
554 }
555 let origin = self
437 556 .windows
438 .get(&Role::Mini)
557 .get(&Role::Gallery)
439 558 .and_then(|placed| placed.native)
440 else {
559 .and_then(platform::window_rect)
560 .map(|rect| (rect.left, rect.top))
561 .or(self.gallery_saved);
562 let rect = gallery_rect(work, layout, origin);
563 match self.windows.get_mut(&Role::Gallery) {
564 Some(placed) => {
565 let size = |rect: ScreenRect| (rect.width(), rect.height());
566 if placed.rect.map(size) != Some(size(rect)) {
567 placed.place(rect, cx);
568 }
569 }
570 None => self.open(Role::Gallery, rect, work.scale, cx),
571 }
572 }
573
574 fn track_position(&mut self, role: Role, cx: &mut Context<Self>) {
575 let Some(native) = self.windows.get(&role).and_then(|placed| placed.native) else {
441 576 return;
442 577 };
443 578 let Some(rect) = platform::window_rect(native) else {
444 579 return;
445 580 };
581 let (key, saved, seen) = match role {
582 Role::Mini => (MINI_POSITION_KEY, &mut self.mini_saved, &mut self.mini_seen),
583 Role::Gallery => (
584 GALLERY_POSITION_KEY,
585 &mut self.gallery_saved,
586 &mut self.gallery_seen,
587 ),
588 Role::Bar | Role::Border(_) => return,
589 };
446 590 let position = (rect.left, rect.top);
447 let settled = self.mini_seen == Some(position);
448 self.mini_seen = Some(position);
449 if settled && self.mini_saved != Some(position) {
450 self.mini_saved = Some(position);
591 let settled = *seen == Some(position);
592 *seen = Some(position);
593 if settled && *saved != Some(position) {
594 *saved = Some(position);
451 595 let _ = self
452 596 .app
453 597 .read(cx)
454 598 .store
455 .set_meta(MINI_POSITION_KEY, &format_position(position.0, position.1));
599 .set_meta(key, &format_position(position.0, position.1));
456 600 }
457 601 }
458 602
@@ -506,6 +650,9 @@ impl CallWindows {
506 650 let view: AnyView = match role {
507 651 Role::Bar => cx.new(|cx| ShareBarView::new(view_controller, cx)).into(),
508 652 Role::Mini => cx.new(|cx| MiniWindowView::new(view_controller, cx)).into(),
653 Role::Gallery => cx
654 .new(|cx| ShareGalleryView::new(view_controller, cx))
655 .into(),
509 656 Role::Border(_) => cx.new(|_| ShareBorderView).into(),
510 657 };
511 658 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
@@ -7,12 +7,18 @@ use gpui_kit::*;
7use super::model::format_elapsed;
7use super::model::format_elapsed;
8use super::overlay_layout::{
8use super::overlay_layout::{
9 BorderVisibility, MINI_POSITION_KEY, bar_collapsed, bar_rect, border_rects, border_thickness,
9 BorderVisibility, MINI_POSITION_KEY, bar_collapsed, bar_rect, border_rects, border_thickness,
10 border_visibility, format_position, mini_rect, mini_wanted, mini_work_area, parse_position,
10 border_visibility, format_position, mini_rect, mini_work_area, parse_position,
11};
12use super::share_overlay::{
13 GALLERY_POSITION_KEY, GalleryLayout, LocalShare, Monitor, Surface, excluded_from_capture,
14 gallery_available_height, gallery_candidates, gallery_layout, gallery_rect,
15 minimize_on_share_start, overlay_plan,
11};
16};
12use crate::app_state::AppState;
17use crate::app_state::AppState;
13use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};
18use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};
14use crate::views::call_mini_window::MiniWindowView;
19use crate::views::call_mini_window::MiniWindowView;
15use crate::views::call_pop_out::{POP_OUT_SIZE, POP_OUT_TITLE, SharePopOutView};
20use crate::views::call_pop_out::{POP_OUT_SIZE, POP_OUT_TITLE, SharePopOutView};
21use crate::views::call_share_gallery::ShareGalleryView;
16use crate::views::share_bar::{ShareBarView, ShareBorderView};
22use crate::views::share_bar::{ShareBarView, ShareBorderView};
17
23
18const TICK: Duration = Duration::from_millis(100);
24const TICK: Duration = Duration::from_millis(100);
@@ -24,6 +30,7 @@ const BORDER_SIDES: usize = 4;
24enum Role {
30enum Role {
25 Bar,
31 Bar,
26 Mini,
32 Mini,
33 Gallery,
27 Border(usize),
34 Border(usize),
28}
35}
29
36
@@ -76,6 +83,7 @@ struct ShareSession {
76 started: Instant,
83 started: Instant,
77 source: Option<ShareSource>,
84 source: Option<ShareSource>,
78 geometry: Option<ShareGeometry>,
85 geometry: Option<ShareGeometry>,
86 minimize_checked: bool,
79}
87}
80
88
81pub struct CallWindows {
89pub struct CallWindows {
@@ -95,6 +103,12 @@ pub struct CallWindows {
95 shown_second: u64,
103 shown_second: u64,
96 mini_saved: Option<(i32, i32)>,
104 mini_saved: Option<(i32, i32)>,
97 mini_seen: Option<(i32, i32)>,
105 mini_seen: Option<(i32, i32)>,
106 gallery_saved: Option<(i32, i32)>,
107 gallery_seen: Option<(i32, i32)>,
108 gallery_layout: GalleryLayout,
109 speaker_only: bool,
110 main_excluded: bool,
111 minimized_for_share: bool,
98 ticks: u32,
112 ticks: u32,
99}
113}
100
114
@@ -125,12 +139,12 @@ fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
125 focus: false,
139 focus: false,
126 show: true,
140 show: true,
127 kind: WindowKind::PopUp,
141 kind: WindowKind::PopUp,
128 is_movable: role == Role::Mini,
142 is_movable: matches!(role, Role::Mini | Role::Gallery),
129 is_resizable: false,
143 is_resizable: false,
130 is_minimizable: false,
144 is_minimizable: false,
131 window_background: match role {
145 window_background: match role {
132 Role::Border(_) => WindowBackgroundAppearance::Opaque,
146 Role::Border(_) => WindowBackgroundAppearance::Opaque,
133 Role::Bar | Role::Mini => WindowBackgroundAppearance::Transparent,
147 Role::Bar | Role::Mini | Role::Gallery => WindowBackgroundAppearance::Transparent,
134 },
148 },
135 ..Default::default()
149 ..Default::default()
136 }
150 }
@@ -138,13 +152,16 @@ fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
138
152
139impl CallWindows {
153impl CallWindows {
140 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
154 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
141 let mini_saved = app
155 let saved_position = |key: &str, cx: &App| {
142 .read(cx)
156 app.read(cx)
143 .store
157 .store
144 .meta(MINI_POSITION_KEY)
158 .meta(key)
145 .ok()
159 .ok()
146 .flatten()
160 .flatten()
147 .and_then(|text| parse_position(&text));
161 .and_then(|text| parse_position(&text))
162 };
163 let mini_saved = saved_position(MINI_POSITION_KEY, cx);
164 let gallery_saved = saved_position(GALLERY_POSITION_KEY, cx);
148 let windows = CallWindows {
165 let windows = CallWindows {
149 app,
166 app,
150 main_window: window.window_handle(),
167 main_window: window.window_handle(),
@@ -162,6 +179,12 @@ impl CallWindows {
162 shown_second: 0,
179 shown_second: 0,
163 mini_saved,
180 mini_saved,
164 mini_seen: None,
181 mini_seen: None,
182 gallery_saved,
183 gallery_seen: None,
184 gallery_layout: gallery_layout(0, true, f32::MAX),
185 speaker_only: false,
186 main_excluded: false,
187 minimized_for_share: false,
165 ticks: 0,
188 ticks: 0,
166 };
189 };
167 cx.spawn(async move |this, cx| {
190 cx.spawn(async move |this, cx| {
@@ -190,6 +213,19 @@ impl CallWindows {
190 self.bar_collapsed
213 self.bar_collapsed
191 }
214 }
192
215
216 pub fn gallery_layout(&self) -> GalleryLayout {
217 self.gallery_layout
218 }
219
220 pub fn sharing(&self) -> bool {
221 self.share.is_some()
222 }
223
224 pub fn toggle_speaker_only(&mut self, cx: &mut Context<Self>) {
225 self.speaker_only = !self.speaker_only;
226 cx.notify();
227 }
228
193 pub fn share_text(&self) -> String {
229 pub fn share_text(&self) -> String {
194 let Some(session) = &self.share else {
230 let Some(session) = &self.share else {
195 return String::new();
231 return String::new();
@@ -233,6 +269,7 @@ impl CallWindows {
233 && self.share.is_none()
269 && self.share.is_none()
234 && self.windows.is_empty()
270 && self.windows.is_empty()
235 && self.opening.is_empty()
271 && self.opening.is_empty()
272 && !self.main_excluded
236 }
273 }
237
274
238 fn tick(&mut self, cx: &mut Context<Self>) -> Duration {
275 fn tick(&mut self, cx: &mut Context<Self>) -> Duration {
@@ -243,10 +280,12 @@ impl CallWindows {
243 let slow = self.ticks % SLOW_TICK_EVERY == 0;
280 let slow = self.ticks % SLOW_TICK_EVERY == 0;
244 self.refresh_main_window();
281 self.refresh_main_window();
245 self.sync_share(slow, cx);
282 self.sync_share(slow, cx);
283 self.sync_capture_exclusion();
246 self.sync_pop_out(cx);
284 self.sync_pop_out(cx);
247 self.sync_mini(cx);
285 self.sync_monitor(cx);
248 if slow {
286 if slow {
249 self.track_mini_position(cx);
287 self.track_position(Role::Mini, cx);
288 self.track_position(Role::Gallery, cx);
250 }
289 }
251 TICK
290 TICK
252 }
291 }
@@ -255,7 +294,11 @@ impl CallWindows {
255 let Some(native) = self.main_native else {
294 let Some(native) = self.main_native else {
256 return;
295 return;
257 };
296 };
258 self.minimized = platform::window_minimized(native);
297 let minimized = platform::window_minimized(native);
298 if self.minimized && !minimized {
299 self.minimized_for_share = false;
300 }
301 self.minimized = minimized;
259 if !self.minimized {
302 if !self.minimized {
260 self.work_area = platform::work_area(native).or(self.work_area);
303 self.work_area = platform::work_area(native).or(self.work_area);
261 }
304 }
@@ -285,6 +328,7 @@ impl CallWindows {
285 started: Instant::now(),
328 started: Instant::now(),
286 source: None,
329 source: None,
287 geometry: None,
330 geometry: None,
331 minimize_checked: false,
288 });
332 });
289 refresh_geometry = true;
333 refresh_geometry = true;
290 }
334 }
@@ -305,6 +349,10 @@ impl CallWindows {
305 }
349 }
306 let geometry = session.geometry;
350 let geometry = session.geometry;
307 let elapsed_seconds = session.started.elapsed().as_secs();
351 let elapsed_seconds = session.started.elapsed().as_secs();
352 let check_minimize = !std::mem::replace(&mut session.minimize_checked, true);
353 if check_minimize {
354 self.minimize_for_share(geometry.map(|geometry| geometry.target), cx);
355 }
308 let Some(work) = geometry
356 let Some(work) = geometry
309 .map(|geometry| geometry.work)
357 .map(|geometry| geometry.work)
310 .or(self.work_area)
358 .or(self.work_area)
@@ -347,10 +395,55 @@ impl CallWindows {
347 }
395 }
348 }
396 }
349
397
398 fn local_share_mode(&self) -> LocalShare {
399 let kind = self
400 .share
401 .as_ref()
402 .and_then(|session| session.source.as_ref())
403 .map(|source| source.kind);
404 LocalShare::of(kind, self.share.is_some())
405 }
406
407 fn minimize_for_share(&mut self, shared: Option<ScreenRect>, cx: &mut Context<Self>) {
408 let Some(native) = self.main_native.filter(|_| !self.minimized) else {
409 return;
410 };
411 if !minimize_on_share_start(
412 self.local_share_mode(),
413 platform::window_rect(native),
414 shared,
415 ) {
416 return;
417 }
418 self.minimized_for_share = true;
419 self.main_window
420 .update(cx, |_, window, _| window.minimize_window())
421 .ok();
422 }
423
424 fn sync_capture_exclusion(&mut self) {
425 let Some(native) = self.main_native else {
426 return;
427 };
428 let wanted = excluded_from_capture(Surface::Main, self.local_share_mode());
429 if wanted == self.main_excluded {
430 return;
431 }
432 self.main_excluded = wanted;
433 if wanted {
434 platform::exclude_from_capture(native);
435 } else {
436 platform::include_in_capture(native);
437 }
438 }
439
350 fn end_share(&mut self, cx: &mut Context<Self>) {
440 fn end_share(&mut self, cx: &mut Context<Self>) {
351 if self.share.take().is_none() {
441 if self.share.take().is_none() {
352 return;
442 return;
353 }
443 }
444 if std::mem::take(&mut self.minimized_for_share) && self.minimized {
445 self.return_to_call(cx);
446 }
354 self.bar_collapsed = false;
447 self.bar_collapsed = false;
355 self.close(Role::Bar, cx);
448 self.close(Role::Bar, cx);
356 self.close_borders(cx);
449 self.close_borders(cx);
@@ -419,40 +512,91 @@ impl CallWindows {
419 });
512 });
420 }
513 }
421
514
422 fn sync_mini(&mut self, cx: &mut Context<Self>) {
515 fn sync_monitor(&mut self, cx: &mut Context<Self>) {
423 let in_call = self.app.read(cx).call.is_some();
516 let in_call = self.app.read(cx).call.is_some();
517 let plan = overlay_plan(
518 in_call,
519 self.local_share_mode(),
520 self.minimized,
521 self.speaker_only,
522 );
424 let work = self.work_area.or_else(|| display_work_area(cx));
523 let work = self.work_area.or_else(|| display_work_area(cx));
425 match work.filter(|_| mini_wanted(in_call, self.minimized)) {
524 match (plan.monitor, work) {
426 Some(main_work) => {
525 (Monitor::Mini, Some(main_work)) => {
526 self.close(Role::Gallery, cx);
427 let work = mini_work_area(main_work, self.mini_saved, platform::work_area_at);
527 let work = mini_work_area(main_work, self.mini_saved, platform::work_area_at);
428 let rect = mini_rect(work, self.mini_saved);
528 let rect = mini_rect(work, self.mini_saved);
429 self.ensure_window(Role::Mini, rect, work.scale, false, cx);
529 self.ensure_window(Role::Mini, rect, work.scale, false, cx);
430 }
530 }
431 None => self.close(Role::Mini, cx),
531 (Monitor::Gallery, Some(main_work)) => {
532 self.close(Role::Mini, cx);
533 self.place_gallery(main_work, cx);
534 }
535 _ => {
536 self.close(Role::Mini, cx);
537 self.close(Role::Gallery, cx);
538 }
432 }
539 }
433 }
540 }
434
541
435 fn track_mini_position(&mut self, cx: &mut Context<Self>) {
542 fn place_gallery(&mut self, main_work: WorkArea, cx: &mut Context<Self>) {
436 let Some(native) = self
543 let work = mini_work_area(main_work, self.gallery_saved, platform::work_area_at);
544 let (others, self_tile) = self.app.read(cx).call.as_ref().map_or((0, true), |call| {
545 (
546 gallery_candidates(&call.model).len(),
547 !call.model.view.hide_me,
548 )
549 });
550 let layout = gallery_layout(others, self_tile, gallery_available_height(work));
551 if layout != self.gallery_layout {
552 self.gallery_layout = layout;
553 cx.notify();
554 }
555 let origin = self
437 .windows
556 .windows
438 .get(&Role::Mini)
557 .get(&Role::Gallery)
439 .and_then(|placed| placed.native)
558 .and_then(|placed| placed.native)
440 else {
559 .and_then(platform::window_rect)
560 .map(|rect| (rect.left, rect.top))
561 .or(self.gallery_saved);
562 let rect = gallery_rect(work, layout, origin);
563 match self.windows.get_mut(&Role::Gallery) {
564 Some(placed) => {
565 let size = |rect: ScreenRect| (rect.width(), rect.height());
566 if placed.rect.map(size) != Some(size(rect)) {
567 placed.place(rect, cx);
568 }
569 }
570 None => self.open(Role::Gallery, rect, work.scale, cx),
571 }
572 }
573
574 fn track_position(&mut self, role: Role, cx: &mut Context<Self>) {
575 let Some(native) = self.windows.get(&role).and_then(|placed| placed.native) else {
441 return;
576 return;
442 };
577 };
443 let Some(rect) = platform::window_rect(native) else {
578 let Some(rect) = platform::window_rect(native) else {
444 return;
579 return;
445 };
580 };
581 let (key, saved, seen) = match role {
582 Role::Mini => (MINI_POSITION_KEY, &mut self.mini_saved, &mut self.mini_seen),
583 Role::Gallery => (
584 GALLERY_POSITION_KEY,
585 &mut self.gallery_saved,
586 &mut self.gallery_seen,
587 ),
588 Role::Bar | Role::Border(_) => return,
589 };
446 let position = (rect.left, rect.top);
590 let position = (rect.left, rect.top);
447 let settled = self.mini_seen == Some(position);
591 let settled = *seen == Some(position);
448 self.mini_seen = Some(position);
592 *seen = Some(position);
449 if settled && self.mini_saved != Some(position) {
593 if settled && *saved != Some(position) {
450 self.mini_saved = Some(position);
594 *saved = Some(position);
451 let _ = self
595 let _ = self
452 .app
596 .app
453 .read(cx)
597 .read(cx)
454 .store
598 .store
455 .set_meta(MINI_POSITION_KEY, &format_position(position.0, position.1));
599 .set_meta(key, &format_position(position.0, position.1));
456 }
600 }
457 }
601 }
458
602
@@ -506,6 +650,9 @@ impl CallWindows {
506 let view: AnyView = match role {
650 let view: AnyView = match role {
507 Role::Bar => cx.new(|cx| ShareBarView::new(view_controller, cx)).into(),
651 Role::Bar => cx.new(|cx| ShareBarView::new(view_controller, cx)).into(),
508 Role::Mini => cx.new(|cx| MiniWindowView::new(view_controller, cx)).into(),
652 Role::Mini => cx.new(|cx| MiniWindowView::new(view_controller, cx)).into(),
653 Role::Gallery => cx
654 .new(|cx| ShareGalleryView::new(view_controller, cx))
655 .into(),
509 Role::Border(_) => cx.new(|_| ShareBorderView).into(),
656 Role::Border(_) => cx.new(|_| ShareBorderView).into(),
510 };
657 };
511 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
658 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
crates/app/src/layout_guard.rs +86 −1
@@ -180,8 +180,10 @@ mod frames {
180 180 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
181 181 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
182 182 };
183 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON};
183 use crate::views::conversation::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
184 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
184 185 use crate::views::message_row::BUBBLE_TAGS;
186 use crate::views::pin_banner::PIN_BANNER_TAG;
185 187 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
186 188 use crate::views::reaction_proposal_pill::REACTION_PILL;
187 189 use crate::views::recap_tab::RECAP_REGION;
@@ -1424,6 +1426,89 @@ mod frames {
1424 1426 }
1425 1427 }
1426 1428
1429 const PINNED_CHAT: &str = "demo-chat-release";
1430 const PINNED_CHANNEL: &str = "demo-channel-1-1";
1431
1432 #[gpui_kit::test]
1433 fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {
1434 let (handle, state) = mount(cx);
1435 let mut visual = VisualTestContext::from_window(handle, cx);
1436 let mut found = Vec::new();
1437 for (width, height) in SIZES {
1438 visual.simulate_resize(size(px(width), px(height)));
1439 visual.update(|_, cx| {
1440 state.update(cx, |state, cx| {
1441 state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)
1442 })
1443 });
1444 collect(&mut visual, Some(PIN_BANNER_TAG));
1445 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
1446 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
1447 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1448 let gaps = [
1449 ("top", f32::from(banner.top() - timeline.top())),
1450 ("left", f32::from(banner.left() - timeline.left())),
1451 ("right", f32::from(timeline.right() - banner.right())),
1452 ("below divider", f32::from(banner.top() - divider.bottom())),
1453 ];
1454 let side = gaps[1].1;
1455 if gaps
1456 .iter()
1457 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1458 {
1459 found.push(format!(
1460 "pin banner@{width}x{height}: gaps {gaps:?} must match"
1461 ));
1462 }
1463 }
1464 assert!(found.is_empty(), "{}", found.join("\n"));
1465 }
1466
1467 #[gpui_kit::test]
1468 fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {
1469 let (handle, state) = mount(cx);
1470 let mut visual = VisualTestContext::from_window(handle, cx);
1471 visual.simulate_resize(size(px(1280.), px(800.)));
1472 visual.update(|_, cx| {
1473 state.update(cx, |state, cx| {
1474 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1475 })
1476 });
1477 collect(&mut visual, Some(TIMELINE_TAG));
1478 assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());
1479 }
1480
1481 #[gpui_kit::test]
1482 fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {
1483 let (handle, state) = mount(cx);
1484 let mut visual = VisualTestContext::from_window(handle, cx);
1485 visual.simulate_resize(size(px(1280.), px(800.)));
1486 visual.update(|_, cx| {
1487 state.update(cx, |state, cx| {
1488 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1489 })
1490 });
1491 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1492 let button = visual
1493 .debug_bounds(CHANNEL_DETAILS_BUTTON)
1494 .expect("channel details button");
1495 visual.simulate_click(button.center(), Default::default());
1496 collect(&mut visual, Some(CHANNEL_DETAILS_TAG));
1497 let pane = visual
1498 .debug_bounds(CHANNEL_DETAILS_TAG)
1499 .expect("details pane");
1500 let main = visual.debug_bounds(MAIN).expect("main island");
1501 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1502 assert!(
1503 (f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,
1504 "pane {pane:?} must end at the main island edge {main:?}"
1505 );
1506 assert!(
1507 (f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,
1508 "pane {pane:?} must start under the header divider {divider:?}"
1509 );
1510 }
1511
1427 1512 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1428 1513 collect(visual, Some(COMPOSER_SEND_TAG));
1429 1514 let mut bounds_of = |path: &'static str| {
@@ -180,8 +180,10 @@ mod frames {
180 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
180 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
181 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
181 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
182 };
182 };
183 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON};
183 use crate::views::conversation::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
184 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
184 use crate::views::message_row::BUBBLE_TAGS;
185 use crate::views::message_row::BUBBLE_TAGS;
186 use crate::views::pin_banner::PIN_BANNER_TAG;
185 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
187 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
186 use crate::views::reaction_proposal_pill::REACTION_PILL;
188 use crate::views::reaction_proposal_pill::REACTION_PILL;
187 use crate::views::recap_tab::RECAP_REGION;
189 use crate::views::recap_tab::RECAP_REGION;
@@ -1424,6 +1426,89 @@ mod frames {
1424 }
1426 }
1425 }
1427 }
1426
1428
1429 const PINNED_CHAT: &str = "demo-chat-release";
1430 const PINNED_CHANNEL: &str = "demo-channel-1-1";
1431
1432 #[gpui_kit::test]
1433 fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {
1434 let (handle, state) = mount(cx);
1435 let mut visual = VisualTestContext::from_window(handle, cx);
1436 let mut found = Vec::new();
1437 for (width, height) in SIZES {
1438 visual.simulate_resize(size(px(width), px(height)));
1439 visual.update(|_, cx| {
1440 state.update(cx, |state, cx| {
1441 state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)
1442 })
1443 });
1444 collect(&mut visual, Some(PIN_BANNER_TAG));
1445 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
1446 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
1447 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1448 let gaps = [
1449 ("top", f32::from(banner.top() - timeline.top())),
1450 ("left", f32::from(banner.left() - timeline.left())),
1451 ("right", f32::from(timeline.right() - banner.right())),
1452 ("below divider", f32::from(banner.top() - divider.bottom())),
1453 ];
1454 let side = gaps[1].1;
1455 if gaps
1456 .iter()
1457 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1458 {
1459 found.push(format!(
1460 "pin banner@{width}x{height}: gaps {gaps:?} must match"
1461 ));
1462 }
1463 }
1464 assert!(found.is_empty(), "{}", found.join("\n"));
1465 }
1466
1467 #[gpui_kit::test]
1468 fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {
1469 let (handle, state) = mount(cx);
1470 let mut visual = VisualTestContext::from_window(handle, cx);
1471 visual.simulate_resize(size(px(1280.), px(800.)));
1472 visual.update(|_, cx| {
1473 state.update(cx, |state, cx| {
1474 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1475 })
1476 });
1477 collect(&mut visual, Some(TIMELINE_TAG));
1478 assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());
1479 }
1480
1481 #[gpui_kit::test]
1482 fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {
1483 let (handle, state) = mount(cx);
1484 let mut visual = VisualTestContext::from_window(handle, cx);
1485 visual.simulate_resize(size(px(1280.), px(800.)));
1486 visual.update(|_, cx| {
1487 state.update(cx, |state, cx| {
1488 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1489 })
1490 });
1491 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1492 let button = visual
1493 .debug_bounds(CHANNEL_DETAILS_BUTTON)
1494 .expect("channel details button");
1495 visual.simulate_click(button.center(), Default::default());
1496 collect(&mut visual, Some(CHANNEL_DETAILS_TAG));
1497 let pane = visual
1498 .debug_bounds(CHANNEL_DETAILS_TAG)
1499 .expect("details pane");
1500 let main = visual.debug_bounds(MAIN).expect("main island");
1501 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1502 assert!(
1503 (f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,
1504 "pane {pane:?} must end at the main island edge {main:?}"
1505 );
1506 assert!(
1507 (f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,
1508 "pane {pane:?} must start under the header divider {divider:?}"
1509 );
1510 }
1511
1427 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1512 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1428 collect(visual, Some(COMPOSER_SEND_TAG));
1513 collect(visual, Some(COMPOSER_SEND_TAG));
1429 let mut bounds_of = |path: &'static str| {
1514 let mut bounds_of = |path: &'static str| {
crates/app/src/notify/center.rs +1 −0
@@ -1397,6 +1397,7 @@ mod tests {
1397 1397 hidden: false,
1398 1398 hidden_channel_ids: Vec::new(),
1399 1399 notifications: Default::default(),
1400 mentions: Default::default(),
1400 1401 }],
1401 1402 }
1402 1403 }
@@ -1397,6 +1397,7 @@ mod tests {
1397 hidden: false,
1397 hidden: false,
1398 hidden_channel_ids: Vec::new(),
1398 hidden_channel_ids: Vec::new(),
1399 notifications: Default::default(),
1399 notifications: Default::default(),
1400 mentions: Default::default(),
1400 }],
1401 }],
1401 }
1402 }
1402 }
1403 }
crates/app/src/views/call_mini_window.rs +27 −11
@@ -3,9 +3,11 @@ use std::time::Instant;
3 3 use calling::VideoKey;
4 4 use gpui_kit::assets::IconName;
5 5 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
6 use gpui_kit::prelude::FluentBuilder as _;
6 7 use gpui_kit::*;
7 8
8 9 use super::avatar::person_avatar;
10 use super::call_share_gallery::{SHOW_MORE_PEOPLE, view_switch_button};
9 11 use super::call_view::{camera_button, leave_button, mute_button, round_control, status_line};
10 12 use super::widgets::icon;
11 13 use crate::app_state::AppState;
@@ -234,6 +236,7 @@ impl Render for MiniWindowView {
234 236 let now = Instant::now();
235 237 let (status, _) = status_line(model, now);
236 238 let windows = self.windows.clone();
239 let sharing = self.windows.read(cx).sharing();
237 240 let speaking = speaker_speaking(model);
238 241 let speaker_name = speaker_name_chip(state, model, now);
239 242 div()
@@ -274,17 +277,30 @@ impl Render for MiniWindowView {
274 277 }))
275 278 .children(self_view(state, model, now)),
276 279 )
277 .child(controls_row(
278 &self.app,
279 model,
280 ControlIds {
281 mute: "call-mini-window-mute",
282 back: "call-mini-window-back",
283 leave: "call-mini-window-leave",
284 },
285 "call-mini-window",
286 move |cx| windows.update(cx, |windows, cx| windows.return_to_call(cx)),
287 ))
280 .child(
281 controls_row(
282 &self.app,
283 model,
284 ControlIds {
285 mute: "call-mini-window-mute",
286 back: "call-mini-window-back",
287 leave: "call-mini-window-leave",
288 },
289 "call-mini-window",
290 move |cx| windows.update(cx, |windows, cx| windows.return_to_call(cx)),
291 )
292 .when(sharing, |row| {
293 row.child(
294 view_switch_button(
295 &self.windows,
296 "call-mini-window-more-people",
297 IconName::Users,
298 SHOW_MORE_PEOPLE,
299 )
300 .size(px(CONTROL_SIZE)),
301 )
302 }),
303 )
288 304 .into_any_element()
289 305 }
290 306 }
@@ -3,9 +3,11 @@ use std::time::Instant;
3use calling::VideoKey;
3use calling::VideoKey;
4use gpui_kit::assets::IconName;
4use gpui_kit::assets::IconName;
5use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
5use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7use gpui_kit::*;
7
8
8use super::avatar::person_avatar;
9use super::avatar::person_avatar;
10use super::call_share_gallery::{SHOW_MORE_PEOPLE, view_switch_button};
9use super::call_view::{camera_button, leave_button, mute_button, round_control, status_line};
11use super::call_view::{camera_button, leave_button, mute_button, round_control, status_line};
10use super::widgets::icon;
12use super::widgets::icon;
11use crate::app_state::AppState;
13use crate::app_state::AppState;
@@ -234,6 +236,7 @@ impl Render for MiniWindowView {
234 let now = Instant::now();
236 let now = Instant::now();
235 let (status, _) = status_line(model, now);
237 let (status, _) = status_line(model, now);
236 let windows = self.windows.clone();
238 let windows = self.windows.clone();
239 let sharing = self.windows.read(cx).sharing();
237 let speaking = speaker_speaking(model);
240 let speaking = speaker_speaking(model);
238 let speaker_name = speaker_name_chip(state, model, now);
241 let speaker_name = speaker_name_chip(state, model, now);
239 div()
242 div()
@@ -274,17 +277,30 @@ impl Render for MiniWindowView {
274 }))
277 }))
275 .children(self_view(state, model, now)),
278 .children(self_view(state, model, now)),
276 )
279 )
277 .child(controls_row(
280 .child(
278 &self.app,
281 controls_row(
279 model,
282 &self.app,
280 ControlIds {
283 model,
281 mute: "call-mini-window-mute",
284 ControlIds {
282 back: "call-mini-window-back",
285 mute: "call-mini-window-mute",
283 leave: "call-mini-window-leave",
286 back: "call-mini-window-back",
284 },
287 leave: "call-mini-window-leave",
285 "call-mini-window",
288 },
286 move |cx| windows.update(cx, |windows, cx| windows.return_to_call(cx)),
289 "call-mini-window",
287 ))
290 move |cx| windows.update(cx, |windows, cx| windows.return_to_call(cx)),
291 )
292 .when(sharing, |row| {
293 row.child(
294 view_switch_button(
295 &self.windows,
296 "call-mini-window-more-people",
297 IconName::Users,
298 SHOW_MORE_PEOPLE,
299 )
300 .size(px(CONTROL_SIZE)),
301 )
302 }),
303 )
288 .into_any_element()
304 .into_any_element()
289 }
305 }
290}
306}
crates/app/src/views/call_view.rs +28 −8
@@ -963,6 +963,17 @@ pub(super) fn person_tile(
963 963 remote: &Tile,
964 964 size: TileSize,
965 965 now: Instant,
966 ) -> AnyElement {
967 let element = plain_person_tile(state, model, remote, size, now);
968 with_tile_menu(app, model, &remote.mri, &remote.name, false, element)
969 }
970
971 pub(super) fn plain_person_tile(
972 state: &AppState,
973 model: &CallModel,
974 remote: &Tile,
975 size: TileSize,
976 now: Instant,
966 977 ) -> AnyElement {
967 978 let extras = TileExtras {
968 979 hand: remote.hand.map(|rank| model.hand_position(rank)),
@@ -973,8 +984,7 @@ pub(super) fn person_tile(
973 984 spotlight: remote.spotlight.is_some(),
974 985 pinned: model.is_pinned(&remote.mri),
975 986 };
976 let element = person_tile_body(state, model, remote, size, now, &extras);
977 with_tile_menu(app, model, &remote.mri, &remote.name, false, element)
987 person_tile_body(state, model, remote, size, now, &extras)
978 988 }
979 989
980 990 fn person_tile_body(
@@ -1042,18 +1052,28 @@ pub(super) fn own_tile(
1042 1052 now: Instant,
1043 1053 ) -> AnyElement {
1044 1054 let own_mri = model.own_mri.clone().unwrap_or_default();
1055 let element = plain_own_tile(state, model, size, now);
1056 if own_mri.is_empty() {
1057 return element;
1058 }
1059 with_tile_menu(app, model, &own_mri, "You", true, element)
1060 }
1061
1062 pub(super) fn plain_own_tile(
1063 state: &AppState,
1064 model: &CallModel,
1065 size: TileSize,
1066 now: Instant,
1067 ) -> AnyElement {
1068 let own_mri = model.own_mri.as_deref().unwrap_or_default();
1045 1069 let extras = TileExtras {
1046 1070 hand: model.own_hand.map(|rank| model.hand_position(rank)),
1047 1071 own: true,
1048 1072 reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),
1049 1073 spotlight: model.own_spotlight.is_some(),
1050 pinned: model.is_pinned(&own_mri),
1074 pinned: model.is_pinned(own_mri),
1051 1075 };
1052 let element = own_tile_body(state, model, size, now, &extras);
1053 if own_mri.is_empty() {
1054 return element;
1055 }
1056 with_tile_menu(app, model, &own_mri, "You", true, element)
1076 own_tile_body(state, model, size, now, &extras)
1057 1077 }
1058 1078
1059 1079 fn own_tile_body(
@@ -963,6 +963,17 @@ pub(super) fn person_tile(
963 remote: &Tile,
963 remote: &Tile,
964 size: TileSize,
964 size: TileSize,
965 now: Instant,
965 now: Instant,
966) -> AnyElement {
967 let element = plain_person_tile(state, model, remote, size, now);
968 with_tile_menu(app, model, &remote.mri, &remote.name, false, element)
969}
970
971pub(super) fn plain_person_tile(
972 state: &AppState,
973 model: &CallModel,
974 remote: &Tile,
975 size: TileSize,
976 now: Instant,
966) -> AnyElement {
977) -> AnyElement {
967 let extras = TileExtras {
978 let extras = TileExtras {
968 hand: remote.hand.map(|rank| model.hand_position(rank)),
979 hand: remote.hand.map(|rank| model.hand_position(rank)),
@@ -973,8 +984,7 @@ pub(super) fn person_tile(
973 spotlight: remote.spotlight.is_some(),
984 spotlight: remote.spotlight.is_some(),
974 pinned: model.is_pinned(&remote.mri),
985 pinned: model.is_pinned(&remote.mri),
975 };
986 };
976 let element = person_tile_body(state, model, remote, size, now, &extras);
987 person_tile_body(state, model, remote, size, now, &extras)
977 with_tile_menu(app, model, &remote.mri, &remote.name, false, element)
978}
988}
979
989
980fn person_tile_body(
990fn person_tile_body(
@@ -1042,18 +1052,28 @@ pub(super) fn own_tile(
1042 now: Instant,
1052 now: Instant,
1043) -> AnyElement {
1053) -> AnyElement {
1044 let own_mri = model.own_mri.clone().unwrap_or_default();
1054 let own_mri = model.own_mri.clone().unwrap_or_default();
1055 let element = plain_own_tile(state, model, size, now);
1056 if own_mri.is_empty() {
1057 return element;
1058 }
1059 with_tile_menu(app, model, &own_mri, "You", true, element)
1060}
1061
1062pub(super) fn plain_own_tile(
1063 state: &AppState,
1064 model: &CallModel,
1065 size: TileSize,
1066 now: Instant,
1067) -> AnyElement {
1068 let own_mri = model.own_mri.as_deref().unwrap_or_default();
1045 let extras = TileExtras {
1069 let extras = TileExtras {
1046 hand: model.own_hand.map(|rank| model.hand_position(rank)),
1070 hand: model.own_hand.map(|rank| model.hand_position(rank)),
1047 own: true,
1071 own: true,
1048 reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),
1072 reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),
1049 spotlight: model.own_spotlight.is_some(),
1073 spotlight: model.own_spotlight.is_some(),
1050 pinned: model.is_pinned(&own_mri),
1074 pinned: model.is_pinned(own_mri),
1051 };
1075 };
1052 let element = own_tile_body(state, model, size, now, &extras);
1076 own_tile_body(state, model, size, now, &extras)
1053 if own_mri.is_empty() {
1054 return element;
1055 }
1056 with_tile_menu(app, model, &own_mri, "You", true, element)
1057}
1077}
1058
1078
1059fn own_tile_body(
1079fn own_tile_body(
crates/app/src/views/conversation.rs +64 −74
@@ -21,8 +21,12 @@ use teams_core::{
21 21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,
22 22 };
23 23
24 mod channel_details;
25 pub use channel_details::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
26 mod deletes;
24 27 mod detached;
25 28 mod feed;
29 mod jump;
26 30 mod pins;
27 31 mod proposal;
28 32 mod recap;
@@ -91,6 +95,7 @@ use shared::SharedState;
91 95
92 96 pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";
93 97 pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
98 pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";
94 99 const HEADER_HEIGHT: f32 = 60.;
95 100 const HEADER_PADDING: f32 = 20.;
96 101 const HEADER_GAP: f32 = 12.;
@@ -212,6 +217,8 @@ pub struct ConversationView {
212 217 reaction_details: Option<ReactionDetails>,
213 218 highlighted_message: Option<String>,
214 219 pin_index: usize,
220 channel_details_open: bool,
221 pinned_posts_expanded: bool,
215 222 pin_previews: HashMap<String, pins::PinPreview>,
216 223 pin_fetches: HashSet<String>,
217 224 notice: Option<String>,
@@ -541,6 +548,8 @@ impl ConversationView {
541 548 reaction_details: None,
542 549 highlighted_message: None,
543 550 pin_index: 0,
551 channel_details_open: false,
552 pinned_posts_expanded: false,
544 553 pin_previews: HashMap::new(),
545 554 pin_fetches: HashSet::new(),
546 555 notice: None,
@@ -883,9 +892,10 @@ impl ConversationView {
883 892 self.start_fetch(cx);
884 893 self.mark_read(ReadTrigger::Open, cx);
885 894 self.refresh_pin_previews(cx);
886 if let Some(chat_id) = self.chat_id() {
895 self.pinned_posts_expanded = false;
896 if let Some(conversation_id) = self.pin_conversation_id() {
887 897 self.app
888 .update(cx, |state, cx| state.refresh_pins(&chat_id, cx));
898 .update(cx, |state, cx| state.refresh_pins(&conversation_id, cx));
889 899 }
890 900 let target = self
891 901 .current
@@ -2808,31 +2818,6 @@ impl ConversationView {
2808 2818 .detach();
2809 2819 }
2810 2820
2811 fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
2812 let Some(mut record) = self.own_record(message_id, cx) else {
2813 return;
2814 };
2815 let state = self.app.read(cx);
2816 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2817 if mode.demo {
2818 record.deleted = true;
2819 let _ = store.upsert_messages(std::slice::from_ref(&record));
2820 self.rebuild(false, cx);
2821 return;
2822 }
2823 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2824 self.show_notice("Read-only mode: message not deleted", cx);
2825 return;
2826 };
2827 let conversation_id = record.conversation_id.clone();
2828 let receiver = runtime::spawn(async move {
2829 engine
2830 .soft_delete_message(&conversation_id, &record.message_id)
2831 .await
2832 });
2833 self.report_failure(receiver, "Delete failed", cx);
2834 }
2835
2836 2821 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
2837 2822 let Some(conversation_id) = self.conversation_id() else {
2838 2823 return;
@@ -2880,26 +2865,6 @@ impl ConversationView {
2880 2865 });
2881 2866 }
2882 2867
2883 fn report_failure(
2884 &mut self,
2885 receiver: tokio::sync::oneshot::Receiver<teams_core::Result<()>>,
2886 label: &'static str,
2887 cx: &mut Context<Self>,
2888 ) {
2889 cx.spawn(async move |this, cx| {
2890 let error = match receiver.await {
2891 Ok(Ok(())) => return,
2892 Ok(Err(error)) => short_error(&error),
2893 Err(_) => "cancelled".to_owned(),
2894 };
2895 this.update(cx, |this, cx| {
2896 this.show_notice(&format!("{label}: {error}"), cx)
2897 })
2898 .ok();
2899 })
2900 .detach();
2901 }
2902
2903 2868 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
2904 2869 let (Some(conversation_id), Some(runs)) =
2905 2870 (self.conversation_id(), crate::agents::runs_handle(cx))
@@ -3058,11 +3023,18 @@ impl ConversationView {
3058 3023 let saved = self
3059 3024 .conversation_id()
3060 3025 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3061 let pinned = chat_id
3062 .as_deref()
3063 .is_some_and(|chat_id| state.is_pinned(chat_id, key));
3064 3026 let quick = state.quick_reactions();
3065 3027 let in_chat = chat_id.is_some();
3028 let pin_conversation_id = self.pin_conversation_id();
3029 let pinned = pin_conversation_id
3030 .as_deref()
3031 .is_some_and(|conversation_id| state.is_pinned(conversation_id, key));
3032 let pinnable = in_chat
3033 || pin_conversation_id.as_deref().is_some_and(|channel_id| {
3034 state
3035 .message_record(channel_id, key)
3036 .is_some_and(|record| record.reply_to_id.is_none())
3037 });
3066 3038 let (delegate, manage_agents) = self.delegate_entries(key, cx);
3067 3039 MessageMenu {
3068 3040 key: key.to_owned(),
@@ -3077,7 +3049,7 @@ impl ConversationView {
3077 3049 translate_label,
3078 3050 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3079 3051 saved,
3080 toggle_pinned: in_chat.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
3052 toggle_pinned: pinnable.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
3081 3053 pinned,
3082 3054 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3083 3055 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
@@ -3457,6 +3429,7 @@ impl ConversationView {
3457 3429 .children(inline_tabs)
3458 3430 .children(stack)
3459 3431 .children(call_controls)
3432 .children(self.channel_details_button(cx))
3460 3433 }
3461 3434 }
3462 3435
@@ -3603,6 +3576,15 @@ impl Render for ConversationView {
3603 3576 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3604 3577 .jump_button(!in_feed)
3605 3578 .force_jump_button(detached)
3579 .with_jump_button_label(jump::JUMP_TO_NEWEST_LABEL)
3580 .with_jump_button_renderer(|button| {
3581 button
3582 .label(jump::JUMP_TO_NEWEST_LABEL)
3583 .tooltip(jump::jump_to_newest_tooltip())
3584 .border_0()
3585 .bg(theme::accent())
3586 .text_color(theme::on_accent())
3587 })
3606 3588 .when(detached, |scroller| {
3607 3589 let view = cx.weak_entity();
3608 3590 scroller.on_jump(move |_, cx| {
@@ -3684,32 +3666,40 @@ impl Render for ConversationView {
3684 3666 } else {
3685 3667 scroller.into_any_element()
3686 3668 };
3669 let channel_details = self.render_channel_details(cx);
3670 let content = v_flex()
3671 .relative()
3672 .flex_1()
3673 .min_w_0()
3674 .min_h_0()
3675 .children(new_post)
3676 .child(
3677 div()
3678 .debug_selector(|| TIMELINE_TAG.into())
3679 .relative()
3680 .flex_1()
3681 .min_h_0()
3682 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3683 .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx)))
3684 .child(body)
3685 .children(pin_banner.map(pin_banner_overlay)),
3686 )
3687 .children(self.render_draft_error(cx))
3688 .when(!in_feed && !recap_active, |column| {
3689 column
3690 .child(self.render_typing_line(cx))
3691 .children(self.render_proposal_card(cx))
3692 .child(self.composer.clone())
3693 })
3694 .child(self.render_drop_overlay(cx));
3687 3695 root.child(
3688 v_flex()
3689 .relative()
3696 h_flex()
3690 3697 .flex_1()
3691 3698 .min_h_0()
3692 .children(new_post)
3693 .child(
3694 div()
3695 .relative()
3696 .flex_1()
3697 .min_h_0()
3698 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3699 .on_scroll_wheel(
3700 cx.listener(|this, _, _, cx| this.close_reaction_details(cx)),
3701 )
3702 .child(body)
3703 .children(pin_banner.map(pin_banner_overlay)),
3704 )
3705 .children(self.render_draft_error(cx))
3706 .when(!in_feed && !recap_active, |column| {
3707 column
3708 .child(self.render_typing_line(cx))
3709 .children(self.render_proposal_card(cx))
3710 .child(self.composer.clone())
3711 })
3712 .child(self.render_drop_overlay(cx)),
3699 .w_full()
3700 .items_stretch()
3701 .child(content)
3702 .children(channel_details),
3713 3703 )
3714 3704 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3715 3705 if this.reaction_details.is_some() {
@@ -21,8 +21,12 @@ use teams_core::{
21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,
21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,
22};
22};
23
23
24mod channel_details;
25pub use channel_details::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
26mod deletes;
24mod detached;
27mod detached;
25mod feed;
28mod feed;
29mod jump;
26mod pins;
30mod pins;
27mod proposal;
31mod proposal;
28mod recap;
32mod recap;
@@ -91,6 +95,7 @@ use shared::SharedState;
91
95
92pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";
96pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";
93pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
97pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
98pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";
94const HEADER_HEIGHT: f32 = 60.;
99const HEADER_HEIGHT: f32 = 60.;
95const HEADER_PADDING: f32 = 20.;
100const HEADER_PADDING: f32 = 20.;
96const HEADER_GAP: f32 = 12.;
101const HEADER_GAP: f32 = 12.;
@@ -212,6 +217,8 @@ pub struct ConversationView {
212 reaction_details: Option<ReactionDetails>,
217 reaction_details: Option<ReactionDetails>,
213 highlighted_message: Option<String>,
218 highlighted_message: Option<String>,
214 pin_index: usize,
219 pin_index: usize,
220 channel_details_open: bool,
221 pinned_posts_expanded: bool,
215 pin_previews: HashMap<String, pins::PinPreview>,
222 pin_previews: HashMap<String, pins::PinPreview>,
216 pin_fetches: HashSet<String>,
223 pin_fetches: HashSet<String>,
217 notice: Option<String>,
224 notice: Option<String>,
@@ -541,6 +548,8 @@ impl ConversationView {
541 reaction_details: None,
548 reaction_details: None,
542 highlighted_message: None,
549 highlighted_message: None,
543 pin_index: 0,
550 pin_index: 0,
551 channel_details_open: false,
552 pinned_posts_expanded: false,
544 pin_previews: HashMap::new(),
553 pin_previews: HashMap::new(),
545 pin_fetches: HashSet::new(),
554 pin_fetches: HashSet::new(),
546 notice: None,
555 notice: None,
@@ -883,9 +892,10 @@ impl ConversationView {
883 self.start_fetch(cx);
892 self.start_fetch(cx);
884 self.mark_read(ReadTrigger::Open, cx);
893 self.mark_read(ReadTrigger::Open, cx);
885 self.refresh_pin_previews(cx);
894 self.refresh_pin_previews(cx);
886 if let Some(chat_id) = self.chat_id() {
895 self.pinned_posts_expanded = false;
896 if let Some(conversation_id) = self.pin_conversation_id() {
887 self.app
897 self.app
888 .update(cx, |state, cx| state.refresh_pins(&chat_id, cx));
898 .update(cx, |state, cx| state.refresh_pins(&conversation_id, cx));
889 }
899 }
890 let target = self
900 let target = self
891 .current
901 .current
@@ -2808,31 +2818,6 @@ impl ConversationView {
2808 .detach();
2818 .detach();
2809 }
2819 }
2810
2820
2811 fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
2812 let Some(mut record) = self.own_record(message_id, cx) else {
2813 return;
2814 };
2815 let state = self.app.read(cx);
2816 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2817 if mode.demo {
2818 record.deleted = true;
2819 let _ = store.upsert_messages(std::slice::from_ref(&record));
2820 self.rebuild(false, cx);
2821 return;
2822 }
2823 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2824 self.show_notice("Read-only mode: message not deleted", cx);
2825 return;
2826 };
2827 let conversation_id = record.conversation_id.clone();
2828 let receiver = runtime::spawn(async move {
2829 engine
2830 .soft_delete_message(&conversation_id, &record.message_id)
2831 .await
2832 });
2833 self.report_failure(receiver, "Delete failed", cx);
2834 }
2835
2836 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
2821 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
2837 let Some(conversation_id) = self.conversation_id() else {
2822 let Some(conversation_id) = self.conversation_id() else {
2838 return;
2823 return;
@@ -2880,26 +2865,6 @@ impl ConversationView {
2880 });
2865 });
2881 }
2866 }
2882
2867
2883 fn report_failure(
2884 &mut self,
2885 receiver: tokio::sync::oneshot::Receiver<teams_core::Result<()>>,
2886 label: &'static str,
2887 cx: &mut Context<Self>,
2888 ) {
2889 cx.spawn(async move |this, cx| {
2890 let error = match receiver.await {
2891 Ok(Ok(())) => return,
2892 Ok(Err(error)) => short_error(&error),
2893 Err(_) => "cancelled".to_owned(),
2894 };
2895 this.update(cx, |this, cx| {
2896 this.show_notice(&format!("{label}: {error}"), cx)
2897 })
2898 .ok();
2899 })
2900 .detach();
2901 }
2902
2903 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
2868 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
2904 let (Some(conversation_id), Some(runs)) =
2869 let (Some(conversation_id), Some(runs)) =
2905 (self.conversation_id(), crate::agents::runs_handle(cx))
2870 (self.conversation_id(), crate::agents::runs_handle(cx))
@@ -3058,11 +3023,18 @@ impl ConversationView {
3058 let saved = self
3023 let saved = self
3059 .conversation_id()
3024 .conversation_id()
3060 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3025 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3061 let pinned = chat_id
3062 .as_deref()
3063 .is_some_and(|chat_id| state.is_pinned(chat_id, key));
3064 let quick = state.quick_reactions();
3026 let quick = state.quick_reactions();
3065 let in_chat = chat_id.is_some();
3027 let in_chat = chat_id.is_some();
3028 let pin_conversation_id = self.pin_conversation_id();
3029 let pinned = pin_conversation_id
3030 .as_deref()
3031 .is_some_and(|conversation_id| state.is_pinned(conversation_id, key));
3032 let pinnable = in_chat
3033 || pin_conversation_id.as_deref().is_some_and(|channel_id| {
3034 state
3035 .message_record(channel_id, key)
3036 .is_some_and(|record| record.reply_to_id.is_none())
3037 });
3066 let (delegate, manage_agents) = self.delegate_entries(key, cx);
3038 let (delegate, manage_agents) = self.delegate_entries(key, cx);
3067 MessageMenu {
3039 MessageMenu {
3068 key: key.to_owned(),
3040 key: key.to_owned(),
@@ -3077,7 +3049,7 @@ impl ConversationView {
3077 translate_label,
3049 translate_label,
3078 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3050 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3079 saved,
3051 saved,
3080 toggle_pinned: in_chat.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
3052 toggle_pinned: pinnable.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
3081 pinned,
3053 pinned,
3082 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3054 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3083 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
3055 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
@@ -3457,6 +3429,7 @@ impl ConversationView {
3457 .children(inline_tabs)
3429 .children(inline_tabs)
3458 .children(stack)
3430 .children(stack)
3459 .children(call_controls)
3431 .children(call_controls)
3432 .children(self.channel_details_button(cx))
3460 }
3433 }
3461}
3434}
3462
3435
@@ -3603,6 +3576,15 @@ impl Render for ConversationView {
3603 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3576 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3604 .jump_button(!in_feed)
3577 .jump_button(!in_feed)
3605 .force_jump_button(detached)
3578 .force_jump_button(detached)
3579 .with_jump_button_label(jump::JUMP_TO_NEWEST_LABEL)
3580 .with_jump_button_renderer(|button| {
3581 button
3582 .label(jump::JUMP_TO_NEWEST_LABEL)
3583 .tooltip(jump::jump_to_newest_tooltip())
3584 .border_0()
3585 .bg(theme::accent())
3586 .text_color(theme::on_accent())
3587 })
3606 .when(detached, |scroller| {
3588 .when(detached, |scroller| {
3607 let view = cx.weak_entity();
3589 let view = cx.weak_entity();
3608 scroller.on_jump(move |_, cx| {
3590 scroller.on_jump(move |_, cx| {
@@ -3684,32 +3666,40 @@ impl Render for ConversationView {
3684 } else {
3666 } else {
3685 scroller.into_any_element()
3667 scroller.into_any_element()
3686 };
3668 };
3669 let channel_details = self.render_channel_details(cx);
3670 let content = v_flex()
3671 .relative()
3672 .flex_1()
3673 .min_w_0()
3674 .min_h_0()
3675 .children(new_post)
3676 .child(
3677 div()
3678 .debug_selector(|| TIMELINE_TAG.into())
3679 .relative()
3680 .flex_1()
3681 .min_h_0()
3682 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3683 .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx)))
3684 .child(body)
3685 .children(pin_banner.map(pin_banner_overlay)),
3686 )
3687 .children(self.render_draft_error(cx))
3688 .when(!in_feed && !recap_active, |column| {
3689 column
3690 .child(self.render_typing_line(cx))
3691 .children(self.render_proposal_card(cx))
3692 .child(self.composer.clone())
3693 })
3694 .child(self.render_drop_overlay(cx));
3687 root.child(
3695 root.child(
3688 v_flex()
3696 h_flex()
3689 .relative()
3690 .flex_1()
3697 .flex_1()
3691 .min_h_0()
3698 .min_h_0()
3692 .children(new_post)
3699 .w_full()
3693 .child(
3700 .items_stretch()
3694 div()
3701 .child(content)
3695 .relative()
3702 .children(channel_details),
3696 .flex_1()
3697 .min_h_0()
3698 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3699 .on_scroll_wheel(
3700 cx.listener(|this, _, _, cx| this.close_reaction_details(cx)),
3701 )
3702 .child(body)
3703 .children(pin_banner.map(pin_banner_overlay)),
3704 )
3705 .children(self.render_draft_error(cx))
3706 .when(!in_feed && !recap_active, |column| {
3707 column
3708 .child(self.render_typing_line(cx))
3709 .children(self.render_proposal_card(cx))
3710 .child(self.composer.clone())
3711 })
3712 .child(self.render_drop_overlay(cx)),
3713 )
3703 )
3714 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3704 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3715 if this.reaction_details.is_some() {
3705 if this.reaction_details.is_some() {
crates/app/src/views/conversation/channel_details.rs added +350 −0
@@ -0,0 +1,350 @@
1 use chrono::{Local, Offset, Utc};
2 use gpui_kit::assets::IconName;
3 use gpui_kit::component::button::{Button, ButtonVariants as _};
4 use gpui_kit::component::{h_flex, v_flex};
5 use gpui_kit::prelude::FluentBuilder as _;
6 use gpui_kit::*;
7 use store::MessageRecord;
8
9 use super::ConversationView;
10 use crate::app_state::Selection;
11 use crate::format;
12 use crate::rows::reply_excerpt;
13 use crate::theme;
14 use crate::views::avatar::person_avatar;
15
16 pub const CHANNEL_DETAILS_TAG: &str = "shell/islands/main/channel-details";
17 pub const CHANNEL_DETAILS_BUTTON: &str = "shell/islands/main/channel-details-button";
18 const OPEN_LABEL: &str = "Open channel details";
19 const CLOSE_LABEL: &str = "Close channel details";
20 const PINNED_TITLE: &str = "Pinned";
21 const SEE_ALL_LABEL: &str = "See all";
22 const SEE_ALL_ARIA: &str = "See all pinned posts";
23 const BACK_LABEL: &str = "Back";
24 const FALLBACK_PREVIEW: &str = "Pinned post";
25 const PANE_WIDTH: f32 = 320.;
26 const PANE_PADDING: f32 = 16.;
27 const HEADER_HEIGHT: f32 = 48.;
28 const BUTTON_SIZE: f32 = 32.;
29 const ITEM_AVATAR: f32 = 24.;
30 const COLLAPSED_PIN_COUNT: usize = 3;
31
32 pub(super) struct PinnedPostItem {
33 pub message_id: String,
34 pub author_id: Option<String>,
35 pub title: String,
36 pub byline: String,
37 }
38
39 /// Teams' info pane item: post subject or text, then "author, date".
40 pub(super) fn pinned_post_item(message_id: &str, record: Option<&MessageRecord>) -> PinnedPostItem {
41 let Some(record) = record else {
42 return PinnedPostItem {
43 message_id: message_id.to_owned(),
44 author_id: None,
45 title: FALLBACK_PREVIEW.to_owned(),
46 byline: String::new(),
47 };
48 };
49 let offset = Local::now().offset().fix();
50 let today = Utc::now().with_timezone(&offset).date_naive();
51 let date = format::list_time_label(record.created_at, today, offset);
52 let author = record.sender_name.clone().unwrap_or_default();
53 let byline = match (author.is_empty(), date.is_empty()) {
54 (false, false) => format!("{author}, {date}"),
55 (false, true) => author,
56 _ => date,
57 };
58 PinnedPostItem {
59 message_id: message_id.to_owned(),
60 author_id: record.sender_id.clone(),
61 title: record
62 .subject
63 .clone()
64 .filter(|subject| !subject.trim().is_empty())
65 .unwrap_or_else(|| reply_excerpt(record)),
66 byline,
67 }
68 }
69
70 pub(super) fn shown_pin_count(total: usize, expanded: bool) -> usize {
71 if expanded {
72 total
73 } else {
74 total.min(COLLAPSED_PIN_COUNT)
75 }
76 }
77
78 impl ConversationView {
79 fn details_channel_id(&self) -> Option<String> {
80 match &self.current.as_ref()?.selection {
81 Selection::Channel(channel_id) => Some(channel_id.clone()),
82 Selection::Chat(_) => None,
83 }
84 }
85
86 pub(super) fn channel_details_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
87 self.details_channel_id()?;
88 let open = self.channel_details_open;
89 Some(
90 Button::new("channel-details-toggle")
91 .debug_selector(|| CHANNEL_DETAILS_BUTTON.into())
92 .icon(if open {
93 IconName::PanelRightClose
94 } else {
95 IconName::PanelRight
96 })
97 .ghost()
98 .size(px(BUTTON_SIZE))
99 .rounded(px(8.))
100 .tooltip(if open { CLOSE_LABEL } else { OPEN_LABEL })
101 .on_click(cx.listener(|this, _, _, cx| {
102 this.channel_details_open = !this.channel_details_open;
103 this.pinned_posts_expanded = false;
104 cx.notify();
105 }))
106 .into_any_element(),
107 )
108 }
109
110 pub(super) fn render_channel_details(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
111 if !self.channel_details_open {
112 return None;
113 }
114 let channel_id = self.details_channel_id()?;
115 let state = self.app.read(cx);
116 let ids: Vec<String> = state
117 .pinned_messages(&channel_id)
118 .iter()
119 .map(|pin| pin.message_id.clone())
120 .collect();
121 let records = state
122 .store
123 .messages_by_id(&channel_id, &ids)
124 .unwrap_or_default();
125 let items: Vec<PinnedPostItem> = ids
126 .iter()
127 .map(|id| pinned_post_item(id, records.get(id)))
128 .collect();
129 let expanded = self.pinned_posts_expanded;
130 let shown = shown_pin_count(items.len(), expanded);
131 let has_more = items.len() > shown;
132 let title = self
133 .current
134 .as_ref()
135 .map(|current| current.title.clone())
136 .unwrap_or_default();
137 let directory = &state.directory;
138 let mut body = v_flex()
139 .w_full()
140 .px(px(PANE_PADDING))
141 .pb(px(PANE_PADDING))
142 .gap(px(4.));
143 if !items.is_empty() {
144 if !expanded {
145 body = body.child(
146 div()
147 .py(px(8.))
148 .text_size(px(14.))
149 .font_weight(FontWeight::SEMIBOLD)
150 .text_color(theme::text())
151 .child(PINNED_TITLE),
152 );
153 }
154 for item in items.iter().take(shown) {
155 body = body.child(self.pinned_post_row(&channel_id, item, directory, cx));
156 }
157 if has_more {
158 body = body.child(
159 Button::new("channel-details-see-all-pins")
160 .ghost()
161 .label(SEE_ALL_LABEL)
162 .tooltip(SEE_ALL_ARIA)
163 .on_click(cx.listener(|this, _, _, cx| {
164 this.pinned_posts_expanded = true;
165 cx.notify();
166 })),
167 );
168 }
169 }
170 let header = if expanded {
171 h_flex()
172 .gap(px(8.))
173 .child(
174 Button::new("channel-details-back")
175 .icon(IconName::ChevronLeft)
176 .ghost()
177 .size(px(BUTTON_SIZE))
178 .rounded(px(8.))
179 .tooltip(BACK_LABEL)
180 .on_click(cx.listener(|this, _, _, cx| {
181 this.pinned_posts_expanded = false;
182 cx.notify();
183 })),
184 )
185 .child(header_title(PINNED_TITLE.to_owned()))
186 } else {
187 h_flex().child(header_title(title))
188 };
189 Some(
190 h_flex()
191 .h_full()
192 .flex_none()
193 .child(div().w(px(1.)).h_full().flex_none().bg(theme::border()))
194 .child(
195 v_flex()
196 .debug_selector(|| CHANNEL_DETAILS_TAG.into())
197 .w(px(PANE_WIDTH))
198 .h_full()
199 .bg(theme::surface())
200 .child(
201 h_flex()
202 .h(px(HEADER_HEIGHT))
203 .flex_none()
204 .px(px(PANE_PADDING))
205 .items_center()
206 .justify_between()
207 .child(header.flex_1().min_w_0().items_center())
208 .child(
209 Button::new("channel-details-close")
210 .icon(IconName::X)
211 .ghost()
212 .size(px(BUTTON_SIZE))
213 .rounded(px(8.))
214 .tooltip(CLOSE_LABEL)
215 .on_click(cx.listener(|this, _, _, cx| {
216 this.channel_details_open = false;
217 this.pinned_posts_expanded = false;
218 cx.notify();
219 })),
220 ),
221 )
222 .child(
223 div()
224 .id("channel-details-body")
225 .flex_1()
226 .min_h_0()
227 .overflow_y_scroll()
228 .child(body),
229 ),
230 )
231 .into_any_element(),
232 )
233 }
234
235 fn pinned_post_row(
236 &self,
237 channel_id: &str,
238 item: &PinnedPostItem,
239 directory: &crate::data::Directory,
240 cx: &Context<Self>,
241 ) -> AnyElement {
242 let (channel_id, message_id) = (channel_id.to_owned(), item.message_id.clone());
243 let author_name = item.byline.split(',').next().unwrap_or_default().to_owned();
244 h_flex()
245 .id(SharedString::from(format!(
246 "pinned-post-{}",
247 item.message_id
248 )))
249 .w_full()
250 .p(px(8.))
251 .gap(px(10.))
252 .items_start()
253 .rounded(px(8.))
254 .cursor_pointer()
255 .hover(|row| row.bg(theme::row_hover()))
256 .child(person_avatar(
257 directory,
258 item.author_id.as_deref(),
259 &author_name,
260 ITEM_AVATAR,
261 ))
262 .child(
263 v_flex()
264 .flex_1()
265 .min_w_0()
266 .gap(px(2.))
267 .child(
268 div()
269 .truncate()
270 .text_size(px(13.))
271 .text_color(theme::text())
272 .child(item.title.clone()),
273 )
274 .when(!item.byline.is_empty(), |column| {
275 column.child(
276 div()
277 .truncate()
278 .text_size(px(12.))
279 .text_color(theme::text_muted())
280 .child(item.byline.clone()),
281 )
282 }),
283 )
284 .on_click(cx.listener(move |this, _, _, cx| {
285 this.jump_to_message(&channel_id, &message_id, cx);
286 }))
287 .into_any_element()
288 }
289 }
290
291 fn header_title(text: String) -> Div {
292 div()
293 .flex_1()
294 .min_w_0()
295 .truncate()
296 .text_size(px(15.))
297 .font_weight(FontWeight::SEMIBOLD)
298 .text_color(theme::text())
299 .child(text)
300 }
301
302 #[cfg(test)]
303 mod tests {
304 use chrono::{TimeZone, Utc};
305 use store::MessageRecord;
306
307 use super::{FALLBACK_PREVIEW, pinned_post_item, shown_pin_count};
308
309 fn record(subject: Option<&str>) -> MessageRecord {
310 MessageRecord {
311 conversation_id: "19:channel".into(),
312 message_id: "1".into(),
313 sender_id: Some("user-ada".into()),
314 sender_name: Some("Ada Lovelace".into()),
315 created_at: Utc.with_ymd_and_hms(2024, 3, 4, 9, 30, 0).unwrap(),
316 body_html: "<p>Release notes are up</p>".into(),
317 subject: subject.map(str::to_owned),
318 attachments_json: "[]".into(),
319 reactions_json: "[]".into(),
320 mentions_json: "[]".into(),
321 links_json: "[]".into(),
322 ..MessageRecord::default()
323 }
324 }
325
326 #[test]
327 fn the_item_prefers_the_subject_and_names_author_and_date() {
328 let item = pinned_post_item("1", Some(&record(Some("Release 4.2"))));
329 assert_eq!(item.title, "Release 4.2");
330 assert!(item.byline.starts_with("Ada Lovelace, "), "{}", item.byline);
331 assert_eq!(item.author_id.as_deref(), Some("user-ada"));
332 let plain = pinned_post_item("1", Some(&record(None)));
333 assert_eq!(plain.title, "Release notes are up");
334 }
335
336 #[test]
337 fn an_uncached_post_keeps_its_place_with_a_fallback() {
338 let item = pinned_post_item("9", None);
339 assert_eq!(item.message_id, "9");
340 assert_eq!(item.title, FALLBACK_PREVIEW);
341 assert!(item.byline.is_empty());
342 }
343
344 #[test]
345 fn three_pins_show_until_see_all() {
346 assert_eq!(shown_pin_count(5, false), 3);
347 assert_eq!(shown_pin_count(2, false), 2);
348 assert_eq!(shown_pin_count(5, true), 5);
349 }
350 }
@@ -0,0 +1,350 @@
1use chrono::{Local, Offset, Utc};
2use gpui_kit::assets::IconName;
3use gpui_kit::component::button::{Button, ButtonVariants as _};
4use gpui_kit::component::{h_flex, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7use store::MessageRecord;
8
9use super::ConversationView;
10use crate::app_state::Selection;
11use crate::format;
12use crate::rows::reply_excerpt;
13use crate::theme;
14use crate::views::avatar::person_avatar;
15
16pub const CHANNEL_DETAILS_TAG: &str = "shell/islands/main/channel-details";
17pub const CHANNEL_DETAILS_BUTTON: &str = "shell/islands/main/channel-details-button";
18const OPEN_LABEL: &str = "Open channel details";
19const CLOSE_LABEL: &str = "Close channel details";
20const PINNED_TITLE: &str = "Pinned";
21const SEE_ALL_LABEL: &str = "See all";
22const SEE_ALL_ARIA: &str = "See all pinned posts";
23const BACK_LABEL: &str = "Back";
24const FALLBACK_PREVIEW: &str = "Pinned post";
25const PANE_WIDTH: f32 = 320.;
26const PANE_PADDING: f32 = 16.;
27const HEADER_HEIGHT: f32 = 48.;
28const BUTTON_SIZE: f32 = 32.;
29const ITEM_AVATAR: f32 = 24.;
30const COLLAPSED_PIN_COUNT: usize = 3;
31
32pub(super) struct PinnedPostItem {
33 pub message_id: String,
34 pub author_id: Option<String>,
35 pub title: String,
36 pub byline: String,
37}
38
39/// Teams' info pane item: post subject or text, then "author, date".
40pub(super) fn pinned_post_item(message_id: &str, record: Option<&MessageRecord>) -> PinnedPostItem {
41 let Some(record) = record else {
42 return PinnedPostItem {
43 message_id: message_id.to_owned(),
44 author_id: None,
45 title: FALLBACK_PREVIEW.to_owned(),
46 byline: String::new(),
47 };
48 };
49 let offset = Local::now().offset().fix();
50 let today = Utc::now().with_timezone(&offset).date_naive();
51 let date = format::list_time_label(record.created_at, today, offset);
52 let author = record.sender_name.clone().unwrap_or_default();
53 let byline = match (author.is_empty(), date.is_empty()) {
54 (false, false) => format!("{author}, {date}"),
55 (false, true) => author,
56 _ => date,
57 };
58 PinnedPostItem {
59 message_id: message_id.to_owned(),
60 author_id: record.sender_id.clone(),
61 title: record
62 .subject
63 .clone()
64 .filter(|subject| !subject.trim().is_empty())
65 .unwrap_or_else(|| reply_excerpt(record)),
66 byline,
67 }
68}
69
70pub(super) fn shown_pin_count(total: usize, expanded: bool) -> usize {
71 if expanded {
72 total
73 } else {
74 total.min(COLLAPSED_PIN_COUNT)
75 }
76}
77
78impl ConversationView {
79 fn details_channel_id(&self) -> Option<String> {
80 match &self.current.as_ref()?.selection {
81 Selection::Channel(channel_id) => Some(channel_id.clone()),
82 Selection::Chat(_) => None,
83 }
84 }
85
86 pub(super) fn channel_details_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
87 self.details_channel_id()?;
88 let open = self.channel_details_open;
89 Some(
90 Button::new("channel-details-toggle")
91 .debug_selector(|| CHANNEL_DETAILS_BUTTON.into())
92 .icon(if open {
93 IconName::PanelRightClose
94 } else {
95 IconName::PanelRight
96 })
97 .ghost()
98 .size(px(BUTTON_SIZE))
99 .rounded(px(8.))
100 .tooltip(if open { CLOSE_LABEL } else { OPEN_LABEL })
101 .on_click(cx.listener(|this, _, _, cx| {
102 this.channel_details_open = !this.channel_details_open;
103 this.pinned_posts_expanded = false;
104 cx.notify();
105 }))
106 .into_any_element(),
107 )
108 }
109
110 pub(super) fn render_channel_details(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
111 if !self.channel_details_open {
112 return None;
113 }
114 let channel_id = self.details_channel_id()?;
115 let state = self.app.read(cx);
116 let ids: Vec<String> = state
117 .pinned_messages(&channel_id)
118 .iter()
119 .map(|pin| pin.message_id.clone())
120 .collect();
121 let records = state
122 .store
123 .messages_by_id(&channel_id, &ids)
124 .unwrap_or_default();
125 let items: Vec<PinnedPostItem> = ids
126 .iter()
127 .map(|id| pinned_post_item(id, records.get(id)))
128 .collect();
129 let expanded = self.pinned_posts_expanded;
130 let shown = shown_pin_count(items.len(), expanded);
131 let has_more = items.len() > shown;
132 let title = self
133 .current
134 .as_ref()
135 .map(|current| current.title.clone())
136 .unwrap_or_default();
137 let directory = &state.directory;
138 let mut body = v_flex()
139 .w_full()
140 .px(px(PANE_PADDING))
141 .pb(px(PANE_PADDING))
142 .gap(px(4.));
143 if !items.is_empty() {
144 if !expanded {
145 body = body.child(
146 div()
147 .py(px(8.))
148 .text_size(px(14.))
149 .font_weight(FontWeight::SEMIBOLD)
150 .text_color(theme::text())
151 .child(PINNED_TITLE),
152 );
153 }
154 for item in items.iter().take(shown) {
155 body = body.child(self.pinned_post_row(&channel_id, item, directory, cx));
156 }
157 if has_more {
158 body = body.child(
159 Button::new("channel-details-see-all-pins")
160 .ghost()
161 .label(SEE_ALL_LABEL)
162 .tooltip(SEE_ALL_ARIA)
163 .on_click(cx.listener(|this, _, _, cx| {
164 this.pinned_posts_expanded = true;
165 cx.notify();
166 })),
167 );
168 }
169 }
170 let header = if expanded {
171 h_flex()
172 .gap(px(8.))
173 .child(
174 Button::new("channel-details-back")
175 .icon(IconName::ChevronLeft)
176 .ghost()
177 .size(px(BUTTON_SIZE))
178 .rounded(px(8.))
179 .tooltip(BACK_LABEL)
180 .on_click(cx.listener(|this, _, _, cx| {
181 this.pinned_posts_expanded = false;
182 cx.notify();
183 })),
184 )
185 .child(header_title(PINNED_TITLE.to_owned()))
186 } else {
187 h_flex().child(header_title(title))
188 };
189 Some(
190 h_flex()
191 .h_full()
192 .flex_none()
193 .child(div().w(px(1.)).h_full().flex_none().bg(theme::border()))
194 .child(
195 v_flex()
196 .debug_selector(|| CHANNEL_DETAILS_TAG.into())
197 .w(px(PANE_WIDTH))
198 .h_full()
199 .bg(theme::surface())
200 .child(
201 h_flex()
202 .h(px(HEADER_HEIGHT))
203 .flex_none()
204 .px(px(PANE_PADDING))
205 .items_center()
206 .justify_between()
207 .child(header.flex_1().min_w_0().items_center())
208 .child(
209 Button::new("channel-details-close")
210 .icon(IconName::X)
211 .ghost()
212 .size(px(BUTTON_SIZE))
213 .rounded(px(8.))
214 .tooltip(CLOSE_LABEL)
215 .on_click(cx.listener(|this, _, _, cx| {
216 this.channel_details_open = false;
217 this.pinned_posts_expanded = false;
218 cx.notify();
219 })),
220 ),
221 )
222 .child(
223 div()
224 .id("channel-details-body")
225 .flex_1()
226 .min_h_0()
227 .overflow_y_scroll()
228 .child(body),
229 ),
230 )
231 .into_any_element(),
232 )
233 }
234
235 fn pinned_post_row(
236 &self,
237 channel_id: &str,
238 item: &PinnedPostItem,
239 directory: &crate::data::Directory,
240 cx: &Context<Self>,
241 ) -> AnyElement {
242 let (channel_id, message_id) = (channel_id.to_owned(), item.message_id.clone());
243 let author_name = item.byline.split(',').next().unwrap_or_default().to_owned();
244 h_flex()
245 .id(SharedString::from(format!(
246 "pinned-post-{}",
247 item.message_id
248 )))
249 .w_full()
250 .p(px(8.))
251 .gap(px(10.))
252 .items_start()
253 .rounded(px(8.))
254 .cursor_pointer()
255 .hover(|row| row.bg(theme::row_hover()))
256 .child(person_avatar(
257 directory,
258 item.author_id.as_deref(),
259 &author_name,
260 ITEM_AVATAR,
261 ))
262 .child(
263 v_flex()
264 .flex_1()
265 .min_w_0()
266 .gap(px(2.))
267 .child(
268 div()
269 .truncate()
270 .text_size(px(13.))
271 .text_color(theme::text())
272 .child(item.title.clone()),
273 )
274 .when(!item.byline.is_empty(), |column| {
275 column.child(
276 div()
277 .truncate()
278 .text_size(px(12.))
279 .text_color(theme::text_muted())
280 .child(item.byline.clone()),
281 )
282 }),
283 )
284 .on_click(cx.listener(move |this, _, _, cx| {
285 this.jump_to_message(&channel_id, &message_id, cx);
286 }))
287 .into_any_element()
288 }
289}
290
291fn header_title(text: String) -> Div {
292 div()
293 .flex_1()
294 .min_w_0()
295 .truncate()
296 .text_size(px(15.))
297 .font_weight(FontWeight::SEMIBOLD)
298 .text_color(theme::text())
299 .child(text)
300}
301
302#[cfg(test)]
303mod tests {
304 use chrono::{TimeZone, Utc};
305 use store::MessageRecord;
306
307 use super::{FALLBACK_PREVIEW, pinned_post_item, shown_pin_count};
308
309 fn record(subject: Option<&str>) -> MessageRecord {
310 MessageRecord {
311 conversation_id: "19:channel".into(),
312 message_id: "1".into(),
313 sender_id: Some("user-ada".into()),
314 sender_name: Some("Ada Lovelace".into()),
315 created_at: Utc.with_ymd_and_hms(2024, 3, 4, 9, 30, 0).unwrap(),
316 body_html: "<p>Release notes are up</p>".into(),
317 subject: subject.map(str::to_owned),
318 attachments_json: "[]".into(),
319 reactions_json: "[]".into(),
320 mentions_json: "[]".into(),
321 links_json: "[]".into(),
322 ..MessageRecord::default()
323 }
324 }
325
326 #[test]
327 fn the_item_prefers_the_subject_and_names_author_and_date() {
328 let item = pinned_post_item("1", Some(&record(Some("Release 4.2"))));
329 assert_eq!(item.title, "Release 4.2");
330 assert!(item.byline.starts_with("Ada Lovelace, "), "{}", item.byline);
331 assert_eq!(item.author_id.as_deref(), Some("user-ada"));
332 let plain = pinned_post_item("1", Some(&record(None)));
333 assert_eq!(plain.title, "Release notes are up");
334 }
335
336 #[test]
337 fn an_uncached_post_keeps_its_place_with_a_fallback() {
338 let item = pinned_post_item("9", None);
339 assert_eq!(item.message_id, "9");
340 assert_eq!(item.title, FALLBACK_PREVIEW);
341 assert!(item.byline.is_empty());
342 }
343
344 #[test]
345 fn three_pins_show_until_see_all() {
346 assert_eq!(shown_pin_count(5, false), 3);
347 assert_eq!(shown_pin_count(2, false), 2);
348 assert_eq!(shown_pin_count(5, true), 5);
349 }
350}
crates/app/src/views/conversation/deletes.rs added +124 −0
@@ -0,0 +1,124 @@
1 use gpui_kit::*;
2 use store::MessageRecord;
3
4 use super::ConversationView;
5 use crate::notice::short_error;
6 use crate::restorable_deletes::RESTORE_FAILED_NOTICE;
7 use crate::runtime;
8
9 impl ConversationView {
10 pub(super) fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
11 let Some(record) = self.own_record(message_id, cx) else {
12 return;
13 };
14 let state = self.app.read(cx);
15 let (mode, engine) = (state.mode, state.engine.clone());
16 if mode.demo {
17 self.remember_delete(&record, cx);
18 self.store_deleted(record, true, cx);
19 return;
20 }
21 let Some(engine) = engine.filter(|_| !mode.read_only) else {
22 self.show_notice("Read-only mode: message not deleted", cx);
23 return;
24 };
25 self.remember_delete(&record, cx);
26 let (conversation_id, message_id) = (record.conversation_id, record.message_id);
27 let (failed_conversation, failed_message) = (conversation_id.clone(), message_id.clone());
28 let receiver = runtime::spawn(async move {
29 engine
30 .soft_delete_message(&conversation_id, &message_id)
31 .await
32 });
33 cx.spawn(async move |this, cx| {
34 let error = match receiver.await {
35 Ok(Ok(())) => return,
36 Ok(Err(error)) => short_error(&error),
37 Err(_) => "cancelled".to_owned(),
38 };
39 this.update(cx, |this, cx| {
40 this.app.update(cx, |state, _| {
41 state
42 .restorable_deletes
43 .forget(&failed_conversation, &failed_message)
44 });
45 this.show_notice(&format!("Delete failed: {error}"), cx);
46 })
47 .ok();
48 })
49 .detach();
50 }
51
52 pub(super) fn undo_delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
53 let Some(record) = self.deleted_own_record(message_id, cx) else {
54 return;
55 };
56 let state = self.app.read(cx);
57 let (mode, engine) = (state.mode, state.engine.clone());
58 if mode.read_only && !mode.demo {
59 return;
60 }
61 let forgotten = self.app.update(cx, |state, _| {
62 state
63 .restorable_deletes
64 .forget(&record.conversation_id, &record.message_id)
65 });
66 if !forgotten {
67 return;
68 }
69 let engine = engine.filter(|_| !mode.demo);
70 self.store_deleted(record.clone(), false, cx);
71 let Some(engine) = engine else {
72 return;
73 };
74 let (conversation_id, message_id) =
75 (record.conversation_id.clone(), record.message_id.clone());
76 let receiver = runtime::spawn(async move {
77 engine
78 .undo_soft_delete_message(&conversation_id, &message_id)
79 .await
80 });
81 cx.spawn(async move |this, cx| {
82 if matches!(receiver.await, Ok(Ok(()))) {
83 return;
84 }
85 this.update(cx, |this, cx| {
86 this.remember_delete(&record, cx);
87 this.store_deleted(record, true, cx);
88 this.show_notice(RESTORE_FAILED_NOTICE, cx);
89 })
90 .ok();
91 })
92 .detach();
93 }
94
95 fn remember_delete(&mut self, record: &MessageRecord, cx: &mut Context<Self>) {
96 self.app.update(cx, |state, _| {
97 state
98 .restorable_deletes
99 .remember(&record.conversation_id, &record.message_id)
100 });
101 }
102
103 fn store_deleted(&mut self, mut record: MessageRecord, deleted: bool, cx: &mut Context<Self>) {
104 record.deleted = deleted;
105 let _ = self
106 .app
107 .read(cx)
108 .store
109 .upsert_messages(std::slice::from_ref(&record));
110 self.rebuild(false, cx);
111 }
112
113 fn deleted_own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> {
114 let conversation_id = self.conversation_id()?;
115 let my_user_id = self.row_context(cx).my_user_id?;
116 self.app
117 .read(cx)
118 .store
119 .messages_by_id(&conversation_id, &[message_id.to_owned()])
120 .ok()?
121 .remove(message_id)
122 .filter(|record| record.deleted && record.sender_id.as_deref() == Some(&my_user_id))
123 }
124 }
@@ -0,0 +1,124 @@
1use gpui_kit::*;
2use store::MessageRecord;
3
4use super::ConversationView;
5use crate::notice::short_error;
6use crate::restorable_deletes::RESTORE_FAILED_NOTICE;
7use crate::runtime;
8
9impl ConversationView {
10 pub(super) fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
11 let Some(record) = self.own_record(message_id, cx) else {
12 return;
13 };
14 let state = self.app.read(cx);
15 let (mode, engine) = (state.mode, state.engine.clone());
16 if mode.demo {
17 self.remember_delete(&record, cx);
18 self.store_deleted(record, true, cx);
19 return;
20 }
21 let Some(engine) = engine.filter(|_| !mode.read_only) else {
22 self.show_notice("Read-only mode: message not deleted", cx);
23 return;
24 };
25 self.remember_delete(&record, cx);
26 let (conversation_id, message_id) = (record.conversation_id, record.message_id);
27 let (failed_conversation, failed_message) = (conversation_id.clone(), message_id.clone());
28 let receiver = runtime::spawn(async move {
29 engine
30 .soft_delete_message(&conversation_id, &message_id)
31 .await
32 });
33 cx.spawn(async move |this, cx| {
34 let error = match receiver.await {
35 Ok(Ok(())) => return,
36 Ok(Err(error)) => short_error(&error),
37 Err(_) => "cancelled".to_owned(),
38 };
39 this.update(cx, |this, cx| {
40 this.app.update(cx, |state, _| {
41 state
42 .restorable_deletes
43 .forget(&failed_conversation, &failed_message)
44 });
45 this.show_notice(&format!("Delete failed: {error}"), cx);
46 })
47 .ok();
48 })
49 .detach();
50 }
51
52 pub(super) fn undo_delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
53 let Some(record) = self.deleted_own_record(message_id, cx) else {
54 return;
55 };
56 let state = self.app.read(cx);
57 let (mode, engine) = (state.mode, state.engine.clone());
58 if mode.read_only && !mode.demo {
59 return;
60 }
61 let forgotten = self.app.update(cx, |state, _| {
62 state
63 .restorable_deletes
64 .forget(&record.conversation_id, &record.message_id)
65 });
66 if !forgotten {
67 return;
68 }
69 let engine = engine.filter(|_| !mode.demo);
70 self.store_deleted(record.clone(), false, cx);
71 let Some(engine) = engine else {
72 return;
73 };
74 let (conversation_id, message_id) =
75 (record.conversation_id.clone(), record.message_id.clone());
76 let receiver = runtime::spawn(async move {
77 engine
78 .undo_soft_delete_message(&conversation_id, &message_id)
79 .await
80 });
81 cx.spawn(async move |this, cx| {
82 if matches!(receiver.await, Ok(Ok(()))) {
83 return;
84 }
85 this.update(cx, |this, cx| {
86 this.remember_delete(&record, cx);
87 this.store_deleted(record, true, cx);
88 this.show_notice(RESTORE_FAILED_NOTICE, cx);
89 })
90 .ok();
91 })
92 .detach();
93 }
94
95 fn remember_delete(&mut self, record: &MessageRecord, cx: &mut Context<Self>) {
96 self.app.update(cx, |state, _| {
97 state
98 .restorable_deletes
99 .remember(&record.conversation_id, &record.message_id)
100 });
101 }
102
103 fn store_deleted(&mut self, mut record: MessageRecord, deleted: bool, cx: &mut Context<Self>) {
104 record.deleted = deleted;
105 let _ = self
106 .app
107 .read(cx)
108 .store
109 .upsert_messages(std::slice::from_ref(&record));
110 self.rebuild(false, cx);
111 }
112
113 fn deleted_own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> {
114 let conversation_id = self.conversation_id()?;
115 let my_user_id = self.row_context(cx).my_user_id?;
116 self.app
117 .read(cx)
118 .store
119 .messages_by_id(&conversation_id, &[message_id.to_owned()])
120 .ok()?
121 .remove(message_id)
122 .filter(|record| record.deleted && record.sender_id.as_deref() == Some(&my_user_id))
123 }
124}
crates/app/src/views/conversation/jump.rs added +46 −0
@@ -0,0 +1,46 @@
1 use gpui_kit::*;
2
3 use super::ConversationView;
4 use crate::read_state::{JumpTarget, jump_target};
5 use crate::rows::Row;
6 use crate::views::shortcuts::keys_for_label;
7
8 pub(super) const JUMP_TO_NEWEST_LABEL: &str = "Jump to newest";
9 const JUMP_SHORTCUT_LABEL: &str = "Jump to last read or newest message";
10
11 pub(super) fn jump_to_newest_tooltip() -> SharedString {
12 match keys_for_label(JUMP_SHORTCUT_LABEL) {
13 Some(keys) => format!("{JUMP_TO_NEWEST_LABEL} ({keys})").into(),
14 None => JUMP_TO_NEWEST_LABEL.into(),
15 }
16 }
17
18 impl ConversationView {
19 pub fn jump_to_last_read_or_newest(&mut self, cx: &mut Context<Self>) {
20 if self.current.is_none() || self.in_feed() {
21 return;
22 }
23 if self.is_detached() {
24 self.leave_detached(cx);
25 return;
26 }
27 let last_read_index = self
28 .rows
29 .borrow()
30 .iter()
31 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
32 let (top_item, scrolled_up) = {
33 let scroller = self.scroller.read(cx);
34 (scroller.top_item(), scroller.is_scrolled_up())
35 };
36 let Some(target) = jump_target(last_read_index, top_item, scrolled_up) else {
37 return;
38 };
39 self.scroller.update(cx, |scroller, cx| match target {
40 JumpTarget::Newest => scroller.scroll_to_end(cx),
41 JumpTarget::LastRead(index) => {
42 scroller.scroll_to_item(index, cx);
43 }
44 });
45 }
46 }
@@ -0,0 +1,46 @@
1use gpui_kit::*;
2
3use super::ConversationView;
4use crate::read_state::{JumpTarget, jump_target};
5use crate::rows::Row;
6use crate::views::shortcuts::keys_for_label;
7
8pub(super) const JUMP_TO_NEWEST_LABEL: &str = "Jump to newest";
9const JUMP_SHORTCUT_LABEL: &str = "Jump to last read or newest message";
10
11pub(super) fn jump_to_newest_tooltip() -> SharedString {
12 match keys_for_label(JUMP_SHORTCUT_LABEL) {
13 Some(keys) => format!("{JUMP_TO_NEWEST_LABEL} ({keys})").into(),
14 None => JUMP_TO_NEWEST_LABEL.into(),
15 }
16}
17
18impl ConversationView {
19 pub fn jump_to_last_read_or_newest(&mut self, cx: &mut Context<Self>) {
20 if self.current.is_none() || self.in_feed() {
21 return;
22 }
23 if self.is_detached() {
24 self.leave_detached(cx);
25 return;
26 }
27 let last_read_index = self
28 .rows
29 .borrow()
30 .iter()
31 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
32 let (top_item, scrolled_up) = {
33 let scroller = self.scroller.read(cx);
34 (scroller.top_item(), scroller.is_scrolled_up())
35 };
36 let Some(target) = jump_target(last_read_index, top_item, scrolled_up) else {
37 return;
38 };
39 self.scroller.update(cx, |scroller, cx| match target {
40 JumpTarget::Newest => scroller.scroll_to_end(cx),
41 JumpTarget::LastRead(index) => {
42 scroller.scroll_to_item(index, cx);
43 }
44 });
45 }
46}
crates/app/src/views/conversation/pins.rs +44 −28
@@ -33,36 +33,42 @@ impl ConversationView {
33 33 }
34 34 }
35 35
36 pub(super) fn pin_conversation_id(&self) -> Option<String> {
37 self.current
38 .as_ref()
39 .map(|current| current.selection.conversation_id().to_owned())
40 }
41
36 42 pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {
37 43 self.pin_previews.clear();
38 44 self.pin_fetches.clear();
39 45 self.pin_index = 0;
40 let Some(chat_id) = self.chat_id() else {
46 let Some(conversation_id) = self.pin_conversation_id() else {
41 47 return;
42 48 };
43 self.update_pin_previews(&chat_id, cx);
49 self.update_pin_previews(&conversation_id, cx);
44 50 cx.notify();
45 51 }
46 52
47 pub(super) fn on_pins_changed(&mut self, chat_id: &str, cx: &mut Context<Self>) {
48 if self.chat_id().as_deref() != Some(chat_id) {
53 pub(super) fn on_pins_changed(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
54 if self.pin_conversation_id().as_deref() != Some(conversation_id) {
49 55 return;
50 56 }
51 57 self.pin_index = 0;
52 self.update_pin_previews(chat_id, cx);
58 self.update_pin_previews(conversation_id, cx);
53 59 cx.notify();
54 60 }
55 61
56 fn update_pin_previews(&mut self, chat_id: &str, cx: &mut Context<Self>) {
62 fn update_pin_previews(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
57 63 let state = self.app.read(cx);
58 64 let ids: Vec<String> = state
59 .pinned_messages(chat_id)
65 .pinned_messages(conversation_id)
60 66 .iter()
61 67 .map(|pin| pin.message_id.clone())
62 68 .collect();
63 69 let records = state
64 70 .store
65 .messages_by_id(chat_id, &ids)
71 .messages_by_id(conversation_id, &ids)
66 72 .unwrap_or_default();
67 73 let mut previews: HashMap<String, PinPreview> = records
68 74 .into_iter()
@@ -82,24 +88,29 @@ impl ConversationView {
82 88 }
83 89 for id in ids {
84 90 if !self.pin_previews.contains_key(&id) {
85 self.fetch_pin_preview(chat_id, id, cx);
91 self.fetch_pin_preview(conversation_id, id, cx);
86 92 }
87 93 }
88 94 }
89 95
90 fn fetch_pin_preview(&mut self, chat_id: &str, message_id: String, cx: &mut Context<Self>) {
96 fn fetch_pin_preview(
97 &mut self,
98 conversation_id: &str,
99 message_id: String,
100 cx: &mut Context<Self>,
101 ) {
91 102 let Some(engine) = self.app.read(cx).engine.clone() else {
92 103 return;
93 104 };
94 if !self.pin_fetches.insert(message_id.clone()) {
105 if self.chat_id().is_none() || !self.pin_fetches.insert(message_id.clone()) {
95 106 return;
96 107 }
97 let chat_id = chat_id.to_owned();
98 let task_chat_id = chat_id.clone();
108 let conversation_id = conversation_id.to_owned();
109 let task_conversation_id = conversation_id.clone();
99 110 let task_message_id = message_id.clone();
100 111 let receiver = runtime::spawn(async move {
101 112 engine
102 .fetch_chat_message(&task_chat_id, &task_message_id)
113 .fetch_chat_message(&task_conversation_id, &task_message_id)
103 114 .await
104 115 });
105 116 cx.spawn(async move |this, cx| {
@@ -107,8 +118,9 @@ impl ConversationView {
107 118 return;
108 119 };
109 120 this.update(cx, |this, cx| {
110 if this.chat_id().as_deref() == Some(chat_id.as_str()) {
111 this.pin_previews.insert(message_id, PinPreview::of(&record));
121 if this.conversation_id().as_deref() == Some(conversation_id.as_str()) {
122 this.pin_previews
123 .insert(message_id, PinPreview::of(&record));
112 124 cx.notify();
113 125 }
114 126 })
@@ -128,8 +140,8 @@ impl ConversationView {
128 140 }
129 141
130 142 pub(super) fn render_pin_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
131 let chat_id = self.chat_id()?;
132 let pins = self.app.read(cx).pinned_messages(&chat_id);
143 let conversation_id = self.chat_id()?;
144 let pins = self.app.read(cx).pinned_messages(&conversation_id);
133 145 let pin = pins.get(self.pin_index)?;
134 146 let preview = self.pin_previews.get(&pin.message_id);
135 147 let data = PinBannerData {
@@ -149,36 +161,40 @@ impl ConversationView {
149 161 }
150 162
151 163 fn shown_pin_id(&self, cx: &App) -> Option<String> {
152 let chat_id = self.chat_id()?;
164 let conversation_id = self.pin_conversation_id()?;
153 165 self.app
154 166 .read(cx)
155 .pinned_messages(&chat_id)
167 .pinned_messages(&conversation_id)
156 168 .get(self.pin_index)
157 169 .map(|pin| pin.message_id.clone())
158 170 }
159 171
160 172 fn open_shown_pin(&mut self, cx: &mut Context<Self>) {
161 let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {
173 let (Some(conversation_id), Some(message_id)) =
174 (self.pin_conversation_id(), self.shown_pin_id(cx))
175 else {
162 176 return;
163 177 };
164 self.jump_to_message(&chat_id, &message_id, cx);
178 self.jump_to_message(&conversation_id, &message_id, cx);
165 179 }
166 180
167 181 fn step_pin(&mut self, delta: isize, cx: &mut Context<Self>) {
168 let Some(chat_id) = self.chat_id() else {
182 let Some(conversation_id) = self.pin_conversation_id() else {
169 183 return;
170 184 };
171 let total = self.app.read(cx).pinned_messages(&chat_id).len();
185 let total = self.app.read(cx).pinned_messages(&conversation_id).len();
172 186 self.pin_index = cycle_pin(self.pin_index, total, delta);
173 187 cx.notify();
174 188 }
175 189
176 190 fn unpin_shown_pin(&mut self, cx: &mut Context<Self>) {
177 let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {
191 let (Some(conversation_id), Some(message_id)) =
192 (self.pin_conversation_id(), self.shown_pin_id(cx))
193 else {
178 194 return;
179 195 };
180 196 self.app.update(cx, |state, cx| {
181 state.set_pinned(&chat_id, &message_id, false, cx)
197 state.set_pinned(&conversation_id, &message_id, false, cx)
182 198 });
183 199 }
184 200
@@ -207,9 +223,9 @@ impl ConversationView {
207 223 }
208 224
209 225 pub(super) fn toggle_pinned(&mut self, message_id: &str, cx: &mut Context<Self>) {
210 if let Some(chat_id) = self.chat_id() {
226 if let Some(conversation_id) = self.pin_conversation_id() {
211 227 self.app.update(cx, |state, cx| {
212 state.toggle_pinned(&chat_id, message_id, cx)
228 state.toggle_pinned(&conversation_id, message_id, cx)
213 229 });
214 230 }
215 231 }
@@ -33,36 +33,42 @@ impl ConversationView {
33 }
33 }
34 }
34 }
35
35
36 pub(super) fn pin_conversation_id(&self) -> Option<String> {
37 self.current
38 .as_ref()
39 .map(|current| current.selection.conversation_id().to_owned())
40 }
41
36 pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {
42 pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {
37 self.pin_previews.clear();
43 self.pin_previews.clear();
38 self.pin_fetches.clear();
44 self.pin_fetches.clear();
39 self.pin_index = 0;
45 self.pin_index = 0;
40 let Some(chat_id) = self.chat_id() else {
46 let Some(conversation_id) = self.pin_conversation_id() else {
41 return;
47 return;
42 };
48 };
43 self.update_pin_previews(&chat_id, cx);
49 self.update_pin_previews(&conversation_id, cx);
44 cx.notify();
50 cx.notify();
45 }
51 }
46
52
47 pub(super) fn on_pins_changed(&mut self, chat_id: &str, cx: &mut Context<Self>) {
53 pub(super) fn on_pins_changed(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
48 if self.chat_id().as_deref() != Some(chat_id) {
54 if self.pin_conversation_id().as_deref() != Some(conversation_id) {
49 return;
55 return;
50 }
56 }
51 self.pin_index = 0;
57 self.pin_index = 0;
52 self.update_pin_previews(chat_id, cx);
58 self.update_pin_previews(conversation_id, cx);
53 cx.notify();
59 cx.notify();
54 }
60 }
55
61
56 fn update_pin_previews(&mut self, chat_id: &str, cx: &mut Context<Self>) {
62 fn update_pin_previews(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
57 let state = self.app.read(cx);
63 let state = self.app.read(cx);
58 let ids: Vec<String> = state
64 let ids: Vec<String> = state
59 .pinned_messages(chat_id)
65 .pinned_messages(conversation_id)
60 .iter()
66 .iter()
61 .map(|pin| pin.message_id.clone())
67 .map(|pin| pin.message_id.clone())
62 .collect();
68 .collect();
63 let records = state
69 let records = state
64 .store
70 .store
65 .messages_by_id(chat_id, &ids)
71 .messages_by_id(conversation_id, &ids)
66 .unwrap_or_default();
72 .unwrap_or_default();
67 let mut previews: HashMap<String, PinPreview> = records
73 let mut previews: HashMap<String, PinPreview> = records
68 .into_iter()
74 .into_iter()
@@ -82,24 +88,29 @@ impl ConversationView {
82 }
88 }
83 for id in ids {
89 for id in ids {
84 if !self.pin_previews.contains_key(&id) {
90 if !self.pin_previews.contains_key(&id) {
85 self.fetch_pin_preview(chat_id, id, cx);
91 self.fetch_pin_preview(conversation_id, id, cx);
86 }
92 }
87 }
93 }
88 }
94 }
89
95
90 fn fetch_pin_preview(&mut self, chat_id: &str, message_id: String, cx: &mut Context<Self>) {
96 fn fetch_pin_preview(
97 &mut self,
98 conversation_id: &str,
99 message_id: String,
100 cx: &mut Context<Self>,
101 ) {
91 let Some(engine) = self.app.read(cx).engine.clone() else {
102 let Some(engine) = self.app.read(cx).engine.clone() else {
92 return;
103 return;
93 };
104 };
94 if !self.pin_fetches.insert(message_id.clone()) {
105 if self.chat_id().is_none() || !self.pin_fetches.insert(message_id.clone()) {
95 return;
106 return;
96 }
107 }
97 let chat_id = chat_id.to_owned();
108 let conversation_id = conversation_id.to_owned();
98 let task_chat_id = chat_id.clone();
109 let task_conversation_id = conversation_id.clone();
99 let task_message_id = message_id.clone();
110 let task_message_id = message_id.clone();
100 let receiver = runtime::spawn(async move {
111 let receiver = runtime::spawn(async move {
101 engine
112 engine
102 .fetch_chat_message(&task_chat_id, &task_message_id)
113 .fetch_chat_message(&task_conversation_id, &task_message_id)
103 .await
114 .await
104 });
115 });
105 cx.spawn(async move |this, cx| {
116 cx.spawn(async move |this, cx| {
@@ -107,8 +118,9 @@ impl ConversationView {
107 return;
118 return;
108 };
119 };
109 this.update(cx, |this, cx| {
120 this.update(cx, |this, cx| {
110 if this.chat_id().as_deref() == Some(chat_id.as_str()) {
121 if this.conversation_id().as_deref() == Some(conversation_id.as_str()) {
111 this.pin_previews.insert(message_id, PinPreview::of(&record));
122 this.pin_previews
123 .insert(message_id, PinPreview::of(&record));
112 cx.notify();
124 cx.notify();
113 }
125 }
114 })
126 })
@@ -128,8 +140,8 @@ impl ConversationView {
128 }
140 }
129
141
130 pub(super) fn render_pin_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
142 pub(super) fn render_pin_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
131 let chat_id = self.chat_id()?;
143 let conversation_id = self.chat_id()?;
132 let pins = self.app.read(cx).pinned_messages(&chat_id);
144 let pins = self.app.read(cx).pinned_messages(&conversation_id);
133 let pin = pins.get(self.pin_index)?;
145 let pin = pins.get(self.pin_index)?;
134 let preview = self.pin_previews.get(&pin.message_id);
146 let preview = self.pin_previews.get(&pin.message_id);
135 let data = PinBannerData {
147 let data = PinBannerData {
@@ -149,36 +161,40 @@ impl ConversationView {
149 }
161 }
150
162
151 fn shown_pin_id(&self, cx: &App) -> Option<String> {
163 fn shown_pin_id(&self, cx: &App) -> Option<String> {
152 let chat_id = self.chat_id()?;
164 let conversation_id = self.pin_conversation_id()?;
153 self.app
165 self.app
154 .read(cx)
166 .read(cx)
155 .pinned_messages(&chat_id)
167 .pinned_messages(&conversation_id)
156 .get(self.pin_index)
168 .get(self.pin_index)
157 .map(|pin| pin.message_id.clone())
169 .map(|pin| pin.message_id.clone())
158 }
170 }
159
171
160 fn open_shown_pin(&mut self, cx: &mut Context<Self>) {
172 fn open_shown_pin(&mut self, cx: &mut Context<Self>) {
161 let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {
173 let (Some(conversation_id), Some(message_id)) =
174 (self.pin_conversation_id(), self.shown_pin_id(cx))
175 else {
162 return;
176 return;
163 };
177 };
164 self.jump_to_message(&chat_id, &message_id, cx);
178 self.jump_to_message(&conversation_id, &message_id, cx);
165 }
179 }
166
180
167 fn step_pin(&mut self, delta: isize, cx: &mut Context<Self>) {
181 fn step_pin(&mut self, delta: isize, cx: &mut Context<Self>) {
168 let Some(chat_id) = self.chat_id() else {
182 let Some(conversation_id) = self.pin_conversation_id() else {
169 return;
183 return;
170 };
184 };
171 let total = self.app.read(cx).pinned_messages(&chat_id).len();
185 let total = self.app.read(cx).pinned_messages(&conversation_id).len();
172 self.pin_index = cycle_pin(self.pin_index, total, delta);
186 self.pin_index = cycle_pin(self.pin_index, total, delta);
173 cx.notify();
187 cx.notify();
174 }
188 }
175
189
176 fn unpin_shown_pin(&mut self, cx: &mut Context<Self>) {
190 fn unpin_shown_pin(&mut self, cx: &mut Context<Self>) {
177 let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {
191 let (Some(conversation_id), Some(message_id)) =
192 (self.pin_conversation_id(), self.shown_pin_id(cx))
193 else {
178 return;
194 return;
179 };
195 };
180 self.app.update(cx, |state, cx| {
196 self.app.update(cx, |state, cx| {
181 state.set_pinned(&chat_id, &message_id, false, cx)
197 state.set_pinned(&conversation_id, &message_id, false, cx)
182 });
198 });
183 }
199 }
184
200
@@ -207,9 +223,9 @@ impl ConversationView {
207 }
223 }
208
224
209 pub(super) fn toggle_pinned(&mut self, message_id: &str, cx: &mut Context<Self>) {
225 pub(super) fn toggle_pinned(&mut self, message_id: &str, cx: &mut Context<Self>) {
210 if let Some(chat_id) = self.chat_id() {
226 if let Some(conversation_id) = self.pin_conversation_id() {
211 self.app.update(cx, |state, cx| {
227 self.app.update(cx, |state, cx| {
212 state.toggle_pinned(&chat_id, message_id, cx)
228 state.toggle_pinned(&conversation_id, message_id, cx)
213 });
229 });
214 }
230 }
215 }
231 }
crates/app/src/views/conversation/render_env.rs +40 −7
@@ -15,14 +15,14 @@ use crate::agent_api::agent_label;
15 15 use crate::agents::AgentRun;
16 16 use crate::app_state::AppState;
17 17 use crate::rows::{Delivery, MessageRow, PostRow, RecordingCard};
18 use crate::views::call_notice::RecapActions;
19 18 use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
20 19 use crate::translation::TranslationLine;
21 20 use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
22 21 use crate::views::attachments::ImageActions;
23 22 use crate::views::call_card::CallActions;
23 use crate::views::call_notice::RecapActions;
24 24 use crate::views::composer::Composer;
25 use crate::views::message_row::{DeliveryActions, RowActions};
25 use crate::views::message_row::{DeliveryActions, RowActions, SharedRowAction};
26 26 use crate::views::post_card::{PostAction, PostActions};
27 27 use crate::views::reaction_proposal_pill::ReactionPill;
28 28 use crate::views::toolbar_placement::TimelineBounds;
@@ -103,12 +103,16 @@ impl RenderEnv {
103 103 emoji: proposal.emoji,
104 104 accept: Rc::new(move |cx| {
105 105 accept_view
106 .update(cx, |this, cx| this.accept_reaction(&accept_key, &accept_id, &emoji, cx))
106 .update(cx, |this, cx| {
107 this.accept_reaction(&accept_key, &accept_id, &emoji, cx)
108 })
107 109 .ok();
108 110 }),
109 111 discard: Rc::new(move |cx| {
110 112 discard_view
111 .update(cx, |this, cx| this.discard_reaction(&discard_key, &discard_id, cx))
113 .update(cx, |this, cx| {
114 this.discard_reaction(&discard_key, &discard_id, cx)
115 })
112 116 .ok();
113 117 }),
114 118 })
@@ -300,14 +304,41 @@ impl RenderEnv {
300 304 .app
301 305 .read(cx)
302 306 .is_saved(&message.conversation_id, &message.key),
307 pinned: self
308 .app
309 .read(cx)
310 .is_pinned(&message.conversation_id, &message.key),
303 311 translation,
304 312 timeline: self.timeline.clone(),
305 313 agent_run: actionable_run,
306 314 call: self.call_actions(message, cx),
307 315 reaction_proposal,
316 undo_delete: self.undo_delete_action(message, is_real, view, cx),
308 317 }
309 318 }
310 319
320 fn undo_delete_action(
321 &self,
322 message: &MessageRow,
323 is_real: bool,
324 view: &WeakEntity<ConversationView>,
325 cx: &App,
326 ) -> SharedRowAction {
327 let restorable = is_real
328 && self.app.read(cx).restorable_deletes.can_undo(
329 &message.conversation_id,
330 &message.key,
331 message.own,
332 message.deleted,
333 );
334 restorable.then(|| {
335 let (view, key) = (view.clone(), message.key.clone());
336 Rc::new(move |cx: &mut App| {
337 view.update(cx, |this, cx| this.undo_delete(&key, cx)).ok();
338 }) as Rc<dyn Fn(&mut App)>
339 })
340 }
341
311 342 fn call_actions(&self, message: &MessageRow, cx: &App) -> CallActions {
312 343 let Some(call) = &message.call else {
313 344 return CallActions::none();
@@ -342,9 +373,11 @@ impl RenderEnv {
342 373 })
343 374 };
344 375 let recording = call.recap.as_ref().map(|recap| &recap.recording);
345 let share = recording.and_then(|recording| recording.url.clone()).map(|url| {
346 boxed(move |cx| cx.write_to_clipboard(ClipboardItem::new_string(url.clone())))
347 });
376 let share = recording
377 .and_then(|recording| recording.url.clone())
378 .map(|url| {
379 boxed(move |cx| cx.write_to_clipboard(ClipboardItem::new_string(url.clone())))
380 });
348 381 CallActions {
349 382 call_back,
350 383 join,
@@ -15,14 +15,14 @@ use crate::agent_api::agent_label;
15use crate::agents::AgentRun;
15use crate::agents::AgentRun;
16use crate::app_state::AppState;
16use crate::app_state::AppState;
17use crate::rows::{Delivery, MessageRow, PostRow, RecordingCard};
17use crate::rows::{Delivery, MessageRow, PostRow, RecordingCard};
18use crate::views::call_notice::RecapActions;
19use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
18use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
20use crate::translation::TranslationLine;
19use crate::translation::TranslationLine;
21use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
20use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
22use crate::views::attachments::ImageActions;
21use crate::views::attachments::ImageActions;
23use crate::views::call_card::CallActions;
22use crate::views::call_card::CallActions;
23use crate::views::call_notice::RecapActions;
24use crate::views::composer::Composer;
24use crate::views::composer::Composer;
25use crate::views::message_row::{DeliveryActions, RowActions};
25use crate::views::message_row::{DeliveryActions, RowActions, SharedRowAction};
26use crate::views::post_card::{PostAction, PostActions};
26use crate::views::post_card::{PostAction, PostActions};
27use crate::views::reaction_proposal_pill::ReactionPill;
27use crate::views::reaction_proposal_pill::ReactionPill;
28use crate::views::toolbar_placement::TimelineBounds;
28use crate::views::toolbar_placement::TimelineBounds;
@@ -103,12 +103,16 @@ impl RenderEnv {
103 emoji: proposal.emoji,
103 emoji: proposal.emoji,
104 accept: Rc::new(move |cx| {
104 accept: Rc::new(move |cx| {
105 accept_view
105 accept_view
106 .update(cx, |this, cx| this.accept_reaction(&accept_key, &accept_id, &emoji, cx))
106 .update(cx, |this, cx| {
107 this.accept_reaction(&accept_key, &accept_id, &emoji, cx)
108 })
107 .ok();
109 .ok();
108 }),
110 }),
109 discard: Rc::new(move |cx| {
111 discard: Rc::new(move |cx| {
110 discard_view
112 discard_view
111 .update(cx, |this, cx| this.discard_reaction(&discard_key, &discard_id, cx))
113 .update(cx, |this, cx| {
114 this.discard_reaction(&discard_key, &discard_id, cx)
115 })
112 .ok();
116 .ok();
113 }),
117 }),
114 })
118 })
@@ -300,14 +304,41 @@ impl RenderEnv {
300 .app
304 .app
301 .read(cx)
305 .read(cx)
302 .is_saved(&message.conversation_id, &message.key),
306 .is_saved(&message.conversation_id, &message.key),
307 pinned: self
308 .app
309 .read(cx)
310 .is_pinned(&message.conversation_id, &message.key),
303 translation,
311 translation,
304 timeline: self.timeline.clone(),
312 timeline: self.timeline.clone(),
305 agent_run: actionable_run,
313 agent_run: actionable_run,
306 call: self.call_actions(message, cx),
314 call: self.call_actions(message, cx),
307 reaction_proposal,
315 reaction_proposal,
316 undo_delete: self.undo_delete_action(message, is_real, view, cx),
308 }
317 }
309 }
318 }
310
319
320 fn undo_delete_action(
321 &self,
322 message: &MessageRow,
323 is_real: bool,
324 view: &WeakEntity<ConversationView>,
325 cx: &App,
326 ) -> SharedRowAction {
327 let restorable = is_real
328 && self.app.read(cx).restorable_deletes.can_undo(
329 &message.conversation_id,
330 &message.key,
331 message.own,
332 message.deleted,
333 );
334 restorable.then(|| {
335 let (view, key) = (view.clone(), message.key.clone());
336 Rc::new(move |cx: &mut App| {
337 view.update(cx, |this, cx| this.undo_delete(&key, cx)).ok();
338 }) as Rc<dyn Fn(&mut App)>
339 })
340 }
341
311 fn call_actions(&self, message: &MessageRow, cx: &App) -> CallActions {
342 fn call_actions(&self, message: &MessageRow, cx: &App) -> CallActions {
312 let Some(call) = &message.call else {
343 let Some(call) = &message.call else {
313 return CallActions::none();
344 return CallActions::none();
@@ -342,9 +373,11 @@ impl RenderEnv {
342 })
373 })
343 };
374 };
344 let recording = call.recap.as_ref().map(|recap| &recap.recording);
375 let recording = call.recap.as_ref().map(|recap| &recap.recording);
345 let share = recording.and_then(|recording| recording.url.clone()).map(|url| {
376 let share = recording
346 boxed(move |cx| cx.write_to_clipboard(ClipboardItem::new_string(url.clone())))
377 .and_then(|recording| recording.url.clone())
347 });
378 .map(|url| {
379 boxed(move |cx| cx.write_to_clipboard(ClipboardItem::new_string(url.clone())))
380 });
348 CallActions {
381 CallActions {
349 call_back,
382 call_back,
350 join,
383 join,
crates/app/src/views/message_row.rs +43 −13
@@ -23,12 +23,14 @@ use crate::agents::{AgentRun, run_chip};
23 23 use crate::card_state::BotIdentity;
24 24 use crate::data::Directory;
25 25 use crate::render::Block;
26 use crate::restorable_deletes::{DELETED_TOMBSTONE, UNDO_DELETE_LABEL};
26 27 use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};
27 28 use crate::sidebar_model::DELETED_PREVIEW;
28 29 use crate::theme;
29 30 use app_ui_kit::layout::ROW_PADDING;
30 31
31 32 pub type RowAction = Option<Box<dyn Fn(&mut App)>>;
33 pub type SharedRowAction = Option<std::rc::Rc<dyn Fn(&mut App)>>;
32 34
33 35 pub const BUBBLE_TAGS: [&str; 12] = [
34 36 "message-bubble/0",
@@ -80,11 +82,13 @@ pub struct RowActions {
80 82 pub open_image: Option<ImageActions>,
81 83 pub highlighted: bool,
82 84 pub saved: bool,
85 pub pinned: bool,
83 86 pub translation: Option<TranslationActions>,
84 87 pub timeline: TimelineBounds,
85 88 pub agent_run: Option<AgentRun>,
86 89 pub call: CallActions,
87 90 pub reaction_proposal: Option<ReactionPill>,
91 pub undo_delete: SharedRowAction,
88 92 }
89 93
90 94 const TOOLBAR_RIGHT_INSET: f32 = 0.;
@@ -121,6 +125,34 @@ pub(super) fn new_marker() -> Div {
121 125 )
122 126 }
123 127
128 pub(super) fn deleted_tombstone(index: usize, undo_delete: SharedRowAction) -> Div {
129 let line =
130 h_flex()
131 .gap(px(8.))
132 .items_baseline()
133 .text_size(px(13.))
134 .child(div().italic().text_color(theme::text_muted()).child(
135 if undo_delete.is_some() {
136 DELETED_TOMBSTONE
137 } else {
138 DELETED_PREVIEW
139 },
140 ));
141 match undo_delete {
142 Some(undo) => line.child(
143 div()
144 .id(ElementId::Name(format!("undo-delete-{index}").into()))
145 .cursor_pointer()
146 .font_weight(FontWeight::SEMIBOLD)
147 .text_color(theme::accent_text())
148 .hover(|link| link.underline())
149 .child(UNDO_DELETE_LABEL)
150 .on_click(move |_, _, cx| undo(cx)),
151 ),
152 None => line,
153 }
154 }
155
124 156 fn bubble_max_width(timeline: &TimelineBounds, reserved: f32) -> Length {
125 157 let Some(bounds) = timeline.get() else {
126 158 return relative(MAX_WIDTH_RATIO).into();
@@ -167,10 +199,7 @@ fn bubble(
167 199 .border_1()
168 200 .border_color(theme::border_strong())
169 201 .py(px(6.))
170 .text_size(px(13.))
171 .italic()
172 .text_color(theme::text_muted())
173 .child(DELETED_PREVIEW);
202 .child(deleted_tombstone(index, extras.undo_delete));
174 203 }
175 204 let failed = matches!(row.delivery, Delivery::Failed(_));
176 205 let scheduled = matches!(row.delivery, Delivery::Scheduled(_));
@@ -318,6 +347,7 @@ struct BubbleExtras {
318 347 timeline: TimelineBounds,
319 348 agent_run: Option<AgentRun>,
320 349 reaction_proposal: Option<ReactionPill>,
350 undo_delete: SharedRowAction,
321 351 }
322 352
323 353 fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
@@ -609,15 +639,12 @@ fn own_row(
609 639 let reaction_proposal = extras.reaction_proposal.take();
610 640 let mut column = v_flex().w_full().items_end().gap(px(2.));
611 641 column = column.child(
612 h_flex()
613 .w_full()
614 .justify_end()
615 .child(
616 div()
617 .min_w_0()
618 .max_w(bubble_max_width(&extras.timeline, 0.))
619 .child(bubble(row, index, true, directory, extras, cx)),
620 ),
642 h_flex().w_full().justify_end().child(
643 div()
644 .min_w_0()
645 .max_w(bubble_max_width(&extras.timeline, 0.))
646 .child(bubble(row, index, true, directory, extras, cx)),
647 ),
621 648 );
622 649 column = column.children(agent_chip(agent_run));
623 650 column = column.children(reaction_proposal.map(|pill| reaction_pill(pill, &row.key)));
@@ -655,7 +682,9 @@ pub fn render_message_row(
655 682 timeline,
656 683 agent_run,
657 684 call: _,
685 pinned: _,
658 686 reaction_proposal,
687 undo_delete,
659 688 } = actions;
660 689 let extras = BubbleExtras {
661 690 hover: hovered,
@@ -670,6 +699,7 @@ pub fn render_message_row(
670 699 timeline,
671 700 agent_run,
672 701 reaction_proposal,
702 undo_delete,
673 703 };
674 704 let own = row.own;
675 705 let spacing = if row.series.has_prev {
@@ -23,12 +23,14 @@ use crate::agents::{AgentRun, run_chip};
23use crate::card_state::BotIdentity;
23use crate::card_state::BotIdentity;
24use crate::data::Directory;
24use crate::data::Directory;
25use crate::render::Block;
25use crate::render::Block;
26use crate::restorable_deletes::{DELETED_TOMBSTONE, UNDO_DELETE_LABEL};
26use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};
27use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};
27use crate::sidebar_model::DELETED_PREVIEW;
28use crate::sidebar_model::DELETED_PREVIEW;
28use crate::theme;
29use crate::theme;
29use app_ui_kit::layout::ROW_PADDING;
30use app_ui_kit::layout::ROW_PADDING;
30
31
31pub type RowAction = Option<Box<dyn Fn(&mut App)>>;
32pub type RowAction = Option<Box<dyn Fn(&mut App)>>;
33pub type SharedRowAction = Option<std::rc::Rc<dyn Fn(&mut App)>>;
32
34
33pub const BUBBLE_TAGS: [&str; 12] = [
35pub const BUBBLE_TAGS: [&str; 12] = [
34 "message-bubble/0",
36 "message-bubble/0",
@@ -80,11 +82,13 @@ pub struct RowActions {
80 pub open_image: Option<ImageActions>,
82 pub open_image: Option<ImageActions>,
81 pub highlighted: bool,
83 pub highlighted: bool,
82 pub saved: bool,
84 pub saved: bool,
85 pub pinned: bool,
83 pub translation: Option<TranslationActions>,
86 pub translation: Option<TranslationActions>,
84 pub timeline: TimelineBounds,
87 pub timeline: TimelineBounds,
85 pub agent_run: Option<AgentRun>,
88 pub agent_run: Option<AgentRun>,
86 pub call: CallActions,
89 pub call: CallActions,
87 pub reaction_proposal: Option<ReactionPill>,
90 pub reaction_proposal: Option<ReactionPill>,
91 pub undo_delete: SharedRowAction,
88}
92}
89
93
90const TOOLBAR_RIGHT_INSET: f32 = 0.;
94const TOOLBAR_RIGHT_INSET: f32 = 0.;
@@ -121,6 +125,34 @@ pub(super) fn new_marker() -> Div {
121 )
125 )
122}
126}
123
127
128pub(super) fn deleted_tombstone(index: usize, undo_delete: SharedRowAction) -> Div {
129 let line =
130 h_flex()
131 .gap(px(8.))
132 .items_baseline()
133 .text_size(px(13.))
134 .child(div().italic().text_color(theme::text_muted()).child(
135 if undo_delete.is_some() {
136 DELETED_TOMBSTONE
137 } else {
138 DELETED_PREVIEW
139 },
140 ));
141 match undo_delete {
142 Some(undo) => line.child(
143 div()
144 .id(ElementId::Name(format!("undo-delete-{index}").into()))
145 .cursor_pointer()
146 .font_weight(FontWeight::SEMIBOLD)
147 .text_color(theme::accent_text())
148 .hover(|link| link.underline())
149 .child(UNDO_DELETE_LABEL)
150 .on_click(move |_, _, cx| undo(cx)),
151 ),
152 None => line,
153 }
154}
155
124fn bubble_max_width(timeline: &TimelineBounds, reserved: f32) -> Length {
156fn bubble_max_width(timeline: &TimelineBounds, reserved: f32) -> Length {
125 let Some(bounds) = timeline.get() else {
157 let Some(bounds) = timeline.get() else {
126 return relative(MAX_WIDTH_RATIO).into();
158 return relative(MAX_WIDTH_RATIO).into();
@@ -167,10 +199,7 @@ fn bubble(
167 .border_1()
199 .border_1()
168 .border_color(theme::border_strong())
200 .border_color(theme::border_strong())
169 .py(px(6.))
201 .py(px(6.))
170 .text_size(px(13.))
202 .child(deleted_tombstone(index, extras.undo_delete));
171 .italic()
172 .text_color(theme::text_muted())
173 .child(DELETED_PREVIEW);
174 }
203 }
175 let failed = matches!(row.delivery, Delivery::Failed(_));
204 let failed = matches!(row.delivery, Delivery::Failed(_));
176 let scheduled = matches!(row.delivery, Delivery::Scheduled(_));
205 let scheduled = matches!(row.delivery, Delivery::Scheduled(_));
@@ -318,6 +347,7 @@ struct BubbleExtras {
318 timeline: TimelineBounds,
347 timeline: TimelineBounds,
319 agent_run: Option<AgentRun>,
348 agent_run: Option<AgentRun>,
320 reaction_proposal: Option<ReactionPill>,
349 reaction_proposal: Option<ReactionPill>,
350 undo_delete: SharedRowAction,
321}
351}
322
352
323fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
353fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
@@ -609,15 +639,12 @@ fn own_row(
609 let reaction_proposal = extras.reaction_proposal.take();
639 let reaction_proposal = extras.reaction_proposal.take();
610 let mut column = v_flex().w_full().items_end().gap(px(2.));
640 let mut column = v_flex().w_full().items_end().gap(px(2.));
611 column = column.child(
641 column = column.child(
612 h_flex()
642 h_flex().w_full().justify_end().child(
613 .w_full()
643 div()
614 .justify_end()
644 .min_w_0()
615 .child(
645 .max_w(bubble_max_width(&extras.timeline, 0.))
616 div()
646 .child(bubble(row, index, true, directory, extras, cx)),
617 .min_w_0()
647 ),
618 .max_w(bubble_max_width(&extras.timeline, 0.))
619 .child(bubble(row, index, true, directory, extras, cx)),
620 ),
621 );
648 );
622 column = column.children(agent_chip(agent_run));
649 column = column.children(agent_chip(agent_run));
623 column = column.children(reaction_proposal.map(|pill| reaction_pill(pill, &row.key)));
650 column = column.children(reaction_proposal.map(|pill| reaction_pill(pill, &row.key)));
@@ -655,7 +682,9 @@ pub fn render_message_row(
655 timeline,
682 timeline,
656 agent_run,
683 agent_run,
657 call: _,
684 call: _,
685 pinned: _,
658 reaction_proposal,
686 reaction_proposal,
687 undo_delete,
659 } = actions;
688 } = actions;
660 let extras = BubbleExtras {
689 let extras = BubbleExtras {
661 hover: hovered,
690 hover: hovered,
@@ -670,6 +699,7 @@ pub fn render_message_row(
670 timeline,
699 timeline,
671 agent_run,
700 agent_run,
672 reaction_proposal,
701 reaction_proposal,
702 undo_delete,
673 };
703 };
674 let own = row.own;
704 let own = row.own;
675 let spacing = if row.series.has_prev {
705 let spacing = if row.series.has_prev {
crates/app/src/views/mod.rs +1 −0
@@ -18,6 +18,7 @@ pub mod call_mini_window;
18 18 pub mod call_organizer;
19 19 pub mod call_people;
20 20 pub mod call_pop_out;
21 pub mod call_share_gallery;
21 22 pub mod call_record;
22 23 pub mod call_stage;
23 24 pub mod call_transcript;
@@ -18,6 +18,7 @@ pub mod call_mini_window;
18pub mod call_organizer;
18pub mod call_organizer;
19pub mod call_people;
19pub mod call_people;
20pub mod call_pop_out;
20pub mod call_pop_out;
21pub mod call_share_gallery;
21pub mod call_record;
22pub mod call_record;
22pub mod call_stage;
23pub mod call_stage;
23pub mod call_transcript;
24pub mod call_transcript;
crates/app/src/views/pin_banner.rs +13 −5
@@ -3,12 +3,15 @@ use gpui_kit::component::{h_flex, tooltip::Tooltip};
3 3 use gpui_kit::prelude::FluentBuilder as _;
4 4 use gpui_kit::*;
5 5
6 use app_ui_kit::layout::ROW_PADDING;
7
6 8 use super::message_actions::Action;
7 9 use super::widgets::icon;
8 10 use crate::theme;
9 11
10 12 const BANNER_HEIGHT: f32 = 40.;
11 const BANNER_MARGIN: f32 = 20.;
13 const BANNER_INSET: f32 = ROW_PADDING;
14 pub const PIN_BANNER_TAG: &str = "shell/islands/main/pin-banner";
12 15 const BANNER_GAP: f32 = 8.;
13 16 const BANNER_PADDING: f32 = 12.;
14 17 const BUTTON_SIZE: f32 = 28.;
@@ -29,15 +32,19 @@ pub struct PinBannerActions {
29 32 }
30 33
31 34 pub fn pin_banner_inset(shown: bool) -> Pixels {
32 px(if shown { BANNER_HEIGHT + BANNER_GAP } else { 0. })
35 px(if shown {
36 BANNER_INSET + BANNER_HEIGHT + BANNER_GAP
37 } else {
38 0.
39 })
33 40 }
34 41
35 42 pub fn pin_banner_overlay(banner: AnyElement) -> AnyElement {
36 43 div()
37 44 .absolute()
38 .top_0()
39 .left(px(BANNER_MARGIN))
40 .right(px(BANNER_MARGIN))
45 .top(px(BANNER_INSET))
46 .left(px(BANNER_INSET))
47 .right(px(BANNER_INSET))
41 48 .child(banner)
42 49 .into_any_element()
43 50 }
@@ -86,6 +93,7 @@ pub fn render_pin_banner(data: PinBannerData, actions: PinBannerActions) -> AnyE
86 93 } = actions;
87 94 h_flex()
88 95 .id("pin-banner")
96 .debug_selector(|| PIN_BANNER_TAG.into())
89 97 .group("pin-banner")
90 98 .occlude()
91 99 .w_full()
@@ -3,12 +3,15 @@ use gpui_kit::component::{h_flex, tooltip::Tooltip};
3use gpui_kit::prelude::FluentBuilder as _;
3use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::*;
4use gpui_kit::*;
5
5
6use app_ui_kit::layout::ROW_PADDING;
7
6use super::message_actions::Action;
8use super::message_actions::Action;
7use super::widgets::icon;
9use super::widgets::icon;
8use crate::theme;
10use crate::theme;
9
11
10const BANNER_HEIGHT: f32 = 40.;
12const BANNER_HEIGHT: f32 = 40.;
11const BANNER_MARGIN: f32 = 20.;
13const BANNER_INSET: f32 = ROW_PADDING;
14pub const PIN_BANNER_TAG: &str = "shell/islands/main/pin-banner";
12const BANNER_GAP: f32 = 8.;
15const BANNER_GAP: f32 = 8.;
13const BANNER_PADDING: f32 = 12.;
16const BANNER_PADDING: f32 = 12.;
14const BUTTON_SIZE: f32 = 28.;
17const BUTTON_SIZE: f32 = 28.;
@@ -29,15 +32,19 @@ pub struct PinBannerActions {
29}
32}
30
33
31pub fn pin_banner_inset(shown: bool) -> Pixels {
34pub fn pin_banner_inset(shown: bool) -> Pixels {
32 px(if shown { BANNER_HEIGHT + BANNER_GAP } else { 0. })
35 px(if shown {
36 BANNER_INSET + BANNER_HEIGHT + BANNER_GAP
37 } else {
38 0.
39 })
33}
40}
34
41
35pub fn pin_banner_overlay(banner: AnyElement) -> AnyElement {
42pub fn pin_banner_overlay(banner: AnyElement) -> AnyElement {
36 div()
43 div()
37 .absolute()
44 .absolute()
38 .top_0()
45 .top(px(BANNER_INSET))
39 .left(px(BANNER_MARGIN))
46 .left(px(BANNER_INSET))
40 .right(px(BANNER_MARGIN))
47 .right(px(BANNER_INSET))
41 .child(banner)
48 .child(banner)
42 .into_any_element()
49 .into_any_element()
43}
50}
@@ -86,6 +93,7 @@ pub fn render_pin_banner(data: PinBannerData, actions: PinBannerActions) -> AnyE
86 } = actions;
93 } = actions;
87 h_flex()
94 h_flex()
88 .id("pin-banner")
95 .id("pin-banner")
96 .debug_selector(|| PIN_BANNER_TAG.into())
89 .group("pin-banner")
97 .group("pin-banner")
90 .occlude()
98 .occlude()
91 .w_full()
99 .w_full()
crates/app/src/views/post_card.rs +26 −10
@@ -10,7 +10,9 @@ use super::call_card::{CallActions, post_call_card};
10 10 use super::call_notice::notice_line;
11 11 use super::link_preview::{link_preview_card, meeting_join_chip};
12 12 use super::message_actions::message_toolbar;
13 use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};
13 use super::message_row::{
14 BODY_SIZE, RowActions, deleted_tombstone, delivery_note, forwarded_header, has_text,
15 };
14 16 use super::profile_card::opens_profile;
15 17 use super::reaction_pills::reaction_pills;
16 18 use super::reaction_proposal_pill::reaction_pill;
@@ -21,7 +23,6 @@ use super::widgets::{icon, symbol};
21 23 use crate::agents::run_chip;
22 24 use crate::data::Directory;
23 25 use crate::rows::{Delivery, MessageRow, PostRow};
24 use crate::sidebar_model::DELETED_PREVIEW;
25 26 use crate::theme;
26 27
27 28 const ROOT_AVATAR: f32 = 32.;
@@ -30,6 +31,7 @@ const AVATAR_GAP: f32 = 10.;
30 31 const CARD_PADDING: f32 = 12.;
31 32 const CARD_RADIUS: f32 = 10.;
32 33 const CARD_GAP: f32 = 12.;
34 const PINNED_LABEL: &str = "Pinned";
33 35 const SLOTS_PER_POST: usize = 64;
34 36 const TOOLBAR_RIGHT_INSET: f32 = 8.;
35 37 const SUBJECT_SIZE: f32 = 14.;
@@ -62,6 +64,16 @@ fn edited_marker() -> Div {
62 64 .child("Edited")
63 65 }
64 66
67 fn pinned_marker() -> Div {
68 h_flex()
69 .gap(px(3.))
70 .items_center()
71 .text_size(px(11.))
72 .text_color(theme::text_muted())
73 .child(icon(IconName::Pin, 11., theme::text_muted()))
74 .child(PINNED_LABEL)
75 }
76
65 77 fn message_content(
66 78 row: &MessageRow,
67 79 index: usize,
@@ -71,13 +83,7 @@ fn message_content(
71 83 ) -> Div {
72 84 let mut content = v_flex().gap(px(6.));
73 85 if row.deleted {
74 return content.child(
75 div()
76 .text_size(px(13.))
77 .italic()
78 .text_color(theme::text_muted())
79 .child(DELETED_PREVIEW),
80 );
86 return content.child(deleted_tombstone(index, actions.undo_delete.clone()));
81 87 }
82 88 if row.forwarded {
83 89 content = content.child(forwarded_header());
@@ -150,6 +156,7 @@ fn message_header(
150 156 author: String,
151 157 profile_user: Option<&str>,
152 158 saved: bool,
159 pinned: bool,
153 160 ) -> Div {
154 161 h_flex()
155 162 .gap(px(6.))
@@ -171,6 +178,7 @@ fn message_header(
171 178 .child(row.time.clone()),
172 179 )
173 180 .when(row.edited, |line| line.child(edited_marker()))
181 .when(pinned, |line| line.child(pinned_marker()))
174 182 .when(saved, |line| {
175 183 line.child(icon(IconName::Bookmark, 12., theme::accent_text()))
176 184 })
@@ -223,6 +231,7 @@ fn message_block(
223 231 None => message_content(row, index, directory, &actions, cx),
224 232 };
225 233 let saved = actions.saved;
234 let pinned = actions.pinned && role == Role::Root;
226 235 let RowActions {
227 236 delivery,
228 237 reply,
@@ -242,7 +251,14 @@ fn message_block(
242 251 .flex_1()
243 252 .min_w_0()
244 253 .gap(px(6.))
245 .child(message_header(row, index, author, profile_user, saved))
254 .child(message_header(
255 row,
256 index,
257 author,
258 profile_user,
259 saved,
260 pinned,
261 ))
246 262 .when_some(
247 263 row.subject.clone().filter(|_| role == Role::Root),
248 264 |column, subject| {
@@ -10,7 +10,9 @@ use super::call_card::{CallActions, post_call_card};
10use super::call_notice::notice_line;
10use super::call_notice::notice_line;
11use super::link_preview::{link_preview_card, meeting_join_chip};
11use super::link_preview::{link_preview_card, meeting_join_chip};
12use super::message_actions::message_toolbar;
12use super::message_actions::message_toolbar;
13use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};
13use super::message_row::{
14 BODY_SIZE, RowActions, deleted_tombstone, delivery_note, forwarded_header, has_text,
15};
14use super::profile_card::opens_profile;
16use super::profile_card::opens_profile;
15use super::reaction_pills::reaction_pills;
17use super::reaction_pills::reaction_pills;
16use super::reaction_proposal_pill::reaction_pill;
18use super::reaction_proposal_pill::reaction_pill;
@@ -21,7 +23,6 @@ use super::widgets::{icon, symbol};
21use crate::agents::run_chip;
23use crate::agents::run_chip;
22use crate::data::Directory;
24use crate::data::Directory;
23use crate::rows::{Delivery, MessageRow, PostRow};
25use crate::rows::{Delivery, MessageRow, PostRow};
24use crate::sidebar_model::DELETED_PREVIEW;
25use crate::theme;
26use crate::theme;
26
27
27const ROOT_AVATAR: f32 = 32.;
28const ROOT_AVATAR: f32 = 32.;
@@ -30,6 +31,7 @@ const AVATAR_GAP: f32 = 10.;
30const CARD_PADDING: f32 = 12.;
31const CARD_PADDING: f32 = 12.;
31const CARD_RADIUS: f32 = 10.;
32const CARD_RADIUS: f32 = 10.;
32const CARD_GAP: f32 = 12.;
33const CARD_GAP: f32 = 12.;
34const PINNED_LABEL: &str = "Pinned";
33const SLOTS_PER_POST: usize = 64;
35const SLOTS_PER_POST: usize = 64;
34const TOOLBAR_RIGHT_INSET: f32 = 8.;
36const TOOLBAR_RIGHT_INSET: f32 = 8.;
35const SUBJECT_SIZE: f32 = 14.;
37const SUBJECT_SIZE: f32 = 14.;
@@ -62,6 +64,16 @@ fn edited_marker() -> Div {
62 .child("Edited")
64 .child("Edited")
63}
65}
64
66
67fn pinned_marker() -> Div {
68 h_flex()
69 .gap(px(3.))
70 .items_center()
71 .text_size(px(11.))
72 .text_color(theme::text_muted())
73 .child(icon(IconName::Pin, 11., theme::text_muted()))
74 .child(PINNED_LABEL)
75}
76
65fn message_content(
77fn message_content(
66 row: &MessageRow,
78 row: &MessageRow,
67 index: usize,
79 index: usize,
@@ -71,13 +83,7 @@ fn message_content(
71) -> Div {
83) -> Div {
72 let mut content = v_flex().gap(px(6.));
84 let mut content = v_flex().gap(px(6.));
73 if row.deleted {
85 if row.deleted {
74 return content.child(
86 return content.child(deleted_tombstone(index, actions.undo_delete.clone()));
75 div()
76 .text_size(px(13.))
77 .italic()
78 .text_color(theme::text_muted())
79 .child(DELETED_PREVIEW),
80 );
81 }
87 }
82 if row.forwarded {
88 if row.forwarded {
83 content = content.child(forwarded_header());
89 content = content.child(forwarded_header());
@@ -150,6 +156,7 @@ fn message_header(
150 author: String,
156 author: String,
151 profile_user: Option<&str>,
157 profile_user: Option<&str>,
152 saved: bool,
158 saved: bool,
159 pinned: bool,
153) -> Div {
160) -> Div {
154 h_flex()
161 h_flex()
155 .gap(px(6.))
162 .gap(px(6.))
@@ -171,6 +178,7 @@ fn message_header(
171 .child(row.time.clone()),
178 .child(row.time.clone()),
172 )
179 )
173 .when(row.edited, |line| line.child(edited_marker()))
180 .when(row.edited, |line| line.child(edited_marker()))
181 .when(pinned, |line| line.child(pinned_marker()))
174 .when(saved, |line| {
182 .when(saved, |line| {
175 line.child(icon(IconName::Bookmark, 12., theme::accent_text()))
183 line.child(icon(IconName::Bookmark, 12., theme::accent_text()))
176 })
184 })
@@ -223,6 +231,7 @@ fn message_block(
223 None => message_content(row, index, directory, &actions, cx),
231 None => message_content(row, index, directory, &actions, cx),
224 };
232 };
225 let saved = actions.saved;
233 let saved = actions.saved;
234 let pinned = actions.pinned && role == Role::Root;
226 let RowActions {
235 let RowActions {
227 delivery,
236 delivery,
228 reply,
237 reply,
@@ -242,7 +251,14 @@ fn message_block(
242 .flex_1()
251 .flex_1()
243 .min_w_0()
252 .min_w_0()
244 .gap(px(6.))
253 .gap(px(6.))
245 .child(message_header(row, index, author, profile_user, saved))
254 .child(message_header(
255 row,
256 index,
257 author,
258 profile_user,
259 saved,
260 pinned,
261 ))
246 .when_some(
262 .when_some(
247 row.subject.clone().filter(|_| role == Role::Root),
263 row.subject.clone().filter(|_| role == Role::Root),
248 |column, subject| {
264 |column, subject| {
crates/app/src/views/shell.rs +9 −1
@@ -19,7 +19,7 @@ use gpui_kit::prelude::FluentBuilder as _;
19 19 use super::rail::RailView;
20 20 use super::saved_panel::{SavedPanel, SavedPanelEvent};
21 21 use super::shortcuts::{
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, NextConversation, OpenActivity,
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
23 23 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
24 24 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
25 25 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
@@ -1040,6 +1040,14 @@ impl Render for AppShell {
1040 1040 .on_action(zoom_listener::<ZoomShareIn>(&self.state, ZoomStep::In))
1041 1041 .on_action(zoom_listener::<ZoomShareOut>(&self.state, ZoomStep::Out))
1042 1042 .on_action(zoom_listener::<ZoomShareReset>(&self.state, ZoomStep::Reset))
1043 .on_action(cx.listener(|this, _: &JumpToLastReadOrNewest, _, cx| {
1044 if this.image_viewer.is_some() || this.state.read(cx).viewing_call() {
1045 cx.propagate();
1046 return;
1047 }
1048 this.conversation
1049 .update(cx, |conversation, cx| conversation.jump_to_last_read_or_newest(cx));
1050 }))
1043 1051 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
1044 1052 this.close_image_viewer(window, cx);
1045 1053 this.conversation.update(cx, |conversation, cx| {
@@ -19,7 +19,7 @@ use gpui_kit::prelude::FluentBuilder as _;
19use super::rail::RailView;
19use super::rail::RailView;
20use super::saved_panel::{SavedPanel, SavedPanelEvent};
20use super::saved_panel::{SavedPanel, SavedPanelEvent};
21use super::shortcuts::{
21use super::shortcuts::{
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, NextConversation, OpenActivity,
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
23 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
23 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
24 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
24 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
25 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
25 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
@@ -1040,6 +1040,14 @@ impl Render for AppShell {
1040 .on_action(zoom_listener::<ZoomShareIn>(&self.state, ZoomStep::In))
1040 .on_action(zoom_listener::<ZoomShareIn>(&self.state, ZoomStep::In))
1041 .on_action(zoom_listener::<ZoomShareOut>(&self.state, ZoomStep::Out))
1041 .on_action(zoom_listener::<ZoomShareOut>(&self.state, ZoomStep::Out))
1042 .on_action(zoom_listener::<ZoomShareReset>(&self.state, ZoomStep::Reset))
1042 .on_action(zoom_listener::<ZoomShareReset>(&self.state, ZoomStep::Reset))
1043 .on_action(cx.listener(|this, _: &JumpToLastReadOrNewest, _, cx| {
1044 if this.image_viewer.is_some() || this.state.read(cx).viewing_call() {
1045 cx.propagate();
1046 return;
1047 }
1048 this.conversation
1049 .update(cx, |conversation, cx| conversation.jump_to_last_read_or_newest(cx));
1050 }))
1043 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
1051 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
1044 this.close_image_viewer(window, cx);
1052 this.close_image_viewer(window, cx);
1045 this.conversation.update(cx, |conversation, cx| {
1053 this.conversation.update(cx, |conversation, cx| {
crates/app/src/views/shortcuts.rs +2 −0
@@ -31,6 +31,7 @@ actions!(
31 31 OpenAgents,
32 32 PreviousConversation,
33 33 NextConversation,
34 JumpToLastReadOrNewest,
34 35 AcceptCall,
35 36 DeclineCall,
36 37 JoinMeetingFromToast,
@@ -129,6 +130,7 @@ pub const SHORTCUTS: &[Shortcut] = &[
129 130 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
130 131 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
131 132 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
133 shortcut!(Composer, Global, "Jump to last read or newest message", "ctrl-j", Some("cmd-j"), JumpToLastReadOrNewest),
132 134 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
133 135 shortcut!(Composer, Composer, "Italic", "ctrl-i", Some("cmd-i"), ToggleItalic),
134 136 shortcut!(Composer, Composer, "Underline", "ctrl-u", Some("cmd-u"), ToggleUnderline),
@@ -31,6 +31,7 @@ actions!(
31 OpenAgents,
31 OpenAgents,
32 PreviousConversation,
32 PreviousConversation,
33 NextConversation,
33 NextConversation,
34 JumpToLastReadOrNewest,
34 AcceptCall,
35 AcceptCall,
35 DeclineCall,
36 DeclineCall,
36 JoinMeetingFromToast,
37 JoinMeetingFromToast,
@@ -129,6 +130,7 @@ pub const SHORTCUTS: &[Shortcut] = &[
129 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
130 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
130 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
131 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
131 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
132 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
133 shortcut!(Composer, Global, "Jump to last read or newest message", "ctrl-j", Some("cmd-j"), JumpToLastReadOrNewest),
132 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
134 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
133 shortcut!(Composer, Composer, "Italic", "ctrl-i", Some("cmd-i"), ToggleItalic),
135 shortcut!(Composer, Composer, "Italic", "ctrl-i", Some("cmd-i"), ToggleItalic),
134 shortcut!(Composer, Composer, "Underline", "ctrl-u", Some("cmd-u"), ToggleUnderline),
136 shortcut!(Composer, Composer, "Underline", "ctrl-u", Some("cmd-u"), ToggleUnderline),
crates/app/src/views/sidebar.rs +104 −43
@@ -30,9 +30,10 @@ use crate::format;
30 30 use crate::local_previews::LocalPreview;
31 31 use crate::notice::truncated;
32 32 use crate::sidebar_model::{
33 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, NameStyle,
34 NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,
35 channel_name_style, older_chats_trigger_resets, step_id, team_name_style, visible_channel_ids,
33 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, MentionBadge,
34 NameStyle, NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,
35 channel_badge, channel_name_style, channel_shown, older_chats_trigger_resets, step_id,
36 team_badge, team_channel_rows, team_hoisted, team_name_style, visible_channel_ids,
36 37 wants_older_chats,
37 38 };
38 39 use crate::theme;
@@ -54,12 +55,14 @@ const VIEWPORT_MARGIN: f32 = 300.;
54 55 const AVATAR_SIZE: f32 = 36.;
55 56 const PINNED_LABEL: &str = "Pinned";
56 57 const TEAMS_LABEL: &str = "Teams";
58 const MARK_ALL_READ_LABEL: &str = "Mark all as read";
57 59 const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
58 60 const TEAM_ROW_HEIGHT: f32 = 40.;
59 61 const REVEAL_ROW_HEIGHT: f32 = 32.;
60 62 const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
61 63 const MENU_ICON_SIZE: f32 = 15.;
62 64 const NOTIFICATION_ICON_SIZE: f32 = 13.;
65 const MENTION_ICON_SIZE: f32 = 15.;
63 66
64 67 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
65 68 pub enum SidebarTab {
@@ -792,6 +795,28 @@ impl SidebarView {
792 795 .dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))
793 796 }
794 797
798 fn channel_list_menu_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
799 let state = self.state.clone();
800 let read_only = self.state.read(cx).mode.read_only;
801 Button::new("channel-list-more")
802 .icon(IconName::Ellipsis)
803 .ghost()
804 .size(px(NEW_CHAT_BUTTON_SIZE))
805 .rounded(px(8.))
806 .tooltip("More options")
807 .dropdown_menu(move |menu, _, _| {
808 let state = state.clone();
809 menu.item(
810 PopupMenuItem::new(MARK_ALL_READ_LABEL)
811 .icon(menu_icon(IconName::CheckCheck))
812 .disabled(read_only)
813 .on_click(move |_, _, cx| {
814 state.update(cx, |state, cx| state.mark_all_channels_read(cx));
815 }),
816 )
817 })
818 }
819
795 820 fn draft_row(&self) -> impl IntoElement {
796 821 h_flex()
797 822 .id("new-chat-draft")
@@ -1049,6 +1074,10 @@ impl SidebarView {
1049 1074 title: item.title.clone(),
1050 1075 };
1051 1076 let menu_context = menu.clone();
1077 let reorder_folder = item
1078 .folder_id
1079 .clone()
1080 .filter(|folder_id| !is_pending_folder(folder_id));
1052 1081 let target = ChatMenuTarget {
1053 1082 id: item.id.clone(),
1054 1083 title: item.title.clone(),
@@ -1074,6 +1103,15 @@ impl SidebarView {
1074 1103 let title = dragged.title.clone();
1075 1104 cx.new(|_| DragGhost { title })
1076 1105 })
1106 .when_some(reorder_folder, |row, folder_id| {
1107 let (drop_state, target_id) = (self.state.clone(), item.id.clone());
1108 row.drag_over::<DraggedChat>(|style, _, _, _| style.bg(theme::drop_background()))
1109 .on_drop(move |dragged: &DraggedChat, _, cx| {
1110 drop_state.update(cx, |state, cx| {
1111 state.drop_chat_on(&dragged.id, &target_id, &folder_id, cx)
1112 });
1113 })
1114 })
1077 1115 .child(avatar)
1078 1116 .child(lines)
1079 1117 .on_click(move |_, _, cx| {
@@ -1263,6 +1301,7 @@ impl SidebarView {
1263 1301 channel: &ChannelRecord,
1264 1302 selected: bool,
1265 1303 notifications: ChannelNotifications,
1304 badge: Option<MentionBadge>,
1266 1305 ) -> AnyElement {
1267 1306 let unread = channel.unread;
1268 1307 let name_style = channel_name_style(unread, true, selected);
@@ -1323,15 +1362,19 @@ impl SidebarView {
1323 1362 ),
1324 1363 )
1325 1364 .child(
1326 h_flex().gap(px(8.)).items_center().child(
1327 div()
1328 .flex_1()
1329 .min_w_0()
1330 .truncate()
1331 .text_size(px(12.))
1332 .text_color(theme::text_muted())
1333 .child(team.name.clone()),
1334 ),
1365 h_flex()
1366 .gap(px(8.))
1367 .items_center()
1368 .child(
1369 div()
1370 .flex_1()
1371 .min_w_0()
1372 .truncate()
1373 .text_size(px(12.))
1374 .text_color(theme::text_muted())
1375 .child(team.name.clone()),
1376 )
1377 .children(badge.map(mention_badge)),
1335 1378 ),
1336 1379 )
1337 1380 .on_click(move |_, _, cx| {
@@ -1368,12 +1411,14 @@ impl SidebarView {
1368 1411 &self,
1369 1412 mut list: Div,
1370 1413 entry: &SidebarTeam,
1414 hoisted_only: bool,
1371 1415 selected: Option<&Selection>,
1372 1416 cx: &mut Context<Self>,
1373 1417 ) -> Div {
1374 1418 let team_id = entry.team.id.clone();
1375 1419 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1376 1420 let name_style = team_name_style(entry, expanded);
1421 let badge = team_badge(entry, expanded);
1377 1422 let toggle_id = team_id.clone();
1378 1423 list = list.child(
1379 1424 h_flex()
@@ -1407,6 +1452,7 @@ impl SidebarView {
1407 1452 .text_color(name_color(name_style))
1408 1453 .child(entry.team.name.clone()),
1409 1454 )
1455 .children(badge.map(mention_badge))
1410 1456 .on_click(cx.listener(move |this, _, _, cx| {
1411 1457 if !this.collapsed_teams.remove(&toggle_id) {
1412 1458 this.collapsed_teams.insert(toggle_id.clone());
@@ -1418,34 +1464,30 @@ impl SidebarView {
1418 1464 if !expanded {
1419 1465 return list;
1420 1466 }
1421 let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
1422 1467 let is_selected =
1423 1468 |channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));
1424 for channel in entry
1425 .channels
1426 .iter()
1427 .filter(|channel| !is_hidden(channel) || is_selected(channel))
1428 {
1469 let revealed = self.revealed_channel_teams.contains(&team_id);
1470 let rows = team_channel_rows(entry, hoisted_only, revealed, is_selected);
1471 for channel in &rows.shown {
1429 1472 list = list.child(self.team_channel_row(
1430 1473 channel,
1431 1474 is_selected(channel),
1432 channel_name_style(channel.unread, !is_hidden(channel), is_selected(channel)),
1475 channel_name_style(
1476 channel.unread,
1477 channel_shown(entry, &channel.id),
1478 is_selected(channel),
1479 ),
1433 1480 entry.channel_notifications(&channel.id),
1481 channel_badge(entry, &channel.id),
1434 1482 ));
1435 1483 }
1436 let hidden: Vec<&ChannelRecord> = entry
1437 .channels
1438 .iter()
1439 .filter(|channel| is_hidden(channel) && !is_selected(channel))
1440 .collect();
1441 if hidden.is_empty() {
1484 if rows.hidden_count == 0 {
1442 1485 return list;
1443 1486 }
1444 let revealed = self.revealed_channel_teams.contains(&team_id);
1445 1487 let toggle_id = team_id.clone();
1446 1488 list = list.child(self.reveal_row(
1447 1489 SharedString::from(format!("hidden-channels-{team_id}")),
1448 hidden_channels_label(hidden.len()),
1490 hidden_channels_label(rows.hidden_count),
1449 1491 revealed,
1450 1492 40.,
1451 1493 cx.listener(move |this, _, _, cx| {
@@ -1455,15 +1497,14 @@ impl SidebarView {
1455 1497 cx.notify();
1456 1498 }),
1457 1499 ));
1458 if revealed {
1459 for channel in hidden {
1460 list = list.child(self.team_channel_row(
1461 channel,
1462 false,
1463 channel_name_style(channel.unread, false, false),
1464 entry.channel_notifications(&channel.id),
1465 ));
1466 }
1500 for channel in rows.revealed {
1501 list = list.child(self.team_channel_row(
1502 channel,
1503 false,
1504 channel_name_style(channel.unread, false, false),
1505 entry.channel_notifications(&channel.id),
1506 channel_badge(entry, &channel.id),
1507 ));
1467 1508 }
1468 1509 list
1469 1510 }
@@ -1512,6 +1553,7 @@ impl SidebarView {
1512 1553 is_selected: bool,
1513 1554 name_style: NameStyle,
1514 1555 notifications: ChannelNotifications,
1556 badge: Option<MentionBadge>,
1515 1557 ) -> impl IntoElement {
1516 1558 let state = self.state.clone();
1517 1559 let menu_state = self.state.clone();
@@ -1552,6 +1594,7 @@ impl SidebarView {
1552 1594 .child(channel.name.clone()),
1553 1595 )
1554 1596 .children(notification_badge(notifications.level))
1597 .children(badge.map(mention_badge))
1555 1598 .on_click(move |_, _, cx| {
1556 1599 let selection = selection.clone();
1557 1600 state.update(cx, |state, cx| state.select(selection, cx));
@@ -1600,14 +1643,19 @@ impl SidebarView {
1600 1643 channel,
1601 1644 is_selected,
1602 1645 entry.channel_notifications(&channel.id),
1646 channel_badge(entry, &channel.id),
1603 1647 ));
1604 1648 }
1605 1649 }
1606 1650 list = list.child(self.plain_header(TEAMS_LABEL));
1607 let (shown_teams, hidden_teams): (Vec<&SidebarTeam>, Vec<&SidebarTeam>) =
1608 sidebar.teams.iter().partition(|entry| !entry.hidden);
1609 for entry in shown_teams {
1610 list = self.team_block(list, entry, selected.as_ref(), cx);
1651 let hidden_teams: Vec<&SidebarTeam> =
1652 sidebar.teams.iter().filter(|entry| entry.hidden).collect();
1653 for entry in sidebar
1654 .teams
1655 .iter()
1656 .filter(|entry| !entry.hidden || team_hoisted(entry))
1657 {
1658 list = self.team_block(list, entry, entry.hidden, selected.as_ref(), cx);
1611 1659 }
1612 1660 if !hidden_teams.is_empty() {
1613 1661 let holds_selection = hidden_teams
@@ -1626,7 +1674,7 @@ impl SidebarView {
1626 1674 ));
1627 1675 if open {
1628 1676 for entry in hidden_teams {
1629 list = self.team_block(list, entry, selected.as_ref(), cx);
1677 list = self.team_block(list, entry, false, selected.as_ref(), cx);
1630 1678 }
1631 1679 }
1632 1680 }
@@ -1657,6 +1705,18 @@ fn name_color(style: NameStyle) -> Hsla {
1657 1705 }
1658 1706 }
1659 1707
1708 fn mention_badge(badge: MentionBadge) -> AnyElement {
1709 match badge {
1710 MentionBadge::Count(count) => count_badge(count, false).into_any_element(),
1711 MentionBadge::Channel => {
1712 icon(IconName::Hash, MENTION_ICON_SIZE, theme::accent_text()).into_any_element()
1713 }
1714 MentionBadge::Team => {
1715 icon(IconName::Users, MENTION_ICON_SIZE, theme::accent_text()).into_any_element()
1716 }
1717 }
1718 }
1719
1660 1720 fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1661 1721 let name = match level {
1662 1722 ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
@@ -1808,9 +1868,10 @@ impl Render for SidebarView {
1808 1868 .child(self.chat_list_menu_button(cx))
1809 1869 .child(self.new_chat_button(cx)),
1810 1870 ),
1811 SidebarTab::Channels | SidebarTab::Calls | SidebarTab::Agents => {
1812 Some(page_header(self.tab.title()))
1871 SidebarTab::Channels => {
1872 Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))
1813 1873 }
1874 SidebarTab::Calls | SidebarTab::Agents => Some(page_header(self.tab.title())),
1814 1875 SidebarTab::Activity | SidebarTab::Saved => None,
1815 1876 };
1816 1877 v_flex()
@@ -30,9 +30,10 @@ use crate::format;
30use crate::local_previews::LocalPreview;
30use crate::local_previews::LocalPreview;
31use crate::notice::truncated;
31use crate::notice::truncated;
32use crate::sidebar_model::{
32use crate::sidebar_model::{
33 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, NameStyle,
33 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, MentionBadge,
34 NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,
34 NameStyle, NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,
35 channel_name_style, older_chats_trigger_resets, step_id, team_name_style, visible_channel_ids,
35 channel_badge, channel_name_style, channel_shown, older_chats_trigger_resets, step_id,
36 team_badge, team_channel_rows, team_hoisted, team_name_style, visible_channel_ids,
36 wants_older_chats,
37 wants_older_chats,
37};
38};
38use crate::theme;
39use crate::theme;
@@ -54,12 +55,14 @@ const VIEWPORT_MARGIN: f32 = 300.;
54const AVATAR_SIZE: f32 = 36.;
55const AVATAR_SIZE: f32 = 36.;
55const PINNED_LABEL: &str = "Pinned";
56const PINNED_LABEL: &str = "Pinned";
56const TEAMS_LABEL: &str = "Teams";
57const TEAMS_LABEL: &str = "Teams";
58const MARK_ALL_READ_LABEL: &str = "Mark all as read";
57const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
59const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
58const TEAM_ROW_HEIGHT: f32 = 40.;
60const TEAM_ROW_HEIGHT: f32 = 40.;
59const REVEAL_ROW_HEIGHT: f32 = 32.;
61const REVEAL_ROW_HEIGHT: f32 = 32.;
60const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
62const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
61const MENU_ICON_SIZE: f32 = 15.;
63const MENU_ICON_SIZE: f32 = 15.;
62const NOTIFICATION_ICON_SIZE: f32 = 13.;
64const NOTIFICATION_ICON_SIZE: f32 = 13.;
65const MENTION_ICON_SIZE: f32 = 15.;
63
66
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum SidebarTab {
68pub enum SidebarTab {
@@ -792,6 +795,28 @@ impl SidebarView {
792 .dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))
795 .dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))
793 }
796 }
794
797
798 fn channel_list_menu_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
799 let state = self.state.clone();
800 let read_only = self.state.read(cx).mode.read_only;
801 Button::new("channel-list-more")
802 .icon(IconName::Ellipsis)
803 .ghost()
804 .size(px(NEW_CHAT_BUTTON_SIZE))
805 .rounded(px(8.))
806 .tooltip("More options")
807 .dropdown_menu(move |menu, _, _| {
808 let state = state.clone();
809 menu.item(
810 PopupMenuItem::new(MARK_ALL_READ_LABEL)
811 .icon(menu_icon(IconName::CheckCheck))
812 .disabled(read_only)
813 .on_click(move |_, _, cx| {
814 state.update(cx, |state, cx| state.mark_all_channels_read(cx));
815 }),
816 )
817 })
818 }
819
795 fn draft_row(&self) -> impl IntoElement {
820 fn draft_row(&self) -> impl IntoElement {
796 h_flex()
821 h_flex()
797 .id("new-chat-draft")
822 .id("new-chat-draft")
@@ -1049,6 +1074,10 @@ impl SidebarView {
1049 title: item.title.clone(),
1074 title: item.title.clone(),
1050 };
1075 };
1051 let menu_context = menu.clone();
1076 let menu_context = menu.clone();
1077 let reorder_folder = item
1078 .folder_id
1079 .clone()
1080 .filter(|folder_id| !is_pending_folder(folder_id));
1052 let target = ChatMenuTarget {
1081 let target = ChatMenuTarget {
1053 id: item.id.clone(),
1082 id: item.id.clone(),
1054 title: item.title.clone(),
1083 title: item.title.clone(),
@@ -1074,6 +1103,15 @@ impl SidebarView {
1074 let title = dragged.title.clone();
1103 let title = dragged.title.clone();
1075 cx.new(|_| DragGhost { title })
1104 cx.new(|_| DragGhost { title })
1076 })
1105 })
1106 .when_some(reorder_folder, |row, folder_id| {
1107 let (drop_state, target_id) = (self.state.clone(), item.id.clone());
1108 row.drag_over::<DraggedChat>(|style, _, _, _| style.bg(theme::drop_background()))
1109 .on_drop(move |dragged: &DraggedChat, _, cx| {
1110 drop_state.update(cx, |state, cx| {
1111 state.drop_chat_on(&dragged.id, &target_id, &folder_id, cx)
1112 });
1113 })
1114 })
1077 .child(avatar)
1115 .child(avatar)
1078 .child(lines)
1116 .child(lines)
1079 .on_click(move |_, _, cx| {
1117 .on_click(move |_, _, cx| {
@@ -1263,6 +1301,7 @@ impl SidebarView {
1263 channel: &ChannelRecord,
1301 channel: &ChannelRecord,
1264 selected: bool,
1302 selected: bool,
1265 notifications: ChannelNotifications,
1303 notifications: ChannelNotifications,
1304 badge: Option<MentionBadge>,
1266 ) -> AnyElement {
1305 ) -> AnyElement {
1267 let unread = channel.unread;
1306 let unread = channel.unread;
1268 let name_style = channel_name_style(unread, true, selected);
1307 let name_style = channel_name_style(unread, true, selected);
@@ -1323,15 +1362,19 @@ impl SidebarView {
1323 ),
1362 ),
1324 )
1363 )
1325 .child(
1364 .child(
1326 h_flex().gap(px(8.)).items_center().child(
1365 h_flex()
1327 div()
1366 .gap(px(8.))
1328 .flex_1()
1367 .items_center()
1329 .min_w_0()
1368 .child(
1330 .truncate()
1369 div()
1331 .text_size(px(12.))
1370 .flex_1()
1332 .text_color(theme::text_muted())
1371 .min_w_0()
1333 .child(team.name.clone()),
1372 .truncate()
1334 ),
1373 .text_size(px(12.))
1374 .text_color(theme::text_muted())
1375 .child(team.name.clone()),
1376 )
1377 .children(badge.map(mention_badge)),
1335 ),
1378 ),
1336 )
1379 )
1337 .on_click(move |_, _, cx| {
1380 .on_click(move |_, _, cx| {
@@ -1368,12 +1411,14 @@ impl SidebarView {
1368 &self,
1411 &self,
1369 mut list: Div,
1412 mut list: Div,
1370 entry: &SidebarTeam,
1413 entry: &SidebarTeam,
1414 hoisted_only: bool,
1371 selected: Option<&Selection>,
1415 selected: Option<&Selection>,
1372 cx: &mut Context<Self>,
1416 cx: &mut Context<Self>,
1373 ) -> Div {
1417 ) -> Div {
1374 let team_id = entry.team.id.clone();
1418 let team_id = entry.team.id.clone();
1375 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1419 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1376 let name_style = team_name_style(entry, expanded);
1420 let name_style = team_name_style(entry, expanded);
1421 let badge = team_badge(entry, expanded);
1377 let toggle_id = team_id.clone();
1422 let toggle_id = team_id.clone();
1378 list = list.child(
1423 list = list.child(
1379 h_flex()
1424 h_flex()
@@ -1407,6 +1452,7 @@ impl SidebarView {
1407 .text_color(name_color(name_style))
1452 .text_color(name_color(name_style))
1408 .child(entry.team.name.clone()),
1453 .child(entry.team.name.clone()),
1409 )
1454 )
1455 .children(badge.map(mention_badge))
1410 .on_click(cx.listener(move |this, _, _, cx| {
1456 .on_click(cx.listener(move |this, _, _, cx| {
1411 if !this.collapsed_teams.remove(&toggle_id) {
1457 if !this.collapsed_teams.remove(&toggle_id) {
1412 this.collapsed_teams.insert(toggle_id.clone());
1458 this.collapsed_teams.insert(toggle_id.clone());
@@ -1418,34 +1464,30 @@ impl SidebarView {
1418 if !expanded {
1464 if !expanded {
1419 return list;
1465 return list;
1420 }
1466 }
1421 let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
1422 let is_selected =
1467 let is_selected =
1423 |channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));
1468 |channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));
1424 for channel in entry
1469 let revealed = self.revealed_channel_teams.contains(&team_id);
1425 .channels
1470 let rows = team_channel_rows(entry, hoisted_only, revealed, is_selected);
1426 .iter()
1471 for channel in &rows.shown {
1427 .filter(|channel| !is_hidden(channel) || is_selected(channel))
1428 {
1429 list = list.child(self.team_channel_row(
1472 list = list.child(self.team_channel_row(
1430 channel,
1473 channel,
1431 is_selected(channel),
1474 is_selected(channel),
1432 channel_name_style(channel.unread, !is_hidden(channel), is_selected(channel)),
1475 channel_name_style(
1476 channel.unread,
1477 channel_shown(entry, &channel.id),
1478 is_selected(channel),
1479 ),
1433 entry.channel_notifications(&channel.id),
1480 entry.channel_notifications(&channel.id),
1481 channel_badge(entry, &channel.id),
1434 ));
1482 ));
1435 }
1483 }
1436 let hidden: Vec<&ChannelRecord> = entry
1484 if rows.hidden_count == 0 {
1437 .channels
1438 .iter()
1439 .filter(|channel| is_hidden(channel) && !is_selected(channel))
1440 .collect();
1441 if hidden.is_empty() {
1442 return list;
1485 return list;
1443 }
1486 }
1444 let revealed = self.revealed_channel_teams.contains(&team_id);
1445 let toggle_id = team_id.clone();
1487 let toggle_id = team_id.clone();
1446 list = list.child(self.reveal_row(
1488 list = list.child(self.reveal_row(
1447 SharedString::from(format!("hidden-channels-{team_id}")),
1489 SharedString::from(format!("hidden-channels-{team_id}")),
1448 hidden_channels_label(hidden.len()),
1490 hidden_channels_label(rows.hidden_count),
1449 revealed,
1491 revealed,
1450 40.,
1492 40.,
1451 cx.listener(move |this, _, _, cx| {
1493 cx.listener(move |this, _, _, cx| {
@@ -1455,15 +1497,14 @@ impl SidebarView {
1455 cx.notify();
1497 cx.notify();
1456 }),
1498 }),
1457 ));
1499 ));
1458 if revealed {
1500 for channel in rows.revealed {
1459 for channel in hidden {
1501 list = list.child(self.team_channel_row(
1460 list = list.child(self.team_channel_row(
1502 channel,
1461 channel,
1503 false,
1462 false,
1504 channel_name_style(channel.unread, false, false),
1463 channel_name_style(channel.unread, false, false),
1505 entry.channel_notifications(&channel.id),
1464 entry.channel_notifications(&channel.id),
1506 channel_badge(entry, &channel.id),
1465 ));
1507 ));
1466 }
1467 }
1508 }
1468 list
1509 list
1469 }
1510 }
@@ -1512,6 +1553,7 @@ impl SidebarView {
1512 is_selected: bool,
1553 is_selected: bool,
1513 name_style: NameStyle,
1554 name_style: NameStyle,
1514 notifications: ChannelNotifications,
1555 notifications: ChannelNotifications,
1556 badge: Option<MentionBadge>,
1515 ) -> impl IntoElement {
1557 ) -> impl IntoElement {
1516 let state = self.state.clone();
1558 let state = self.state.clone();
1517 let menu_state = self.state.clone();
1559 let menu_state = self.state.clone();
@@ -1552,6 +1594,7 @@ impl SidebarView {
1552 .child(channel.name.clone()),
1594 .child(channel.name.clone()),
1553 )
1595 )
1554 .children(notification_badge(notifications.level))
1596 .children(notification_badge(notifications.level))
1597 .children(badge.map(mention_badge))
1555 .on_click(move |_, _, cx| {
1598 .on_click(move |_, _, cx| {
1556 let selection = selection.clone();
1599 let selection = selection.clone();
1557 state.update(cx, |state, cx| state.select(selection, cx));
1600 state.update(cx, |state, cx| state.select(selection, cx));
@@ -1600,14 +1643,19 @@ impl SidebarView {
1600 channel,
1643 channel,
1601 is_selected,
1644 is_selected,
1602 entry.channel_notifications(&channel.id),
1645 entry.channel_notifications(&channel.id),
1646 channel_badge(entry, &channel.id),
1603 ));
1647 ));
1604 }
1648 }
1605 }
1649 }
1606 list = list.child(self.plain_header(TEAMS_LABEL));
1650 list = list.child(self.plain_header(TEAMS_LABEL));
1607 let (shown_teams, hidden_teams): (Vec<&SidebarTeam>, Vec<&SidebarTeam>) =
1651 let hidden_teams: Vec<&SidebarTeam> =
1608 sidebar.teams.iter().partition(|entry| !entry.hidden);
1652 sidebar.teams.iter().filter(|entry| entry.hidden).collect();
1609 for entry in shown_teams {
1653 for entry in sidebar
1610 list = self.team_block(list, entry, selected.as_ref(), cx);
1654 .teams
1655 .iter()
1656 .filter(|entry| !entry.hidden || team_hoisted(entry))
1657 {
1658 list = self.team_block(list, entry, entry.hidden, selected.as_ref(), cx);
1611 }
1659 }
1612 if !hidden_teams.is_empty() {
1660 if !hidden_teams.is_empty() {
1613 let holds_selection = hidden_teams
1661 let holds_selection = hidden_teams
@@ -1626,7 +1674,7 @@ impl SidebarView {
1626 ));
1674 ));
1627 if open {
1675 if open {
1628 for entry in hidden_teams {
1676 for entry in hidden_teams {
1629 list = self.team_block(list, entry, selected.as_ref(), cx);
1677 list = self.team_block(list, entry, false, selected.as_ref(), cx);
1630 }
1678 }
1631 }
1679 }
1632 }
1680 }
@@ -1657,6 +1705,18 @@ fn name_color(style: NameStyle) -> Hsla {
1657 }
1705 }
1658}
1706}
1659
1707
1708fn mention_badge(badge: MentionBadge) -> AnyElement {
1709 match badge {
1710 MentionBadge::Count(count) => count_badge(count, false).into_any_element(),
1711 MentionBadge::Channel => {
1712 icon(IconName::Hash, MENTION_ICON_SIZE, theme::accent_text()).into_any_element()
1713 }
1714 MentionBadge::Team => {
1715 icon(IconName::Users, MENTION_ICON_SIZE, theme::accent_text()).into_any_element()
1716 }
1717 }
1718}
1719
1660fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1720fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1661 let name = match level {
1721 let name = match level {
1662 ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
1722 ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
@@ -1808,9 +1868,10 @@ impl Render for SidebarView {
1808 .child(self.chat_list_menu_button(cx))
1868 .child(self.chat_list_menu_button(cx))
1809 .child(self.new_chat_button(cx)),
1869 .child(self.new_chat_button(cx)),
1810 ),
1870 ),
1811 SidebarTab::Channels | SidebarTab::Calls | SidebarTab::Agents => {
1871 SidebarTab::Channels => {
1812 Some(page_header(self.tab.title()))
1872 Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))
1813 }
1873 }
1874 SidebarTab::Calls | SidebarTab::Agents => Some(page_header(self.tab.title())),
1814 SidebarTab::Activity | SidebarTab::Saved => None,
1875 SidebarTab::Activity | SidebarTab::Saved => None,
1815 };
1876 };
1816 v_flex()
1877 v_flex()
crates/chatsvc/assets/csa_skype_fetch.js added +38 −0
@@ -0,0 +1,38 @@
1 const cache = (window.__rustyTeamsSkype = window.__rustyTeamsSkype || {});
2 if (!cache.token || cache.expires <= Date.now() + 60000) {
3 const spaces = await acquire('https://api.spaces.skype.com', 'authorization.readwrite');
4 if (!spaces.token) return {status: 0, body: 'no token for authsvc'};
5 let response;
6 try {
7 response = await fetch('https://teams.cloud.microsoft/api/authsvc/v1.0/authz', {
8 method: 'POST',
9 headers: {Authorization: 'Bearer ' + spaces.token},
10 });
11 } catch (error) {
12 return {status: 0, body: 'authz_unreachable'};
13 }
14 if (!response.ok) return {status: 0, body: 'authz_http_' + response.status};
15 try {
16 const answer = await response.json();
17 cache.token = answer.tokens.skypeToken;
18 cache.expires = Date.now() + Number(answer.tokens.expiresIn || 0) * 1000;
19 cache.chatService = answer.regionGtms.chatService;
20 } catch (error) {
21 return {status: 0, body: 'authz_shape'};
22 }
23 }
24 const headers = {...args.headers, Authorization: 'Bearer ' + token, 'x-skypetoken': cache.token};
25 if (cache.chatService) headers['x-csendpoint'] = cache.chatService;
26 try {
27 const response = await fetch(args.url, {
28 method: args.method,
29 headers,
30 body: args.body === null ? undefined : JSON.stringify(args.body),
31 });
32 const text = await response.text();
33 let body = text;
34 try { body = text ? JSON.parse(text) : null; } catch (error) {}
35 return {status: response.status, retryAfter: response.headers.get('Retry-After'), body};
36 } catch (error) {
37 return {status: 0, body: String(error)};
38 }
@@ -0,0 +1,38 @@
1const cache = (window.__rustyTeamsSkype = window.__rustyTeamsSkype || {});
2if (!cache.token || cache.expires <= Date.now() + 60000) {
3 const spaces = await acquire('https://api.spaces.skype.com', 'authorization.readwrite');
4 if (!spaces.token) return {status: 0, body: 'no token for authsvc'};
5 let response;
6 try {
7 response = await fetch('https://teams.cloud.microsoft/api/authsvc/v1.0/authz', {
8 method: 'POST',
9 headers: {Authorization: 'Bearer ' + spaces.token},
10 });
11 } catch (error) {
12 return {status: 0, body: 'authz_unreachable'};
13 }
14 if (!response.ok) return {status: 0, body: 'authz_http_' + response.status};
15 try {
16 const answer = await response.json();
17 cache.token = answer.tokens.skypeToken;
18 cache.expires = Date.now() + Number(answer.tokens.expiresIn || 0) * 1000;
19 cache.chatService = answer.regionGtms.chatService;
20 } catch (error) {
21 return {status: 0, body: 'authz_shape'};
22 }
23}
24const headers = {...args.headers, Authorization: 'Bearer ' + token, 'x-skypetoken': cache.token};
25if (cache.chatService) headers['x-csendpoint'] = cache.chatService;
26try {
27 const response = await fetch(args.url, {
28 method: args.method,
29 headers,
30 body: args.body === null ? undefined : JSON.stringify(args.body),
31 });
32 const text = await response.text();
33 let body = text;
34 try { body = text ? JSON.parse(text) : null; } catch (error) {}
35 return {status: response.status, retryAfter: response.headers.get('Retry-After'), body};
36} catch (error) {
37 return {status: 0, body: String(error)};
38}
crates/chatsvc/src/activity_mentions.rs added +294 −0
@@ -0,0 +1,294 @@
1 use chrono::DateTime;
2 use serde_json::Value;
3 use session::{Request, Session};
4
5 use crate::error::{Error, Result};
6 use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success};
7 use crate::pins::DEFAULT_REGION;
8
9 const PAGE_SIZE: usize = 200;
10 const MAX_PAGES: usize = 3;
11 const MENTION_TYPES: [&str; 2] = ["mention", "mentionInCommunity"];
12
13 /// Who an @mention addressed, as Teams splits them in `ChannelActivitiesPublisher`.
14 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
15 pub enum MentionKind {
16 Personal,
17 Channel,
18 Team,
19 }
20
21 #[derive(Debug, Clone, PartialEq, Eq)]
22 pub struct MentionActivity {
23 pub activity_id: String,
24 pub kind: MentionKind,
25 pub source_thread_id: String,
26 pub source_message_id: Option<String>,
27 pub timestamp_ms: i64,
28 pub is_read: bool,
29 }
30
31 pub struct ActivityFeed<T: MessageTransport = SessionMessageTransport> {
32 transport: T,
33 stream_url: String,
34 }
35
36 impl ActivityFeed<SessionMessageTransport> {
37 pub fn new(session: &Session) -> Self {
38 ActivityFeed::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
39 }
40 }
41
42 impl<T: MessageTransport> ActivityFeed<T> {
43 pub fn with_transport(transport: T, region: &str) -> Self {
44 ActivityFeed {
45 transport,
46 stream_url: format!(
47 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/streams/notifications/messages"
48 ),
49 }
50 }
51
52 pub fn first_page_url(&self) -> String {
53 format!(
54 "{}?view=msnp24Equivalent|supportsMessageProperties&pageSize={PAGE_SIZE}&startTime=1",
55 self.stream_url
56 )
57 }
58
59 /// Newest activity pages, mentions only.
60 pub async fn mentions(&self) -> Result<Vec<MentionActivity>> {
61 let mut mentions = Vec::new();
62 let mut next_url = Some(self.first_page_url());
63 for _ in 0..MAX_PAGES {
64 let Some(url) = next_url.take() else {
65 break;
66 };
67 let answer = self.transport.send(Request::get(&url)).await?;
68 ensure_success(&answer)?;
69 mentions.extend(parse_mention_page(&answer.body)?);
70 next_url = answer
71 .body
72 .pointer("/_metadata/backwardLink")
73 .and_then(Value::as_str)
74 .filter(|link| !link.is_empty() && *link != url)
75 .map(str::to_owned);
76 }
77 Ok(mentions)
78 }
79 }
80
81 pub fn parse_mention_page(body: &Value) -> Result<Vec<MentionActivity>> {
82 let messages = body
83 .get("messages")
84 .and_then(Value::as_array)
85 .ok_or_else(|| Error::UnexpectedAnswer("activity messages missing".into()))?;
86 Ok(messages.iter().filter_map(mention_activity).collect())
87 }
88
89 fn object_property(properties: &Value, key: &str) -> Option<Value> {
90 match properties.get(key)? {
91 Value::String(text) => serde_json::from_str::<Value>(text)
92 .ok()
93 .filter(Value::is_object),
94 other if other.is_object() => Some(other.clone()),
95 _ => None,
96 }
97 }
98
99 fn text_of(value: &Value) -> Option<String> {
100 match value {
101 Value::String(text) if !text.is_empty() => Some(text.clone()),
102 Value::Number(number) => Some(number.to_string()),
103 _ => None,
104 }
105 }
106
107 fn flag(value: Option<&Value>) -> bool {
108 match value {
109 Some(Value::Bool(flag)) => *flag,
110 Some(Value::String(text)) => text.eq_ignore_ascii_case("true"),
111 _ => false,
112 }
113 }
114
115 fn timestamp_ms(value: &Value) -> Option<i64> {
116 match value {
117 Value::Number(number) => number.as_i64(),
118 Value::String(text) => text.parse::<i64>().ok().or_else(|| {
119 DateTime::parse_from_rfc3339(text)
120 .ok()
121 .map(|time| time.timestamp_millis())
122 }),
123 _ => None,
124 }
125 }
126
127 fn mention_kind(subtype: &str) -> Option<MentionKind> {
128 match subtype.to_ascii_lowercase().as_str() {
129 "person" | "tag" => Some(MentionKind::Personal),
130 "channel" => Some(MentionKind::Channel),
131 "team" => Some(MentionKind::Team),
132 _ => None,
133 }
134 }
135
136 fn mention_activity(message: &Value) -> Option<MentionActivity> {
137 let properties = message.get("properties")?;
138 let activity = object_property(properties, "activity")?;
139 let activity_type = activity.get("activityType")?.as_str()?;
140 if !MENTION_TYPES.contains(&activity_type) {
141 return None;
142 }
143 let kind = mention_kind(activity.get("activitySubtype")?.as_str()?)?;
144 Some(MentionActivity {
145 activity_id: activity
146 .get("activityId")
147 .and_then(text_of)
148 .or_else(|| message.get("id").and_then(text_of))?,
149 kind,
150 source_thread_id: activity.get("sourceThreadId")?.as_str()?.to_owned(),
151 source_message_id: activity.get("sourceMessageId").and_then(text_of),
152 timestamp_ms: activity
153 .get("activityTimestamp")
154 .and_then(timestamp_ms)
155 .unwrap_or(0),
156 is_read: flag(properties.get("isread")),
157 })
158 }
159
160 #[cfg(test)]
161 mod tests {
162 use std::collections::VecDeque;
163 use std::sync::Mutex;
164
165 use serde_json::json;
166 use session::ApiResponse;
167
168 use super::*;
169
170 struct Canned {
171 answers: Mutex<VecDeque<(u16, Value)>>,
172 requests: Mutex<Vec<Request>>,
173 }
174
175 impl MessageTransport for &Canned {
176 async fn send(&self, request: Request) -> Result<ApiResponse> {
177 self.requests.lock().unwrap().push(request);
178 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
179 Ok(ApiResponse {
180 status,
181 body,
182 retry_after: None,
183 })
184 }
185 }
186
187 fn activity_message(id: &str, activity: Value, isread: Option<&str>) -> Value {
188 let mut properties = json!({"activity": activity});
189 if let Some(isread) = isread {
190 properties["isread"] = json!(isread);
191 }
192 json!({"id": id, "messagetype": "Text", "properties": properties})
193 }
194
195 #[test]
196 fn keeps_mentions_and_maps_the_subtypes() {
197 let body = json!({"messages": [
198 activity_message("m1", json!({
199 "activityId": 101, "activityType": "mention", "activitySubtype": "person",
200 "sourceThreadId": "19:a@thread.tacv2", "sourceMessageId": 1791368000000_i64,
201 "activityTimestamp": "2026-10-17T08:00:00.000Z"
202 }), Some("true")),
203 activity_message("m2", json!({
204 "activityType": "mention", "activitySubtype": "tag",
205 "sourceThreadId": "19:a@thread.tacv2", "activityTimestamp": 1791368100000_i64
206 }), None),
207 activity_message("m3", json!({
208 "activityId": "103", "activityType": "mention", "activitySubtype": "channel",
209 "sourceThreadId": "19:b@thread.tacv2"
210 }), Some("false")),
211 activity_message("m4", json!({
212 "activityId": "104", "activityType": "mentionInCommunity", "activitySubtype": "team",
213 "sourceThreadId": "19:b@thread.tacv2"
214 }), None),
215 activity_message("m5", json!({
216 "activityId": "105", "activityType": "reply", "activitySubtype": "person",
217 "sourceThreadId": "19:b@thread.tacv2"
218 }), None),
219 activity_message("m6", json!({
220 "activityId": "106", "activityType": "mention", "activitySubtype": "everyone",
221 "sourceThreadId": "19:b@thread.tacv2"
222 }), None),
223 {"id": "m7", "properties": {}}
224 ]});
225 let mentions = parse_mention_page(&body).unwrap();
226 let kinds: Vec<(&str, MentionKind)> = mentions
227 .iter()
228 .map(|mention| (mention.activity_id.as_str(), mention.kind))
229 .collect();
230 assert_eq!(
231 kinds,
232 [
233 ("101", MentionKind::Personal),
234 ("m2", MentionKind::Personal),
235 ("103", MentionKind::Channel),
236 ("104", MentionKind::Team),
237 ]
238 );
239 assert!(mentions[0].is_read);
240 assert!(!mentions[1].is_read);
241 assert_eq!(
242 mentions[0].source_message_id.as_deref(),
243 Some("1791368000000")
244 );
245 assert_eq!(mentions[0].timestamp_ms, 1792224000000);
246 assert_eq!(mentions[1].timestamp_ms, 1791368100000);
247 assert_eq!(mentions[2].timestamp_ms, 0);
248 }
249
250 #[test]
251 fn reads_the_activity_when_it_is_a_json_string() {
252 let activity = json!({
253 "activityId": "7", "activityType": "mention", "activitySubtype": "person",
254 "sourceThreadId": "19:a@thread.tacv2"
255 });
256 let body = json!({"messages": [
257 activity_message("m1", Value::String(activity.to_string()), Some("True"))
258 ]});
259 let mentions = parse_mention_page(&body).unwrap();
260 assert_eq!(mentions.len(), 1);
261 assert!(mentions[0].is_read);
262 }
263
264 #[test]
265 fn an_answer_without_messages_is_unexpected() {
266 assert!(parse_mention_page(&json!({})).is_err());
267 }
268
269 #[tokio::test]
270 async fn pages_backward_through_the_stream() {
271 let transport = Canned {
272 answers: Mutex::new(
273 vec![
274 (
275 200,
276 json!({"messages": [], "_metadata": {"backwardLink": "https://next"}}),
277 ),
278 (200, json!({"messages": [], "_metadata": {"backwardLink": ""}})),
279 ]
280 .into(),
281 ),
282 requests: Mutex::new(Vec::new()),
283 };
284 let feed = ActivityFeed::with_transport(&transport, "emea");
285 assert!(feed.mentions().await.unwrap().is_empty());
286 let requests = transport.requests.lock().unwrap();
287 assert_eq!(
288 requests[0].url,
289 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/streams/notifications/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=200&startTime=1"
290 );
291 assert_eq!(requests[1].url, "https://next");
292 assert_eq!(requests.len(), 2);
293 }
294 }
@@ -0,0 +1,294 @@
1use chrono::DateTime;
2use serde_json::Value;
3use session::{Request, Session};
4
5use crate::error::{Error, Result};
6use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success};
7use crate::pins::DEFAULT_REGION;
8
9const PAGE_SIZE: usize = 200;
10const MAX_PAGES: usize = 3;
11const MENTION_TYPES: [&str; 2] = ["mention", "mentionInCommunity"];
12
13/// Who an @mention addressed, as Teams splits them in `ChannelActivitiesPublisher`.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum MentionKind {
16 Personal,
17 Channel,
18 Team,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct MentionActivity {
23 pub activity_id: String,
24 pub kind: MentionKind,
25 pub source_thread_id: String,
26 pub source_message_id: Option<String>,
27 pub timestamp_ms: i64,
28 pub is_read: bool,
29}
30
31pub struct ActivityFeed<T: MessageTransport = SessionMessageTransport> {
32 transport: T,
33 stream_url: String,
34}
35
36impl ActivityFeed<SessionMessageTransport> {
37 pub fn new(session: &Session) -> Self {
38 ActivityFeed::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
39 }
40}
41
42impl<T: MessageTransport> ActivityFeed<T> {
43 pub fn with_transport(transport: T, region: &str) -> Self {
44 ActivityFeed {
45 transport,
46 stream_url: format!(
47 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/streams/notifications/messages"
48 ),
49 }
50 }
51
52 pub fn first_page_url(&self) -> String {
53 format!(
54 "{}?view=msnp24Equivalent|supportsMessageProperties&pageSize={PAGE_SIZE}&startTime=1",
55 self.stream_url
56 )
57 }
58
59 /// Newest activity pages, mentions only.
60 pub async fn mentions(&self) -> Result<Vec<MentionActivity>> {
61 let mut mentions = Vec::new();
62 let mut next_url = Some(self.first_page_url());
63 for _ in 0..MAX_PAGES {
64 let Some(url) = next_url.take() else {
65 break;
66 };
67 let answer = self.transport.send(Request::get(&url)).await?;
68 ensure_success(&answer)?;
69 mentions.extend(parse_mention_page(&answer.body)?);
70 next_url = answer
71 .body
72 .pointer("/_metadata/backwardLink")
73 .and_then(Value::as_str)
74 .filter(|link| !link.is_empty() && *link != url)
75 .map(str::to_owned);
76 }
77 Ok(mentions)
78 }
79}
80
81pub fn parse_mention_page(body: &Value) -> Result<Vec<MentionActivity>> {
82 let messages = body
83 .get("messages")
84 .and_then(Value::as_array)
85 .ok_or_else(|| Error::UnexpectedAnswer("activity messages missing".into()))?;
86 Ok(messages.iter().filter_map(mention_activity).collect())
87}
88
89fn object_property(properties: &Value, key: &str) -> Option<Value> {
90 match properties.get(key)? {
91 Value::String(text) => serde_json::from_str::<Value>(text)
92 .ok()
93 .filter(Value::is_object),
94 other if other.is_object() => Some(other.clone()),
95 _ => None,
96 }
97}
98
99fn text_of(value: &Value) -> Option<String> {
100 match value {
101 Value::String(text) if !text.is_empty() => Some(text.clone()),
102 Value::Number(number) => Some(number.to_string()),
103 _ => None,
104 }
105}
106
107fn flag(value: Option<&Value>) -> bool {
108 match value {
109 Some(Value::Bool(flag)) => *flag,
110 Some(Value::String(text)) => text.eq_ignore_ascii_case("true"),
111 _ => false,
112 }
113}
114
115fn timestamp_ms(value: &Value) -> Option<i64> {
116 match value {
117 Value::Number(number) => number.as_i64(),
118 Value::String(text) => text.parse::<i64>().ok().or_else(|| {
119 DateTime::parse_from_rfc3339(text)
120 .ok()
121 .map(|time| time.timestamp_millis())
122 }),
123 _ => None,
124 }
125}
126
127fn mention_kind(subtype: &str) -> Option<MentionKind> {
128 match subtype.to_ascii_lowercase().as_str() {
129 "person" | "tag" => Some(MentionKind::Personal),
130 "channel" => Some(MentionKind::Channel),
131 "team" => Some(MentionKind::Team),
132 _ => None,
133 }
134}
135
136fn mention_activity(message: &Value) -> Option<MentionActivity> {
137 let properties = message.get("properties")?;
138 let activity = object_property(properties, "activity")?;
139 let activity_type = activity.get("activityType")?.as_str()?;
140 if !MENTION_TYPES.contains(&activity_type) {
141 return None;
142 }
143 let kind = mention_kind(activity.get("activitySubtype")?.as_str()?)?;
144 Some(MentionActivity {
145 activity_id: activity
146 .get("activityId")
147 .and_then(text_of)
148 .or_else(|| message.get("id").and_then(text_of))?,
149 kind,
150 source_thread_id: activity.get("sourceThreadId")?.as_str()?.to_owned(),
151 source_message_id: activity.get("sourceMessageId").and_then(text_of),
152 timestamp_ms: activity
153 .get("activityTimestamp")
154 .and_then(timestamp_ms)
155 .unwrap_or(0),
156 is_read: flag(properties.get("isread")),
157 })
158}
159
160#[cfg(test)]
161mod tests {
162 use std::collections::VecDeque;
163 use std::sync::Mutex;
164
165 use serde_json::json;
166 use session::ApiResponse;
167
168 use super::*;
169
170 struct Canned {
171 answers: Mutex<VecDeque<(u16, Value)>>,
172 requests: Mutex<Vec<Request>>,
173 }
174
175 impl MessageTransport for &Canned {
176 async fn send(&self, request: Request) -> Result<ApiResponse> {
177 self.requests.lock().unwrap().push(request);
178 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
179 Ok(ApiResponse {
180 status,
181 body,
182 retry_after: None,
183 })
184 }
185 }
186
187 fn activity_message(id: &str, activity: Value, isread: Option<&str>) -> Value {
188 let mut properties = json!({"activity": activity});
189 if let Some(isread) = isread {
190 properties["isread"] = json!(isread);
191 }
192 json!({"id": id, "messagetype": "Text", "properties": properties})
193 }
194
195 #[test]
196 fn keeps_mentions_and_maps_the_subtypes() {
197 let body = json!({"messages": [
198 activity_message("m1", json!({
199 "activityId": 101, "activityType": "mention", "activitySubtype": "person",
200 "sourceThreadId": "19:a@thread.tacv2", "sourceMessageId": 1791368000000_i64,
201 "activityTimestamp": "2026-10-17T08:00:00.000Z"
202 }), Some("true")),
203 activity_message("m2", json!({
204 "activityType": "mention", "activitySubtype": "tag",
205 "sourceThreadId": "19:a@thread.tacv2", "activityTimestamp": 1791368100000_i64
206 }), None),
207 activity_message("m3", json!({
208 "activityId": "103", "activityType": "mention", "activitySubtype": "channel",
209 "sourceThreadId": "19:b@thread.tacv2"
210 }), Some("false")),
211 activity_message("m4", json!({
212 "activityId": "104", "activityType": "mentionInCommunity", "activitySubtype": "team",
213 "sourceThreadId": "19:b@thread.tacv2"
214 }), None),
215 activity_message("m5", json!({
216 "activityId": "105", "activityType": "reply", "activitySubtype": "person",
217 "sourceThreadId": "19:b@thread.tacv2"
218 }), None),
219 activity_message("m6", json!({
220 "activityId": "106", "activityType": "mention", "activitySubtype": "everyone",
221 "sourceThreadId": "19:b@thread.tacv2"
222 }), None),
223 {"id": "m7", "properties": {}}
224 ]});
225 let mentions = parse_mention_page(&body).unwrap();
226 let kinds: Vec<(&str, MentionKind)> = mentions
227 .iter()
228 .map(|mention| (mention.activity_id.as_str(), mention.kind))
229 .collect();
230 assert_eq!(
231 kinds,
232 [
233 ("101", MentionKind::Personal),
234 ("m2", MentionKind::Personal),
235 ("103", MentionKind::Channel),
236 ("104", MentionKind::Team),
237 ]
238 );
239 assert!(mentions[0].is_read);
240 assert!(!mentions[1].is_read);
241 assert_eq!(
242 mentions[0].source_message_id.as_deref(),
243 Some("1791368000000")
244 );
245 assert_eq!(mentions[0].timestamp_ms, 1792224000000);
246 assert_eq!(mentions[1].timestamp_ms, 1791368100000);
247 assert_eq!(mentions[2].timestamp_ms, 0);
248 }
249
250 #[test]
251 fn reads_the_activity_when_it_is_a_json_string() {
252 let activity = json!({
253 "activityId": "7", "activityType": "mention", "activitySubtype": "person",
254 "sourceThreadId": "19:a@thread.tacv2"
255 });
256 let body = json!({"messages": [
257 activity_message("m1", Value::String(activity.to_string()), Some("True"))
258 ]});
259 let mentions = parse_mention_page(&body).unwrap();
260 assert_eq!(mentions.len(), 1);
261 assert!(mentions[0].is_read);
262 }
263
264 #[test]
265 fn an_answer_without_messages_is_unexpected() {
266 assert!(parse_mention_page(&json!({})).is_err());
267 }
268
269 #[tokio::test]
270 async fn pages_backward_through_the_stream() {
271 let transport = Canned {
272 answers: Mutex::new(
273 vec![
274 (
275 200,
276 json!({"messages": [], "_metadata": {"backwardLink": "https://next"}}),
277 ),
278 (200, json!({"messages": [], "_metadata": {"backwardLink": ""}})),
279 ]
280 .into(),
281 ),
282 requests: Mutex::new(Vec::new()),
283 };
284 let feed = ActivityFeed::with_transport(&transport, "emea");
285 assert!(feed.mentions().await.unwrap().is_empty());
286 let requests = transport.requests.lock().unwrap();
287 assert_eq!(
288 requests[0].url,
289 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/streams/notifications/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=200&startTime=1"
290 );
291 assert_eq!(requests[1].url, "https://next");
292 assert_eq!(requests.len(), 2);
293 }
294}
crates/chatsvc/src/lib.rs +6 −1
@@ -1,3 +1,4 @@
1 pub mod activity_mentions;
1 2 pub mod bot_profiles;
2 3 pub mod calendar;
3 4 pub mod calllog;
@@ -33,6 +34,7 @@ pub mod transcripts;
33 34 pub mod translate;
34 35 pub mod window;
35 36
37 pub use activity_mentions::{ActivityFeed, MentionActivity, MentionKind};
36 38 pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
37 39 pub use calendar::{
38 40 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
@@ -86,7 +88,10 @@ pub use recap::{
86 88 pub use receipts::{MemberHorizon, Receipts};
87 89 pub use recording_policy::{RecordingPolicy, parse_recording_policy};
88 90 pub use saved::SavedMessage;
89 pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
91 pub use settings::{
92 AppConsumptionHorizon, ChatSection, ChatSectionSettings, UserSettings,
93 parse_app_consumption_horizon,
94 };
90 95 pub use substrate_search::{
91 96 QueryRequest, QueryResults, QueryScope, SearchIdentity, SearchSession, SubstrateSearch,
92 97 Suggestions,
@@ -1,3 +1,4 @@
1pub mod activity_mentions;
1pub mod bot_profiles;
2pub mod bot_profiles;
2pub mod calendar;
3pub mod calendar;
3pub mod calllog;
4pub mod calllog;
@@ -33,6 +34,7 @@ pub mod transcripts;
33pub mod translate;
34pub mod translate;
34pub mod window;
35pub mod window;
35
36
37pub use activity_mentions::{ActivityFeed, MentionActivity, MentionKind};
36pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
38pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
37pub use calendar::{
39pub use calendar::{
38 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
40 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
@@ -86,7 +88,10 @@ pub use recap::{
86pub use receipts::{MemberHorizon, Receipts};
88pub use receipts::{MemberHorizon, Receipts};
87pub use recording_policy::{RecordingPolicy, parse_recording_policy};
89pub use recording_policy::{RecordingPolicy, parse_recording_policy};
88pub use saved::SavedMessage;
90pub use saved::SavedMessage;
89pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
91pub use settings::{
92 AppConsumptionHorizon, ChatSection, ChatSectionSettings, UserSettings,
93 parse_app_consumption_horizon,
94};
90pub use substrate_search::{
95pub use substrate_search::{
91 QueryRequest, QueryResults, QueryScope, SearchIdentity, SearchSession, SubstrateSearch,
96 QueryRequest, QueryResults, QueryScope, SearchIdentity, SearchSession, SubstrateSearch,
92 Suggestions,
97 Suggestions,
crates/chatsvc/src/messages.rs +17 −0
@@ -164,6 +164,23 @@ impl<T: MessageTransport> Messages<T> {
164 164 ensure_success(&answer)
165 165 }
166 166
167 pub async fn undelete_message(
168 &self,
169 conversation: &ConversationRef,
170 message_id: &str,
171 ) -> Result<()> {
172 let url = format!(
173 "{}/properties?name=deletetime",
174 self.message_url(conversation, message_id)
175 );
176 let body = json!({"deletetime": null});
177 let answer = self
178 .transport
179 .send(Request::with_body(Method::Delete, &url, body))
180 .await?;
181 ensure_success(&answer)
182 }
183
167 184 pub async fn set_emotion(
168 185 &self,
169 186 conversation: &ConversationRef,
@@ -164,6 +164,23 @@ impl<T: MessageTransport> Messages<T> {
164 ensure_success(&answer)
164 ensure_success(&answer)
165 }
165 }
166
166
167 pub async fn undelete_message(
168 &self,
169 conversation: &ConversationRef,
170 message_id: &str,
171 ) -> Result<()> {
172 let url = format!(
173 "{}/properties?name=deletetime",
174 self.message_url(conversation, message_id)
175 );
176 let body = json!({"deletetime": null});
177 let answer = self
178 .transport
179 .send(Request::with_body(Method::Delete, &url, body))
180 .await?;
181 ensure_success(&answer)
182 }
183
167 pub async fn set_emotion(
184 pub async fn set_emotion(
168 &self,
185 &self,
169 conversation: &ConversationRef,
186 conversation: &ConversationRef,
crates/chatsvc/src/pins/folders.rs +118 −24
@@ -51,7 +51,7 @@ impl Folders {
51 51
52 52 fn containing(&self, conversation_id: &str) -> Option<&Folder> {
53 53 self.folders.iter().find(|folder| {
54 folder.kind == FolderKind::UserCreated
54 matches!(folder.kind, FolderKind::Favorites | FolderKind::UserCreated)
55 55 && folder
56 56 .conversation_ids
57 57 .iter()
@@ -143,8 +143,54 @@ fn expanded_body(hierarchy_version: i64, expanded: bool) -> Value {
143 143 })
144 144 }
145 145
146 fn add_item(folder_id: &str, conversation_id: &str) -> Value {
147 json!({"action": "AddItem", "folderId": folder_id, "itemId": conversation_id})
146 fn add_item(folder_id: &str, conversation_id: &str, index: Option<usize>) -> Value {
147 let mut action = json!({"action": "AddItem", "folderId": folder_id, "itemId": conversation_id});
148 if let Some(index) = index {
149 action["itemIndex"] = json!(index);
150 }
151 action
152 }
153
154 fn reorder_items(folder_id: &str, conversation_ids: Vec<String>) -> Value {
155 json!({"action": "ReorderItems", "folderId": folder_id, "newItemsOrder": conversation_ids})
156 }
157
158 fn placed_order(conversation_ids: &[String], conversation_id: &str, index: usize) -> Vec<String> {
159 let mut order: Vec<String> = conversation_ids
160 .iter()
161 .filter(|id| *id != conversation_id)
162 .cloned()
163 .collect();
164 order.insert(index.min(order.len()), conversation_id.to_owned());
165 order
166 }
167
168 fn place_actions(
169 state: &Folders,
170 conversation_id: &str,
171 target_folder_id: &str,
172 index: Option<usize>,
173 ) -> Result<Vec<Value>> {
174 let target = state.find(target_folder_id)?;
175 if target
176 .conversation_ids
177 .iter()
178 .any(|id| id == conversation_id)
179 {
180 let Some(index) = index else {
181 return Ok(Vec::new());
182 };
183 let order = placed_order(&target.conversation_ids, conversation_id, index);
184 if order == target.conversation_ids {
185 return Ok(Vec::new());
186 }
187 return Ok(vec![reorder_items(target_folder_id, order)]);
188 }
189 let mut actions = vec![add_item(target_folder_id, conversation_id, index)];
190 if let Some(current) = state.containing(conversation_id) {
191 actions.push(remove_item(&current.id, conversation_id));
192 }
193 Ok(actions)
148 194 }
149 195
150 196 fn remove_item(folder_id: &str, conversation_id: &str) -> Value {
@@ -220,28 +266,10 @@ impl<T: CsaTransport> Pins<T> {
220 266 &self,
221 267 conversation_id: &str,
222 268 target_folder_id: &str,
269 index: Option<usize>,
223 270 ) -> Result<Folders> {
224 self.write_folders(|state| {
225 let target = state
226 .folders
227 .iter()
228 .find(|folder| folder.id == target_folder_id)
229 .ok_or_else(|| Error::UnknownFolder(target_folder_id.to_owned()))?;
230 if target
231 .conversation_ids
232 .iter()
233 .any(|id| id == conversation_id)
234 {
235 return Ok(Vec::new());
236 }
237 let mut actions = Vec::new();
238 if let Some(current) = state.containing(conversation_id) {
239 actions.push(remove_item(&current.id, conversation_id));
240 }
241 actions.push(add_item(target_folder_id, conversation_id));
242 Ok(actions)
243 })
244 .await
271 self.write_folders(|state| place_actions(state, conversation_id, target_folder_id, index))
272 .await
245 273 }
246 274
247 275 pub async fn remove_from_folder(
@@ -491,6 +519,72 @@ mod tests {
491 519 ));
492 520 }
493 521
522 fn state(folders: &[(&str, FolderKind, &[&str])]) -> Folders {
523 Folders {
524 hierarchy_version: 1,
525 folders: folders
526 .iter()
527 .map(|(id, kind, ids)| Folder {
528 id: (*id).to_owned(),
529 name: (*id).to_owned(),
530 kind: *kind,
531 expanded: true,
532 conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
533 })
534 .collect(),
535 order: Vec::new(),
536 }
537 }
538
539 #[test]
540 fn placing_inside_the_same_folder_sends_the_full_new_order() {
541 let folders = state(&[("fav", FolderKind::Favorites, &["a", "b", "c", "d"])]);
542 assert_eq!(
543 place_actions(&folders, "a", "fav", Some(2)).unwrap(),
544 [
545 json!({"action": "ReorderItems", "folderId": "fav", "newItemsOrder": ["b", "c", "a", "d"]})
546 ]
547 );
548 assert_eq!(
549 place_actions(&folders, "d", "fav", Some(1)).unwrap(),
550 [
551 json!({"action": "ReorderItems", "folderId": "fav", "newItemsOrder": ["a", "d", "b", "c"]})
552 ]
553 );
554 assert!(
555 place_actions(&folders, "b", "fav", Some(1))
556 .unwrap()
557 .is_empty()
558 );
559 assert!(
560 place_actions(&folders, "b", "fav", None)
561 .unwrap()
562 .is_empty()
563 );
564 }
565
566 #[test]
567 fn moving_out_of_favorites_adds_at_the_index_then_removes_like_teams() {
568 let folders = state(&[
569 ("fav", FolderKind::Favorites, &["a"]),
570 ("work", FolderKind::UserCreated, &["b", "c"]),
571 ]);
572 assert_eq!(
573 place_actions(&folders, "a", "work", Some(1)).unwrap(),
574 [
575 json!({"action": "AddItem", "folderId": "work", "itemId": "a", "itemIndex": 1}),
576 json!({"action": "RemoveItem", "folderId": "fav", "itemId": "a"}),
577 ]
578 );
579 assert_eq!(
580 place_actions(&folders, "b", "fav", None).unwrap(),
581 [
582 json!({"action": "AddItem", "folderId": "fav", "itemId": "b"}),
583 json!({"action": "RemoveItem", "folderId": "work", "itemId": "b"}),
584 ]
585 );
586 }
587
494 588 #[test]
495 589 fn write_body_puts_the_lock_before_the_fields() {
496 590 let write = FolderWrite::reread(Method::Put, Some("a"), json!({"folderName": "B"}));
@@ -51,7 +51,7 @@ impl Folders {
51
51
52 fn containing(&self, conversation_id: &str) -> Option<&Folder> {
52 fn containing(&self, conversation_id: &str) -> Option<&Folder> {
53 self.folders.iter().find(|folder| {
53 self.folders.iter().find(|folder| {
54 folder.kind == FolderKind::UserCreated
54 matches!(folder.kind, FolderKind::Favorites | FolderKind::UserCreated)
55 && folder
55 && folder
56 .conversation_ids
56 .conversation_ids
57 .iter()
57 .iter()
@@ -143,8 +143,54 @@ fn expanded_body(hierarchy_version: i64, expanded: bool) -> Value {
143 })
143 })
144}
144}
145
145
146fn add_item(folder_id: &str, conversation_id: &str) -> Value {
146fn add_item(folder_id: &str, conversation_id: &str, index: Option<usize>) -> Value {
147 json!({"action": "AddItem", "folderId": folder_id, "itemId": conversation_id})
147 let mut action = json!({"action": "AddItem", "folderId": folder_id, "itemId": conversation_id});
148 if let Some(index) = index {
149 action["itemIndex"] = json!(index);
150 }
151 action
152}
153
154fn reorder_items(folder_id: &str, conversation_ids: Vec<String>) -> Value {
155 json!({"action": "ReorderItems", "folderId": folder_id, "newItemsOrder": conversation_ids})
156}
157
158fn placed_order(conversation_ids: &[String], conversation_id: &str, index: usize) -> Vec<String> {
159 let mut order: Vec<String> = conversation_ids
160 .iter()
161 .filter(|id| *id != conversation_id)
162 .cloned()
163 .collect();
164 order.insert(index.min(order.len()), conversation_id.to_owned());
165 order
166}
167
168fn place_actions(
169 state: &Folders,
170 conversation_id: &str,
171 target_folder_id: &str,
172 index: Option<usize>,
173) -> Result<Vec<Value>> {
174 let target = state.find(target_folder_id)?;
175 if target
176 .conversation_ids
177 .iter()
178 .any(|id| id == conversation_id)
179 {
180 let Some(index) = index else {
181 return Ok(Vec::new());
182 };
183 let order = placed_order(&target.conversation_ids, conversation_id, index);
184 if order == target.conversation_ids {
185 return Ok(Vec::new());
186 }
187 return Ok(vec![reorder_items(target_folder_id, order)]);
188 }
189 let mut actions = vec![add_item(target_folder_id, conversation_id, index)];
190 if let Some(current) = state.containing(conversation_id) {
191 actions.push(remove_item(&current.id, conversation_id));
192 }
193 Ok(actions)
148}
194}
149
195
150fn remove_item(folder_id: &str, conversation_id: &str) -> Value {
196fn remove_item(folder_id: &str, conversation_id: &str) -> Value {
@@ -220,28 +266,10 @@ impl<T: CsaTransport> Pins<T> {
220 &self,
266 &self,
221 conversation_id: &str,
267 conversation_id: &str,
222 target_folder_id: &str,
268 target_folder_id: &str,
269 index: Option<usize>,
223 ) -> Result<Folders> {
270 ) -> Result<Folders> {
224 self.write_folders(|state| {
271 self.write_folders(|state| place_actions(state, conversation_id, target_folder_id, index))
225 let target = state
272 .await
226 .folders
227 .iter()
228 .find(|folder| folder.id == target_folder_id)
229 .ok_or_else(|| Error::UnknownFolder(target_folder_id.to_owned()))?;
230 if target
231 .conversation_ids
232 .iter()
233 .any(|id| id == conversation_id)
234 {
235 return Ok(Vec::new());
236 }
237 let mut actions = Vec::new();
238 if let Some(current) = state.containing(conversation_id) {
239 actions.push(remove_item(&current.id, conversation_id));
240 }
241 actions.push(add_item(target_folder_id, conversation_id));
242 Ok(actions)
243 })
244 .await
245 }
273 }
246
274
247 pub async fn remove_from_folder(
275 pub async fn remove_from_folder(
@@ -491,6 +519,72 @@ mod tests {
491 ));
519 ));
492 }
520 }
493
521
522 fn state(folders: &[(&str, FolderKind, &[&str])]) -> Folders {
523 Folders {
524 hierarchy_version: 1,
525 folders: folders
526 .iter()
527 .map(|(id, kind, ids)| Folder {
528 id: (*id).to_owned(),
529 name: (*id).to_owned(),
530 kind: *kind,
531 expanded: true,
532 conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
533 })
534 .collect(),
535 order: Vec::new(),
536 }
537 }
538
539 #[test]
540 fn placing_inside_the_same_folder_sends_the_full_new_order() {
541 let folders = state(&[("fav", FolderKind::Favorites, &["a", "b", "c", "d"])]);
542 assert_eq!(
543 place_actions(&folders, "a", "fav", Some(2)).unwrap(),
544 [
545 json!({"action": "ReorderItems", "folderId": "fav", "newItemsOrder": ["b", "c", "a", "d"]})
546 ]
547 );
548 assert_eq!(
549 place_actions(&folders, "d", "fav", Some(1)).unwrap(),
550 [
551 json!({"action": "ReorderItems", "folderId": "fav", "newItemsOrder": ["a", "d", "b", "c"]})
552 ]
553 );
554 assert!(
555 place_actions(&folders, "b", "fav", Some(1))
556 .unwrap()
557 .is_empty()
558 );
559 assert!(
560 place_actions(&folders, "b", "fav", None)
561 .unwrap()
562 .is_empty()
563 );
564 }
565
566 #[test]
567 fn moving_out_of_favorites_adds_at_the_index_then_removes_like_teams() {
568 let folders = state(&[
569 ("fav", FolderKind::Favorites, &["a"]),
570 ("work", FolderKind::UserCreated, &["b", "c"]),
571 ]);
572 assert_eq!(
573 place_actions(&folders, "a", "work", Some(1)).unwrap(),
574 [
575 json!({"action": "AddItem", "folderId": "work", "itemId": "a", "itemIndex": 1}),
576 json!({"action": "RemoveItem", "folderId": "fav", "itemId": "a"}),
577 ]
578 );
579 assert_eq!(
580 place_actions(&folders, "b", "fav", None).unwrap(),
581 [
582 json!({"action": "AddItem", "folderId": "fav", "itemId": "b"}),
583 json!({"action": "RemoveItem", "folderId": "work", "itemId": "b"}),
584 ]
585 );
586 }
587
494 #[test]
588 #[test]
495 fn write_body_puts_the_lock_before_the_fields() {
589 fn write_body_puts_the_lock_before_the_fields() {
496 let write = FolderWrite::reread(Method::Put, Some("a"), json!({"folderName": "B"}));
590 let write = FolderWrite::reread(Method::Put, Some("a"), json!({"folderName": "B"}));
crates/chatsvc/src/pins/mod.rs +9 −1
@@ -2,6 +2,7 @@ mod channels;
2 2 mod chats;
3 3 mod folders;
4 4 mod pinbar;
5 mod posts;
5 6 mod state;
6 7 mod teams;
7 8 mod transport;
@@ -10,9 +11,10 @@ use session::Session;
10 11
11 12 pub use folders::{Folder, FolderKind, Folders};
12 13 pub use pinbar::PinnedMessage;
14 pub use posts::{PINNED_POSTS_PAGE_SIZE, PinnedPostsPage, parse_pinned_posts};
13 15 pub use state::{PinnedChannels, PinnedChats};
14 16 pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};
15 pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};
17 pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport, SkypeTokenTransport};
16 18
17 19 pub const DEFAULT_REGION: &str = "emea";
18 20
@@ -32,6 +34,12 @@ impl Pins<SessionTransport> {
32 34 }
33 35 }
34 36
37 impl Pins<SkypeTokenTransport> {
38 pub fn with_skype_token(session: &Session) -> Self {
39 Pins::with_transport(SkypeTokenTransport::new(session), DEFAULT_REGION)
40 }
41 }
42
35 43 impl<T: CsaTransport> Pins<T> {
36 44 pub fn with_transport(transport: T, region: &str) -> Self {
37 45 Pins {
@@ -2,6 +2,7 @@ mod channels;
2mod chats;
2mod chats;
3mod folders;
3mod folders;
4mod pinbar;
4mod pinbar;
5mod posts;
5mod state;
6mod state;
6mod teams;
7mod teams;
7mod transport;
8mod transport;
@@ -10,9 +11,10 @@ use session::Session;
10
11
11pub use folders::{Folder, FolderKind, Folders};
12pub use folders::{Folder, FolderKind, Folders};
12pub use pinbar::PinnedMessage;
13pub use pinbar::PinnedMessage;
14pub use posts::{PINNED_POSTS_PAGE_SIZE, PinnedPostsPage, parse_pinned_posts};
13pub use state::{PinnedChannels, PinnedChats};
15pub use state::{PinnedChannels, PinnedChats};
14pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};
16pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};
15pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};
17pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport, SkypeTokenTransport};
16
18
17pub const DEFAULT_REGION: &str = "emea";
19pub const DEFAULT_REGION: &str = "emea";
18
20
@@ -32,6 +34,12 @@ impl Pins<SessionTransport> {
32 }
34 }
33}
35}
34
36
37impl Pins<SkypeTokenTransport> {
38 pub fn with_skype_token(session: &Session) -> Self {
39 Pins::with_transport(SkypeTokenTransport::new(session), DEFAULT_REGION)
40 }
41}
42
35impl<T: CsaTransport> Pins<T> {
43impl<T: CsaTransport> Pins<T> {
36 pub fn with_transport(transport: T, region: &str) -> Self {
44 pub fn with_transport(transport: T, region: &str) -> Self {
37 Pins {
45 Pins {
crates/chatsvc/src/pins/posts.rs added +310 −0
@@ -0,0 +1,310 @@
1 use chrono::{DateTime, Utc};
2 use serde_json::Value;
3 use session::{Method, Request};
4
5 use super::Pins;
6 use super::chats::{api_error, ensure_success};
7 use super::pinbar::PinnedMessage;
8 use super::transport::CsaTransport;
9 use crate::error::{Error, Result};
10 use crate::messages::encode;
11
12 pub const PINNED_POSTS_PAGE_SIZE: usize = 20;
13 const MAX_PINNED_POST_PAGES: usize = 10;
14 const CONTINUATION_HEADER: &str = "x-ms-continuation";
15
16 #[derive(Debug, Clone, PartialEq, Eq)]
17 pub struct PinnedPostsPage {
18 pub pins: Vec<PinnedMessage>,
19 pub continuation_token: Option<String>,
20 }
21
22 fn pinned_time(message: &Value) -> Option<DateTime<Utc>> {
23 let pinned = message.pointer("/properties/pinned")?;
24 let parsed;
25 let pinned = match pinned {
26 Value::String(text) => {
27 parsed = serde_json::from_str::<Value>(text).ok()?;
28 &parsed
29 }
30 other => other,
31 };
32 let millis = match pinned.get("pinnedTime")? {
33 Value::String(text) => text.parse::<i64>().ok()?,
34 other => other.as_i64()?,
35 };
36 DateTime::from_timestamp_millis(millis)
37 }
38
39 fn pinned_post(message: &Value) -> Option<PinnedMessage> {
40 let message_id = match message.get("id")? {
41 Value::String(text) => text.clone(),
42 Value::Number(number) => number.to_string(),
43 _ => return None,
44 };
45 Some(PinnedMessage {
46 message_id,
47 pinned_at: pinned_time(message),
48 parent_id: None,
49 })
50 }
51
52 pub fn parse_pinned_posts(body: &Value) -> Result<PinnedPostsPage> {
53 let messages = body
54 .get("messages")
55 .and_then(Value::as_array)
56 .ok_or_else(|| Error::UnexpectedAnswer("pinned posts messages missing".into()))?;
57 Ok(PinnedPostsPage {
58 pins: messages.iter().filter_map(pinned_post).collect(),
59 continuation_token: body
60 .get("continuationToken")
61 .and_then(Value::as_str)
62 .filter(|token| !token.is_empty())
63 .map(str::to_owned),
64 })
65 }
66
67 impl<T: CsaTransport> Pins<T> {
68 pub fn channel_url(&self, team_thread_id: &str, channel_id: &str) -> String {
69 format!(
70 "{}/teams/{}/channels/{}",
71 self.api_url,
72 encode(team_thread_id),
73 encode(channel_id)
74 )
75 }
76
77 pub fn pinned_posts_request(
78 &self,
79 team_thread_id: &str,
80 channel_id: &str,
81 continuation_token: Option<&str>,
82 ) -> Request {
83 let mut request = Request::get(format!(
84 "{}/pins?pageSize={PINNED_POSTS_PAGE_SIZE}",
85 self.channel_url(team_thread_id, channel_id)
86 ));
87 if let Some(token) = continuation_token {
88 request
89 .headers
90 .push((CONTINUATION_HEADER.to_owned(), token.to_owned()));
91 }
92 request
93 }
94
95 pub fn post_pin_request(
96 &self,
97 team_thread_id: &str,
98 channel_id: &str,
99 post_id: &str,
100 pinned: bool,
101 ) -> Request {
102 let url = format!(
103 "{}/posts/{post_id}/pin",
104 self.channel_url(team_thread_id, channel_id)
105 );
106 if pinned {
107 Request {
108 method: Method::Post,
109 ..Request::get(url)
110 }
111 } else {
112 Request::delete(url)
113 }
114 }
115
116 /// Pinned root posts in service order; only roots can be pinned while `enablePinMessageV2` is off.
117 pub async fn channel_pinned_posts(
118 &self,
119 team_thread_id: &str,
120 channel_id: &str,
121 ) -> Result<Vec<PinnedMessage>> {
122 let mut pins = Vec::new();
123 let mut continuation_token: Option<String> = None;
124 for _ in 0..MAX_PINNED_POST_PAGES {
125 let request = self.pinned_posts_request(
126 team_thread_id,
127 channel_id,
128 continuation_token.as_deref(),
129 );
130 let answer = self.transport.send(request).await?;
131 ensure_success(&answer)?;
132 let page = parse_pinned_posts(&answer.body)?;
133 pins.extend(page.pins);
134 match page.continuation_token {
135 Some(token) if Some(&token) != continuation_token.as_ref() => {
136 continuation_token = Some(token)
137 }
138 _ => break,
139 }
140 }
141 Ok(pins)
142 }
143
144 pub async fn set_post_pinned(
145 &self,
146 team_thread_id: &str,
147 channel_id: &str,
148 post_id: &str,
149 pinned: bool,
150 ) -> Result<()> {
151 let request = self.post_pin_request(team_thread_id, channel_id, post_id, pinned);
152 let answer = self.transport.send(request).await?;
153 if answer.is_success() {
154 Ok(())
155 } else {
156 Err(api_error(&answer))
157 }
158 }
159 }
160
161 #[cfg(test)]
162 mod tests {
163 use std::collections::VecDeque;
164 use std::sync::Mutex;
165
166 use serde_json::json;
167 use session::ApiResponse;
168
169 use super::*;
170
171 const TEAM: &str = "19:team@thread.tacv2";
172 const CHANNEL: &str = "19:channel@thread.tacv2";
173 const CHANNEL_URL: &str = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/19%3Ateam%40thread.tacv2/channels/19%3Achannel%40thread.tacv2";
174
175 struct Canned {
176 answers: Mutex<VecDeque<(u16, Value)>>,
177 requests: Mutex<Vec<Request>>,
178 }
179
180 impl CsaTransport for Canned {
181 async fn send(&self, request: Request) -> Result<ApiResponse> {
182 self.requests.lock().unwrap().push(request);
183 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
184 Ok(ApiResponse {
185 status,
186 body,
187 retry_after: None,
188 })
189 }
190 }
191
192 fn canned(answers: Vec<(u16, Value)>) -> Pins<Canned> {
193 Pins::with_transport(
194 Canned {
195 answers: Mutex::new(answers.into()),
196 requests: Mutex::new(Vec::new()),
197 },
198 "emea",
199 )
200 }
201
202 #[test]
203 fn parses_ids_pinned_time_and_the_continuation() {
204 let body = json!({
205 "messages": [
206 {"id": "1791368000000", "parentMessageId": "1791368000000",
207 "properties": {"pinned": "{\"pinnedTime\":1791368500000}"}},
208 {"id": 1791367000000_i64, "properties": {"pinned": {"pinnedTime": "1791367500000"}}},
209 {"id": "1791366000000"},
210 {"content": "no id"}
211 ],
212 "continuationToken": "next-page"
213 });
214 let page = parse_pinned_posts(&body).unwrap();
215 let ids: Vec<&str> = page
216 .pins
217 .iter()
218 .map(|pin| pin.message_id.as_str())
219 .collect();
220 assert_eq!(ids, ["1791368000000", "1791367000000", "1791366000000"]);
221 assert_eq!(
222 page.pins[0].pinned_at.map(|time| time.timestamp_millis()),
223 Some(1791368500000)
224 );
225 assert_eq!(
226 page.pins[1].pinned_at.map(|time| time.timestamp_millis()),
227 Some(1791367500000)
228 );
229 assert_eq!(page.pins[2].pinned_at, None);
230 assert_eq!(page.continuation_token.as_deref(), Some("next-page"));
231 }
232
233 #[test]
234 fn an_answer_without_messages_is_unexpected() {
235 assert!(matches!(
236 parse_pinned_posts(&json!({"continuationToken": "x"})),
237 Err(Error::UnexpectedAnswer(_))
238 ));
239 }
240
241 #[test]
242 fn pin_and_unpin_hit_the_post_pin_url_without_a_body() {
243 let pins = canned(Vec::new());
244 let pin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", true);
245 assert_eq!(pin.method, Method::Post);
246 assert_eq!(pin.url, format!("{CHANNEL_URL}/posts/1791368000000/pin"));
247 assert_eq!(pin.body, None);
248 let unpin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", false);
249 assert_eq!(unpin.method, Method::Delete);
250 assert_eq!(unpin.url, pin.url);
251 assert_eq!(unpin.body, None);
252 }
253
254 #[tokio::test]
255 async fn pinned_posts_follow_the_continuation_header() {
256 let pins = canned(vec![
257 (
258 200,
259 json!({"messages": [{"id": "3"}, {"id": "2"}], "continuationToken": "page-2"}),
260 ),
261 (200, json!({"messages": [{"id": "1"}]})),
262 ]);
263 let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();
264 let ids: Vec<&str> = found.iter().map(|pin| pin.message_id.as_str()).collect();
265 assert_eq!(ids, ["3", "2", "1"]);
266 let requests = pins.transport.requests.lock().unwrap();
267 assert_eq!(requests[0].url, format!("{CHANNEL_URL}/pins?pageSize=20"));
268 assert!(requests[0].headers.is_empty());
269 assert_eq!(
270 requests[1].headers,
271 [("x-ms-continuation".to_owned(), "page-2".to_owned())]
272 );
273 }
274
275 #[tokio::test]
276 async fn a_repeated_continuation_stops_paging() {
277 let pins = canned(vec![
278 (
279 200,
280 json!({"messages": [{"id": "2"}], "continuationToken": "same"}),
281 ),
282 (
283 200,
284 json!({"messages": [{"id": "1"}], "continuationToken": "same"}),
285 ),
286 ]);
287 let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();
288 assert_eq!(found.len(), 2);
289 assert_eq!(pins.transport.requests.lock().unwrap().len(), 2);
290 }
291
292 #[tokio::test]
293 async fn failures_are_errors() {
294 let pins = canned(vec![(403, json!({})), (412, json!({}))]);
295 assert!(pins.channel_pinned_posts(TEAM, CHANNEL).await.is_err());
296 assert!(
297 pins.set_post_pinned(TEAM, CHANNEL, "1", true)
298 .await
299 .is_err()
300 );
301 }
302
303 #[tokio::test]
304 async fn unpin_accepts_no_content() {
305 let pins = canned(vec![(204, Value::Null)]);
306 pins.set_post_pinned(TEAM, CHANNEL, "1", false)
307 .await
308 .unwrap();
309 }
310 }
@@ -0,0 +1,310 @@
1use chrono::{DateTime, Utc};
2use serde_json::Value;
3use session::{Method, Request};
4
5use super::Pins;
6use super::chats::{api_error, ensure_success};
7use super::pinbar::PinnedMessage;
8use super::transport::CsaTransport;
9use crate::error::{Error, Result};
10use crate::messages::encode;
11
12pub const PINNED_POSTS_PAGE_SIZE: usize = 20;
13const MAX_PINNED_POST_PAGES: usize = 10;
14const CONTINUATION_HEADER: &str = "x-ms-continuation";
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct PinnedPostsPage {
18 pub pins: Vec<PinnedMessage>,
19 pub continuation_token: Option<String>,
20}
21
22fn pinned_time(message: &Value) -> Option<DateTime<Utc>> {
23 let pinned = message.pointer("/properties/pinned")?;
24 let parsed;
25 let pinned = match pinned {
26 Value::String(text) => {
27 parsed = serde_json::from_str::<Value>(text).ok()?;
28 &parsed
29 }
30 other => other,
31 };
32 let millis = match pinned.get("pinnedTime")? {
33 Value::String(text) => text.parse::<i64>().ok()?,
34 other => other.as_i64()?,
35 };
36 DateTime::from_timestamp_millis(millis)
37}
38
39fn pinned_post(message: &Value) -> Option<PinnedMessage> {
40 let message_id = match message.get("id")? {
41 Value::String(text) => text.clone(),
42 Value::Number(number) => number.to_string(),
43 _ => return None,
44 };
45 Some(PinnedMessage {
46 message_id,
47 pinned_at: pinned_time(message),
48 parent_id: None,
49 })
50}
51
52pub fn parse_pinned_posts(body: &Value) -> Result<PinnedPostsPage> {
53 let messages = body
54 .get("messages")
55 .and_then(Value::as_array)
56 .ok_or_else(|| Error::UnexpectedAnswer("pinned posts messages missing".into()))?;
57 Ok(PinnedPostsPage {
58 pins: messages.iter().filter_map(pinned_post).collect(),
59 continuation_token: body
60 .get("continuationToken")
61 .and_then(Value::as_str)
62 .filter(|token| !token.is_empty())
63 .map(str::to_owned),
64 })
65}
66
67impl<T: CsaTransport> Pins<T> {
68 pub fn channel_url(&self, team_thread_id: &str, channel_id: &str) -> String {
69 format!(
70 "{}/teams/{}/channels/{}",
71 self.api_url,
72 encode(team_thread_id),
73 encode(channel_id)
74 )
75 }
76
77 pub fn pinned_posts_request(
78 &self,
79 team_thread_id: &str,
80 channel_id: &str,
81 continuation_token: Option<&str>,
82 ) -> Request {
83 let mut request = Request::get(format!(
84 "{}/pins?pageSize={PINNED_POSTS_PAGE_SIZE}",
85 self.channel_url(team_thread_id, channel_id)
86 ));
87 if let Some(token) = continuation_token {
88 request
89 .headers
90 .push((CONTINUATION_HEADER.to_owned(), token.to_owned()));
91 }
92 request
93 }
94
95 pub fn post_pin_request(
96 &self,
97 team_thread_id: &str,
98 channel_id: &str,
99 post_id: &str,
100 pinned: bool,
101 ) -> Request {
102 let url = format!(
103 "{}/posts/{post_id}/pin",
104 self.channel_url(team_thread_id, channel_id)
105 );
106 if pinned {
107 Request {
108 method: Method::Post,
109 ..Request::get(url)
110 }
111 } else {
112 Request::delete(url)
113 }
114 }
115
116 /// Pinned root posts in service order; only roots can be pinned while `enablePinMessageV2` is off.
117 pub async fn channel_pinned_posts(
118 &self,
119 team_thread_id: &str,
120 channel_id: &str,
121 ) -> Result<Vec<PinnedMessage>> {
122 let mut pins = Vec::new();
123 let mut continuation_token: Option<String> = None;
124 for _ in 0..MAX_PINNED_POST_PAGES {
125 let request = self.pinned_posts_request(
126 team_thread_id,
127 channel_id,
128 continuation_token.as_deref(),
129 );
130 let answer = self.transport.send(request).await?;
131 ensure_success(&answer)?;
132 let page = parse_pinned_posts(&answer.body)?;
133 pins.extend(page.pins);
134 match page.continuation_token {
135 Some(token) if Some(&token) != continuation_token.as_ref() => {
136 continuation_token = Some(token)
137 }
138 _ => break,
139 }
140 }
141 Ok(pins)
142 }
143
144 pub async fn set_post_pinned(
145 &self,
146 team_thread_id: &str,
147 channel_id: &str,
148 post_id: &str,
149 pinned: bool,
150 ) -> Result<()> {
151 let request = self.post_pin_request(team_thread_id, channel_id, post_id, pinned);
152 let answer = self.transport.send(request).await?;
153 if answer.is_success() {
154 Ok(())
155 } else {
156 Err(api_error(&answer))
157 }
158 }
159}
160
161#[cfg(test)]
162mod tests {
163 use std::collections::VecDeque;
164 use std::sync::Mutex;
165
166 use serde_json::json;
167 use session::ApiResponse;
168
169 use super::*;
170
171 const TEAM: &str = "19:team@thread.tacv2";
172 const CHANNEL: &str = "19:channel@thread.tacv2";
173 const CHANNEL_URL: &str = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/19%3Ateam%40thread.tacv2/channels/19%3Achannel%40thread.tacv2";
174
175 struct Canned {
176 answers: Mutex<VecDeque<(u16, Value)>>,
177 requests: Mutex<Vec<Request>>,
178 }
179
180 impl CsaTransport for Canned {
181 async fn send(&self, request: Request) -> Result<ApiResponse> {
182 self.requests.lock().unwrap().push(request);
183 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
184 Ok(ApiResponse {
185 status,
186 body,
187 retry_after: None,
188 })
189 }
190 }
191
192 fn canned(answers: Vec<(u16, Value)>) -> Pins<Canned> {
193 Pins::with_transport(
194 Canned {
195 answers: Mutex::new(answers.into()),
196 requests: Mutex::new(Vec::new()),
197 },
198 "emea",
199 )
200 }
201
202 #[test]
203 fn parses_ids_pinned_time_and_the_continuation() {
204 let body = json!({
205 "messages": [
206 {"id": "1791368000000", "parentMessageId": "1791368000000",
207 "properties": {"pinned": "{\"pinnedTime\":1791368500000}"}},
208 {"id": 1791367000000_i64, "properties": {"pinned": {"pinnedTime": "1791367500000"}}},
209 {"id": "1791366000000"},
210 {"content": "no id"}
211 ],
212 "continuationToken": "next-page"
213 });
214 let page = parse_pinned_posts(&body).unwrap();
215 let ids: Vec<&str> = page
216 .pins
217 .iter()
218 .map(|pin| pin.message_id.as_str())
219 .collect();
220 assert_eq!(ids, ["1791368000000", "1791367000000", "1791366000000"]);
221 assert_eq!(
222 page.pins[0].pinned_at.map(|time| time.timestamp_millis()),
223 Some(1791368500000)
224 );
225 assert_eq!(
226 page.pins[1].pinned_at.map(|time| time.timestamp_millis()),
227 Some(1791367500000)
228 );
229 assert_eq!(page.pins[2].pinned_at, None);
230 assert_eq!(page.continuation_token.as_deref(), Some("next-page"));
231 }
232
233 #[test]
234 fn an_answer_without_messages_is_unexpected() {
235 assert!(matches!(
236 parse_pinned_posts(&json!({"continuationToken": "x"})),
237 Err(Error::UnexpectedAnswer(_))
238 ));
239 }
240
241 #[test]
242 fn pin_and_unpin_hit_the_post_pin_url_without_a_body() {
243 let pins = canned(Vec::new());
244 let pin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", true);
245 assert_eq!(pin.method, Method::Post);
246 assert_eq!(pin.url, format!("{CHANNEL_URL}/posts/1791368000000/pin"));
247 assert_eq!(pin.body, None);
248 let unpin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", false);
249 assert_eq!(unpin.method, Method::Delete);
250 assert_eq!(unpin.url, pin.url);
251 assert_eq!(unpin.body, None);
252 }
253
254 #[tokio::test]
255 async fn pinned_posts_follow_the_continuation_header() {
256 let pins = canned(vec![
257 (
258 200,
259 json!({"messages": [{"id": "3"}, {"id": "2"}], "continuationToken": "page-2"}),
260 ),
261 (200, json!({"messages": [{"id": "1"}]})),
262 ]);
263 let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();
264 let ids: Vec<&str> = found.iter().map(|pin| pin.message_id.as_str()).collect();
265 assert_eq!(ids, ["3", "2", "1"]);
266 let requests = pins.transport.requests.lock().unwrap();
267 assert_eq!(requests[0].url, format!("{CHANNEL_URL}/pins?pageSize=20"));
268 assert!(requests[0].headers.is_empty());
269 assert_eq!(
270 requests[1].headers,
271 [("x-ms-continuation".to_owned(), "page-2".to_owned())]
272 );
273 }
274
275 #[tokio::test]
276 async fn a_repeated_continuation_stops_paging() {
277 let pins = canned(vec![
278 (
279 200,
280 json!({"messages": [{"id": "2"}], "continuationToken": "same"}),
281 ),
282 (
283 200,
284 json!({"messages": [{"id": "1"}], "continuationToken": "same"}),
285 ),
286 ]);
287 let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();
288 assert_eq!(found.len(), 2);
289 assert_eq!(pins.transport.requests.lock().unwrap().len(), 2);
290 }
291
292 #[tokio::test]
293 async fn failures_are_errors() {
294 let pins = canned(vec![(403, json!({})), (412, json!({}))]);
295 assert!(pins.channel_pinned_posts(TEAM, CHANNEL).await.is_err());
296 assert!(
297 pins.set_post_pinned(TEAM, CHANNEL, "1", true)
298 .await
299 .is_err()
300 );
301 }
302
303 #[tokio::test]
304 async fn unpin_accepts_no_content() {
305 let pins = canned(vec![(204, Value::Null)]);
306 pins.set_post_pinned(TEAM, CHANNEL, "1", false)
307 .await
308 .unwrap();
309 }
310}
crates/chatsvc/src/pins/transport.rs +103 −1
@@ -1,4 +1,5 @@
1 use session::{ApiResponse, Request, Scope, Session};
1 use serde_json::{Value, json};
2 use session::{ApiResponse, App, Request, Scope, Session};
2 3
3 4 use crate::error::Result;
4 5
@@ -33,3 +34,104 @@ impl CsaTransport for SessionTransport {
33 34 Ok(answers.remove(0))
34 35 }
35 36 }
37
38 const SKYPE_FETCH_BODY: &str = include_str!("../../assets/csa_skype_fetch.js");
39
40 /// Teams sends the skype token and the chat service endpoint next to the CSA bearer on the pinned post routes.
41 pub struct SkypeTokenTransport {
42 session: Session,
43 scope: Scope,
44 }
45
46 impl SkypeTokenTransport {
47 pub fn new(session: &Session) -> Self {
48 SkypeTokenTransport {
49 session: session.clone(),
50 scope: Scope::new(CSA_RESOURCE, CSA_SCOPE),
51 }
52 }
53 }
54
55 pub fn skype_fetch_args(request: &Request) -> Value {
56 let headers: serde_json::Map<String, Value> = request
57 .headers
58 .iter()
59 .map(|(name, value)| (name.clone(), Value::String(value.clone())))
60 .collect();
61 json!({
62 "method": request.method.as_str(),
63 "url": request.url,
64 "headers": headers,
65 "body": request.body,
66 })
67 }
68
69 pub fn skype_fetch_answer(answer: Value) -> ApiResponse {
70 ApiResponse {
71 status: answer
72 .get("status")
73 .and_then(Value::as_u64)
74 .and_then(|status| u16::try_from(status).ok())
75 .unwrap_or(0),
76 retry_after: answer
77 .get("retryAfter")
78 .and_then(Value::as_str)
79 .map(str::to_owned),
80 body: answer.get("body").cloned().unwrap_or(Value::Null),
81 }
82 }
83
84 impl CsaTransport for SkypeTokenTransport {
85 async fn send(&self, request: Request) -> Result<ApiResponse> {
86 let answer = self
87 .session
88 .run_with_token(
89 App::Teams,
90 &self.scope,
91 SKYPE_FETCH_BODY,
92 &skype_fetch_args(&request),
93 false,
94 )
95 .await?;
96 Ok(skype_fetch_answer(answer))
97 }
98 }
99
100 #[cfg(test)]
101 mod tests {
102 use session::Method;
103
104 use super::*;
105
106 #[test]
107 fn skype_fetch_args_carry_method_url_headers_and_body() {
108 let mut request = Request::delete("https://csa/pin");
109 request
110 .headers
111 .push(("x-ms-continuation".to_owned(), "next".to_owned()));
112 assert_eq!(
113 skype_fetch_args(&request),
114 json!({
115 "method": "DELETE",
116 "url": "https://csa/pin",
117 "headers": {"x-ms-continuation": "next"},
118 "body": null,
119 })
120 );
121 let post = Request {
122 method: Method::Post,
123 ..Request::get("https://csa/pin")
124 };
125 assert_eq!(skype_fetch_args(&post)["method"], "POST");
126 }
127
128 #[test]
129 fn page_answers_become_api_responses() {
130 let answer = skype_fetch_answer(json!({"status": 204, "retryAfter": null, "body": null}));
131 assert_eq!(answer.status, 204);
132 assert!(answer.is_success());
133 let failed = skype_fetch_answer(json!({"status": 0, "body": "authz_http_401"}));
134 assert!(!failed.is_success());
135 assert_eq!(failed.body, json!("authz_http_401"));
136 }
137 }
@@ -1,4 +1,5 @@
1use session::{ApiResponse, Request, Scope, Session};
1use serde_json::{Value, json};
2use session::{ApiResponse, App, Request, Scope, Session};
2
3
3use crate::error::Result;
4use crate::error::Result;
4
5
@@ -33,3 +34,104 @@ impl CsaTransport for SessionTransport {
33 Ok(answers.remove(0))
34 Ok(answers.remove(0))
34 }
35 }
35}
36}
37
38const SKYPE_FETCH_BODY: &str = include_str!("../../assets/csa_skype_fetch.js");
39
40/// Teams sends the skype token and the chat service endpoint next to the CSA bearer on the pinned post routes.
41pub struct SkypeTokenTransport {
42 session: Session,
43 scope: Scope,
44}
45
46impl SkypeTokenTransport {
47 pub fn new(session: &Session) -> Self {
48 SkypeTokenTransport {
49 session: session.clone(),
50 scope: Scope::new(CSA_RESOURCE, CSA_SCOPE),
51 }
52 }
53}
54
55pub fn skype_fetch_args(request: &Request) -> Value {
56 let headers: serde_json::Map<String, Value> = request
57 .headers
58 .iter()
59 .map(|(name, value)| (name.clone(), Value::String(value.clone())))
60 .collect();
61 json!({
62 "method": request.method.as_str(),
63 "url": request.url,
64 "headers": headers,
65 "body": request.body,
66 })
67}
68
69pub fn skype_fetch_answer(answer: Value) -> ApiResponse {
70 ApiResponse {
71 status: answer
72 .get("status")
73 .and_then(Value::as_u64)
74 .and_then(|status| u16::try_from(status).ok())
75 .unwrap_or(0),
76 retry_after: answer
77 .get("retryAfter")
78 .and_then(Value::as_str)
79 .map(str::to_owned),
80 body: answer.get("body").cloned().unwrap_or(Value::Null),
81 }
82}
83
84impl CsaTransport for SkypeTokenTransport {
85 async fn send(&self, request: Request) -> Result<ApiResponse> {
86 let answer = self
87 .session
88 .run_with_token(
89 App::Teams,
90 &self.scope,
91 SKYPE_FETCH_BODY,
92 &skype_fetch_args(&request),
93 false,
94 )
95 .await?;
96 Ok(skype_fetch_answer(answer))
97 }
98}
99
100#[cfg(test)]
101mod tests {
102 use session::Method;
103
104 use super::*;
105
106 #[test]
107 fn skype_fetch_args_carry_method_url_headers_and_body() {
108 let mut request = Request::delete("https://csa/pin");
109 request
110 .headers
111 .push(("x-ms-continuation".to_owned(), "next".to_owned()));
112 assert_eq!(
113 skype_fetch_args(&request),
114 json!({
115 "method": "DELETE",
116 "url": "https://csa/pin",
117 "headers": {"x-ms-continuation": "next"},
118 "body": null,
119 })
120 );
121 let post = Request {
122 method: Method::Post,
123 ..Request::get("https://csa/pin")
124 };
125 assert_eq!(skype_fetch_args(&post)["method"], "POST");
126 }
127
128 #[test]
129 fn page_answers_become_api_responses() {
130 let answer = skype_fetch_answer(json!({"status": 204, "retryAfter": null, "body": null}));
131 assert_eq!(answer.status, 204);
132 assert!(answer.is_success());
133 let failed = skype_fetch_answer(json!({"status": 0, "body": "authz_http_401"}));
134 assert!(!failed.is_success());
135 assert_eq!(failed.body, json!("authz_http_401"));
136 }
137}
crates/chatsvc/src/read_horizon.rs +42 −3
@@ -8,6 +8,7 @@ pub const PROPERTY_NAME: &str = "consumptionhorizon";
8 8 pub struct ReadHorizon {
9 9 pub consumed_until_ms: i64,
10 10 pub bookmark_ms: i64,
11 pub bookmark_timestamp_ms: i64,
11 12 pub bookmark_message_set: bool,
12 13 pub last_message_ms: i64,
13 14 pub last_message_from: Option<String>,
@@ -22,6 +23,7 @@ impl ReadHorizon {
22 23 ReadHorizon {
23 24 consumed_until_ms: horizon.arrival_ms,
24 25 bookmark_ms: bookmark.arrival_ms,
26 bookmark_timestamp_ms: bookmark.timestamp_ms,
25 27 bookmark_message_set: bookmark.message_set,
26 28 last_message_ms: last_message_ms(conversation),
27 29 last_message_from: last_message["from"]
@@ -33,10 +35,19 @@ impl ReadHorizon {
33 35 }
34 36
35 37 pub fn is_unread(&self, my_user_id: &str) -> bool {
36 if self.bookmark_ms != 0 && self.bookmark_message_set {
38 self.is_unread_after(my_user_id, 0)
39 }
40
41 /// `app_horizon_ms` is the `appConsumptionHorizon` entry of the conversation's app ("Mark all as read").
42 pub fn is_unread_after(&self, my_user_id: &str, app_horizon_ms: i64) -> bool {
43 let app_horizon_set = app_horizon_ms > 0;
44 let bookmark_cleared = app_horizon_set && app_horizon_ms >= self.bookmark_timestamp_ms;
45 let bookmark_ms = if bookmark_cleared { 0 } else { self.bookmark_ms };
46 if bookmark_ms != 0 && self.bookmark_message_set {
37 47 return true;
38 48 }
39 let unread = self.bookmark_ms != 0 || self.last_message_ms > self.consumed_until_ms;
49 let consumed_until_ms = self.consumed_until_ms.max(app_horizon_ms);
50 let unread = bookmark_ms != 0 || self.last_message_ms > consumed_until_ms;
40 51 let from_me = self
41 52 .last_message_from
42 53 .as_deref()
@@ -62,6 +73,7 @@ pub fn read_up_to(last_message_at: DateTime<Utc>, now: DateTime<Utc>) -> String
62 73
63 74 struct ParsedHorizon {
64 75 arrival_ms: i64,
76 timestamp_ms: i64,
65 77 message_set: bool,
66 78 }
67 79
@@ -70,6 +82,7 @@ fn parse_horizon(text: Option<&str>) -> ParsedHorizon {
70 82 let number = |part: &str| part.trim().parse::<i64>().ok();
71 83 let unset = ParsedHorizon {
72 84 arrival_ms: 0,
85 timestamp_ms: 0,
73 86 message_set: false,
74 87 };
75 88 let [arrival, timestamp, message_id] = parts.as_slice() else {
@@ -77,8 +90,9 @@ fn parse_horizon(text: Option<&str>) -> ParsedHorizon {
77 90 };
78 91 let message_id = message_id.trim();
79 92 match (number(arrival), number(timestamp)) {
80 (Some(arrival_ms), Some(_)) if !message_id.is_empty() => ParsedHorizon {
93 (Some(arrival_ms), Some(timestamp_ms)) if !message_id.is_empty() => ParsedHorizon {
81 94 arrival_ms,
95 timestamp_ms,
82 96 message_set: message_id != "0",
83 97 },
84 98 _ => unset,
@@ -192,6 +206,31 @@ mod tests {
192 206 assert!(unread(&value));
193 207 }
194 208
209 #[test]
210 fn app_horizon_reads_everything_that_arrived_before_it() {
211 let value = conversation(
212 Some("1791884440747;1791885752824;1"),
213 None,
214 Some(("2026-10-16T09:42:25.6780000Z", "8:orgid:other")),
215 );
216 let horizon = ReadHorizon::from_conversation(&value);
217 assert!(horizon.is_unread_after(ME, 0));
218 assert!(horizon.is_unread_after(ME, horizon.last_message_ms - 1));
219 assert!(!horizon.is_unread_after(ME, horizon.last_message_ms));
220 }
221
222 #[test]
223 fn app_horizon_clears_an_older_bookmark_only() {
224 let value = conversation(
225 Some("1792171970947;1792171971513;1"),
226 Some("1792171970000;1792171971513;42"),
227 Some(("2026-10-16T17:32:50.9470000Z", "8:orgid:other")),
228 );
229 let horizon = ReadHorizon::from_conversation(&value);
230 assert!(horizon.is_unread_after(ME, 1792171971512));
231 assert!(!horizon.is_unread_after(ME, 1792171971513));
232 }
233
195 234 #[test]
196 235 fn read_value_carries_the_last_arrival_and_now() {
197 236 let last = DateTime::from_timestamp_millis(1792182658901).unwrap();
@@ -8,6 +8,7 @@ pub const PROPERTY_NAME: &str = "consumptionhorizon";
8pub struct ReadHorizon {
8pub struct ReadHorizon {
9 pub consumed_until_ms: i64,
9 pub consumed_until_ms: i64,
10 pub bookmark_ms: i64,
10 pub bookmark_ms: i64,
11 pub bookmark_timestamp_ms: i64,
11 pub bookmark_message_set: bool,
12 pub bookmark_message_set: bool,
12 pub last_message_ms: i64,
13 pub last_message_ms: i64,
13 pub last_message_from: Option<String>,
14 pub last_message_from: Option<String>,
@@ -22,6 +23,7 @@ impl ReadHorizon {
22 ReadHorizon {
23 ReadHorizon {
23 consumed_until_ms: horizon.arrival_ms,
24 consumed_until_ms: horizon.arrival_ms,
24 bookmark_ms: bookmark.arrival_ms,
25 bookmark_ms: bookmark.arrival_ms,
26 bookmark_timestamp_ms: bookmark.timestamp_ms,
25 bookmark_message_set: bookmark.message_set,
27 bookmark_message_set: bookmark.message_set,
26 last_message_ms: last_message_ms(conversation),
28 last_message_ms: last_message_ms(conversation),
27 last_message_from: last_message["from"]
29 last_message_from: last_message["from"]
@@ -33,10 +35,19 @@ impl ReadHorizon {
33 }
35 }
34
36
35 pub fn is_unread(&self, my_user_id: &str) -> bool {
37 pub fn is_unread(&self, my_user_id: &str) -> bool {
36 if self.bookmark_ms != 0 && self.bookmark_message_set {
38 self.is_unread_after(my_user_id, 0)
39 }
40
41 /// `app_horizon_ms` is the `appConsumptionHorizon` entry of the conversation's app ("Mark all as read").
42 pub fn is_unread_after(&self, my_user_id: &str, app_horizon_ms: i64) -> bool {
43 let app_horizon_set = app_horizon_ms > 0;
44 let bookmark_cleared = app_horizon_set && app_horizon_ms >= self.bookmark_timestamp_ms;
45 let bookmark_ms = if bookmark_cleared { 0 } else { self.bookmark_ms };
46 if bookmark_ms != 0 && self.bookmark_message_set {
37 return true;
47 return true;
38 }
48 }
39 let unread = self.bookmark_ms != 0 || self.last_message_ms > self.consumed_until_ms;
49 let consumed_until_ms = self.consumed_until_ms.max(app_horizon_ms);
50 let unread = bookmark_ms != 0 || self.last_message_ms > consumed_until_ms;
40 let from_me = self
51 let from_me = self
41 .last_message_from
52 .last_message_from
42 .as_deref()
53 .as_deref()
@@ -62,6 +73,7 @@ pub fn read_up_to(last_message_at: DateTime<Utc>, now: DateTime<Utc>) -> String
62
73
63struct ParsedHorizon {
74struct ParsedHorizon {
64 arrival_ms: i64,
75 arrival_ms: i64,
76 timestamp_ms: i64,
65 message_set: bool,
77 message_set: bool,
66}
78}
67
79
@@ -70,6 +82,7 @@ fn parse_horizon(text: Option<&str>) -> ParsedHorizon {
70 let number = |part: &str| part.trim().parse::<i64>().ok();
82 let number = |part: &str| part.trim().parse::<i64>().ok();
71 let unset = ParsedHorizon {
83 let unset = ParsedHorizon {
72 arrival_ms: 0,
84 arrival_ms: 0,
85 timestamp_ms: 0,
73 message_set: false,
86 message_set: false,
74 };
87 };
75 let [arrival, timestamp, message_id] = parts.as_slice() else {
88 let [arrival, timestamp, message_id] = parts.as_slice() else {
@@ -77,8 +90,9 @@ fn parse_horizon(text: Option<&str>) -> ParsedHorizon {
77 };
90 };
78 let message_id = message_id.trim();
91 let message_id = message_id.trim();
79 match (number(arrival), number(timestamp)) {
92 match (number(arrival), number(timestamp)) {
80 (Some(arrival_ms), Some(_)) if !message_id.is_empty() => ParsedHorizon {
93 (Some(arrival_ms), Some(timestamp_ms)) if !message_id.is_empty() => ParsedHorizon {
81 arrival_ms,
94 arrival_ms,
95 timestamp_ms,
82 message_set: message_id != "0",
96 message_set: message_id != "0",
83 },
97 },
84 _ => unset,
98 _ => unset,
@@ -192,6 +206,31 @@ mod tests {
192 assert!(unread(&value));
206 assert!(unread(&value));
193 }
207 }
194
208
209 #[test]
210 fn app_horizon_reads_everything_that_arrived_before_it() {
211 let value = conversation(
212 Some("1791884440747;1791885752824;1"),
213 None,
214 Some(("2026-10-16T09:42:25.6780000Z", "8:orgid:other")),
215 );
216 let horizon = ReadHorizon::from_conversation(&value);
217 assert!(horizon.is_unread_after(ME, 0));
218 assert!(horizon.is_unread_after(ME, horizon.last_message_ms - 1));
219 assert!(!horizon.is_unread_after(ME, horizon.last_message_ms));
220 }
221
222 #[test]
223 fn app_horizon_clears_an_older_bookmark_only() {
224 let value = conversation(
225 Some("1792171970947;1792171971513;1"),
226 Some("1792171970000;1792171971513;42"),
227 Some(("2026-10-16T17:32:50.9470000Z", "8:orgid:other")),
228 );
229 let horizon = ReadHorizon::from_conversation(&value);
230 assert!(horizon.is_unread_after(ME, 1792171971512));
231 assert!(!horizon.is_unread_after(ME, 1792171971513));
232 }
233
195 #[test]
234 #[test]
196 fn read_value_carries_the_last_arrival_and_now() {
235 fn read_value_carries_the_last_arrival_and_now() {
197 let last = DateTime::from_timestamp_millis(1792182658901).unwrap();
236 let last = DateTime::from_timestamp_millis(1792182658901).unwrap();
crates/chatsvc/src/settings.rs +121 −0
@@ -10,6 +10,8 @@ const SETTINGS_ID: &str = "simpleCollabUserSettingsId";
10 10 const TEAMS_ORDER_KEY: &str = "teamsOrder";
11 11 const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
12 12 const DEFAULT_REACTIONS_KEY: &str = "defaultMessageReactions";
13 const APP_HORIZON_KEY: &str = "appConsumptionHorizon";
14 const APP_HORIZON_APPS: [&str; 3] = ["chat", "channel", "engage_community"];
13 15 const MAX_SKIN_TONE: u8 = 5;
14 16 const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
15 17 const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
@@ -104,6 +106,18 @@ impl<T: MessageTransport> UserSettings<T> {
104 106 .await
105 107 }
106 108
109 /// Teams' "Mark all as read" for channels: one write, the channel entry of `appConsumptionHorizon` moves to now.
110 pub async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {
111 let properties = self.properties().await?;
112 let horizon = AppConsumptionHorizon {
113 channel_ms: now_ms,
114 ..parse_app_consumption_horizon(&properties)
115 };
116 self.set_property(APP_HORIZON_KEY, Value::String(horizon.property_value()))
117 .await?;
118 Ok(horizon)
119 }
120
107 121 pub async fn set_property(&self, name: &str, value: Value) -> Result<()> {
108 122 let url = format!("{}?name={name}", self.base_url);
109 123 let mut body = Map::new();
@@ -200,6 +214,54 @@ pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {
200 214 order
201 215 }
202 216
217 /// Per app "read everything before" times in ms; Teams treats a conversation of that app as read up to it.
218 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
219 pub struct AppConsumptionHorizon {
220 pub chat_ms: i64,
221 pub channel_ms: i64,
222 pub engage_community_ms: i64,
223 }
224
225 impl AppConsumptionHorizon {
226 pub fn property_value(&self) -> String {
227 let values = [self.chat_ms, self.channel_ms, self.engage_community_ms];
228 let mut fields = Map::new();
229 for (app, value) in APP_HORIZON_APPS.iter().zip(values) {
230 fields.insert((*app).to_owned(), Value::from(value));
231 }
232 Value::Object(fields).to_string()
233 }
234 }
235
236 pub fn parse_app_consumption_horizon(properties: &Value) -> AppConsumptionHorizon {
237 let parsed = match properties.get(APP_HORIZON_KEY) {
238 Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
239 Some(other) => Some(other.clone()),
240 None => None,
241 };
242 let Some(fields) = parsed.as_ref().and_then(Value::as_object) else {
243 return AppConsumptionHorizon::default();
244 };
245 let valid = (fields.contains_key("chat") || fields.contains_key("channel"))
246 && fields
247 .values()
248 .all(|value| value.as_f64().is_some_and(|number| number >= 0.0));
249 if !valid {
250 return AppConsumptionHorizon::default();
251 }
252 let read = |app: &str| {
253 fields
254 .get(app)
255 .and_then(Value::as_f64)
256 .map_or(0, |number| number as i64)
257 };
258 AppConsumptionHorizon {
259 chat_ms: read("chat"),
260 channel_ms: read("channel"),
261 engage_community_ms: read("engage_community"),
262 }
263 }
264
203 265 pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {
204 266 let mut settings = stored_settings(properties);
205 267 settings
@@ -406,4 +468,63 @@ mod tests {
406 468 assert_eq!(value["keep"], json!(1));
407 469 assert_eq!(value["hasUserEnabledMutedChatSection"], json!(false));
408 470 }
471
472 #[test]
473 fn app_horizon_reads_the_string_and_ignores_invalid_values() {
474 let parsed = parse_app_consumption_horizon(&json!({
475 "appConsumptionHorizon": "{\"chat\":1791368000000,\"channel\":1791369000000,\"engage_community\":0}"
476 }));
477 assert_eq!(
478 parsed,
479 AppConsumptionHorizon {
480 chat_ms: 1791368000000,
481 channel_ms: 1791369000000,
482 engage_community_ms: 0,
483 }
484 );
485 let object = parse_app_consumption_horizon(&json!({"appConsumptionHorizon": {"channel": 5}}));
486 assert_eq!(object.channel_ms, 5);
487 for broken in [
488 json!({}),
489 json!({"appConsumptionHorizon": "not json"}),
490 json!({"appConsumptionHorizon": "{\"engage_community\":5}"}),
491 json!({"appConsumptionHorizon": "{\"channel\":-1}"}),
492 json!({"appConsumptionHorizon": "{\"channel\":\"5\"}"}),
493 ] {
494 assert_eq!(
495 parse_app_consumption_horizon(&broken),
496 AppConsumptionHorizon::default()
497 );
498 }
499 }
500
501 #[tokio::test]
502 async fn mark_all_channels_read_moves_only_the_channel_entry() {
503 let stored = json!({
504 "appConsumptionHorizon": "{\"chat\":100,\"channel\":200,\"engage_community\":300}"
505 });
506 let transport = Canned {
507 answers: Mutex::new(vec![(200, stored), (200, Value::Null)].into()),
508 requests: Mutex::new(Vec::new()),
509 };
510 let horizon = UserSettings::with_transport(&transport, "emea")
511 .mark_all_channels_read(1791368000000)
512 .await
513 .unwrap();
514 assert_eq!(horizon.channel_ms, 1791368000000);
515 let requests = transport.requests.lock().unwrap();
516 assert_eq!(requests[1].method, Method::Put);
517 assert_eq!(
518 requests[1].url,
519 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=appConsumptionHorizon"
520 );
521 let sent = requests[1].body.as_ref().unwrap()["appConsumptionHorizon"]
522 .as_str()
523 .unwrap();
524 let value: Value = serde_json::from_str(sent).unwrap();
525 assert_eq!(
526 value,
527 json!({"chat": 100, "channel": 1791368000000_i64, "engage_community": 300})
528 );
529 }
409 530 }
@@ -10,6 +10,8 @@ const SETTINGS_ID: &str = "simpleCollabUserSettingsId";
10const TEAMS_ORDER_KEY: &str = "teamsOrder";
10const TEAMS_ORDER_KEY: &str = "teamsOrder";
11const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
11const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
12const DEFAULT_REACTIONS_KEY: &str = "defaultMessageReactions";
12const DEFAULT_REACTIONS_KEY: &str = "defaultMessageReactions";
13const APP_HORIZON_KEY: &str = "appConsumptionHorizon";
14const APP_HORIZON_APPS: [&str; 3] = ["chat", "channel", "engage_community"];
13const MAX_SKIN_TONE: u8 = 5;
15const MAX_SKIN_TONE: u8 = 5;
14const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
16const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
15const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
17const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
@@ -104,6 +106,18 @@ impl<T: MessageTransport> UserSettings<T> {
104 .await
106 .await
105 }
107 }
106
108
109 /// Teams' "Mark all as read" for channels: one write, the channel entry of `appConsumptionHorizon` moves to now.
110 pub async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {
111 let properties = self.properties().await?;
112 let horizon = AppConsumptionHorizon {
113 channel_ms: now_ms,
114 ..parse_app_consumption_horizon(&properties)
115 };
116 self.set_property(APP_HORIZON_KEY, Value::String(horizon.property_value()))
117 .await?;
118 Ok(horizon)
119 }
120
107 pub async fn set_property(&self, name: &str, value: Value) -> Result<()> {
121 pub async fn set_property(&self, name: &str, value: Value) -> Result<()> {
108 let url = format!("{}?name={name}", self.base_url);
122 let url = format!("{}?name={name}", self.base_url);
109 let mut body = Map::new();
123 let mut body = Map::new();
@@ -200,6 +214,54 @@ pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {
200 order
214 order
201}
215}
202
216
217/// Per app "read everything before" times in ms; Teams treats a conversation of that app as read up to it.
218#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
219pub struct AppConsumptionHorizon {
220 pub chat_ms: i64,
221 pub channel_ms: i64,
222 pub engage_community_ms: i64,
223}
224
225impl AppConsumptionHorizon {
226 pub fn property_value(&self) -> String {
227 let values = [self.chat_ms, self.channel_ms, self.engage_community_ms];
228 let mut fields = Map::new();
229 for (app, value) in APP_HORIZON_APPS.iter().zip(values) {
230 fields.insert((*app).to_owned(), Value::from(value));
231 }
232 Value::Object(fields).to_string()
233 }
234}
235
236pub fn parse_app_consumption_horizon(properties: &Value) -> AppConsumptionHorizon {
237 let parsed = match properties.get(APP_HORIZON_KEY) {
238 Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
239 Some(other) => Some(other.clone()),
240 None => None,
241 };
242 let Some(fields) = parsed.as_ref().and_then(Value::as_object) else {
243 return AppConsumptionHorizon::default();
244 };
245 let valid = (fields.contains_key("chat") || fields.contains_key("channel"))
246 && fields
247 .values()
248 .all(|value| value.as_f64().is_some_and(|number| number >= 0.0));
249 if !valid {
250 return AppConsumptionHorizon::default();
251 }
252 let read = |app: &str| {
253 fields
254 .get(app)
255 .and_then(Value::as_f64)
256 .map_or(0, |number| number as i64)
257 };
258 AppConsumptionHorizon {
259 chat_ms: read("chat"),
260 channel_ms: read("channel"),
261 engage_community_ms: read("engage_community"),
262 }
263}
264
203pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {
265pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {
204 let mut settings = stored_settings(properties);
266 let mut settings = stored_settings(properties);
205 settings
267 settings
@@ -406,4 +468,63 @@ mod tests {
406 assert_eq!(value["keep"], json!(1));
468 assert_eq!(value["keep"], json!(1));
407 assert_eq!(value["hasUserEnabledMutedChatSection"], json!(false));
469 assert_eq!(value["hasUserEnabledMutedChatSection"], json!(false));
408 }
470 }
471
472 #[test]
473 fn app_horizon_reads_the_string_and_ignores_invalid_values() {
474 let parsed = parse_app_consumption_horizon(&json!({
475 "appConsumptionHorizon": "{\"chat\":1791368000000,\"channel\":1791369000000,\"engage_community\":0}"
476 }));
477 assert_eq!(
478 parsed,
479 AppConsumptionHorizon {
480 chat_ms: 1791368000000,
481 channel_ms: 1791369000000,
482 engage_community_ms: 0,
483 }
484 );
485 let object = parse_app_consumption_horizon(&json!({"appConsumptionHorizon": {"channel": 5}}));
486 assert_eq!(object.channel_ms, 5);
487 for broken in [
488 json!({}),
489 json!({"appConsumptionHorizon": "not json"}),
490 json!({"appConsumptionHorizon": "{\"engage_community\":5}"}),
491 json!({"appConsumptionHorizon": "{\"channel\":-1}"}),
492 json!({"appConsumptionHorizon": "{\"channel\":\"5\"}"}),
493 ] {
494 assert_eq!(
495 parse_app_consumption_horizon(&broken),
496 AppConsumptionHorizon::default()
497 );
498 }
499 }
500
501 #[tokio::test]
502 async fn mark_all_channels_read_moves_only_the_channel_entry() {
503 let stored = json!({
504 "appConsumptionHorizon": "{\"chat\":100,\"channel\":200,\"engage_community\":300}"
505 });
506 let transport = Canned {
507 answers: Mutex::new(vec![(200, stored), (200, Value::Null)].into()),
508 requests: Mutex::new(Vec::new()),
509 };
510 let horizon = UserSettings::with_transport(&transport, "emea")
511 .mark_all_channels_read(1791368000000)
512 .await
513 .unwrap();
514 assert_eq!(horizon.channel_ms, 1791368000000);
515 let requests = transport.requests.lock().unwrap();
516 assert_eq!(requests[1].method, Method::Put);
517 assert_eq!(
518 requests[1].url,
519 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=appConsumptionHorizon"
520 );
521 let sent = requests[1].body.as_ref().unwrap()["appConsumptionHorizon"]
522 .as_str()
523 .unwrap();
524 let value: Value = serde_json::from_str(sent).unwrap();
525 assert_eq!(
526 value,
527 json!({"chat": 100, "channel": 1791368000000_i64, "engage_community": 300})
528 );
529 }
409}
530}
crates/chatsvc/tests/messages.rs +20 −0
@@ -125,6 +125,26 @@ async fn delete_is_soft_without_a_body() {
125 125 assert!(requests[0].body.is_none());
126 126 }
127 127
128 #[tokio::test]
129 async fn undelete_clears_the_delete_time_property_like_teams() {
130 let mock = Mock::new(&[200]);
131 messages(&mock)
132 .undelete_message(&ConversationRef::chat("19:a@thread.v2"), "m1")
133 .await
134 .unwrap();
135 let requests = mock.requests();
136 assert_eq!(requests.len(), 1);
137 assert_eq!(requests[0].method, Method::Delete);
138 assert_eq!(
139 requests[0].url,
140 format!("{BASE}/19%3Aa%40thread.v2/messages/m1/properties?name=deletetime")
141 );
142 assert_eq!(
143 requests[0].body,
144 Some(serde_json::json!({"deletetime": null}))
145 );
146 }
147
128 148 #[tokio::test]
129 149 async fn edit_retries_once_on_404() {
130 150 let mock = Mock::new(&[404, 200]);
@@ -125,6 +125,26 @@ async fn delete_is_soft_without_a_body() {
125 assert!(requests[0].body.is_none());
125 assert!(requests[0].body.is_none());
126}
126}
127
127
128#[tokio::test]
129async fn undelete_clears_the_delete_time_property_like_teams() {
130 let mock = Mock::new(&[200]);
131 messages(&mock)
132 .undelete_message(&ConversationRef::chat("19:a@thread.v2"), "m1")
133 .await
134 .unwrap();
135 let requests = mock.requests();
136 assert_eq!(requests.len(), 1);
137 assert_eq!(requests[0].method, Method::Delete);
138 assert_eq!(
139 requests[0].url,
140 format!("{BASE}/19%3Aa%40thread.v2/messages/m1/properties?name=deletetime")
141 );
142 assert_eq!(
143 requests[0].body,
144 Some(serde_json::json!({"deletetime": null}))
145 );
146}
147
128#[tokio::test]
148#[tokio::test]
129async fn edit_retries_once_on_404() {
149async fn edit_retries_once_on_404() {
130 let mock = Mock::new(&[404, 200]);
150 let mock = Mock::new(&[404, 200]);
crates/chatsvc/tests/pins.rs +31 −10
@@ -384,20 +384,23 @@ fn sections(version: i64, custom: &[(&str, &[&str])], pinned: &[&str]) -> Value
384 384 }
385 385
386 386 #[tokio::test]
387 async fn move_to_folder_removes_from_the_current_custom_folder_then_adds_in_one_request() {
387 async fn move_to_folder_adds_then_removes_from_the_current_folder_in_one_request() {
388 388 let mock = Mock::new(vec![
389 389 (200, sections(10, &[("t~u~A", &["c"]), ("t~u~B", &[])], &[])),
390 390 (200, sections(11, &[("t~u~A", &[]), ("t~u~B", &["c"])], &[])),
391 391 ]);
392 let state = pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
392 let state = pins(&mock)
393 .move_to_folder("c", "t~u~B", None)
394 .await
395 .unwrap();
393 396 assert_eq!(state.folders[2].conversation_ids, ["c"]);
394 397 let body = sent(&mock)[1].2.clone().unwrap();
395 398 assert_eq!(body["folderHierarchyVersion"], 10);
396 399 assert_eq!(
397 400 body["actions"],
398 401 json!([
399 {"action": "RemoveItem", "folderId": "t~u~A", "itemId": "c"},
400 {"action": "AddItem", "folderId": "t~u~B", "itemId": "c"}
402 {"action": "AddItem", "folderId": "t~u~B", "itemId": "c"},
403 {"action": "RemoveItem", "folderId": "t~u~A", "itemId": "c"}
401 404 ])
402 405 );
403 406 }
@@ -408,7 +411,10 @@ async fn move_to_folder_without_a_current_folder_only_adds() {
408 411 (200, sections(10, &[("t~u~B", &[])], &[])),
409 412 (200, sections(11, &[("t~u~B", &["c"])], &[])),
410 413 ]);
411 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
414 pins(&mock)
415 .move_to_folder("c", "t~u~B", None)
416 .await
417 .unwrap();
412 418 assert_eq!(
413 419 sent(&mock)[1].2.as_ref().unwrap()["actions"]
414 420 .as_array()
@@ -425,7 +431,10 @@ async fn move_to_folder_retries_once_and_replans_from_the_412_state() {
425 431 (412, sections(15, &[("t~u~A", &["c"]), ("t~u~B", &[])], &[])),
426 432 (200, sections(16, &[("t~u~A", &[]), ("t~u~B", &["c"])], &[])),
427 433 ]);
428 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
434 pins(&mock)
435 .move_to_folder("c", "t~u~B", None)
436 .await
437 .unwrap();
429 438 let retry = sent(&mock)[2].2.clone().unwrap();
430 439 assert_eq!(retry["folderHierarchyVersion"], 15);
431 440 assert_eq!(retry["actions"].as_array().unwrap().len(), 2);
@@ -434,14 +443,20 @@ async fn move_to_folder_retries_once_and_replans_from_the_412_state() {
434 443 #[tokio::test]
435 444 async fn move_into_the_folder_it_is_already_in_sends_nothing() {
436 445 let mock = Mock::new(vec![(200, sections(10, &[("t~u~B", &["c"])], &[]))]);
437 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
446 pins(&mock)
447 .move_to_folder("c", "t~u~B", None)
448 .await
449 .unwrap();
438 450 assert_eq!(sent(&mock).len(), 1);
439 451 }
440 452
441 453 #[tokio::test]
442 454 async fn unknown_target_folder_is_typed() {
443 455 let mock = Mock::new(vec![(200, sections(10, &[], &[]))]);
444 let error = pins(&mock).move_to_folder("c", "nope").await.unwrap_err();
456 let error = pins(&mock)
457 .move_to_folder("c", "nope", None)
458 .await
459 .unwrap_err();
445 460 assert!(matches!(error, Error::UnknownFolder(_)));
446 461 }
447 462
@@ -584,13 +599,19 @@ async fn folder_action_posts_still_take_a_full_answer_as_state() {
584 599 (200, partial),
585 600 (200, sections(11, &[("t~u~B", &["c"])], &[])),
586 601 ]);
587 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
602 pins(&mock)
603 .move_to_folder("c", "t~u~B", None)
604 .await
605 .unwrap();
588 606 assert_eq!(sent(&mock).len(), 3);
589 607 let idle = Mock::new(vec![
590 608 (200, sections(10, &[("t~u~B", &[])], &[])),
591 609 (200, sections(11, &[("t~u~B", &["c"])], &[])),
592 610 ]);
593 pins(&idle).move_to_folder("c", "t~u~B").await.unwrap();
611 pins(&idle)
612 .move_to_folder("c", "t~u~B", None)
613 .await
614 .unwrap();
594 615 assert_eq!(sent(&idle).len(), 2);
595 616 }
596 617
@@ -384,20 +384,23 @@ fn sections(version: i64, custom: &[(&str, &[&str])], pinned: &[&str]) -> Value
384}
384}
385
385
386#[tokio::test]
386#[tokio::test]
387async fn move_to_folder_removes_from_the_current_custom_folder_then_adds_in_one_request() {
387async fn move_to_folder_adds_then_removes_from_the_current_folder_in_one_request() {
388 let mock = Mock::new(vec![
388 let mock = Mock::new(vec![
389 (200, sections(10, &[("t~u~A", &["c"]), ("t~u~B", &[])], &[])),
389 (200, sections(10, &[("t~u~A", &["c"]), ("t~u~B", &[])], &[])),
390 (200, sections(11, &[("t~u~A", &[]), ("t~u~B", &["c"])], &[])),
390 (200, sections(11, &[("t~u~A", &[]), ("t~u~B", &["c"])], &[])),
391 ]);
391 ]);
392 let state = pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
392 let state = pins(&mock)
393 .move_to_folder("c", "t~u~B", None)
394 .await
395 .unwrap();
393 assert_eq!(state.folders[2].conversation_ids, ["c"]);
396 assert_eq!(state.folders[2].conversation_ids, ["c"]);
394 let body = sent(&mock)[1].2.clone().unwrap();
397 let body = sent(&mock)[1].2.clone().unwrap();
395 assert_eq!(body["folderHierarchyVersion"], 10);
398 assert_eq!(body["folderHierarchyVersion"], 10);
396 assert_eq!(
399 assert_eq!(
397 body["actions"],
400 body["actions"],
398 json!([
401 json!([
399 {"action": "RemoveItem", "folderId": "t~u~A", "itemId": "c"},
402 {"action": "AddItem", "folderId": "t~u~B", "itemId": "c"},
400 {"action": "AddItem", "folderId": "t~u~B", "itemId": "c"}
403 {"action": "RemoveItem", "folderId": "t~u~A", "itemId": "c"}
401 ])
404 ])
402 );
405 );
403}
406}
@@ -408,7 +411,10 @@ async fn move_to_folder_without_a_current_folder_only_adds() {
408 (200, sections(10, &[("t~u~B", &[])], &[])),
411 (200, sections(10, &[("t~u~B", &[])], &[])),
409 (200, sections(11, &[("t~u~B", &["c"])], &[])),
412 (200, sections(11, &[("t~u~B", &["c"])], &[])),
410 ]);
413 ]);
411 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
414 pins(&mock)
415 .move_to_folder("c", "t~u~B", None)
416 .await
417 .unwrap();
412 assert_eq!(
418 assert_eq!(
413 sent(&mock)[1].2.as_ref().unwrap()["actions"]
419 sent(&mock)[1].2.as_ref().unwrap()["actions"]
414 .as_array()
420 .as_array()
@@ -425,7 +431,10 @@ async fn move_to_folder_retries_once_and_replans_from_the_412_state() {
425 (412, sections(15, &[("t~u~A", &["c"]), ("t~u~B", &[])], &[])),
431 (412, sections(15, &[("t~u~A", &["c"]), ("t~u~B", &[])], &[])),
426 (200, sections(16, &[("t~u~A", &[]), ("t~u~B", &["c"])], &[])),
432 (200, sections(16, &[("t~u~A", &[]), ("t~u~B", &["c"])], &[])),
427 ]);
433 ]);
428 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
434 pins(&mock)
435 .move_to_folder("c", "t~u~B", None)
436 .await
437 .unwrap();
429 let retry = sent(&mock)[2].2.clone().unwrap();
438 let retry = sent(&mock)[2].2.clone().unwrap();
430 assert_eq!(retry["folderHierarchyVersion"], 15);
439 assert_eq!(retry["folderHierarchyVersion"], 15);
431 assert_eq!(retry["actions"].as_array().unwrap().len(), 2);
440 assert_eq!(retry["actions"].as_array().unwrap().len(), 2);
@@ -434,14 +443,20 @@ async fn move_to_folder_retries_once_and_replans_from_the_412_state() {
434#[tokio::test]
443#[tokio::test]
435async fn move_into_the_folder_it_is_already_in_sends_nothing() {
444async fn move_into_the_folder_it_is_already_in_sends_nothing() {
436 let mock = Mock::new(vec![(200, sections(10, &[("t~u~B", &["c"])], &[]))]);
445 let mock = Mock::new(vec![(200, sections(10, &[("t~u~B", &["c"])], &[]))]);
437 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
446 pins(&mock)
447 .move_to_folder("c", "t~u~B", None)
448 .await
449 .unwrap();
438 assert_eq!(sent(&mock).len(), 1);
450 assert_eq!(sent(&mock).len(), 1);
439}
451}
440
452
441#[tokio::test]
453#[tokio::test]
442async fn unknown_target_folder_is_typed() {
454async fn unknown_target_folder_is_typed() {
443 let mock = Mock::new(vec![(200, sections(10, &[], &[]))]);
455 let mock = Mock::new(vec![(200, sections(10, &[], &[]))]);
444 let error = pins(&mock).move_to_folder("c", "nope").await.unwrap_err();
456 let error = pins(&mock)
457 .move_to_folder("c", "nope", None)
458 .await
459 .unwrap_err();
445 assert!(matches!(error, Error::UnknownFolder(_)));
460 assert!(matches!(error, Error::UnknownFolder(_)));
446}
461}
447
462
@@ -584,13 +599,19 @@ async fn folder_action_posts_still_take_a_full_answer_as_state() {
584 (200, partial),
599 (200, partial),
585 (200, sections(11, &[("t~u~B", &["c"])], &[])),
600 (200, sections(11, &[("t~u~B", &["c"])], &[])),
586 ]);
601 ]);
587 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
602 pins(&mock)
603 .move_to_folder("c", "t~u~B", None)
604 .await
605 .unwrap();
588 assert_eq!(sent(&mock).len(), 3);
606 assert_eq!(sent(&mock).len(), 3);
589 let idle = Mock::new(vec![
607 let idle = Mock::new(vec![
590 (200, sections(10, &[("t~u~B", &[])], &[])),
608 (200, sections(10, &[("t~u~B", &[])], &[])),
591 (200, sections(11, &[("t~u~B", &["c"])], &[])),
609 (200, sections(11, &[("t~u~B", &["c"])], &[])),
592 ]);
610 ]);
593 pins(&idle).move_to_folder("c", "t~u~B").await.unwrap();
611 pins(&idle)
612 .move_to_folder("c", "t~u~B", None)
613 .await
614 .unwrap();
594 assert_eq!(sent(&idle).len(), 2);
615 assert_eq!(sent(&idle).len(), 2);
595}
616}
596
617
crates/core/src/actions.rs +26 −0
@@ -392,6 +392,18 @@ impl<R: Remote> SyncEngine<R> {
392 392 )
393 393 .await?;
394 394 self.store.mark_channel_read(channel_id)?;
395 self.store.clear_channel_mentions(channel_id)?;
396 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
397 Ok(())
398 }
399
400 pub async fn mark_all_channels_read(&self) -> Result<()> {
401 let horizon = self
402 .remote
403 .mark_all_channels_read(Utc::now().timestamp_millis())
404 .await?;
405 *self.app_channel_horizon_ms.lock().unwrap() = horizon.channel_ms;
406 self.store.mark_all_channels_read()?;
395 407 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
396 408 Ok(())
397 409 }
@@ -641,6 +653,20 @@ impl<R: Remote> SyncEngine<R> {
641 653 Ok(())
642 654 }
643 655
656 pub async fn undo_soft_delete_message(
657 &self,
658 conversation_id: &str,
659 message_id: &str,
660 ) -> Result<()> {
661 let target = self.message_target(conversation_id, message_id)?;
662 let user_id = self.my_user_id().await?;
663 self.remote
664 .undo_soft_delete_message(&user_id, &target)
665 .await?;
666 self.refresh_message(conversation_id, message_id).await?;
667 Ok(())
668 }
669
644 670 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
645 671 Ok(match self.resolve_stored(conversation_id)? {
646 672 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
@@ -392,6 +392,18 @@ impl<R: Remote> SyncEngine<R> {
392 )
392 )
393 .await?;
393 .await?;
394 self.store.mark_channel_read(channel_id)?;
394 self.store.mark_channel_read(channel_id)?;
395 self.store.clear_channel_mentions(channel_id)?;
396 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
397 Ok(())
398 }
399
400 pub async fn mark_all_channels_read(&self) -> Result<()> {
401 let horizon = self
402 .remote
403 .mark_all_channels_read(Utc::now().timestamp_millis())
404 .await?;
405 *self.app_channel_horizon_ms.lock().unwrap() = horizon.channel_ms;
406 self.store.mark_all_channels_read()?;
395 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
407 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
396 Ok(())
408 Ok(())
397 }
409 }
@@ -641,6 +653,20 @@ impl<R: Remote> SyncEngine<R> {
641 Ok(())
653 Ok(())
642 }
654 }
643
655
656 pub async fn undo_soft_delete_message(
657 &self,
658 conversation_id: &str,
659 message_id: &str,
660 ) -> Result<()> {
661 let target = self.message_target(conversation_id, message_id)?;
662 let user_id = self.my_user_id().await?;
663 self.remote
664 .undo_soft_delete_message(&user_id, &target)
665 .await?;
666 self.refresh_message(conversation_id, message_id).await?;
667 Ok(())
668 }
669
644 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
670 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
645 Ok(match self.resolve_stored(conversation_id)? {
671 Ok(match self.resolve_stored(conversation_id)? {
646 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
672 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
crates/core/src/channel_mentions.rs added +132 −0
@@ -0,0 +1,132 @@
1 use std::collections::{HashMap, HashSet};
2
3 use chatsvc::{ConversationState, MentionActivity, MentionKind};
4 use store::ChannelMentions;
5
6 /// Teams counts a mention only while its channel is unread, it is newer than the read horizon and not read.
7 pub fn channel_mentions(
8 activities: &[MentionActivity],
9 states: &[ConversationState],
10 my_user_id: &str,
11 app_horizon_ms: i64,
12 ) -> Vec<(String, ChannelMentions)> {
13 let states: HashMap<&str, &ConversationState> = states
14 .iter()
15 .map(|state| (state.id.as_str(), state))
16 .collect();
17 let mut counted_activity_ids = HashSet::new();
18 let mut mentions: HashMap<String, ChannelMentions> = HashMap::new();
19 for activity in activities {
20 if activity.is_read || !counted_activity_ids.insert(activity.activity_id.as_str()) {
21 continue;
22 }
23 let Some(state) = states.get(activity.source_thread_id.as_str()) else {
24 continue;
25 };
26 let horizon_ms = state.read.consumed_until_ms.max(app_horizon_ms);
27 if activity.timestamp_ms <= horizon_ms
28 || !state.read.is_unread_after(my_user_id, app_horizon_ms)
29 {
30 continue;
31 }
32 let counts = mentions
33 .entry(activity.source_thread_id.clone())
34 .or_default();
35 match activity.kind {
36 MentionKind::Personal => counts.personal += 1,
37 MentionKind::Channel => counts.channel += 1,
38 MentionKind::Team => counts.team += 1,
39 }
40 }
41 let mut mentions: Vec<(String, ChannelMentions)> = mentions.into_iter().collect();
42 mentions.sort_by(|left, right| left.0.cmp(&right.0));
43 mentions
44 }
45
46 #[cfg(test)]
47 mod tests {
48 use chatsvc::ReadHorizon;
49
50 use super::*;
51
52 const ME: &str = "8:orgid:me";
53
54 fn state(id: &str, consumed_until_ms: i64, last_message_ms: i64) -> ConversationState {
55 ConversationState {
56 id: id.to_owned(),
57 muted: false,
58 hidden: None,
59 read: ReadHorizon {
60 consumed_until_ms,
61 last_message_ms,
62 last_message_from: Some("8:orgid:someone".to_owned()),
63 ..ReadHorizon::default()
64 },
65 }
66 }
67
68 fn activity(id: &str, thread: &str, kind: MentionKind, timestamp_ms: i64) -> MentionActivity {
69 MentionActivity {
70 activity_id: id.to_owned(),
71 kind,
72 source_thread_id: thread.to_owned(),
73 source_message_id: None,
74 timestamp_ms,
75 is_read: false,
76 }
77 }
78
79 fn counts(personal: u32, channel: u32, team: u32) -> ChannelMentions {
80 ChannelMentions {
81 personal,
82 channel,
83 team,
84 }
85 }
86
87 #[test]
88 fn counts_unread_mentions_after_the_horizon_per_kind() {
89 let states = [state("19:a", 100, 500), state("19:b", 100, 500)];
90 let activities = [
91 activity("1", "19:a", MentionKind::Personal, 200),
92 activity("2", "19:a", MentionKind::Personal, 300),
93 activity("2", "19:a", MentionKind::Personal, 300),
94 activity("3", "19:a", MentionKind::Channel, 300),
95 activity("4", "19:b", MentionKind::Team, 400),
96 activity("5", "19:a", MentionKind::Personal, 50),
97 MentionActivity {
98 is_read: true,
99 ..activity("6", "19:b", MentionKind::Personal, 400)
100 },
101 activity("7", "19:unknown", MentionKind::Personal, 400),
102 ];
103 assert_eq!(
104 channel_mentions(&activities, &states, ME, 0),
105 [
106 ("19:a".to_owned(), counts(2, 1, 0)),
107 ("19:b".to_owned(), counts(0, 0, 1)),
108 ]
109 );
110 }
111
112 #[test]
113 fn a_read_channel_has_no_mentions() {
114 let states = [state("19:a", 600, 500)];
115 let activities = [activity("1", "19:a", MentionKind::Personal, 550)];
116 assert!(channel_mentions(&activities, &states, ME, 0).is_empty());
117 }
118
119 #[test]
120 fn mark_all_as_read_hides_older_mentions() {
121 let states = [state("19:a", 100, 900)];
122 let activities = [
123 activity("1", "19:a", MentionKind::Personal, 300),
124 activity("2", "19:a", MentionKind::Personal, 800),
125 ];
126 assert_eq!(
127 channel_mentions(&activities, &states, ME, 500),
128 [("19:a".to_owned(), counts(1, 0, 0))]
129 );
130 assert!(channel_mentions(&activities, &states, ME, 950).is_empty());
131 }
132 }
@@ -0,0 +1,132 @@
1use std::collections::{HashMap, HashSet};
2
3use chatsvc::{ConversationState, MentionActivity, MentionKind};
4use store::ChannelMentions;
5
6/// Teams counts a mention only while its channel is unread, it is newer than the read horizon and not read.
7pub fn channel_mentions(
8 activities: &[MentionActivity],
9 states: &[ConversationState],
10 my_user_id: &str,
11 app_horizon_ms: i64,
12) -> Vec<(String, ChannelMentions)> {
13 let states: HashMap<&str, &ConversationState> = states
14 .iter()
15 .map(|state| (state.id.as_str(), state))
16 .collect();
17 let mut counted_activity_ids = HashSet::new();
18 let mut mentions: HashMap<String, ChannelMentions> = HashMap::new();
19 for activity in activities {
20 if activity.is_read || !counted_activity_ids.insert(activity.activity_id.as_str()) {
21 continue;
22 }
23 let Some(state) = states.get(activity.source_thread_id.as_str()) else {
24 continue;
25 };
26 let horizon_ms = state.read.consumed_until_ms.max(app_horizon_ms);
27 if activity.timestamp_ms <= horizon_ms
28 || !state.read.is_unread_after(my_user_id, app_horizon_ms)
29 {
30 continue;
31 }
32 let counts = mentions
33 .entry(activity.source_thread_id.clone())
34 .or_default();
35 match activity.kind {
36 MentionKind::Personal => counts.personal += 1,
37 MentionKind::Channel => counts.channel += 1,
38 MentionKind::Team => counts.team += 1,
39 }
40 }
41 let mut mentions: Vec<(String, ChannelMentions)> = mentions.into_iter().collect();
42 mentions.sort_by(|left, right| left.0.cmp(&right.0));
43 mentions
44}
45
46#[cfg(test)]
47mod tests {
48 use chatsvc::ReadHorizon;
49
50 use super::*;
51
52 const ME: &str = "8:orgid:me";
53
54 fn state(id: &str, consumed_until_ms: i64, last_message_ms: i64) -> ConversationState {
55 ConversationState {
56 id: id.to_owned(),
57 muted: false,
58 hidden: None,
59 read: ReadHorizon {
60 consumed_until_ms,
61 last_message_ms,
62 last_message_from: Some("8:orgid:someone".to_owned()),
63 ..ReadHorizon::default()
64 },
65 }
66 }
67
68 fn activity(id: &str, thread: &str, kind: MentionKind, timestamp_ms: i64) -> MentionActivity {
69 MentionActivity {
70 activity_id: id.to_owned(),
71 kind,
72 source_thread_id: thread.to_owned(),
73 source_message_id: None,
74 timestamp_ms,
75 is_read: false,
76 }
77 }
78
79 fn counts(personal: u32, channel: u32, team: u32) -> ChannelMentions {
80 ChannelMentions {
81 personal,
82 channel,
83 team,
84 }
85 }
86
87 #[test]
88 fn counts_unread_mentions_after_the_horizon_per_kind() {
89 let states = [state("19:a", 100, 500), state("19:b", 100, 500)];
90 let activities = [
91 activity("1", "19:a", MentionKind::Personal, 200),
92 activity("2", "19:a", MentionKind::Personal, 300),
93 activity("2", "19:a", MentionKind::Personal, 300),
94 activity("3", "19:a", MentionKind::Channel, 300),
95 activity("4", "19:b", MentionKind::Team, 400),
96 activity("5", "19:a", MentionKind::Personal, 50),
97 MentionActivity {
98 is_read: true,
99 ..activity("6", "19:b", MentionKind::Personal, 400)
100 },
101 activity("7", "19:unknown", MentionKind::Personal, 400),
102 ];
103 assert_eq!(
104 channel_mentions(&activities, &states, ME, 0),
105 [
106 ("19:a".to_owned(), counts(2, 1, 0)),
107 ("19:b".to_owned(), counts(0, 0, 1)),
108 ]
109 );
110 }
111
112 #[test]
113 fn a_read_channel_has_no_mentions() {
114 let states = [state("19:a", 600, 500)];
115 let activities = [activity("1", "19:a", MentionKind::Personal, 550)];
116 assert!(channel_mentions(&activities, &states, ME, 0).is_empty());
117 }
118
119 #[test]
120 fn mark_all_as_read_hides_older_mentions() {
121 let states = [state("19:a", 100, 900)];
122 let activities = [
123 activity("1", "19:a", MentionKind::Personal, 300),
124 activity("2", "19:a", MentionKind::Personal, 800),
125 ];
126 assert_eq!(
127 channel_mentions(&activities, &states, ME, 500),
128 [("19:a".to_owned(), counts(1, 0, 0))]
129 );
130 assert!(channel_mentions(&activities, &states, ME, 950).is_empty());
131 }
132}
crates/core/src/engine.rs +2 −0
@@ -131,6 +131,7 @@ pub struct SyncEngine<R: Remote = Graph> {
131 131 pub(crate) links_backfilled: Mutex<HashSet<String>>,
132 132 pub(crate) forwards_healed: Mutex<HashSet<String>>,
133 133 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
134 pub(crate) app_channel_horizon_ms: Mutex<i64>,
134 135 pub(crate) chat_paging: Mutex<ChatPaging>,
135 136 pub(crate) locally_hidden_lock: Mutex<()>,
136 137 pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,
@@ -167,6 +168,7 @@ impl<R: Remote> SyncEngine<R> {
167 168 links_backfilled: Mutex::new(HashSet::new()),
168 169 forwards_healed: Mutex::new(HashSet::new()),
169 170 chat_states: Mutex::new(HashMap::new()),
171 app_channel_horizon_ms: Mutex::new(0),
170 172 chat_paging,
171 173 locally_hidden_lock: Mutex::new(()),
172 174 bot_partners: Mutex::default(),
@@ -131,6 +131,7 @@ pub struct SyncEngine<R: Remote = Graph> {
131 pub(crate) links_backfilled: Mutex<HashSet<String>>,
131 pub(crate) links_backfilled: Mutex<HashSet<String>>,
132 pub(crate) forwards_healed: Mutex<HashSet<String>>,
132 pub(crate) forwards_healed: Mutex<HashSet<String>>,
133 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
133 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
134 pub(crate) app_channel_horizon_ms: Mutex<i64>,
134 pub(crate) chat_paging: Mutex<ChatPaging>,
135 pub(crate) chat_paging: Mutex<ChatPaging>,
135 pub(crate) locally_hidden_lock: Mutex<()>,
136 pub(crate) locally_hidden_lock: Mutex<()>,
136 pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,
137 pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,
@@ -167,6 +168,7 @@ impl<R: Remote> SyncEngine<R> {
167 links_backfilled: Mutex::new(HashSet::new()),
168 links_backfilled: Mutex::new(HashSet::new()),
168 forwards_healed: Mutex::new(HashSet::new()),
169 forwards_healed: Mutex::new(HashSet::new()),
169 chat_states: Mutex::new(HashMap::new()),
170 chat_states: Mutex::new(HashMap::new()),
171 app_channel_horizon_ms: Mutex::new(0),
170 chat_paging,
172 chat_paging,
171 locally_hidden_lock: Mutex::new(()),
173 locally_hidden_lock: Mutex::new(()),
172 bot_partners: Mutex::default(),
174 bot_partners: Mutex::default(),
crates/core/src/folders.rs +5 −2
@@ -92,6 +92,7 @@ pub trait FolderSource: Send + Sync {
92 92 &'a self,
93 93 conversation_id: &'a str,
94 94 target_folder_id: &'a str,
95 index: Option<usize>,
95 96 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
96 97 fn remove_from_folder<'a>(
97 98 &'a self,
@@ -229,11 +230,12 @@ impl FolderSource for ChatsvcFolderSource {
229 230 &'a self,
230 231 conversation_id: &'a str,
231 232 target_folder_id: &'a str,
233 index: Option<usize>,
232 234 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
233 235 Box::pin(async move {
234 236 Ok(convert(
235 237 self.pins
236 .move_to_folder(conversation_id, target_folder_id)
238 .move_to_folder(conversation_id, target_folder_id, index)
237 239 .await?,
238 240 ))
239 241 })
@@ -581,10 +583,11 @@ impl<R: Remote> SyncEngine<R> {
581 583 &self,
582 584 conversation_id: &str,
583 585 target_folder_id: &str,
586 index: Option<usize>,
584 587 ) -> Result<()> {
585 588 let folders = self
586 589 .folder_source()?
587 .move_to_folder(conversation_id, target_folder_id)
590 .move_to_folder(conversation_id, target_folder_id, index)
588 591 .await?;
589 592 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
590 593 }
@@ -92,6 +92,7 @@ pub trait FolderSource: Send + Sync {
92 &'a self,
92 &'a self,
93 conversation_id: &'a str,
93 conversation_id: &'a str,
94 target_folder_id: &'a str,
94 target_folder_id: &'a str,
95 index: Option<usize>,
95 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
96 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
96 fn remove_from_folder<'a>(
97 fn remove_from_folder<'a>(
97 &'a self,
98 &'a self,
@@ -229,11 +230,12 @@ impl FolderSource for ChatsvcFolderSource {
229 &'a self,
230 &'a self,
230 conversation_id: &'a str,
231 conversation_id: &'a str,
231 target_folder_id: &'a str,
232 target_folder_id: &'a str,
233 index: Option<usize>,
232 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
234 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
233 Box::pin(async move {
235 Box::pin(async move {
234 Ok(convert(
236 Ok(convert(
235 self.pins
237 self.pins
236 .move_to_folder(conversation_id, target_folder_id)
238 .move_to_folder(conversation_id, target_folder_id, index)
237 .await?,
239 .await?,
238 ))
240 ))
239 })
241 })
@@ -581,10 +583,11 @@ impl<R: Remote> SyncEngine<R> {
581 &self,
583 &self,
582 conversation_id: &str,
584 conversation_id: &str,
583 target_folder_id: &str,
585 target_folder_id: &str,
586 index: Option<usize>,
584 ) -> Result<()> {
587 ) -> Result<()> {
585 let folders = self
588 let folders = self
586 .folder_source()?
589 .folder_source()?
587 .move_to_folder(conversation_id, target_folder_id)
590 .move_to_folder(conversation_id, target_folder_id, index)
588 .await?;
591 .await?;
589 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
592 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
590 }
593 }
crates/core/src/lib.rs +1 −0
@@ -11,6 +11,7 @@ mod card_layout;
11 11 mod card_table;
12 12 mod card_widgets;
13 13 mod card_width;
14 mod channel_mentions;
14 15 mod channel_sync;
15 16 mod chat_paging;
16 17 mod default_reactions;
@@ -11,6 +11,7 @@ mod card_layout;
11mod card_table;
11mod card_table;
12mod card_widgets;
12mod card_widgets;
13mod card_width;
13mod card_width;
14mod channel_mentions;
14mod channel_sync;
15mod channel_sync;
15mod chat_paging;
16mod chat_paging;
16mod default_reactions;
17mod default_reactions;
crates/core/src/message_actions.rs +59 −20
@@ -68,32 +68,78 @@ impl<R: Remote> SyncEngine<R> {
68 68 self.remote.list_call_logs().await
69 69 }
70 70
71 pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
72 self.ensure_chat(chat_id)?;
73 self.remote.chat_pins(chat_id).await
71 pub async fn chat_pins(&self, conversation_id: &str) -> Result<Vec<PinnedMessage>> {
72 match self.resolve_stored(conversation_id)? {
73 Conversation::Chat => self.remote.chat_pins(conversation_id).await,
74 Conversation::Channel { team_id } => {
75 let team_thread_id = self.team_thread_id(&team_id)?;
76 self.remote
77 .channel_pinned_posts(&team_thread_id, conversation_id)
78 .await
79 }
80 }
74 81 }
75 82
76 pub async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
77 self.ensure_chat(chat_id)?;
78 self.remote.pin_message(chat_id, message_id).await?;
79 self.announce_pins(chat_id);
83 pub async fn pin_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {
84 match self.resolve_stored(conversation_id)? {
85 Conversation::Chat => self.remote.pin_message(conversation_id, message_id).await?,
86 Conversation::Channel { team_id } => {
87 self.set_post_pinned(&team_id, conversation_id, message_id, true)
88 .await?
89 }
90 }
91 self.announce_pins(conversation_id);
80 92 Ok(())
81 93 }
82 94
83 95 pub async fn unpin_message(
84 96 &self,
85 chat_id: &str,
97 conversation_id: &str,
86 98 message_id: &str,
87 99 parent_id: Option<&str>,
88 100 ) -> Result<()> {
89 self.ensure_chat(chat_id)?;
90 self.remote
91 .unpin_message(chat_id, message_id, parent_id)
92 .await?;
93 self.announce_pins(chat_id);
101 match self.resolve_stored(conversation_id)? {
102 Conversation::Chat => {
103 self.remote
104 .unpin_message(conversation_id, message_id, parent_id)
105 .await?
106 }
107 Conversation::Channel { team_id } => {
108 self.set_post_pinned(&team_id, conversation_id, message_id, false)
109 .await?
110 }
111 }
112 self.announce_pins(conversation_id);
94 113 Ok(())
95 114 }
96 115
116 async fn set_post_pinned(
117 &self,
118 team_id: &str,
119 channel_id: &str,
120 post_id: &str,
121 pinned: bool,
122 ) -> Result<()> {
123 let is_reply = self
124 .store
125 .messages_by_id(channel_id, &[post_id.to_owned()])?
126 .get(post_id)
127 .is_some_and(|record| record.reply_to_id.is_some());
128 if is_reply {
129 return Err(Error::Unsupported("pinning a channel reply"));
130 }
131 let team_thread_id = self.team_thread_id(team_id)?;
132 self.remote
133 .set_post_pinned(&team_thread_id, channel_id, post_id, pinned)
134 .await
135 }
136
137 fn team_thread_id(&self, team_id: &str) -> Result<String> {
138 self.store
139 .team_thread_id(team_id)?
140 .ok_or_else(|| Error::UnknownConversation(team_id.to_owned()))
141 }
142
97 143 pub async fn message_link(&self, conversation_id: &str, message_id: &str) -> Result<String> {
98 144 let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {
99 145 let notes_oid = if conversation_id == NOTES_CHAT_ID {
@@ -153,13 +199,6 @@ impl<R: Remote> SyncEngine<R> {
153 199 }
154 200 }
155 201
156 fn ensure_chat(&self, conversation_id: &str) -> Result<()> {
157 match self.resolve_stored(conversation_id)? {
158 Conversation::Chat => Ok(()),
159 Conversation::Channel { .. } => Err(Error::Unsupported("pinned messages in a channel")),
160 }
161 }
162
163 202 fn announce_pins(&self, conversation_id: &str) {
164 203 let _ = self.events.send(CoreEvent::PinsChanged {
165 204 conversation_id: conversation_id.to_owned(),
@@ -68,32 +68,78 @@ impl<R: Remote> SyncEngine<R> {
68 self.remote.list_call_logs().await
68 self.remote.list_call_logs().await
69 }
69 }
70
70
71 pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
71 pub async fn chat_pins(&self, conversation_id: &str) -> Result<Vec<PinnedMessage>> {
72 self.ensure_chat(chat_id)?;
72 match self.resolve_stored(conversation_id)? {
73 self.remote.chat_pins(chat_id).await
73 Conversation::Chat => self.remote.chat_pins(conversation_id).await,
74 Conversation::Channel { team_id } => {
75 let team_thread_id = self.team_thread_id(&team_id)?;
76 self.remote
77 .channel_pinned_posts(&team_thread_id, conversation_id)
78 .await
79 }
80 }
74 }
81 }
75
82
76 pub async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
83 pub async fn pin_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {
77 self.ensure_chat(chat_id)?;
84 match self.resolve_stored(conversation_id)? {
78 self.remote.pin_message(chat_id, message_id).await?;
85 Conversation::Chat => self.remote.pin_message(conversation_id, message_id).await?,
79 self.announce_pins(chat_id);
86 Conversation::Channel { team_id } => {
87 self.set_post_pinned(&team_id, conversation_id, message_id, true)
88 .await?
89 }
90 }
91 self.announce_pins(conversation_id);
80 Ok(())
92 Ok(())
81 }
93 }
82
94
83 pub async fn unpin_message(
95 pub async fn unpin_message(
84 &self,
96 &self,
85 chat_id: &str,
97 conversation_id: &str,
86 message_id: &str,
98 message_id: &str,
87 parent_id: Option<&str>,
99 parent_id: Option<&str>,
88 ) -> Result<()> {
100 ) -> Result<()> {
89 self.ensure_chat(chat_id)?;
101 match self.resolve_stored(conversation_id)? {
90 self.remote
102 Conversation::Chat => {
91 .unpin_message(chat_id, message_id, parent_id)
103 self.remote
92 .await?;
104 .unpin_message(conversation_id, message_id, parent_id)
93 self.announce_pins(chat_id);
105 .await?
106 }
107 Conversation::Channel { team_id } => {
108 self.set_post_pinned(&team_id, conversation_id, message_id, false)
109 .await?
110 }
111 }
112 self.announce_pins(conversation_id);
94 Ok(())
113 Ok(())
95 }
114 }
96
115
116 async fn set_post_pinned(
117 &self,
118 team_id: &str,
119 channel_id: &str,
120 post_id: &str,
121 pinned: bool,
122 ) -> Result<()> {
123 let is_reply = self
124 .store
125 .messages_by_id(channel_id, &[post_id.to_owned()])?
126 .get(post_id)
127 .is_some_and(|record| record.reply_to_id.is_some());
128 if is_reply {
129 return Err(Error::Unsupported("pinning a channel reply"));
130 }
131 let team_thread_id = self.team_thread_id(team_id)?;
132 self.remote
133 .set_post_pinned(&team_thread_id, channel_id, post_id, pinned)
134 .await
135 }
136
137 fn team_thread_id(&self, team_id: &str) -> Result<String> {
138 self.store
139 .team_thread_id(team_id)?
140 .ok_or_else(|| Error::UnknownConversation(team_id.to_owned()))
141 }
142
97 pub async fn message_link(&self, conversation_id: &str, message_id: &str) -> Result<String> {
143 pub async fn message_link(&self, conversation_id: &str, message_id: &str) -> Result<String> {
98 let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {
144 let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {
99 let notes_oid = if conversation_id == NOTES_CHAT_ID {
145 let notes_oid = if conversation_id == NOTES_CHAT_ID {
@@ -153,13 +199,6 @@ impl<R: Remote> SyncEngine<R> {
153 }
199 }
154 }
200 }
155
201
156 fn ensure_chat(&self, conversation_id: &str) -> Result<()> {
157 match self.resolve_stored(conversation_id)? {
158 Conversation::Chat => Ok(()),
159 Conversation::Channel { .. } => Err(Error::Unsupported("pinned messages in a channel")),
160 }
161 }
162
163 fn announce_pins(&self, conversation_id: &str) {
202 fn announce_pins(&self, conversation_id: &str) {
164 let _ = self.events.send(CoreEvent::PinsChanged {
203 let _ = self.events.send(CoreEvent::PinsChanged {
165 conversation_id: conversation_id.to_owned(),
204 conversation_id: conversation_id.to_owned(),
crates/core/src/remote.rs +81 −0
@@ -2,6 +2,10 @@ use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
2 2 use chatsvc::substrate_search::{
3 3 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
4 4 };
5 use chatsvc::{
6 ActivityFeed, AppConsumptionHorizon, MentionActivity, UserSettings,
7 parse_app_consumption_horizon,
8 };
5 9 use chatsvc::{
6 10 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
7 11 ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
@@ -158,6 +162,7 @@ pub trait Remote {
158 162 extras: &MessageExtras,
159 163 ) -> Result<()>;
160 164 async fn soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()>;
165 async fn undo_soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()>;
161 166 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat>;
162 167 async fn create_group(
163 168 &self,
@@ -358,6 +363,36 @@ pub trait Remote {
358 363 Err(Error::Unsupported("pinning messages"))
359 364 }
360 365
366 async fn channel_pinned_posts(
367 &self,
368 _team_thread_id: &str,
369 _channel_id: &str,
370 ) -> Result<Vec<PinnedMessage>> {
371 Err(Error::Unsupported("pinned channel posts"))
372 }
373
374 async fn set_post_pinned(
375 &self,
376 _team_thread_id: &str,
377 _channel_id: &str,
378 _post_id: &str,
379 _pinned: bool,
380 ) -> Result<()> {
381 Err(Error::Unsupported("pinning channel posts"))
382 }
383
384 async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {
385 Err(Error::Unsupported("the activity feed"))
386 }
387
388 async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
389 Ok(AppConsumptionHorizon::default())
390 }
391
392 async fn mark_all_channels_read(&self, _now_ms: i64) -> Result<AppConsumptionHorizon> {
393 Err(Error::Unsupported("marking all channels as read"))
394 }
395
361 396 async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {
362 397 Err(Error::Unsupported("chat apps"))
363 398 }
@@ -798,6 +833,15 @@ impl Remote for Graph {
798 833 }
799 834 }
800 835
836 async fn undo_soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()> {
837 match chatsvc_conversation(target) {
838 Some(conversation) => Ok(Messages::new(self.session())
839 .undelete_message(&conversation, target.message_id())
840 .await?),
841 None => Ok(Graph::undo_soft_delete_message(self, user_id, target).await?),
842 }
843 }
844
801 845 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
802 846 Ok(Graph::create_one_on_one(self, my_user_id, user_id).await?)
803 847 }
@@ -1057,6 +1101,43 @@ impl Remote for Graph {
1057 1101 .await?)
1058 1102 }
1059 1103
1104 async fn channel_pinned_posts(
1105 &self,
1106 team_thread_id: &str,
1107 channel_id: &str,
1108 ) -> Result<Vec<PinnedMessage>> {
1109 Ok(Pins::with_skype_token(self.session())
1110 .channel_pinned_posts(team_thread_id, channel_id)
1111 .await?)
1112 }
1113
1114 async fn set_post_pinned(
1115 &self,
1116 team_thread_id: &str,
1117 channel_id: &str,
1118 post_id: &str,
1119 pinned: bool,
1120 ) -> Result<()> {
1121 Ok(Pins::with_skype_token(self.session())
1122 .set_post_pinned(team_thread_id, channel_id, post_id, pinned)
1123 .await?)
1124 }
1125
1126 async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {
1127 Ok(ActivityFeed::new(self.session()).mentions().await?)
1128 }
1129
1130 async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
1131 let properties = UserSettings::new(self.session()).properties().await?;
1132 Ok(parse_app_consumption_horizon(&properties))
1133 }
1134
1135 async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {
1136 Ok(UserSettings::new(self.session())
1137 .mark_all_channels_read(now_ms)
1138 .await?)
1139 }
1140
1060 1141 async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {
1061 1142 Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)
1062 1143 }
@@ -2,6 +2,10 @@ use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
2use chatsvc::substrate_search::{
2use chatsvc::substrate_search::{
3 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
3 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
4};
4};
5use chatsvc::{
6 ActivityFeed, AppConsumptionHorizon, MentionActivity, UserSettings,
7 parse_app_consumption_horizon,
8};
5use chatsvc::{
9use chatsvc::{
6 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
10 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
7 ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
11 ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
@@ -158,6 +162,7 @@ pub trait Remote {
158 extras: &MessageExtras,
162 extras: &MessageExtras,
159 ) -> Result<()>;
163 ) -> Result<()>;
160 async fn soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()>;
164 async fn soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()>;
165 async fn undo_soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()>;
161 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat>;
166 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat>;
162 async fn create_group(
167 async fn create_group(
163 &self,
168 &self,
@@ -358,6 +363,36 @@ pub trait Remote {
358 Err(Error::Unsupported("pinning messages"))
363 Err(Error::Unsupported("pinning messages"))
359 }
364 }
360
365
366 async fn channel_pinned_posts(
367 &self,
368 _team_thread_id: &str,
369 _channel_id: &str,
370 ) -> Result<Vec<PinnedMessage>> {
371 Err(Error::Unsupported("pinned channel posts"))
372 }
373
374 async fn set_post_pinned(
375 &self,
376 _team_thread_id: &str,
377 _channel_id: &str,
378 _post_id: &str,
379 _pinned: bool,
380 ) -> Result<()> {
381 Err(Error::Unsupported("pinning channel posts"))
382 }
383
384 async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {
385 Err(Error::Unsupported("the activity feed"))
386 }
387
388 async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
389 Ok(AppConsumptionHorizon::default())
390 }
391
392 async fn mark_all_channels_read(&self, _now_ms: i64) -> Result<AppConsumptionHorizon> {
393 Err(Error::Unsupported("marking all channels as read"))
394 }
395
361 async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {
396 async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {
362 Err(Error::Unsupported("chat apps"))
397 Err(Error::Unsupported("chat apps"))
363 }
398 }
@@ -798,6 +833,15 @@ impl Remote for Graph {
798 }
833 }
799 }
834 }
800
835
836 async fn undo_soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()> {
837 match chatsvc_conversation(target) {
838 Some(conversation) => Ok(Messages::new(self.session())
839 .undelete_message(&conversation, target.message_id())
840 .await?),
841 None => Ok(Graph::undo_soft_delete_message(self, user_id, target).await?),
842 }
843 }
844
801 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
845 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
802 Ok(Graph::create_one_on_one(self, my_user_id, user_id).await?)
846 Ok(Graph::create_one_on_one(self, my_user_id, user_id).await?)
803 }
847 }
@@ -1057,6 +1101,43 @@ impl Remote for Graph {
1057 .await?)
1101 .await?)
1058 }
1102 }
1059
1103
1104 async fn channel_pinned_posts(
1105 &self,
1106 team_thread_id: &str,
1107 channel_id: &str,
1108 ) -> Result<Vec<PinnedMessage>> {
1109 Ok(Pins::with_skype_token(self.session())
1110 .channel_pinned_posts(team_thread_id, channel_id)
1111 .await?)
1112 }
1113
1114 async fn set_post_pinned(
1115 &self,
1116 team_thread_id: &str,
1117 channel_id: &str,
1118 post_id: &str,
1119 pinned: bool,
1120 ) -> Result<()> {
1121 Ok(Pins::with_skype_token(self.session())
1122 .set_post_pinned(team_thread_id, channel_id, post_id, pinned)
1123 .await?)
1124 }
1125
1126 async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {
1127 Ok(ActivityFeed::new(self.session()).mentions().await?)
1128 }
1129
1130 async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
1131 let properties = UserSettings::new(self.session()).properties().await?;
1132 Ok(parse_app_consumption_horizon(&properties))
1133 }
1134
1135 async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {
1136 Ok(UserSettings::new(self.session())
1137 .mark_all_channels_read(now_ms)
1138 .await?)
1139 }
1140
1060 async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {
1141 async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {
1061 Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)
1142 Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)
1062 }
1143 }
crates/core/src/sidebar_sync.rs +54 −6
@@ -1,13 +1,14 @@
1 1 use std::collections::HashMap;
2 2
3 use chatsvc::ConversationState;
3 use chatsvc::{ConversationState, MentionActivity};
4 4 use chrono::{DateTime, Duration, Utc};
5 5 use store::{ChatRecord, Store};
6 6
7 7 use crate::bot_partners::BotPartners;
8 use crate::channel_mentions::channel_mentions;
8 9 use crate::chat_paging::ChatPaging;
9 10 use crate::engine::{SidebarSummary, SyncEngine};
10 use crate::error::Result;
11 use crate::error::{Error, Result};
11 12 use crate::events::CoreEvent;
12 13 use crate::hidden_chats::{LocallyHidden, resolve_hidden};
13 14 use crate::mapping::{channel_record, team_record};
@@ -69,7 +70,11 @@ impl<R: Remote> SyncEngine<R> {
69 70 let mut hidden_ids = Vec::new();
70 71 let mut complete = false;
71 72 let mut continuation = None;
72 let states = self.refresh_chat_states().await;
73 let (states, app_horizon_ms, mentions) = tokio::join!(
74 self.refresh_chat_states(),
75 self.refresh_app_channel_horizon(),
76 self.remote.mention_activities()
77 );
73 78 self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
74 79 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
75 80 loop {
@@ -98,7 +103,8 @@ impl<R: Remote> SyncEngine<R> {
98 103 self.refresh_notes_chat(states.as_deref(), &my_user_id)
99 104 .await,
100 105 );
101 self.apply_channel_read_states(states.as_deref(), &my_user_id);
106 self.apply_channel_read_states(states.as_deref(), &my_user_id, app_horizon_ms);
107 self.apply_channel_mentions(states.as_deref(), mentions, &my_user_id, app_horizon_ms);
102 108 self.apply_muted_chats(states);
103 109 if full {
104 110 if complete {
@@ -145,7 +151,49 @@ impl<R: Remote> SyncEngine<R> {
145 151 Ok(())
146 152 }
147 153
148 fn apply_channel_read_states(&self, states: Option<&[ConversationState]>, my_user_id: &str) {
154 async fn refresh_app_channel_horizon(&self) -> i64 {
155 match self.remote.app_consumption_horizon().await {
156 Ok(horizon) => {
157 let mut known = self.app_channel_horizon_ms.lock().unwrap();
158 *known = horizon.channel_ms.max(*known);
159 *known
160 }
161 Err(error) => {
162 self.report(format!("cannot read the mark all as read horizon: {error}"));
163 *self.app_channel_horizon_ms.lock().unwrap()
164 }
165 }
166 }
167
168 fn apply_channel_mentions(
169 &self,
170 states: Option<&[ConversationState]>,
171 mentions: Result<Vec<MentionActivity>>,
172 my_user_id: &str,
173 app_horizon_ms: i64,
174 ) {
175 let (Some(states), Ok(mentions)) = (
176 states,
177 mentions.inspect_err(|error| {
178 if !matches!(error, Error::Unsupported(_)) {
179 self.report(format!("cannot refresh channel mentions: {error}"));
180 }
181 }),
182 ) else {
183 return;
184 };
185 let counts = channel_mentions(&mentions, states, my_user_id, app_horizon_ms);
186 if let Err(error) = self.store.replace_channel_mentions(&counts) {
187 self.report(format!("cannot store channel mentions: {error}"));
188 }
189 }
190
191 fn apply_channel_read_states(
192 &self,
193 states: Option<&[ConversationState]>,
194 my_user_id: &str,
195 app_horizon_ms: i64,
196 ) {
149 197 let Some(states) = states else {
150 198 return;
151 199 };
@@ -154,7 +202,7 @@ impl<R: Remote> SyncEngine<R> {
154 202 .map(|state| {
155 203 (
156 204 state.id.clone(),
157 state.read.is_unread(my_user_id),
205 state.read.is_unread_after(my_user_id, app_horizon_ms),
158 206 state.read.last_message_at(),
159 207 )
160 208 })
@@ -1,13 +1,14 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2
2
3use chatsvc::ConversationState;
3use chatsvc::{ConversationState, MentionActivity};
4use chrono::{DateTime, Duration, Utc};
4use chrono::{DateTime, Duration, Utc};
5use store::{ChatRecord, Store};
5use store::{ChatRecord, Store};
6
6
7use crate::bot_partners::BotPartners;
7use crate::bot_partners::BotPartners;
8use crate::channel_mentions::channel_mentions;
8use crate::chat_paging::ChatPaging;
9use crate::chat_paging::ChatPaging;
9use crate::engine::{SidebarSummary, SyncEngine};
10use crate::engine::{SidebarSummary, SyncEngine};
10use crate::error::Result;
11use crate::error::{Error, Result};
11use crate::events::CoreEvent;
12use crate::events::CoreEvent;
12use crate::hidden_chats::{LocallyHidden, resolve_hidden};
13use crate::hidden_chats::{LocallyHidden, resolve_hidden};
13use crate::mapping::{channel_record, team_record};
14use crate::mapping::{channel_record, team_record};
@@ -69,7 +70,11 @@ impl<R: Remote> SyncEngine<R> {
69 let mut hidden_ids = Vec::new();
70 let mut hidden_ids = Vec::new();
70 let mut complete = false;
71 let mut complete = false;
71 let mut continuation = None;
72 let mut continuation = None;
72 let states = self.refresh_chat_states().await;
73 let (states, app_horizon_ms, mentions) = tokio::join!(
74 self.refresh_chat_states(),
75 self.refresh_app_channel_horizon(),
76 self.remote.mention_activities()
77 );
73 self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
78 self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
74 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
79 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
75 loop {
80 loop {
@@ -98,7 +103,8 @@ impl<R: Remote> SyncEngine<R> {
98 self.refresh_notes_chat(states.as_deref(), &my_user_id)
103 self.refresh_notes_chat(states.as_deref(), &my_user_id)
99 .await,
104 .await,
100 );
105 );
101 self.apply_channel_read_states(states.as_deref(), &my_user_id);
106 self.apply_channel_read_states(states.as_deref(), &my_user_id, app_horizon_ms);
107 self.apply_channel_mentions(states.as_deref(), mentions, &my_user_id, app_horizon_ms);
102 self.apply_muted_chats(states);
108 self.apply_muted_chats(states);
103 if full {
109 if full {
104 if complete {
110 if complete {
@@ -145,7 +151,49 @@ impl<R: Remote> SyncEngine<R> {
145 Ok(())
151 Ok(())
146 }
152 }
147
153
148 fn apply_channel_read_states(&self, states: Option<&[ConversationState]>, my_user_id: &str) {
154 async fn refresh_app_channel_horizon(&self) -> i64 {
155 match self.remote.app_consumption_horizon().await {
156 Ok(horizon) => {
157 let mut known = self.app_channel_horizon_ms.lock().unwrap();
158 *known = horizon.channel_ms.max(*known);
159 *known
160 }
161 Err(error) => {
162 self.report(format!("cannot read the mark all as read horizon: {error}"));
163 *self.app_channel_horizon_ms.lock().unwrap()
164 }
165 }
166 }
167
168 fn apply_channel_mentions(
169 &self,
170 states: Option<&[ConversationState]>,
171 mentions: Result<Vec<MentionActivity>>,
172 my_user_id: &str,
173 app_horizon_ms: i64,
174 ) {
175 let (Some(states), Ok(mentions)) = (
176 states,
177 mentions.inspect_err(|error| {
178 if !matches!(error, Error::Unsupported(_)) {
179 self.report(format!("cannot refresh channel mentions: {error}"));
180 }
181 }),
182 ) else {
183 return;
184 };
185 let counts = channel_mentions(&mentions, states, my_user_id, app_horizon_ms);
186 if let Err(error) = self.store.replace_channel_mentions(&counts) {
187 self.report(format!("cannot store channel mentions: {error}"));
188 }
189 }
190
191 fn apply_channel_read_states(
192 &self,
193 states: Option<&[ConversationState]>,
194 my_user_id: &str,
195 app_horizon_ms: i64,
196 ) {
149 let Some(states) = states else {
197 let Some(states) = states else {
150 return;
198 return;
151 };
199 };
@@ -154,7 +202,7 @@ impl<R: Remote> SyncEngine<R> {
154 .map(|state| {
202 .map(|state| {
155 (
203 (
156 state.id.clone(),
204 state.id.clone(),
157 state.read.is_unread(my_user_id),
205 state.read.is_unread_after(my_user_id, app_horizon_ms),
158 state.read.last_message_at(),
206 state.read.last_message_at(),
159 )
207 )
160 })
208 })
crates/core/tests/engine.rs +135 −6
@@ -135,6 +135,8 @@ struct Fake {
135 135 window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
136 136 search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,
137 137 member_requests: Mutex<Vec<String>>,
138 mention_activities: Mutex<Vec<chatsvc::MentionActivity>>,
139 app_channel_horizon_ms: Mutex<i64>,
138 140 }
139 141
140 142 impl Fake {
@@ -677,6 +679,11 @@ impl Remote for Handle {
677 679 Ok(())
678 680 }
679 681
682 async fn undo_soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()> {
683 self.record(format!("undo_soft_delete {user_id} {}", describe(target)));
684 Ok(())
685 }
686
680 687 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
681 688 self.record(format!("one_on_one {my_user_id} {user_id}"));
682 689 Ok(chat("19:new@thread.v2", None, 40, 40, ME, false))
@@ -876,6 +883,49 @@ impl Remote for Handle {
876 883 Ok(())
877 884 }
878 885
886 async fn channel_pinned_posts(
887 &self,
888 team_thread_id: &str,
889 channel_id: &str,
890 ) -> Result<Vec<chatsvc::PinnedMessage>> {
891 self.record(format!("channel pins {team_thread_id} {channel_id}"));
892 Ok(vec![chatsvc::PinnedMessage {
893 message_id: "30".to_owned(),
894 pinned_at: None,
895 parent_id: None,
896 }])
897 }
898
899 async fn set_post_pinned(
900 &self,
901 team_thread_id: &str,
902 channel_id: &str,
903 post_id: &str,
904 pinned: bool,
905 ) -> Result<()> {
906 self.record(format!(
907 "post pin {team_thread_id} {channel_id} {post_id} {pinned}"
908 ));
909 Ok(())
910 }
911
912 async fn mention_activities(&self) -> Result<Vec<chatsvc::MentionActivity>> {
913 Ok(self.mention_activities.lock().unwrap().clone())
914 }
915
916 async fn app_consumption_horizon(&self) -> Result<chatsvc::AppConsumptionHorizon> {
917 Ok(chatsvc::AppConsumptionHorizon {
918 channel_ms: *self.app_channel_horizon_ms.lock().unwrap(),
919 ..chatsvc::AppConsumptionHorizon::default()
920 })
921 }
922
923 async fn mark_all_channels_read(&self, now_ms: i64) -> Result<chatsvc::AppConsumptionHorizon> {
924 self.record("mark all channels read".to_owned());
925 *self.app_channel_horizon_ms.lock().unwrap() = now_ms;
926 self.app_consumption_horizon().await
927 }
928
879 929 async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {
880 930 *self.app_calls.lock().unwrap() += 1;
881 931 Ok(self.apps.lock().unwrap().clone())
@@ -2563,12 +2613,17 @@ async fn chat_actions_call_graph_with_the_right_ids() {
2563 2613 .await
2564 2614 .unwrap();
2565 2615 engine.soft_delete_message(CHAT, "m0003").await.unwrap();
2616 engine
2617 .undo_soft_delete_message(CHAT, "m0003")
2618 .await
2619 .unwrap();
2566 2620 let calls = fake.calls();
2567 2621 assert_eq!(calls[0], format!("mark_read {CHAT} {ME} tenant-1"));
2568 2622 assert!(calls.contains(&"set_reaction m0001 like".to_owned()));
2569 2623 assert!(calls.contains(&"unset_reaction m0001 like".to_owned()));
2570 2624 assert!(calls.contains(&"edit m0002 new <b>text</b>".to_owned()));
2571 2625 assert!(calls.contains(&format!("soft_delete {ME} m0003")));
2626 assert!(calls.contains(&format!("undo_soft_delete {ME} m0003")));
2572 2627 assert!(!engine.sidebar().unwrap().chats[0].unread);
2573 2628 }
2574 2629
@@ -3071,6 +3126,7 @@ impl FolderSource for FakeFolders {
3071 3126 &'a self,
3072 3127 conversation_id: &'a str,
3073 3128 target_folder_id: &'a str,
3129 _index: Option<usize>,
3074 3130 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
3075 3131 Box::pin(async move {
3076 3132 self.calls
@@ -3225,7 +3281,7 @@ async fn folders_refresh_move_and_remove_go_through_the_source_and_cache() {
3225 3281 engine.refresh_folders().await.unwrap();
3226 3282 assert!(events.try_recv().is_err());
3227 3283
3228 engine.move_to_folder("a", "work").await.unwrap();
3284 engine.move_to_folder("a", "work", None).await.unwrap();
3229 3285 assert_eq!(
3230 3286 engine.chat_folders().unwrap()[1].conversation_ids,
3231 3287 ids(&["c", "a"])
@@ -3489,7 +3545,7 @@ async fn folders_without_a_source_are_unsupported() {
3489 3545 Err(Error::Unsupported(_))
3490 3546 ));
3491 3547 assert!(matches!(
3492 engine.move_to_folder("a", "b").await,
3548 engine.move_to_folder("a", "b", None).await,
3493 3549 Err(Error::Unsupported(_))
3494 3550 ));
3495 3551 }
@@ -4670,7 +4726,7 @@ async fn save_uses_the_message_id_as_root_in_chats() {
4670 4726 }
4671 4727
4672 4728 #[tokio::test]
4673 async fn pinning_announces_and_is_refused_in_channels() {
4729 async fn pinning_announces_in_chats() {
4674 4730 let fake = Arc::new(Fake::default());
4675 4731 let engine = channel_engine(&fake).await;
4676 4732 *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
@@ -4691,10 +4747,83 @@ async fn pinning_announces_and_is_refused_in_channels() {
4691 4747 fake.calls().last().unwrap(),
4692 4748 &format!("unpin {CHAT} 5 Some(\"folder-1\")")
4693 4749 );
4694 assert!(matches!(
4695 engine.pin_message(CHANNEL, "5").await,
4696 Err(Error::Unsupported(_))
4750 }
4751
4752 #[tokio::test]
4753 async fn channel_pins_use_the_post_pin_routes_of_the_team_thread() {
4754 let fake = Arc::new(Fake::default());
4755 let engine = channel_engine(&fake).await;
4756 engine.fetch_newer(CHANNEL).await.unwrap();
4757 let pins = engine.chat_pins(CHANNEL).await.unwrap();
4758 assert_eq!(pins[0].message_id, "30");
4759 assert_eq!(
4760 fake.calls().last().unwrap(),
4761 &format!("channel pins {CHANNEL} {CHANNEL}")
4762 );
4763 let mut events = engine.subscribe();
4764 engine.pin_message(CHANNEL, "30").await.unwrap();
4765 assert_eq!(
4766 fake.calls().last().unwrap(),
4767 &format!("post pin {CHANNEL} {CHANNEL} 30 true")
4768 );
4769 assert_eq!(
4770 events.try_recv().unwrap(),
4771 CoreEvent::PinsChanged {
4772 conversation_id: CHANNEL.to_owned()
4773 }
4774 );
4775 engine.unpin_message(CHANNEL, "30", None).await.unwrap();
4776 assert_eq!(
4777 fake.calls().last().unwrap(),
4778 &format!("post pin {CHANNEL} {CHANNEL} 30 false")
4779 );
4780 }
4781
4782 #[tokio::test]
4783 async fn channel_mentions_follow_the_activity_feed_and_mark_all_as_read() {
4784 let fake = Arc::new(Fake::default());
4785 fake.read_states.lock().unwrap().push((
4786 CHANNEL.to_owned(),
4787 chatsvc::ReadHorizon {
4788 consumed_until_ms: 5,
4789 last_message_ms: 9,
4790 last_message_from: Some("8:orgid:user-ada".to_owned()),
4791 ..chatsvc::ReadHorizon::default()
4792 },
4697 4793 ));
4794 let mention = |activity_id: &str, kind: chatsvc::MentionKind| chatsvc::MentionActivity {
4795 activity_id: activity_id.to_owned(),
4796 kind,
4797 source_thread_id: CHANNEL.to_owned(),
4798 source_message_id: None,
4799 timestamp_ms: 8,
4800 is_read: false,
4801 };
4802 *fake.mention_activities.lock().unwrap() = vec![
4803 mention("1", chatsvc::MentionKind::Personal),
4804 mention("2", chatsvc::MentionKind::Team),
4805 ];
4806 let engine = channel_engine(&fake).await;
4807 engine.refresh_sidebar().await.unwrap();
4808 let mentions = engine.store().sidebar().unwrap().teams[0].channel_mentions(CHANNEL);
4809 assert_eq!((mentions.personal, mentions.team), (1, 1));
4810
4811 engine.mark_all_channels_read().await.unwrap();
4812
4813 assert_eq!(fake.calls().last().unwrap(), "mark all channels read");
4814 assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);
4815 assert!(
4816 engine.store().sidebar().unwrap().teams[0]
4817 .mentions
4818 .is_empty()
4819 );
4820 engine.refresh_sidebar().await.unwrap();
4821 assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);
4822 assert!(
4823 engine.store().sidebar().unwrap().teams[0]
4824 .mentions
4825 .is_empty()
4826 );
4698 4827 }
4699 4828
4700 4829 #[tokio::test]
@@ -135,6 +135,8 @@ struct Fake {
135 window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
135 window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
136 search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,
136 search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,
137 member_requests: Mutex<Vec<String>>,
137 member_requests: Mutex<Vec<String>>,
138 mention_activities: Mutex<Vec<chatsvc::MentionActivity>>,
139 app_channel_horizon_ms: Mutex<i64>,
138}
140}
139
141
140impl Fake {
142impl Fake {
@@ -677,6 +679,11 @@ impl Remote for Handle {
677 Ok(())
679 Ok(())
678 }
680 }
679
681
682 async fn undo_soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()> {
683 self.record(format!("undo_soft_delete {user_id} {}", describe(target)));
684 Ok(())
685 }
686
680 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
687 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
681 self.record(format!("one_on_one {my_user_id} {user_id}"));
688 self.record(format!("one_on_one {my_user_id} {user_id}"));
682 Ok(chat("19:new@thread.v2", None, 40, 40, ME, false))
689 Ok(chat("19:new@thread.v2", None, 40, 40, ME, false))
@@ -876,6 +883,49 @@ impl Remote for Handle {
876 Ok(())
883 Ok(())
877 }
884 }
878
885
886 async fn channel_pinned_posts(
887 &self,
888 team_thread_id: &str,
889 channel_id: &str,
890 ) -> Result<Vec<chatsvc::PinnedMessage>> {
891 self.record(format!("channel pins {team_thread_id} {channel_id}"));
892 Ok(vec![chatsvc::PinnedMessage {
893 message_id: "30".to_owned(),
894 pinned_at: None,
895 parent_id: None,
896 }])
897 }
898
899 async fn set_post_pinned(
900 &self,
901 team_thread_id: &str,
902 channel_id: &str,
903 post_id: &str,
904 pinned: bool,
905 ) -> Result<()> {
906 self.record(format!(
907 "post pin {team_thread_id} {channel_id} {post_id} {pinned}"
908 ));
909 Ok(())
910 }
911
912 async fn mention_activities(&self) -> Result<Vec<chatsvc::MentionActivity>> {
913 Ok(self.mention_activities.lock().unwrap().clone())
914 }
915
916 async fn app_consumption_horizon(&self) -> Result<chatsvc::AppConsumptionHorizon> {
917 Ok(chatsvc::AppConsumptionHorizon {
918 channel_ms: *self.app_channel_horizon_ms.lock().unwrap(),
919 ..chatsvc::AppConsumptionHorizon::default()
920 })
921 }
922
923 async fn mark_all_channels_read(&self, now_ms: i64) -> Result<chatsvc::AppConsumptionHorizon> {
924 self.record("mark all channels read".to_owned());
925 *self.app_channel_horizon_ms.lock().unwrap() = now_ms;
926 self.app_consumption_horizon().await
927 }
928
879 async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {
929 async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {
880 *self.app_calls.lock().unwrap() += 1;
930 *self.app_calls.lock().unwrap() += 1;
881 Ok(self.apps.lock().unwrap().clone())
931 Ok(self.apps.lock().unwrap().clone())
@@ -2563,12 +2613,17 @@ async fn chat_actions_call_graph_with_the_right_ids() {
2563 .await
2613 .await
2564 .unwrap();
2614 .unwrap();
2565 engine.soft_delete_message(CHAT, "m0003").await.unwrap();
2615 engine.soft_delete_message(CHAT, "m0003").await.unwrap();
2616 engine
2617 .undo_soft_delete_message(CHAT, "m0003")
2618 .await
2619 .unwrap();
2566 let calls = fake.calls();
2620 let calls = fake.calls();
2567 assert_eq!(calls[0], format!("mark_read {CHAT} {ME} tenant-1"));
2621 assert_eq!(calls[0], format!("mark_read {CHAT} {ME} tenant-1"));
2568 assert!(calls.contains(&"set_reaction m0001 like".to_owned()));
2622 assert!(calls.contains(&"set_reaction m0001 like".to_owned()));
2569 assert!(calls.contains(&"unset_reaction m0001 like".to_owned()));
2623 assert!(calls.contains(&"unset_reaction m0001 like".to_owned()));
2570 assert!(calls.contains(&"edit m0002 new <b>text</b>".to_owned()));
2624 assert!(calls.contains(&"edit m0002 new <b>text</b>".to_owned()));
2571 assert!(calls.contains(&format!("soft_delete {ME} m0003")));
2625 assert!(calls.contains(&format!("soft_delete {ME} m0003")));
2626 assert!(calls.contains(&format!("undo_soft_delete {ME} m0003")));
2572 assert!(!engine.sidebar().unwrap().chats[0].unread);
2627 assert!(!engine.sidebar().unwrap().chats[0].unread);
2573}
2628}
2574
2629
@@ -3071,6 +3126,7 @@ impl FolderSource for FakeFolders {
3071 &'a self,
3126 &'a self,
3072 conversation_id: &'a str,
3127 conversation_id: &'a str,
3073 target_folder_id: &'a str,
3128 target_folder_id: &'a str,
3129 _index: Option<usize>,
3074 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
3130 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
3075 Box::pin(async move {
3131 Box::pin(async move {
3076 self.calls
3132 self.calls
@@ -3225,7 +3281,7 @@ async fn folders_refresh_move_and_remove_go_through_the_source_and_cache() {
3225 engine.refresh_folders().await.unwrap();
3281 engine.refresh_folders().await.unwrap();
3226 assert!(events.try_recv().is_err());
3282 assert!(events.try_recv().is_err());
3227
3283
3228 engine.move_to_folder("a", "work").await.unwrap();
3284 engine.move_to_folder("a", "work", None).await.unwrap();
3229 assert_eq!(
3285 assert_eq!(
3230 engine.chat_folders().unwrap()[1].conversation_ids,
3286 engine.chat_folders().unwrap()[1].conversation_ids,
3231 ids(&["c", "a"])
3287 ids(&["c", "a"])
@@ -3489,7 +3545,7 @@ async fn folders_without_a_source_are_unsupported() {
3489 Err(Error::Unsupported(_))
3545 Err(Error::Unsupported(_))
3490 ));
3546 ));
3491 assert!(matches!(
3547 assert!(matches!(
3492 engine.move_to_folder("a", "b").await,
3548 engine.move_to_folder("a", "b", None).await,
3493 Err(Error::Unsupported(_))
3549 Err(Error::Unsupported(_))
3494 ));
3550 ));
3495}
3551}
@@ -4670,7 +4726,7 @@ async fn save_uses_the_message_id_as_root_in_chats() {
4670}
4726}
4671
4727
4672#[tokio::test]
4728#[tokio::test]
4673async fn pinning_announces_and_is_refused_in_channels() {
4729async fn pinning_announces_in_chats() {
4674 let fake = Arc::new(Fake::default());
4730 let fake = Arc::new(Fake::default());
4675 let engine = channel_engine(&fake).await;
4731 let engine = channel_engine(&fake).await;
4676 *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
4732 *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
@@ -4691,10 +4747,83 @@ async fn pinning_announces_and_is_refused_in_channels() {
4691 fake.calls().last().unwrap(),
4747 fake.calls().last().unwrap(),
4692 &format!("unpin {CHAT} 5 Some(\"folder-1\")")
4748 &format!("unpin {CHAT} 5 Some(\"folder-1\")")
4693 );
4749 );
4694 assert!(matches!(
4750}
4695 engine.pin_message(CHANNEL, "5").await,
4751
4696 Err(Error::Unsupported(_))
4752#[tokio::test]
4753async fn channel_pins_use_the_post_pin_routes_of_the_team_thread() {
4754 let fake = Arc::new(Fake::default());
4755 let engine = channel_engine(&fake).await;
4756 engine.fetch_newer(CHANNEL).await.unwrap();
4757 let pins = engine.chat_pins(CHANNEL).await.unwrap();
4758 assert_eq!(pins[0].message_id, "30");
4759 assert_eq!(
4760 fake.calls().last().unwrap(),
4761 &format!("channel pins {CHANNEL} {CHANNEL}")
4762 );
4763 let mut events = engine.subscribe();
4764 engine.pin_message(CHANNEL, "30").await.unwrap();
4765 assert_eq!(
4766 fake.calls().last().unwrap(),
4767 &format!("post pin {CHANNEL} {CHANNEL} 30 true")
4768 );
4769 assert_eq!(
4770 events.try_recv().unwrap(),
4771 CoreEvent::PinsChanged {
4772 conversation_id: CHANNEL.to_owned()
4773 }
4774 );
4775 engine.unpin_message(CHANNEL, "30", None).await.unwrap();
4776 assert_eq!(
4777 fake.calls().last().unwrap(),
4778 &format!("post pin {CHANNEL} {CHANNEL} 30 false")
4779 );
4780}
4781
4782#[tokio::test]
4783async fn channel_mentions_follow_the_activity_feed_and_mark_all_as_read() {
4784 let fake = Arc::new(Fake::default());
4785 fake.read_states.lock().unwrap().push((
4786 CHANNEL.to_owned(),
4787 chatsvc::ReadHorizon {
4788 consumed_until_ms: 5,
4789 last_message_ms: 9,
4790 last_message_from: Some("8:orgid:user-ada".to_owned()),
4791 ..chatsvc::ReadHorizon::default()
4792 },
4697 ));
4793 ));
4794 let mention = |activity_id: &str, kind: chatsvc::MentionKind| chatsvc::MentionActivity {
4795 activity_id: activity_id.to_owned(),
4796 kind,
4797 source_thread_id: CHANNEL.to_owned(),
4798 source_message_id: None,
4799 timestamp_ms: 8,
4800 is_read: false,
4801 };
4802 *fake.mention_activities.lock().unwrap() = vec![
4803 mention("1", chatsvc::MentionKind::Personal),
4804 mention("2", chatsvc::MentionKind::Team),
4805 ];
4806 let engine = channel_engine(&fake).await;
4807 engine.refresh_sidebar().await.unwrap();
4808 let mentions = engine.store().sidebar().unwrap().teams[0].channel_mentions(CHANNEL);
4809 assert_eq!((mentions.personal, mentions.team), (1, 1));
4810
4811 engine.mark_all_channels_read().await.unwrap();
4812
4813 assert_eq!(fake.calls().last().unwrap(), "mark all channels read");
4814 assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);
4815 assert!(
4816 engine.store().sidebar().unwrap().teams[0]
4817 .mentions
4818 .is_empty()
4819 );
4820 engine.refresh_sidebar().await.unwrap();
4821 assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);
4822 assert!(
4823 engine.store().sidebar().unwrap().teams[0]
4824 .mentions
4825 .is_empty()
4826 );
4698}
4827}
4699
4828
4700#[tokio::test]
4829#[tokio::test]
crates/graph/src/target.rs +19 −0
@@ -76,6 +76,16 @@ impl MessageTarget {
76 76 }
77 77 }
78 78
79 pub(crate) fn undo_soft_delete_url(&self, user_id: &str) -> String {
80 match self {
81 MessageTarget::Chat {
82 chat_id,
83 message_id,
84 } => urls::undo_soft_delete(user_id, chat_id, message_id),
85 channel => format!("{}/undoSoftDelete", channel.url()),
86 }
87 }
88
79 89 pub(crate) fn reaction_url(&self, action: &str) -> String {
80 90 format!("{}/{action}", self.url())
81 91 }
@@ -125,6 +135,15 @@ mod tests {
125 135 chat.soft_delete_url("u1"),
126 136 "https://graph.microsoft.com/v1.0/users/u1/chats/19%3Aa%40thread.v2/messages/m1/softDelete"
127 137 );
138 assert_eq!(
139 chat.undo_soft_delete_url("u1"),
140 "https://graph.microsoft.com/v1.0/users/u1/chats/19%3Aa%40thread.v2/messages/m1/undoSoftDelete"
141 );
142 assert!(
143 MessageTarget::channel("t", "19:c@thread.tacv2", "r1", Some("m1"))
144 .undo_soft_delete_url("u")
145 .ends_with("/messages/m1/replies/r1/undoSoftDelete")
146 );
128 147 assert!(
129 148 chat.reaction_url("unsetReaction")
130 149 .ends_with("/messages/m1/unsetReaction")
@@ -76,6 +76,16 @@ impl MessageTarget {
76 }
76 }
77 }
77 }
78
78
79 pub(crate) fn undo_soft_delete_url(&self, user_id: &str) -> String {
80 match self {
81 MessageTarget::Chat {
82 chat_id,
83 message_id,
84 } => urls::undo_soft_delete(user_id, chat_id, message_id),
85 channel => format!("{}/undoSoftDelete", channel.url()),
86 }
87 }
88
79 pub(crate) fn reaction_url(&self, action: &str) -> String {
89 pub(crate) fn reaction_url(&self, action: &str) -> String {
80 format!("{}/{action}", self.url())
90 format!("{}/{action}", self.url())
81 }
91 }
@@ -125,6 +135,15 @@ mod tests {
125 chat.soft_delete_url("u1"),
135 chat.soft_delete_url("u1"),
126 "https://graph.microsoft.com/v1.0/users/u1/chats/19%3Aa%40thread.v2/messages/m1/softDelete"
136 "https://graph.microsoft.com/v1.0/users/u1/chats/19%3Aa%40thread.v2/messages/m1/softDelete"
127 );
137 );
138 assert_eq!(
139 chat.undo_soft_delete_url("u1"),
140 "https://graph.microsoft.com/v1.0/users/u1/chats/19%3Aa%40thread.v2/messages/m1/undoSoftDelete"
141 );
142 assert!(
143 MessageTarget::channel("t", "19:c@thread.tacv2", "r1", Some("m1"))
144 .undo_soft_delete_url("u")
145 .ends_with("/messages/m1/replies/r1/undoSoftDelete")
146 );
128 assert!(
147 assert!(
129 chat.reaction_url("unsetReaction")
148 chat.reaction_url("unsetReaction")
130 .ends_with("/messages/m1/unsetReaction")
149 .ends_with("/messages/m1/unsetReaction")
crates/graph/src/urls.rs +14 −1
@@ -89,8 +89,21 @@ pub fn chat_message(chat_id: &str, message_id: &str) -> String {
89 89 }
90 90
91 91 pub fn soft_delete(user_id: &str, chat_id: &str, message_id: &str) -> String {
92 user_chat_message_action(user_id, chat_id, message_id, "softDelete")
93 }
94
95 pub fn undo_soft_delete(user_id: &str, chat_id: &str, message_id: &str) -> String {
96 user_chat_message_action(user_id, chat_id, message_id, "undoSoftDelete")
97 }
98
99 fn user_chat_message_action(
100 user_id: &str,
101 chat_id: &str,
102 message_id: &str,
103 action: &str,
104 ) -> String {
92 105 format!(
93 "{GRAPH}/v1.0/users/{}/chats/{}/messages/{}/softDelete",
106 "{GRAPH}/v1.0/users/{}/chats/{}/messages/{}/{action}",
94 107 segment(user_id),
95 108 segment(chat_id),
96 109 segment(message_id)
@@ -89,8 +89,21 @@ pub fn chat_message(chat_id: &str, message_id: &str) -> String {
89}
89}
90
90
91pub fn soft_delete(user_id: &str, chat_id: &str, message_id: &str) -> String {
91pub fn soft_delete(user_id: &str, chat_id: &str, message_id: &str) -> String {
92 user_chat_message_action(user_id, chat_id, message_id, "softDelete")
93}
94
95pub fn undo_soft_delete(user_id: &str, chat_id: &str, message_id: &str) -> String {
96 user_chat_message_action(user_id, chat_id, message_id, "undoSoftDelete")
97}
98
99fn user_chat_message_action(
100 user_id: &str,
101 chat_id: &str,
102 message_id: &str,
103 action: &str,
104) -> String {
92 format!(
105 format!(
93 "{GRAPH}/v1.0/users/{}/chats/{}/messages/{}/softDelete",
106 "{GRAPH}/v1.0/users/{}/chats/{}/messages/{}/{action}",
94 segment(user_id),
107 segment(user_id),
95 segment(chat_id),
108 segment(chat_id),
96 segment(message_id)
109 segment(message_id)
crates/graph/src/writes.rs +15 −0
@@ -225,6 +225,21 @@ impl Graph {
225 225 .await
226 226 }
227 227
228 /// `user_id` is only used for chats.
229 pub async fn undo_soft_delete_message(
230 &self,
231 user_id: &str,
232 target: &MessageTarget,
233 ) -> Result<()> {
234 self.write(
235 Method::Post,
236 &target.undo_soft_delete_url(user_id),
237 target.write_scope(),
238 None,
239 )
240 .await
241 }
242
228 243 pub async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
229 244 let body = json!({
230 245 "chatType": "oneOnOne",
@@ -225,6 +225,21 @@ impl Graph {
225 .await
225 .await
226 }
226 }
227
227
228 /// `user_id` is only used for chats.
229 pub async fn undo_soft_delete_message(
230 &self,
231 user_id: &str,
232 target: &MessageTarget,
233 ) -> Result<()> {
234 self.write(
235 Method::Post,
236 &target.undo_soft_delete_url(user_id),
237 target.write_scope(),
238 None,
239 )
240 .await
241 }
242
228 pub async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
243 pub async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
229 let body = json!({
244 let body = json!({
230 "chatType": "oneOnOne",
245 "chatType": "oneOnOne",
crates/store/src/lib.rs +1 −1
@@ -27,7 +27,7 @@ pub use error::{Error, Result};
27 27 pub use image_files::ImageFileCache;
28 28 pub use models::{
29 29 ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,
30 AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelNotificationLevel,
30 AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
31 31 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
32 32 ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
33 33 OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,
@@ -27,7 +27,7 @@ pub use error::{Error, Result};
27pub use image_files::ImageFileCache;
27pub use image_files::ImageFileCache;
28pub use models::{
28pub use models::{
29 ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,
29 ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,
30 AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelNotificationLevel,
30 AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
31 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
31 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
32 ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
32 ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
33 OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,
33 OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,
crates/store/src/migrations.rs +4 −0
@@ -97,6 +97,10 @@ const MIGRATIONS: &[Migration] = &[
97 97 script: include_str!("migrations/0022_read_horizons.sql"),
98 98 after: None,
99 99 },
100 Migration {
101 script: include_str!("migrations/0023_channel_mentions.sql"),
102 after: None,
103 },
100 104 ];
101 105
102 106 pub fn latest_version() -> i64 {
@@ -97,6 +97,10 @@ const MIGRATIONS: &[Migration] = &[
97 script: include_str!("migrations/0022_read_horizons.sql"),
97 script: include_str!("migrations/0022_read_horizons.sql"),
98 after: None,
98 after: None,
99 },
99 },
100 Migration {
101 script: include_str!("migrations/0023_channel_mentions.sql"),
102 after: None,
103 },
100];
104];
101
105
102pub fn latest_version() -> i64 {
106pub fn latest_version() -> i64 {
crates/store/src/migrations/0023_channel_mentions.sql added +6 −0
@@ -0,0 +1,6 @@
1 CREATE TABLE IF NOT EXISTS channel_mentions (
2 channel_id TEXT PRIMARY KEY NOT NULL,
3 personal INTEGER NOT NULL DEFAULT 0,
4 channel INTEGER NOT NULL DEFAULT 0,
5 team INTEGER NOT NULL DEFAULT 0
6 );
@@ -0,0 +1,6 @@
1CREATE TABLE IF NOT EXISTS channel_mentions (
2 channel_id TEXT PRIMARY KEY NOT NULL,
3 personal INTEGER NOT NULL DEFAULT 0,
4 channel INTEGER NOT NULL DEFAULT 0,
5 team INTEGER NOT NULL DEFAULT 0
6);
crates/store/src/models.rs +19 −0
@@ -147,6 +147,7 @@ pub struct SidebarTeam {
147 147 pub hidden: bool,
148 148 pub hidden_channel_ids: Vec<String>,
149 149 pub notifications: HashMap<String, ChannelNotifications>,
150 pub mentions: HashMap<String, ChannelMentions>,
150 151 }
151 152
152 153 impl SidebarTeam {
@@ -156,6 +157,24 @@ impl SidebarTeam {
156 157 .copied()
157 158 .unwrap_or_default()
158 159 }
160
161 pub fn channel_mentions(&self, channel_id: &str) -> ChannelMentions {
162 self.mentions.get(channel_id).copied().unwrap_or_default()
163 }
164 }
165
166 /// Unread @mentions of one channel: personal (person or tag), @channel, @team.
167 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
168 pub struct ChannelMentions {
169 pub personal: u32,
170 pub channel: u32,
171 pub team: u32,
172 }
173
174 impl ChannelMentions {
175 pub fn is_empty(&self) -> bool {
176 *self == ChannelMentions::default()
177 }
159 178 }
160 179
161 180 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -147,6 +147,7 @@ pub struct SidebarTeam {
147 pub hidden: bool,
147 pub hidden: bool,
148 pub hidden_channel_ids: Vec<String>,
148 pub hidden_channel_ids: Vec<String>,
149 pub notifications: HashMap<String, ChannelNotifications>,
149 pub notifications: HashMap<String, ChannelNotifications>,
150 pub mentions: HashMap<String, ChannelMentions>,
150}
151}
151
152
152impl SidebarTeam {
153impl SidebarTeam {
@@ -156,6 +157,24 @@ impl SidebarTeam {
156 .copied()
157 .copied()
157 .unwrap_or_default()
158 .unwrap_or_default()
158 }
159 }
160
161 pub fn channel_mentions(&self, channel_id: &str) -> ChannelMentions {
162 self.mentions.get(channel_id).copied().unwrap_or_default()
163 }
164}
165
166/// Unread @mentions of one channel: personal (person or tag), @channel, @team.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
168pub struct ChannelMentions {
169 pub personal: u32,
170 pub channel: u32,
171 pub team: u32,
172}
173
174impl ChannelMentions {
175 pub fn is_empty(&self) -> bool {
176 *self == ChannelMentions::default()
177 }
159}
178}
160
179
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
crates/store/src/sidebar.rs +60 −2
@@ -5,8 +5,8 @@ use rusqlite::params;
5 5
6 6 use crate::error::Result;
7 7 use crate::models::{
8 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, Sidebar,
9 SidebarTeam, TeamLayoutRecord, TeamRecord,
8 ChannelMentions, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
9 ChannelTabRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord,
10 10 };
11 11 use crate::store::Store;
12 12 use crate::teams::channel_from_row;
@@ -83,6 +83,19 @@ impl Store {
83 83 .then_with(|| compare_names(&left.channel.name, &right.channel.name))
84 84 .then_with(|| left.channel.id.cmp(&right.channel.id))
85 85 });
86 let mut mentions: HashMap<String, ChannelMentions> = connection
87 .prepare_cached("SELECT channel_id, personal, channel, team FROM channel_mentions")?
88 .query_map([], |row| {
89 Ok((
90 row.get::<_, String>(0)?,
91 ChannelMentions {
92 personal: row.get(1)?,
93 channel: row.get(2)?,
94 team: row.get(3)?,
95 },
96 ))
97 })?
98 .collect::<rusqlite::Result<_>>()?;
86 99 let mut teams: Vec<SidebarTeam> = team_rows
87 100 .into_iter()
88 101 .map(|row| SidebarTeam {
@@ -91,6 +104,7 @@ impl Store {
91 104 hidden: row.hidden,
92 105 hidden_channel_ids: Vec::new(),
93 106 notifications: HashMap::new(),
107 mentions: HashMap::new(),
94 108 })
95 109 .collect();
96 110 for row in channel_rows {
@@ -105,6 +119,9 @@ impl Store {
105 119 team.notifications
106 120 .insert(row.channel.id.clone(), row.notifications);
107 121 }
122 if let Some(found) = mentions.remove(&row.channel.id) {
123 team.mentions.insert(row.channel.id.clone(), found);
124 }
108 125 team.channels.push(row.channel);
109 126 }
110 127 }
@@ -156,6 +173,47 @@ impl Store {
156 173 Ok(transaction.commit()?)
157 174 }
158 175
176 /// Replaces every stored mention count; channels left out have none.
177 pub fn replace_channel_mentions(&self, mentions: &[(String, ChannelMentions)]) -> Result<()> {
178 let mut connection = self.lock()?;
179 let transaction = connection.transaction()?;
180 transaction.execute("DELETE FROM channel_mentions", [])?;
181 {
182 let mut insert = transaction.prepare_cached(
183 "INSERT OR REPLACE INTO channel_mentions (channel_id, personal, channel, team)
184 VALUES (?1, ?2, ?3, ?4)",
185 )?;
186 for (channel_id, counts) in mentions.iter().filter(|(_, counts)| !counts.is_empty()) {
187 insert.execute(params![channel_id, counts.personal, counts.channel, counts.team])?;
188 }
189 }
190 Ok(transaction.commit()?)
191 }
192
193 pub fn clear_channel_mentions(&self, channel_id: &str) -> Result<()> {
194 self.lock()?.execute(
195 "DELETE FROM channel_mentions WHERE channel_id = ?1",
196 [channel_id],
197 )?;
198 Ok(())
199 }
200
201 /// The team's own thread id, which Teams' CSA routes take: the id of its General channel.
202 pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {
203 let connection = self.lock()?;
204 Ok(connection
205 .prepare_cached(
206 "SELECT channels.id FROM channels
207 LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id
208 WHERE channels.team_id = ?1
209 AND COALESCE(channel_layout.general, channels.name = ?2)
210 ORDER BY channels.id LIMIT 1",
211 )?
212 .query_map(params![team_id, GENERAL_FALLBACK_NAME], |row| row.get(0))?
213 .next()
214 .transpose()?)
215 }
216
159 217 pub fn set_channel_notifications(
160 218 &self,
161 219 channel_id: &str,
@@ -5,8 +5,8 @@ use rusqlite::params;
5
5
6use crate::error::Result;
6use crate::error::Result;
7use crate::models::{
7use crate::models::{
8 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, Sidebar,
8 ChannelMentions, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
9 SidebarTeam, TeamLayoutRecord, TeamRecord,
9 ChannelTabRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord,
10};
10};
11use crate::store::Store;
11use crate::store::Store;
12use crate::teams::channel_from_row;
12use crate::teams::channel_from_row;
@@ -83,6 +83,19 @@ impl Store {
83 .then_with(|| compare_names(&left.channel.name, &right.channel.name))
83 .then_with(|| compare_names(&left.channel.name, &right.channel.name))
84 .then_with(|| left.channel.id.cmp(&right.channel.id))
84 .then_with(|| left.channel.id.cmp(&right.channel.id))
85 });
85 });
86 let mut mentions: HashMap<String, ChannelMentions> = connection
87 .prepare_cached("SELECT channel_id, personal, channel, team FROM channel_mentions")?
88 .query_map([], |row| {
89 Ok((
90 row.get::<_, String>(0)?,
91 ChannelMentions {
92 personal: row.get(1)?,
93 channel: row.get(2)?,
94 team: row.get(3)?,
95 },
96 ))
97 })?
98 .collect::<rusqlite::Result<_>>()?;
86 let mut teams: Vec<SidebarTeam> = team_rows
99 let mut teams: Vec<SidebarTeam> = team_rows
87 .into_iter()
100 .into_iter()
88 .map(|row| SidebarTeam {
101 .map(|row| SidebarTeam {
@@ -91,6 +104,7 @@ impl Store {
91 hidden: row.hidden,
104 hidden: row.hidden,
92 hidden_channel_ids: Vec::new(),
105 hidden_channel_ids: Vec::new(),
93 notifications: HashMap::new(),
106 notifications: HashMap::new(),
107 mentions: HashMap::new(),
94 })
108 })
95 .collect();
109 .collect();
96 for row in channel_rows {
110 for row in channel_rows {
@@ -105,6 +119,9 @@ impl Store {
105 team.notifications
119 team.notifications
106 .insert(row.channel.id.clone(), row.notifications);
120 .insert(row.channel.id.clone(), row.notifications);
107 }
121 }
122 if let Some(found) = mentions.remove(&row.channel.id) {
123 team.mentions.insert(row.channel.id.clone(), found);
124 }
108 team.channels.push(row.channel);
125 team.channels.push(row.channel);
109 }
126 }
110 }
127 }
@@ -156,6 +173,47 @@ impl Store {
156 Ok(transaction.commit()?)
173 Ok(transaction.commit()?)
157 }
174 }
158
175
176 /// Replaces every stored mention count; channels left out have none.
177 pub fn replace_channel_mentions(&self, mentions: &[(String, ChannelMentions)]) -> Result<()> {
178 let mut connection = self.lock()?;
179 let transaction = connection.transaction()?;
180 transaction.execute("DELETE FROM channel_mentions", [])?;
181 {
182 let mut insert = transaction.prepare_cached(
183 "INSERT OR REPLACE INTO channel_mentions (channel_id, personal, channel, team)
184 VALUES (?1, ?2, ?3, ?4)",
185 )?;
186 for (channel_id, counts) in mentions.iter().filter(|(_, counts)| !counts.is_empty()) {
187 insert.execute(params![channel_id, counts.personal, counts.channel, counts.team])?;
188 }
189 }
190 Ok(transaction.commit()?)
191 }
192
193 pub fn clear_channel_mentions(&self, channel_id: &str) -> Result<()> {
194 self.lock()?.execute(
195 "DELETE FROM channel_mentions WHERE channel_id = ?1",
196 [channel_id],
197 )?;
198 Ok(())
199 }
200
201 /// The team's own thread id, which Teams' CSA routes take: the id of its General channel.
202 pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {
203 let connection = self.lock()?;
204 Ok(connection
205 .prepare_cached(
206 "SELECT channels.id FROM channels
207 LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id
208 WHERE channels.team_id = ?1
209 AND COALESCE(channel_layout.general, channels.name = ?2)
210 ORDER BY channels.id LIMIT 1",
211 )?
212 .query_map(params![team_id, GENERAL_FALLBACK_NAME], |row| row.get(0))?
213 .next()
214 .transpose()?)
215 }
216
159 pub fn set_channel_notifications(
217 pub fn set_channel_notifications(
160 &self,
218 &self,
161 channel_id: &str,
219 channel_id: &str,
crates/store/src/teams.rs +8 −0
@@ -78,6 +78,14 @@ impl Store {
78 78 Ok(())
79 79 }
80 80
81 pub fn mark_all_channels_read(&self) -> Result<()> {
82 let mut connection = self.lock()?;
83 let transaction = connection.transaction()?;
84 transaction.execute("UPDATE channels SET unread = 0 WHERE unread != 0", [])?;
85 transaction.execute("DELETE FROM channel_mentions", [])?;
86 Ok(transaction.commit()?)
87 }
88
81 89 pub fn remove_teams_except(&self, kept_team_ids: &[String]) -> Result<usize> {
82 90 let mut connection = self.lock()?;
83 91 let transaction = connection.transaction()?;
@@ -78,6 +78,14 @@ impl Store {
78 Ok(())
78 Ok(())
79 }
79 }
80
80
81 pub fn mark_all_channels_read(&self) -> Result<()> {
82 let mut connection = self.lock()?;
83 let transaction = connection.transaction()?;
84 transaction.execute("UPDATE channels SET unread = 0 WHERE unread != 0", [])?;
85 transaction.execute("DELETE FROM channel_mentions", [])?;
86 Ok(transaction.commit()?)
87 }
88
81 pub fn remove_teams_except(&self, kept_team_ids: &[String]) -> Result<usize> {
89 pub fn remove_teams_except(&self, kept_team_ids: &[String]) -> Result<usize> {
82 let mut connection = self.lock()?;
90 let mut connection = self.lock()?;
83 let transaction = connection.transaction()?;
91 let transaction = connection.transaction()?;
crates/store/tests/store.rs +138 −21
@@ -1,10 +1,10 @@
1 1 use chrono::{DateTime, TimeZone, Utc};
2 2 use rusqlite::Connection;
3 3 use store::{
4 AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,
5 ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
6 MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,
7 TeamRecord, UNKNOWN_USER_NAME,
4 AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
5 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,
6 MemberRecord, MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState,
7 TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,
8 8 };
9 9
10 10 #[test]
@@ -546,11 +546,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
546 546 let path = directory.path().join("nested").join("cache.sqlite3");
547 547 {
548 548 let store = Store::open(&path).unwrap();
549 assert_eq!(store.schema_version().unwrap(), 22);
549 assert_eq!(store.schema_version().unwrap(), 23);
550 550 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
551 551 }
552 552 let reopened = Store::open(&path).unwrap();
553 assert_eq!(reopened.schema_version().unwrap(), 22);
553 assert_eq!(reopened.schema_version().unwrap(), 23);
554 554 assert_eq!(reopened.message_count("c").unwrap(), 1);
555 555 drop(reopened);
556 556 let mode: String = rusqlite_open(&path)
@@ -582,7 +582,7 @@ fn old_schema_is_upgraded_in_place() {
582 582 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
583 583 drop(connection);
584 584 let store = Store::open(&path).unwrap();
585 assert_eq!(store.schema_version().unwrap(), 22);
585 assert_eq!(store.schema_version().unwrap(), 23);
586 586 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
587 587 }
588 588
@@ -648,7 +648,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
648 648 let store = Store::open(&path).unwrap();
649 649 let state = store.sync_state("c").unwrap().unwrap();
650 650 assert_eq!(state.delta_link, None);
651 assert_eq!(store.schema_version().unwrap(), 22);
651 assert_eq!(store.schema_version().unwrap(), 23);
652 652 }
653 653
654 654 #[test]
@@ -677,7 +677,10 @@ fn migration_to_v13_clears_channel_delta_links_only() {
677 677 }
678 678 let store = Store::open(&path).unwrap();
679 679 assert_eq!(
680 store.sync_state("ch").unwrap().and_then(|state| state.delta_link),
680 store
681 .sync_state("ch")
682 .unwrap()
683 .and_then(|state| state.delta_link),
681 684 None
682 685 );
683 686 assert_eq!(
@@ -1302,6 +1305,98 @@ fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {
1302 1305 assert_eq!(team().channel_notifications("c2"), off);
1303 1306 }
1304 1307
1308 #[test]
1309 fn channel_mentions_are_replaced_whole_and_cleared_per_channel() {
1310 let store = Store::open_in_memory().unwrap();
1311 store
1312 .upsert_teams(&[TeamRecord {
1313 id: "t1".to_owned(),
1314 name: "Alpha".to_owned(),
1315 }])
1316 .unwrap();
1317 let channel = |id: &str, name: &str| ChannelRecord {
1318 id: id.to_owned(),
1319 team_id: "t1".to_owned(),
1320 name: name.to_owned(),
1321 membership_type: None,
1322 last_message_at: None,
1323 unread: true,
1324 };
1325 store
1326 .upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1327 .unwrap();
1328 let counts = |personal, channel, team| ChannelMentions {
1329 personal,
1330 channel,
1331 team,
1332 };
1333 store
1334 .replace_channel_mentions(&[
1335 ("c1".to_owned(), counts(2, 0, 1)),
1336 ("c2".to_owned(), counts(0, 0, 0)),
1337 ])
1338 .unwrap();
1339 let team = || store.sidebar().unwrap().teams.remove(0);
1340 assert_eq!(team().channel_mentions("c1"), counts(2, 0, 1));
1341 assert!(!team().mentions.contains_key("c2"));
1342 store
1343 .replace_channel_mentions(&[("c2".to_owned(), counts(0, 1, 0))])
1344 .unwrap();
1345 assert_eq!(team().channel_mentions("c1"), ChannelMentions::default());
1346 assert_eq!(team().channel_mentions("c2"), counts(0, 1, 0));
1347 store.clear_channel_mentions("c2").unwrap();
1348 assert!(team().mentions.is_empty());
1349 }
1350
1351 #[test]
1352 fn the_team_thread_id_is_the_general_channel_id() {
1353 let store = Store::open_in_memory().unwrap();
1354 store
1355 .upsert_teams(&["group-a", "group-b"].map(|id| TeamRecord {
1356 id: id.to_owned(),
1357 name: id.to_owned(),
1358 }))
1359 .unwrap();
1360 let channel = |id: &str, team_id: &str, name: &str| ChannelRecord {
1361 id: id.to_owned(),
1362 team_id: team_id.to_owned(),
1363 name: name.to_owned(),
1364 membership_type: None,
1365 last_message_at: None,
1366 unread: false,
1367 };
1368 store
1369 .upsert_channels(&[
1370 channel("19:a-random", "group-a", "Random"),
1371 channel("19:a-general", "group-a", "General"),
1372 channel("19:b-renamed", "group-b", "Allgemein"),
1373 channel("19:b-other", "group-b", "Other"),
1374 ])
1375 .unwrap();
1376 store
1377 .replace_team_layout(&[TeamLayoutRecord {
1378 team_id: "group-b".to_owned(),
1379 hidden: false,
1380 channels: vec![ChannelLayoutRecord {
1381 channel_id: "19:b-renamed".to_owned(),
1382 general: true,
1383 hidden: false,
1384 tabs: Vec::new(),
1385 notifications: ChannelNotifications::default(),
1386 }],
1387 }])
1388 .unwrap();
1389 assert_eq!(
1390 store.team_thread_id("group-a").unwrap().as_deref(),
1391 Some("19:a-general")
1392 );
1393 assert_eq!(
1394 store.team_thread_id("group-b").unwrap().as_deref(),
1395 Some("19:b-renamed")
1396 );
1397 assert_eq!(store.team_thread_id("group-c").unwrap(), None);
1398 }
1399
1305 1400 #[test]
1306 1401 fn recent_messages_run_newest_first_across_scopes_with_a_cursor() {
1307 1402 let store = Store::open_in_memory().unwrap();
@@ -1411,23 +1506,33 @@ fn migration_to_v20_adds_the_call_event_column() {
1411 1506 {
1412 1507 let store = Store::open(&path).unwrap();
1413 1508 store.upsert_messages(&[message("c", "old", 1)]).unwrap();
1414 store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1509 store
1510 .upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1511 .unwrap();
1415 1512 store.set_sync_state("c", &SyncState::default()).unwrap();
1416 store.set_sync_state("channel", &SyncState::default()).unwrap();
1513 store
1514 .set_sync_state("channel", &SyncState::default())
1515 .unwrap();
1417 1516 drop(store);
1418 1517 Connection::open(&path)
1419 1518 .unwrap()
1420 .execute_batch("ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19")
1519 .execute_batch(
1520 "ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19",
1521 )
1421 1522 .unwrap();
1422 1523 }
1423 1524 let store = Store::open(&path).unwrap();
1424 assert_eq!(store.schema_version().unwrap(), 22);
1525 assert_eq!(store.schema_version().unwrap(), 23);
1425 1526 let old = store.messages("c", None, 10).unwrap();
1426 1527 assert_eq!(old[0].call_event_json, None);
1427 1528 assert!(store.sync_state("c").unwrap().is_none());
1428 1529 assert!(store.sync_state("channel").unwrap().is_some());
1429 1530 store.upsert_messages(&[call_message("call", 2)]).unwrap();
1430 assert!(store.messages("c", None, 10).unwrap()[1].call_event_json.is_some());
1531 assert!(
1532 store.messages("c", None, 10).unwrap()[1]
1533 .call_event_json
1534 .is_some()
1535 );
1431 1536 }
1432 1537
1433 1538 #[test]
@@ -1436,7 +1541,9 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1436 1541 let path = directory.path().join("old.sqlite3");
1437 1542 {
1438 1543 let store = Store::open(&path).unwrap();
1439 store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1544 store
1545 .upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1546 .unwrap();
1440 1547 store
1441 1548 .upsert_teams(&[TeamRecord {
1442 1549 id: "team".to_owned(),
@@ -1465,7 +1572,7 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1465 1572 .unwrap();
1466 1573 }
1467 1574 let store = Store::open(&path).unwrap();
1468 assert_eq!(store.schema_version().unwrap(), 22);
1575 assert_eq!(store.schema_version().unwrap(), 23);
1469 1576 assert!(store.sync_state("c").unwrap().is_none());
1470 1577 assert!(store.sync_state("channel").unwrap().is_none());
1471 1578 assert!(store.sync_state("other").unwrap().is_some());
@@ -1485,7 +1592,9 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1485 1592 let path = directory.path().join("old.sqlite3");
1486 1593 {
1487 1594 let store = Store::open(&path).unwrap();
1488 store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1595 store
1596 .upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1597 .unwrap();
1489 1598 drop(store);
1490 1599 Connection::open(&path)
1491 1600 .unwrap()
@@ -1493,9 +1602,12 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1493 1602 .unwrap();
1494 1603 }
1495 1604 let store = Store::open(&path).unwrap();
1496 assert_eq!(store.schema_version().unwrap(), 22);
1605 assert_eq!(store.schema_version().unwrap(), 23);
1497 1606 assert!(store.read_horizons("c").unwrap().is_empty());
1498 let horizons = [horizon("8:orgid:ada", 3, Some(4)), horizon("8:orgid:bob", 2, None)];
1607 let horizons = [
1608 horizon("8:orgid:ada", 3, Some(4)),
1609 horizon("8:orgid:bob", 2, None),
1610 ];
1499 1611 store.set_read_horizons("c", &horizons).unwrap();
1500 1612 drop(store);
1501 1613 let reopened = Store::open(&path).unwrap();
@@ -1505,9 +1617,14 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1505 1617 #[test]
1506 1618 fn setting_read_horizons_replaces_the_conversation_only() {
1507 1619 let store = Store::open_in_memory().unwrap();
1508 let first = [horizon("8:orgid:ada", 3, None), horizon("8:orgid:bob", 2, None)];
1620 let first = [
1621 horizon("8:orgid:ada", 3, None),
1622 horizon("8:orgid:bob", 2, None),
1623 ];
1509 1624 store.set_read_horizons("c", &first).unwrap();
1510 store.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)]).unwrap();
1625 store
1626 .set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)])
1627 .unwrap();
1511 1628 let second = [horizon("8:orgid:ada", 5, Some(6))];
1512 1629 store.set_read_horizons("c", &second).unwrap();
1513 1630 assert_eq!(store.read_horizons("c").unwrap(), second);
@@ -1,10 +1,10 @@
1use chrono::{DateTime, TimeZone, Utc};
1use chrono::{DateTime, TimeZone, Utc};
2use rusqlite::Connection;
2use rusqlite::Connection;
3use store::{
3use store::{
4 AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,
4 AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
5 ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
5 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,
6 MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,
6 MemberRecord, MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState,
7 TeamRecord, UNKNOWN_USER_NAME,
7 TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,
8};
8};
9
9
10#[test]
10#[test]
@@ -546,11 +546,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
546 let path = directory.path().join("nested").join("cache.sqlite3");
546 let path = directory.path().join("nested").join("cache.sqlite3");
547 {
547 {
548 let store = Store::open(&path).unwrap();
548 let store = Store::open(&path).unwrap();
549 assert_eq!(store.schema_version().unwrap(), 22);
549 assert_eq!(store.schema_version().unwrap(), 23);
550 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
550 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
551 }
551 }
552 let reopened = Store::open(&path).unwrap();
552 let reopened = Store::open(&path).unwrap();
553 assert_eq!(reopened.schema_version().unwrap(), 22);
553 assert_eq!(reopened.schema_version().unwrap(), 23);
554 assert_eq!(reopened.message_count("c").unwrap(), 1);
554 assert_eq!(reopened.message_count("c").unwrap(), 1);
555 drop(reopened);
555 drop(reopened);
556 let mode: String = rusqlite_open(&path)
556 let mode: String = rusqlite_open(&path)
@@ -582,7 +582,7 @@ fn old_schema_is_upgraded_in_place() {
582 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
582 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
583 drop(connection);
583 drop(connection);
584 let store = Store::open(&path).unwrap();
584 let store = Store::open(&path).unwrap();
585 assert_eq!(store.schema_version().unwrap(), 22);
585 assert_eq!(store.schema_version().unwrap(), 23);
586 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
586 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
587}
587}
588
588
@@ -648,7 +648,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
648 let store = Store::open(&path).unwrap();
648 let store = Store::open(&path).unwrap();
649 let state = store.sync_state("c").unwrap().unwrap();
649 let state = store.sync_state("c").unwrap().unwrap();
650 assert_eq!(state.delta_link, None);
650 assert_eq!(state.delta_link, None);
651 assert_eq!(store.schema_version().unwrap(), 22);
651 assert_eq!(store.schema_version().unwrap(), 23);
652}
652}
653
653
654#[test]
654#[test]
@@ -677,7 +677,10 @@ fn migration_to_v13_clears_channel_delta_links_only() {
677 }
677 }
678 let store = Store::open(&path).unwrap();
678 let store = Store::open(&path).unwrap();
679 assert_eq!(
679 assert_eq!(
680 store.sync_state("ch").unwrap().and_then(|state| state.delta_link),
680 store
681 .sync_state("ch")
682 .unwrap()
683 .and_then(|state| state.delta_link),
681 None
684 None
682 );
685 );
683 assert_eq!(
686 assert_eq!(
@@ -1302,6 +1305,98 @@ fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {
1302 assert_eq!(team().channel_notifications("c2"), off);
1305 assert_eq!(team().channel_notifications("c2"), off);
1303}
1306}
1304
1307
1308#[test]
1309fn channel_mentions_are_replaced_whole_and_cleared_per_channel() {
1310 let store = Store::open_in_memory().unwrap();
1311 store
1312 .upsert_teams(&[TeamRecord {
1313 id: "t1".to_owned(),
1314 name: "Alpha".to_owned(),
1315 }])
1316 .unwrap();
1317 let channel = |id: &str, name: &str| ChannelRecord {
1318 id: id.to_owned(),
1319 team_id: "t1".to_owned(),
1320 name: name.to_owned(),
1321 membership_type: None,
1322 last_message_at: None,
1323 unread: true,
1324 };
1325 store
1326 .upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1327 .unwrap();
1328 let counts = |personal, channel, team| ChannelMentions {
1329 personal,
1330 channel,
1331 team,
1332 };
1333 store
1334 .replace_channel_mentions(&[
1335 ("c1".to_owned(), counts(2, 0, 1)),
1336 ("c2".to_owned(), counts(0, 0, 0)),
1337 ])
1338 .unwrap();
1339 let team = || store.sidebar().unwrap().teams.remove(0);
1340 assert_eq!(team().channel_mentions("c1"), counts(2, 0, 1));
1341 assert!(!team().mentions.contains_key("c2"));
1342 store
1343 .replace_channel_mentions(&[("c2".to_owned(), counts(0, 1, 0))])
1344 .unwrap();
1345 assert_eq!(team().channel_mentions("c1"), ChannelMentions::default());
1346 assert_eq!(team().channel_mentions("c2"), counts(0, 1, 0));
1347 store.clear_channel_mentions("c2").unwrap();
1348 assert!(team().mentions.is_empty());
1349}
1350
1351#[test]
1352fn the_team_thread_id_is_the_general_channel_id() {
1353 let store = Store::open_in_memory().unwrap();
1354 store
1355 .upsert_teams(&["group-a", "group-b"].map(|id| TeamRecord {
1356 id: id.to_owned(),
1357 name: id.to_owned(),
1358 }))
1359 .unwrap();
1360 let channel = |id: &str, team_id: &str, name: &str| ChannelRecord {
1361 id: id.to_owned(),
1362 team_id: team_id.to_owned(),
1363 name: name.to_owned(),
1364 membership_type: None,
1365 last_message_at: None,
1366 unread: false,
1367 };
1368 store
1369 .upsert_channels(&[
1370 channel("19:a-random", "group-a", "Random"),
1371 channel("19:a-general", "group-a", "General"),
1372 channel("19:b-renamed", "group-b", "Allgemein"),
1373 channel("19:b-other", "group-b", "Other"),
1374 ])
1375 .unwrap();
1376 store
1377 .replace_team_layout(&[TeamLayoutRecord {
1378 team_id: "group-b".to_owned(),
1379 hidden: false,
1380 channels: vec![ChannelLayoutRecord {
1381 channel_id: "19:b-renamed".to_owned(),
1382 general: true,
1383 hidden: false,
1384 tabs: Vec::new(),
1385 notifications: ChannelNotifications::default(),
1386 }],
1387 }])
1388 .unwrap();
1389 assert_eq!(
1390 store.team_thread_id("group-a").unwrap().as_deref(),
1391 Some("19:a-general")
1392 );
1393 assert_eq!(
1394 store.team_thread_id("group-b").unwrap().as_deref(),
1395 Some("19:b-renamed")
1396 );
1397 assert_eq!(store.team_thread_id("group-c").unwrap(), None);
1398}
1399
1305#[test]
1400#[test]
1306fn recent_messages_run_newest_first_across_scopes_with_a_cursor() {
1401fn recent_messages_run_newest_first_across_scopes_with_a_cursor() {
1307 let store = Store::open_in_memory().unwrap();
1402 let store = Store::open_in_memory().unwrap();
@@ -1411,23 +1506,33 @@ fn migration_to_v20_adds_the_call_event_column() {
1411 {
1506 {
1412 let store = Store::open(&path).unwrap();
1507 let store = Store::open(&path).unwrap();
1413 store.upsert_messages(&[message("c", "old", 1)]).unwrap();
1508 store.upsert_messages(&[message("c", "old", 1)]).unwrap();
1414 store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1509 store
1510 .upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1511 .unwrap();
1415 store.set_sync_state("c", &SyncState::default()).unwrap();
1512 store.set_sync_state("c", &SyncState::default()).unwrap();
1416 store.set_sync_state("channel", &SyncState::default()).unwrap();
1513 store
1514 .set_sync_state("channel", &SyncState::default())
1515 .unwrap();
1417 drop(store);
1516 drop(store);
1418 Connection::open(&path)
1517 Connection::open(&path)
1419 .unwrap()
1518 .unwrap()
1420 .execute_batch("ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19")
1519 .execute_batch(
1520 "ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19",
1521 )
1421 .unwrap();
1522 .unwrap();
1422 }
1523 }
1423 let store = Store::open(&path).unwrap();
1524 let store = Store::open(&path).unwrap();
1424 assert_eq!(store.schema_version().unwrap(), 22);
1525 assert_eq!(store.schema_version().unwrap(), 23);
1425 let old = store.messages("c", None, 10).unwrap();
1526 let old = store.messages("c", None, 10).unwrap();
1426 assert_eq!(old[0].call_event_json, None);
1527 assert_eq!(old[0].call_event_json, None);
1427 assert!(store.sync_state("c").unwrap().is_none());
1528 assert!(store.sync_state("c").unwrap().is_none());
1428 assert!(store.sync_state("channel").unwrap().is_some());
1529 assert!(store.sync_state("channel").unwrap().is_some());
1429 store.upsert_messages(&[call_message("call", 2)]).unwrap();
1530 store.upsert_messages(&[call_message("call", 2)]).unwrap();
1430 assert!(store.messages("c", None, 10).unwrap()[1].call_event_json.is_some());
1531 assert!(
1532 store.messages("c", None, 10).unwrap()[1]
1533 .call_event_json
1534 .is_some()
1535 );
1431}
1536}
1432
1537
1433#[test]
1538#[test]
@@ -1436,7 +1541,9 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1436 let path = directory.path().join("old.sqlite3");
1541 let path = directory.path().join("old.sqlite3");
1437 {
1542 {
1438 let store = Store::open(&path).unwrap();
1543 let store = Store::open(&path).unwrap();
1439 store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1544 store
1545 .upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1546 .unwrap();
1440 store
1547 store
1441 .upsert_teams(&[TeamRecord {
1548 .upsert_teams(&[TeamRecord {
1442 id: "team".to_owned(),
1549 id: "team".to_owned(),
@@ -1465,7 +1572,7 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1465 .unwrap();
1572 .unwrap();
1466 }
1573 }
1467 let store = Store::open(&path).unwrap();
1574 let store = Store::open(&path).unwrap();
1468 assert_eq!(store.schema_version().unwrap(), 22);
1575 assert_eq!(store.schema_version().unwrap(), 23);
1469 assert!(store.sync_state("c").unwrap().is_none());
1576 assert!(store.sync_state("c").unwrap().is_none());
1470 assert!(store.sync_state("channel").unwrap().is_none());
1577 assert!(store.sync_state("channel").unwrap().is_none());
1471 assert!(store.sync_state("other").unwrap().is_some());
1578 assert!(store.sync_state("other").unwrap().is_some());
@@ -1485,7 +1592,9 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1485 let path = directory.path().join("old.sqlite3");
1592 let path = directory.path().join("old.sqlite3");
1486 {
1593 {
1487 let store = Store::open(&path).unwrap();
1594 let store = Store::open(&path).unwrap();
1488 store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1595 store
1596 .upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1597 .unwrap();
1489 drop(store);
1598 drop(store);
1490 Connection::open(&path)
1599 Connection::open(&path)
1491 .unwrap()
1600 .unwrap()
@@ -1493,9 +1602,12 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1493 .unwrap();
1602 .unwrap();
1494 }
1603 }
1495 let store = Store::open(&path).unwrap();
1604 let store = Store::open(&path).unwrap();
1496 assert_eq!(store.schema_version().unwrap(), 22);
1605 assert_eq!(store.schema_version().unwrap(), 23);
1497 assert!(store.read_horizons("c").unwrap().is_empty());
1606 assert!(store.read_horizons("c").unwrap().is_empty());
1498 let horizons = [horizon("8:orgid:ada", 3, Some(4)), horizon("8:orgid:bob", 2, None)];
1607 let horizons = [
1608 horizon("8:orgid:ada", 3, Some(4)),
1609 horizon("8:orgid:bob", 2, None),
1610 ];
1499 store.set_read_horizons("c", &horizons).unwrap();
1611 store.set_read_horizons("c", &horizons).unwrap();
1500 drop(store);
1612 drop(store);
1501 let reopened = Store::open(&path).unwrap();
1613 let reopened = Store::open(&path).unwrap();
@@ -1505,9 +1617,14 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1505#[test]
1617#[test]
1506fn setting_read_horizons_replaces_the_conversation_only() {
1618fn setting_read_horizons_replaces_the_conversation_only() {
1507 let store = Store::open_in_memory().unwrap();
1619 let store = Store::open_in_memory().unwrap();
1508 let first = [horizon("8:orgid:ada", 3, None), horizon("8:orgid:bob", 2, None)];
1620 let first = [
1621 horizon("8:orgid:ada", 3, None),
1622 horizon("8:orgid:bob", 2, None),
1623 ];
1509 store.set_read_horizons("c", &first).unwrap();
1624 store.set_read_horizons("c", &first).unwrap();
1510 store.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)]).unwrap();
1625 store
1626 .set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)])
1627 .unwrap();
1511 let second = [horizon("8:orgid:ada", 5, Some(6))];
1628 let second = [horizon("8:orgid:ada", 5, Some(6))];
1512 store.set_read_horizons("c", &second).unwrap();
1629 store.set_read_horizons("c", &second).unwrap();
1513 assert_eq!(store.read_horizons("c").unwrap(), second);
1630 assert_eq!(store.read_horizons("c").unwrap(), second);
vendor/gpui-component/src/message_scroller.rs +5 −0
@@ -67,6 +67,11 @@ impl MessageScrollerState {
67 67 && !self.list_state.is_scrolled_to_end().unwrap_or(false)
68 68 }
69 69
70 /// Return the index of the row at the top of the viewport.
71 pub fn top_item(&self) -> usize {
72 self.list_state.logical_scroll_top().item_ix
73 }
74
70 75 /// Return whether the list is actively following its tail.
71 76 pub fn is_following_tail(&self) -> bool {
72 77 self.list_state.is_following_tail()
@@ -67,6 +67,11 @@ impl MessageScrollerState {
67 && !self.list_state.is_scrolled_to_end().unwrap_or(false)
67 && !self.list_state.is_scrolled_to_end().unwrap_or(false)
68 }
68 }
69
69
70 /// Return the index of the row at the top of the viewport.
71 pub fn top_item(&self) -> usize {
72 self.list_state.logical_scroll_top().item_ix
73 }
74
70 /// Return whether the list is actively following its tail.
75 /// Return whether the list is actively following its tail.
71 pub fn is_following_tail(&self) -> bool {
76 pub fn is_following_tail(&self) -> bool {
72 self.list_state.is_following_tail()
77 self.list_state.is_following_tail()