fix(write-path): write chat quote replies like Teams via chatsvc
- chat and 48:notes quote replies go through chatsvc with Teams' blockquote + qtdMsgs instead of Graph replyWithQuote (messageReference attachment) - one property set for chat and channel quote replies: importance, links, mentions, onbehalfof, files, qtdMsgs, formatVariant TEAMS; no empty subject - mention itemid as string, channel mentions in the chatsvc shape; team mentions, images, files and uncached quotes stay on Graph - bot senders are quoted with their 28: MRI - clientmessageid in Teams' 19-digit shape (shared with drafts), amsreferences [] - mcp test: set channel unread through apply_channel_read_states (upsert_channels keeps the read state on purpose) - write_shape_probe example: read-only shape dump of 48:notes for the live check - plain chat/channel sends and thread replies stay on Graph (no difference for recipients) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -7,13 +7,13 @@ use session::{ApiResponse, Method, Request, Session};
7
7
use crate::error::Result;
8
8
use crate::messages::{
9
9
DEFAULT_RETRY_DELAY, MessageTransport, SessionMessageTransport, encode, ensure_success,
10
new_client_message_id,
10
11
};
11
12
use crate::pins::DEFAULT_REGION;
12
13
13
14
const SCHEDULED_DRAFT: &str = "ScheduledDraft";
14
15
const NOT_FOUND_RETRIES: u32 = 3;
15
16
const BACKOFF_FACTOR: u32 = 3;
16
const CLIENT_MESSAGE_ID_LENGTH: usize = 19;
17
17
const LIST_PAGE_SIZE: u32 = 200;
18
18
const LIST_WINDOW_DAYS: i64 = 8;
19
19
@@ -215,15 +215,6 @@ fn draft_body(
215
215
})
216
216
}
217
217
218
fn new_client_message_id() -> String {
219
let random = uuid::Uuid::new_v4().as_u128();
220
let first = (random >> 96) as u32;
221
let second = (random >> 64) as u32;
222
let mut id = format!("{first}{second}");
223
id.truncate(CLIENT_MESSAGE_ID_LENGTH);
224
id
225
}
226
227
218
fn parse_drafts(body: &Value) -> Vec<ScheduledDraft> {
228
219
body.get("drafts")
229
220
.and_then(Value::as_array)
@@ -7,13 +7,13 @@ use session::{ApiResponse, Method, Request, Session};7
use crate::error::Result;7
use crate::error::Result;8
use crate::messages::{8
use crate::messages::{9
DEFAULT_RETRY_DELAY, MessageTransport, SessionMessageTransport, encode, ensure_success,9
DEFAULT_RETRY_DELAY, MessageTransport, SessionMessageTransport, encode, ensure_success,10
new_client_message_id,10
};11
};11
use crate::pins::DEFAULT_REGION;12
use crate::pins::DEFAULT_REGION;12
13
13
const SCHEDULED_DRAFT: &str = "ScheduledDraft";14
const SCHEDULED_DRAFT: &str = "ScheduledDraft";14
const NOT_FOUND_RETRIES: u32 = 3;15
const NOT_FOUND_RETRIES: u32 = 3;15
const BACKOFF_FACTOR: u32 = 3;16
const BACKOFF_FACTOR: u32 = 3;16
const CLIENT_MESSAGE_ID_LENGTH: usize = 19;17
const LIST_PAGE_SIZE: u32 = 200;17
const LIST_PAGE_SIZE: u32 = 200;18
const LIST_WINDOW_DAYS: i64 = 8;18
const LIST_WINDOW_DAYS: i64 = 8;19
19
@@ -215,15 +215,6 @@ fn draft_body(215
})215
})216
}216
}217
217
218
fn new_client_message_id() -> String {219
let random = uuid::Uuid::new_v4().as_u128();220
let first = (random >> 96) as u32;221
let second = (random >> 64) as u32;222
let mut id = format!("{first}{second}");223
id.truncate(CLIENT_MESSAGE_ID_LENGTH);224
id225
}226
227
fn parse_drafts(body: &Value) -> Vec<ScheduledDraft> {218
fn parse_drafts(body: &Value) -> Vec<ScheduledDraft> {228
body.get("drafts")219
body.get("drafts")229
.and_then(Value::as_array)220
.and_then(Value::as_array)@@ -307,15 +307,28 @@ fn edit_body(message_id: &str, html: &str) -> Value {
307
307
308
308
fn rich_text_body(html: &str, display_name: &str, properties: &Value) -> Value {
309
309
json!({
310
"clientmessageid": Utc::now().timestamp_millis().to_string(),
310
"clientmessageid": new_client_message_id(),
311
311
"content": html,
312
312
"messagetype": "RichText/Html",
313
313
"contenttype": "text",
314
314
"imdisplayname": display_name,
315
"amsreferences": [],
315
316
"properties": properties,
316
317
})
317
318
}
318
319
320
const CLIENT_MESSAGE_ID_LENGTH: usize = 19;
321
322
/// Teams web: two random `uint32` as decimal strings, joined and cut to 19 characters.
323
pub(crate) fn new_client_message_id() -> String {
324
let random = uuid::Uuid::new_v4().as_u128();
325
let first = (random >> 96) as u32;
326
let second = (random >> 64) as u32;
327
let mut id = format!("{first}{second}");
328
id.truncate(CLIENT_MESSAGE_ID_LENGTH);
329
id
330
}
331
319
332
fn typing_body(active: bool) -> Value {
320
333
json!({
321
334
"content": "",
@@ -307,15 +307,28 @@ fn edit_body(message_id: &str, html: &str) -> Value {307
307
308
fn rich_text_body(html: &str, display_name: &str, properties: &Value) -> Value {308
fn rich_text_body(html: &str, display_name: &str, properties: &Value) -> Value {309
json!({309
json!({310
"clientmessageid": Utc::now().timestamp_millis().to_string(),310
"clientmessageid": new_client_message_id(),311
"content": html,311
"content": html,312
"messagetype": "RichText/Html",312
"messagetype": "RichText/Html",313
"contenttype": "text",313
"contenttype": "text",314
"imdisplayname": display_name,314
"imdisplayname": display_name,315
"amsreferences": [],315
"properties": properties,316
"properties": properties,316
})317
})317
}318
}318
319
320
const CLIENT_MESSAGE_ID_LENGTH: usize = 19;321
322
/// Teams web: two random `uint32` as decimal strings, joined and cut to 19 characters.323
pub(crate) fn new_client_message_id() -> String {324
let random = uuid::Uuid::new_v4().as_u128();325
let first = (random >> 96) as u32;326
let second = (random >> 64) as u32;327
let mut id = format!("{first}{second}");328
id.truncate(CLIENT_MESSAGE_ID_LENGTH);329
id330
}331
319
fn typing_body(active: bool) -> Value {332
fn typing_body(active: bool) -> Value {320
json!({333
json!({321
"content": "",334
"content": "",@@ -407,7 +407,8 @@ async fn post_message_sends_rich_text_to_the_reply_thread_and_returns_the_arriva
407
407
let mock = ArrivalMock {
408
408
requests: Mutex::new(Vec::new()),
409
409
};
410
let properties = serde_json::json!({"importance": "", "subject": "", "qtdMsgs": "[]"});
410
let properties =
411
serde_json::json!({"importance": "", "mentions": "[]", "formatVariant": "TEAMS"});
411
412
let message_id = Messages::with_transport(&mock, "emea")
412
413
.post_message(
413
414
&ConversationRef::channel_reply("19:c@thread.tacv2", "99"),
@@ -430,5 +431,12 @@ async fn post_message_sends_rich_text_to_the_reply_thread_and_returns_the_arriva
430
431
assert_eq!(body["content"], "<p>hi</p>");
431
432
assert_eq!(body["imdisplayname"], "Daniel");
432
433
assert_eq!(body["properties"], properties);
433
assert!(body["clientmessageid"].is_string());
434
assert_eq!(body["amsreferences"], serde_json::json!([]));
435
let client_message_id = body["clientmessageid"].as_str().unwrap();
436
assert!((2..=19).contains(&client_message_id.len()));
437
assert!(
438
client_message_id
439
.chars()
440
.all(|character| character.is_ascii_digit())
441
);
434
442
}
@@ -407,7 +407,8 @@ async fn post_message_sends_rich_text_to_the_reply_thread_and_returns_the_arriva407
let mock = ArrivalMock {407
let mock = ArrivalMock {408
requests: Mutex::new(Vec::new()),408
requests: Mutex::new(Vec::new()),409
};409
};410
let properties = serde_json::json!({"importance": "", "subject": "", "qtdMsgs": "[]"});410
let properties =411
serde_json::json!({"importance": "", "mentions": "[]", "formatVariant": "TEAMS"});411
let message_id = Messages::with_transport(&mock, "emea")412
let message_id = Messages::with_transport(&mock, "emea")412
.post_message(413
.post_message(413
&ConversationRef::channel_reply("19:c@thread.tacv2", "99"),414
&ConversationRef::channel_reply("19:c@thread.tacv2", "99"),@@ -430,5 +431,12 @@ async fn post_message_sends_rich_text_to_the_reply_thread_and_returns_the_arriva430
assert_eq!(body["content"], "<p>hi</p>");431
assert_eq!(body["content"], "<p>hi</p>");431
assert_eq!(body["imdisplayname"], "Daniel");432
assert_eq!(body["imdisplayname"], "Daniel");432
assert_eq!(body["properties"], properties);433
assert_eq!(body["properties"], properties);433
assert!(body["clientmessageid"].is_string());434
assert_eq!(body["amsreferences"], serde_json::json!([]));435
let client_message_id = body["clientmessageid"].as_str().unwrap();436
assert!((2..=19).contains(&client_message_id.len()));437
assert!(438
client_message_id439
.chars()440
.all(|character| character.is_ascii_digit())441
);434
}442
}@@ -0,0 +1,111 @@
1
use serde_json::Value;
2
use session::{DEFAULT_ENDPOINT, IC3, Request, Scope, Session};
3
4
const NOTES_URL: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/48%3Anotes/messages?view=msnp24Equivalent&pageSize=200";
5
6
#[tokio::main]
7
async fn main() {
8
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
9
let session = Session::connect(&endpoint).await.expect("browser");
10
let scope = Scope::new(IC3, "Teams.AccessAsUser.All");
11
let answer = session
12
.batch(&[Request::get(NOTES_URL)], &scope)
13
.await
14
.expect("chatsvc")
15
.remove(0);
16
println!("# GET status {}", answer.status);
17
for message in answer.body["messages"].as_array().into_iter().flatten() {
18
let messagetype = message["messagetype"].as_str().unwrap_or("");
19
if !messagetype.starts_with("RichText") && messagetype != "Text" {
20
continue;
21
}
22
let properties = message["properties"].as_object();
23
let keys: Vec<String> = properties
24
.into_iter()
25
.flatten()
26
.map(|(key, value)| format!("{key}={}", shape(key, value)))
27
.collect();
28
println!(
29
"- type={messagetype} contenttype={} clientmessageid_len={} ams={} imdisplayname={} props=[{}]",
30
message["contenttype"],
31
message["clientmessageid"]
32
.as_str()
33
.map(str::len)
34
.unwrap_or(0),
35
message["amsreferences"]
36
.as_array()
37
.map(Vec::len)
38
.unwrap_or(0),
39
message["imdisplayname"].is_string(),
40
keys.join(", ")
41
);
42
println!(
43
" skeleton: {}",
44
skeleton(message["content"].as_str().unwrap_or(""))
45
);
46
}
47
}
48
49
fn shape(key: &str, value: &Value) -> String {
50
match value {
51
Value::String(text) if key == "formatVariant" || key == "importance" => format!("{text:?}"),
52
Value::String(text) if text.starts_with('[') => {
53
let parsed: Value = serde_json::from_str(text).unwrap_or(Value::Null);
54
let entries = parsed.as_array().cloned().unwrap_or_default();
55
let fields: Vec<String> = entries
56
.first()
57
.and_then(Value::as_object)
58
.map(|object| {
59
object
60
.iter()
61
.map(|(field, field_value)| match field.as_str() {
62
"@type" | "mentionType" | "fileType" | "type" => {
63
format!("{field}:{field_value}")
64
}
65
"itemid" => format!(
66
"itemid:{}",
67
if field_value.is_string() {
68
"str"
69
} else {
70
"num"
71
}
72
),
73
_ => field.clone(),
74
})
75
.collect()
76
})
77
.unwrap_or_default();
78
format!("str[{}]{{{}}}", entries.len(), fields.join(" "))
79
}
80
Value::String(text) => format!("str({})", text.len()),
81
Value::Null => "null".into(),
82
other => format!("{}", other.to_string().len()),
83
}
84
}
85
86
fn skeleton(html: &str) -> String {
87
let mut out = String::new();
88
let mut rest = html;
89
while let Some(start) = rest.find('<') {
90
let Some(end) = rest[start..].find('>') else {
91
break;
92
};
93
let tag = &rest[start + 1..start + end];
94
let name: String = tag.split_whitespace().next().unwrap_or("").to_owned();
95
let itemtype = tag
96
.split("itemtype=\"")
97
.nth(1)
98
.and_then(|value| value.split('"').next())
99
.map(|value| format!(" itemtype={value}"))
100
.unwrap_or_default();
101
let attributes: Vec<&str> = tag
102
.split_whitespace()
103
.skip(1)
104
.filter_map(|attribute| attribute.split('=').next())
105
.filter(|attribute| *attribute != "itemtype")
106
.collect();
107
out.push_str(&format!("<{name}{itemtype} [{}]>", attributes.join(",")));
108
rest = &rest[start + end + 1..];
109
}
110
out
111
}
@@ -0,0 +1,111 @@1
use serde_json::Value;2
use session::{DEFAULT_ENDPOINT, IC3, Request, Scope, Session};3
4
const NOTES_URL: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/48%3Anotes/messages?view=msnp24Equivalent&pageSize=200";5
6
#[tokio::main]7
async fn main() {8
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());9
let session = Session::connect(&endpoint).await.expect("browser");10
let scope = Scope::new(IC3, "Teams.AccessAsUser.All");11
let answer = session12
.batch(&[Request::get(NOTES_URL)], &scope)13
.await14
.expect("chatsvc")15
.remove(0);16
println!("# GET status {}", answer.status);17
for message in answer.body["messages"].as_array().into_iter().flatten() {18
let messagetype = message["messagetype"].as_str().unwrap_or("");19
if !messagetype.starts_with("RichText") && messagetype != "Text" {20
continue;21
}22
let properties = message["properties"].as_object();23
let keys: Vec<String> = properties24
.into_iter()25
.flatten()26
.map(|(key, value)| format!("{key}={}", shape(key, value)))27
.collect();28
println!(29
"- type={messagetype} contenttype={} clientmessageid_len={} ams={} imdisplayname={} props=[{}]",30
message["contenttype"],31
message["clientmessageid"]32
.as_str()33
.map(str::len)34
.unwrap_or(0),35
message["amsreferences"]36
.as_array()37
.map(Vec::len)38
.unwrap_or(0),39
message["imdisplayname"].is_string(),40
keys.join(", ")41
);42
println!(43
" skeleton: {}",44
skeleton(message["content"].as_str().unwrap_or(""))45
);46
}47
}48
49
fn shape(key: &str, value: &Value) -> String {50
match value {51
Value::String(text) if key == "formatVariant" || key == "importance" => format!("{text:?}"),52
Value::String(text) if text.starts_with('[') => {53
let parsed: Value = serde_json::from_str(text).unwrap_or(Value::Null);54
let entries = parsed.as_array().cloned().unwrap_or_default();55
let fields: Vec<String> = entries56
.first()57
.and_then(Value::as_object)58
.map(|object| {59
object60
.iter()61
.map(|(field, field_value)| match field.as_str() {62
"@type" | "mentionType" | "fileType" | "type" => {63
format!("{field}:{field_value}")64
}65
"itemid" => format!(66
"itemid:{}",67
if field_value.is_string() {68
"str"69
} else {70
"num"71
}72
),73
_ => field.clone(),74
})75
.collect()76
})77
.unwrap_or_default();78
format!("str[{}]{{{}}}", entries.len(), fields.join(" "))79
}80
Value::String(text) => format!("str({})", text.len()),81
Value::Null => "null".into(),82
other => format!("{}", other.to_string().len()),83
}84
}85
86
fn skeleton(html: &str) -> String {87
let mut out = String::new();88
let mut rest = html;89
while let Some(start) = rest.find('<') {90
let Some(end) = rest[start..].find('>') else {91
break;92
};93
let tag = &rest[start + 1..start + end];94
let name: String = tag.split_whitespace().next().unwrap_or("").to_owned();95
let itemtype = tag96
.split("itemtype=\"")97
.nth(1)98
.and_then(|value| value.split('"').next())99
.map(|value| format!(" itemtype={value}"))100
.unwrap_or_default();101
let attributes: Vec<&str> = tag102
.split_whitespace()103
.skip(1)104
.filter_map(|attribute| attribute.split('=').next())105
.filter(|attribute| *attribute != "itemtype")106
.collect();107
out.push_str(&format!("<{name}{itemtype} [{}]>", attributes.join(",")));108
rest = &rest[start + end + 1..];109
}110
out111
}@@ -1,8 +1,8 @@
1
1
use chatsvc::ConversationRef;
2
2
use chrono::{DateTime, Duration, Utc};
3
3
use graph::{
4
FileReference, MessageExtras, MessageTarget, OutgoingMention,
5
UploadDestination, UploadedFile, hosted_image_order,
4
FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
5
hosted_image_order,
6
6
};
7
7
use store::MessageRecord;
8
8
@@ -87,7 +87,7 @@ impl<R: Remote> SyncEngine<R> {
87
87
self.cache_sent(conversation_id, &sent, &html, extras)
88
88
}
89
89
90
/// Chat: quoted reply (Graph beta `replyWithQuote`). Channel: reply in the thread of `message_id`.
90
/// Quoted reply in Teams' chatsvc shape; channels answer in the thread of `message_id`.
91
91
pub async fn reply_to(
92
92
&self,
93
93
conversation_id: &str,
@@ -125,52 +125,57 @@ impl<R: Remote> SyncEngine<R> {
125
125
) -> Result<MessageRecord> {
126
126
let conversation = self.resolve(conversation_id).await?;
127
127
let (html, mentions) = outgoing(&conversation, html, mentions)?;
128
let (sent, extras) = match conversation {
129
Conversation::Chat => {
130
let sent = self
131
.remote
132
.reply_with_quote(conversation_id, message_id, &html, &mentions, extras)
133
.await?;
134
(sent, extras.clone())
135
}
136
Conversation::Channel { team_id } => {
137
let quoted = self
138
.store
139
.messages_by_id(conversation_id, &[message_id.to_owned()])?
140
.remove(message_id);
128
let quoted = self
129
.store
130
.messages_by_id(conversation_id, &[message_id.to_owned()])?
131
.remove(message_id);
132
let (chatsvc_conversation, root_id) = match &conversation {
133
Conversation::Chat => (ConversationRef::chat(conversation_id), None),
134
Conversation::Channel { .. } => {
141
135
let root_id = quoted
142
136
.as_ref()
143
137
.and_then(|record| record.reply_to_id.clone())
144
138
.unwrap_or_else(|| message_id.to_owned());
145
if let Some(quoted) = "ed
146
&& let Some((sent, html)) = self
147
.quote_reply_via_chatsvc(
148
conversation_id,
149
&root_id,
150
quoted,
151
&html,
152
&mentions,
153
extras,
154
)
155
.await?
156
{
157
return self.cache_sent(conversation_id, &sent, &html, extras);
158
}
159
let sent = self
160
.remote
139
(
140
ConversationRef::channel_reply(conversation_id, &root_id),
141
Some(root_id),
142
)
143
}
144
};
145
if let Some(quoted) = "ed
146
&& let Some((sent, html)) = self
147
.quote_reply_via_chatsvc(
148
&chatsvc_conversation,
149
root_id.as_deref(),
150
quoted,
151
&html,
152
&mentions,
153
extras,
154
)
155
.await?
156
{
157
return self.cache_sent(conversation_id, &sent, &html, extras);
158
}
159
let sent = match (&conversation, &root_id) {
160
(Conversation::Channel { team_id }, Some(root_id)) => {
161
self.remote
161
162
.reply_to_channel_message(
162
&team_id,
163
team_id,
163
164
conversation_id,
164
&root_id,
165
root_id,
165
166
&html,
166
167
&mentions,
167
168
extras,
168
169
)
169
.await?;
170
(sent, extras.clone())
170
.await?
171
}
172
_ => {
173
self.remote
174
.reply_with_quote(conversation_id, message_id, &html, &mentions, extras)
175
.await?
171
176
}
172
177
};
173
self.cache_sent(conversation_id, &sent, &html, &extras)
178
self.cache_sent(conversation_id, &sent, &html, extras)
174
179
}
175
180
176
181
/// Own and not deleted. Chat messages, channel posts and channel replies alike.
@@ -750,10 +755,11 @@ impl<R: Remote> SyncEngine<R> {
750
755
self.seed_images(&seeds)
751
756
}
752
757
758
/// `None` when Teams' shape cannot be written here (images, files, team mentions, no quote).
753
759
async fn quote_reply_via_chatsvc(
754
760
&self,
755
channel_id: &str,
756
root_id: &str,
761
conversation: &ConversationRef,
762
root_id: Option<&str>,
757
763
quoted: &MessageRecord,
758
764
html: &str,
759
765
mentions: &[OutgoingMention],
@@ -775,12 +781,7 @@ impl<R: Remote> SyncEngine<R> {
775
781
let content = format!("{}{}", quote.html, chatsvc_mention_html(html, mentions));
776
782
let message_id = self
777
783
.remote
778
.post_chatsvc_message(
779
&ConversationRef::channel_reply(channel_id, root_id),
780
&content,
781
&me.display_name,
782
&properties,
783
)
784
.post_chatsvc_message(conversation, &content, &me.display_name, &properties)
784
785
.await?;
785
786
let created_at = message_id
786
787
.parse::<i64>()
@@ -1,8 +1,8 @@1
use chatsvc::ConversationRef;1
use chatsvc::ConversationRef;2
use chrono::{DateTime, Duration, Utc};2
use chrono::{DateTime, Duration, Utc};3
use graph::{3
use graph::{4
FileReference, MessageExtras, MessageTarget, OutgoingMention,4
FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,5
UploadDestination, UploadedFile, hosted_image_order,5
hosted_image_order,6
};6
};7
use store::MessageRecord;7
use store::MessageRecord;8
8
@@ -87,7 +87,7 @@ impl<R: Remote> SyncEngine<R> {87
self.cache_sent(conversation_id, &sent, &html, extras)87
self.cache_sent(conversation_id, &sent, &html, extras)88
}88
}89
89
90
/// Chat: quoted reply (Graph beta `replyWithQuote`). Channel: reply in the thread of `message_id`.90
/// Quoted reply in Teams' chatsvc shape; channels answer in the thread of `message_id`.91
pub async fn reply_to(91
pub async fn reply_to(92
&self,92
&self,93
conversation_id: &str,93
conversation_id: &str,@@ -125,52 +125,57 @@ impl<R: Remote> SyncEngine<R> {125
) -> Result<MessageRecord> {125
) -> Result<MessageRecord> {126
let conversation = self.resolve(conversation_id).await?;126
let conversation = self.resolve(conversation_id).await?;127
let (html, mentions) = outgoing(&conversation, html, mentions)?;127
let (html, mentions) = outgoing(&conversation, html, mentions)?;128
let (sent, extras) = match conversation {128
let quoted = self129
Conversation::Chat => {129
.store130
let sent = self130
.messages_by_id(conversation_id, &[message_id.to_owned()])?131
.remote131
.remove(message_id);132
.reply_with_quote(conversation_id, message_id, &html, &mentions, extras)132
let (chatsvc_conversation, root_id) = match &conversation {133
.await?;133
Conversation::Chat => (ConversationRef::chat(conversation_id), None),134
(sent, extras.clone())134
Conversation::Channel { .. } => {135
}136
Conversation::Channel { team_id } => {137
let quoted = self138
.store139
.messages_by_id(conversation_id, &[message_id.to_owned()])?140
.remove(message_id);141
let root_id = quoted135
let root_id = quoted142
.as_ref()136
.as_ref()143
.and_then(|record| record.reply_to_id.clone())137
.and_then(|record| record.reply_to_id.clone())144
.unwrap_or_else(|| message_id.to_owned());138
.unwrap_or_else(|| message_id.to_owned());145
if let Some(quoted) = "ed139
(146
&& let Some((sent, html)) = self140
ConversationRef::channel_reply(conversation_id, &root_id),147
.quote_reply_via_chatsvc(141
Some(root_id),148
conversation_id,142
)149
&root_id,143
}150
quoted,144
};151
&html,145
if let Some(quoted) = "ed152
&mentions,146
&& let Some((sent, html)) = self153
extras,147
.quote_reply_via_chatsvc(154
)148
&chatsvc_conversation,155
.await?149
root_id.as_deref(),156
{150
quoted,157
return self.cache_sent(conversation_id, &sent, &html, extras);151
&html,158
}152
&mentions,159
let sent = self153
extras,160
.remote154
)155
.await?156
{157
return self.cache_sent(conversation_id, &sent, &html, extras);158
}159
let sent = match (&conversation, &root_id) {160
(Conversation::Channel { team_id }, Some(root_id)) => {161
self.remote161
.reply_to_channel_message(162
.reply_to_channel_message(162
&team_id,163
team_id,163
conversation_id,164
conversation_id,164
&root_id,165
root_id,165
&html,166
&html,166
&mentions,167
&mentions,167
extras,168
extras,168
)169
)169
.await?;170
.await?170
(sent, extras.clone())171
}172
_ => {173
self.remote174
.reply_with_quote(conversation_id, message_id, &html, &mentions, extras)175
.await?171
}176
}172
};177
};173
self.cache_sent(conversation_id, &sent, &html, &extras)178
self.cache_sent(conversation_id, &sent, &html, extras)174
}179
}175
180
176
/// Own and not deleted. Chat messages, channel posts and channel replies alike.181
/// Own and not deleted. Chat messages, channel posts and channel replies alike.@@ -750,10 +755,11 @@ impl<R: Remote> SyncEngine<R> {750
self.seed_images(&seeds)755
self.seed_images(&seeds)751
}756
}752
757
758
/// `None` when Teams' shape cannot be written here (images, files, team mentions, no quote).753
async fn quote_reply_via_chatsvc(759
async fn quote_reply_via_chatsvc(754
&self,760
&self,755
channel_id: &str,761
conversation: &ConversationRef,756
root_id: &str,762
root_id: Option<&str>,757
quoted: &MessageRecord,763
quoted: &MessageRecord,758
html: &str,764
html: &str,759
mentions: &[OutgoingMention],765
mentions: &[OutgoingMention],@@ -775,12 +781,7 @@ impl<R: Remote> SyncEngine<R> {775
let content = format!("{}{}", quote.html, chatsvc_mention_html(html, mentions));781
let content = format!("{}{}", quote.html, chatsvc_mention_html(html, mentions));776
let message_id = self782
let message_id = self777
.remote783
.remote778
.post_chatsvc_message(784
.post_chatsvc_message(conversation, &content, &me.display_name, &properties)779
&ConversationRef::channel_reply(channel_id, root_id),780
&content,781
&me.display_name,782
&properties,783
)784
.await?;785
.await?;785
let created_at = message_id786
let created_at = message_id786
.parse::<i64>()787
.parse::<i64>()@@ -8,6 +8,8 @@ use crate::preview::preview_text;
8
8
const REPLY_ITEMTYPE: &str = "http://schema.skype.com/Reply";
9
9
const MENTION_ITEMTYPE: &str = "http://schema.skype.com/Mention";
10
10
const ORGID_PREFIX: &str = "8:orgid:";
11
const BOT_PREFIX: &str = "28:";
12
const FORMAT_VARIANT: &str = "TEAMS";
11
13
12
14
#[derive(Debug, Clone, PartialEq)]
13
15
pub(crate) struct TeamsQuote {
@@ -17,8 +19,11 @@ pub(crate) struct TeamsQuote {
17
19
18
20
/// Teams' `createBlockquoteTag`: no quote without sender, name or preview.
19
21
pub(crate) fn teams_quote(record: &MessageRecord) -> Option<TeamsQuote> {
20
let sender_mri = user_mri(record.sender_id.as_deref()?);
21
let sender_name = record.sender_name.as_deref().filter(|name| !name.is_empty())?;
22
let sender_mri = sender_mri(record)?;
23
let sender_name = record
24
.sender_name
25
.as_deref()
26
.filter(|name| !name.is_empty())?;
22
27
let preview = preview_text(&record.body_html).filter(|preview| !preview.is_empty())?;
23
28
let time = record.created_at.timestamp_millis();
24
29
let html = format!(
@@ -39,33 +44,40 @@ pub(crate) fn teams_quote(record: &MessageRecord) -> Option<TeamsQuote> {
39
44
})
40
45
}
41
46
47
/// The `properties` Teams' `sendMessageInConv` writes; `None` when a mention has no chatsvc shape here.
42
48
pub(crate) fn quote_reply_properties(
43
49
quote: &TeamsQuote,
44
50
mentions: &[OutgoingMention],
45
51
importance: Option<&str>,
46
52
) -> Option<Value> {
47
let mut properties = json!({
53
let mention_entries = mentions
54
.iter()
55
.map(mention_entry)
56
.collect::<Option<Vec<_>>>()?;
57
Some(json!({
48
58
"importance": importance.unwrap_or_default(),
49
"subject": "",
59
"links": "[]",
60
"mentions": Value::Array(mention_entries).to_string(),
61
"onbehalfof": null,
62
"files": "[]",
50
63
"qtdMsgs": Value::Array(vec![quote.quoted_message.clone()]).to_string(),
51
});
52
if !mentions.is_empty() {
53
let entries = mentions
54
.iter()
55
.map(|mention| match &mention.target {
56
MentionTarget::User { user_id } => Some(json!({
57
"@type": MENTION_ITEMTYPE,
58
"itemid": mention.id,
59
"mri": user_mri(user_id),
60
"mentionType": "person",
61
"displayName": mention.text,
62
})),
63
MentionTarget::Channel { .. } | MentionTarget::Team { .. } => None,
64
})
65
.collect::<Option<Vec<_>>>()?;
66
properties["mentions"] = json!(Value::Array(entries).to_string());
67
}
68
Some(properties)
64
"formatVariant": FORMAT_VARIANT,
65
}))
66
}
67
68
fn mention_entry(mention: &OutgoingMention) -> Option<Value> {
69
let (mri, mention_type) = match &mention.target {
70
MentionTarget::User { user_id } => (user_mri(user_id), "person"),
71
MentionTarget::Channel { channel_id } => (channel_id.clone(), "channel"),
72
MentionTarget::Team { .. } => return None,
73
};
74
Some(json!({
75
"@type": MENTION_ITEMTYPE,
76
"itemid": mention.id.to_string(),
77
"mri": mri,
78
"mentionType": mention_type,
79
"displayName": mention.text,
80
}))
69
81
}
70
82
71
83
pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) -> String {
@@ -82,8 +94,19 @@ pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) ->
82
94
converted.replace("</at>", "</span>")
83
95
}
84
96
97
fn sender_mri(record: &MessageRecord) -> Option<String> {
98
match (&record.sender_id, &record.sender_application_id) {
99
(Some(user_id), _) => Some(user_mri(user_id)),
100
(None, Some(application_id)) if application_id.contains(':') => {
101
Some(application_id.clone())
102
}
103
(None, Some(application_id)) => Some(format!("{BOT_PREFIX}{application_id}")),
104
(None, None) => None,
105
}
106
}
107
85
108
fn user_mri(user_id: &str) -> String {
86
if user_id.starts_with("8:") {
109
if user_id.contains(':') {
87
110
user_id.to_owned()
88
111
} else {
89
112
format!("{ORGID_PREFIX}{user_id}")
@@ -102,12 +125,32 @@ mod tests {
102
125
}
103
126
}
104
127
105
#[test]
106
fn person_mentions_become_teams_spans_and_a_mentions_property() {
107
let quote = TeamsQuote {
128
fn quote() -> TeamsQuote {
129
TeamsQuote {
108
130
html: String::new(),
109
131
quoted_message: json!({"messageId": "1"}),
110
};
132
}
133
}
134
135
#[test]
136
fn a_quote_reply_gets_the_teams_property_set() {
137
let properties = quote_reply_properties("e(), &[], None).unwrap();
138
assert_eq!(
139
properties,
140
json!({
141
"importance": "",
142
"links": "[]",
143
"mentions": "[]",
144
"onbehalfof": null,
145
"files": "[]",
146
"qtdMsgs": "[{\"messageId\":\"1\"}]",
147
"formatVariant": "TEAMS",
148
})
149
);
150
}
151
152
#[test]
153
fn person_mentions_become_teams_spans_and_a_mentions_property() {
111
154
let mentions = [mention(
112
155
0,
113
156
MentionTarget::User {
@@ -119,27 +162,61 @@ mod tests {
119
162
html,
120
163
"hi <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada</span>"
121
164
);
122
let properties = quote_reply_properties("e, &mentions, Some("high")).unwrap();
165
let properties = quote_reply_properties("e(), &mentions, Some("high")).unwrap();
123
166
assert_eq!(properties["importance"], "high");
124
167
assert_eq!(properties["qtdMsgs"], "[{\"messageId\":\"1\"}]");
125
168
let entries: Value =
126
169
serde_json::from_str(properties["mentions"].as_str().unwrap()).unwrap();
127
assert_eq!(entries[0]["mri"], "8:orgid:user-ada");
128
assert_eq!(entries[0]["mentionType"], "person");
170
assert_eq!(
171
entries,
172
json!([{
173
"@type": "http://schema.skype.com/Mention",
174
"itemid": "0",
175
"mri": "8:orgid:user-ada",
176
"mentionType": "person",
177
"displayName": "Ada",
178
}])
179
);
129
180
}
130
181
131
182
#[test]
132
fn a_channel_mention_has_no_chatsvc_shape() {
133
let quote = TeamsQuote {
134
html: String::new(),
135
quoted_message: Value::Null,
136
};
183
fn a_channel_mention_points_at_the_channel_thread() {
137
184
let mentions = [mention(
138
0,
185
1,
139
186
MentionTarget::Channel {
140
channel_id: "19:c".into(),
187
channel_id: "19:c@thread.tacv2".into(),
188
},
189
)];
190
let properties = quote_reply_properties("e(), &mentions, None).unwrap();
191
let entries: Value =
192
serde_json::from_str(properties["mentions"].as_str().unwrap()).unwrap();
193
assert_eq!(entries[0]["mri"], "19:c@thread.tacv2");
194
assert_eq!(entries[0]["mentionType"], "channel");
195
assert_eq!(entries[0]["itemid"], "1");
196
}
197
198
#[test]
199
fn a_team_mention_has_no_chatsvc_shape() {
200
let mentions = [mention(
201
0,
202
MentionTarget::Team {
203
team_id: "team-1".into(),
141
204
},
142
205
)];
143
assert!(quote_reply_properties("e, &mentions, None).is_none());
206
assert!(quote_reply_properties("e(), &mentions, None).is_none());
207
}
208
209
#[test]
210
fn a_bot_sender_is_quoted_with_its_28_mri() {
211
let record = MessageRecord {
212
message_id: "5".into(),
213
sender_name: Some("Echo".into()),
214
sender_application_id: Some("app-1".into()),
215
body_html: "<p>pong</p>".into(),
216
..MessageRecord::default()
217
};
218
let quote = teams_quote(&record).unwrap();
219
assert_eq!(quote.quoted_message["sender"], "28:app-1");
220
assert!(quote.html.contains("itemid=\"28:app-1\">Echo</strong>"));
144
221
}
145
222
}
@@ -8,6 +8,8 @@ use crate::preview::preview_text;8
const REPLY_ITEMTYPE: &str = "http://schema.skype.com/Reply";8
const REPLY_ITEMTYPE: &str = "http://schema.skype.com/Reply";9
const MENTION_ITEMTYPE: &str = "http://schema.skype.com/Mention";9
const MENTION_ITEMTYPE: &str = "http://schema.skype.com/Mention";10
const ORGID_PREFIX: &str = "8:orgid:";10
const ORGID_PREFIX: &str = "8:orgid:";11
const BOT_PREFIX: &str = "28:";12
const FORMAT_VARIANT: &str = "TEAMS";11
13
12
#[derive(Debug, Clone, PartialEq)]14
#[derive(Debug, Clone, PartialEq)]13
pub(crate) struct TeamsQuote {15
pub(crate) struct TeamsQuote {@@ -17,8 +19,11 @@ pub(crate) struct TeamsQuote {17
19
18
/// Teams' `createBlockquoteTag`: no quote without sender, name or preview.20
/// Teams' `createBlockquoteTag`: no quote without sender, name or preview.19
pub(crate) fn teams_quote(record: &MessageRecord) -> Option<TeamsQuote> {21
pub(crate) fn teams_quote(record: &MessageRecord) -> Option<TeamsQuote> {20
let sender_mri = user_mri(record.sender_id.as_deref()?);22
let sender_mri = sender_mri(record)?;21
let sender_name = record.sender_name.as_deref().filter(|name| !name.is_empty())?;23
let sender_name = record24
.sender_name25
.as_deref()26
.filter(|name| !name.is_empty())?;22
let preview = preview_text(&record.body_html).filter(|preview| !preview.is_empty())?;27
let preview = preview_text(&record.body_html).filter(|preview| !preview.is_empty())?;23
let time = record.created_at.timestamp_millis();28
let time = record.created_at.timestamp_millis();24
let html = format!(29
let html = format!(@@ -39,33 +44,40 @@ pub(crate) fn teams_quote(record: &MessageRecord) -> Option<TeamsQuote> {39
})44
})40
}45
}41
46
47
/// The `properties` Teams' `sendMessageInConv` writes; `None` when a mention has no chatsvc shape here.42
pub(crate) fn quote_reply_properties(48
pub(crate) fn quote_reply_properties(43
quote: &TeamsQuote,49
quote: &TeamsQuote,44
mentions: &[OutgoingMention],50
mentions: &[OutgoingMention],45
importance: Option<&str>,51
importance: Option<&str>,46
) -> Option<Value> {52
) -> Option<Value> {47
let mut properties = json!({53
let mention_entries = mentions54
.iter()55
.map(mention_entry)56
.collect::<Option<Vec<_>>>()?;57
Some(json!({48
"importance": importance.unwrap_or_default(),58
"importance": importance.unwrap_or_default(),49
"subject": "",59
"links": "[]",60
"mentions": Value::Array(mention_entries).to_string(),61
"onbehalfof": null,62
"files": "[]",50
"qtdMsgs": Value::Array(vec![quote.quoted_message.clone()]).to_string(),63
"qtdMsgs": Value::Array(vec![quote.quoted_message.clone()]).to_string(),51
});64
"formatVariant": FORMAT_VARIANT,52
if !mentions.is_empty() {65
}))53
let entries = mentions66
}54
.iter()67
55
.map(|mention| match &mention.target {68
fn mention_entry(mention: &OutgoingMention) -> Option<Value> {56
MentionTarget::User { user_id } => Some(json!({69
let (mri, mention_type) = match &mention.target {57
"@type": MENTION_ITEMTYPE,70
MentionTarget::User { user_id } => (user_mri(user_id), "person"),58
"itemid": mention.id,71
MentionTarget::Channel { channel_id } => (channel_id.clone(), "channel"),59
"mri": user_mri(user_id),72
MentionTarget::Team { .. } => return None,60
"mentionType": "person",73
};61
"displayName": mention.text,74
Some(json!({62
})),75
"@type": MENTION_ITEMTYPE,63
MentionTarget::Channel { .. } | MentionTarget::Team { .. } => None,76
"itemid": mention.id.to_string(),64
})77
"mri": mri,65
.collect::<Option<Vec<_>>>()?;78
"mentionType": mention_type,66
properties["mentions"] = json!(Value::Array(entries).to_string());79
"displayName": mention.text,67
}80
}))68
Some(properties)69
}81
}70
82
71
pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) -> String {83
pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) -> String {@@ -82,8 +94,19 @@ pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) ->82
converted.replace("</at>", "</span>")94
converted.replace("</at>", "</span>")83
}95
}84
96
97
fn sender_mri(record: &MessageRecord) -> Option<String> {98
match (&record.sender_id, &record.sender_application_id) {99
(Some(user_id), _) => Some(user_mri(user_id)),100
(None, Some(application_id)) if application_id.contains(':') => {101
Some(application_id.clone())102
}103
(None, Some(application_id)) => Some(format!("{BOT_PREFIX}{application_id}")),104
(None, None) => None,105
}106
}107
85
fn user_mri(user_id: &str) -> String {108
fn user_mri(user_id: &str) -> String {86
if user_id.starts_with("8:") {109
if user_id.contains(':') {87
user_id.to_owned()110
user_id.to_owned()88
} else {111
} else {89
format!("{ORGID_PREFIX}{user_id}")112
format!("{ORGID_PREFIX}{user_id}")@@ -102,12 +125,32 @@ mod tests {102
}125
}103
}126
}104
127
105
#[test]128
fn quote() -> TeamsQuote {106
fn person_mentions_become_teams_spans_and_a_mentions_property() {129
TeamsQuote {107
let quote = TeamsQuote {108
html: String::new(),130
html: String::new(),109
quoted_message: json!({"messageId": "1"}),131
quoted_message: json!({"messageId": "1"}),110
};132
}133
}134
135
#[test]136
fn a_quote_reply_gets_the_teams_property_set() {137
let properties = quote_reply_properties("e(), &[], None).unwrap();138
assert_eq!(139
properties,140
json!({141
"importance": "",142
"links": "[]",143
"mentions": "[]",144
"onbehalfof": null,145
"files": "[]",146
"qtdMsgs": "[{\"messageId\":\"1\"}]",147
"formatVariant": "TEAMS",148
})149
);150
}151
152
#[test]153
fn person_mentions_become_teams_spans_and_a_mentions_property() {111
let mentions = [mention(154
let mentions = [mention(112
0,155
0,113
MentionTarget::User {156
MentionTarget::User {@@ -119,27 +162,61 @@ mod tests {119
html,162
html,120
"hi <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada</span>"163
"hi <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada</span>"121
);164
);122
let properties = quote_reply_properties("e, &mentions, Some("high")).unwrap();165
let properties = quote_reply_properties("e(), &mentions, Some("high")).unwrap();123
assert_eq!(properties["importance"], "high");166
assert_eq!(properties["importance"], "high");124
assert_eq!(properties["qtdMsgs"], "[{\"messageId\":\"1\"}]");167
assert_eq!(properties["qtdMsgs"], "[{\"messageId\":\"1\"}]");125
let entries: Value =168
let entries: Value =126
serde_json::from_str(properties["mentions"].as_str().unwrap()).unwrap();169
serde_json::from_str(properties["mentions"].as_str().unwrap()).unwrap();127
assert_eq!(entries[0]["mri"], "8:orgid:user-ada");170
assert_eq!(128
assert_eq!(entries[0]["mentionType"], "person");171
entries,172
json!([{173
"@type": "http://schema.skype.com/Mention",174
"itemid": "0",175
"mri": "8:orgid:user-ada",176
"mentionType": "person",177
"displayName": "Ada",178
}])179
);129
}180
}130
181
131
#[test]182
#[test]132
fn a_channel_mention_has_no_chatsvc_shape() {183
fn a_channel_mention_points_at_the_channel_thread() {133
let quote = TeamsQuote {134
html: String::new(),135
quoted_message: Value::Null,136
};137
let mentions = [mention(184
let mentions = [mention(138
0,185
1,139
MentionTarget::Channel {186
MentionTarget::Channel {140
channel_id: "19:c".into(),187
channel_id: "19:c@thread.tacv2".into(),188
},189
)];190
let properties = quote_reply_properties("e(), &mentions, None).unwrap();191
let entries: Value =192
serde_json::from_str(properties["mentions"].as_str().unwrap()).unwrap();193
assert_eq!(entries[0]["mri"], "19:c@thread.tacv2");194
assert_eq!(entries[0]["mentionType"], "channel");195
assert_eq!(entries[0]["itemid"], "1");196
}197
198
#[test]199
fn a_team_mention_has_no_chatsvc_shape() {200
let mentions = [mention(201
0,202
MentionTarget::Team {203
team_id: "team-1".into(),141
},204
},142
)];205
)];143
assert!(quote_reply_properties("e, &mentions, None).is_none());206
assert!(quote_reply_properties("e(), &mentions, None).is_none());207
}208
209
#[test]210
fn a_bot_sender_is_quoted_with_its_28_mri() {211
let record = MessageRecord {212
message_id: "5".into(),213
sender_name: Some("Echo".into()),214
sender_application_id: Some("app-1".into()),215
body_html: "<p>pong</p>".into(),216
..MessageRecord::default()217
};218
let quote = teams_quote(&record).unwrap();219
assert_eq!(quote.quoted_message["sender"], "28:app-1");220
assert!(quote.html.contains("itemid=\"28:app-1\">Echo</strong>"));144
}221
}145
}222
}@@ -2395,7 +2395,7 @@ async fn the_notes_chat_takes_every_write_without_a_graph_chat_lookup() {
2395
2395
assert_eq!(fake.sent.lock().unwrap().as_slice(), ["note to self"]);
2396
2396
let calls = fake.calls();
2397
2397
for expected in [
2398
"quote_reply 48:notes m9000 again",
2398
"chatsvc post 48:notes",
2399
2399
"edit m9000 edited",
2400
2400
"set_reaction m9000 \u{1f44d}",
2401
2401
"unset_reaction m9000 \u{1f44d}",
@@ -3844,10 +3844,13 @@ async fn chat_reply_quotes_and_channel_reply_uses_the_thread_root() {
3844
3844
.reply_to(CHAT, "m0001", "answer **bold**")
3845
3845
.await
3846
3846
.unwrap();
3847
assert_eq!(sent.message_id, "m9003");
3847
assert_eq!(sent.message_id, "1727203440000");
3848
assert!(fake.calls().contains(&format!("chatsvc post {CHAT}")));
3848
3849
assert!(
3849
fake.calls()
3850
.contains(&format!("quote_reply {CHAT} m0001 answer <b>bold</b>"))
3850
!fake
3851
.calls()
3852
.iter()
3853
.any(|call| call.starts_with("quote_reply"))
3851
3854
);
3852
3855
3853
3856
let channel_fake = Arc::new(Fake::default());
@@ -5439,6 +5442,110 @@ async fn marking_the_notes_chat_read_takes_the_tenant_from_another_chat() {
5439
5442
);
5440
5443
}
5441
5444
5445
#[tokio::test]
5446
async fn a_quoted_chat_reply_is_written_through_chatsvc_in_the_teams_shape() {
5447
let fake = Arc::new(Fake::default());
5448
fake.set_chat_messages(numbered(2));
5449
let engine = chat_engine(&fake, small_pages()).await;
5450
engine.fetch_newer(CHAT).await.unwrap();
5451
let extras = MessageExtras {
5452
importance: Some("high"),
5453
..MessageExtras::default()
5454
};
5455
let sent = engine
5456
.reply_to_with_extras(
5457
CHAT,
5458
"m0001",
5459
"<p>thanks @Ada Example</p>",
5460
&[MentionInput::user("user-ada", "Ada Example")],
5461
&extras,
5462
)
5463
.await
5464
.unwrap();
5465
let (conversation_id, html, display_name, properties) =
5466
fake.chatsvc_posts.lock().unwrap().last().cloned().unwrap();
5467
assert_eq!(conversation_id, CHAT);
5468
assert_eq!(display_name, "Me Myself");
5469
let time = (base() + Duration::minutes(1)).timestamp_millis();
5470
let quote = format!(
5471
"<blockquote itemscope=\"\" itemtype=\"http://schema.skype.com/Reply\" itemid=\"m0001\"><strong itemprop=\"mri\" itemid=\"8:orgid:user-ada\">Ada Example</strong><span itemprop=\"time\" itemid=\"{time}\"></span><p itemprop=\"preview\">n1</p></blockquote>"
5472
);
5473
assert_eq!(
5474
html,
5475
format!(
5476
"{quote}<p>thanks <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada Example</span></p>"
5477
)
5478
);
5479
let mentions = json!([{
5480
"@type": "http://schema.skype.com/Mention",
5481
"itemid": "0",
5482
"mri": "8:orgid:user-ada",
5483
"mentionType": "person",
5484
"displayName": "Ada Example",
5485
}]);
5486
let quoted = json!([{"messageId": "m0001", "sender": "8:orgid:user-ada", "time": time}]);
5487
assert_eq!(
5488
properties,
5489
json!({
5490
"importance": "high",
5491
"links": "[]",
5492
"mentions": mentions.to_string(),
5493
"onbehalfof": null,
5494
"files": "[]",
5495
"qtdMsgs": quoted.to_string(),
5496
"formatVariant": "TEAMS",
5497
})
5498
);
5499
assert_eq!(sent.message_id, "1727203440000");
5500
assert_eq!(sent.reply_to_id, None);
5501
assert_eq!(sent.importance, store::MessageImportance::High);
5502
assert!(sent.body_html.starts_with("e));
5503
assert!(
5504
!fake
5505
.calls()
5506
.iter()
5507
.any(|call| call.starts_with("quote_reply"))
5508
);
5509
}
5510
5511
#[tokio::test]
5512
async fn a_quoted_chat_reply_with_an_image_stays_on_graph() {
5513
let fake = Arc::new(Fake::default());
5514
fake.set_chat_messages(numbered(2));
5515
let engine = chat_engine(&fake, small_pages()).await;
5516
engine.fetch_newer(CHAT).await.unwrap();
5517
let extras = MessageExtras {
5518
images: vec![HostedImage {
5519
content_type: "image/png".into(),
5520
bytes: Arc::new(vec![9]),
5521
}],
5522
..MessageExtras::default()
5523
};
5524
engine
5525
.reply_to_with_extras(CHAT, "m0001", "look", &[], &extras)
5526
.await
5527
.unwrap();
5528
assert!(fake.chatsvc_posts.lock().unwrap().is_empty());
5529
assert!(
5530
fake.calls()
5531
.contains(&format!("quote_reply {CHAT} m0001 look"))
5532
);
5533
}
5534
5535
#[tokio::test]
5536
async fn a_quoted_reply_to_an_unknown_message_stays_on_graph() {
5537
let fake = Arc::new(Fake::default());
5538
fake.set_chat_messages(numbered(2));
5539
let engine = chat_engine(&fake, small_pages()).await;
5540
engine.fetch_newer(CHAT).await.unwrap();
5541
engine.reply_to(CHAT, "m7777", "hi").await.unwrap();
5542
assert!(fake.chatsvc_posts.lock().unwrap().is_empty());
5543
assert!(
5544
fake.calls()
5545
.contains(&format!("quote_reply {CHAT} m7777 hi"))
5546
);
5547
}
5548
5442
5549
#[tokio::test]
5443
5550
async fn a_quoted_channel_reply_is_written_through_chatsvc_in_the_teams_quote_shape() {
5444
5551
let fake = Arc::new(Fake::default());
@@ -2395,7 +2395,7 @@ async fn the_notes_chat_takes_every_write_without_a_graph_chat_lookup() {2395
assert_eq!(fake.sent.lock().unwrap().as_slice(), ["note to self"]);2395
assert_eq!(fake.sent.lock().unwrap().as_slice(), ["note to self"]);2396
let calls = fake.calls();2396
let calls = fake.calls();2397
for expected in [2397
for expected in [2398
"quote_reply 48:notes m9000 again",2398
"chatsvc post 48:notes",2399
"edit m9000 edited",2399
"edit m9000 edited",2400
"set_reaction m9000 \u{1f44d}",2400
"set_reaction m9000 \u{1f44d}",2401
"unset_reaction m9000 \u{1f44d}",2401
"unset_reaction m9000 \u{1f44d}",@@ -3844,10 +3844,13 @@ async fn chat_reply_quotes_and_channel_reply_uses_the_thread_root() {3844
.reply_to(CHAT, "m0001", "answer **bold**")3844
.reply_to(CHAT, "m0001", "answer **bold**")3845
.await3845
.await3846
.unwrap();3846
.unwrap();3847
assert_eq!(sent.message_id, "m9003");3847
assert_eq!(sent.message_id, "1727203440000");3848
assert!(fake.calls().contains(&format!("chatsvc post {CHAT}")));3848
assert!(3849
assert!(3849
fake.calls()3850
!fake3850
.contains(&format!("quote_reply {CHAT} m0001 answer <b>bold</b>"))3851
.calls()3852
.iter()3853
.any(|call| call.starts_with("quote_reply"))3851
);3854
);3852
3855
3853
let channel_fake = Arc::new(Fake::default());3856
let channel_fake = Arc::new(Fake::default());@@ -5439,6 +5442,110 @@ async fn marking_the_notes_chat_read_takes_the_tenant_from_another_chat() {5439
);5442
);5440
}5443
}5441
5444
5445
#[tokio::test]5446
async fn a_quoted_chat_reply_is_written_through_chatsvc_in_the_teams_shape() {5447
let fake = Arc::new(Fake::default());5448
fake.set_chat_messages(numbered(2));5449
let engine = chat_engine(&fake, small_pages()).await;5450
engine.fetch_newer(CHAT).await.unwrap();5451
let extras = MessageExtras {5452
importance: Some("high"),5453
..MessageExtras::default()5454
};5455
let sent = engine5456
.reply_to_with_extras(5457
CHAT,5458
"m0001",5459
"<p>thanks @Ada Example</p>",5460
&[MentionInput::user("user-ada", "Ada Example")],5461
&extras,5462
)5463
.await5464
.unwrap();5465
let (conversation_id, html, display_name, properties) =5466
fake.chatsvc_posts.lock().unwrap().last().cloned().unwrap();5467
assert_eq!(conversation_id, CHAT);5468
assert_eq!(display_name, "Me Myself");5469
let time = (base() + Duration::minutes(1)).timestamp_millis();5470
let quote = format!(5471
"<blockquote itemscope=\"\" itemtype=\"http://schema.skype.com/Reply\" itemid=\"m0001\"><strong itemprop=\"mri\" itemid=\"8:orgid:user-ada\">Ada Example</strong><span itemprop=\"time\" itemid=\"{time}\"></span><p itemprop=\"preview\">n1</p></blockquote>"5472
);5473
assert_eq!(5474
html,5475
format!(5476
"{quote}<p>thanks <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada Example</span></p>"5477
)5478
);5479
let mentions = json!([{5480
"@type": "http://schema.skype.com/Mention",5481
"itemid": "0",5482
"mri": "8:orgid:user-ada",5483
"mentionType": "person",5484
"displayName": "Ada Example",5485
}]);5486
let quoted = json!([{"messageId": "m0001", "sender": "8:orgid:user-ada", "time": time}]);5487
assert_eq!(5488
properties,5489
json!({5490
"importance": "high",5491
"links": "[]",5492
"mentions": mentions.to_string(),5493
"onbehalfof": null,5494
"files": "[]",5495
"qtdMsgs": quoted.to_string(),5496
"formatVariant": "TEAMS",5497
})5498
);5499
assert_eq!(sent.message_id, "1727203440000");5500
assert_eq!(sent.reply_to_id, None);5501
assert_eq!(sent.importance, store::MessageImportance::High);5502
assert!(sent.body_html.starts_with("e));5503
assert!(5504
!fake5505
.calls()5506
.iter()5507
.any(|call| call.starts_with("quote_reply"))5508
);5509
}5510
5511
#[tokio::test]5512
async fn a_quoted_chat_reply_with_an_image_stays_on_graph() {5513
let fake = Arc::new(Fake::default());5514
fake.set_chat_messages(numbered(2));5515
let engine = chat_engine(&fake, small_pages()).await;5516
engine.fetch_newer(CHAT).await.unwrap();5517
let extras = MessageExtras {5518
images: vec![HostedImage {5519
content_type: "image/png".into(),5520
bytes: Arc::new(vec![9]),5521
}],5522
..MessageExtras::default()5523
};5524
engine5525
.reply_to_with_extras(CHAT, "m0001", "look", &[], &extras)5526
.await5527
.unwrap();5528
assert!(fake.chatsvc_posts.lock().unwrap().is_empty());5529
assert!(5530
fake.calls()5531
.contains(&format!("quote_reply {CHAT} m0001 look"))5532
);5533
}5534
5535
#[tokio::test]5536
async fn a_quoted_reply_to_an_unknown_message_stays_on_graph() {5537
let fake = Arc::new(Fake::default());5538
fake.set_chat_messages(numbered(2));5539
let engine = chat_engine(&fake, small_pages()).await;5540
engine.fetch_newer(CHAT).await.unwrap();5541
engine.reply_to(CHAT, "m7777", "hi").await.unwrap();5542
assert!(fake.chatsvc_posts.lock().unwrap().is_empty());5543
assert!(5544
fake.calls()5545
.contains(&format!("quote_reply {CHAT} m7777 hi"))5546
);5547
}5548
5442
#[tokio::test]5549
#[tokio::test]5443
async fn a_quoted_channel_reply_is_written_through_chatsvc_in_the_teams_quote_shape() {5550
async fn a_quoted_channel_reply_is_written_through_chatsvc_in_the_teams_quote_shape() {5444
let fake = Arc::new(Fake::default());5551
let fake = Arc::new(Fake::default());@@ -5,9 +5,9 @@ use base64::Engine;
5
5
use base64::engine::general_purpose::STANDARD;
6
6
use chrono::{DateTime, TimeZone, Utc};
7
7
use mcp::{
8
Access, AgentHub, AgentPolicy, EncodedImage, FileInfo, ForwardedInfo, ImageInfo, ImageKind, LinkInfo, Meeting,
9
MentionInfo, MessageExtras, Outcome, QuoteInfo, ReactionInfo, ServerHandle, SourceError,
10
SourceFuture, TeamsSource, Transcript, TranscriptTurn,
8
Access, AgentHub, AgentPolicy, EncodedImage, FileInfo, ForwardedInfo, ImageInfo, ImageKind,
9
LinkInfo, Meeting, MentionInfo, MessageExtras, Outcome, QuoteInfo, ReactionInfo, ServerHandle,
10
SourceError, SourceFuture, TeamsSource, Transcript, TranscriptTurn,
11
11
};
12
12
use rmcp::ServiceExt;
13
13
use rmcp::model::{CallToolRequestParams, CallToolResult, ClientConfig};
@@ -1026,14 +1026,11 @@ async fn recent_messages_unread_only_covers_chats_and_channels() {
1026
1026
1027
1027
harness
1028
1028
.store
1029
.upsert_channels(&[ChannelRecord {
1030
id: CHANNEL.to_owned(),
1031
team_id: "team-1".to_owned(),
1032
name: "General".to_owned(),
1033
membership_type: None,
1034
last_message_at: Some(Utc.with_ymd_and_hms(2026, 10, 6, 9, 6, 0).unwrap()),
1035
unread: true,
1036
}])
1029
.apply_channel_read_states(&[(
1030
CHANNEL.to_owned(),
1031
true,
1032
Some(Utc.with_ymd_and_hms(2026, 10, 6, 9, 6, 0).unwrap()),
1033
)])
1037
1034
.unwrap();
1038
1035
let (_, body) = call(&client, "recent_messages", arguments()).await;
1039
1036
assert_eq!(
@@ -5,9 +5,9 @@ use base64::Engine;5
use base64::engine::general_purpose::STANDARD;5
use base64::engine::general_purpose::STANDARD;6
use chrono::{DateTime, TimeZone, Utc};6
use chrono::{DateTime, TimeZone, Utc};7
use mcp::{7
use mcp::{8
Access, AgentHub, AgentPolicy, EncodedImage, FileInfo, ForwardedInfo, ImageInfo, ImageKind, LinkInfo, Meeting,8
Access, AgentHub, AgentPolicy, EncodedImage, FileInfo, ForwardedInfo, ImageInfo, ImageKind,9
MentionInfo, MessageExtras, Outcome, QuoteInfo, ReactionInfo, ServerHandle, SourceError,9
LinkInfo, Meeting, MentionInfo, MessageExtras, Outcome, QuoteInfo, ReactionInfo, ServerHandle,10
SourceFuture, TeamsSource, Transcript, TranscriptTurn,10
SourceError, SourceFuture, TeamsSource, Transcript, TranscriptTurn,11
};11
};12
use rmcp::ServiceExt;12
use rmcp::ServiceExt;13
use rmcp::model::{CallToolRequestParams, CallToolResult, ClientConfig};13
use rmcp::model::{CallToolRequestParams, CallToolResult, ClientConfig};@@ -1026,14 +1026,11 @@ async fn recent_messages_unread_only_covers_chats_and_channels() {1026
1026
1027
harness1027
harness1028
.store1028
.store1029
.upsert_channels(&[ChannelRecord {1029
.apply_channel_read_states(&[(1030
id: CHANNEL.to_owned(),1030
CHANNEL.to_owned(),1031
team_id: "team-1".to_owned(),1031
true,1032
name: "General".to_owned(),1032
Some(Utc.with_ymd_and_hms(2026, 10, 6, 9, 6, 0).unwrap()),1033
membership_type: None,1033
)])1034
last_message_at: Some(Utc.with_ymd_and_hms(2026, 10, 6, 9, 6, 0).unwrap()),1035
unread: true,1036
}])1037
.unwrap();1034
.unwrap();1038
let (_, body) = call(&client, "recent_messages", arguments()).await;1035
let (_, body) = call(&client, "recent_messages", arguments()).await;1039
assert_eq!(1036
assert_eq!(