BlueGit

ict rusty-teams

feat(channels): pinned posts like Teams, skype token on pin routes

- No pin banner in channels (Teams has none); the chat banner and its top gap stay
- Pinned root posts show the "Pinned" status in the post header
- Channel details pane from a header toggle ("Open channel details") with the Teams "Pinned" section: 3 posts, See all, Back, jump to post
- Pin routes send x-skypetoken and x-csendpoint from authsvc authz next to the CSA bearer, like Teams
- layout_guard: banner gap check for chats, no banner in channels, details pane bounds

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
532e5f8d7914781602f5d143c1a7d276aa630057
Parent
9af01ed6
12 files changed +681 −79
crates/app/src/layout_guard.rs +69 −27
@@ -180,6 +180,7 @@ 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::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
183 184 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
184 185 use crate::views::message_row::BUBBLE_TAGS;
185 186 use crate::views::pin_banner::PIN_BANNER_TAG;
@@ -1371,38 +1372,79 @@ mod frames {
1371 1372 let mut found = Vec::new();
1372 1373 for (width, height) in SIZES {
1373 1374 visual.simulate_resize(size(px(width), px(height)));
1374 for selection in [
1375 Selection::Chat(PINNED_CHAT.to_owned()),
1376 Selection::Channel(PINNED_CHANNEL.to_owned()),
1377 ] {
1378 let in_chat = matches!(selection, Selection::Chat(_));
1379 visual.update(|_, cx| state.update(cx, |state, cx| state.select(selection, cx)));
1380 collect(&mut visual, Some(PIN_BANNER_TAG));
1381 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
1382 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
1383 let mut gaps = vec![
1384 ("top", f32::from(banner.top() - timeline.top())),
1385 ("left", f32::from(banner.left() - timeline.left())),
1386 ("right", f32::from(timeline.right() - banner.right())),
1387 ];
1388 if in_chat {
1389 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1390 gaps.push(("below divider", f32::from(banner.top() - divider.bottom())));
1391 }
1392 let side = gaps[1].1;
1393 if gaps
1394 .iter()
1395 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1396 {
1397 found.push(format!(
1398 "pin banner@{width}x{height} chat={in_chat}: gaps {gaps:?} must match"
1399 ));
1400 }
1375 visual.update(|_, cx| {
1376 state.update(cx, |state, cx| {
1377 state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)
1378 })
1379 });
1380 collect(&mut visual, Some(PIN_BANNER_TAG));
1381 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
1382 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
1383 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1384 let gaps = [
1385 ("top", f32::from(banner.top() - timeline.top())),
1386 ("left", f32::from(banner.left() - timeline.left())),
1387 ("right", f32::from(timeline.right() - banner.right())),
1388 ("below divider", f32::from(banner.top() - divider.bottom())),
1389 ];
1390 let side = gaps[1].1;
1391 if gaps
1392 .iter()
1393 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1394 {
1395 found.push(format!(
1396 "pin banner@{width}x{height}: gaps {gaps:?} must match"
1397 ));
1401 1398 }
1402 1399 }
1403 1400 assert!(found.is_empty(), "{}", found.join("\n"));
1404 1401 }
1405 1402
1403 #[gpui_kit::test]
1404 fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {
1405 let (handle, state) = mount(cx);
1406 let mut visual = VisualTestContext::from_window(handle, cx);
1407 visual.simulate_resize(size(px(1280.), px(800.)));
1408 visual.update(|_, cx| {
1409 state.update(cx, |state, cx| {
1410 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1411 })
1412 });
1413 collect(&mut visual, Some(TIMELINE_TAG));
1414 assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());
1415 }
1416
1417 #[gpui_kit::test]
1418 fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {
1419 let (handle, state) = mount(cx);
1420 let mut visual = VisualTestContext::from_window(handle, cx);
1421 visual.simulate_resize(size(px(1280.), px(800.)));
1422 visual.update(|_, cx| {
1423 state.update(cx, |state, cx| {
1424 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1425 })
1426 });
1427 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1428 let button = visual
1429 .debug_bounds(CHANNEL_DETAILS_BUTTON)
1430 .expect("channel details button");
1431 visual.simulate_click(button.center(), Default::default());
1432 collect(&mut visual, Some(CHANNEL_DETAILS_TAG));
1433 let pane = visual
1434 .debug_bounds(CHANNEL_DETAILS_TAG)
1435 .expect("details pane");
1436 let main = visual.debug_bounds(MAIN).expect("main island");
1437 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1438 assert!(
1439 (f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,
1440 "pane {pane:?} must end at the main island edge {main:?}"
1441 );
1442 assert!(
1443 (f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,
1444 "pane {pane:?} must start under the header divider {divider:?}"
1445 );
1446 }
1447
1406 1448 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1407 1449 collect(visual, Some(COMPOSER_SEND_TAG));
1408 1450 let mut bounds_of = |path: &'static str| {
@@ -180,6 +180,7 @@ 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::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
183 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_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;
185 use crate::views::pin_banner::PIN_BANNER_TAG;
186 use crate::views::pin_banner::PIN_BANNER_TAG;
@@ -1371,38 +1372,79 @@ mod frames {
1371 let mut found = Vec::new();
1372 let mut found = Vec::new();
1372 for (width, height) in SIZES {
1373 for (width, height) in SIZES {
1373 visual.simulate_resize(size(px(width), px(height)));
1374 visual.simulate_resize(size(px(width), px(height)));
1374 for selection in [
1375 visual.update(|_, cx| {
1375 Selection::Chat(PINNED_CHAT.to_owned()),
1376 state.update(cx, |state, cx| {
1376 Selection::Channel(PINNED_CHANNEL.to_owned()),
1377 state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)
1377 ] {
1378 })
1378 let in_chat = matches!(selection, Selection::Chat(_));
1379 });
1379 visual.update(|_, cx| state.update(cx, |state, cx| state.select(selection, cx)));
1380 collect(&mut visual, Some(PIN_BANNER_TAG));
1380 collect(&mut visual, Some(PIN_BANNER_TAG));
1381 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
1381 let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
1382 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
1382 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
1383 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1383 let mut gaps = vec![
1384 let gaps = [
1384 ("top", f32::from(banner.top() - timeline.top())),
1385 ("top", f32::from(banner.top() - timeline.top())),
1385 ("left", f32::from(banner.left() - timeline.left())),
1386 ("left", f32::from(banner.left() - timeline.left())),
1386 ("right", f32::from(timeline.right() - banner.right())),
1387 ("right", f32::from(timeline.right() - banner.right())),
1387 ];
1388 ("below divider", f32::from(banner.top() - divider.bottom())),
1388 if in_chat {
1389 ];
1389 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1390 let side = gaps[1].1;
1390 gaps.push(("below divider", f32::from(banner.top() - divider.bottom())));
1391 if gaps
1391 }
1392 .iter()
1392 let side = gaps[1].1;
1393 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1393 if gaps
1394 {
1394 .iter()
1395 found.push(format!(
1395 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1396 "pin banner@{width}x{height}: gaps {gaps:?} must match"
1396 {
1397 ));
1397 found.push(format!(
1398 "pin banner@{width}x{height} chat={in_chat}: gaps {gaps:?} must match"
1399 ));
1400 }
1401 }
1398 }
1402 }
1399 }
1403 assert!(found.is_empty(), "{}", found.join("\n"));
1400 assert!(found.is_empty(), "{}", found.join("\n"));
1404 }
1401 }
1405
1402
1403 #[gpui_kit::test]
1404 fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {
1405 let (handle, state) = mount(cx);
1406 let mut visual = VisualTestContext::from_window(handle, cx);
1407 visual.simulate_resize(size(px(1280.), px(800.)));
1408 visual.update(|_, cx| {
1409 state.update(cx, |state, cx| {
1410 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1411 })
1412 });
1413 collect(&mut visual, Some(TIMELINE_TAG));
1414 assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());
1415 }
1416
1417 #[gpui_kit::test]
1418 fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {
1419 let (handle, state) = mount(cx);
1420 let mut visual = VisualTestContext::from_window(handle, cx);
1421 visual.simulate_resize(size(px(1280.), px(800.)));
1422 visual.update(|_, cx| {
1423 state.update(cx, |state, cx| {
1424 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1425 })
1426 });
1427 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1428 let button = visual
1429 .debug_bounds(CHANNEL_DETAILS_BUTTON)
1430 .expect("channel details button");
1431 visual.simulate_click(button.center(), Default::default());
1432 collect(&mut visual, Some(CHANNEL_DETAILS_TAG));
1433 let pane = visual
1434 .debug_bounds(CHANNEL_DETAILS_TAG)
1435 .expect("details pane");
1436 let main = visual.debug_bounds(MAIN).expect("main island");
1437 let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1438 assert!(
1439 (f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,
1440 "pane {pane:?} must end at the main island edge {main:?}"
1441 );
1442 assert!(
1443 (f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,
1444 "pane {pane:?} must start under the header divider {divider:?}"
1445 );
1446 }
1447
1406 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1448 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1407 collect(visual, Some(COMPOSER_SEND_TAG));
1449 collect(visual, Some(COMPOSER_SEND_TAG));
1408 let mut bounds_of = |path: &'static str| {
1450 let mut bounds_of = |path: &'static str| {
crates/app/src/views/conversation.rs +39 −24
@@ -21,6 +21,8 @@ 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};
24 26 mod detached;
25 27 mod feed;
26 28 mod pins;
@@ -211,6 +213,8 @@ pub struct ConversationView {
211 213 reaction_details: Option<ReactionDetails>,
212 214 highlighted_message: Option<String>,
213 215 pin_index: usize,
216 channel_details_open: bool,
217 pinned_posts_expanded: bool,
214 218 pin_previews: HashMap<String, pins::PinPreview>,
215 219 pin_fetches: HashSet<String>,
216 220 notice: Option<String>,
@@ -540,6 +544,8 @@ impl ConversationView {
540 544 reaction_details: None,
541 545 highlighted_message: None,
542 546 pin_index: 0,
547 channel_details_open: false,
548 pinned_posts_expanded: false,
543 549 pin_previews: HashMap::new(),
544 550 pin_fetches: HashSet::new(),
545 551 notice: None,
@@ -882,6 +888,7 @@ impl ConversationView {
882 888 self.start_fetch(cx);
883 889 self.mark_read(ReadTrigger::Open, cx);
884 890 self.refresh_pin_previews(cx);
891 self.pinned_posts_expanded = false;
885 892 if let Some(conversation_id) = self.pin_conversation_id() {
886 893 self.app
887 894 .update(cx, |state, cx| state.refresh_pins(&conversation_id, cx));
@@ -3425,6 +3432,7 @@ impl ConversationView {
3425 3432 .children(inline_tabs)
3426 3433 .children(stack)
3427 3434 .children(call_controls)
3435 .children(self.channel_details_button(cx))
3428 3436 }
3429 3437 }
3430 3438
@@ -3650,33 +3658,40 @@ impl Render for ConversationView {
3650 3658 } else {
3651 3659 scroller.into_any_element()
3652 3660 };
3661 let channel_details = self.render_channel_details(cx);
3662 let content = v_flex()
3663 .relative()
3664 .flex_1()
3665 .min_w_0()
3666 .min_h_0()
3667 .children(new_post)
3668 .child(
3669 div()
3670 .debug_selector(|| TIMELINE_TAG.into())
3671 .relative()
3672 .flex_1()
3673 .min_h_0()
3674 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3675 .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx)))
3676 .child(body)
3677 .children(pin_banner.map(pin_banner_overlay)),
3678 )
3679 .children(self.render_draft_error(cx))
3680 .when(!in_feed && !recap_active, |column| {
3681 column
3682 .child(self.render_typing_line(cx))
3683 .children(self.render_proposal_card(cx))
3684 .child(self.composer.clone())
3685 })
3686 .child(self.render_drop_overlay(cx));
3653 3687 root.child(
3654 v_flex()
3655 .relative()
3688 h_flex()
3656 3689 .flex_1()
3657 3690 .min_h_0()
3658 .children(new_post)
3659 .child(
3660 div()
3661 .debug_selector(|| TIMELINE_TAG.into())
3662 .relative()
3663 .flex_1()
3664 .min_h_0()
3665 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3666 .on_scroll_wheel(
3667 cx.listener(|this, _, _, cx| this.close_reaction_details(cx)),
3668 )
3669 .child(body)
3670 .children(pin_banner.map(pin_banner_overlay)),
3671 )
3672 .children(self.render_draft_error(cx))
3673 .when(!in_feed && !recap_active, |column| {
3674 column
3675 .child(self.render_typing_line(cx))
3676 .children(self.render_proposal_card(cx))
3677 .child(self.composer.clone())
3678 })
3679 .child(self.render_drop_overlay(cx)),
3691 .w_full()
3692 .items_stretch()
3693 .child(content)
3694 .children(channel_details),
3680 3695 )
3681 3696 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3682 3697 if this.reaction_details.is_some() {
@@ -21,6 +21,8 @@ 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};
24mod detached;
26mod detached;
25mod feed;
27mod feed;
26mod pins;
28mod pins;
@@ -211,6 +213,8 @@ pub struct ConversationView {
211 reaction_details: Option<ReactionDetails>,
213 reaction_details: Option<ReactionDetails>,
212 highlighted_message: Option<String>,
214 highlighted_message: Option<String>,
213 pin_index: usize,
215 pin_index: usize,
216 channel_details_open: bool,
217 pinned_posts_expanded: bool,
214 pin_previews: HashMap<String, pins::PinPreview>,
218 pin_previews: HashMap<String, pins::PinPreview>,
215 pin_fetches: HashSet<String>,
219 pin_fetches: HashSet<String>,
216 notice: Option<String>,
220 notice: Option<String>,
@@ -540,6 +544,8 @@ impl ConversationView {
540 reaction_details: None,
544 reaction_details: None,
541 highlighted_message: None,
545 highlighted_message: None,
542 pin_index: 0,
546 pin_index: 0,
547 channel_details_open: false,
548 pinned_posts_expanded: false,
543 pin_previews: HashMap::new(),
549 pin_previews: HashMap::new(),
544 pin_fetches: HashSet::new(),
550 pin_fetches: HashSet::new(),
545 notice: None,
551 notice: None,
@@ -882,6 +888,7 @@ impl ConversationView {
882 self.start_fetch(cx);
888 self.start_fetch(cx);
883 self.mark_read(ReadTrigger::Open, cx);
889 self.mark_read(ReadTrigger::Open, cx);
884 self.refresh_pin_previews(cx);
890 self.refresh_pin_previews(cx);
891 self.pinned_posts_expanded = false;
885 if let Some(conversation_id) = self.pin_conversation_id() {
892 if let Some(conversation_id) = self.pin_conversation_id() {
886 self.app
893 self.app
887 .update(cx, |state, cx| state.refresh_pins(&conversation_id, cx));
894 .update(cx, |state, cx| state.refresh_pins(&conversation_id, cx));
@@ -3425,6 +3432,7 @@ impl ConversationView {
3425 .children(inline_tabs)
3432 .children(inline_tabs)
3426 .children(stack)
3433 .children(stack)
3427 .children(call_controls)
3434 .children(call_controls)
3435 .children(self.channel_details_button(cx))
3428 }
3436 }
3429}
3437}
3430
3438
@@ -3650,33 +3658,40 @@ impl Render for ConversationView {
3650 } else {
3658 } else {
3651 scroller.into_any_element()
3659 scroller.into_any_element()
3652 };
3660 };
3661 let channel_details = self.render_channel_details(cx);
3662 let content = v_flex()
3663 .relative()
3664 .flex_1()
3665 .min_w_0()
3666 .min_h_0()
3667 .children(new_post)
3668 .child(
3669 div()
3670 .debug_selector(|| TIMELINE_TAG.into())
3671 .relative()
3672 .flex_1()
3673 .min_h_0()
3674 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3675 .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx)))
3676 .child(body)
3677 .children(pin_banner.map(pin_banner_overlay)),
3678 )
3679 .children(self.render_draft_error(cx))
3680 .when(!in_feed && !recap_active, |column| {
3681 column
3682 .child(self.render_typing_line(cx))
3683 .children(self.render_proposal_card(cx))
3684 .child(self.composer.clone())
3685 })
3686 .child(self.render_drop_overlay(cx));
3653 root.child(
3687 root.child(
3654 v_flex()
3688 h_flex()
3655 .relative()
3656 .flex_1()
3689 .flex_1()
3657 .min_h_0()
3690 .min_h_0()
3658 .children(new_post)
3691 .w_full()
3659 .child(
3692 .items_stretch()
3660 div()
3693 .child(content)
3661 .debug_selector(|| TIMELINE_TAG.into())
3694 .children(channel_details),
3662 .relative()
3663 .flex_1()
3664 .min_h_0()
3665 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3666 .on_scroll_wheel(
3667 cx.listener(|this, _, _, cx| this.close_reaction_details(cx)),
3668 )
3669 .child(body)
3670 .children(pin_banner.map(pin_banner_overlay)),
3671 )
3672 .children(self.render_draft_error(cx))
3673 .when(!in_feed && !recap_active, |column| {
3674 column
3675 .child(self.render_typing_line(cx))
3676 .children(self.render_proposal_card(cx))
3677 .child(self.composer.clone())
3678 })
3679 .child(self.render_drop_overlay(cx)),
3680 )
3695 )
3681 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3696 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3682 if this.reaction_details.is_some() {
3697 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/pins.rs +1 −1
@@ -140,7 +140,7 @@ impl ConversationView {
140 140 }
141 141
142 142 pub(super) fn render_pin_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
143 let conversation_id = self.pin_conversation_id()?;
143 let conversation_id = self.chat_id()?;
144 144 let pins = self.app.read(cx).pinned_messages(&conversation_id);
145 145 let pin = pins.get(self.pin_index)?;
146 146 let preview = self.pin_previews.get(&pin.message_id);
@@ -140,7 +140,7 @@ impl ConversationView {
140 }
140 }
141
141
142 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> {
143 let conversation_id = self.pin_conversation_id()?;
143 let conversation_id = self.chat_id()?;
144 let pins = self.app.read(cx).pinned_messages(&conversation_id);
144 let pins = self.app.read(cx).pinned_messages(&conversation_id);
145 let pin = pins.get(self.pin_index)?;
145 let pin = pins.get(self.pin_index)?;
146 let preview = self.pin_previews.get(&pin.message_id);
146 let preview = self.pin_previews.get(&pin.message_id);
crates/app/src/views/conversation/render_env.rs +16 −6
@@ -15,12 +15,12 @@ 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 25 use crate::views::message_row::{DeliveryActions, RowActions};
26 26 use crate::views::post_card::{PostAction, PostActions};
@@ -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,6 +304,10 @@ 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,
@@ -342,9 +350,11 @@ impl RenderEnv {
342 350 })
343 351 };
344 352 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 });
353 let share = recording
354 .and_then(|recording| recording.url.clone())
355 .map(|url| {
356 boxed(move |cx| cx.write_to_clipboard(ClipboardItem::new_string(url.clone())))
357 });
348 358 CallActions {
349 359 call_back,
350 360 join,
@@ -15,12 +15,12 @@ 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};
26use crate::views::post_card::{PostAction, PostActions};
26use crate::views::post_card::{PostAction, PostActions};
@@ -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,6 +304,10 @@ 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,
@@ -342,9 +350,11 @@ impl RenderEnv {
342 })
350 })
343 };
351 };
344 let recording = call.recap.as_ref().map(|recap| &recap.recording);
352 let recording = call.recap.as_ref().map(|recap| &recap.recording);
345 let share = recording.and_then(|recording| recording.url.clone()).map(|url| {
353 let share = recording
346 boxed(move |cx| cx.write_to_clipboard(ClipboardItem::new_string(url.clone())))
354 .and_then(|recording| recording.url.clone())
347 });
355 .map(|url| {
356 boxed(move |cx| cx.write_to_clipboard(ClipboardItem::new_string(url.clone())))
357 });
348 CallActions {
358 CallActions {
349 call_back,
359 call_back,
350 join,
360 join,
crates/app/src/views/message_row.rs +8 −9
@@ -80,6 +80,7 @@ pub struct RowActions {
80 80 pub open_image: Option<ImageActions>,
81 81 pub highlighted: bool,
82 82 pub saved: bool,
83 pub pinned: bool,
83 84 pub translation: Option<TranslationActions>,
84 85 pub timeline: TimelineBounds,
85 86 pub agent_run: Option<AgentRun>,
@@ -609,15 +610,12 @@ fn own_row(
609 610 let reaction_proposal = extras.reaction_proposal.take();
610 611 let mut column = v_flex().w_full().items_end().gap(px(2.));
611 612 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 ),
613 h_flex().w_full().justify_end().child(
614 div()
615 .min_w_0()
616 .max_w(bubble_max_width(&extras.timeline, 0.))
617 .child(bubble(row, index, true, directory, extras, cx)),
618 ),
621 619 );
622 620 column = column.children(agent_chip(agent_run));
623 621 column = column.children(reaction_proposal.map(|pill| reaction_pill(pill, &row.key)));
@@ -655,6 +653,7 @@ pub fn render_message_row(
655 653 timeline,
656 654 agent_run,
657 655 call: _,
656 pinned: _,
658 657 reaction_proposal,
659 658 } = actions;
660 659 let extras = BubbleExtras {
@@ -80,6 +80,7 @@ pub struct RowActions {
80 pub open_image: Option<ImageActions>,
80 pub open_image: Option<ImageActions>,
81 pub highlighted: bool,
81 pub highlighted: bool,
82 pub saved: bool,
82 pub saved: bool,
83 pub pinned: bool,
83 pub translation: Option<TranslationActions>,
84 pub translation: Option<TranslationActions>,
84 pub timeline: TimelineBounds,
85 pub timeline: TimelineBounds,
85 pub agent_run: Option<AgentRun>,
86 pub agent_run: Option<AgentRun>,
@@ -609,15 +610,12 @@ fn own_row(
609 let reaction_proposal = extras.reaction_proposal.take();
610 let reaction_proposal = extras.reaction_proposal.take();
610 let mut column = v_flex().w_full().items_end().gap(px(2.));
611 let mut column = v_flex().w_full().items_end().gap(px(2.));
611 column = column.child(
612 column = column.child(
612 h_flex()
613 h_flex().w_full().justify_end().child(
613 .w_full()
614 div()
614 .justify_end()
615 .min_w_0()
615 .child(
616 .max_w(bubble_max_width(&extras.timeline, 0.))
616 div()
617 .child(bubble(row, index, true, directory, extras, cx)),
617 .min_w_0()
618 ),
618 .max_w(bubble_max_width(&extras.timeline, 0.))
619 .child(bubble(row, index, true, directory, extras, cx)),
620 ),
621 );
619 );
622 column = column.children(agent_chip(agent_run));
620 column = column.children(agent_chip(agent_run));
623 column = column.children(reaction_proposal.map(|pill| reaction_pill(pill, &row.key)));
621 column = column.children(reaction_proposal.map(|pill| reaction_pill(pill, &row.key)));
@@ -655,6 +653,7 @@ pub fn render_message_row(
655 timeline,
653 timeline,
656 agent_run,
654 agent_run,
657 call: _,
655 call: _,
656 pinned: _,
658 reaction_proposal,
657 reaction_proposal,
659 } = actions;
658 } = actions;
660 let extras = BubbleExtras {
659 let extras = BubbleExtras {
crates/app/src/views/post_card.rs +22 −1
@@ -30,6 +30,7 @@ const AVATAR_GAP: f32 = 10.;
30 30 const CARD_PADDING: f32 = 12.;
31 31 const CARD_RADIUS: f32 = 10.;
32 32 const CARD_GAP: f32 = 12.;
33 const PINNED_LABEL: &str = "Pinned";
33 34 const SLOTS_PER_POST: usize = 64;
34 35 const TOOLBAR_RIGHT_INSET: f32 = 8.;
35 36 const SUBJECT_SIZE: f32 = 14.;
@@ -62,6 +63,16 @@ fn edited_marker() -> Div {
62 63 .child("Edited")
63 64 }
64 65
66 fn pinned_marker() -> Div {
67 h_flex()
68 .gap(px(3.))
69 .items_center()
70 .text_size(px(11.))
71 .text_color(theme::text_muted())
72 .child(icon(IconName::Pin, 11., theme::text_muted()))
73 .child(PINNED_LABEL)
74 }
75
65 76 fn message_content(
66 77 row: &MessageRow,
67 78 index: usize,
@@ -150,6 +161,7 @@ fn message_header(
150 161 author: String,
151 162 profile_user: Option<&str>,
152 163 saved: bool,
164 pinned: bool,
153 165 ) -> Div {
154 166 h_flex()
155 167 .gap(px(6.))
@@ -171,6 +183,7 @@ fn message_header(
171 183 .child(row.time.clone()),
172 184 )
173 185 .when(row.edited, |line| line.child(edited_marker()))
186 .when(pinned, |line| line.child(pinned_marker()))
174 187 .when(saved, |line| {
175 188 line.child(icon(IconName::Bookmark, 12., theme::accent_text()))
176 189 })
@@ -223,6 +236,7 @@ fn message_block(
223 236 None => message_content(row, index, directory, &actions, cx),
224 237 };
225 238 let saved = actions.saved;
239 let pinned = actions.pinned && role == Role::Root;
226 240 let RowActions {
227 241 delivery,
228 242 reply,
@@ -242,7 +256,14 @@ fn message_block(
242 256 .flex_1()
243 257 .min_w_0()
244 258 .gap(px(6.))
245 .child(message_header(row, index, author, profile_user, saved))
259 .child(message_header(
260 row,
261 index,
262 author,
263 profile_user,
264 saved,
265 pinned,
266 ))
246 267 .when_some(
247 268 row.subject.clone().filter(|_| role == Role::Root),
248 269 |column, subject| {
@@ -30,6 +30,7 @@ const AVATAR_GAP: f32 = 10.;
30const CARD_PADDING: f32 = 12.;
30const CARD_PADDING: f32 = 12.;
31const CARD_RADIUS: f32 = 10.;
31const CARD_RADIUS: f32 = 10.;
32const CARD_GAP: f32 = 12.;
32const CARD_GAP: f32 = 12.;
33const PINNED_LABEL: &str = "Pinned";
33const SLOTS_PER_POST: usize = 64;
34const SLOTS_PER_POST: usize = 64;
34const TOOLBAR_RIGHT_INSET: f32 = 8.;
35const TOOLBAR_RIGHT_INSET: f32 = 8.;
35const SUBJECT_SIZE: f32 = 14.;
36const SUBJECT_SIZE: f32 = 14.;
@@ -62,6 +63,16 @@ fn edited_marker() -> Div {
62 .child("Edited")
63 .child("Edited")
63}
64}
64
65
66fn pinned_marker() -> Div {
67 h_flex()
68 .gap(px(3.))
69 .items_center()
70 .text_size(px(11.))
71 .text_color(theme::text_muted())
72 .child(icon(IconName::Pin, 11., theme::text_muted()))
73 .child(PINNED_LABEL)
74}
75
65fn message_content(
76fn message_content(
66 row: &MessageRow,
77 row: &MessageRow,
67 index: usize,
78 index: usize,
@@ -150,6 +161,7 @@ fn message_header(
150 author: String,
161 author: String,
151 profile_user: Option<&str>,
162 profile_user: Option<&str>,
152 saved: bool,
163 saved: bool,
164 pinned: bool,
153) -> Div {
165) -> Div {
154 h_flex()
166 h_flex()
155 .gap(px(6.))
167 .gap(px(6.))
@@ -171,6 +183,7 @@ fn message_header(
171 .child(row.time.clone()),
183 .child(row.time.clone()),
172 )
184 )
173 .when(row.edited, |line| line.child(edited_marker()))
185 .when(row.edited, |line| line.child(edited_marker()))
186 .when(pinned, |line| line.child(pinned_marker()))
174 .when(saved, |line| {
187 .when(saved, |line| {
175 line.child(icon(IconName::Bookmark, 12., theme::accent_text()))
188 line.child(icon(IconName::Bookmark, 12., theme::accent_text()))
176 })
189 })
@@ -223,6 +236,7 @@ fn message_block(
223 None => message_content(row, index, directory, &actions, cx),
236 None => message_content(row, index, directory, &actions, cx),
224 };
237 };
225 let saved = actions.saved;
238 let saved = actions.saved;
239 let pinned = actions.pinned && role == Role::Root;
226 let RowActions {
240 let RowActions {
227 delivery,
241 delivery,
228 reply,
242 reply,
@@ -242,7 +256,14 @@ fn message_block(
242 .flex_1()
256 .flex_1()
243 .min_w_0()
257 .min_w_0()
244 .gap(px(6.))
258 .gap(px(6.))
245 .child(message_header(row, index, author, profile_user, saved))
259 .child(message_header(
260 row,
261 index,
262 author,
263 profile_user,
264 saved,
265 pinned,
266 ))
246 .when_some(
267 .when_some(
247 row.subject.clone().filter(|_| role == Role::Root),
268 row.subject.clone().filter(|_| role == Role::Root),
248 |column, subject| {
269 |column, subject| {
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/pins/mod.rs +7 −1
@@ -14,7 +14,7 @@ pub use pinbar::PinnedMessage;
14 14 pub use posts::{PINNED_POSTS_PAGE_SIZE, PinnedPostsPage, parse_pinned_posts};
15 15 pub use state::{PinnedChannels, PinnedChats};
16 16 pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};
17 pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};
17 pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport, SkypeTokenTransport};
18 18
19 19 pub const DEFAULT_REGION: &str = "emea";
20 20
@@ -34,6 +34,12 @@ impl Pins<SessionTransport> {
34 34 }
35 35 }
36 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
37 43 impl<T: CsaTransport> Pins<T> {
38 44 pub fn with_transport(transport: T, region: &str) -> Self {
39 45 Pins {
@@ -14,7 +14,7 @@ pub use pinbar::PinnedMessage;
14pub use posts::{PINNED_POSTS_PAGE_SIZE, PinnedPostsPage, parse_pinned_posts};
14pub use posts::{PINNED_POSTS_PAGE_SIZE, PinnedPostsPage, parse_pinned_posts};
15pub use state::{PinnedChannels, PinnedChats};
15pub use state::{PinnedChannels, PinnedChats};
16pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};
16pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};
17pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};
17pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport, SkypeTokenTransport};
18
18
19pub const DEFAULT_REGION: &str = "emea";
19pub const DEFAULT_REGION: &str = "emea";
20
20
@@ -34,6 +34,12 @@ impl Pins<SessionTransport> {
34 }
34 }
35}
35}
36
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
37impl<T: CsaTransport> Pins<T> {
43impl<T: CsaTransport> Pins<T> {
38 pub fn with_transport(transport: T, region: &str) -> Self {
44 pub fn with_transport(transport: T, region: &str) -> Self {
39 Pins {
45 Pins {
crates/chatsvc/src/pins/posts.rs +26 −7
@@ -122,8 +122,11 @@ impl<T: CsaTransport> Pins<T> {
122 122 let mut pins = Vec::new();
123 123 let mut continuation_token: Option<String> = None;
124 124 for _ in 0..MAX_PINNED_POST_PAGES {
125 let request =
126 self.pinned_posts_request(team_thread_id, channel_id, continuation_token.as_deref());
125 let request = self.pinned_posts_request(
126 team_thread_id,
127 channel_id,
128 continuation_token.as_deref(),
129 );
127 130 let answer = self.transport.send(request).await?;
128 131 ensure_success(&answer)?;
129 132 let page = parse_pinned_posts(&answer.body)?;
@@ -209,7 +212,11 @@ mod tests {
209 212 "continuationToken": "next-page"
210 213 });
211 214 let page = parse_pinned_posts(&body).unwrap();
212 let ids: Vec<&str> = page.pins.iter().map(|pin| pin.message_id.as_str()).collect();
215 let ids: Vec<&str> = page
216 .pins
217 .iter()
218 .map(|pin| pin.message_id.as_str())
219 .collect();
213 220 assert_eq!(ids, ["1791368000000", "1791367000000", "1791366000000"]);
214 221 assert_eq!(
215 222 page.pins[0].pinned_at.map(|time| time.timestamp_millis()),
@@ -268,8 +275,14 @@ mod tests {
268 275 #[tokio::test]
269 276 async fn a_repeated_continuation_stops_paging() {
270 277 let pins = canned(vec![
271 (200, json!({"messages": [{"id": "2"}], "continuationToken": "same"})),
272 (200, json!({"messages": [{"id": "1"}], "continuationToken": "same"})),
278 (
279 200,
280 json!({"messages": [{"id": "2"}], "continuationToken": "same"}),
281 ),
282 (
283 200,
284 json!({"messages": [{"id": "1"}], "continuationToken": "same"}),
285 ),
273 286 ]);
274 287 let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();
275 288 assert_eq!(found.len(), 2);
@@ -280,12 +293,18 @@ mod tests {
280 293 async fn failures_are_errors() {
281 294 let pins = canned(vec![(403, json!({})), (412, json!({}))]);
282 295 assert!(pins.channel_pinned_posts(TEAM, CHANNEL).await.is_err());
283 assert!(pins.set_post_pinned(TEAM, CHANNEL, "1", true).await.is_err());
296 assert!(
297 pins.set_post_pinned(TEAM, CHANNEL, "1", true)
298 .await
299 .is_err()
300 );
284 301 }
285 302
286 303 #[tokio::test]
287 304 async fn unpin_accepts_no_content() {
288 305 let pins = canned(vec![(204, Value::Null)]);
289 pins.set_post_pinned(TEAM, CHANNEL, "1", false).await.unwrap();
306 pins.set_post_pinned(TEAM, CHANNEL, "1", false)
307 .await
308 .unwrap();
290 309 }
291 310 }
@@ -122,8 +122,11 @@ impl<T: CsaTransport> Pins<T> {
122 let mut pins = Vec::new();
122 let mut pins = Vec::new();
123 let mut continuation_token: Option<String> = None;
123 let mut continuation_token: Option<String> = None;
124 for _ in 0..MAX_PINNED_POST_PAGES {
124 for _ in 0..MAX_PINNED_POST_PAGES {
125 let request =
125 let request = self.pinned_posts_request(
126 self.pinned_posts_request(team_thread_id, channel_id, continuation_token.as_deref());
126 team_thread_id,
127 channel_id,
128 continuation_token.as_deref(),
129 );
127 let answer = self.transport.send(request).await?;
130 let answer = self.transport.send(request).await?;
128 ensure_success(&answer)?;
131 ensure_success(&answer)?;
129 let page = parse_pinned_posts(&answer.body)?;
132 let page = parse_pinned_posts(&answer.body)?;
@@ -209,7 +212,11 @@ mod tests {
209 "continuationToken": "next-page"
212 "continuationToken": "next-page"
210 });
213 });
211 let page = parse_pinned_posts(&body).unwrap();
214 let page = parse_pinned_posts(&body).unwrap();
212 let ids: Vec<&str> = page.pins.iter().map(|pin| pin.message_id.as_str()).collect();
215 let ids: Vec<&str> = page
216 .pins
217 .iter()
218 .map(|pin| pin.message_id.as_str())
219 .collect();
213 assert_eq!(ids, ["1791368000000", "1791367000000", "1791366000000"]);
220 assert_eq!(ids, ["1791368000000", "1791367000000", "1791366000000"]);
214 assert_eq!(
221 assert_eq!(
215 page.pins[0].pinned_at.map(|time| time.timestamp_millis()),
222 page.pins[0].pinned_at.map(|time| time.timestamp_millis()),
@@ -268,8 +275,14 @@ mod tests {
268 #[tokio::test]
275 #[tokio::test]
269 async fn a_repeated_continuation_stops_paging() {
276 async fn a_repeated_continuation_stops_paging() {
270 let pins = canned(vec![
277 let pins = canned(vec![
271 (200, json!({"messages": [{"id": "2"}], "continuationToken": "same"})),
278 (
272 (200, json!({"messages": [{"id": "1"}], "continuationToken": "same"})),
279 200,
280 json!({"messages": [{"id": "2"}], "continuationToken": "same"}),
281 ),
282 (
283 200,
284 json!({"messages": [{"id": "1"}], "continuationToken": "same"}),
285 ),
273 ]);
286 ]);
274 let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();
287 let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();
275 assert_eq!(found.len(), 2);
288 assert_eq!(found.len(), 2);
@@ -280,12 +293,18 @@ mod tests {
280 async fn failures_are_errors() {
293 async fn failures_are_errors() {
281 let pins = canned(vec![(403, json!({})), (412, json!({}))]);
294 let pins = canned(vec![(403, json!({})), (412, json!({}))]);
282 assert!(pins.channel_pinned_posts(TEAM, CHANNEL).await.is_err());
295 assert!(pins.channel_pinned_posts(TEAM, CHANNEL).await.is_err());
283 assert!(pins.set_post_pinned(TEAM, CHANNEL, "1", true).await.is_err());
296 assert!(
297 pins.set_post_pinned(TEAM, CHANNEL, "1", true)
298 .await
299 .is_err()
300 );
284 }
301 }
285
302
286 #[tokio::test]
303 #[tokio::test]
287 async fn unpin_accepts_no_content() {
304 async fn unpin_accepts_no_content() {
288 let pins = canned(vec![(204, Value::Null)]);
305 let pins = canned(vec![(204, Value::Null)]);
289 pins.set_post_pinned(TEAM, CHANNEL, "1", false).await.unwrap();
306 pins.set_post_pinned(TEAM, CHANNEL, "1", false)
307 .await
308 .unwrap();
290 }
309 }
291}
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/core/src/remote.rs +2 −2
@@ -1058,7 +1058,7 @@ impl Remote for Graph {
1058 1058 team_thread_id: &str,
1059 1059 channel_id: &str,
1060 1060 ) -> Result<Vec<PinnedMessage>> {
1061 Ok(Pins::new(self.session())
1061 Ok(Pins::with_skype_token(self.session())
1062 1062 .channel_pinned_posts(team_thread_id, channel_id)
1063 1063 .await?)
1064 1064 }
@@ -1070,7 +1070,7 @@ impl Remote for Graph {
1070 1070 post_id: &str,
1071 1071 pinned: bool,
1072 1072 ) -> Result<()> {
1073 Ok(Pins::new(self.session())
1073 Ok(Pins::with_skype_token(self.session())
1074 1074 .set_post_pinned(team_thread_id, channel_id, post_id, pinned)
1075 1075 .await?)
1076 1076 }
@@ -1058,7 +1058,7 @@ impl Remote for Graph {
1058 team_thread_id: &str,
1058 team_thread_id: &str,
1059 channel_id: &str,
1059 channel_id: &str,
1060 ) -> Result<Vec<PinnedMessage>> {
1060 ) -> Result<Vec<PinnedMessage>> {
1061 Ok(Pins::new(self.session())
1061 Ok(Pins::with_skype_token(self.session())
1062 .channel_pinned_posts(team_thread_id, channel_id)
1062 .channel_pinned_posts(team_thread_id, channel_id)
1063 .await?)
1063 .await?)
1064 }
1064 }
@@ -1070,7 +1070,7 @@ impl Remote for Graph {
1070 post_id: &str,
1070 post_id: &str,
1071 pinned: bool,
1071 pinned: bool,
1072 ) -> Result<()> {
1072 ) -> Result<()> {
1073 Ok(Pins::new(self.session())
1073 Ok(Pins::with_skype_token(self.session())
1074 .set_post_pinned(team_thread_id, channel_id, post_id, pinned)
1074 .set_post_pinned(team_thread_id, channel_id, post_id, pinned)
1075 .await?)
1075 .await?)
1076 }
1076 }