Merge remote-tracking branch 'origin/main' into feat/rich-formatting
@@ -0,0 +1,34 @@
1
const COMMON_WORDS: &[&str] = &[
2
"a", "about", "account", "active", "admin", "after", "agent", "alert", "all", "also", "and", "answer", "any", "app",
3
"are", "art", "at", "audio", "auto", "away", "back", "bad", "band", "bank", "bass", "be", "bell", "best", "big",
4
"bird", "black", "block", "blue", "board", "bot", "box", "brown", "bug", "build", "busy", "but", "by", "call",
5
"camera", "can", "case", "cast", "center", "change", "channel", "chat", "check", "city", "class", "clear", "client",
6
"close", "code", "cold", "come", "conference", "connect", "connected", "contact", "cook", "core", "cost", "count",
7
"cross", "data", "date", "day", "de", "del", "demo", "den", "der", "des", "desk", "device", "die", "das",
8
"do", "door", "down", "drop", "du", "early", "east", "echo", "end", "error", "event", "fall", "fast", "field",
9
"file", "fine", "first", "fish", "for", "fox", "frame", "free", "from", "front", "full", "game", "gate",
10
"general", "get", "go", "gold", "good", "gray", "green", "grey", "group", "guest", "hall", "hand", "hard", "has",
11
"have", "head", "heat", "help", "here", "high", "hill", "hold", "home", "host", "hot", "house", "hub", "ice", "id",
12
"in", "info", "input", "is", "it", "join", "joined", "just", "key", "king", "lab", "lake", "land", "lane", "last",
13
"le", "lead", "left", "level", "light", "line", "link", "little", "live", "lobby", "local", "lock", "log", "long",
14
"loss", "low", "main", "major", "man", "mark", "master", "may", "media", "meet", "meeting", "member", "mic",
15
"mill", "mobile", "mode", "more", "moss", "mute", "muted", "my", "name", "net", "network", "new", "news",
16
"next", "night", "no", "none", "north", "not", "note", "now", "null", "of", "off", "office", "ok", "old", "on",
17
"one", "online", "only", "open", "or", "out", "output", "owner", "page", "park", "path", "peer", "phone", "pine",
18
"play", "pool", "port", "post", "power", "price", "pro", "queue", "quick", "rain", "ready", "red", "relay", "remote",
19
"reply", "report", "rich", "ring", "river", "road", "rock", "room", "rose", "rule", "run", "sales", "same", "screen",
20
"see", "self", "send", "server", "service", "session", "set", "share", "shared", "short", "side", "sign", "silver",
21
"small", "smart", "snow", "so", "sound", "south", "speaker", "speed", "spring", "staff", "stage", "star",
22
"start", "state", "status", "stone", "stop", "storm", "stream", "street", "strong", "summer", "support",
23
"system", "team", "teams", "tech", "test", "tester", "the", "time", "to", "top", "track", "true", "turn", "up",
24
"user", "van", "video", "view", "voice", "von", "wait", "wall", "ward", "water", "way", "web", "well", "west",
25
"white", "will", "win", "winter", "with", "wood", "word", "work", "world", "young", "your", "zu", "zum", "zur",
26
"max", "min", "rob", "ray", "pat", "eve", "jan", "feb", "mar", "apr", "jun", "jul", "aug", "sep",
27
"oct", "nov", "dec",
28
"mon", "tue", "wed", "thu", "fri", "sat", "sun", "am", "an", "auf", "aus", "bei", "ein", "eine", "im", "ist", "mit", "nach", "neu", "und", "vom",
29
];
30
31
pub fn is_common_word(word: &str) -> bool {
32
let lowered = word.to_lowercase();
33
COMMON_WORDS.contains(&lowered.as_str())
34
}
@@ -0,0 +1,34 @@1
const COMMON_WORDS: &[&str] = &[2
"a", "about", "account", "active", "admin", "after", "agent", "alert", "all", "also", "and", "answer", "any", "app",3
"are", "art", "at", "audio", "auto", "away", "back", "bad", "band", "bank", "bass", "be", "bell", "best", "big",4
"bird", "black", "block", "blue", "board", "bot", "box", "brown", "bug", "build", "busy", "but", "by", "call",5
"camera", "can", "case", "cast", "center", "change", "channel", "chat", "check", "city", "class", "clear", "client",6
"close", "code", "cold", "come", "conference", "connect", "connected", "contact", "cook", "core", "cost", "count",7
"cross", "data", "date", "day", "de", "del", "demo", "den", "der", "des", "desk", "device", "die", "das",8
"do", "door", "down", "drop", "du", "early", "east", "echo", "end", "error", "event", "fall", "fast", "field",9
"file", "fine", "first", "fish", "for", "fox", "frame", "free", "from", "front", "full", "game", "gate",10
"general", "get", "go", "gold", "good", "gray", "green", "grey", "group", "guest", "hall", "hand", "hard", "has",11
"have", "head", "heat", "help", "here", "high", "hill", "hold", "home", "host", "hot", "house", "hub", "ice", "id",12
"in", "info", "input", "is", "it", "join", "joined", "just", "key", "king", "lab", "lake", "land", "lane", "last",13
"le", "lead", "left", "level", "light", "line", "link", "little", "live", "lobby", "local", "lock", "log", "long",14
"loss", "low", "main", "major", "man", "mark", "master", "may", "media", "meet", "meeting", "member", "mic",15
"mill", "mobile", "mode", "more", "moss", "mute", "muted", "my", "name", "net", "network", "new", "news",16
"next", "night", "no", "none", "north", "not", "note", "now", "null", "of", "off", "office", "ok", "old", "on",17
"one", "online", "only", "open", "or", "out", "output", "owner", "page", "park", "path", "peer", "phone", "pine",18
"play", "pool", "port", "post", "power", "price", "pro", "queue", "quick", "rain", "ready", "red", "relay", "remote",19
"reply", "report", "rich", "ring", "river", "road", "rock", "room", "rose", "rule", "run", "sales", "same", "screen",20
"see", "self", "send", "server", "service", "session", "set", "share", "shared", "short", "side", "sign", "silver",21
"small", "smart", "snow", "so", "sound", "south", "speaker", "speed", "spring", "staff", "stage", "star",22
"start", "state", "status", "stone", "stop", "storm", "stream", "street", "strong", "summer", "support",23
"system", "team", "teams", "tech", "test", "tester", "the", "time", "to", "top", "track", "true", "turn", "up",24
"user", "van", "video", "view", "voice", "von", "wait", "wall", "ward", "water", "way", "web", "well", "west",25
"white", "will", "win", "winter", "with", "wood", "word", "work", "world", "young", "your", "zu", "zum", "zur",26
"max", "min", "rob", "ray", "pat", "eve", "jan", "feb", "mar", "apr", "jun", "jul", "aug", "sep",27
"oct", "nov", "dec",28
"mon", "tue", "wed", "thu", "fri", "sat", "sun", "am", "an", "auf", "aus", "bei", "ein", "eine", "im", "ist", "mit", "nach", "neu", "und", "vom",29
];30
31
pub fn is_common_word(word: &str) -> bool {32
let lowered = word.to_lowercase();33
COMMON_WORDS.contains(&lowered.as_str())34
}@@ -1,3 +1,4 @@
1
mod common_words;
1
2
mod document;
2
3
mod markdown;
3
4
mod scrub;
@@ -1,3 +1,4 @@1
mod common_words;1
mod document;2
mod document;2
mod markdown;3
mod markdown;3
mod scrub;4
mod scrub;@@ -3,6 +3,8 @@ use std::sync::LazyLock;
3
3
4
4
use regex::{Captures, Regex, escape};
5
5
6
use super::common_words::is_common_word;
7
6
8
pub const SELF_PLACEHOLDER: &str = "self";
7
9
pub const ECHO_PLACEHOLDER: &str = "echo-bot";
8
10
const ORGID_PREFIX: &str = "8:orgid:";
@@ -44,10 +46,27 @@ static IPV6: LazyLock<Regex> = LazyLock::new(|| {
44
46
static PHONE: LazyLock<Regex> = LazyLock::new(|| compiled(r"\+\d[\d ()\-/]{6,}\d"));
45
47
static OPAQUE: LazyLock<Regex> = LazyLock::new(|| compiled(r"[A-Za-z0-9+/_\-]{40,}={0,2}"));
46
48
49
#[derive(Debug, Clone)]
50
struct NameMatch {
51
name: String,
52
placeholder: String,
53
exact_case: bool,
54
}
55
56
impl NameMatch {
57
fn matches(&self, text: &str) -> bool {
58
if self.exact_case {
59
self.name == text
60
} else {
61
self.name.to_lowercase() == text.to_lowercase()
62
}
63
}
64
}
65
47
66
#[derive(Debug, Clone, Default)]
48
67
pub struct Scrubber {
49
68
people: HashMap<String, String>,
50
names: Vec<(String, String)>,
69
names: Vec<NameMatch>,
51
70
meetings: HashMap<String, String>,
52
71
identifiers: HashMap<String, String>,
53
72
person_count: usize,
@@ -69,7 +88,7 @@ impl Scrubber {
69
88
let placeholder = if mri == calling::signaling::ECHO_BOT_MRI {
70
89
self.alias(mri, ECHO_PLACEHOLDER);
71
90
if !display_name.trim().is_empty() {
72
self.names.push((display_name.to_owned(), ECHO_PLACEHOLDER.to_owned()));
91
self.push_name(display_name, ECHO_PLACEHOLDER, false);
73
92
}
74
93
return;
75
94
} else if mri.is_empty() {
@@ -103,19 +122,29 @@ impl Scrubber {
103
122
if name.trim().is_empty() {
104
123
return;
105
124
}
106
let mut candidates = vec![name.to_owned()];
107
candidates.extend(
108
name.split(|character: char| !character.is_alphanumeric())
109
.filter(|part| part.chars().count() >= MIN_NAME_PART)
110
.map(str::to_owned),
111
);
112
for candidate in candidates {
113
if !self.names.iter().any(|(known, _)| known.eq_ignore_ascii_case(&candidate)) {
114
self.names.push((candidate, placeholder.to_owned()));
115
}
125
let full_name = name.trim();
126
let parts: Vec<&str> =
127
full_name.split(|character: char| !character.is_alphanumeric()).filter(|part| !part.is_empty()).collect();
128
if full_name.chars().count() > 1 {
129
self.push_name(full_name, placeholder, parts.len() == 1 && is_common_word(full_name));
130
}
131
for part in parts.into_iter().filter(|part| is_name_part(part)) {
132
self.push_name(part, placeholder, is_common_word(part));
116
133
}
117
134
}
118
135
136
/// `exact_case`: a dictionary word only counts as the name in the name's own spelling ("Mark", not "mark").
137
fn push_name(&mut self, name: &str, placeholder: &str, exact_case: bool) {
138
if self.names.iter().any(|known| known.name.eq_ignore_ascii_case(name)) {
139
return;
140
}
141
self.names.push(NameMatch {
142
name: name.to_owned(),
143
placeholder: placeholder.to_owned(),
144
exact_case,
145
});
146
}
147
119
148
pub fn scrub(&mut self, text: &str) -> String {
120
149
let mut text = URL.replace_all(text, |captures: &Captures| scrub_url(&captures[0])).into_owned();
121
150
text = JWT.replace_all(&text, REMOVED).into_owned();
@@ -154,25 +183,33 @@ impl Scrubber {
154
183
if self.names.is_empty() {
155
184
return text.to_owned();
156
185
}
157
let mut ordered: Vec<&(String, String)> = self.names.iter().collect();
158
ordered.sort_by_key(|(name, _)| std::cmp::Reverse(name.chars().count()));
159
let alternatives: Vec<String> = ordered.iter().map(|(name, _)| escape(name)).collect();
160
let pattern = format!(r"(?i)\b(?:{})\b", alternatives.join("|"));
186
let mut ordered: Vec<&NameMatch> = self.names.iter().collect();
187
ordered.sort_by_key(|entry| std::cmp::Reverse(entry.name.chars().count()));
188
let alternatives: Vec<String> = ordered
189
.iter()
190
.map(|entry| if entry.exact_case { escape(&entry.name) } else { format!("(?i:{})", escape(&entry.name)) })
191
.collect();
192
let pattern = format!(r"\b(?:{})\b", alternatives.join("|"));
161
193
let Ok(names) = Regex::new(&pattern) else {
162
194
return text.to_owned();
163
195
};
164
196
names
165
197
.replace_all(text, |captures: &Captures| {
166
let matched = captures[0].to_lowercase();
167
198
ordered
168
199
.iter()
169
.find(|(name, _)| name.to_lowercase() == matched)
170
.map_or_else(|| REMOVED.to_owned(), |(_, placeholder)| placeholder.clone())
200
.find(|entry| entry.matches(&captures[0]))
201
.map_or_else(|| REMOVED.to_owned(), |entry| entry.placeholder.clone())
171
202
})
172
203
.into_owned()
173
204
}
174
205
}
175
206
207
fn is_name_part(part: &str) -> bool {
208
part.chars().count() >= MIN_NAME_PART
209
&& !part.chars().all(|character| character.is_ascii_digit())
210
&& (!is_common_word(part) || part.chars().next().is_some_and(char::is_uppercase))
211
}
212
176
213
fn normalize(key: &str) -> String {
177
214
key.trim().to_lowercase()
178
215
}
@@ -278,6 +315,48 @@ meeting id 12345678-aaaa-bbbb-cccc-1234567890ab at 12:30:45.";
278
315
assert_eq!(scrubber.scrub(text), text);
279
316
}
280
317
318
#[test]
319
fn common_words_in_a_name_are_only_replaced_in_the_names_spelling() {
320
let mut scrubber = Scrubber::new();
321
scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Check Testperson");
322
scrubber.register_person("8:orgid:99999999-8888-7777-6666-555555555555", "Max Video");
323
assert_eq!(
324
scrubber.scrub("check video max bitrate, Check Testperson and Max Video joined, testperson left"),
325
"check video max bitrate, person-1 and person-2 joined, person-1 left"
326
);
327
}
328
329
#[test]
330
fn name_parts_match_only_whole_words() {
331
let mut scrubber = Scrubber::new();
332
scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Quilla Brandtmoor");
333
assert_eq!(
334
scrubber.scrub("Quillay quilla Brandtmoorish BRANDTMOOR"),
335
"Quillay person-1 Brandtmoorish person-1"
336
);
337
}
338
339
#[test]
340
fn short_and_numeric_name_parts_are_ignored() {
341
let mut scrubber = Scrubber::new();
342
scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Yu Zentrel 2024");
343
assert_eq!(scrubber.scrub("yu 2024 Zentrel Yu Zentrel 2024"), "yu 2024 person-1 person-1");
344
}
345
346
#[test]
347
fn a_single_word_common_name_is_replaced_only_in_its_spelling() {
348
let mut scrubber = Scrubber::new();
349
scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Test");
350
assert_eq!(scrubber.scrub("test call Test"), "test call person-1");
351
}
352
353
#[test]
354
fn a_given_name_that_is_a_word_is_still_replaced_when_capitalized() {
355
let mut scrubber = Scrubber::new();
356
scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Mark Zentrel");
357
assert_eq!(scrubber.scrub("Mark joined, mark the stream"), "person-1 joined, mark the stream");
358
}
359
281
360
#[test]
282
361
fn the_echo_bot_is_named_not_numbered() {
283
362
let mut scrubber = Scrubber::new();
@@ -3,6 +3,8 @@ use std::sync::LazyLock;3
3
4
use regex::{Captures, Regex, escape};4
use regex::{Captures, Regex, escape};5
5
6
use super::common_words::is_common_word;7
6
pub const SELF_PLACEHOLDER: &str = "self";8
pub const SELF_PLACEHOLDER: &str = "self";7
pub const ECHO_PLACEHOLDER: &str = "echo-bot";9
pub const ECHO_PLACEHOLDER: &str = "echo-bot";8
const ORGID_PREFIX: &str = "8:orgid:";10
const ORGID_PREFIX: &str = "8:orgid:";@@ -44,10 +46,27 @@ static IPV6: LazyLock<Regex> = LazyLock::new(|| {44
static PHONE: LazyLock<Regex> = LazyLock::new(|| compiled(r"\+\d[\d ()\-/]{6,}\d"));46
static PHONE: LazyLock<Regex> = LazyLock::new(|| compiled(r"\+\d[\d ()\-/]{6,}\d"));45
static OPAQUE: LazyLock<Regex> = LazyLock::new(|| compiled(r"[A-Za-z0-9+/_\-]{40,}={0,2}"));47
static OPAQUE: LazyLock<Regex> = LazyLock::new(|| compiled(r"[A-Za-z0-9+/_\-]{40,}={0,2}"));46
48
49
#[derive(Debug, Clone)]50
struct NameMatch {51
name: String,52
placeholder: String,53
exact_case: bool,54
}55
56
impl NameMatch {57
fn matches(&self, text: &str) -> bool {58
if self.exact_case {59
self.name == text60
} else {61
self.name.to_lowercase() == text.to_lowercase()62
}63
}64
}65
47
#[derive(Debug, Clone, Default)]66
#[derive(Debug, Clone, Default)]48
pub struct Scrubber {67
pub struct Scrubber {49
people: HashMap<String, String>,68
people: HashMap<String, String>,50
names: Vec<(String, String)>,69
names: Vec<NameMatch>,51
meetings: HashMap<String, String>,70
meetings: HashMap<String, String>,52
identifiers: HashMap<String, String>,71
identifiers: HashMap<String, String>,53
person_count: usize,72
person_count: usize,@@ -69,7 +88,7 @@ impl Scrubber {69
let placeholder = if mri == calling::signaling::ECHO_BOT_MRI {88
let placeholder = if mri == calling::signaling::ECHO_BOT_MRI {70
self.alias(mri, ECHO_PLACEHOLDER);89
self.alias(mri, ECHO_PLACEHOLDER);71
if !display_name.trim().is_empty() {90
if !display_name.trim().is_empty() {72
self.names.push((display_name.to_owned(), ECHO_PLACEHOLDER.to_owned()));91
self.push_name(display_name, ECHO_PLACEHOLDER, false);73
}92
}74
return;93
return;75
} else if mri.is_empty() {94
} else if mri.is_empty() {@@ -103,19 +122,29 @@ impl Scrubber {103
if name.trim().is_empty() {122
if name.trim().is_empty() {104
return;123
return;105
}124
}106
let mut candidates = vec![name.to_owned()];125
let full_name = name.trim();107
candidates.extend(126
let parts: Vec<&str> =108
name.split(|character: char| !character.is_alphanumeric())127
full_name.split(|character: char| !character.is_alphanumeric()).filter(|part| !part.is_empty()).collect();109
.filter(|part| part.chars().count() >= MIN_NAME_PART)128
if full_name.chars().count() > 1 {110
.map(str::to_owned),129
self.push_name(full_name, placeholder, parts.len() == 1 && is_common_word(full_name));111
);130
}112
for candidate in candidates {131
for part in parts.into_iter().filter(|part| is_name_part(part)) {113
if !self.names.iter().any(|(known, _)| known.eq_ignore_ascii_case(&candidate)) {132
self.push_name(part, placeholder, is_common_word(part));114
self.names.push((candidate, placeholder.to_owned()));115
}116
}133
}117
}134
}118
135
136
/// `exact_case`: a dictionary word only counts as the name in the name's own spelling ("Mark", not "mark").137
fn push_name(&mut self, name: &str, placeholder: &str, exact_case: bool) {138
if self.names.iter().any(|known| known.name.eq_ignore_ascii_case(name)) {139
return;140
}141
self.names.push(NameMatch {142
name: name.to_owned(),143
placeholder: placeholder.to_owned(),144
exact_case,145
});146
}147
119
pub fn scrub(&mut self, text: &str) -> String {148
pub fn scrub(&mut self, text: &str) -> String {120
let mut text = URL.replace_all(text, |captures: &Captures| scrub_url(&captures[0])).into_owned();149
let mut text = URL.replace_all(text, |captures: &Captures| scrub_url(&captures[0])).into_owned();121
text = JWT.replace_all(&text, REMOVED).into_owned();150
text = JWT.replace_all(&text, REMOVED).into_owned();@@ -154,25 +183,33 @@ impl Scrubber {154
if self.names.is_empty() {183
if self.names.is_empty() {155
return text.to_owned();184
return text.to_owned();156
}185
}157
let mut ordered: Vec<&(String, String)> = self.names.iter().collect();186
let mut ordered: Vec<&NameMatch> = self.names.iter().collect();158
ordered.sort_by_key(|(name, _)| std::cmp::Reverse(name.chars().count()));187
ordered.sort_by_key(|entry| std::cmp::Reverse(entry.name.chars().count()));159
let alternatives: Vec<String> = ordered.iter().map(|(name, _)| escape(name)).collect();188
let alternatives: Vec<String> = ordered160
let pattern = format!(r"(?i)\b(?:{})\b", alternatives.join("|"));189
.iter()190
.map(|entry| if entry.exact_case { escape(&entry.name) } else { format!("(?i:{})", escape(&entry.name)) })191
.collect();192
let pattern = format!(r"\b(?:{})\b", alternatives.join("|"));161
let Ok(names) = Regex::new(&pattern) else {193
let Ok(names) = Regex::new(&pattern) else {162
return text.to_owned();194
return text.to_owned();163
};195
};164
names196
names165
.replace_all(text, |captures: &Captures| {197
.replace_all(text, |captures: &Captures| {166
let matched = captures[0].to_lowercase();167
ordered198
ordered168
.iter()199
.iter()169
.find(|(name, _)| name.to_lowercase() == matched)200
.find(|entry| entry.matches(&captures[0]))170
.map_or_else(|| REMOVED.to_owned(), |(_, placeholder)| placeholder.clone())201
.map_or_else(|| REMOVED.to_owned(), |entry| entry.placeholder.clone())171
})202
})172
.into_owned()203
.into_owned()173
}204
}174
}205
}175
206
207
fn is_name_part(part: &str) -> bool {208
part.chars().count() >= MIN_NAME_PART209
&& !part.chars().all(|character| character.is_ascii_digit())210
&& (!is_common_word(part) || part.chars().next().is_some_and(char::is_uppercase))211
}212
176
fn normalize(key: &str) -> String {213
fn normalize(key: &str) -> String {177
key.trim().to_lowercase()214
key.trim().to_lowercase()178
}215
}@@ -278,6 +315,48 @@ meeting id 12345678-aaaa-bbbb-cccc-1234567890ab at 12:30:45.";278
assert_eq!(scrubber.scrub(text), text);315
assert_eq!(scrubber.scrub(text), text);279
}316
}280
317
318
#[test]319
fn common_words_in_a_name_are_only_replaced_in_the_names_spelling() {320
let mut scrubber = Scrubber::new();321
scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Check Testperson");322
scrubber.register_person("8:orgid:99999999-8888-7777-6666-555555555555", "Max Video");323
assert_eq!(324
scrubber.scrub("check video max bitrate, Check Testperson and Max Video joined, testperson left"),325
"check video max bitrate, person-1 and person-2 joined, person-1 left"326
);327
}328
329
#[test]330
fn name_parts_match_only_whole_words() {331
let mut scrubber = Scrubber::new();332
scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Quilla Brandtmoor");333
assert_eq!(334
scrubber.scrub("Quillay quilla Brandtmoorish BRANDTMOOR"),335
"Quillay person-1 Brandtmoorish person-1"336
);337
}338
339
#[test]340
fn short_and_numeric_name_parts_are_ignored() {341
let mut scrubber = Scrubber::new();342
scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Yu Zentrel 2024");343
assert_eq!(scrubber.scrub("yu 2024 Zentrel Yu Zentrel 2024"), "yu 2024 person-1 person-1");344
}345
346
#[test]347
fn a_single_word_common_name_is_replaced_only_in_its_spelling() {348
let mut scrubber = Scrubber::new();349
scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Test");350
assert_eq!(scrubber.scrub("test call Test"), "test call person-1");351
}352
353
#[test]354
fn a_given_name_that_is_a_word_is_still_replaced_when_capitalized() {355
let mut scrubber = Scrubber::new();356
scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Mark Zentrel");357
assert_eq!(scrubber.scrub("Mark joined, mark the stream"), "person-1 joined, mark the stream");358
}359
281
#[test]360
#[test]282
fn the_echo_bot_is_named_not_numbered() {361
fn the_echo_bot_is_named_not_numbered() {283
let mut scrubber = Scrubber::new();362
let mut scrubber = Scrubber::new();@@ -441,6 +441,7 @@ impl CallEngine {
441
441
pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {
442
442
let inner = self.inner.as_ref();
443
443
let _one_call_at_a_time = if options.concurrent { None } else { Some(inner.gate.lock().await) };
444
let _trouter_tab_stays = inner.session.hold_tab(session::App::Teams);
444
445
let timeline = Timeline::new(options.trace);
445
446
let mut report = CallReport::default();
446
447
let mut state = CallState::Idle;
@@ -441,6 +441,7 @@ impl CallEngine {441
pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {441
pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {442
let inner = self.inner.as_ref();442
let inner = self.inner.as_ref();443
let _one_call_at_a_time = if options.concurrent { None } else { Some(inner.gate.lock().await) };443
let _one_call_at_a_time = if options.concurrent { None } else { Some(inner.gate.lock().await) };444
let _trouter_tab_stays = inner.session.hold_tab(session::App::Teams);444
let timeline = Timeline::new(options.trace);445
let timeline = Timeline::new(options.trace);445
let mut report = CallReport::default();446
let mut report = CallReport::default();446
let mut state = CallState::Idle;447
let mut state = CallState::Idle;@@ -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,38 @@ 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 MentionTarget::User { user_id } = &mention.target else {
70
return None;
71
};
72
Some(json!({
73
"@type": MENTION_ITEMTYPE,
74
"itemid": mention.id.to_string(),
75
"mri": user_mri(user_id),
76
"mentionType": "person",
77
"displayName": mention.text,
78
}))
69
79
}
70
80
71
81
pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) -> String {
@@ -82,8 +92,19 @@ pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) ->
82
92
converted.replace("</at>", "</span>")
83
93
}
84
94
95
fn sender_mri(record: &MessageRecord) -> Option<String> {
96
match (&record.sender_id, &record.sender_application_id) {
97
(Some(user_id), _) => Some(user_mri(user_id)),
98
(None, Some(application_id)) if application_id.contains(':') => {
99
Some(application_id.clone())
100
}
101
(None, Some(application_id)) => Some(format!("{BOT_PREFIX}{application_id}")),
102
(None, None) => None,
103
}
104
}
105
85
106
fn user_mri(user_id: &str) -> String {
86
if user_id.starts_with("8:") {
107
if user_id.contains(':') {
87
108
user_id.to_owned()
88
109
} else {
89
110
format!("{ORGID_PREFIX}{user_id}")
@@ -102,12 +123,32 @@ mod tests {
102
123
}
103
124
}
104
125
105
#[test]
106
fn person_mentions_become_teams_spans_and_a_mentions_property() {
107
let quote = TeamsQuote {
126
fn quote() -> TeamsQuote {
127
TeamsQuote {
108
128
html: String::new(),
109
129
quoted_message: json!({"messageId": "1"}),
110
};
130
}
131
}
132
133
#[test]
134
fn a_quote_reply_gets_the_teams_property_set() {
135
let properties = quote_reply_properties("e(), &[], None).unwrap();
136
assert_eq!(
137
properties,
138
json!({
139
"importance": "",
140
"links": "[]",
141
"mentions": "[]",
142
"onbehalfof": null,
143
"files": "[]",
144
"qtdMsgs": "[{\"messageId\":\"1\"}]",
145
"formatVariant": "TEAMS",
146
})
147
);
148
}
149
150
#[test]
151
fn person_mentions_become_teams_spans_and_a_mentions_property() {
111
152
let mentions = [mention(
112
153
0,
113
154
MentionTarget::User {
@@ -119,27 +160,49 @@ mod tests {
119
160
html,
120
161
"hi <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada</span>"
121
162
);
122
let properties = quote_reply_properties("e, &mentions, Some("high")).unwrap();
163
let properties = quote_reply_properties("e(), &mentions, Some("high")).unwrap();
123
164
assert_eq!(properties["importance"], "high");
124
165
assert_eq!(properties["qtdMsgs"], "[{\"messageId\":\"1\"}]");
125
166
let entries: Value =
126
167
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");
168
assert_eq!(
169
entries,
170
json!([{
171
"@type": "http://schema.skype.com/Mention",
172
"itemid": "0",
173
"mri": "8:orgid:user-ada",
174
"mentionType": "person",
175
"displayName": "Ada",
176
}])
177
);
129
178
}
130
179
131
180
#[test]
132
fn a_channel_mention_has_no_chatsvc_shape() {
133
let quote = TeamsQuote {
134
html: String::new(),
135
quoted_message: Value::Null,
136
};
137
let mentions = [mention(
138
0,
181
fn channel_and_team_mentions_have_no_chatsvc_shape() {
182
for target in [
139
183
MentionTarget::Channel {
140
channel_id: "19:c".into(),
184
channel_id: "19:c@thread.tacv2".into(),
141
185
},
142
)];
143
assert!(quote_reply_properties("e, &mentions, None).is_none());
186
MentionTarget::Team {
187
team_id: "team-1".into(),
188
},
189
] {
190
let mentions = [mention(0, target)];
191
assert!(quote_reply_properties("e(), &mentions, None).is_none());
192
}
193
}
194
195
#[test]
196
fn a_bot_sender_is_quoted_with_its_28_mri() {
197
let record = MessageRecord {
198
message_id: "5".into(),
199
sender_name: Some("Echo".into()),
200
sender_application_id: Some("app-1".into()),
201
body_html: "<p>pong</p>".into(),
202
..MessageRecord::default()
203
};
204
let quote = teams_quote(&record).unwrap();
205
assert_eq!(quote.quoted_message["sender"], "28:app-1");
206
assert!(quote.html.contains("itemid=\"28:app-1\">Echo</strong>"));
144
207
}
145
208
}
@@ -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,38 @@ 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 MentionTarget::User { user_id } = &mention.target else {57
"@type": MENTION_ITEMTYPE,70
return None;58
"itemid": mention.id,71
};59
"mri": user_mri(user_id),72
Some(json!({60
"mentionType": "person",73
"@type": MENTION_ITEMTYPE,61
"displayName": mention.text,74
"itemid": mention.id.to_string(),62
})),75
"mri": user_mri(user_id),63
MentionTarget::Channel { .. } | MentionTarget::Team { .. } => None,76
"mentionType": "person",64
})77
"displayName": mention.text,65
.collect::<Option<Vec<_>>>()?;78
}))66
properties["mentions"] = json!(Value::Array(entries).to_string());67
}68
Some(properties)69
}79
}70
80
71
pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) -> String {81
pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) -> String {@@ -82,8 +92,19 @@ pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) ->82
converted.replace("</at>", "</span>")92
converted.replace("</at>", "</span>")83
}93
}84
94
95
fn sender_mri(record: &MessageRecord) -> Option<String> {96
match (&record.sender_id, &record.sender_application_id) {97
(Some(user_id), _) => Some(user_mri(user_id)),98
(None, Some(application_id)) if application_id.contains(':') => {99
Some(application_id.clone())100
}101
(None, Some(application_id)) => Some(format!("{BOT_PREFIX}{application_id}")),102
(None, None) => None,103
}104
}105
85
fn user_mri(user_id: &str) -> String {106
fn user_mri(user_id: &str) -> String {86
if user_id.starts_with("8:") {107
if user_id.contains(':') {87
user_id.to_owned()108
user_id.to_owned()88
} else {109
} else {89
format!("{ORGID_PREFIX}{user_id}")110
format!("{ORGID_PREFIX}{user_id}")@@ -102,12 +123,32 @@ mod tests {102
}123
}103
}124
}104
125
105
#[test]126
fn quote() -> TeamsQuote {106
fn person_mentions_become_teams_spans_and_a_mentions_property() {127
TeamsQuote {107
let quote = TeamsQuote {108
html: String::new(),128
html: String::new(),109
quoted_message: json!({"messageId": "1"}),129
quoted_message: json!({"messageId": "1"}),110
};130
}131
}132
133
#[test]134
fn a_quote_reply_gets_the_teams_property_set() {135
let properties = quote_reply_properties("e(), &[], None).unwrap();136
assert_eq!(137
properties,138
json!({139
"importance": "",140
"links": "[]",141
"mentions": "[]",142
"onbehalfof": null,143
"files": "[]",144
"qtdMsgs": "[{\"messageId\":\"1\"}]",145
"formatVariant": "TEAMS",146
})147
);148
}149
150
#[test]151
fn person_mentions_become_teams_spans_and_a_mentions_property() {111
let mentions = [mention(152
let mentions = [mention(112
0,153
0,113
MentionTarget::User {154
MentionTarget::User {@@ -119,27 +160,49 @@ mod tests {119
html,160
html,120
"hi <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada</span>"161
"hi <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada</span>"121
);162
);122
let properties = quote_reply_properties("e, &mentions, Some("high")).unwrap();163
let properties = quote_reply_properties("e(), &mentions, Some("high")).unwrap();123
assert_eq!(properties["importance"], "high");164
assert_eq!(properties["importance"], "high");124
assert_eq!(properties["qtdMsgs"], "[{\"messageId\":\"1\"}]");165
assert_eq!(properties["qtdMsgs"], "[{\"messageId\":\"1\"}]");125
let entries: Value =166
let entries: Value =126
serde_json::from_str(properties["mentions"].as_str().unwrap()).unwrap();167
serde_json::from_str(properties["mentions"].as_str().unwrap()).unwrap();127
assert_eq!(entries[0]["mri"], "8:orgid:user-ada");168
assert_eq!(128
assert_eq!(entries[0]["mentionType"], "person");169
entries,170
json!([{171
"@type": "http://schema.skype.com/Mention",172
"itemid": "0",173
"mri": "8:orgid:user-ada",174
"mentionType": "person",175
"displayName": "Ada",176
}])177
);129
}178
}130
179
131
#[test]180
#[test]132
fn a_channel_mention_has_no_chatsvc_shape() {181
fn channel_and_team_mentions_have_no_chatsvc_shape() {133
let quote = TeamsQuote {182
for target in [134
html: String::new(),135
quoted_message: Value::Null,136
};137
let mentions = [mention(138
0,139
MentionTarget::Channel {183
MentionTarget::Channel {140
channel_id: "19:c".into(),184
channel_id: "19:c@thread.tacv2".into(),141
},185
},142
)];186
MentionTarget::Team {143
assert!(quote_reply_properties("e, &mentions, None).is_none());187
team_id: "team-1".into(),188
},189
] {190
let mentions = [mention(0, target)];191
assert!(quote_reply_properties("e(), &mentions, None).is_none());192
}193
}194
195
#[test]196
fn a_bot_sender_is_quoted_with_its_28_mri() {197
let record = MessageRecord {198
message_id: "5".into(),199
sender_name: Some("Echo".into()),200
sender_application_id: Some("app-1".into()),201
body_html: "<p>pong</p>".into(),202
..MessageRecord::default()203
};204
let quote = teams_quote(&record).unwrap();205
assert_eq!(quote.quoted_message["sender"], "28:app-1");206
assert!(quote.html.contains("itemid=\"28:app-1\">Echo</strong>"));144
}207
}145
}208
}@@ -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!(@@ -14,5 +14,5 @@ pub use events::{TabChannel, TabCommand, TabControl, TabEvent, TabEvents};
14
14
pub use page_script::token_acquirer_script;
15
15
pub use request::{ApiResponse, BodyToken, Method, Request};
16
16
pub use scope::{GRAPH, IC3, OUTLOOK, PRESENCE, SPACES, Scope};
17
pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig};
17
pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold};
18
18
pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};
@@ -14,5 +14,5 @@ pub use events::{TabChannel, TabCommand, TabControl, TabEvent, TabEvents};14
pub use page_script::token_acquirer_script;14
pub use page_script::token_acquirer_script;15
pub use request::{ApiResponse, BodyToken, Method, Request};15
pub use request::{ApiResponse, BodyToken, Method, Request};16
pub use scope::{GRAPH, IC3, OUTLOOK, PRESENCE, SPACES, Scope};16
pub use scope::{GRAPH, IC3, OUTLOOK, PRESENCE, SPACES, Scope};17
pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig};17
pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold};18
pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};18
pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};@@ -139,6 +139,15 @@ impl Session {
139
139
Ok(results.into_iter().flatten().collect())
140
140
}
141
141
142
/// Keeps the app tab where it is until the guard drops, e.g. for the length of a call.
143
pub fn hold_tab(&self, app: App) -> TabHold {
144
self.transport.hold(app, true);
145
TabHold {
146
transport: self.transport.clone(),
147
app,
148
}
149
}
150
142
151
pub async fn close(&self) {
143
152
self.drop_all().await;
144
153
}
@@ -270,6 +279,17 @@ impl Session {
270
279
}
271
280
}
272
281
282
pub struct TabHold {
283
transport: Arc<dyn Transport>,
284
app: App,
285
}
286
287
impl Drop for TabHold {
288
fn drop(&mut self) {
289
self.transport.hold(self.app, false);
290
}
291
}
292
273
293
pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
274
294
header
275
295
.and_then(|value| value.trim().parse::<f64>().ok())
@@ -280,7 +300,47 @@ pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
280
300
281
301
#[cfg(test)]
282
302
mod tests {
303
use std::sync::Mutex as StdMutex;
304
283
305
use super::*;
306
use crate::transport::{BoxFuture, Diagnosis, OpenedTab};
307
308
#[derive(Default)]
309
struct HoldRecorder {
310
holds: StdMutex<Vec<(App, bool)>>,
311
}
312
313
impl Transport for HoldRecorder {
314
fn check(&self) -> BoxFuture<'_, Result<()>> {
315
Box::pin(async { Ok(()) })
316
}
317
318
fn open(&self, _app: App, _with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>> {
319
Box::pin(async { Ok(None) })
320
}
321
322
fn wake(&self, _app: App) -> BoxFuture<'_, Result<()>> {
323
Box::pin(async { Ok(()) })
324
}
325
326
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {
327
Box::pin(async { Ok(Diagnosis::default()) })
328
}
329
330
fn hold(&self, app: App, held: bool) {
331
self.holds.lock().unwrap().push((app, held));
332
}
333
}
334
335
#[tokio::test]
336
async fn tab_hold_releases_the_tab_when_dropped() {
337
let recorder = Arc::new(HoldRecorder::default());
338
let session = Session::with_transport(recorder.clone(), SessionConfig::default()).await.unwrap();
339
let hold = session.hold_tab(App::Teams);
340
assert_eq!(*recorder.holds.lock().unwrap(), vec![(App::Teams, true)]);
341
drop(hold);
342
assert_eq!(*recorder.holds.lock().unwrap(), vec![(App::Teams, true), (App::Teams, false)]);
343
}
284
344
285
345
#[test]
286
346
fn retry_after_seconds_parse() {
@@ -139,6 +139,15 @@ impl Session {139
Ok(results.into_iter().flatten().collect())139
Ok(results.into_iter().flatten().collect())140
}140
}141
141
142
/// Keeps the app tab where it is until the guard drops, e.g. for the length of a call.143
pub fn hold_tab(&self, app: App) -> TabHold {144
self.transport.hold(app, true);145
TabHold {146
transport: self.transport.clone(),147
app,148
}149
}150
142
pub async fn close(&self) {151
pub async fn close(&self) {143
self.drop_all().await;152
self.drop_all().await;144
}153
}@@ -270,6 +279,17 @@ impl Session {270
}279
}271
}280
}272
281
282
pub struct TabHold {283
transport: Arc<dyn Transport>,284
app: App,285
}286
287
impl Drop for TabHold {288
fn drop(&mut self) {289
self.transport.hold(self.app, false);290
}291
}292
273
pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {293
pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {274
header294
header275
.and_then(|value| value.trim().parse::<f64>().ok())295
.and_then(|value| value.trim().parse::<f64>().ok())@@ -280,7 +300,47 @@ pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {280
300
281
#[cfg(test)]301
#[cfg(test)]282
mod tests {302
mod tests {303
use std::sync::Mutex as StdMutex;304
283
use super::*;305
use super::*;306
use crate::transport::{BoxFuture, Diagnosis, OpenedTab};307
308
#[derive(Default)]309
struct HoldRecorder {310
holds: StdMutex<Vec<(App, bool)>>,311
}312
313
impl Transport for HoldRecorder {314
fn check(&self) -> BoxFuture<'_, Result<()>> {315
Box::pin(async { Ok(()) })316
}317
318
fn open(&self, _app: App, _with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>> {319
Box::pin(async { Ok(None) })320
}321
322
fn wake(&self, _app: App) -> BoxFuture<'_, Result<()>> {323
Box::pin(async { Ok(()) })324
}325
326
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {327
Box::pin(async { Ok(Diagnosis::default()) })328
}329
330
fn hold(&self, app: App, held: bool) {331
self.holds.lock().unwrap().push((app, held));332
}333
}334
335
#[tokio::test]336
async fn tab_hold_releases_the_tab_when_dropped() {337
let recorder = Arc::new(HoldRecorder::default());338
let session = Session::with_transport(recorder.clone(), SessionConfig::default()).await.unwrap();339
let hold = session.hold_tab(App::Teams);340
assert_eq!(*recorder.holds.lock().unwrap(), vec![(App::Teams, true)]);341
drop(hold);342
assert_eq!(*recorder.holds.lock().unwrap(), vec![(App::Teams, true), (App::Teams, false)]);343
}284
344
285
#[test]345
#[test]286
fn retry_after_seconds_parse() {346
fn retry_after_seconds_parse() {@@ -28,6 +28,9 @@ pub trait Transport: Send + Sync {
28
28
fn wake(&self, app: App) -> BoxFuture<'_, Result<()>>;
29
29
30
30
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>>;
31
32
/// While held the host must not navigate the app on its own (no parking).
33
fn hold(&self, _app: App, _held: bool) {}
31
34
}
32
35
33
36
pub struct CdpTransport {
@@ -28,6 +28,9 @@ pub trait Transport: Send + Sync {28
fn wake(&self, app: App) -> BoxFuture<'_, Result<()>>;28
fn wake(&self, app: App) -> BoxFuture<'_, Result<()>>;29
29
30
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>>;30
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>>;31
32
/// While held the host must not navigate the app on its own (no parking).33
fn hold(&self, _app: App, _held: bool) {}31
}34
}32
35
33
pub struct CdpTransport {36
pub struct CdpTransport {@@ -0,0 +1,93 @@
1
use serde_json::Value;
2
use session::{App, is_login_url};
3
4
/// Coarse state of the app tab for error reports, never the URL itself.
5
pub(crate) fn tab_state(app: App, url: &str) -> &'static str {
6
if url.is_empty() {
7
"no document"
8
} else if app.is_park_url(url) {
9
"parked"
10
} else if is_login_url(url) {
11
"login"
12
} else if app.origins().iter().any(|origin| url.starts_with(origin)) {
13
"app"
14
} else if url.starts_with("about:") {
15
"about"
16
} else if url.starts_with("chrome-error:") {
17
"error page"
18
} else {
19
"other"
20
}
21
}
22
23
pub(crate) struct CallContext<'a> {
24
pub method: &'a str,
25
pub params_bytes: usize,
26
pub tab: &'static str,
27
pub in_flight: usize,
28
}
29
30
/// WebView2 answers every protocol error with E_INVALIDARG; the protocol's own error sits in the JSON.
31
pub(crate) fn failure_reason(context: &CallContext, hresult: &str, json: &str) -> String {
32
let parsed = serde_json::from_str::<Value>(json).unwrap_or(Value::Null);
33
let error = parsed.get("error").unwrap_or(&parsed);
34
let message = error.get("message").and_then(Value::as_str).unwrap_or(hresult);
35
let code = error
36
.get("code")
37
.and_then(Value::as_i64)
38
.map(|code| format!(" code {code},"))
39
.unwrap_or_default();
40
format!(
41
"{message} [{}{code} params {} bytes, tab {}, {} call(s) in flight]",
42
context.method, context.params_bytes, context.tab, context.in_flight,
43
)
44
}
45
46
#[cfg(test)]
47
mod tests {
48
use super::*;
49
50
const HRESULT: &str = "The parameter is incorrect. (0x80070057)";
51
52
fn context() -> CallContext<'static> {
53
CallContext {
54
method: "Runtime.evaluate",
55
params_bytes: 48213,
56
tab: "parked",
57
in_flight: 2,
58
}
59
}
60
61
#[test]
62
fn the_protocol_message_leads_the_reason() {
63
let json = r#"{"code":-32000,"message":"Execution context was destroyed."}"#;
64
assert_eq!(
65
failure_reason(&context(), HRESULT, json),
66
"Execution context was destroyed. [Runtime.evaluate code -32000, params 48213 bytes, tab parked, 2 call(s) in flight]"
67
);
68
}
69
70
#[test]
71
fn a_nested_protocol_error_is_read_too() {
72
let json = r#"{"error":{"code":-32601,"message":"'Foo.bar' wasn't found"}}"#;
73
assert!(failure_reason(&context(), HRESULT, json).starts_with("'Foo.bar' wasn't found [Runtime.evaluate code -32601,"));
74
}
75
76
#[test]
77
fn without_a_protocol_error_the_hresult_and_the_call_are_named() {
78
assert_eq!(
79
failure_reason(&context(), HRESULT, ""),
80
"The parameter is incorrect. (0x80070057) [Runtime.evaluate params 48213 bytes, tab parked, 2 call(s) in flight]"
81
);
82
}
83
84
#[test]
85
fn the_tab_state_never_carries_the_url() {
86
assert_eq!(tab_state(App::Teams, "https://teams.cloud.microsoft/robots.txt"), "parked");
87
assert_eq!(tab_state(App::Teams, "https://teams.cloud.microsoft/v2/?ctx=chat"), "app");
88
assert_eq!(tab_state(App::Teams, "about:blank"), "about");
89
assert_eq!(tab_state(App::Teams, "chrome-error://chromewebdata/"), "error page");
90
assert_eq!(tab_state(App::Teams, ""), "no document");
91
assert_eq!(tab_state(App::Teams, "https://example.com/private/path"), "other");
92
}
93
}
@@ -0,0 +1,93 @@1
use serde_json::Value;2
use session::{App, is_login_url};3
4
/// Coarse state of the app tab for error reports, never the URL itself.5
pub(crate) fn tab_state(app: App, url: &str) -> &'static str {6
if url.is_empty() {7
"no document"8
} else if app.is_park_url(url) {9
"parked"10
} else if is_login_url(url) {11
"login"12
} else if app.origins().iter().any(|origin| url.starts_with(origin)) {13
"app"14
} else if url.starts_with("about:") {15
"about"16
} else if url.starts_with("chrome-error:") {17
"error page"18
} else {19
"other"20
}21
}22
23
pub(crate) struct CallContext<'a> {24
pub method: &'a str,25
pub params_bytes: usize,26
pub tab: &'static str,27
pub in_flight: usize,28
}29
30
/// WebView2 answers every protocol error with E_INVALIDARG; the protocol's own error sits in the JSON.31
pub(crate) fn failure_reason(context: &CallContext, hresult: &str, json: &str) -> String {32
let parsed = serde_json::from_str::<Value>(json).unwrap_or(Value::Null);33
let error = parsed.get("error").unwrap_or(&parsed);34
let message = error.get("message").and_then(Value::as_str).unwrap_or(hresult);35
let code = error36
.get("code")37
.and_then(Value::as_i64)38
.map(|code| format!(" code {code},"))39
.unwrap_or_default();40
format!(41
"{message} [{}{code} params {} bytes, tab {}, {} call(s) in flight]",42
context.method, context.params_bytes, context.tab, context.in_flight,43
)44
}45
46
#[cfg(test)]47
mod tests {48
use super::*;49
50
const HRESULT: &str = "The parameter is incorrect. (0x80070057)";51
52
fn context() -> CallContext<'static> {53
CallContext {54
method: "Runtime.evaluate",55
params_bytes: 48213,56
tab: "parked",57
in_flight: 2,58
}59
}60
61
#[test]62
fn the_protocol_message_leads_the_reason() {63
let json = r#"{"code":-32000,"message":"Execution context was destroyed."}"#;64
assert_eq!(65
failure_reason(&context(), HRESULT, json),66
"Execution context was destroyed. [Runtime.evaluate code -32000, params 48213 bytes, tab parked, 2 call(s) in flight]"67
);68
}69
70
#[test]71
fn a_nested_protocol_error_is_read_too() {72
let json = r#"{"error":{"code":-32601,"message":"'Foo.bar' wasn't found"}}"#;73
assert!(failure_reason(&context(), HRESULT, json).starts_with("'Foo.bar' wasn't found [Runtime.evaluate code -32601,"));74
}75
76
#[test]77
fn without_a_protocol_error_the_hresult_and_the_call_are_named() {78
assert_eq!(79
failure_reason(&context(), HRESULT, ""),80
"The parameter is incorrect. (0x80070057) [Runtime.evaluate params 48213 bytes, tab parked, 2 call(s) in flight]"81
);82
}83
84
#[test]85
fn the_tab_state_never_carries_the_url() {86
assert_eq!(tab_state(App::Teams, "https://teams.cloud.microsoft/robots.txt"), "parked");87
assert_eq!(tab_state(App::Teams, "https://teams.cloud.microsoft/v2/?ctx=chat"), "app");88
assert_eq!(tab_state(App::Teams, "about:blank"), "about");89
assert_eq!(tab_state(App::Teams, "chrome-error://chromewebdata/"), "error page");90
assert_eq!(tab_state(App::Teams, ""), "no document");91
assert_eq!(tab_state(App::Teams, "https://example.com/private/path"), "other");92
}93
}@@ -6,7 +6,7 @@ use std::sync::{Arc, mpsc};
6
6
use std::time::{Duration, Instant};
7
7
8
8
use serde_json::Value;
9
use session::{App, Error, Result, TabCommand, TabEvent, is_login_url};
9
use session::{App, Error, TabCommand, TabEvent, is_login_url};
10
10
use tokio::sync::watch;
11
11
use webview2_com::Microsoft::Web::WebView2::Win32::*;
12
12
use webview2_com::{
@@ -21,8 +21,10 @@ use windows::Win32::System::LibraryLoader::GetModuleHandleW;
21
21
use windows::Win32::UI::WindowsAndMessaging::*;
22
22
use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};
23
23
24
use crate::cdp_failure::{CallContext, failure_reason, tab_state};
24
25
use crate::fanout::Subscribers;
25
26
use crate::host_dialog::{self, Dialog};
27
use crate::park::{ParkDecision, ParkGate};
26
28
use crate::transport::{HostState, UiRequest, WebViewTransport};
27
29
use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};
28
30
@@ -55,6 +57,7 @@ pub(crate) struct Shared {
55
57
pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,
56
58
pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,
57
59
subscribers: RefCell<Subscribers>,
60
park_gate: RefCell<ParkGate>,
58
61
state: watch::Sender<HostState>,
59
62
requests: mpsc::Receiver<UiRequest>,
60
63
restarting: Cell<bool>,
@@ -115,6 +118,7 @@ fn run(
115
118
environment: RefCell::new(None),
116
119
dialogs: RefCell::new(HashMap::new()),
117
120
subscribers: RefCell::new(Subscribers::default()),
121
park_gate: RefCell::new(ParkGate::default()),
118
122
state,
119
123
requests,
120
124
restarting: Cell::new(false),
@@ -426,6 +430,7 @@ fn drain(shared: &Rc<Shared>) {
426
430
UiRequest::Call { app, command } => call(shared, app, command),
427
431
UiRequest::Subscribe { app, sink } => shared.subscribers.borrow_mut().add(app, sink),
428
432
UiRequest::Wake { app } => wake(shared, app),
433
UiRequest::Hold { app, held } => shared.park_gate.borrow_mut().hold(app, held),
429
434
UiRequest::Retry => {
430
435
if !shared.state.borrow().ready && !shared.restarting.replace(true) {
431
436
restart(shared);
@@ -443,14 +448,30 @@ fn call(shared: &Shared, app: App, command: TabCommand) {
443
448
let Some(webview) = webview_of(shared, app) else {
444
449
return command.respond(Err(Error::Cdp("webview is restarting".into())));
445
450
};
451
let parameters_json = command.params.to_string();
452
let parameters_bytes = parameters_json.len();
446
453
let method = HSTRING::from(command.method.as_str());
447
let parameters = HSTRING::from(command.params.to_string());
454
let parameters = HSTRING::from(parameters_json);
448
455
let pending = Rc::new(RefCell::new(Some(command)));
449
456
let answered = pending.clone();
457
shared.park_gate.borrow_mut().command_started(app);
450
458
let handler =
451
459
CallDevToolsProtocolMethodCompletedHandler::create(Box::new(move |code, json| {
452
460
if let Some(command) = answered.borrow_mut().take() {
453
command.respond(answer(code, &json));
461
let result = match code {
462
Ok(()) => Ok(serde_json::from_str(&json).unwrap_or(Value::Null)),
463
Err(error) => Err(Error::Cdp(describe_failure(
464
app,
465
&command.method,
466
parameters_bytes,
467
&error.to_string(),
468
&json,
469
))),
470
};
471
if let Some(shared) = self::shared() {
472
shared.park_gate.borrow_mut().command_finished(app);
473
}
474
command.respond(result);
454
475
}
455
476
Ok(())
456
477
}));
@@ -458,24 +479,27 @@ fn call(shared: &Shared, app: App, command: TabCommand) {
458
479
unsafe { webview.CallDevToolsProtocolMethod(&method, ¶meters, &handler) }
459
480
&& let Some(command) = pending.borrow_mut().take()
460
481
{
461
let reason = format!("{}: {error}", command.method);
482
let reason = describe_failure(app, &command.method, parameters_bytes, &error.to_string(), "");
483
shared.park_gate.borrow_mut().command_finished(app);
462
484
command.respond(Err(Error::Cdp(reason)));
463
485
}
464
486
}
465
487
466
fn answer(code: windows::core::Result<()>, json: &str) -> Result<Value> {
467
let parsed = serde_json::from_str::<Value>(json).unwrap_or(Value::Null);
468
match code {
469
Ok(()) => Ok(parsed),
470
Err(error) => {
471
let reason = parsed
472
.get("message")
473
.and_then(Value::as_str)
474
.map(str::to_owned)
475
.unwrap_or_else(|| error.to_string());
476
Err(Error::Cdp(reason))
477
}
478
}
488
fn describe_failure(app: App, method: &str, parameters_bytes: usize, hresult: &str, json: &str) -> String {
489
let (tab, in_flight) = match shared() {
490
Some(shared) => (
491
tab_state(app, ¤t_url(&shared, app)),
492
shared.park_gate.borrow().in_flight(app),
493
),
494
None => ("unknown", 0),
495
};
496
let context = CallContext {
497
method,
498
params_bytes: parameters_bytes,
499
tab,
500
in_flight,
501
};
502
failure_reason(&context, hresult, json)
479
503
}
480
504
481
505
fn wake(shared: &Shared, app: App) {
@@ -523,6 +547,7 @@ fn show(shared: &Shared, app: App) {
523
547
fn restart(shared: &Rc<Shared>) {
524
548
shared.state.send_modify(|state| state.ready = false);
525
549
shared.subscribers.borrow_mut().clear();
550
shared.park_gate.borrow_mut().forget_commands();
526
551
host_dialog::close_all(shared);
527
552
let views: Vec<View> = shared
528
553
.views
@@ -590,7 +615,13 @@ extern "system" fn window_procedure(
590
615
let _ = KillTimer(Some(window), PARK_TIMER);
591
616
}
592
617
if let Some(app) = app_of(&shared, window) {
593
park(&shared, app);
618
let decision = shared.park_gate.borrow_mut().decide(app);
619
match decision {
620
ParkDecision::Park => park(&shared, app),
621
ParkDecision::Wait => unsafe {
622
SetTimer(Some(window), PARK_TIMER, PARK_DELAY_MS, None);
623
},
624
}
594
625
}
595
626
}
596
627
WM_CLOSE => unsafe {
@@ -6,7 +6,7 @@ use std::sync::{Arc, mpsc};6
use std::time::{Duration, Instant};6
use std::time::{Duration, Instant};7
7
8
use serde_json::Value;8
use serde_json::Value;9
use session::{App, Error, Result, TabCommand, TabEvent, is_login_url};9
use session::{App, Error, TabCommand, TabEvent, is_login_url};10
use tokio::sync::watch;10
use tokio::sync::watch;11
use webview2_com::Microsoft::Web::WebView2::Win32::*;11
use webview2_com::Microsoft::Web::WebView2::Win32::*;12
use webview2_com::{12
use webview2_com::{@@ -21,8 +21,10 @@ use windows::Win32::System::LibraryLoader::GetModuleHandleW;21
use windows::Win32::UI::WindowsAndMessaging::*;21
use windows::Win32::UI::WindowsAndMessaging::*;22
use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};22
use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};23
23
24
use crate::cdp_failure::{CallContext, failure_reason, tab_state};24
use crate::fanout::Subscribers;25
use crate::fanout::Subscribers;25
use crate::host_dialog::{self, Dialog};26
use crate::host_dialog::{self, Dialog};27
use crate::park::{ParkDecision, ParkGate};26
use crate::transport::{HostState, UiRequest, WebViewTransport};28
use crate::transport::{HostState, UiRequest, WebViewTransport};27
use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};29
use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};28
30
@@ -55,6 +57,7 @@ pub(crate) struct Shared {55
pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,57
pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,56
pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,58
pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,57
subscribers: RefCell<Subscribers>,59
subscribers: RefCell<Subscribers>,60
park_gate: RefCell<ParkGate>,58
state: watch::Sender<HostState>,61
state: watch::Sender<HostState>,59
requests: mpsc::Receiver<UiRequest>,62
requests: mpsc::Receiver<UiRequest>,60
restarting: Cell<bool>,63
restarting: Cell<bool>,@@ -115,6 +118,7 @@ fn run(115
environment: RefCell::new(None),118
environment: RefCell::new(None),116
dialogs: RefCell::new(HashMap::new()),119
dialogs: RefCell::new(HashMap::new()),117
subscribers: RefCell::new(Subscribers::default()),120
subscribers: RefCell::new(Subscribers::default()),121
park_gate: RefCell::new(ParkGate::default()),118
state,122
state,119
requests,123
requests,120
restarting: Cell::new(false),124
restarting: Cell::new(false),@@ -426,6 +430,7 @@ fn drain(shared: &Rc<Shared>) {426
UiRequest::Call { app, command } => call(shared, app, command),430
UiRequest::Call { app, command } => call(shared, app, command),427
UiRequest::Subscribe { app, sink } => shared.subscribers.borrow_mut().add(app, sink),431
UiRequest::Subscribe { app, sink } => shared.subscribers.borrow_mut().add(app, sink),428
UiRequest::Wake { app } => wake(shared, app),432
UiRequest::Wake { app } => wake(shared, app),433
UiRequest::Hold { app, held } => shared.park_gate.borrow_mut().hold(app, held),429
UiRequest::Retry => {434
UiRequest::Retry => {430
if !shared.state.borrow().ready && !shared.restarting.replace(true) {435
if !shared.state.borrow().ready && !shared.restarting.replace(true) {431
restart(shared);436
restart(shared);@@ -443,14 +448,30 @@ fn call(shared: &Shared, app: App, command: TabCommand) {443
let Some(webview) = webview_of(shared, app) else {448
let Some(webview) = webview_of(shared, app) else {444
return command.respond(Err(Error::Cdp("webview is restarting".into())));449
return command.respond(Err(Error::Cdp("webview is restarting".into())));445
};450
};451
let parameters_json = command.params.to_string();452
let parameters_bytes = parameters_json.len();446
let method = HSTRING::from(command.method.as_str());453
let method = HSTRING::from(command.method.as_str());447
let parameters = HSTRING::from(command.params.to_string());454
let parameters = HSTRING::from(parameters_json);448
let pending = Rc::new(RefCell::new(Some(command)));455
let pending = Rc::new(RefCell::new(Some(command)));449
let answered = pending.clone();456
let answered = pending.clone();457
shared.park_gate.borrow_mut().command_started(app);450
let handler =458
let handler =451
CallDevToolsProtocolMethodCompletedHandler::create(Box::new(move |code, json| {459
CallDevToolsProtocolMethodCompletedHandler::create(Box::new(move |code, json| {452
if let Some(command) = answered.borrow_mut().take() {460
if let Some(command) = answered.borrow_mut().take() {453
command.respond(answer(code, &json));461
let result = match code {462
Ok(()) => Ok(serde_json::from_str(&json).unwrap_or(Value::Null)),463
Err(error) => Err(Error::Cdp(describe_failure(464
app,465
&command.method,466
parameters_bytes,467
&error.to_string(),468
&json,469
))),470
};471
if let Some(shared) = self::shared() {472
shared.park_gate.borrow_mut().command_finished(app);473
}474
command.respond(result);454
}475
}455
Ok(())476
Ok(())456
}));477
}));@@ -458,24 +479,27 @@ fn call(shared: &Shared, app: App, command: TabCommand) {458
unsafe { webview.CallDevToolsProtocolMethod(&method, ¶meters, &handler) }479
unsafe { webview.CallDevToolsProtocolMethod(&method, ¶meters, &handler) }459
&& let Some(command) = pending.borrow_mut().take()480
&& let Some(command) = pending.borrow_mut().take()460
{481
{461
let reason = format!("{}: {error}", command.method);482
let reason = describe_failure(app, &command.method, parameters_bytes, &error.to_string(), "");483
shared.park_gate.borrow_mut().command_finished(app);462
command.respond(Err(Error::Cdp(reason)));484
command.respond(Err(Error::Cdp(reason)));463
}485
}464
}486
}465
487
466
fn answer(code: windows::core::Result<()>, json: &str) -> Result<Value> {488
fn describe_failure(app: App, method: &str, parameters_bytes: usize, hresult: &str, json: &str) -> String {467
let parsed = serde_json::from_str::<Value>(json).unwrap_or(Value::Null);489
let (tab, in_flight) = match shared() {468
match code {490
Some(shared) => (469
Ok(()) => Ok(parsed),491
tab_state(app, ¤t_url(&shared, app)),470
Err(error) => {492
shared.park_gate.borrow().in_flight(app),471
let reason = parsed493
),472
.get("message")494
None => ("unknown", 0),473
.and_then(Value::as_str)495
};474
.map(str::to_owned)496
let context = CallContext {475
.unwrap_or_else(|| error.to_string());497
method,476
Err(Error::Cdp(reason))498
params_bytes: parameters_bytes,477
}499
tab,478
}500
in_flight,501
};502
failure_reason(&context, hresult, json)479
}503
}480
504
481
fn wake(shared: &Shared, app: App) {505
fn wake(shared: &Shared, app: App) {@@ -523,6 +547,7 @@ fn show(shared: &Shared, app: App) {523
fn restart(shared: &Rc<Shared>) {547
fn restart(shared: &Rc<Shared>) {524
shared.state.send_modify(|state| state.ready = false);548
shared.state.send_modify(|state| state.ready = false);525
shared.subscribers.borrow_mut().clear();549
shared.subscribers.borrow_mut().clear();550
shared.park_gate.borrow_mut().forget_commands();526
host_dialog::close_all(shared);551
host_dialog::close_all(shared);527
let views: Vec<View> = shared552
let views: Vec<View> = shared528
.views553
.views@@ -590,7 +615,13 @@ extern "system" fn window_procedure(590
let _ = KillTimer(Some(window), PARK_TIMER);615
let _ = KillTimer(Some(window), PARK_TIMER);591
}616
}592
if let Some(app) = app_of(&shared, window) {617
if let Some(app) = app_of(&shared, window) {593
park(&shared, app);618
let decision = shared.park_gate.borrow_mut().decide(app);619
match decision {620
ParkDecision::Park => park(&shared, app),621
ParkDecision::Wait => unsafe {622
SetTimer(Some(window), PARK_TIMER, PARK_DELAY_MS, None);623
},624
}594
}625
}595
}626
}596
WM_CLOSE => unsafe {627
WM_CLOSE => unsafe {@@ -1,3 +1,5 @@
1
#[cfg(any(windows, test))]
2
mod cdp_failure;
1
3
#[cfg(windows)]
2
4
mod dialog;
3
5
#[cfg(windows)]
@@ -11,6 +13,8 @@ mod host;
11
13
mod host_dialog;
12
14
#[cfg(windows)]
13
15
mod main_embed;
16
#[cfg(any(windows, test))]
17
mod park;
14
18
#[cfg(windows)]
15
19
mod transport;
16
20
@@ -1,3 +1,5 @@1
#[cfg(any(windows, test))]2
mod cdp_failure;1
#[cfg(windows)]3
#[cfg(windows)]2
mod dialog;4
mod dialog;3
#[cfg(windows)]5
#[cfg(windows)]@@ -11,6 +13,8 @@ mod host;11
mod host_dialog;13
mod host_dialog;12
#[cfg(windows)]14
#[cfg(windows)]13
mod main_embed;15
mod main_embed;16
#[cfg(any(windows, test))]17
mod park;14
#[cfg(windows)]18
#[cfg(windows)]15
mod transport;19
mod transport;16
20
@@ -0,0 +1,121 @@
1
use std::collections::HashMap;
2
3
use session::App;
4
5
const MAX_COMMAND_WAITS: usize = 5;
6
7
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8
pub(crate) enum ParkDecision {
9
Park,
10
Wait,
11
}
12
13
/// A navigation of the app tab destroys the page context of every running protocol call
14
/// and the Trouter sockets of a live call, so parking waits until the tab is idle.
15
#[derive(Debug, Default)]
16
pub(crate) struct ParkGate {
17
holds: HashMap<App, usize>,
18
in_flight: HashMap<App, usize>,
19
command_waits: HashMap<App, usize>,
20
}
21
22
impl ParkGate {
23
pub(crate) fn hold(&mut self, app: App, held: bool) {
24
adjust(&mut self.holds, app, held);
25
}
26
27
pub(crate) fn command_started(&mut self, app: App) {
28
adjust(&mut self.in_flight, app, true);
29
}
30
31
pub(crate) fn command_finished(&mut self, app: App) {
32
adjust(&mut self.in_flight, app, false);
33
}
34
35
pub(crate) fn forget_commands(&mut self) {
36
self.in_flight.clear();
37
}
38
39
pub(crate) fn in_flight(&self, app: App) -> usize {
40
self.in_flight.get(&app).copied().unwrap_or(0)
41
}
42
43
/// A protocol call whose page promise never settles stays in flight; after a few waits it no longer blocks the park.
44
pub(crate) fn decide(&mut self, app: App) -> ParkDecision {
45
if self.holds.get(&app).copied().unwrap_or(0) > 0 {
46
return ParkDecision::Wait;
47
}
48
let waits = self.command_waits.entry(app).or_default();
49
if self.in_flight.get(&app).copied().unwrap_or(0) > 0 && *waits < MAX_COMMAND_WAITS {
50
*waits += 1;
51
return ParkDecision::Wait;
52
}
53
*waits = 0;
54
ParkDecision::Park
55
}
56
}
57
58
fn adjust(counts: &mut HashMap<App, usize>, app: App, up: bool) {
59
let count = counts.entry(app).or_default();
60
*count = if up { *count + 1 } else { count.saturating_sub(1) };
61
}
62
63
#[cfg(test)]
64
mod tests {
65
use super::*;
66
67
#[test]
68
fn an_idle_tab_parks() {
69
assert_eq!(ParkGate::default().decide(App::Teams), ParkDecision::Park);
70
}
71
72
#[test]
73
fn a_running_command_delays_the_park_until_it_answers() {
74
let mut gate = ParkGate::default();
75
gate.command_started(App::Teams);
76
assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
77
assert_eq!(gate.decide(App::Outlook), ParkDecision::Park);
78
gate.command_finished(App::Teams);
79
assert_eq!(gate.decide(App::Teams), ParkDecision::Park);
80
}
81
82
#[test]
83
fn a_command_that_never_answers_stops_blocking_after_a_few_waits() {
84
let mut gate = ParkGate::default();
85
gate.command_started(App::Teams);
86
for _ in 0..MAX_COMMAND_WAITS {
87
assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
88
}
89
assert_eq!(gate.decide(App::Teams), ParkDecision::Park);
90
}
91
92
#[test]
93
fn a_held_tab_waits_for_every_hold_to_end() {
94
let mut gate = ParkGate::default();
95
gate.hold(App::Teams, true);
96
gate.hold(App::Teams, true);
97
gate.hold(App::Teams, false);
98
assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
99
gate.hold(App::Teams, false);
100
assert_eq!(gate.decide(App::Teams), ParkDecision::Park);
101
}
102
103
#[test]
104
fn extra_releases_do_not_underflow() {
105
let mut gate = ParkGate::default();
106
gate.hold(App::Teams, false);
107
gate.command_finished(App::Teams);
108
gate.hold(App::Teams, true);
109
assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
110
}
111
112
#[test]
113
fn a_restart_forgets_unanswered_commands_but_keeps_holds() {
114
let mut gate = ParkGate::default();
115
gate.command_started(App::Outlook);
116
gate.hold(App::Teams, true);
117
gate.forget_commands();
118
assert_eq!(gate.decide(App::Outlook), ParkDecision::Park);
119
assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
120
}
121
}
@@ -0,0 +1,121 @@1
use std::collections::HashMap;2
3
use session::App;4
5
const MAX_COMMAND_WAITS: usize = 5;6
7
#[derive(Debug, Clone, Copy, PartialEq, Eq)]8
pub(crate) enum ParkDecision {9
Park,10
Wait,11
}12
13
/// A navigation of the app tab destroys the page context of every running protocol call14
/// and the Trouter sockets of a live call, so parking waits until the tab is idle.15
#[derive(Debug, Default)]16
pub(crate) struct ParkGate {17
holds: HashMap<App, usize>,18
in_flight: HashMap<App, usize>,19
command_waits: HashMap<App, usize>,20
}21
22
impl ParkGate {23
pub(crate) fn hold(&mut self, app: App, held: bool) {24
adjust(&mut self.holds, app, held);25
}26
27
pub(crate) fn command_started(&mut self, app: App) {28
adjust(&mut self.in_flight, app, true);29
}30
31
pub(crate) fn command_finished(&mut self, app: App) {32
adjust(&mut self.in_flight, app, false);33
}34
35
pub(crate) fn forget_commands(&mut self) {36
self.in_flight.clear();37
}38
39
pub(crate) fn in_flight(&self, app: App) -> usize {40
self.in_flight.get(&app).copied().unwrap_or(0)41
}42
43
/// A protocol call whose page promise never settles stays in flight; after a few waits it no longer blocks the park.44
pub(crate) fn decide(&mut self, app: App) -> ParkDecision {45
if self.holds.get(&app).copied().unwrap_or(0) > 0 {46
return ParkDecision::Wait;47
}48
let waits = self.command_waits.entry(app).or_default();49
if self.in_flight.get(&app).copied().unwrap_or(0) > 0 && *waits < MAX_COMMAND_WAITS {50
*waits += 1;51
return ParkDecision::Wait;52
}53
*waits = 0;54
ParkDecision::Park55
}56
}57
58
fn adjust(counts: &mut HashMap<App, usize>, app: App, up: bool) {59
let count = counts.entry(app).or_default();60
*count = if up { *count + 1 } else { count.saturating_sub(1) };61
}62
63
#[cfg(test)]64
mod tests {65
use super::*;66
67
#[test]68
fn an_idle_tab_parks() {69
assert_eq!(ParkGate::default().decide(App::Teams), ParkDecision::Park);70
}71
72
#[test]73
fn a_running_command_delays_the_park_until_it_answers() {74
let mut gate = ParkGate::default();75
gate.command_started(App::Teams);76
assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);77
assert_eq!(gate.decide(App::Outlook), ParkDecision::Park);78
gate.command_finished(App::Teams);79
assert_eq!(gate.decide(App::Teams), ParkDecision::Park);80
}81
82
#[test]83
fn a_command_that_never_answers_stops_blocking_after_a_few_waits() {84
let mut gate = ParkGate::default();85
gate.command_started(App::Teams);86
for _ in 0..MAX_COMMAND_WAITS {87
assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);88
}89
assert_eq!(gate.decide(App::Teams), ParkDecision::Park);90
}91
92
#[test]93
fn a_held_tab_waits_for_every_hold_to_end() {94
let mut gate = ParkGate::default();95
gate.hold(App::Teams, true);96
gate.hold(App::Teams, true);97
gate.hold(App::Teams, false);98
assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);99
gate.hold(App::Teams, false);100
assert_eq!(gate.decide(App::Teams), ParkDecision::Park);101
}102
103
#[test]104
fn extra_releases_do_not_underflow() {105
let mut gate = ParkGate::default();106
gate.hold(App::Teams, false);107
gate.command_finished(App::Teams);108
gate.hold(App::Teams, true);109
assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);110
}111
112
#[test]113
fn a_restart_forgets_unanswered_commands_but_keeps_holds() {114
let mut gate = ParkGate::default();115
gate.command_started(App::Outlook);116
gate.hold(App::Teams, true);117
gate.forget_commands();118
assert_eq!(gate.decide(App::Outlook), ParkDecision::Park);119
assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);120
}121
}@@ -29,6 +29,10 @@ pub(crate) enum UiRequest {
29
29
Wake {
30
30
app: App,
31
31
},
32
Hold {
33
app: App,
34
held: bool,
35
},
32
36
Retry,
33
37
OpenDialog {
34
38
id: u64,
@@ -147,6 +151,10 @@ impl Transport for WebViewTransport {
147
151
Box::pin(async move { self.send(UiRequest::Wake { app }) })
148
152
}
149
153
154
fn hold(&self, app: App, held: bool) {
155
let _ = self.send(UiRequest::Hold { app, held });
156
}
157
150
158
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {
151
159
Box::pin(async move {
152
160
let state = self.state.borrow();
@@ -29,6 +29,10 @@ pub(crate) enum UiRequest {29
Wake {29
Wake {30
app: App,30
app: App,31
},31
},32
Hold {33
app: App,34
held: bool,35
},32
Retry,36
Retry,33
OpenDialog {37
OpenDialog {34
id: u64,38
id: u64,@@ -147,6 +151,10 @@ impl Transport for WebViewTransport {147
Box::pin(async move { self.send(UiRequest::Wake { app }) })151
Box::pin(async move { self.send(UiRequest::Wake { app }) })148
}152
}149
153
154
fn hold(&self, app: App, held: bool) {155
let _ = self.send(UiRequest::Hold { app, held });156
}157
150
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {158
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {151
Box::pin(async move {159
Box::pin(async move {152
let state = self.state.borrow();160
let state = self.state.borrow();