BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into feat/substrate-search

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
bcc3dbb4d417c28b3eeaf90a4b073d95e36a7da2
27 files changed +768 −51
Cargo.lock +0 −2
@@ -4074,8 +4074,6 @@ dependencies = [
4074 4074 [[package]]
4075 4075 name = "gpui-pre-windows"
4076 4076 version = "0.3.8"
4077 source = "registry+https://github.com/rust-lang/crates.io-index"
4078 checksum = "371f9bb13f97e3bea2f8b8e5e81232bb74d735153c244ae67f7400e743925b1c"
4079 4077 dependencies = [
4080 4078 "accesskit",
4081 4079 "accesskit_windows",
@@ -4074,8 +4074,6 @@ dependencies = [
4074[[package]]
4074[[package]]
4075name = "gpui-pre-windows"
4075name = "gpui-pre-windows"
4076version = "0.3.8"
4076version = "0.3.8"
4077source = "registry+https://github.com/rust-lang/crates.io-index"
4078checksum = "371f9bb13f97e3bea2f8b8e5e81232bb74d735153c244ae67f7400e743925b1c"
4079dependencies = [
4077dependencies = [
4080 "accesskit",
4078 "accesskit",
4081 "accesskit_windows",
4079 "accesskit_windows",
GUARDRAILS.md added +52 −0
@@ -0,0 +1,52 @@
1 # Guardrails: where Rusty Teams matches Teams and where it may differ
2
3 Rules for every change, by people and by agents. If a rule here and a habit elsewhere disagree, this file wins.
4
5 ## Must match Teams
6
7 | Area | Rule |
8 |---|---|
9 | Content of a screen | Same elements, same order, same states, same meaning of icons as the Teams web client. |
10 | Texts | Teams strings from the bundle, in the account's Teams language. Own features get own texts in the same tone. |
11 | Behaviour | Click paths, shortcuts, defaults, when toasts and badges appear: as in Teams. Extras only additive, never replacing a Teams behaviour. |
12 | Data in the account | Same endpoints and payloads for every write. Settings Teams knows are saved to the Teams account where Teams saves them, never only locally. |
13 | What others see | Message formats, reactions, presence, call signaling: indistinguishable from Teams. |
14
15 ## May differ
16
17 | Area | Allowed |
18 |---|---|
19 | Look | Colors, spacing, islands, radii, theme (`docs/design/islands/SPEC.md`). |
20 | Data source | Microsoft Graph first, it is the official API and the path for a future registered client. Results and behaviour must still equal Teams. |
21 | Graph gaps | Where Graph loses data Teams has (e.g. reaction skin tone), take only the missing part from the Teams service (chatsvc etc.). |
22 | Requests | Extra or different requests (prefetch, caching, polling) when the result in the account is the same. |
23 | Telemetry | Leave out Teams telemetry and analytics calls. |
24 | Local bugs | Fix Teams bugs that are purely local (rendering, scroll, focus). Anything touching server data or other people stays as Teams does it. |
25 | Performance | Faster, less memory, offline reading from the cache. |
26 | Platform | OS-native toasts, tray, title bar and sounds. |
27 | Own features | MCP, agents, session inbox: allowed when nobody else can tell. Nothing sent automatically, no own message formats. |
28 | Own settings | Settings Teams does not know stay in the local DB, never in Teams account properties. |
29
30 ## Never
31
32 - UI for a Teams feature we do not build (Copilot, Loop, breakout rooms): no button, no placeholder, no dead click.
33 - Own properties or message formats on the server.
34
35 ## Internal endpoints
36
37 Every non-Graph endpoint (chatsvc, Substrate, calling, presence service, ...) lives behind its own clearly named module and is listed in `docs/research/internal-endpoints.md` with what it is used for and whether Graph could replace it.
38
39 ## Testing with the real account
40
41 | Allowed without asking | Ask first |
42 |---|---|
43 | Anything only Daniel sees: `48:notes`, Echo bot, Meet now alone, own settings | Messages, reactions or calls in chats with other people |
44 | Short presence or status changes, reset afterwards | |
45
46 Clean up after every test: delete test messages, restore settings and status.
47
48 ## Before building
49
50 1. Find how Teams does it: `docs/research/*.md`, then the live bundle.
51 2. Write findings back to `docs/research/<topic>.md`.
52 3. If a change has to break a "must match" rule, name the deviation in the commit body.
@@ -0,0 +1,52 @@
1# Guardrails: where Rusty Teams matches Teams and where it may differ
2
3Rules for every change, by people and by agents. If a rule here and a habit elsewhere disagree, this file wins.
4
5## Must match Teams
6
7| Area | Rule |
8|---|---|
9| Content of a screen | Same elements, same order, same states, same meaning of icons as the Teams web client. |
10| Texts | Teams strings from the bundle, in the account's Teams language. Own features get own texts in the same tone. |
11| Behaviour | Click paths, shortcuts, defaults, when toasts and badges appear: as in Teams. Extras only additive, never replacing a Teams behaviour. |
12| Data in the account | Same endpoints and payloads for every write. Settings Teams knows are saved to the Teams account where Teams saves them, never only locally. |
13| What others see | Message formats, reactions, presence, call signaling: indistinguishable from Teams. |
14
15## May differ
16
17| Area | Allowed |
18|---|---|
19| Look | Colors, spacing, islands, radii, theme (`docs/design/islands/SPEC.md`). |
20| Data source | Microsoft Graph first, it is the official API and the path for a future registered client. Results and behaviour must still equal Teams. |
21| Graph gaps | Where Graph loses data Teams has (e.g. reaction skin tone), take only the missing part from the Teams service (chatsvc etc.). |
22| Requests | Extra or different requests (prefetch, caching, polling) when the result in the account is the same. |
23| Telemetry | Leave out Teams telemetry and analytics calls. |
24| Local bugs | Fix Teams bugs that are purely local (rendering, scroll, focus). Anything touching server data or other people stays as Teams does it. |
25| Performance | Faster, less memory, offline reading from the cache. |
26| Platform | OS-native toasts, tray, title bar and sounds. |
27| Own features | MCP, agents, session inbox: allowed when nobody else can tell. Nothing sent automatically, no own message formats. |
28| Own settings | Settings Teams does not know stay in the local DB, never in Teams account properties. |
29
30## Never
31
32- UI for a Teams feature we do not build (Copilot, Loop, breakout rooms): no button, no placeholder, no dead click.
33- Own properties or message formats on the server.
34
35## Internal endpoints
36
37Every non-Graph endpoint (chatsvc, Substrate, calling, presence service, ...) lives behind its own clearly named module and is listed in `docs/research/internal-endpoints.md` with what it is used for and whether Graph could replace it.
38
39## Testing with the real account
40
41| Allowed without asking | Ask first |
42|---|---|
43| Anything only Daniel sees: `48:notes`, Echo bot, Meet now alone, own settings | Messages, reactions or calls in chats with other people |
44| Short presence or status changes, reset afterwards | |
45
46Clean up after every test: delete test messages, restore settings and status.
47
48## Before building
49
501. Find how Teams does it: `docs/research/*.md`, then the live bundle.
512. Write findings back to `docs/research/<topic>.md`.
523. If a change has to break a "must match" rule, name the deviation in the commit body.
crates/app-base/src/assets.rs +2 −1
@@ -8,7 +8,8 @@ macro_rules! symbols {
8 8 };
9 9 }
10 10
11 const SYMBOLS: [(&str, &[u8]); 53] = symbols![
11 const SYMBOLS: [(&str, &[u8]); 54] = symbols![
12 "bot",
12 13 "done",
13 14 "done_all",
14 15 "keyboard_return",
@@ -8,7 +8,8 @@ macro_rules! symbols {
8 };
8 };
9}
9}
10
10
11const SYMBOLS: [(&str, &[u8]); 53] = symbols![
11const SYMBOLS: [(&str, &[u8]); 54] = symbols![
12 "bot",
12 "done",
13 "done",
13 "done_all",
14 "done_all",
14 "keyboard_return",
15 "keyboard_return",
crates/app-base/src/theme.rs +5 −0
@@ -64,6 +64,7 @@ const RED_TINT: u32 = 0xfca5a5;
64 64 const AMBER: u32 = 0xfbbf24;
65 65 const OUT_OF_OFFICE: u32 = 0xc239b3;
66 66 const MEETING_AVATAR: u32 = 0x4f52b2;
67 const BOT_AVATAR: u32 = 0x3a96dd;
67 68 const AVATAR_PALETTE: [u32; 6] = [0x9a4a22, 0x44606e, 0x8a3434, 0x4f6a3c, 0x6a4f7a, 0x2f6b63];
68 69
69 70 pub fn color(hex: u32) -> Hsla {
@@ -395,6 +396,10 @@ pub fn meeting_avatar() -> Hsla {
395 396 color(MEETING_AVATAR)
396 397 }
397 398
399 pub fn bot_avatar() -> Hsla {
400 color(BOT_AVATAR)
401 }
402
398 403 pub fn avatar_color(index: usize) -> Hsla {
399 404 color(AVATAR_PALETTE[index % AVATAR_PALETTE.len()])
400 405 }
@@ -64,6 +64,7 @@ const RED_TINT: u32 = 0xfca5a5;
64const AMBER: u32 = 0xfbbf24;
64const AMBER: u32 = 0xfbbf24;
65const OUT_OF_OFFICE: u32 = 0xc239b3;
65const OUT_OF_OFFICE: u32 = 0xc239b3;
66const MEETING_AVATAR: u32 = 0x4f52b2;
66const MEETING_AVATAR: u32 = 0x4f52b2;
67const BOT_AVATAR: u32 = 0x3a96dd;
67const AVATAR_PALETTE: [u32; 6] = [0x9a4a22, 0x44606e, 0x8a3434, 0x4f6a3c, 0x6a4f7a, 0x2f6b63];
68const AVATAR_PALETTE: [u32; 6] = [0x9a4a22, 0x44606e, 0x8a3434, 0x4f6a3c, 0x6a4f7a, 0x2f6b63];
68
69
69pub fn color(hex: u32) -> Hsla {
70pub fn color(hex: u32) -> Hsla {
@@ -395,6 +396,10 @@ pub fn meeting_avatar() -> Hsla {
395 color(MEETING_AVATAR)
396 color(MEETING_AVATAR)
396}
397}
397
398
399pub fn bot_avatar() -> Hsla {
400 color(BOT_AVATAR)
401}
402
398pub fn avatar_color(index: usize) -> Hsla {
403pub fn avatar_color(index: usize) -> Hsla {
399 color(AVATAR_PALETTE[index % AVATAR_PALETTE.len()])
404 color(AVATAR_PALETTE[index % AVATAR_PALETTE.len()])
400}
405}
crates/app-state/src/call/target.rs +2 −1
@@ -1,5 +1,5 @@
1 1 use calling::meeting::LiveMeeting;
2 use store::ChatRecord;
2 use store::{ChatRecord, is_bot_id};
3 3
4 4 use crate::data::{Person, is_one_on_one, others};
5 5
@@ -17,6 +17,7 @@ pub fn plan_for_chat(chat: &ChatRecord, me: Option<&Person>) -> Option<CallPlan>
17 17 }
18 18 let callees: Vec<(String, String)> = others(chat, me)
19 19 .into_iter()
20 .filter(|(user_id, _)| !user_id.as_deref().is_some_and(is_bot_id))
20 21 .filter_map(|(user_id, name)| Some((format!("{ORGID_PREFIX}{}", user_id?), name)))
21 22 .collect();
22 23 let title = match callees.as_slice() {
@@ -1,5 +1,5 @@
1use calling::meeting::LiveMeeting;
1use calling::meeting::LiveMeeting;
2use store::ChatRecord;
2use store::{ChatRecord, is_bot_id};
3
3
4use crate::data::{Person, is_one_on_one, others};
4use crate::data::{Person, is_one_on_one, others};
5
5
@@ -17,6 +17,7 @@ pub fn plan_for_chat(chat: &ChatRecord, me: Option<&Person>) -> Option<CallPlan>
17 }
17 }
18 let callees: Vec<(String, String)> = others(chat, me)
18 let callees: Vec<(String, String)> = others(chat, me)
19 .into_iter()
19 .into_iter()
20 .filter(|(user_id, _)| !user_id.as_deref().is_some_and(is_bot_id))
20 .filter_map(|(user_id, name)| Some((format!("{ORGID_PREFIX}{}", user_id?), name)))
21 .filter_map(|(user_id, name)| Some((format!("{ORGID_PREFIX}{}", user_id?), name)))
21 .collect();
22 .collect();
22 let title = match callees.as_slice() {
23 let title = match callees.as_slice() {
crates/app-state/src/data.rs +20 −6
@@ -4,7 +4,7 @@ use std::sync::Arc;
4 4 use std::time::{Duration, Instant};
5 5
6 6 use gpui_kit::{Image, ImageFormat};
7 use store::{ChatRecord, Store};
7 use store::{ChatRecord, Store, is_bot_id};
8 8
9 9 use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange};
10 10 use tokio::sync::oneshot;
@@ -442,6 +442,18 @@ pub fn others(chat: &ChatRecord, me: Option<&Person>) -> Vec<(Option<String>, St
442 442 .collect()
443 443 }
444 444
445 pub fn one_on_one_bot(chat: &ChatRecord, me: Option<&Person>) -> Option<(Option<String>, String)> {
446 if !is_one_on_one(chat) {
447 return None;
448 }
449 match others(chat, me).as_slice() {
450 [(Some(user_id), name)] if is_bot_id(user_id) => {
451 Some((Some(user_id.clone()), name.clone()))
452 }
453 _ => None,
454 }
455 }
456
445 457 pub fn existing_one_on_one<'chats>(
446 458 chats: &'chats [ChatRecord],
447 459 me: Option<&Person>,
@@ -521,11 +533,13 @@ pub fn pinned_channels(store: &Store) -> Vec<String> {
521 533
522 534 pub fn cached_avatar(store: &Store, user_id: &str) -> Option<Option<Arc<Image>>> {
523 535 let record = store.avatar(user_id).ok().flatten()?;
524 Some(
525 record
526 .bytes
527 .map(|bytes| avatar_image_from(&record.content_type, bytes)),
528 )
536 Some(record.bytes.map(|bytes| {
537 if is_bot_id(user_id) {
538 Arc::new(Image::from_bytes(image_format(&record.content_type), bytes))
539 } else {
540 avatar_image_from(&record.content_type, bytes)
541 }
542 }))
529 543 }
530 544
531 545 pub fn avatar_image_from(content_type: &str, bytes: Vec<u8>) -> Arc<Image> {
@@ -4,7 +4,7 @@ use std::sync::Arc;
4use std::time::{Duration, Instant};
4use std::time::{Duration, Instant};
5
5
6use gpui_kit::{Image, ImageFormat};
6use gpui_kit::{Image, ImageFormat};
7use store::{ChatRecord, Store};
7use store::{ChatRecord, Store, is_bot_id};
8
8
9use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange};
9use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange};
10use tokio::sync::oneshot;
10use tokio::sync::oneshot;
@@ -442,6 +442,18 @@ pub fn others(chat: &ChatRecord, me: Option<&Person>) -> Vec<(Option<String>, St
442 .collect()
442 .collect()
443}
443}
444
444
445pub fn one_on_one_bot(chat: &ChatRecord, me: Option<&Person>) -> Option<(Option<String>, String)> {
446 if !is_one_on_one(chat) {
447 return None;
448 }
449 match others(chat, me).as_slice() {
450 [(Some(user_id), name)] if is_bot_id(user_id) => {
451 Some((Some(user_id.clone()), name.clone()))
452 }
453 _ => None,
454 }
455}
456
445pub fn existing_one_on_one<'chats>(
457pub fn existing_one_on_one<'chats>(
446 chats: &'chats [ChatRecord],
458 chats: &'chats [ChatRecord],
447 me: Option<&Person>,
459 me: Option<&Person>,
@@ -521,11 +533,13 @@ pub fn pinned_channels(store: &Store) -> Vec<String> {
521
533
522pub fn cached_avatar(store: &Store, user_id: &str) -> Option<Option<Arc<Image>>> {
534pub fn cached_avatar(store: &Store, user_id: &str) -> Option<Option<Arc<Image>>> {
523 let record = store.avatar(user_id).ok().flatten()?;
535 let record = store.avatar(user_id).ok().flatten()?;
524 Some(
536 Some(record.bytes.map(|bytes| {
525 record
537 if is_bot_id(user_id) {
526 .bytes
538 Arc::new(Image::from_bytes(image_format(&record.content_type), bytes))
527 .map(|bytes| avatar_image_from(&record.content_type, bytes)),
539 } else {
528 )
540 avatar_image_from(&record.content_type, bytes)
541 }
542 }))
529}
543}
530
544
531pub fn avatar_image_from(content_type: &str, bytes: Vec<u8>) -> Arc<Image> {
545pub fn avatar_image_from(content_type: &str, bytes: Vec<u8>) -> Arc<Image> {
crates/app-state/src/demo.rs +12 −0
@@ -38,6 +38,8 @@ const LINK_IMAGE_SIZE: (u32, u32) = (320, 180);
38 38 const PRIORITY_CHAT: &str = "demo-chat-priya";
39 39 const BOT_CHAT: &str = "demo-chat-wiki-bot";
40 40 const BOT_NAME: &str = "Wiki Bot";
41 const ECHO_CHAT: &str = "demo-chat-echo";
42 const ECHO_BOT_ID: &str = "28:demo-echo";
41 43 const BOT_APP_NAME: &str = "Wiki Cloud";
42 44 const BOT_ID: &str = "00000000-0000-0000-0000-00000000b07a";
43 45 const CARD_ANSWER_DELAY: std::time::Duration = std::time::Duration::from_millis(700);
@@ -294,6 +296,16 @@ fn demo_chats() -> Vec<DemoChat> {
294 296 preview: Some((PRIYA_ID, "Priya Nair", "Who is taking the review?")),
295 297 deleted: false,
296 298 },
299 DemoChat {
300 id: ECHO_CHAT,
301 kind: "oneOnOne",
302 title: "Echo",
303 members: people(&[(ECHO_BOT_ID, "Echo")]),
304 time: at(0, 11, 20),
305 unread: false,
306 preview: Some(("", "", "Recording is ready")),
307 deleted: false,
308 },
297 309 DemoChat {
298 310 id: "demo-chat-jonas",
299 311 kind: "oneOnOne",
@@ -38,6 +38,8 @@ const LINK_IMAGE_SIZE: (u32, u32) = (320, 180);
38const PRIORITY_CHAT: &str = "demo-chat-priya";
38const PRIORITY_CHAT: &str = "demo-chat-priya";
39const BOT_CHAT: &str = "demo-chat-wiki-bot";
39const BOT_CHAT: &str = "demo-chat-wiki-bot";
40const BOT_NAME: &str = "Wiki Bot";
40const BOT_NAME: &str = "Wiki Bot";
41const ECHO_CHAT: &str = "demo-chat-echo";
42const ECHO_BOT_ID: &str = "28:demo-echo";
41const BOT_APP_NAME: &str = "Wiki Cloud";
43const BOT_APP_NAME: &str = "Wiki Cloud";
42const BOT_ID: &str = "00000000-0000-0000-0000-00000000b07a";
44const BOT_ID: &str = "00000000-0000-0000-0000-00000000b07a";
43const CARD_ANSWER_DELAY: std::time::Duration = std::time::Duration::from_millis(700);
45const CARD_ANSWER_DELAY: std::time::Duration = std::time::Duration::from_millis(700);
@@ -294,6 +296,16 @@ fn demo_chats() -> Vec<DemoChat> {
294 preview: Some((PRIYA_ID, "Priya Nair", "Who is taking the review?")),
296 preview: Some((PRIYA_ID, "Priya Nair", "Who is taking the review?")),
295 deleted: false,
297 deleted: false,
296 },
298 },
299 DemoChat {
300 id: ECHO_CHAT,
301 kind: "oneOnOne",
302 title: "Echo",
303 members: people(&[(ECHO_BOT_ID, "Echo")]),
304 time: at(0, 11, 20),
305 unread: false,
306 preview: Some(("", "", "Recording is ready")),
307 deleted: false,
308 },
297 DemoChat {
309 DemoChat {
298 id: "demo-chat-jonas",
310 id: "demo-chat-jonas",
299 kind: "oneOnOne",
311 kind: "oneOnOne",
crates/app-state/src/sidebar_model.rs +59 −5
@@ -1,13 +1,14 @@
1 1 use std::collections::{HashMap, HashSet};
2 2
3 3 use chrono::{DateTime, FixedOffset, Utc};
4 use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam};
5 use teams_core::ChatSection;
4 use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};
5 use teams_core::{ChatSection, is_event_preview};
6 6 use app_ui_kit::widgets::Unread;
7 7
8 8 use crate::app_state::chat_title;
9 9 use crate::data::{
10 Directory, FolderKind, Person, face_members, is_one_on_one, others, unread_count,
10 Directory, FolderKind, Person, face_members, is_one_on_one, one_on_one_bot, others,
11 unread_count,
11 12 };
12 13 use crate::format;
13 14 use crate::typing::{TypingState, preview_label};
@@ -28,6 +29,7 @@ const GROUP_KIND: &str = "group";
28 29 pub enum Preview {
29 30 Empty,
30 31 Deleted,
32 Event(String),
31 33 Typing(String),
32 34 Text {
33 35 prefix: Option<String>,
@@ -45,6 +47,7 @@ pub struct Face {
45 47 pub enum AvatarSpec {
46 48 Single(Face),
47 49 Pair(Face, Face),
50 Bot(Face),
48 51 Meeting,
49 52 Muted,
50 53 }
@@ -108,7 +111,14 @@ pub fn preview_for(chat: &ChatRecord, me: Option<&Person>) -> Preview {
108 111 else {
109 112 return Preview::Empty;
110 113 };
111 let from_me = match (chat.last_message_sender_id.as_deref(), me) {
114 let sender_id = chat
115 .last_message_sender_id
116 .as_deref()
117 .filter(|sender_id| !sender_id.is_empty());
118 if sender_id.is_none() && is_event_preview(text) {
119 return Preview::Event(text.to_owned());
120 }
121 let from_me = match (sender_id, me) {
112 122 (Some(sender), Some(me)) => sender == me.user_id,
113 123 _ => false,
114 124 };
@@ -134,6 +144,9 @@ pub fn avatar_for(chat: &ChatRecord, me: Option<&Person>) -> AvatarSpec {
134 144 }
135 145 let faces = face_members(chat, me);
136 146 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
147 if let Some(bot) = one_on_one_bot(chat, me) {
148 return AvatarSpec::Bot(face(bot));
149 }
137 150 if is_one_on_one(chat) || faces.len() < 2 {
138 151 return AvatarSpec::Single(match faces.into_iter().next() {
139 152 Some(first) => face(first),
@@ -169,7 +182,8 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<
169 182 .into_iter()
170 183 .find_map(|(user_id, _)| user_id)
171 184 })
172 .flatten();
185 .flatten()
186 .filter(|user_id| !is_bot_id(user_id));
173 187 let typing_names = input.typing.names(&chat.id);
174 188 let preview = if typing_names.is_empty() {
175 189 preview_for(chat, me)
@@ -1025,6 +1039,46 @@ mod tests {
1025 1039 assert_eq!(avatar_for(&meeting_chat("meeting-1"), None), AvatarSpec::Meeting);
1026 1040 }
1027 1041
1042 #[test]
1043 fn a_one_on_one_with_a_bot_shows_the_bot_tile_and_no_presence() {
1044 let directory = Directory {
1045 me: Some(me()),
1046 ..Default::default()
1047 };
1048 let collapsed = HashSet::new();
1049 let mut echo = chat("echo", "oneOnOne", false);
1050 echo.title = "Echo".into();
1051 echo.members.truncate(1);
1052 echo.members.push(MemberRecord {
1053 user_id: Some("28:bot-echo".into()),
1054 display_name: "Echo".into(),
1055 });
1056 echo.last_message_preview = Some("Recording is ready".into());
1057 let chats = vec![echo];
1058 let context = input(&chats, &directory, &collapsed);
1059 let item = chat_item(&chats[0], &context, None);
1060 assert_eq!(item.title, "Echo");
1061 assert_eq!(item.presence_user, None);
1062 assert!(
1063 matches!(item.avatar, AvatarSpec::Bot(ref face) if face.user_id.as_deref() == Some("28:bot-echo"))
1064 );
1065 assert_eq!(item.preview, Preview::Event("Recording is ready".into()));
1066 }
1067
1068 #[test]
1069 fn an_event_label_from_a_person_stays_plain_text() {
1070 let mut direct = chat("d", "oneOnOne", false);
1071 direct.last_message_preview = Some("Recording is ready".into());
1072 direct.last_message_sender_id = Some("ada".into());
1073 assert_eq!(
1074 preview_for(&direct, Some(&me())),
1075 Preview::Text {
1076 prefix: None,
1077 text: "Recording is ready".into()
1078 }
1079 );
1080 }
1081
1028 1082 #[test]
1029 1083 fn typing_replaces_the_preview_even_in_muted_chats() {
1030 1084 let mut direct = chat("d", "oneOnOne", false);
@@ -1,13 +1,14 @@
1use std::collections::{HashMap, HashSet};
1use std::collections::{HashMap, HashSet};
2
2
3use chrono::{DateTime, FixedOffset, Utc};
3use chrono::{DateTime, FixedOffset, Utc};
4use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam};
4use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};
5use teams_core::ChatSection;
5use teams_core::{ChatSection, is_event_preview};
6use app_ui_kit::widgets::Unread;
6use app_ui_kit::widgets::Unread;
7
7
8use crate::app_state::chat_title;
8use crate::app_state::chat_title;
9use crate::data::{
9use crate::data::{
10 Directory, FolderKind, Person, face_members, is_one_on_one, others, unread_count,
10 Directory, FolderKind, Person, face_members, is_one_on_one, one_on_one_bot, others,
11 unread_count,
11};
12};
12use crate::format;
13use crate::format;
13use crate::typing::{TypingState, preview_label};
14use crate::typing::{TypingState, preview_label};
@@ -28,6 +29,7 @@ const GROUP_KIND: &str = "group";
28pub enum Preview {
29pub enum Preview {
29 Empty,
30 Empty,
30 Deleted,
31 Deleted,
32 Event(String),
31 Typing(String),
33 Typing(String),
32 Text {
34 Text {
33 prefix: Option<String>,
35 prefix: Option<String>,
@@ -45,6 +47,7 @@ pub struct Face {
45pub enum AvatarSpec {
47pub enum AvatarSpec {
46 Single(Face),
48 Single(Face),
47 Pair(Face, Face),
49 Pair(Face, Face),
50 Bot(Face),
48 Meeting,
51 Meeting,
49 Muted,
52 Muted,
50}
53}
@@ -108,7 +111,14 @@ pub fn preview_for(chat: &ChatRecord, me: Option<&Person>) -> Preview {
108 else {
111 else {
109 return Preview::Empty;
112 return Preview::Empty;
110 };
113 };
111 let from_me = match (chat.last_message_sender_id.as_deref(), me) {
114 let sender_id = chat
115 .last_message_sender_id
116 .as_deref()
117 .filter(|sender_id| !sender_id.is_empty());
118 if sender_id.is_none() && is_event_preview(text) {
119 return Preview::Event(text.to_owned());
120 }
121 let from_me = match (sender_id, me) {
112 (Some(sender), Some(me)) => sender == me.user_id,
122 (Some(sender), Some(me)) => sender == me.user_id,
113 _ => false,
123 _ => false,
114 };
124 };
@@ -134,6 +144,9 @@ pub fn avatar_for(chat: &ChatRecord, me: Option<&Person>) -> AvatarSpec {
134 }
144 }
135 let faces = face_members(chat, me);
145 let faces = face_members(chat, me);
136 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
146 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
147 if let Some(bot) = one_on_one_bot(chat, me) {
148 return AvatarSpec::Bot(face(bot));
149 }
137 if is_one_on_one(chat) || faces.len() < 2 {
150 if is_one_on_one(chat) || faces.len() < 2 {
138 return AvatarSpec::Single(match faces.into_iter().next() {
151 return AvatarSpec::Single(match faces.into_iter().next() {
139 Some(first) => face(first),
152 Some(first) => face(first),
@@ -169,7 +182,8 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<
169 .into_iter()
182 .into_iter()
170 .find_map(|(user_id, _)| user_id)
183 .find_map(|(user_id, _)| user_id)
171 })
184 })
172 .flatten();
185 .flatten()
186 .filter(|user_id| !is_bot_id(user_id));
173 let typing_names = input.typing.names(&chat.id);
187 let typing_names = input.typing.names(&chat.id);
174 let preview = if typing_names.is_empty() {
188 let preview = if typing_names.is_empty() {
175 preview_for(chat, me)
189 preview_for(chat, me)
@@ -1025,6 +1039,46 @@ mod tests {
1025 assert_eq!(avatar_for(&meeting_chat("meeting-1"), None), AvatarSpec::Meeting);
1039 assert_eq!(avatar_for(&meeting_chat("meeting-1"), None), AvatarSpec::Meeting);
1026 }
1040 }
1027
1041
1042 #[test]
1043 fn a_one_on_one_with_a_bot_shows_the_bot_tile_and_no_presence() {
1044 let directory = Directory {
1045 me: Some(me()),
1046 ..Default::default()
1047 };
1048 let collapsed = HashSet::new();
1049 let mut echo = chat("echo", "oneOnOne", false);
1050 echo.title = "Echo".into();
1051 echo.members.truncate(1);
1052 echo.members.push(MemberRecord {
1053 user_id: Some("28:bot-echo".into()),
1054 display_name: "Echo".into(),
1055 });
1056 echo.last_message_preview = Some("Recording is ready".into());
1057 let chats = vec![echo];
1058 let context = input(&chats, &directory, &collapsed);
1059 let item = chat_item(&chats[0], &context, None);
1060 assert_eq!(item.title, "Echo");
1061 assert_eq!(item.presence_user, None);
1062 assert!(
1063 matches!(item.avatar, AvatarSpec::Bot(ref face) if face.user_id.as_deref() == Some("28:bot-echo"))
1064 );
1065 assert_eq!(item.preview, Preview::Event("Recording is ready".into()));
1066 }
1067
1068 #[test]
1069 fn an_event_label_from_a_person_stays_plain_text() {
1070 let mut direct = chat("d", "oneOnOne", false);
1071 direct.last_message_preview = Some("Recording is ready".into());
1072 direct.last_message_sender_id = Some("ada".into());
1073 assert_eq!(
1074 preview_for(&direct, Some(&me())),
1075 Preview::Text {
1076 prefix: None,
1077 text: "Recording is ready".into()
1078 }
1079 );
1080 }
1081
1028 #[test]
1082 #[test]
1029 fn typing_replaces_the_preview_even_in_muted_chats() {
1083 fn typing_replaces_the_preview_even_in_muted_chats() {
1030 let mut direct = chat("d", "oneOnOne", false);
1084 let mut direct = chat("d", "oneOnOne", false);
crates/app/assets/symbols/bot.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 300" width="24" height="24"><path d="M116 85 57.5 150 116 215M184 85 242.5 150 184 215" fill="none" stroke="#000" stroke-width="18" stroke-linecap="round" stroke-linejoin="round"/><circle cx="126.5" cy="150" r="11"/><circle cx="171.5" cy="150" r="11"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 300" width="24" height="24"><path d="M116 85 57.5 150 116 215M184 85 242.5 150 184 215" fill="none" stroke="#000" stroke-width="18" stroke-linecap="round" stroke-linejoin="round"/><circle cx="126.5" cy="150" r="11"/><circle cx="171.5" cy="150" r="11"/></svg>
crates/app/src/views/avatar.rs +26 −1
@@ -11,7 +11,7 @@ use crate::format;
11 11 use crate::sidebar_model::{AvatarSpec, Face};
12 12 use crate::theme;
13 13 use crate::views::profile_card::opens_profile;
14 use crate::views::widgets::{Corner, corner_badge, icon};
14 use crate::views::widgets::{Corner, corner_badge, icon, symbol};
15 15
16 16 const PAIR_RATIO: f32 = 24. / 36.;
17 17 const PRESENCE_MIN: f32 = 10.;
@@ -23,6 +23,7 @@ const CACHED_PRESENCE_OPACITY: f32 = 0.5;
23 23 const INITIALS_RATIO: f32 = 0.36;
24 24 const PAIR_INITIALS_RATIO: f32 = 0.42;
25 25 const MEETING_ICON_RATIO: f32 = 0.5;
26 const BOT_CORNER_RATIO: f32 = 0.25;
26 27
27 28 fn initials_circle(name: &str, key: &str, size: f32, pending: bool, text_ratio: f32) -> Div {
28 29 let (background, foreground) = if pending {
@@ -113,6 +114,29 @@ pub fn bot_avatar(identity: &BotIdentity, size: f32) -> AnyElement {
113 114 }
114 115 }
115 116
117 pub fn bot_tile(directory: &Directory, face: &Face, size: f32) -> AnyElement {
118 let radius = (size * BOT_CORNER_RATIO).round();
119 let image = face
120 .user_id
121 .as_deref()
122 .and_then(|user_id| directory.avatar(user_id));
123 let tile = div().size(px(size)).flex_none().rounded(px(radius));
124 match image {
125 Some(AvatarState::Ready(image)) => tile
126 .child(
127 img(ImageSource::Image(image.clone()))
128 .size_full()
129 .rounded(px(radius))
130 .object_fit(ObjectFit::Cover),
131 )
132 .into_any_element(),
133 _ => tile
134 .bg(theme::bot_avatar())
135 .child(symbol("bot", size, theme::white()))
136 .into_any_element(),
137 }
138 }
139
116 140 pub fn presence_size(avatar_size: f32) -> f32 {
117 141 (avatar_size * PRESENCE_RATIO)
118 142 .round()
@@ -189,6 +213,7 @@ pub fn with_presence(avatar: AnyElement, presence: Presence, size: f32, ring: Hs
189 213 pub fn spec_avatar(directory: &Directory, spec: &AvatarSpec, size: f32, ring: Hsla) -> AnyElement {
190 214 match spec {
191 215 AvatarSpec::Single(face) => face_circle(directory, face, size, INITIALS_RATIO),
216 AvatarSpec::Bot(face) => bot_tile(directory, face, size),
192 217 AvatarSpec::Meeting => div()
193 218 .size(px(size))
194 219 .flex_none()
@@ -11,7 +11,7 @@ use crate::format;
11use crate::sidebar_model::{AvatarSpec, Face};
11use crate::sidebar_model::{AvatarSpec, Face};
12use crate::theme;
12use crate::theme;
13use crate::views::profile_card::opens_profile;
13use crate::views::profile_card::opens_profile;
14use crate::views::widgets::{Corner, corner_badge, icon};
14use crate::views::widgets::{Corner, corner_badge, icon, symbol};
15
15
16const PAIR_RATIO: f32 = 24. / 36.;
16const PAIR_RATIO: f32 = 24. / 36.;
17const PRESENCE_MIN: f32 = 10.;
17const PRESENCE_MIN: f32 = 10.;
@@ -23,6 +23,7 @@ const CACHED_PRESENCE_OPACITY: f32 = 0.5;
23const INITIALS_RATIO: f32 = 0.36;
23const INITIALS_RATIO: f32 = 0.36;
24const PAIR_INITIALS_RATIO: f32 = 0.42;
24const PAIR_INITIALS_RATIO: f32 = 0.42;
25const MEETING_ICON_RATIO: f32 = 0.5;
25const MEETING_ICON_RATIO: f32 = 0.5;
26const BOT_CORNER_RATIO: f32 = 0.25;
26
27
27fn initials_circle(name: &str, key: &str, size: f32, pending: bool, text_ratio: f32) -> Div {
28fn initials_circle(name: &str, key: &str, size: f32, pending: bool, text_ratio: f32) -> Div {
28 let (background, foreground) = if pending {
29 let (background, foreground) = if pending {
@@ -113,6 +114,29 @@ pub fn bot_avatar(identity: &BotIdentity, size: f32) -> AnyElement {
113 }
114 }
114}
115}
115
116
117pub fn bot_tile(directory: &Directory, face: &Face, size: f32) -> AnyElement {
118 let radius = (size * BOT_CORNER_RATIO).round();
119 let image = face
120 .user_id
121 .as_deref()
122 .and_then(|user_id| directory.avatar(user_id));
123 let tile = div().size(px(size)).flex_none().rounded(px(radius));
124 match image {
125 Some(AvatarState::Ready(image)) => tile
126 .child(
127 img(ImageSource::Image(image.clone()))
128 .size_full()
129 .rounded(px(radius))
130 .object_fit(ObjectFit::Cover),
131 )
132 .into_any_element(),
133 _ => tile
134 .bg(theme::bot_avatar())
135 .child(symbol("bot", size, theme::white()))
136 .into_any_element(),
137 }
138}
139
116pub fn presence_size(avatar_size: f32) -> f32 {
140pub fn presence_size(avatar_size: f32) -> f32 {
117 (avatar_size * PRESENCE_RATIO)
141 (avatar_size * PRESENCE_RATIO)
118 .round()
142 .round()
@@ -189,6 +213,7 @@ pub fn with_presence(avatar: AnyElement, presence: Presence, size: f32, ring: Hs
189pub fn spec_avatar(directory: &Directory, spec: &AvatarSpec, size: f32, ring: Hsla) -> AnyElement {
213pub fn spec_avatar(directory: &Directory, spec: &AvatarSpec, size: f32, ring: Hsla) -> AnyElement {
190 match spec {
214 match spec {
191 AvatarSpec::Single(face) => face_circle(directory, face, size, INITIALS_RATIO),
215 AvatarSpec::Single(face) => face_circle(directory, face, size, INITIALS_RATIO),
216 AvatarSpec::Bot(face) => bot_tile(directory, face, size),
192 AvatarSpec::Meeting => div()
217 AvatarSpec::Meeting => div()
193 .size(px(size))
218 .size(px(size))
194 .flex_none()
219 .flex_none()
crates/app/src/views/conversation.rs +21 −10
@@ -16,7 +16,7 @@ use gpui_kit::component::{
16 16 };
17 17 use gpui_kit::prelude::FluentBuilder as _;
18 18 use gpui_kit::*;
19 use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget};
19 use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget, is_bot_id};
20 20 use teams_core::{
21 21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,
22 22 };
@@ -31,7 +31,9 @@ mod scheduled;
31 31 mod shared;
32 32
33 33 use super::attachments::FileActions;
34 use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
34 use super::avatar::{
35 bot_tile, member_stack, person_avatar, spec_avatar, square_avatar, with_presence,
36 };
35 37 use super::call_controls::header_call_controls;
36 38 use super::channel_tabs::ChannelPane;
37 39 use super::chat_members::members_popover;
@@ -51,7 +53,7 @@ use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_t
51 53 use crate::backend::Engine;
52 54 use crate::card_state::CardScope;
53 55 use crate::channel_files::DownloadSource;
54 use crate::data::{existing_one_on_one, is_one_on_one, others};
56 use crate::data::{existing_one_on_one, is_one_on_one, one_on_one_bot, others};
55 57 use crate::demo_library::DemoLibrary;
56 58 use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
57 59 use crate::emoji;
@@ -3221,7 +3223,9 @@ impl ConversationView {
3221 3223 let faces = others(chat, me);
3222 3224 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
3223 3225 let first = faces.first().cloned().map(face);
3224 if is_one_on_one(chat) || faces.len() < 2 {
3226 if let Some(bot) = one_on_one_bot(chat, me) {
3227 lead = Some(bot_tile(directory, &face(bot), 36.));
3228 } else if is_one_on_one(chat) || faces.len() < 2 {
3225 3229 let name = first
3226 3230 .as_ref()
3227 3231 .map_or(current.title.as_str(), |face| face.name.as_str());
@@ -3467,12 +3471,19 @@ impl Render for ConversationView {
3467 3471 .gap(px(8.))
3468 3472 .pt(px(32.))
3469 3473 .pb(px(16.))
3470 .child(person_avatar(
3471 &state.directory,
3472 start.user_id.as_deref(),
3473 &start.title,
3474 56.,
3475 ))
3474 .child(match start.user_id.as_deref() {
3475 Some(user_id) if is_bot_id(user_id) => bot_tile(
3476 &state.directory,
3477 &Face {
3478 user_id: Some(user_id.to_owned()),
3479 name: start.title.clone(),
3480 },
3481 56.,
3482 ),
3483 user_id => {
3484 person_avatar(&state.directory, user_id, &start.title, 56.)
3485 }
3486 })
3476 3487 .child(
3477 3488 div()
3478 3489 .text_size(px(16.))
@@ -16,7 +16,7 @@ use gpui_kit::component::{
16};
16};
17use gpui_kit::prelude::FluentBuilder as _;
17use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::*;
18use gpui_kit::*;
19use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget};
19use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget, is_bot_id};
20use teams_core::{
20use teams_core::{
21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,
21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,
22};
22};
@@ -31,7 +31,9 @@ mod scheduled;
31mod shared;
31mod shared;
32
32
33use super::attachments::FileActions;
33use super::attachments::FileActions;
34use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
34use super::avatar::{
35 bot_tile, member_stack, person_avatar, spec_avatar, square_avatar, with_presence,
36};
35use super::call_controls::header_call_controls;
37use super::call_controls::header_call_controls;
36use super::channel_tabs::ChannelPane;
38use super::channel_tabs::ChannelPane;
37use super::chat_members::members_popover;
39use super::chat_members::members_popover;
@@ -51,7 +53,7 @@ use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_t
51use crate::backend::Engine;
53use crate::backend::Engine;
52use crate::card_state::CardScope;
54use crate::card_state::CardScope;
53use crate::channel_files::DownloadSource;
55use crate::channel_files::DownloadSource;
54use crate::data::{existing_one_on_one, is_one_on_one, others};
56use crate::data::{existing_one_on_one, is_one_on_one, one_on_one_bot, others};
55use crate::demo_library::DemoLibrary;
57use crate::demo_library::DemoLibrary;
56use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
58use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
57use crate::emoji;
59use crate::emoji;
@@ -3221,7 +3223,9 @@ impl ConversationView {
3221 let faces = others(chat, me);
3223 let faces = others(chat, me);
3222 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
3224 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
3223 let first = faces.first().cloned().map(face);
3225 let first = faces.first().cloned().map(face);
3224 if is_one_on_one(chat) || faces.len() < 2 {
3226 if let Some(bot) = one_on_one_bot(chat, me) {
3227 lead = Some(bot_tile(directory, &face(bot), 36.));
3228 } else if is_one_on_one(chat) || faces.len() < 2 {
3225 let name = first
3229 let name = first
3226 .as_ref()
3230 .as_ref()
3227 .map_or(current.title.as_str(), |face| face.name.as_str());
3231 .map_or(current.title.as_str(), |face| face.name.as_str());
@@ -3467,12 +3471,19 @@ impl Render for ConversationView {
3467 .gap(px(8.))
3471 .gap(px(8.))
3468 .pt(px(32.))
3472 .pt(px(32.))
3469 .pb(px(16.))
3473 .pb(px(16.))
3470 .child(person_avatar(
3474 .child(match start.user_id.as_deref() {
3471 &state.directory,
3475 Some(user_id) if is_bot_id(user_id) => bot_tile(
3472 start.user_id.as_deref(),
3476 &state.directory,
3473 &start.title,
3477 &Face {
3474 56.,
3478 user_id: Some(user_id.to_owned()),
3475 ))
3479 name: start.title.clone(),
3480 },
3481 56.,
3482 ),
3483 user_id => {
3484 person_avatar(&state.directory, user_id, &start.title, 56.)
3485 }
3486 })
3476 .child(
3487 .child(
3477 div()
3488 div()
3478 .text_size(px(16.))
3489 .text_size(px(16.))
crates/app/src/views/sidebar.rs +2 −1
@@ -491,6 +491,7 @@ fn preview_text(preview: &Preview) -> Option<(String, bool)> {
491 491 match preview {
492 492 Preview::Empty => None,
493 493 Preview::Deleted => Some((DELETED_CHAT_PREVIEW.to_owned(), true)),
494 Preview::Event(text) => Some((text.clone(), true)),
494 495 Preview::Typing(text) => Some((text.clone(), true)),
495 496 Preview::Text {
496 497 prefix: Some(prefix),
@@ -1713,7 +1714,7 @@ fn hidden_channels_label(count: usize) -> String {
1713 1714
1714 1715 fn collect_faces(spec: &AvatarSpec, faces: &mut Vec<String>) {
1715 1716 match spec {
1716 AvatarSpec::Single(face) => faces.extend(face.user_id.clone()),
1717 AvatarSpec::Single(face) | AvatarSpec::Bot(face) => faces.extend(face.user_id.clone()),
1717 1718 AvatarSpec::Pair(first, second) => {
1718 1719 faces.extend(first.user_id.clone());
1719 1720 faces.extend(second.user_id.clone());
@@ -491,6 +491,7 @@ fn preview_text(preview: &Preview) -> Option<(String, bool)> {
491 match preview {
491 match preview {
492 Preview::Empty => None,
492 Preview::Empty => None,
493 Preview::Deleted => Some((DELETED_CHAT_PREVIEW.to_owned(), true)),
493 Preview::Deleted => Some((DELETED_CHAT_PREVIEW.to_owned(), true)),
494 Preview::Event(text) => Some((text.clone(), true)),
494 Preview::Typing(text) => Some((text.clone(), true)),
495 Preview::Typing(text) => Some((text.clone(), true)),
495 Preview::Text {
496 Preview::Text {
496 prefix: Some(prefix),
497 prefix: Some(prefix),
@@ -1713,7 +1714,7 @@ fn hidden_channels_label(count: usize) -> String {
1713
1714
1714fn collect_faces(spec: &AvatarSpec, faces: &mut Vec<String>) {
1715fn collect_faces(spec: &AvatarSpec, faces: &mut Vec<String>) {
1715 match spec {
1716 match spec {
1716 AvatarSpec::Single(face) => faces.extend(face.user_id.clone()),
1717 AvatarSpec::Single(face) | AvatarSpec::Bot(face) => faces.extend(face.user_id.clone()),
1717 AvatarSpec::Pair(first, second) => {
1718 AvatarSpec::Pair(first, second) => {
1718 faces.extend(first.user_id.clone());
1719 faces.extend(first.user_id.clone());
1719 faces.extend(second.user_id.clone());
1720 faces.extend(second.user_id.clone());
crates/chatsvc/src/bot_profiles.rs added +174 −0
@@ -0,0 +1,174 @@
1 use serde_json::{Value, json};
2 use session::{Method, Request, SPACES, Scope, Session};
3
4 use crate::error::Result;
5 use crate::language_settings::with_headers;
6 use crate::messages::ensure_success;
7 use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
9 const SKYPE_SCOPE: &str = "user_impersonation";
10 const BOT_MRI_PREFIX: &str = "28:";
11 const BOT_TYPE: &str = "BOT";
12 const PLACEHOLDER_IMAGE_HOST: &str = "www.contoso.com";
13 const SECURE_SCHEME: &str = "https://";
14 const PROFILE_QUERY: &str = "isMailAddress=false&enableGuest=true&includeIBBarredUsers=true&skypeTeamsInfo=true&includeBots=true";
15
16 #[derive(Debug, Clone, PartialEq, Eq)]
17 pub struct BotProfile {
18 pub bot_id: String,
19 pub display_name: String,
20 pub image_url: Option<String>,
21 }
22
23 pub struct BotProfiles<T: CsaTransport = SessionTransport> {
24 transport: T,
25 url: String,
26 }
27
28 impl BotProfiles<SessionTransport> {
29 pub fn new(session: &Session) -> Self {
30 let transport = SessionTransport::with_scope(session, Scope::new(SPACES, SKYPE_SCOPE));
31 BotProfiles::with_transport(transport, DEFAULT_REGION)
32 }
33 }
34
35 impl<T: CsaTransport> BotProfiles<T> {
36 pub fn with_transport(transport: T, region: &str) -> Self {
37 BotProfiles {
38 transport,
39 url: format!(
40 "https://teams.cloud.microsoft/api/mt/{region}/beta/users/fetchShortProfile?{PROFILE_QUERY}"
41 ),
42 }
43 }
44
45 pub async fn fetch(&self, bot_ids: &[String]) -> Result<Vec<BotProfile>> {
46 if bot_ids.is_empty() {
47 return Ok(Vec::new());
48 }
49 let mris: Vec<Value> = bot_ids
50 .iter()
51 .map(|bot_id| json!(format!("{BOT_MRI_PREFIX}{bot_id}")))
52 .collect();
53 let answer = self
54 .transport
55 .send(with_headers(Request::with_body(
56 Method::Post,
57 self.url.clone(),
58 Value::Array(mris),
59 )))
60 .await?;
61 ensure_success(&answer)?;
62 Ok(parse_bot_profiles(&answer.body))
63 }
64 }
65
66 pub fn parse_bot_profiles(body: &Value) -> Vec<BotProfile> {
67 body.get("value")
68 .and_then(Value::as_array)
69 .map(Vec::as_slice)
70 .unwrap_or_default()
71 .iter()
72 .filter(|profile| profile.get("type").and_then(Value::as_str) == Some(BOT_TYPE))
73 .filter_map(|profile| {
74 let bot_id = profile
75 .get("mri")
76 .and_then(Value::as_str)?
77 .strip_prefix(BOT_MRI_PREFIX)?
78 .to_owned();
79 let display_name = profile
80 .get("displayName")
81 .and_then(Value::as_str)
82 .filter(|name| !name.trim().is_empty())?
83 .to_owned();
84 let image_url = profile
85 .get("imageUri")
86 .and_then(Value::as_str)
87 .filter(|url| is_real_image(url))
88 .map(str::to_owned);
89 Some(BotProfile {
90 bot_id,
91 display_name,
92 image_url,
93 })
94 })
95 .collect()
96 }
97
98 fn is_real_image(url: &str) -> bool {
99 url.strip_prefix(SECURE_SCHEME)
100 .and_then(|rest| rest.split('/').next())
101 .is_some_and(|host| !host.is_empty() && host != PLACEHOLDER_IMAGE_HOST)
102 }
103
104 #[cfg(test)]
105 mod tests {
106 use std::sync::Mutex;
107
108 use session::ApiResponse;
109
110 use super::*;
111
112 struct Canned {
113 body: Value,
114 requests: Mutex<Vec<Request>>,
115 }
116
117 impl CsaTransport for &Canned {
118 async fn send(&self, request: Request) -> Result<ApiResponse> {
119 self.requests.lock().unwrap().push(request);
120 Ok(ApiResponse {
121 status: 200,
122 body: self.body.clone(),
123 retry_after: None,
124 })
125 }
126 }
127
128 fn answer() -> Value {
129 json!({"value": [
130 {"mri": "28:cf28171e", "displayName": "Echo", "type": "BOT", "imageUri": "http://www.contoso.com/"},
131 {"mri": "28:358f0194", "displayName": "Workflows", "type": "BOT",
132 "imageUri": "https://res.cdn.office.net/teamsappdata/workflows_largeimage.png"},
133 {"mri": "8:orgid:user-ada", "displayName": "Ada Example", "type": "ADUser"}
134 ]})
135 }
136
137 #[test]
138 fn bots_keep_their_name_and_only_a_real_icon() {
139 let profiles = parse_bot_profiles(&answer());
140 assert_eq!(
141 profiles,
142 [
143 BotProfile {
144 bot_id: "cf28171e".into(),
145 display_name: "Echo".into(),
146 image_url: None,
147 },
148 BotProfile {
149 bot_id: "358f0194".into(),
150 display_name: "Workflows".into(),
151 image_url: Some(
152 "https://res.cdn.office.net/teamsappdata/workflows_largeimage.png".into()
153 ),
154 },
155 ]
156 );
157 }
158
159 #[tokio::test]
160 async fn the_lookup_posts_bot_mris_to_the_middle_tier() {
161 let canned = Canned {
162 body: answer(),
163 requests: Mutex::new(Vec::new()),
164 };
165 let client = BotProfiles::with_transport(&canned, "emea");
166 let profiles = client.fetch(&["cf28171e".to_owned()]).await.unwrap();
167 assert_eq!(profiles.len(), 2);
168 let requests = canned.requests.lock().unwrap();
169 assert!(requests[0].url.starts_with(
170 "https://teams.cloud.microsoft/api/mt/emea/beta/users/fetchShortProfile?"
171 ));
172 assert_eq!(requests[0].body, Some(json!(["28:cf28171e"])));
173 }
174 }
@@ -0,0 +1,174 @@
1use serde_json::{Value, json};
2use session::{Method, Request, SPACES, Scope, Session};
3
4use crate::error::Result;
5use crate::language_settings::with_headers;
6use crate::messages::ensure_success;
7use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
9const SKYPE_SCOPE: &str = "user_impersonation";
10const BOT_MRI_PREFIX: &str = "28:";
11const BOT_TYPE: &str = "BOT";
12const PLACEHOLDER_IMAGE_HOST: &str = "www.contoso.com";
13const SECURE_SCHEME: &str = "https://";
14const PROFILE_QUERY: &str = "isMailAddress=false&enableGuest=true&includeIBBarredUsers=true&skypeTeamsInfo=true&includeBots=true";
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct BotProfile {
18 pub bot_id: String,
19 pub display_name: String,
20 pub image_url: Option<String>,
21}
22
23pub struct BotProfiles<T: CsaTransport = SessionTransport> {
24 transport: T,
25 url: String,
26}
27
28impl BotProfiles<SessionTransport> {
29 pub fn new(session: &Session) -> Self {
30 let transport = SessionTransport::with_scope(session, Scope::new(SPACES, SKYPE_SCOPE));
31 BotProfiles::with_transport(transport, DEFAULT_REGION)
32 }
33}
34
35impl<T: CsaTransport> BotProfiles<T> {
36 pub fn with_transport(transport: T, region: &str) -> Self {
37 BotProfiles {
38 transport,
39 url: format!(
40 "https://teams.cloud.microsoft/api/mt/{region}/beta/users/fetchShortProfile?{PROFILE_QUERY}"
41 ),
42 }
43 }
44
45 pub async fn fetch(&self, bot_ids: &[String]) -> Result<Vec<BotProfile>> {
46 if bot_ids.is_empty() {
47 return Ok(Vec::new());
48 }
49 let mris: Vec<Value> = bot_ids
50 .iter()
51 .map(|bot_id| json!(format!("{BOT_MRI_PREFIX}{bot_id}")))
52 .collect();
53 let answer = self
54 .transport
55 .send(with_headers(Request::with_body(
56 Method::Post,
57 self.url.clone(),
58 Value::Array(mris),
59 )))
60 .await?;
61 ensure_success(&answer)?;
62 Ok(parse_bot_profiles(&answer.body))
63 }
64}
65
66pub fn parse_bot_profiles(body: &Value) -> Vec<BotProfile> {
67 body.get("value")
68 .and_then(Value::as_array)
69 .map(Vec::as_slice)
70 .unwrap_or_default()
71 .iter()
72 .filter(|profile| profile.get("type").and_then(Value::as_str) == Some(BOT_TYPE))
73 .filter_map(|profile| {
74 let bot_id = profile
75 .get("mri")
76 .and_then(Value::as_str)?
77 .strip_prefix(BOT_MRI_PREFIX)?
78 .to_owned();
79 let display_name = profile
80 .get("displayName")
81 .and_then(Value::as_str)
82 .filter(|name| !name.trim().is_empty())?
83 .to_owned();
84 let image_url = profile
85 .get("imageUri")
86 .and_then(Value::as_str)
87 .filter(|url| is_real_image(url))
88 .map(str::to_owned);
89 Some(BotProfile {
90 bot_id,
91 display_name,
92 image_url,
93 })
94 })
95 .collect()
96}
97
98fn is_real_image(url: &str) -> bool {
99 url.strip_prefix(SECURE_SCHEME)
100 .and_then(|rest| rest.split('/').next())
101 .is_some_and(|host| !host.is_empty() && host != PLACEHOLDER_IMAGE_HOST)
102}
103
104#[cfg(test)]
105mod tests {
106 use std::sync::Mutex;
107
108 use session::ApiResponse;
109
110 use super::*;
111
112 struct Canned {
113 body: Value,
114 requests: Mutex<Vec<Request>>,
115 }
116
117 impl CsaTransport for &Canned {
118 async fn send(&self, request: Request) -> Result<ApiResponse> {
119 self.requests.lock().unwrap().push(request);
120 Ok(ApiResponse {
121 status: 200,
122 body: self.body.clone(),
123 retry_after: None,
124 })
125 }
126 }
127
128 fn answer() -> Value {
129 json!({"value": [
130 {"mri": "28:cf28171e", "displayName": "Echo", "type": "BOT", "imageUri": "http://www.contoso.com/"},
131 {"mri": "28:358f0194", "displayName": "Workflows", "type": "BOT",
132 "imageUri": "https://res.cdn.office.net/teamsappdata/workflows_largeimage.png"},
133 {"mri": "8:orgid:user-ada", "displayName": "Ada Example", "type": "ADUser"}
134 ]})
135 }
136
137 #[test]
138 fn bots_keep_their_name_and_only_a_real_icon() {
139 let profiles = parse_bot_profiles(&answer());
140 assert_eq!(
141 profiles,
142 [
143 BotProfile {
144 bot_id: "cf28171e".into(),
145 display_name: "Echo".into(),
146 image_url: None,
147 },
148 BotProfile {
149 bot_id: "358f0194".into(),
150 display_name: "Workflows".into(),
151 image_url: Some(
152 "https://res.cdn.office.net/teamsappdata/workflows_largeimage.png".into()
153 ),
154 },
155 ]
156 );
157 }
158
159 #[tokio::test]
160 async fn the_lookup_posts_bot_mris_to_the_middle_tier() {
161 let canned = Canned {
162 body: answer(),
163 requests: Mutex::new(Vec::new()),
164 };
165 let client = BotProfiles::with_transport(&canned, "emea");
166 let profiles = client.fetch(&["cf28171e".to_owned()]).await.unwrap();
167 assert_eq!(profiles.len(), 2);
168 let requests = canned.requests.lock().unwrap();
169 assert!(requests[0].url.starts_with(
170 "https://teams.cloud.microsoft/api/mt/emea/beta/users/fetchShortProfile?"
171 ));
172 assert_eq!(requests[0].body, Some(json!(["28:cf28171e"])));
173 }
174}
crates/chatsvc/src/lib.rs +2 −0
@@ -1,3 +1,4 @@
1 pub mod bot_profiles;
1 2 pub mod calendar;
2 3 pub mod calllog;
3 4 pub mod cards;
@@ -29,6 +30,7 @@ pub mod transcripts;
29 30 pub mod translate;
30 31 pub mod window;
31 32
33 pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
32 34 pub use calendar::{
33 35 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
34 36 ResponseType, meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
@@ -1,3 +1,4 @@
1pub mod bot_profiles;
1pub mod calendar;
2pub mod calendar;
2pub mod calllog;
3pub mod calllog;
3pub mod cards;
4pub mod cards;
@@ -29,6 +30,7 @@ pub mod transcripts;
29pub mod translate;
30pub mod translate;
30pub mod window;
31pub mod window;
31
32
33pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
32pub use calendar::{
34pub use calendar::{
33 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
35 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
34 ResponseType, meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
36 ResponseType, meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
crates/core/src/actions.rs +3 −2
@@ -10,7 +10,7 @@ use crate::engine::{Conversation, META_USER_ID, SyncEngine};
10 10 use crate::error::{Error, Result};
11 11 use crate::external_image::external_image_url;
12 12 use crate::links::LinkPreview;
13 use crate::mapping::{chat_record, message_record};
13 use crate::mapping::message_record;
14 14 use crate::markdown::markdown_to_html;
15 15 use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
16 16 use crate::remote::Remote;
@@ -617,7 +617,8 @@ impl<R: Remote> SyncEngine<R> {
617 617 }
618 618
619 619 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
620 self.store.upsert_chats(&[chat_record(chat, my_user_id)])?;
620 self.store
621 .upsert_chats(&[self.partner_chat_record(chat, my_user_id)])?;
621 622 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
622 623 Ok(chat.id.clone())
623 624 }
@@ -10,7 +10,7 @@ use crate::engine::{Conversation, META_USER_ID, SyncEngine};
10use crate::error::{Error, Result};
10use crate::error::{Error, Result};
11use crate::external_image::external_image_url;
11use crate::external_image::external_image_url;
12use crate::links::LinkPreview;
12use crate::links::LinkPreview;
13use crate::mapping::{chat_record, message_record};
13use crate::mapping::message_record;
14use crate::markdown::markdown_to_html;
14use crate::markdown::markdown_to_html;
15use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
15use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
16use crate::remote::Remote;
16use crate::remote::Remote;
@@ -617,7 +617,8 @@ impl<R: Remote> SyncEngine<R> {
617 }
617 }
618
618
619 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
619 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
620 self.store.upsert_chats(&[chat_record(chat, my_user_id)])?;
620 self.store
621 .upsert_chats(&[self.partner_chat_record(chat, my_user_id)])?;
621 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
622 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
622 Ok(chat.id.clone())
623 Ok(chat.id.clone())
623 }
624 }
crates/core/src/avatars.rs +21 −2
@@ -1,5 +1,5 @@
1 1 use chrono::{Duration, Utc};
2 use store::AvatarRecord;
2 use store::{AvatarRecord, is_bot_id};
3 3
4 4 use crate::engine::SyncEngine;
5 5 use crate::error::Result;
@@ -37,9 +37,28 @@ impl<R: Remote> SyncEngine<R> {
37 37 }
38 38
39 39 async fn fetch_claimed_avatars(&self, claimed: &[String]) -> Result<()> {
40 let (bots, people): (Vec<String>, Vec<String>) = claimed
41 .iter()
42 .cloned()
43 .partition(|user_id| is_bot_id(user_id));
40 44 let mut first_error = None;
41 45 let mut fetched_any = false;
42 for chunk in claimed.chunks(AVATAR_BATCH) {
46 if !bots.is_empty() {
47 match self.fetch_bot_icons(&bots).await {
48 Ok(changed) => {
49 fetched_any = true;
50 if !changed.is_empty() {
51 let _ = self
52 .events
53 .send(CoreEvent::AvatarsChanged { user_ids: changed });
54 }
55 }
56 Err(error) => {
57 first_error.get_or_insert(error);
58 }
59 }
60 }
61 for chunk in people.chunks(AVATAR_BATCH) {
43 62 let photos = match self.remote.user_photos(chunk).await {
44 63 Ok(photos) => photos,
45 64 Err(error) => {
@@ -1,5 +1,5 @@
1use chrono::{Duration, Utc};
1use chrono::{Duration, Utc};
2use store::AvatarRecord;
2use store::{AvatarRecord, is_bot_id};
3
3
4use crate::engine::SyncEngine;
4use crate::engine::SyncEngine;
5use crate::error::Result;
5use crate::error::Result;
@@ -37,9 +37,28 @@ impl<R: Remote> SyncEngine<R> {
37 }
37 }
38
38
39 async fn fetch_claimed_avatars(&self, claimed: &[String]) -> Result<()> {
39 async fn fetch_claimed_avatars(&self, claimed: &[String]) -> Result<()> {
40 let (bots, people): (Vec<String>, Vec<String>) = claimed
41 .iter()
42 .cloned()
43 .partition(|user_id| is_bot_id(user_id));
40 let mut first_error = None;
44 let mut first_error = None;
41 let mut fetched_any = false;
45 let mut fetched_any = false;
42 for chunk in claimed.chunks(AVATAR_BATCH) {
46 if !bots.is_empty() {
47 match self.fetch_bot_icons(&bots).await {
48 Ok(changed) => {
49 fetched_any = true;
50 if !changed.is_empty() {
51 let _ = self
52 .events
53 .send(CoreEvent::AvatarsChanged { user_ids: changed });
54 }
55 }
56 Err(error) => {
57 first_error.get_or_insert(error);
58 }
59 }
60 }
61 for chunk in people.chunks(AVATAR_BATCH) {
43 let photos = match self.remote.user_photos(chunk).await {
62 let photos = match self.remote.user_photos(chunk).await {
44 Ok(photos) => photos,
63 Ok(photos) => photos,
45 Err(error) => {
64 Err(error) => {
crates/core/src/bot_partners.rs added +184 −0
@@ -0,0 +1,184 @@
1 use std::collections::HashMap;
2
3 use chatsvc::BotProfile;
4 use chrono::Utc;
5 use graph::Chat;
6 use store::{AvatarRecord, BOT_MRI_PREFIX, ChatRecord, MemberRecord};
7
8 use crate::engine::SyncEngine;
9 use crate::error::{Error, Result};
10 use crate::mapping::chat_record;
11 use crate::remote::Remote;
12
13 /// Bots Graph leaves out of 1:1 chat members, such as the Echo test call bot, by the id in the chat id.
14 #[derive(Default)]
15 pub(crate) struct BotPartners {
16 known: HashMap<String, Option<BotProfile>>,
17 }
18
19 impl BotPartners {
20 pub(crate) fn unknown_ids(&self, chats: &[Chat], my_user_id: &str) -> Vec<String> {
21 let mut unknown: Vec<String> = chats
22 .iter()
23 .filter_map(|chat| chat.memberless_partner_id(my_user_id))
24 .filter(|partner_id| !self.known.contains_key(*partner_id))
25 .map(str::to_owned)
26 .collect();
27 unknown.sort();
28 unknown.dedup();
29 unknown
30 }
31
32 pub(crate) fn remember(&mut self, asked: &[String], profiles: Vec<BotProfile>) {
33 for bot_id in asked {
34 self.known.entry(bot_id.clone()).or_insert(None);
35 }
36 for profile in profiles {
37 self.known.insert(profile.bot_id.clone(), Some(profile));
38 }
39 }
40
41 pub(crate) fn profile(&self, bot_id: &str) -> Option<&BotProfile> {
42 self.known.get(bot_id)?.as_ref()
43 }
44
45 pub(crate) fn chat_record(&self, chat: &Chat, my_user_id: &str) -> ChatRecord {
46 let mut record = chat_record(chat, my_user_id);
47 let partner = chat
48 .memberless_partner_id(my_user_id)
49 .and_then(|partner_id| self.profile(partner_id));
50 if let Some(profile) = partner {
51 record.title = profile.display_name.clone();
52 record.member_summary = profile.display_name.clone();
53 record.members.push(MemberRecord {
54 user_id: Some(format!("{BOT_MRI_PREFIX}{}", profile.bot_id)),
55 display_name: profile.display_name.clone(),
56 });
57 }
58 record
59 }
60 }
61
62 impl<R: Remote> SyncEngine<R> {
63 pub(crate) async fn resolve_bot_partners(&self, chats: &[Chat], my_user_id: &str) {
64 let unknown = self.bot_partners().unknown_ids(chats, my_user_id);
65 self.fetch_bot_profiles(&unknown).await;
66 }
67
68 async fn fetch_bot_profiles(&self, bot_ids: &[String]) {
69 if bot_ids.is_empty() {
70 return;
71 }
72 match self.remote.bot_profiles(bot_ids).await {
73 Ok(profiles) => self.bot_partners().remember(bot_ids, profiles),
74 Err(Error::Unsupported(_)) => self.bot_partners().remember(bot_ids, Vec::new()),
75 Err(error) => self.report(format!("cannot look up bot chats: {error}")),
76 }
77 }
78
79 pub(crate) fn bot_partners(&self) -> std::sync::MutexGuard<'_, BotPartners> {
80 self.bot_partners
81 .lock()
82 .unwrap_or_else(|poisoned| poisoned.into_inner())
83 }
84
85 pub(crate) fn partner_chat_record(&self, chat: &Chat, my_user_id: &str) -> ChatRecord {
86 self.bot_partners().chat_record(chat, my_user_id)
87 }
88
89 pub(crate) async fn fetch_bot_icons(&self, bot_mris: &[String]) -> Result<Vec<String>> {
90 let bot_ids: Vec<String> = bot_mris
91 .iter()
92 .filter_map(|mri| mri.strip_prefix(BOT_MRI_PREFIX))
93 .map(str::to_owned)
94 .collect();
95 let missing: Vec<String> = {
96 let partners = self.bot_partners();
97 bot_ids
98 .iter()
99 .filter(|bot_id| !partners.known.contains_key(*bot_id))
100 .cloned()
101 .collect()
102 };
103 self.fetch_bot_profiles(&missing).await;
104 let mut changed = Vec::new();
105 for bot_id in bot_ids {
106 let image_url = self
107 .bot_partners()
108 .profile(&bot_id)
109 .and_then(|profile| profile.image_url.clone());
110 let photo = match image_url {
111 Some(url) => match self.remote.external_image(&url).await {
112 Ok(photo) => Some(photo),
113 Err(error) => {
114 self.report(format!("cannot load a bot icon: {error}"));
115 continue;
116 }
117 },
118 None => None,
119 };
120 let user_id = format!("{BOT_MRI_PREFIX}{bot_id}");
121 if photo.is_some() {
122 changed.push(user_id.clone());
123 }
124 self.store.upsert_avatar(&AvatarRecord {
125 user_id,
126 content_type: photo
127 .as_ref()
128 .map(|photo| photo.content_type.clone())
129 .unwrap_or_default(),
130 bytes: photo.map(|photo| photo.bytes),
131 fetched_at: Utc::now(),
132 })?;
133 }
134 Ok(changed)
135 }
136 }
137
138 #[cfg(test)]
139 mod tests {
140 use super::*;
141
142 fn echo_chat() -> Chat {
143 serde_json::from_value(serde_json::json!({
144 "id": "19:user-me_bot-echo@unq.gbl.spaces",
145 "chatType": "oneOnOne",
146 "members": [{"userId": "user-me", "displayName": "Test Me"}],
147 }))
148 .unwrap()
149 }
150
151 fn echo_profile() -> BotProfile {
152 BotProfile {
153 bot_id: "bot-echo".into(),
154 display_name: "Echo".into(),
155 image_url: None,
156 }
157 }
158
159 #[test]
160 fn a_resolved_bot_names_the_chat_and_joins_its_members() {
161 let mut partners = BotPartners::default();
162 let chats = [echo_chat()];
163 assert_eq!(partners.unknown_ids(&chats, "user-me"), ["bot-echo"]);
164 partners.remember(&["bot-echo".to_owned()], vec![echo_profile()]);
165 assert!(partners.unknown_ids(&chats, "user-me").is_empty());
166 let record = partners.chat_record(&chats[0], "user-me");
167 assert_eq!(record.title, "Echo");
168 assert_eq!(record.member_summary, "Echo");
169 let bot = record.members.last().unwrap();
170 assert_eq!(bot.user_id.as_deref(), Some("28:bot-echo"));
171 assert!(bot.is_bot());
172 }
173
174 #[test]
175 fn a_partner_that_is_no_bot_is_asked_once_and_keeps_the_graph_title() {
176 let mut partners = BotPartners::default();
177 let chats = [echo_chat()];
178 partners.remember(&["bot-echo".to_owned()], Vec::new());
179 assert!(partners.unknown_ids(&chats, "user-me").is_empty());
180 let record = partners.chat_record(&chats[0], "user-me");
181 assert_eq!(record.title, "(only you)");
182 assert_eq!(record.members.len(), 1);
183 }
184 }
@@ -0,0 +1,184 @@
1use std::collections::HashMap;
2
3use chatsvc::BotProfile;
4use chrono::Utc;
5use graph::Chat;
6use store::{AvatarRecord, BOT_MRI_PREFIX, ChatRecord, MemberRecord};
7
8use crate::engine::SyncEngine;
9use crate::error::{Error, Result};
10use crate::mapping::chat_record;
11use crate::remote::Remote;
12
13/// Bots Graph leaves out of 1:1 chat members, such as the Echo test call bot, by the id in the chat id.
14#[derive(Default)]
15pub(crate) struct BotPartners {
16 known: HashMap<String, Option<BotProfile>>,
17}
18
19impl BotPartners {
20 pub(crate) fn unknown_ids(&self, chats: &[Chat], my_user_id: &str) -> Vec<String> {
21 let mut unknown: Vec<String> = chats
22 .iter()
23 .filter_map(|chat| chat.memberless_partner_id(my_user_id))
24 .filter(|partner_id| !self.known.contains_key(*partner_id))
25 .map(str::to_owned)
26 .collect();
27 unknown.sort();
28 unknown.dedup();
29 unknown
30 }
31
32 pub(crate) fn remember(&mut self, asked: &[String], profiles: Vec<BotProfile>) {
33 for bot_id in asked {
34 self.known.entry(bot_id.clone()).or_insert(None);
35 }
36 for profile in profiles {
37 self.known.insert(profile.bot_id.clone(), Some(profile));
38 }
39 }
40
41 pub(crate) fn profile(&self, bot_id: &str) -> Option<&BotProfile> {
42 self.known.get(bot_id)?.as_ref()
43 }
44
45 pub(crate) fn chat_record(&self, chat: &Chat, my_user_id: &str) -> ChatRecord {
46 let mut record = chat_record(chat, my_user_id);
47 let partner = chat
48 .memberless_partner_id(my_user_id)
49 .and_then(|partner_id| self.profile(partner_id));
50 if let Some(profile) = partner {
51 record.title = profile.display_name.clone();
52 record.member_summary = profile.display_name.clone();
53 record.members.push(MemberRecord {
54 user_id: Some(format!("{BOT_MRI_PREFIX}{}", profile.bot_id)),
55 display_name: profile.display_name.clone(),
56 });
57 }
58 record
59 }
60}
61
62impl<R: Remote> SyncEngine<R> {
63 pub(crate) async fn resolve_bot_partners(&self, chats: &[Chat], my_user_id: &str) {
64 let unknown = self.bot_partners().unknown_ids(chats, my_user_id);
65 self.fetch_bot_profiles(&unknown).await;
66 }
67
68 async fn fetch_bot_profiles(&self, bot_ids: &[String]) {
69 if bot_ids.is_empty() {
70 return;
71 }
72 match self.remote.bot_profiles(bot_ids).await {
73 Ok(profiles) => self.bot_partners().remember(bot_ids, profiles),
74 Err(Error::Unsupported(_)) => self.bot_partners().remember(bot_ids, Vec::new()),
75 Err(error) => self.report(format!("cannot look up bot chats: {error}")),
76 }
77 }
78
79 pub(crate) fn bot_partners(&self) -> std::sync::MutexGuard<'_, BotPartners> {
80 self.bot_partners
81 .lock()
82 .unwrap_or_else(|poisoned| poisoned.into_inner())
83 }
84
85 pub(crate) fn partner_chat_record(&self, chat: &Chat, my_user_id: &str) -> ChatRecord {
86 self.bot_partners().chat_record(chat, my_user_id)
87 }
88
89 pub(crate) async fn fetch_bot_icons(&self, bot_mris: &[String]) -> Result<Vec<String>> {
90 let bot_ids: Vec<String> = bot_mris
91 .iter()
92 .filter_map(|mri| mri.strip_prefix(BOT_MRI_PREFIX))
93 .map(str::to_owned)
94 .collect();
95 let missing: Vec<String> = {
96 let partners = self.bot_partners();
97 bot_ids
98 .iter()
99 .filter(|bot_id| !partners.known.contains_key(*bot_id))
100 .cloned()
101 .collect()
102 };
103 self.fetch_bot_profiles(&missing).await;
104 let mut changed = Vec::new();
105 for bot_id in bot_ids {
106 let image_url = self
107 .bot_partners()
108 .profile(&bot_id)
109 .and_then(|profile| profile.image_url.clone());
110 let photo = match image_url {
111 Some(url) => match self.remote.external_image(&url).await {
112 Ok(photo) => Some(photo),
113 Err(error) => {
114 self.report(format!("cannot load a bot icon: {error}"));
115 continue;
116 }
117 },
118 None => None,
119 };
120 let user_id = format!("{BOT_MRI_PREFIX}{bot_id}");
121 if photo.is_some() {
122 changed.push(user_id.clone());
123 }
124 self.store.upsert_avatar(&AvatarRecord {
125 user_id,
126 content_type: photo
127 .as_ref()
128 .map(|photo| photo.content_type.clone())
129 .unwrap_or_default(),
130 bytes: photo.map(|photo| photo.bytes),
131 fetched_at: Utc::now(),
132 })?;
133 }
134 Ok(changed)
135 }
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141
142 fn echo_chat() -> Chat {
143 serde_json::from_value(serde_json::json!({
144 "id": "19:user-me_bot-echo@unq.gbl.spaces",
145 "chatType": "oneOnOne",
146 "members": [{"userId": "user-me", "displayName": "Test Me"}],
147 }))
148 .unwrap()
149 }
150
151 fn echo_profile() -> BotProfile {
152 BotProfile {
153 bot_id: "bot-echo".into(),
154 display_name: "Echo".into(),
155 image_url: None,
156 }
157 }
158
159 #[test]
160 fn a_resolved_bot_names_the_chat_and_joins_its_members() {
161 let mut partners = BotPartners::default();
162 let chats = [echo_chat()];
163 assert_eq!(partners.unknown_ids(&chats, "user-me"), ["bot-echo"]);
164 partners.remember(&["bot-echo".to_owned()], vec![echo_profile()]);
165 assert!(partners.unknown_ids(&chats, "user-me").is_empty());
166 let record = partners.chat_record(&chats[0], "user-me");
167 assert_eq!(record.title, "Echo");
168 assert_eq!(record.member_summary, "Echo");
169 let bot = record.members.last().unwrap();
170 assert_eq!(bot.user_id.as_deref(), Some("28:bot-echo"));
171 assert!(bot.is_bot());
172 }
173
174 #[test]
175 fn a_partner_that_is_no_bot_is_asked_once_and_keeps_the_graph_title() {
176 let mut partners = BotPartners::default();
177 let chats = [echo_chat()];
178 partners.remember(&["bot-echo".to_owned()], Vec::new());
179 assert!(partners.unknown_ids(&chats, "user-me").is_empty());
180 let record = partners.chat_record(&chats[0], "user-me");
181 assert_eq!(record.title, "(only you)");
182 assert_eq!(record.members.len(), 1);
183 }
184}
crates/core/src/call_event.rs +6 −0
@@ -25,6 +25,12 @@ pub enum CallPhase {
25 25 TranscriptStarted,
26 26 }
27 27
28 impl CallPhase {
29 pub fn is_call(self) -> bool {
30 matches!(self, CallPhase::Started | CallPhase::Ended)
31 }
32 }
33
28 34 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29 35 pub enum CallType {
30 36 Call,
@@ -25,6 +25,12 @@ pub enum CallPhase {
25 TranscriptStarted,
25 TranscriptStarted,
26}
26}
27
27
28impl CallPhase {
29 pub fn is_call(self) -> bool {
30 matches!(self, CallPhase::Started | CallPhase::Ended)
31 }
32}
33
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29pub enum CallType {
35pub enum CallType {
30 Call,
36 Call,
crates/core/src/engine.rs +7 −3
@@ -13,7 +13,7 @@ use crate::error::{Error, Result};
13 13 use crate::events::CoreEvent;
14 14 use crate::folders::FolderSource;
15 15 use crate::links::{LinkPreview, has_stored_links};
16 use crate::mapping::{chat_record, flatten_thread, message_record};
16 use crate::mapping::{flatten_thread, message_record};
17 17 use crate::people::DirectoryCache;
18 18 use crate::presence::Presence;
19 19 use crate::preview::OwnedPreview;
@@ -132,6 +132,7 @@ pub struct SyncEngine<R: Remote = Graph> {
132 132 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
133 133 pub(crate) chat_paging: Mutex<ChatPaging>,
134 134 pub(crate) locally_hidden_lock: Mutex<()>,
135 pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,
135 136 }
136 137
137 138 impl<R: Remote> SyncEngine<R> {
@@ -167,6 +168,7 @@ impl<R: Remote> SyncEngine<R> {
167 168 chat_states: Mutex::new(HashMap::new()),
168 169 chat_paging,
169 170 locally_hidden_lock: Mutex::new(()),
171 bot_partners: Mutex::default(),
170 172 }
171 173 }
172 174
@@ -356,8 +358,10 @@ impl<R: Remote> SyncEngine<R> {
356 358 Err(error) => return Err(error),
357 359 };
358 360 let my_user_id = self.my_user_id().await?;
361 self.resolve_bot_partners(std::slice::from_ref(&chat), &my_user_id)
362 .await;
359 363 self.store
360 .upsert_chats(&[chat_record(&chat, &my_user_id)])?;
364 .upsert_chats(&[self.partner_chat_record(&chat, &my_user_id)])?;
361 365 let _ = self.events.send(CoreEvent::SidebarChanged);
362 366 Ok(Conversation::Chat)
363 367 }
@@ -495,7 +499,7 @@ impl<R: Remote> SyncEngine<R> {
495 499 pub(crate) fn update_chat_preview(&self, records: &[MessageRecord]) -> Result<()> {
496 500 let Some(newest) = records
497 501 .iter()
498 .filter(|record| record.call_event_json.is_none())
502 .filter(|record| !crate::preview::keeps_previous_line(record))
499 503 .max_by_key(|record| record.created_at)
500 504 else {
501 505 return Ok(());
@@ -13,7 +13,7 @@ use crate::error::{Error, Result};
13use crate::events::CoreEvent;
13use crate::events::CoreEvent;
14use crate::folders::FolderSource;
14use crate::folders::FolderSource;
15use crate::links::{LinkPreview, has_stored_links};
15use crate::links::{LinkPreview, has_stored_links};
16use crate::mapping::{chat_record, flatten_thread, message_record};
16use crate::mapping::{flatten_thread, message_record};
17use crate::people::DirectoryCache;
17use crate::people::DirectoryCache;
18use crate::presence::Presence;
18use crate::presence::Presence;
19use crate::preview::OwnedPreview;
19use crate::preview::OwnedPreview;
@@ -132,6 +132,7 @@ pub struct SyncEngine<R: Remote = Graph> {
132 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
132 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
133 pub(crate) chat_paging: Mutex<ChatPaging>,
133 pub(crate) chat_paging: Mutex<ChatPaging>,
134 pub(crate) locally_hidden_lock: Mutex<()>,
134 pub(crate) locally_hidden_lock: Mutex<()>,
135 pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,
135}
136}
136
137
137impl<R: Remote> SyncEngine<R> {
138impl<R: Remote> SyncEngine<R> {
@@ -167,6 +168,7 @@ impl<R: Remote> SyncEngine<R> {
167 chat_states: Mutex::new(HashMap::new()),
168 chat_states: Mutex::new(HashMap::new()),
168 chat_paging,
169 chat_paging,
169 locally_hidden_lock: Mutex::new(()),
170 locally_hidden_lock: Mutex::new(()),
171 bot_partners: Mutex::default(),
170 }
172 }
171 }
173 }
172
174
@@ -356,8 +358,10 @@ impl<R: Remote> SyncEngine<R> {
356 Err(error) => return Err(error),
358 Err(error) => return Err(error),
357 };
359 };
358 let my_user_id = self.my_user_id().await?;
360 let my_user_id = self.my_user_id().await?;
361 self.resolve_bot_partners(std::slice::from_ref(&chat), &my_user_id)
362 .await;
359 self.store
363 self.store
360 .upsert_chats(&[chat_record(&chat, &my_user_id)])?;
364 .upsert_chats(&[self.partner_chat_record(&chat, &my_user_id)])?;
361 let _ = self.events.send(CoreEvent::SidebarChanged);
365 let _ = self.events.send(CoreEvent::SidebarChanged);
362 Ok(Conversation::Chat)
366 Ok(Conversation::Chat)
363 }
367 }
@@ -495,7 +499,7 @@ impl<R: Remote> SyncEngine<R> {
495 pub(crate) fn update_chat_preview(&self, records: &[MessageRecord]) -> Result<()> {
499 pub(crate) fn update_chat_preview(&self, records: &[MessageRecord]) -> Result<()> {
496 let Some(newest) = records
500 let Some(newest) = records
497 .iter()
501 .iter()
498 .filter(|record| record.call_event_json.is_none())
502 .filter(|record| !crate::preview::keeps_previous_line(record))
499 .max_by_key(|record| record.created_at)
503 .max_by_key(|record| record.created_at)
500 else {
504 else {
501 return Ok(());
505 return Ok(());
crates/core/src/lib.rs +2 −1
@@ -1,6 +1,7 @@
1 1 mod actions;
2 2 mod adaptive_card;
3 3 mod avatars;
4 mod bot_partners;
4 5 mod call_event;
5 6 mod card_actions;
6 7 mod card_chart;
@@ -135,7 +136,7 @@ pub use message_link::{
135 136 pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
136 137 pub use people::{MentionCandidate, PersonCandidate, PersonSource};
137 138 pub use presence::{Activity, Availability, Presence};
138 pub use preview::preview_text;
139 pub use preview::{is_event_preview, preview_text};
139 140 pub use profile::{OrgPerson, PersonProfile};
140 141 pub use receipts::{ReceiptReader, ReceiptState};
141 142 pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
@@ -1,6 +1,7 @@
1mod actions;
1mod actions;
2mod adaptive_card;
2mod adaptive_card;
3mod avatars;
3mod avatars;
4mod bot_partners;
4mod call_event;
5mod call_event;
5mod card_actions;
6mod card_actions;
6mod card_chart;
7mod card_chart;
@@ -135,7 +136,7 @@ pub use message_link::{
135pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
136pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
136pub use people::{MentionCandidate, PersonCandidate, PersonSource};
137pub use people::{MentionCandidate, PersonCandidate, PersonSource};
137pub use presence::{Activity, Availability, Presence};
138pub use presence::{Activity, Availability, Presence};
138pub use preview::preview_text;
139pub use preview::{is_event_preview, preview_text};
139pub use profile::{OrgPerson, PersonProfile};
140pub use profile::{OrgPerson, PersonProfile};
140pub use receipts::{ReceiptReader, ReceiptState};
141pub use receipts::{ReceiptReader, ReceiptState};
141pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
142pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
crates/core/src/preview.rs +84 −11
@@ -2,7 +2,7 @@ use graph::Message;
2 2 use serde_json::Value;
3 3 use store::{ChatPreview, MessageRecord};
4 4
5 use crate::call_event::CallEvent;
5 use crate::call_event::{CallEvent, CallPhase, call_event};
6 6 use crate::external_image::is_giphy_url;
7 7 use crate::forwarded::FORWARDED_CONTENT_TYPE;
8 8 use crate::spans::{Span, html_to_spans};
@@ -24,6 +24,14 @@ pub const RECORDING_READY_PREVIEW: &str = "Recording is ready";
24 24 pub const TRANSCRIPT_PREVIEW: &str = "Transcript is available";
25 25 pub const USER_ADDED_PREVIEW: &str = "User added";
26 26 pub const USER_JOINED_PREVIEW: &str = "User joined";
27 const EVENT_PREVIEWS: [&str; 6] = [
28 RECORDING_STARTED_PREVIEW,
29 RECORDING_STOPPED_PREVIEW,
30 RECORDING_READY_PREVIEW,
31 TRANSCRIPT_PREVIEW,
32 USER_ADDED_PREVIEW,
33 USER_JOINED_PREVIEW,
34 ];
27 35
28 36 const AUDIO_CARD_TYPE: &str = "application/vnd.microsoft.card.audio";
29 37 const LOOP_CARD_TYPE: &str = "application/vnd.microsoft.card.fluidEmbedCard";
@@ -47,6 +55,10 @@ pub fn preview_text(html: &str) -> Option<String> {
47 55 collapse(&parts.text)
48 56 }
49 57
58 pub fn is_event_preview(text: &str) -> bool {
59 EVENT_PREVIEWS.contains(&text)
60 }
61
50 62 /// The chat list line for a message, with the Teams labels for bodies without text.
51 63 pub fn message_preview(html: &str, attachments: &[AttachmentInfo]) -> Option<String> {
52 64 if html.contains("<video") {
@@ -159,6 +171,21 @@ fn system_event_preview(detail: &Value) -> Option<&'static str> {
159 171 }
160 172 }
161 173
174 fn call_phase_preview(phase: CallPhase) -> Option<&'static str> {
175 match phase {
176 CallPhase::RecordingStarted => Some(RECORDING_STARTED_PREVIEW),
177 CallPhase::RecordingStopped => Some(RECORDING_STOPPED_PREVIEW),
178 CallPhase::RecordingSaved => Some(RECORDING_READY_PREVIEW),
179 CallPhase::TranscriptStarted => Some(TRANSCRIPT_PREVIEW),
180 CallPhase::Started | CallPhase::Ended => None,
181 }
182 }
183
184 /// Teams leaves call start and end out of the chat list line; recordings and transcripts stay in it.
185 pub(crate) fn keeps_previous_line(record: &MessageRecord) -> bool {
186 call_event(record).is_some_and(|event| event.phase.is_call())
187 }
188
162 189 fn added_only_self(detail: &Value) -> bool {
163 190 let Some(initiator) = detail.pointer("/initiator/user/id").and_then(Value::as_str) else {
164 191 return false;
@@ -191,7 +218,9 @@ impl OwnedPreview {
191 218 .is_none_or(|kind| kind == "message");
192 219 let deleted = message.is_deleted();
193 220 let detail = message.event_detail.as_ref().filter(|_| !regular);
194 let call = detail.and_then(CallEvent::from_graph).is_some();
221 let call = detail
222 .and_then(CallEvent::from_graph)
223 .is_some_and(|event| event.phase.is_call());
195 224 let text = if deleted {
196 225 None
197 226 } else if regular {
@@ -219,17 +248,22 @@ impl OwnedPreview {
219 248 }
220 249
221 250 pub(crate) fn from_record(record: &MessageRecord) -> Self {
251 let event = call_event(record);
252 let text = if record.deleted {
253 None
254 } else if let Some(event) = &event {
255 call_phase_preview(event.phase).map(str::to_owned)
256 } else {
257 message_preview(&record.body_html, &attachments(record))
258 };
259 let sender = event.is_none();
222 260 OwnedPreview {
223 text: if record.deleted {
224 None
225 } else {
226 message_preview(&record.body_html, &attachments(record))
227 },
228 sender_id: record.sender_id.clone(),
229 sender_name: record.sender_name.clone(),
261 text,
262 sender_id: record.sender_id.clone().filter(|_| sender),
263 sender_name: record.sender_name.clone().filter(|_| sender),
230 264 deleted: record.deleted,
231 system: false,
232 call: record.call_event_json.is_some(),
265 system: event.is_some(),
266 call: event.is_some_and(|event| event.phase.is_call()),
233 267 }
234 268 }
235 269
@@ -383,6 +417,8 @@ mod tests {
383 417 };
384 418 let ready = event(serde_json::json!({
385 419 "@odata.type": RECORDING_TYPE,
420 "callId": "a64b5e71",
421 "callRecordingDisplayName": "Call with Echo-20261015_120906-Meeting Recording.mp4",
386 422 "callRecordingStatus": "success",
387 423 }));
388 424 assert_eq!(ready.text.as_deref(), Some(RECORDING_READY_PREVIEW));
@@ -460,4 +496,41 @@ mod tests {
460 496 assert_eq!(preview.text.as_deref(), Some(IMAGE_PREVIEW));
461 497 assert_eq!(preview.sender_name.as_deref(), Some("Lukas Berg"));
462 498 }
499
500 fn call_record(phase: &str) -> MessageRecord {
501 MessageRecord {
502 conversation_id: "19:chat".into(),
503 message_id: "1".into(),
504 sender_id: Some("u1".into()),
505 sender_name: Some("Ada Lovelace".into()),
506 call_event_json: Some(
507 serde_json::json!({
508 "phase": phase,
509 "call_type": "Call",
510 "call_id": "c1",
511 "duration_seconds": null,
512 "initiator_id": null,
513 "initiator_name": null,
514 "participant_ids": [],
515 })
516 .to_string(),
517 ),
518 ..Default::default()
519 }
520 }
521
522 #[test]
523 fn stored_recordings_fill_the_line_and_calls_keep_the_previous_one() {
524 let saved = call_record("RecordingSaved");
525 assert!(!keeps_previous_line(&saved));
526 let preview = OwnedPreview::from_record(&saved);
527 assert_eq!(preview.text.as_deref(), Some(RECORDING_READY_PREVIEW));
528 assert_eq!(preview.sender_name, None);
529 assert!(!preview.call);
530 let transcript = OwnedPreview::from_record(&call_record("TranscriptStarted"));
531 assert_eq!(transcript.text.as_deref(), Some(TRANSCRIPT_PREVIEW));
532 let ended = call_record("Ended");
533 assert!(keeps_previous_line(&ended));
534 assert!(OwnedPreview::from_record(&ended).call);
535 }
463 536 }
@@ -2,7 +2,7 @@ use graph::Message;
2use serde_json::Value;
2use serde_json::Value;
3use store::{ChatPreview, MessageRecord};
3use store::{ChatPreview, MessageRecord};
4
4
5use crate::call_event::CallEvent;
5use crate::call_event::{CallEvent, CallPhase, call_event};
6use crate::external_image::is_giphy_url;
6use crate::external_image::is_giphy_url;
7use crate::forwarded::FORWARDED_CONTENT_TYPE;
7use crate::forwarded::FORWARDED_CONTENT_TYPE;
8use crate::spans::{Span, html_to_spans};
8use crate::spans::{Span, html_to_spans};
@@ -24,6 +24,14 @@ pub const RECORDING_READY_PREVIEW: &str = "Recording is ready";
24pub const TRANSCRIPT_PREVIEW: &str = "Transcript is available";
24pub const TRANSCRIPT_PREVIEW: &str = "Transcript is available";
25pub const USER_ADDED_PREVIEW: &str = "User added";
25pub const USER_ADDED_PREVIEW: &str = "User added";
26pub const USER_JOINED_PREVIEW: &str = "User joined";
26pub const USER_JOINED_PREVIEW: &str = "User joined";
27const EVENT_PREVIEWS: [&str; 6] = [
28 RECORDING_STARTED_PREVIEW,
29 RECORDING_STOPPED_PREVIEW,
30 RECORDING_READY_PREVIEW,
31 TRANSCRIPT_PREVIEW,
32 USER_ADDED_PREVIEW,
33 USER_JOINED_PREVIEW,
34];
27
35
28const AUDIO_CARD_TYPE: &str = "application/vnd.microsoft.card.audio";
36const AUDIO_CARD_TYPE: &str = "application/vnd.microsoft.card.audio";
29const LOOP_CARD_TYPE: &str = "application/vnd.microsoft.card.fluidEmbedCard";
37const LOOP_CARD_TYPE: &str = "application/vnd.microsoft.card.fluidEmbedCard";
@@ -47,6 +55,10 @@ pub fn preview_text(html: &str) -> Option<String> {
47 collapse(&parts.text)
55 collapse(&parts.text)
48}
56}
49
57
58pub fn is_event_preview(text: &str) -> bool {
59 EVENT_PREVIEWS.contains(&text)
60}
61
50/// The chat list line for a message, with the Teams labels for bodies without text.
62/// The chat list line for a message, with the Teams labels for bodies without text.
51pub fn message_preview(html: &str, attachments: &[AttachmentInfo]) -> Option<String> {
63pub fn message_preview(html: &str, attachments: &[AttachmentInfo]) -> Option<String> {
52 if html.contains("<video") {
64 if html.contains("<video") {
@@ -159,6 +171,21 @@ fn system_event_preview(detail: &Value) -> Option<&'static str> {
159 }
171 }
160}
172}
161
173
174fn call_phase_preview(phase: CallPhase) -> Option<&'static str> {
175 match phase {
176 CallPhase::RecordingStarted => Some(RECORDING_STARTED_PREVIEW),
177 CallPhase::RecordingStopped => Some(RECORDING_STOPPED_PREVIEW),
178 CallPhase::RecordingSaved => Some(RECORDING_READY_PREVIEW),
179 CallPhase::TranscriptStarted => Some(TRANSCRIPT_PREVIEW),
180 CallPhase::Started | CallPhase::Ended => None,
181 }
182}
183
184/// Teams leaves call start and end out of the chat list line; recordings and transcripts stay in it.
185pub(crate) fn keeps_previous_line(record: &MessageRecord) -> bool {
186 call_event(record).is_some_and(|event| event.phase.is_call())
187}
188
162fn added_only_self(detail: &Value) -> bool {
189fn added_only_self(detail: &Value) -> bool {
163 let Some(initiator) = detail.pointer("/initiator/user/id").and_then(Value::as_str) else {
190 let Some(initiator) = detail.pointer("/initiator/user/id").and_then(Value::as_str) else {
164 return false;
191 return false;
@@ -191,7 +218,9 @@ impl OwnedPreview {
191 .is_none_or(|kind| kind == "message");
218 .is_none_or(|kind| kind == "message");
192 let deleted = message.is_deleted();
219 let deleted = message.is_deleted();
193 let detail = message.event_detail.as_ref().filter(|_| !regular);
220 let detail = message.event_detail.as_ref().filter(|_| !regular);
194 let call = detail.and_then(CallEvent::from_graph).is_some();
221 let call = detail
222 .and_then(CallEvent::from_graph)
223 .is_some_and(|event| event.phase.is_call());
195 let text = if deleted {
224 let text = if deleted {
196 None
225 None
197 } else if regular {
226 } else if regular {
@@ -219,17 +248,22 @@ impl OwnedPreview {
219 }
248 }
220
249
221 pub(crate) fn from_record(record: &MessageRecord) -> Self {
250 pub(crate) fn from_record(record: &MessageRecord) -> Self {
251 let event = call_event(record);
252 let text = if record.deleted {
253 None
254 } else if let Some(event) = &event {
255 call_phase_preview(event.phase).map(str::to_owned)
256 } else {
257 message_preview(&record.body_html, &attachments(record))
258 };
259 let sender = event.is_none();
222 OwnedPreview {
260 OwnedPreview {
223 text: if record.deleted {
261 text,
224 None
262 sender_id: record.sender_id.clone().filter(|_| sender),
225 } else {
263 sender_name: record.sender_name.clone().filter(|_| sender),
226 message_preview(&record.body_html, &attachments(record))
227 },
228 sender_id: record.sender_id.clone(),
229 sender_name: record.sender_name.clone(),
230 deleted: record.deleted,
264 deleted: record.deleted,
231 system: false,
265 system: event.is_some(),
232 call: record.call_event_json.is_some(),
266 call: event.is_some_and(|event| event.phase.is_call()),
233 }
267 }
234 }
268 }
235
269
@@ -383,6 +417,8 @@ mod tests {
383 };
417 };
384 let ready = event(serde_json::json!({
418 let ready = event(serde_json::json!({
385 "@odata.type": RECORDING_TYPE,
419 "@odata.type": RECORDING_TYPE,
420 "callId": "a64b5e71",
421 "callRecordingDisplayName": "Call with Echo-20261015_120906-Meeting Recording.mp4",
386 "callRecordingStatus": "success",
422 "callRecordingStatus": "success",
387 }));
423 }));
388 assert_eq!(ready.text.as_deref(), Some(RECORDING_READY_PREVIEW));
424 assert_eq!(ready.text.as_deref(), Some(RECORDING_READY_PREVIEW));
@@ -460,4 +496,41 @@ mod tests {
460 assert_eq!(preview.text.as_deref(), Some(IMAGE_PREVIEW));
496 assert_eq!(preview.text.as_deref(), Some(IMAGE_PREVIEW));
461 assert_eq!(preview.sender_name.as_deref(), Some("Lukas Berg"));
497 assert_eq!(preview.sender_name.as_deref(), Some("Lukas Berg"));
462 }
498 }
499
500 fn call_record(phase: &str) -> MessageRecord {
501 MessageRecord {
502 conversation_id: "19:chat".into(),
503 message_id: "1".into(),
504 sender_id: Some("u1".into()),
505 sender_name: Some("Ada Lovelace".into()),
506 call_event_json: Some(
507 serde_json::json!({
508 "phase": phase,
509 "call_type": "Call",
510 "call_id": "c1",
511 "duration_seconds": null,
512 "initiator_id": null,
513 "initiator_name": null,
514 "participant_ids": [],
515 })
516 .to_string(),
517 ),
518 ..Default::default()
519 }
520 }
521
522 #[test]
523 fn stored_recordings_fill_the_line_and_calls_keep_the_previous_one() {
524 let saved = call_record("RecordingSaved");
525 assert!(!keeps_previous_line(&saved));
526 let preview = OwnedPreview::from_record(&saved);
527 assert_eq!(preview.text.as_deref(), Some(RECORDING_READY_PREVIEW));
528 assert_eq!(preview.sender_name, None);
529 assert!(!preview.call);
530 let transcript = OwnedPreview::from_record(&call_record("TranscriptStarted"));
531 assert_eq!(transcript.text.as_deref(), Some(TRANSCRIPT_PREVIEW));
532 let ended = call_record("Ended");
533 assert!(keeps_previous_line(&ended));
534 assert!(OwnedPreview::from_record(&ended).call);
535 }
463}
536}
crates/core/src/remote.rs +10 −1
@@ -1,5 +1,6 @@
1 1 use chatsvc::{
2 CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState, Conversations,
2 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState,
3 Conversations,
3 4 ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,
4 5 LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,
5 6 MessageEmotions, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus,
@@ -241,6 +242,10 @@ pub trait Remote {
241 242 Err(Error::Unsupported("profile cards"))
242 243 }
243 244
245 async fn bot_profiles(&self, _bot_ids: &[String]) -> Result<Vec<BotProfile>> {
246 Err(Error::Unsupported("bot profiles"))
247 }
248
244 249 async fn subscribe_presence(
245 250 &self,
246 251 _endpoint_id: &str,
@@ -848,6 +853,10 @@ impl Remote for Graph {
848 853 crate::profile::load_profile(self, user_id).await
849 854 }
850 855
856 async fn bot_profiles(&self, bot_ids: &[String]) -> Result<Vec<BotProfile>> {
857 Ok(BotProfiles::new(self.session()).fetch(bot_ids).await?)
858 }
859
851 860 async fn subscribe_presence(
852 861 &self,
853 862 endpoint_id: &str,
@@ -1,5 +1,6 @@
1use chatsvc::{
1use chatsvc::{
2 CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState, Conversations,
2 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState,
3 Conversations,
3 ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,
4 ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,
4 LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,
5 LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,
5 MessageEmotions, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus,
6 MessageEmotions, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus,
@@ -241,6 +242,10 @@ pub trait Remote {
241 Err(Error::Unsupported("profile cards"))
242 Err(Error::Unsupported("profile cards"))
242 }
243 }
243
244
245 async fn bot_profiles(&self, _bot_ids: &[String]) -> Result<Vec<BotProfile>> {
246 Err(Error::Unsupported("bot profiles"))
247 }
248
244 async fn subscribe_presence(
249 async fn subscribe_presence(
245 &self,
250 &self,
246 _endpoint_id: &str,
251 _endpoint_id: &str,
@@ -848,6 +853,10 @@ impl Remote for Graph {
848 crate::profile::load_profile(self, user_id).await
853 crate::profile::load_profile(self, user_id).await
849 }
854 }
850
855
856 async fn bot_profiles(&self, bot_ids: &[String]) -> Result<Vec<BotProfile>> {
857 Ok(BotProfiles::new(self.session()).fetch(bot_ids).await?)
858 }
859
851 async fn subscribe_presence(
860 async fn subscribe_presence(
852 &self,
861 &self,
853 endpoint_id: &str,
862 endpoint_id: &str,
crates/core/src/sidebar_sync.rs +7 −2
@@ -4,12 +4,13 @@ use chatsvc::ConversationState;
4 4 use chrono::{DateTime, Duration, Utc};
5 5 use store::{ChatRecord, Store};
6 6
7 use crate::bot_partners::BotPartners;
7 8 use crate::chat_paging::ChatPaging;
8 9 use crate::engine::{SidebarSummary, SyncEngine};
9 10 use crate::error::Result;
10 11 use crate::events::CoreEvent;
11 12 use crate::hidden_chats::{LocallyHidden, resolve_hidden};
12 use crate::mapping::{channel_record, chat_record, team_record};
13 use crate::mapping::{channel_record, team_record};
13 14 use crate::remote::{ChatsPage, Remote};
14 15
15 16 const META_CHATS_FULL_AT: &str = "chats_full_refreshed_at";
@@ -72,6 +73,7 @@ impl<R: Remote> SyncEngine<R> {
72 73 self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
73 74 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
74 75 loop {
76 self.resolve_bot_partners(&page.items, &my_user_id).await;
75 77 refresh.pages += 1;
76 78 refresh.fetched += page.items.len();
77 79 let (records, hidden) = self.split_page(&page, &my_user_id)?;
@@ -209,6 +211,7 @@ impl<R: Remote> SyncEngine<R> {
209 211 self.refresh_chat_states().await;
210 212 }
211 213 let page = self.remote.chats_at(link).await?;
214 self.resolve_bot_partners(&page.items, &my_user_id).await;
212 215 Ok((my_user_id, page))
213 216 }
214 217
@@ -267,6 +270,7 @@ impl<R: Remote> SyncEngine<R> {
267 270 page,
268 271 my_user_id,
269 272 &self.chat_states.lock().unwrap(),
273 &self.bot_partners(),
270 274 locally,
271 275 now,
272 276 )
@@ -348,6 +352,7 @@ fn split_hidden(
348 352 page: &ChatsPage,
349 353 my_user_id: &str,
350 354 states: &HashMap<String, ConversationState>,
355 partners: &BotPartners,
351 356 locally: &mut LocallyHidden,
352 357 now: DateTime<Utc>,
353 358 ) -> (Vec<ChatRecord>, Vec<String>) {
@@ -357,7 +362,7 @@ fn split_hidden(
357 362 if resolve_hidden(chat, states, locally, now) {
358 363 hidden.push(chat.id.clone());
359 364 } else {
360 records.push(chat_record(chat, my_user_id));
365 records.push(partners.chat_record(chat, my_user_id));
361 366 }
362 367 }
363 368 (records, hidden)
@@ -4,12 +4,13 @@ use chatsvc::ConversationState;
4use chrono::{DateTime, Duration, Utc};
4use chrono::{DateTime, Duration, Utc};
5use store::{ChatRecord, Store};
5use store::{ChatRecord, Store};
6
6
7use crate::bot_partners::BotPartners;
7use crate::chat_paging::ChatPaging;
8use crate::chat_paging::ChatPaging;
8use crate::engine::{SidebarSummary, SyncEngine};
9use crate::engine::{SidebarSummary, SyncEngine};
9use crate::error::Result;
10use crate::error::Result;
10use crate::events::CoreEvent;
11use crate::events::CoreEvent;
11use crate::hidden_chats::{LocallyHidden, resolve_hidden};
12use crate::hidden_chats::{LocallyHidden, resolve_hidden};
12use crate::mapping::{channel_record, chat_record, team_record};
13use crate::mapping::{channel_record, team_record};
13use crate::remote::{ChatsPage, Remote};
14use crate::remote::{ChatsPage, Remote};
14
15
15const META_CHATS_FULL_AT: &str = "chats_full_refreshed_at";
16const META_CHATS_FULL_AT: &str = "chats_full_refreshed_at";
@@ -72,6 +73,7 @@ impl<R: Remote> SyncEngine<R> {
72 self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
73 self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
73 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
74 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
74 loop {
75 loop {
76 self.resolve_bot_partners(&page.items, &my_user_id).await;
75 refresh.pages += 1;
77 refresh.pages += 1;
76 refresh.fetched += page.items.len();
78 refresh.fetched += page.items.len();
77 let (records, hidden) = self.split_page(&page, &my_user_id)?;
79 let (records, hidden) = self.split_page(&page, &my_user_id)?;
@@ -209,6 +211,7 @@ impl<R: Remote> SyncEngine<R> {
209 self.refresh_chat_states().await;
211 self.refresh_chat_states().await;
210 }
212 }
211 let page = self.remote.chats_at(link).await?;
213 let page = self.remote.chats_at(link).await?;
214 self.resolve_bot_partners(&page.items, &my_user_id).await;
212 Ok((my_user_id, page))
215 Ok((my_user_id, page))
213 }
216 }
214
217
@@ -267,6 +270,7 @@ impl<R: Remote> SyncEngine<R> {
267 page,
270 page,
268 my_user_id,
271 my_user_id,
269 &self.chat_states.lock().unwrap(),
272 &self.chat_states.lock().unwrap(),
273 &self.bot_partners(),
270 locally,
274 locally,
271 now,
275 now,
272 )
276 )
@@ -348,6 +352,7 @@ fn split_hidden(
348 page: &ChatsPage,
352 page: &ChatsPage,
349 my_user_id: &str,
353 my_user_id: &str,
350 states: &HashMap<String, ConversationState>,
354 states: &HashMap<String, ConversationState>,
355 partners: &BotPartners,
351 locally: &mut LocallyHidden,
356 locally: &mut LocallyHidden,
352 now: DateTime<Utc>,
357 now: DateTime<Utc>,
353) -> (Vec<ChatRecord>, Vec<String>) {
358) -> (Vec<ChatRecord>, Vec<String>) {
@@ -357,7 +362,7 @@ fn split_hidden(
357 if resolve_hidden(chat, states, locally, now) {
362 if resolve_hidden(chat, states, locally, now) {
358 hidden.push(chat.id.clone());
363 hidden.push(chat.id.clone());
359 } else {
364 } else {
360 records.push(chat_record(chat, my_user_id));
365 records.push(partners.chat_record(chat, my_user_id));
361 }
366 }
362 }
367 }
363 (records, hidden)
368 (records, hidden)
crates/graph/src/models.rs +23 −0
@@ -177,6 +177,29 @@ impl Chat {
177 177 }
178 178 }
179 179
180 /// The other side of a 1:1 chat that Graph lists without a member, such as a bot, read from the `19:{a}_{b}@unq.gbl.spaces` id.
181 pub fn memberless_partner_id(&self, my_user_id: &str) -> Option<&str> {
182 if !self.chat_type.eq_ignore_ascii_case("oneOnOne")
183 || self
184 .members
185 .iter()
186 .any(|member| member.user_id.as_deref() != Some(my_user_id))
187 {
188 return None;
189 }
190 let pair = self
191 .id
192 .strip_prefix("19:")?
193 .strip_suffix("@unq.gbl.spaces")?;
194 let (first, second) = pair.split_once('_')?;
195 match (first == my_user_id, second == my_user_id) {
196 (true, false) => Some(second),
197 (false, true) => Some(first),
198 _ => None,
199 }
200 .filter(|partner| !partner.is_empty())
201 }
202
180 203 fn preview_sender_name(&self, my_user_id: &str) -> Option<&str> {
181 204 let sender = self.last_message_preview.as_ref()?.from.as_ref()?;
182 205 let application = sender
@@ -177,6 +177,29 @@ impl Chat {
177 }
177 }
178 }
178 }
179
179
180 /// The other side of a 1:1 chat that Graph lists without a member, such as a bot, read from the `19:{a}_{b}@unq.gbl.spaces` id.
181 pub fn memberless_partner_id(&self, my_user_id: &str) -> Option<&str> {
182 if !self.chat_type.eq_ignore_ascii_case("oneOnOne")
183 || self
184 .members
185 .iter()
186 .any(|member| member.user_id.as_deref() != Some(my_user_id))
187 {
188 return None;
189 }
190 let pair = self
191 .id
192 .strip_prefix("19:")?
193 .strip_suffix("@unq.gbl.spaces")?;
194 let (first, second) = pair.split_once('_')?;
195 match (first == my_user_id, second == my_user_id) {
196 (true, false) => Some(second),
197 (false, true) => Some(first),
198 _ => None,
199 }
200 .filter(|partner| !partner.is_empty())
201 }
202
180 fn preview_sender_name(&self, my_user_id: &str) -> Option<&str> {
203 fn preview_sender_name(&self, my_user_id: &str) -> Option<&str> {
181 let sender = self.last_message_preview.as_ref()?.from.as_ref()?;
204 let sender = self.last_message_preview.as_ref()?.from.as_ref()?;
182 let application = sender
205 let application = sender
crates/graph/tests/models.rs +29 −0
@@ -63,6 +63,35 @@ fn chat_with_only_me_stays_a_note_to_self_without_another_sender() {
63 63 assert_eq!(nameless.title("user-me"), "(only you)");
64 64 }
65 65
66 #[test]
67 fn memberless_partner_comes_from_the_one_on_one_chat_id() {
68 let chat = |id: &str, kind: &str, members: Value| -> Chat {
69 serde_json::from_value(serde_json::json!({"id": id, "chatType": kind, "members": members}))
70 .unwrap()
71 };
72 let only_me = serde_json::json!([{"userId": "user-me"}]);
73 let echo = chat(
74 "19:user-me_bot-echo@unq.gbl.spaces",
75 "oneOnOne",
76 only_me.clone(),
77 );
78 assert_eq!(echo.memberless_partner_id("user-me"), Some("bot-echo"));
79 let reversed = chat(
80 "19:bot-echo_user-me@unq.gbl.spaces",
81 "oneOnOne",
82 only_me.clone(),
83 );
84 assert_eq!(reversed.memberless_partner_id("user-me"), Some("bot-echo"));
85 let with_member = chat(
86 "19:user-me_user-ada@unq.gbl.spaces",
87 "oneOnOne",
88 serde_json::json!([{"userId": "user-me"}, {"userId": "user-ada"}]),
89 );
90 assert_eq!(with_member.memberless_partner_id("user-me"), None);
91 let group = chat("19:abc@thread.v2", "group", only_me);
92 assert_eq!(group.memberless_partner_id("user-me"), None);
93 }
94
66 95 #[test]
67 96 fn chat_last_message_time_comes_from_preview() {
68 97 let chats: Vec<Chat> = items("chats.json");
@@ -63,6 +63,35 @@ fn chat_with_only_me_stays_a_note_to_self_without_another_sender() {
63 assert_eq!(nameless.title("user-me"), "(only you)");
63 assert_eq!(nameless.title("user-me"), "(only you)");
64}
64}
65
65
66#[test]
67fn memberless_partner_comes_from_the_one_on_one_chat_id() {
68 let chat = |id: &str, kind: &str, members: Value| -> Chat {
69 serde_json::from_value(serde_json::json!({"id": id, "chatType": kind, "members": members}))
70 .unwrap()
71 };
72 let only_me = serde_json::json!([{"userId": "user-me"}]);
73 let echo = chat(
74 "19:user-me_bot-echo@unq.gbl.spaces",
75 "oneOnOne",
76 only_me.clone(),
77 );
78 assert_eq!(echo.memberless_partner_id("user-me"), Some("bot-echo"));
79 let reversed = chat(
80 "19:bot-echo_user-me@unq.gbl.spaces",
81 "oneOnOne",
82 only_me.clone(),
83 );
84 assert_eq!(reversed.memberless_partner_id("user-me"), Some("bot-echo"));
85 let with_member = chat(
86 "19:user-me_user-ada@unq.gbl.spaces",
87 "oneOnOne",
88 serde_json::json!([{"userId": "user-me"}, {"userId": "user-ada"}]),
89 );
90 assert_eq!(with_member.memberless_partner_id("user-me"), None);
91 let group = chat("19:abc@thread.v2", "group", only_me);
92 assert_eq!(group.memberless_partner_id("user-me"), None);
93}
94
66#[test]
95#[test]
67fn chat_last_message_time_comes_from_preview() {
96fn chat_last_message_time_comes_from_preview() {
68 let chats: Vec<Chat> = items("chats.json");
97 let chats: Vec<Chat> = items("chats.json");
crates/store/src/lib.rs +2 −2
@@ -26,11 +26,11 @@ pub use error::{Error, Result};
26 26 pub use image_files::ImageFileCache;
27 27 pub use models::{
28 28 ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,
29 AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel,
29 AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelNotificationLevel,
30 30 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
31 31 ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
32 32 OutboxRecord, OutboxState, OutboxTarget, RecentScope, SearchHit, Sidebar, SidebarTeam,
33 SyncState, TeamLayoutRecord, TeamRecord,
33 SyncState, TeamLayoutRecord, TeamRecord, is_bot_id,
34 34 };
35 35 pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
36 36 pub use store::{DATA_DIR_NAME, Store, default_database_path};
@@ -26,11 +26,11 @@ pub use error::{Error, Result};
26pub use image_files::ImageFileCache;
26pub use image_files::ImageFileCache;
27pub use models::{
27pub use models::{
28 ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,
28 ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,
29 AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel,
29 AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelNotificationLevel,
30 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
30 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
31 ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
31 ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
32 OutboxRecord, OutboxState, OutboxTarget, RecentScope, SearchHit, Sidebar, SidebarTeam,
32 OutboxRecord, OutboxState, OutboxTarget, RecentScope, SearchHit, Sidebar, SidebarTeam,
33 SyncState, TeamLayoutRecord, TeamRecord,
33 SyncState, TeamLayoutRecord, TeamRecord, is_bot_id,
34};
34};
35pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
35pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
36pub use store::{DATA_DIR_NAME, Store, default_database_path};
36pub use store::{DATA_DIR_NAME, Store, default_database_path};
crates/store/src/models.rs +12 −0
@@ -2,12 +2,24 @@ use std::collections::HashMap;
2 2
3 3 use chrono::{DateTime, Utc};
4 4
5 pub const BOT_MRI_PREFIX: &str = "28:";
6
7 pub fn is_bot_id(user_id: &str) -> bool {
8 user_id.starts_with(BOT_MRI_PREFIX)
9 }
10
5 11 #[derive(Debug, Clone, PartialEq, Default)]
6 12 pub struct MemberRecord {
7 13 pub user_id: Option<String>,
8 14 pub display_name: String,
9 15 }
10 16
17 impl MemberRecord {
18 pub fn is_bot(&self) -> bool {
19 self.user_id.as_deref().is_some_and(is_bot_id)
20 }
21 }
22
11 23 #[derive(Debug, Clone, PartialEq, Default)]
12 24 pub struct ChatRecord {
13 25 pub id: String,
@@ -2,12 +2,24 @@ use std::collections::HashMap;
2
2
3use chrono::{DateTime, Utc};
3use chrono::{DateTime, Utc};
4
4
5pub const BOT_MRI_PREFIX: &str = "28:";
6
7pub fn is_bot_id(user_id: &str) -> bool {
8 user_id.starts_with(BOT_MRI_PREFIX)
9}
10
5#[derive(Debug, Clone, PartialEq, Default)]
11#[derive(Debug, Clone, PartialEq, Default)]
6pub struct MemberRecord {
12pub struct MemberRecord {
7 pub user_id: Option<String>,
13 pub user_id: Option<String>,
8 pub display_name: String,
14 pub display_name: String,
9}
15}
10
16
17impl MemberRecord {
18 pub fn is_bot(&self) -> bool {
19 self.user_id.as_deref().is_some_and(is_bot_id)
20 }
21}
22
11#[derive(Debug, Clone, PartialEq, Default)]
23#[derive(Debug, Clone, PartialEq, Default)]
12pub struct ChatRecord {
24pub struct ChatRecord {
13 pub id: String,
25 pub id: String,