BlueGit

ict rusty-teams

feat(people): names, External label and search for people of other organizations

- members the short profile lookup does not know are looked up with fetchFederated, so a chat shows the name instead of Unknown User
- people of other organizations are kept in a new external_people table and get an External label in the 1:1 chat header
- a full email address in people search and the search box also asks externalsearchv3, like Teams

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

metis Daniel Däschle · pushed by metis

Authored 2026-11-20 · 11 days ago

Hash
a5957bf49422aca9f58ff71949cca57c4f393419
Parent
9dc4ec73
15 files changed +298 −13
crates/app-state/src/app_state.rs +6 −0
@@ -644,6 +644,12 @@ impl AppState {
644 644 .flatten()
645 645 .unwrap_or_default();
646 646 self.directory.folders = data::folders(&self.store, &self.favorite_ids);
647 self.directory.external = self
648 .store
649 .external_people()
650 .unwrap_or_default()
651 .into_iter()
652 .collect();
647 653 self.reapply_section_changes();
648 654 self.directory.section_settings = teams_core::stored_section_settings(&self.store);
649 655 self.adopt_folder_expanded();
@@ -644,6 +644,12 @@ impl AppState {
644 .flatten()
644 .flatten()
645 .unwrap_or_default();
645 .unwrap_or_default();
646 self.directory.folders = data::folders(&self.store, &self.favorite_ids);
646 self.directory.folders = data::folders(&self.store, &self.favorite_ids);
647 self.directory.external = self
648 .store
649 .external_people()
650 .unwrap_or_default()
651 .into_iter()
652 .collect();
647 self.reapply_section_changes();
653 self.reapply_section_changes();
648 self.directory.section_settings = teams_core::stored_section_settings(&self.store);
654 self.directory.section_settings = teams_core::stored_section_settings(&self.store);
649 self.adopt_folder_expanded();
655 self.adopt_folder_expanded();
crates/app-state/src/data.rs +6 −0
@@ -142,11 +142,17 @@ pub struct Directory {
142 142 pub images_requested: HashSet<String>,
143 143 pub images_failed: HashMap<String, Instant>,
144 144 pub avatars_failed: HashMap<String, Instant>,
145 /// People of other organizations, with their organization's name when known.
146 pub external: HashMap<String, Option<String>>,
145 147 }
146 148
147 149 const IMAGE_RETRY_AFTER: Duration = Duration::from_secs(60);
148 150
149 151 impl Directory {
152 pub fn is_external(&self, user_id: &str) -> bool {
153 self.external.contains_key(user_id)
154 }
155
150 156 pub fn avatar(&self, user_id: &str) -> Option<&AvatarState> {
151 157 self.avatars.get(user_id)
152 158 }
@@ -142,11 +142,17 @@ pub struct Directory {
142 pub images_requested: HashSet<String>,
142 pub images_requested: HashSet<String>,
143 pub images_failed: HashMap<String, Instant>,
143 pub images_failed: HashMap<String, Instant>,
144 pub avatars_failed: HashMap<String, Instant>,
144 pub avatars_failed: HashMap<String, Instant>,
145 /// People of other organizations, with their organization's name when known.
146 pub external: HashMap<String, Option<String>>,
145}
147}
146
148
147const IMAGE_RETRY_AFTER: Duration = Duration::from_secs(60);
149const IMAGE_RETRY_AFTER: Duration = Duration::from_secs(60);
148
150
149impl Directory {
151impl Directory {
152 pub fn is_external(&self, user_id: &str) -> bool {
153 self.external.contains_key(user_id)
154 }
155
150 pub fn avatar(&self, user_id: &str) -> Option<&AvatarState> {
156 pub fn avatar(&self, user_id: &str) -> Option<&AvatarState> {
151 self.avatars.get(user_id)
157 self.avatars.get(user_id)
152 }
158 }
crates/app/src/layout_guard.rs +23 −0
@@ -1441,6 +1441,29 @@ mod frames {
1441 1441 assert_eq!(reversals, 0, "resting {resting:?}, frames {positions:?}");
1442 1442 }
1443 1443
1444 #[gpui_kit::test]
1445 fn a_chat_with_someone_of_another_organization_says_external(cx: &mut TestAppContext) {
1446 let (handle, app) = mount(cx);
1447 let mut visual = VisualTestContext::from_window(handle, cx);
1448 visual.simulate_resize(size(px(1280.), px(800.)));
1449 visual.update(|_, cx| {
1450 app.update(cx, |state, cx| {
1451 state
1452 .directory
1453 .external
1454 .insert(demo::MARA_ID.to_owned(), Some("Example Corp".to_owned()));
1455 state.select(Selection::Chat(REACTION_CHAT.to_owned()), cx)
1456 })
1457 });
1458 collect(&mut visual, Some(TIMELINE_TAG));
1459 collect(&mut visual, None);
1460 assert!(
1461 visual
1462 .debug_bounds(crate::views::conversation::chat_header_actions::EXTERNAL_BADGE)
1463 .is_some()
1464 );
1465 }
1466
1444 1467 #[gpui_kit::test]
1445 1468 fn the_time_of_a_short_own_message_with_a_reaction_stays_in_its_bubble(
1446 1469 cx: &mut TestAppContext,
@@ -1441,6 +1441,29 @@ mod frames {
1441 assert_eq!(reversals, 0, "resting {resting:?}, frames {positions:?}");
1441 assert_eq!(reversals, 0, "resting {resting:?}, frames {positions:?}");
1442 }
1442 }
1443
1443
1444 #[gpui_kit::test]
1445 fn a_chat_with_someone_of_another_organization_says_external(cx: &mut TestAppContext) {
1446 let (handle, app) = mount(cx);
1447 let mut visual = VisualTestContext::from_window(handle, cx);
1448 visual.simulate_resize(size(px(1280.), px(800.)));
1449 visual.update(|_, cx| {
1450 app.update(cx, |state, cx| {
1451 state
1452 .directory
1453 .external
1454 .insert(demo::MARA_ID.to_owned(), Some("Example Corp".to_owned()));
1455 state.select(Selection::Chat(REACTION_CHAT.to_owned()), cx)
1456 })
1457 });
1458 collect(&mut visual, Some(TIMELINE_TAG));
1459 collect(&mut visual, None);
1460 assert!(
1461 visual
1462 .debug_bounds(crate::views::conversation::chat_header_actions::EXTERNAL_BADGE)
1463 .is_some()
1464 );
1465 }
1466
1444 #[gpui_kit::test]
1467 #[gpui_kit::test]
1445 fn the_time_of_a_short_own_message_with_a_reaction_stays_in_its_bubble(
1468 fn the_time_of_a_short_own_message_with_a_reaction_stays_in_its_bubble(
1446 cx: &mut TestAppContext,
1469 cx: &mut TestAppContext,
crates/app/src/views/conversation.rs +6 −1
@@ -23,7 +23,7 @@ use teams_core::{
23 23 };
24 24
25 25 mod channel_details;
26 mod chat_header_actions;
26 pub(crate) mod chat_header_actions;
27 27 mod copilot;
28 28 pub use channel_details::{
29 29 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
@@ -4047,6 +4047,7 @@ impl ConversationView {
4047 4047 let mut stack: Option<AnyElement> = None;
4048 4048 let mut rename: Option<AnyElement> = None;
4049 4049 let mut names_title: Option<Div> = None;
4050 let mut external: Option<Div> = None;
4050 4051 let mut header_title = current.title.clone();
4051 4052 match &current.selection {
4052 4053 Selection::Chat(chat_id) => {
@@ -4082,6 +4083,9 @@ impl ConversationView {
4082 4083 if is_one_on_one(chat) && !is_notes_chat(chat_id) {
4083 4084 stack = Some(add_people_button(&self.app, chat_id));
4084 4085 }
4086 if user_id.is_some_and(|id| directory.is_external(id)) {
4087 external = Some(chat_header_actions::external_badge());
4088 }
4085 4089 } else {
4086 4090 if chat.kind == GROUP_KIND
4087 4091 && me.is_some_and(|me| {
@@ -4230,6 +4234,7 @@ impl ConversationView {
4230 4234 None => title.child(header_title),
4231 4235 }),
4232 4236 )
4237 .children(external)
4233 4238 .children(rename),
4234 4239 )
4235 4240 .when(!subline.is_empty(), |column| {
@@ -23,7 +23,7 @@ use teams_core::{
23};
23};
24
24
25mod channel_details;
25mod channel_details;
26mod chat_header_actions;
26pub(crate) mod chat_header_actions;
27mod copilot;
27mod copilot;
28pub use channel_details::{
28pub use channel_details::{
29 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
29 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
@@ -4047,6 +4047,7 @@ impl ConversationView {
4047 let mut stack: Option<AnyElement> = None;
4047 let mut stack: Option<AnyElement> = None;
4048 let mut rename: Option<AnyElement> = None;
4048 let mut rename: Option<AnyElement> = None;
4049 let mut names_title: Option<Div> = None;
4049 let mut names_title: Option<Div> = None;
4050 let mut external: Option<Div> = None;
4050 let mut header_title = current.title.clone();
4051 let mut header_title = current.title.clone();
4051 match &current.selection {
4052 match &current.selection {
4052 Selection::Chat(chat_id) => {
4053 Selection::Chat(chat_id) => {
@@ -4082,6 +4083,9 @@ impl ConversationView {
4082 if is_one_on_one(chat) && !is_notes_chat(chat_id) {
4083 if is_one_on_one(chat) && !is_notes_chat(chat_id) {
4083 stack = Some(add_people_button(&self.app, chat_id));
4084 stack = Some(add_people_button(&self.app, chat_id));
4084 }
4085 }
4086 if user_id.is_some_and(|id| directory.is_external(id)) {
4087 external = Some(chat_header_actions::external_badge());
4088 }
4085 } else {
4089 } else {
4086 if chat.kind == GROUP_KIND
4090 if chat.kind == GROUP_KIND
4087 && me.is_some_and(|me| {
4091 && me.is_some_and(|me| {
@@ -4230,6 +4234,7 @@ impl ConversationView {
4230 None => title.child(header_title),
4234 None => title.child(header_title),
4231 }),
4235 }),
4232 )
4236 )
4237 .children(external)
4233 .children(rename),
4238 .children(rename),
4234 )
4239 )
4235 .when(!subline.is_empty(), |column| {
4240 .when(!subline.is_empty(), |column| {
crates/app/src/views/conversation/chat_header_actions.rs +16 −0
@@ -198,6 +198,22 @@ pub fn member_count(count: usize) -> Div {
198 198 .child(count.to_string())
199 199 }
200 200
201 pub fn external_badge() -> Div {
202 div()
203 .debug_selector(|| EXTERNAL_BADGE.into())
204 .flex_none()
205 .ml(px(6.))
206 .px(px(6.))
207 .rounded(px(4.))
208 .bg(theme::row_hover())
209 .text_size(px(11.))
210 .line_height(px(18.))
211 .text_color(theme::text_soft())
212 .child("External")
213 }
214
215 pub const EXTERNAL_BADGE: &str = "chat-header/external";
216
201 217 const TITLE_NAMES: usize = 3;
202 218 const NAME_DOT: f32 = 10.;
203 219
@@ -198,6 +198,22 @@ pub fn member_count(count: usize) -> Div {
198 .child(count.to_string())
198 .child(count.to_string())
199}
199}
200
200
201pub fn external_badge() -> Div {
202 div()
203 .debug_selector(|| EXTERNAL_BADGE.into())
204 .flex_none()
205 .ml(px(6.))
206 .px(px(6.))
207 .rounded(px(4.))
208 .bg(theme::row_hover())
209 .text_size(px(11.))
210 .line_height(px(18.))
211 .text_color(theme::text_soft())
212 .child("External")
213}
214
215pub const EXTERNAL_BADGE: &str = "chat-header/external";
216
201const TITLE_NAMES: usize = 3;
217const TITLE_NAMES: usize = 3;
202const NAME_DOT: f32 = 10.;
218const NAME_DOT: f32 = 10.;
203
219
crates/chatsvc/src/user_profiles.rs +57 −6
@@ -3,7 +3,7 @@ use session::{Method, Request, SPACES, Scope, Session};
3 3
4 4 use crate::error::Result;
5 5 use crate::language_settings::with_headers;
6 use crate::messages::ensure_success;
6 use crate::messages::{encode, ensure_success};
7 7 use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8 8
9 9 const SKYPE_SCOPE: &str = "user_impersonation";
@@ -20,11 +20,12 @@ pub struct UserProfile {
20 20 pub user_principal_name: Option<String>,
21 21 pub job_title: Option<String>,
22 22 pub department: Option<String>,
23 pub tenant_name: Option<String>,
23 24 }
24 25
25 26 pub struct UserProfiles<T: CsaTransport = SessionTransport> {
26 27 transport: T,
27 url: String,
28 users_url: String,
28 29 }
29 30
30 31 impl UserProfiles<SessionTransport> {
@@ -38,13 +39,39 @@ impl<T: CsaTransport> UserProfiles<T> {
38 39 pub fn with_transport(transport: T, region: &str) -> Self {
39 40 UserProfiles {
40 41 transport,
41 url: format!(
42 "https://teams.cloud.microsoft/api/mt/{region}/beta/users/fetchShortProfile?{PROFILE_QUERY}"
43 ),
42 users_url: format!("https://teams.cloud.microsoft/api/mt/{region}/beta/users"),
44 43 }
45 44 }
46 45
47 46 pub async fn fetch(&self, user_ids: &[String]) -> Result<Vec<UserProfile>> {
47 self.post_mris(
48 &format!("{}/fetchShortProfile?{PROFILE_QUERY}", self.users_url),
49 user_ids,
50 )
51 .await
52 }
53
54 /// People of other organizations; the short profile lookup answers nothing for them.
55 pub async fn fetch_federated(&self, user_ids: &[String]) -> Result<Vec<UserProfile>> {
56 self.post_mris(&format!("{}/fetchFederated", self.users_url), user_ids)
57 .await
58 }
59
60 /// Teams finds a person of another organization only by the full email address.
61 pub async fn search_external(&self, email: &str) -> Result<Vec<UserProfile>> {
62 let answer = self
63 .transport
64 .send(with_headers(Request::get(format!(
65 "{}/{}/externalsearchv3?includeTFLUsers=true",
66 self.users_url,
67 encode(email.trim())
68 ))))
69 .await?;
70 ensure_success(&answer)?;
71 Ok(parse_user_profiles(&json!({"value": answer.body})))
72 }
73
74 async fn post_mris(&self, url: &str, user_ids: &[String]) -> Result<Vec<UserProfile>> {
48 75 let mut profiles = Vec::new();
49 76 for chunk in user_ids.chunks(PROFILES_PER_REQUEST) {
50 77 let mris: Vec<Value> = chunk
@@ -55,7 +82,7 @@ impl<T: CsaTransport> UserProfiles<T> {
55 82 .transport
56 83 .send(with_headers(Request::with_body(
57 84 Method::Post,
58 self.url.clone(),
85 url.to_owned(),
59 86 Value::Array(mris),
60 87 )))
61 88 .await?;
@@ -91,6 +118,7 @@ pub fn parse_user_profiles(body: &Value) -> Vec<UserProfile> {
91 118 user_principal_name: text(profile, "userPrincipalName"),
92 119 job_title: text(profile, "jobTitle"),
93 120 department: text(profile, "department"),
121 tenant_name: text(profile, "tenantName"),
94 122 })
95 123 })
96 124 .collect()
@@ -149,5 +177,28 @@ mod tests {
149 177 requests[0].body,
150 178 Some(json!(["8:orgid:ann", "8:orgid:bob"]))
151 179 );
180 assert!(requests[0].url.contains("/users/fetchShortProfile?"));
181 }
182
183 #[tokio::test]
184 async fn people_of_other_organizations_come_from_the_federated_lookup() {
185 let canned = Canned {
186 requests: Mutex::new(Vec::new()),
187 };
188 UserProfiles::with_transport(&canned, "emea")
189 .fetch_federated(&["ann".into()])
190 .await
191 .unwrap();
192 let requests = canned.requests.lock().unwrap();
193 assert!(requests[0].url.ends_with("/emea/beta/users/fetchFederated"));
194 assert_eq!(requests[0].body, Some(json!(["8:orgid:ann"])));
195 }
196
197 #[test]
198 fn a_federated_profile_carries_its_organization() {
199 let profiles = parse_user_profiles(&json!({"value": [
200 {"mri": "8:orgid:ann", "objectId": "ann", "displayName": "Ann", "tenantName": "Example Corp"},
201 ]}));
202 assert_eq!(profiles[0].tenant_name.as_deref(), Some("Example Corp"));
152 203 }
153 204 }
@@ -3,7 +3,7 @@ use session::{Method, Request, SPACES, Scope, Session};
3
3
4use crate::error::Result;
4use crate::error::Result;
5use crate::language_settings::with_headers;
5use crate::language_settings::with_headers;
6use crate::messages::ensure_success;
6use crate::messages::{encode, ensure_success};
7use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
7use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
8
9const SKYPE_SCOPE: &str = "user_impersonation";
9const SKYPE_SCOPE: &str = "user_impersonation";
@@ -20,11 +20,12 @@ pub struct UserProfile {
20 pub user_principal_name: Option<String>,
20 pub user_principal_name: Option<String>,
21 pub job_title: Option<String>,
21 pub job_title: Option<String>,
22 pub department: Option<String>,
22 pub department: Option<String>,
23 pub tenant_name: Option<String>,
23}
24}
24
25
25pub struct UserProfiles<T: CsaTransport = SessionTransport> {
26pub struct UserProfiles<T: CsaTransport = SessionTransport> {
26 transport: T,
27 transport: T,
27 url: String,
28 users_url: String,
28}
29}
29
30
30impl UserProfiles<SessionTransport> {
31impl UserProfiles<SessionTransport> {
@@ -38,13 +39,39 @@ impl<T: CsaTransport> UserProfiles<T> {
38 pub fn with_transport(transport: T, region: &str) -> Self {
39 pub fn with_transport(transport: T, region: &str) -> Self {
39 UserProfiles {
40 UserProfiles {
40 transport,
41 transport,
41 url: format!(
42 users_url: format!("https://teams.cloud.microsoft/api/mt/{region}/beta/users"),
42 "https://teams.cloud.microsoft/api/mt/{region}/beta/users/fetchShortProfile?{PROFILE_QUERY}"
43 ),
44 }
43 }
45 }
44 }
46
45
47 pub async fn fetch(&self, user_ids: &[String]) -> Result<Vec<UserProfile>> {
46 pub async fn fetch(&self, user_ids: &[String]) -> Result<Vec<UserProfile>> {
47 self.post_mris(
48 &format!("{}/fetchShortProfile?{PROFILE_QUERY}", self.users_url),
49 user_ids,
50 )
51 .await
52 }
53
54 /// People of other organizations; the short profile lookup answers nothing for them.
55 pub async fn fetch_federated(&self, user_ids: &[String]) -> Result<Vec<UserProfile>> {
56 self.post_mris(&format!("{}/fetchFederated", self.users_url), user_ids)
57 .await
58 }
59
60 /// Teams finds a person of another organization only by the full email address.
61 pub async fn search_external(&self, email: &str) -> Result<Vec<UserProfile>> {
62 let answer = self
63 .transport
64 .send(with_headers(Request::get(format!(
65 "{}/{}/externalsearchv3?includeTFLUsers=true",
66 self.users_url,
67 encode(email.trim())
68 ))))
69 .await?;
70 ensure_success(&answer)?;
71 Ok(parse_user_profiles(&json!({"value": answer.body})))
72 }
73
74 async fn post_mris(&self, url: &str, user_ids: &[String]) -> Result<Vec<UserProfile>> {
48 let mut profiles = Vec::new();
75 let mut profiles = Vec::new();
49 for chunk in user_ids.chunks(PROFILES_PER_REQUEST) {
76 for chunk in user_ids.chunks(PROFILES_PER_REQUEST) {
50 let mris: Vec<Value> = chunk
77 let mris: Vec<Value> = chunk
@@ -55,7 +82,7 @@ impl<T: CsaTransport> UserProfiles<T> {
55 .transport
82 .transport
56 .send(with_headers(Request::with_body(
83 .send(with_headers(Request::with_body(
57 Method::Post,
84 Method::Post,
58 self.url.clone(),
85 url.to_owned(),
59 Value::Array(mris),
86 Value::Array(mris),
60 )))
87 )))
61 .await?;
88 .await?;
@@ -91,6 +118,7 @@ pub fn parse_user_profiles(body: &Value) -> Vec<UserProfile> {
91 user_principal_name: text(profile, "userPrincipalName"),
118 user_principal_name: text(profile, "userPrincipalName"),
92 job_title: text(profile, "jobTitle"),
119 job_title: text(profile, "jobTitle"),
93 department: text(profile, "department"),
120 department: text(profile, "department"),
121 tenant_name: text(profile, "tenantName"),
94 })
122 })
95 })
123 })
96 .collect()
124 .collect()
@@ -149,5 +177,28 @@ mod tests {
149 requests[0].body,
177 requests[0].body,
150 Some(json!(["8:orgid:ann", "8:orgid:bob"]))
178 Some(json!(["8:orgid:ann", "8:orgid:bob"]))
151 );
179 );
180 assert!(requests[0].url.contains("/users/fetchShortProfile?"));
181 }
182
183 #[tokio::test]
184 async fn people_of_other_organizations_come_from_the_federated_lookup() {
185 let canned = Canned {
186 requests: Mutex::new(Vec::new()),
187 };
188 UserProfiles::with_transport(&canned, "emea")
189 .fetch_federated(&["ann".into()])
190 .await
191 .unwrap();
192 let requests = canned.requests.lock().unwrap();
193 assert!(requests[0].url.ends_with("/emea/beta/users/fetchFederated"));
194 assert_eq!(requests[0].body, Some(json!(["8:orgid:ann"])));
195 }
196
197 #[test]
198 fn a_federated_profile_carries_its_organization() {
199 let profiles = parse_user_profiles(&json!({"value": [
200 {"mri": "8:orgid:ann", "objectId": "ann", "displayName": "Ann", "tenantName": "Example Corp"},
201 ]}));
202 assert_eq!(profiles[0].tenant_name.as_deref(), Some("Example Corp"));
152 }
203 }
153}
204}
crates/core/src/native/mod.rs +3 −1
@@ -5,7 +5,9 @@ mod source;
5 5
6 6 pub use chat::{NativeMember, chat_type, graph_chat, graph_chat_from_aggregator};
7 7 pub use message::graph_message;
8 pub use source::{NativeChats, known_profile};
8 pub use source::{
9 NativeChats, external_people, is_email_address, known_profile, remember_external,
10 };
9 11
10 12 #[cfg(test)]
11 13 mod event_tests {
@@ -5,7 +5,9 @@ mod source;
5
5
6pub use chat::{NativeMember, chat_type, graph_chat, graph_chat_from_aggregator};
6pub use chat::{NativeMember, chat_type, graph_chat, graph_chat_from_aggregator};
7pub use message::graph_message;
7pub use message::graph_message;
8pub use source::{NativeChats, known_profile};
8pub use source::{
9 NativeChats, external_people, is_email_address, known_profile, remember_external,
10};
9
11
10#[cfg(test)]
12#[cfg(test)]
11mod event_tests {
13mod event_tests {
crates/core/src/native/source.rs +68 −1
@@ -22,6 +22,8 @@ const OLDER_PAGE_MARKER: &str = "chatsvc:older";
22 22 /// Profiles looked up so far; `None` when the directory does not know the id, such as a bot.
23 23 static PROFILES: LazyLock<Mutex<HashMap<String, Option<UserProfile>>>> =
24 24 LazyLock::new(|| Mutex::new(HashMap::new()));
25 static EXTERNAL: LazyLock<Mutex<HashMap<String, Option<String>>>> =
26 LazyLock::new(|| Mutex::new(HashMap::new()));
25 27 /// Thread members by chat, kept while the thread's roster version stays the same.
26 28 static ROSTERS: LazyLock<Mutex<HashMap<String, (String, Vec<NativeMember>)>>> =
27 29 LazyLock::new(|| Mutex::new(HashMap::new()));
@@ -237,9 +239,24 @@ impl<'a> NativeChats<'a> {
237 239 if unknown.is_empty() {
238 240 return;
239 241 }
240 let Ok(profiles) = UserProfiles::new(self.session).fetch(&unknown).await else {
242 let lookup = UserProfiles::new(self.session);
243 let Ok(mut profiles) = lookup.fetch(&unknown).await else {
241 244 return;
242 245 };
246 let missing: Vec<String> = unknown
247 .iter()
248 .filter(|user_id| !profiles.iter().any(|profile| &profile.user_id == *user_id))
249 .cloned()
250 .collect();
251 if !missing.is_empty()
252 && let Ok(federated) = lookup.fetch_federated(&missing).await
253 {
254 let mut external = EXTERNAL.lock().unwrap();
255 for profile in &federated {
256 external.insert(profile.user_id.clone(), profile.tenant_name.clone());
257 }
258 profiles.extend(federated);
259 }
243 260 let mut known = PROFILES.lock().unwrap();
244 261 for user_id in unknown {
245 262 known.insert(user_id, None);
@@ -273,6 +290,45 @@ impl<'a> NativeChats<'a> {
273 290 }
274 291 }
275 292
293 /// Directory people for profiles found outside the own organization, remembered as external.
294 pub fn remember_external(profiles: Vec<UserProfile>) -> Vec<graph::User> {
295 let mut external = EXTERNAL.lock().unwrap();
296 let mut known = PROFILES.lock().unwrap();
297 profiles
298 .into_iter()
299 .map(|profile| {
300 external.insert(profile.user_id.clone(), profile.tenant_name.clone());
301 let user = graph::User {
302 id: profile.user_id.clone(),
303 display_name: profile.display_name.clone(),
304 mail: profile.email.clone(),
305 user_principal_name: profile.user_principal_name.clone(),
306 job_title: profile.job_title.clone(),
307 department: profile.department.clone(),
308 };
309 known.insert(profile.user_id.clone(), Some(profile));
310 user
311 })
312 .collect()
313 }
314
315 pub fn is_email_address(query: &str) -> bool {
316 let query = query.trim();
317 query.split_once('@').is_some_and(|(local, domain)| {
318 !local.is_empty() && domain.contains('.') && !query.contains(char::is_whitespace)
319 })
320 }
321
322 /// People of other organizations the lookups met, with their organization's name.
323 pub fn external_people() -> Vec<(String, Option<String>)> {
324 EXTERNAL
325 .lock()
326 .unwrap()
327 .iter()
328 .map(|(user_id, tenant)| (user_id.clone(), tenant.clone()))
329 .collect()
330 }
331
276 332 /// What the directory lookups learned about a user, for callers outside the chat path.
277 333 pub fn known_profile(user_id: &str) -> Option<UserProfile> {
278 334 PROFILES.lock().unwrap().get(user_id).cloned().flatten()
@@ -285,3 +341,14 @@ fn profile_name(user_id: &str) -> Option<String> {
285 341 fn profile_email(user_id: &str) -> Option<String> {
286 342 known_profile(user_id).and_then(|profile| profile.email)
287 343 }
344
345 #[cfg(test)]
346 mod tests {
347 #[test]
348 fn only_a_full_email_address_asks_for_people_of_other_organizations() {
349 assert!(super::is_email_address(" ann@example.com "));
350 assert!(!super::is_email_address("ann@example"));
351 assert!(!super::is_email_address("ann example@x.com"));
352 assert!(!super::is_email_address("@example.com"));
353 }
354 }
@@ -22,6 +22,8 @@ const OLDER_PAGE_MARKER: &str = "chatsvc:older";
22/// Profiles looked up so far; `None` when the directory does not know the id, such as a bot.
22/// Profiles looked up so far; `None` when the directory does not know the id, such as a bot.
23static PROFILES: LazyLock<Mutex<HashMap<String, Option<UserProfile>>>> =
23static PROFILES: LazyLock<Mutex<HashMap<String, Option<UserProfile>>>> =
24 LazyLock::new(|| Mutex::new(HashMap::new()));
24 LazyLock::new(|| Mutex::new(HashMap::new()));
25static EXTERNAL: LazyLock<Mutex<HashMap<String, Option<String>>>> =
26 LazyLock::new(|| Mutex::new(HashMap::new()));
25/// Thread members by chat, kept while the thread's roster version stays the same.
27/// Thread members by chat, kept while the thread's roster version stays the same.
26static ROSTERS: LazyLock<Mutex<HashMap<String, (String, Vec<NativeMember>)>>> =
28static ROSTERS: LazyLock<Mutex<HashMap<String, (String, Vec<NativeMember>)>>> =
27 LazyLock::new(|| Mutex::new(HashMap::new()));
29 LazyLock::new(|| Mutex::new(HashMap::new()));
@@ -237,9 +239,24 @@ impl<'a> NativeChats<'a> {
237 if unknown.is_empty() {
239 if unknown.is_empty() {
238 return;
240 return;
239 }
241 }
240 let Ok(profiles) = UserProfiles::new(self.session).fetch(&unknown).await else {
242 let lookup = UserProfiles::new(self.session);
243 let Ok(mut profiles) = lookup.fetch(&unknown).await else {
241 return;
244 return;
242 };
245 };
246 let missing: Vec<String> = unknown
247 .iter()
248 .filter(|user_id| !profiles.iter().any(|profile| &profile.user_id == *user_id))
249 .cloned()
250 .collect();
251 if !missing.is_empty()
252 && let Ok(federated) = lookup.fetch_federated(&missing).await
253 {
254 let mut external = EXTERNAL.lock().unwrap();
255 for profile in &federated {
256 external.insert(profile.user_id.clone(), profile.tenant_name.clone());
257 }
258 profiles.extend(federated);
259 }
243 let mut known = PROFILES.lock().unwrap();
260 let mut known = PROFILES.lock().unwrap();
244 for user_id in unknown {
261 for user_id in unknown {
245 known.insert(user_id, None);
262 known.insert(user_id, None);
@@ -273,6 +290,45 @@ impl<'a> NativeChats<'a> {
273 }
290 }
274}
291}
275
292
293/// Directory people for profiles found outside the own organization, remembered as external.
294pub fn remember_external(profiles: Vec<UserProfile>) -> Vec<graph::User> {
295 let mut external = EXTERNAL.lock().unwrap();
296 let mut known = PROFILES.lock().unwrap();
297 profiles
298 .into_iter()
299 .map(|profile| {
300 external.insert(profile.user_id.clone(), profile.tenant_name.clone());
301 let user = graph::User {
302 id: profile.user_id.clone(),
303 display_name: profile.display_name.clone(),
304 mail: profile.email.clone(),
305 user_principal_name: profile.user_principal_name.clone(),
306 job_title: profile.job_title.clone(),
307 department: profile.department.clone(),
308 };
309 known.insert(profile.user_id.clone(), Some(profile));
310 user
311 })
312 .collect()
313}
314
315pub fn is_email_address(query: &str) -> bool {
316 let query = query.trim();
317 query.split_once('@').is_some_and(|(local, domain)| {
318 !local.is_empty() && domain.contains('.') && !query.contains(char::is_whitespace)
319 })
320}
321
322/// People of other organizations the lookups met, with their organization's name.
323pub fn external_people() -> Vec<(String, Option<String>)> {
324 EXTERNAL
325 .lock()
326 .unwrap()
327 .iter()
328 .map(|(user_id, tenant)| (user_id.clone(), tenant.clone()))
329 .collect()
330}
331
276/// What the directory lookups learned about a user, for callers outside the chat path.
332/// What the directory lookups learned about a user, for callers outside the chat path.
277pub fn known_profile(user_id: &str) -> Option<UserProfile> {
333pub fn known_profile(user_id: &str) -> Option<UserProfile> {
278 PROFILES.lock().unwrap().get(user_id).cloned().flatten()
334 PROFILES.lock().unwrap().get(user_id).cloned().flatten()
@@ -285,3 +341,14 @@ fn profile_name(user_id: &str) -> Option<String> {
285fn profile_email(user_id: &str) -> Option<String> {
341fn profile_email(user_id: &str) -> Option<String> {
286 known_profile(user_id).and_then(|profile| profile.email)
342 known_profile(user_id).and_then(|profile| profile.email)
287}
343}
344
345#[cfg(test)]
346mod tests {
347 #[test]
348 fn only_a_full_email_address_asks_for_people_of_other_organizations() {
349 assert!(super::is_email_address(" ann@example.com "));
350 assert!(!super::is_email_address("ann@example"));
351 assert!(!super::is_email_address("ann example@x.com"));
352 assert!(!super::is_email_address("@example.com"));
353 }
354}
crates/core/src/remote.rs +14 −1
@@ -1054,7 +1054,20 @@ impl Remote for Graph {
1054 1054 }
1055 1055
1056 1056 async fn search_people(&self, query: &str) -> Result<Vec<User>> {
1057 Ok(Graph::search_people(self, query).await?)
1057 let mut users = Graph::search_people(self, query).await?;
1058 if crate::native::is_email_address(query)
1059 && !users.iter().any(|user| {
1060 user.mail
1061 .as_deref()
1062 .is_some_and(|mail| mail.eq_ignore_ascii_case(query.trim()))
1063 })
1064 && let Ok(external) = chatsvc::UserProfiles::new(self.session())
1065 .search_external(query)
1066 .await
1067 {
1068 users.extend(crate::native::remember_external(external));
1069 }
1070 Ok(users)
1058 1071 }
1059 1072
1060 1073 async fn team_tags(&self, team_id: &str) -> Result<Vec<Tag>> {
@@ -1054,7 +1054,20 @@ impl Remote for Graph {
1054 }
1054 }
1055
1055
1056 async fn search_people(&self, query: &str) -> Result<Vec<User>> {
1056 async fn search_people(&self, query: &str) -> Result<Vec<User>> {
1057 Ok(Graph::search_people(self, query).await?)
1057 let mut users = Graph::search_people(self, query).await?;
1058 if crate::native::is_email_address(query)
1059 && !users.iter().any(|user| {
1060 user.mail
1061 .as_deref()
1062 .is_some_and(|mail| mail.eq_ignore_ascii_case(query.trim()))
1063 })
1064 && let Ok(external) = chatsvc::UserProfiles::new(self.session())
1065 .search_external(query)
1066 .await
1067 {
1068 users.extend(crate::native::remember_external(external));
1069 }
1070 Ok(users)
1058 }
1071 }
1059
1072
1060 async fn team_tags(&self, team_id: &str) -> Result<Vec<Tag>> {
1073 async fn team_tags(&self, team_id: &str) -> Result<Vec<Tag>> {
crates/core/src/server_search.rs +36 −3
@@ -1,5 +1,5 @@
1 1 use chatsvc::substrate_search::{
2 QueryRequest, QueryResults, SearchIdentity, SearchSession, Suggestions,
2 QueryRequest, QueryResults, SearchIdentity, SearchPerson, SearchSession, Suggestions,
3 3 };
4 4
5 5 use crate::engine::SyncEngine;
@@ -21,9 +21,33 @@ impl<R: Remote> SyncEngine<R> {
21 21 text: &str,
22 22 ) -> Result<Suggestions> {
23 23 let identity = self.search_identity().await?;
24 self.remote
24 let mut suggestions = self
25 .remote
25 26 .server_suggestions(&identity, search_session, text)
26 .await
27 .await?;
28 if crate::native::is_email_address(text) && !has_person_with_email(&suggestions, text) {
29 let external = self.search_people(text).await.unwrap_or_default();
30 suggestions.people.extend(
31 external
32 .into_iter()
33 .filter(|user| {
34 user.mail
35 .as_deref()
36 .is_some_and(|mail| mail.eq_ignore_ascii_case(text.trim()))
37 })
38 .map(|user| SearchPerson {
39 company_name: crate::native::known_profile(&user.id)
40 .and_then(|profile| profile.tenant_name),
41 mri: Some(format!("8:orgid:{}", user.id)),
42 email_addresses: user.mail.into_iter().collect(),
43 display_name: user.display_name.unwrap_or_default(),
44 user_principal_name: user.user_principal_name,
45 user_id: Some(user.id),
46 ..SearchPerson::default()
47 }),
48 );
49 }
50 Ok(suggestions)
27 51 }
28 52
29 53 pub async fn server_query(
@@ -44,3 +68,12 @@ impl<R: Remote> SyncEngine<R> {
44 68 })
45 69 }
46 70 }
71
72 fn has_person_with_email(suggestions: &Suggestions, email: &str) -> bool {
73 suggestions.people.iter().any(|person| {
74 person
75 .email_addresses
76 .iter()
77 .any(|address| address.eq_ignore_ascii_case(email.trim()))
78 })
79 }
@@ -1,5 +1,5 @@
1use chatsvc::substrate_search::{
1use chatsvc::substrate_search::{
2 QueryRequest, QueryResults, SearchIdentity, SearchSession, Suggestions,
2 QueryRequest, QueryResults, SearchIdentity, SearchPerson, SearchSession, Suggestions,
3};
3};
4
4
5use crate::engine::SyncEngine;
5use crate::engine::SyncEngine;
@@ -21,9 +21,33 @@ impl<R: Remote> SyncEngine<R> {
21 text: &str,
21 text: &str,
22 ) -> Result<Suggestions> {
22 ) -> Result<Suggestions> {
23 let identity = self.search_identity().await?;
23 let identity = self.search_identity().await?;
24 self.remote
24 let mut suggestions = self
25 .remote
25 .server_suggestions(&identity, search_session, text)
26 .server_suggestions(&identity, search_session, text)
26 .await
27 .await?;
28 if crate::native::is_email_address(text) && !has_person_with_email(&suggestions, text) {
29 let external = self.search_people(text).await.unwrap_or_default();
30 suggestions.people.extend(
31 external
32 .into_iter()
33 .filter(|user| {
34 user.mail
35 .as_deref()
36 .is_some_and(|mail| mail.eq_ignore_ascii_case(text.trim()))
37 })
38 .map(|user| SearchPerson {
39 company_name: crate::native::known_profile(&user.id)
40 .and_then(|profile| profile.tenant_name),
41 mri: Some(format!("8:orgid:{}", user.id)),
42 email_addresses: user.mail.into_iter().collect(),
43 display_name: user.display_name.unwrap_or_default(),
44 user_principal_name: user.user_principal_name,
45 user_id: Some(user.id),
46 ..SearchPerson::default()
47 }),
48 );
49 }
50 Ok(suggestions)
27 }
51 }
28
52
29 pub async fn server_query(
53 pub async fn server_query(
@@ -44,3 +68,12 @@ impl<R: Remote> SyncEngine<R> {
44 })
68 })
45 }
69 }
46}
70}
71
72fn has_person_with_email(suggestions: &Suggestions, email: &str) -> bool {
73 suggestions.people.iter().any(|person| {
74 person
75 .email_addresses
76 .iter()
77 .any(|address| address.eq_ignore_ascii_case(email.trim()))
78 })
79}
crates/core/src/sidebar_sync.rs +2 −0
@@ -85,6 +85,8 @@ impl<R: Remote> SyncEngine<R> {
85 85 let (records, hidden) = self.split_page(&page, &my_user_id)?;
86 86 let any_changed = self.any_chat_changed(&records)?;
87 87 self.store.upsert_chats(&records)?;
88 self.store
89 .upsert_external_people(&crate::native::external_people())?;
88 90 self.fill_kept_previews(&records)?;
89 91 kept_ids.extend(records.iter().map(|record| record.id.clone()));
90 92 hidden_ids.extend(hidden);
@@ -85,6 +85,8 @@ impl<R: Remote> SyncEngine<R> {
85 let (records, hidden) = self.split_page(&page, &my_user_id)?;
85 let (records, hidden) = self.split_page(&page, &my_user_id)?;
86 let any_changed = self.any_chat_changed(&records)?;
86 let any_changed = self.any_chat_changed(&records)?;
87 self.store.upsert_chats(&records)?;
87 self.store.upsert_chats(&records)?;
88 self.store
89 .upsert_external_people(&crate::native::external_people())?;
88 self.fill_kept_previews(&records)?;
90 self.fill_kept_previews(&records)?;
89 kept_ids.extend(records.iter().map(|record| record.id.clone()));
91 kept_ids.extend(records.iter().map(|record| record.id.clone()));
90 hidden_ids.extend(hidden);
92 hidden_ids.extend(hidden);
crates/store/src/external_people.rs added +52 −0
@@ -0,0 +1,52 @@
1 use rusqlite::params;
2
3 use crate::error::Result;
4 use crate::store::Store;
5
6 impl Store {
7 /// People of other organizations, with their organization's name when Teams gave one.
8 pub fn external_people(&self) -> Result<Vec<(String, Option<String>)>> {
9 let connection = self.lock()?;
10 let mut statement =
11 connection.prepare_cached("SELECT user_id, tenant_name FROM external_people")?;
12 let rows = statement.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;
13 Ok(rows.collect::<rusqlite::Result<_>>()?)
14 }
15
16 pub fn upsert_external_people(&self, people: &[(String, Option<String>)]) -> Result<()> {
17 let mut connection = self.lock()?;
18 let transaction = connection.transaction()?;
19 {
20 let mut statement = transaction.prepare_cached(
21 "INSERT INTO external_people (user_id, tenant_name) VALUES (?1, ?2)
22 ON CONFLICT (user_id) DO UPDATE SET
23 tenant_name = COALESCE(excluded.tenant_name, external_people.tenant_name)",
24 )?;
25 for (user_id, tenant_name) in people {
26 statement.execute(params![user_id, tenant_name])?;
27 }
28 }
29 transaction.commit()?;
30 Ok(())
31 }
32 }
33
34 #[cfg(test)]
35 mod tests {
36 use crate::store::Store;
37
38 #[test]
39 fn an_external_person_keeps_a_known_organization() {
40 let store = Store::open_in_memory().unwrap();
41 store
42 .upsert_external_people(&[("ann".into(), Some("Example Corp".into()))])
43 .unwrap();
44 store
45 .upsert_external_people(&[("ann".into(), None)])
46 .unwrap();
47 assert_eq!(
48 store.external_people().unwrap(),
49 [("ann".to_owned(), Some("Example Corp".to_owned()))]
50 );
51 }
52 }
@@ -0,0 +1,52 @@
1use rusqlite::params;
2
3use crate::error::Result;
4use crate::store::Store;
5
6impl Store {
7 /// People of other organizations, with their organization's name when Teams gave one.
8 pub fn external_people(&self) -> Result<Vec<(String, Option<String>)>> {
9 let connection = self.lock()?;
10 let mut statement =
11 connection.prepare_cached("SELECT user_id, tenant_name FROM external_people")?;
12 let rows = statement.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;
13 Ok(rows.collect::<rusqlite::Result<_>>()?)
14 }
15
16 pub fn upsert_external_people(&self, people: &[(String, Option<String>)]) -> Result<()> {
17 let mut connection = self.lock()?;
18 let transaction = connection.transaction()?;
19 {
20 let mut statement = transaction.prepare_cached(
21 "INSERT INTO external_people (user_id, tenant_name) VALUES (?1, ?2)
22 ON CONFLICT (user_id) DO UPDATE SET
23 tenant_name = COALESCE(excluded.tenant_name, external_people.tenant_name)",
24 )?;
25 for (user_id, tenant_name) in people {
26 statement.execute(params![user_id, tenant_name])?;
27 }
28 }
29 transaction.commit()?;
30 Ok(())
31 }
32}
33
34#[cfg(test)]
35mod tests {
36 use crate::store::Store;
37
38 #[test]
39 fn an_external_person_keeps_a_known_organization() {
40 let store = Store::open_in_memory().unwrap();
41 store
42 .upsert_external_people(&[("ann".into(), Some("Example Corp".into()))])
43 .unwrap();
44 store
45 .upsert_external_people(&[("ann".into(), None)])
46 .unwrap();
47 assert_eq!(
48 store.external_people().unwrap(),
49 [("ann".to_owned(), Some("Example Corp".to_owned()))]
50 );
51 }
52}
crates/store/src/lib.rs +1 −0
@@ -5,6 +5,7 @@ mod calendar_accounts;
5 5 mod chats;
6 6 mod drafts;
7 7 mod error;
8 mod external_people;
8 9 mod folders;
9 10 mod image_files;
10 11 mod images;
@@ -5,6 +5,7 @@ mod calendar_accounts;
5mod chats;
5mod chats;
6mod drafts;
6mod drafts;
7mod error;
7mod error;
8mod external_people;
8mod folders;
9mod folders;
9mod image_files;
10mod image_files;
10mod images;
11mod images;
crates/store/src/migrations.rs +4 −0
@@ -133,6 +133,10 @@ const MIGRATIONS: &[Migration] = &[
133 133 script: include_str!("migrations/0031_agent_meeting_proposals.sql"),
134 134 after: None,
135 135 },
136 Migration {
137 script: include_str!("migrations/0032_external_people.sql"),
138 after: None,
139 },
136 140 ];
137 141
138 142 pub fn latest_version() -> i64 {
@@ -133,6 +133,10 @@ const MIGRATIONS: &[Migration] = &[
133 script: include_str!("migrations/0031_agent_meeting_proposals.sql"),
133 script: include_str!("migrations/0031_agent_meeting_proposals.sql"),
134 after: None,
134 after: None,
135 },
135 },
136 Migration {
137 script: include_str!("migrations/0032_external_people.sql"),
138 after: None,
139 },
136];
140];
137
141
138pub fn latest_version() -> i64 {
142pub fn latest_version() -> i64 {
crates/store/src/migrations/0032_external_people.sql added +4 −0
@@ -0,0 +1,4 @@
1 CREATE TABLE IF NOT EXISTS external_people (
2 user_id TEXT PRIMARY KEY,
3 tenant_name TEXT
4 );
@@ -0,0 +1,4 @@
1CREATE TABLE IF NOT EXISTS external_people (
2 user_id TEXT PRIMARY KEY,
3 tenant_name TEXT
4);