feat(forwards): heal alongside the delta, loading and not-available states
- heal_forwards runs in parallel with the delta fetch and announces on its own - background heal of all chats with stale forwards after the first sidebar sync, newest first, 2 s apart - placeholder line "Loading forwarded message" inside the forward frame - no original from Graph (answer without content, 403/404/410): stored marker, "Original message not available", no retry Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -18,6 +18,7 @@ use crate::presence_link::{self, LinkSignal};
18
18
19
19
pub type Engine = SyncEngine<Graph>;
20
20
21
const FORWARD_HEAL_PAUSE: Duration = Duration::from_secs(2);
21
22
const CONNECT_RETRY: Duration = Duration::from_secs(8);
22
23
const REFRESH_INTERVAL: Duration = Duration::from_secs(120);
23
24
const REFRESH_SETTLE: Duration = Duration::from_secs(2);
@@ -201,6 +202,7 @@ async fn refresh_loop(
201
202
mut nudges: mpsc::UnboundedReceiver<()>,
202
203
) {
203
204
let mut interval = tokio::time::interval(REFRESH_INTERVAL);
205
let mut forwards_healing = false;
204
206
loop {
205
207
tokio::select! {
206
208
_ = interval.tick() => {}
@@ -214,6 +216,10 @@ async fn refresh_loop(
214
216
}
215
217
match engine.refresh_sidebar().await {
216
218
Ok(_) => {
219
if !std::mem::replace(&mut forwards_healing, true) {
220
let engine = engine.clone();
221
tokio::spawn(async move { engine.heal_all_forwards(FORWARD_HEAL_PAUSE).await });
222
}
217
223
if let Err(error) = engine.refresh_folders().await {
218
224
crate::diagnostics::record(format!(
219
225
"sync: chat folders and channel layout not refreshed: {error}"
@@ -18,6 +18,7 @@ use crate::presence_link::{self, LinkSignal};18
18
19
pub type Engine = SyncEngine<Graph>;19
pub type Engine = SyncEngine<Graph>;20
20
21
const FORWARD_HEAL_PAUSE: Duration = Duration::from_secs(2);21
const CONNECT_RETRY: Duration = Duration::from_secs(8);22
const CONNECT_RETRY: Duration = Duration::from_secs(8);22
const REFRESH_INTERVAL: Duration = Duration::from_secs(120);23
const REFRESH_INTERVAL: Duration = Duration::from_secs(120);23
const REFRESH_SETTLE: Duration = Duration::from_secs(2);24
const REFRESH_SETTLE: Duration = Duration::from_secs(2);@@ -201,6 +202,7 @@ async fn refresh_loop(201
mut nudges: mpsc::UnboundedReceiver<()>,202
mut nudges: mpsc::UnboundedReceiver<()>,202
) {203
) {203
let mut interval = tokio::time::interval(REFRESH_INTERVAL);204
let mut interval = tokio::time::interval(REFRESH_INTERVAL);205
let mut forwards_healing = false;204
loop {206
loop {205
tokio::select! {207
tokio::select! {206
_ = interval.tick() => {}208
_ = interval.tick() => {}@@ -214,6 +216,10 @@ async fn refresh_loop(214
}216
}215
match engine.refresh_sidebar().await {217
match engine.refresh_sidebar().await {216
Ok(_) => {218
Ok(_) => {219
if !std::mem::replace(&mut forwards_healing, true) {220
let engine = engine.clone();221
tokio::spawn(async move { engine.heal_all_forwards(FORWARD_HEAL_PAUSE).await });222
}217
if let Err(error) = engine.refresh_folders().await {223
if let Err(error) = engine.refresh_folders().await {218
crate::diagnostics::record(format!(224
crate::diagnostics::record(format!(219
"sync: chat folders and channel layout not refreshed: {error}"225
"sync: chat folders and channel layout not refreshed: {error}"@@ -1625,6 +1625,16 @@ fn release_messages() -> Vec<MessageRecord> {
1625
1625
"[]",
1626
1626
false,
1627
1627
),
1628
message(
1629
chat,
1630
"m5e",
1631
None,
1632
jonas,
1633
at(0, 12, 40),
1634
"<p>Context from the old planning chat.</p><attachment id=\"1789000000000\"></attachment>",
1635
r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"id":"1789000000000","content":null,"unavailable":true}]"#,
1636
false,
1637
),
1628
1638
message(
1629
1639
chat,
1630
1640
"m6",
@@ -1625,6 +1625,16 @@ fn release_messages() -> Vec<MessageRecord> {1625
"[]",1625
"[]",1626
false,1626
false,1627
),1627
),1628
message(1629
chat,1630
"m5e",1631
None,1632
jonas,1633
at(0, 12, 40),1634
"<p>Context from the old planning chat.</p><attachment id=\"1789000000000\"></attachment>",1635
r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"id":"1789000000000","content":null,"unavailable":true}]"#,1636
false,1637
),1628
message(1638
message(1629
chat,1639
chat,1630
"m6",1640
"m6",@@ -194,15 +194,23 @@ impl<R: Remote> SyncEngine<R> {
194
194
}
195
195
196
196
pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> {
197
let mut delta = match self.resolve(conversation_id).await? {
198
Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,
199
Conversation::Channel { team_id } => {
200
self.fetch_newer_channel(&team_id, conversation_id).await?
197
let heal = async {
198
if self.heal_forwards(conversation_id).await {
199
self.announce(conversation_id, true);
201
200
}
202
201
};
202
let fetch = async {
203
Ok::<_, Error>(match self.resolve(conversation_id).await? {
204
Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,
205
Conversation::Channel { team_id } => {
206
self.fetch_newer_channel(&team_id, conversation_id).await?
207
}
208
})
209
};
210
let (fetched, ()) = tokio::join!(fetch, heal);
211
let mut delta = fetched?;
203
212
let cache_changed = self.attach_delta_links(conversation_id, &mut delta).await
204
| self.backfill_links(conversation_id).await
205
| self.heal_forwards(conversation_id).await;
213
| self.backfill_links(conversation_id).await;
206
214
self.announce(conversation_id, !delta.is_empty() || cache_changed);
207
215
Ok(delta)
208
216
}
@@ -194,15 +194,23 @@ impl<R: Remote> SyncEngine<R> {194
}194
}195
195
196
pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> {196
pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> {197
let mut delta = match self.resolve(conversation_id).await? {197
let heal = async {198
Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,198
if self.heal_forwards(conversation_id).await {199
Conversation::Channel { team_id } => {199
self.announce(conversation_id, true);200
self.fetch_newer_channel(&team_id, conversation_id).await?201
}200
}202
};201
};202
let fetch = async {203
Ok::<_, Error>(match self.resolve(conversation_id).await? {204
Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,205
Conversation::Channel { team_id } => {206
self.fetch_newer_channel(&team_id, conversation_id).await?207
}208
})209
};210
let (fetched, ()) = tokio::join!(fetch, heal);211
let mut delta = fetched?;203
let cache_changed = self.attach_delta_links(conversation_id, &mut delta).await212
let cache_changed = self.attach_delta_links(conversation_id, &mut delta).await204
| self.backfill_links(conversation_id).await213
| self.backfill_links(conversation_id).await;205
| self.heal_forwards(conversation_id).await;206
self.announce(conversation_id, !delta.is_empty() || cache_changed);214
self.announce(conversation_id, !delta.is_empty() || cache_changed);207
Ok(delta)215
Ok(delta)208
}216
}@@ -1,8 +1,24 @@
1
use std::time::Duration;
2
3
use store::MessageRecord;
4
1
5
use crate::engine::{Conversation, SyncEngine};
2
use crate::forwarded::{FORWARDED_CONTENT_TYPE, lacks_forward_content};
6
use crate::error::Error;
7
use crate::forwarded::{FORWARDED_CONTENT_TYPE, lacks_forward_content, mark_forwards_unavailable};
3
8
use crate::mapping::message_record;
4
9
use crate::remote::Remote;
5
10
11
/// Graph answered for good: the original is gone or not readable for this account.
12
fn is_gone(error: &Error) -> bool {
13
matches!(
14
error,
15
Error::Graph(graph::Error::Session(session::Error::Api {
16
status: 403 | 404 | 410,
17
..
18
}))
19
)
20
}
21
6
22
impl<R: Remote> SyncEngine<R> {
7
23
/// Once per chat and session, for cached forwards stored before their original message was kept.
8
24
pub(crate) async fn heal_forwards(&self, conversation_id: &str) -> bool {
@@ -20,24 +36,94 @@ impl<R: Remote> SyncEngine<R> {
20
36
else {
21
37
return false;
22
38
};
23
let stale: Vec<String> = cached
24
.iter()
25
.filter(|record| lacks_forward_content(record))
26
.map(|record| record.message_id.clone())
39
let stale_ids: Vec<String> = cached
40
.into_iter()
41
.filter(lacks_forward_content)
42
.map(|record| record.message_id)
27
43
.collect();
28
if stale.is_empty() {
44
if stale_ids.is_empty() {
29
45
return false;
30
46
}
31
let Ok(answers) = self.remote.chat_messages_by_id(conversation_id, &stale).await else {
47
let Ok(answers) = self
48
.remote
49
.chat_messages_by_id(conversation_id, &stale_ids)
50
.await
51
else {
32
52
return false;
33
53
};
34
let mut records: Vec<_> = answers
35
.iter()
36
.flatten()
37
.filter_map(|message| message_record(conversation_id, message))
38
.collect();
39
self.apply_chat_emotions(conversation_id, &mut records).await;
40
self.ingest(conversation_id, records)
54
let mut healed = Vec::new();
55
let mut given_up_ids = Vec::new();
56
for (message_id, answer) in stale_ids.iter().zip(answers) {
57
let fresh = match answer {
58
Ok(message) => message_record(conversation_id, &message),
59
Err(error) if is_gone(&error) => None,
60
Err(_) => continue,
61
};
62
match fresh {
63
Some(record) if !lacks_forward_content(&record) => healed.push(record),
64
_ => given_up_ids.push(message_id.clone()),
65
}
66
}
67
self.apply_chat_emotions(conversation_id, &mut healed).await;
68
healed.extend(self.given_up_forwards(conversation_id, &given_up_ids));
69
self.ingest(conversation_id, healed)
41
70
.is_ok_and(|delta| !delta.is_empty())
42
71
}
72
73
/// Read again, as the delta fetch running alongside may have stored a newer version meanwhile.
74
fn given_up_forwards(
75
&self,
76
conversation_id: &str,
77
message_ids: &[String],
78
) -> Vec<MessageRecord> {
79
if message_ids.is_empty() {
80
return Vec::new();
81
}
82
self.store
83
.messages_by_id(conversation_id, message_ids)
84
.map(|current| {
85
current
86
.values()
87
.filter_map(mark_forwards_unavailable)
88
.collect()
89
})
90
.unwrap_or_default()
91
}
92
93
/// Heals every chat that still holds forwards without their original, newest chat first, one Graph batch per chat.
94
pub async fn heal_all_forwards(&self, pause: Duration) {
95
let Ok(conversation_ids) = self
96
.store
97
.conversations_with_stale_attachments(FORWARDED_CONTENT_TYPE)
98
else {
99
return;
100
};
101
for conversation_id in conversation_ids {
102
if self.heal_forwards(&conversation_id).await {
103
self.announce(&conversation_id, true);
104
}
105
tokio::time::sleep(pause).await;
106
}
107
}
108
}
109
110
#[cfg(test)]
111
mod tests {
112
use super::*;
113
114
#[test]
115
fn only_a_definite_graph_answer_gives_a_forward_up() {
116
let api = |status| {
117
Error::Graph(graph::Error::Session(session::Error::api(
118
status,
119
"https://graph.microsoft.com/v1.0/chats/c/messages/m",
120
serde_json::json!({}),
121
)))
122
};
123
assert!(is_gone(&api(404)));
124
assert!(is_gone(&api(403)));
125
assert!(!is_gone(&api(429)));
126
assert!(!is_gone(&api(503)));
127
assert!(!is_gone(&Error::Unsupported("batched message reads")));
128
}
43
129
}
@@ -1,8 +1,24 @@1
use std::time::Duration;2
3
use store::MessageRecord;4
1
use crate::engine::{Conversation, SyncEngine};5
use crate::engine::{Conversation, SyncEngine};2
use crate::forwarded::{FORWARDED_CONTENT_TYPE, lacks_forward_content};6
use crate::error::Error;7
use crate::forwarded::{FORWARDED_CONTENT_TYPE, lacks_forward_content, mark_forwards_unavailable};3
use crate::mapping::message_record;8
use crate::mapping::message_record;4
use crate::remote::Remote;9
use crate::remote::Remote;5
10
11
/// Graph answered for good: the original is gone or not readable for this account.12
fn is_gone(error: &Error) -> bool {13
matches!(14
error,15
Error::Graph(graph::Error::Session(session::Error::Api {16
status: 403 | 404 | 410,17
..18
}))19
)20
}21
6
impl<R: Remote> SyncEngine<R> {22
impl<R: Remote> SyncEngine<R> {7
/// Once per chat and session, for cached forwards stored before their original message was kept.23
/// Once per chat and session, for cached forwards stored before their original message was kept.8
pub(crate) async fn heal_forwards(&self, conversation_id: &str) -> bool {24
pub(crate) async fn heal_forwards(&self, conversation_id: &str) -> bool {@@ -20,24 +36,94 @@ impl<R: Remote> SyncEngine<R> {20
else {36
else {21
return false;37
return false;22
};38
};23
let stale: Vec<String> = cached39
let stale_ids: Vec<String> = cached24
.iter()40
.into_iter()25
.filter(|record| lacks_forward_content(record))41
.filter(lacks_forward_content)26
.map(|record| record.message_id.clone())42
.map(|record| record.message_id)27
.collect();43
.collect();28
if stale.is_empty() {44
if stale_ids.is_empty() {29
return false;45
return false;30
}46
}31
let Ok(answers) = self.remote.chat_messages_by_id(conversation_id, &stale).await else {47
let Ok(answers) = self48
.remote49
.chat_messages_by_id(conversation_id, &stale_ids)50
.await51
else {32
return false;52
return false;33
};53
};34
let mut records: Vec<_> = answers54
let mut healed = Vec::new();35
.iter()55
let mut given_up_ids = Vec::new();36
.flatten()56
for (message_id, answer) in stale_ids.iter().zip(answers) {37
.filter_map(|message| message_record(conversation_id, message))57
let fresh = match answer {38
.collect();58
Ok(message) => message_record(conversation_id, &message),39
self.apply_chat_emotions(conversation_id, &mut records).await;59
Err(error) if is_gone(&error) => None,40
self.ingest(conversation_id, records)60
Err(_) => continue,61
};62
match fresh {63
Some(record) if !lacks_forward_content(&record) => healed.push(record),64
_ => given_up_ids.push(message_id.clone()),65
}66
}67
self.apply_chat_emotions(conversation_id, &mut healed).await;68
healed.extend(self.given_up_forwards(conversation_id, &given_up_ids));69
self.ingest(conversation_id, healed)41
.is_ok_and(|delta| !delta.is_empty())70
.is_ok_and(|delta| !delta.is_empty())42
}71
}72
73
/// Read again, as the delta fetch running alongside may have stored a newer version meanwhile.74
fn given_up_forwards(75
&self,76
conversation_id: &str,77
message_ids: &[String],78
) -> Vec<MessageRecord> {79
if message_ids.is_empty() {80
return Vec::new();81
}82
self.store83
.messages_by_id(conversation_id, message_ids)84
.map(|current| {85
current86
.values()87
.filter_map(mark_forwards_unavailable)88
.collect()89
})90
.unwrap_or_default()91
}92
93
/// Heals every chat that still holds forwards without their original, newest chat first, one Graph batch per chat.94
pub async fn heal_all_forwards(&self, pause: Duration) {95
let Ok(conversation_ids) = self96
.store97
.conversations_with_stale_attachments(FORWARDED_CONTENT_TYPE)98
else {99
return;100
};101
for conversation_id in conversation_ids {102
if self.heal_forwards(&conversation_id).await {103
self.announce(&conversation_id, true);104
}105
tokio::time::sleep(pause).await;106
}107
}108
}109
110
#[cfg(test)]111
mod tests {112
use super::*;113
114
#[test]115
fn only_a_definite_graph_answer_gives_a_forward_up() {116
let api = |status| {117
Error::Graph(graph::Error::Session(session::Error::api(118
status,119
"https://graph.microsoft.com/v1.0/chats/c/messages/m",120
serde_json::json!({}),121
)))122
};123
assert!(is_gone(&api(404)));124
assert!(is_gone(&api(403)));125
assert!(!is_gone(&api(429)));126
assert!(!is_gone(&api(503)));127
assert!(!is_gone(&Error::Unsupported("batched message reads")));128
}43
}129
}@@ -11,13 +11,24 @@ use crate::stored::{AttachmentInfo, attachments, push_plain};
11
11
12
12
pub const FORWARDED_CONTENT_TYPE: &str = "forwardedMessageReference";
13
13
pub(crate) const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";
14
pub const FORWARD_LOADING_TEXT: &str = "Loading forwarded message";
15
pub const FORWARD_UNAVAILABLE_TEXT: &str = "Original message not available";
14
16
15
17
static MENTION_ID: LazyLock<Regex> =
16
18
LazyLock::new(|| Regex::new(r"<at\b[^>]*>").expect("mention tag pattern"));
17
19
20
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21
pub enum ForwardState {
22
Ready,
23
/// Cached without its original; the heal fetches it.
24
Loading,
25
Unavailable,
26
}
27
18
28
/// The original message carried by a Graph `forwardedMessageReference` attachment.
19
29
#[derive(Debug, Clone, PartialEq, Eq)]
20
30
pub struct ForwardInfo {
31
pub state: ForwardState,
21
32
pub attachment_id: Option<String>,
22
33
pub message_id: String,
23
34
pub conversation_id: Option<String>,
@@ -43,9 +54,13 @@ impl ForwardInfo {
43
54
if attachment.content_type.as_deref() != Some(FORWARDED_CONTENT_TYPE) {
44
55
return None;
45
56
}
46
let content: ForwardContent = serde_json::from_str(attachment.content.as_deref()?).ok()?;
57
let Some(raw) = attachment.content.as_deref() else {
58
return Some(ForwardInfo::without_content(attachment));
59
};
60
let content: ForwardContent = serde_json::from_str(raw).ok()?;
47
61
let sender = content.original_message_sender.as_ref();
48
62
Some(ForwardInfo {
63
state: ForwardState::Ready,
49
64
message_id: content
50
65
.original_message_id
51
66
.or_else(|| attachment.id.clone())?,
@@ -62,6 +77,23 @@ impl ForwardInfo {
62
77
})
63
78
}
64
79
80
fn without_content(attachment: &AttachmentInfo) -> ForwardInfo {
81
ForwardInfo {
82
state: if attachment.unavailable {
83
ForwardState::Unavailable
84
} else {
85
ForwardState::Loading
86
},
87
attachment_id: attachment.id.clone(),
88
message_id: attachment.id.clone().unwrap_or_default(),
89
conversation_id: None,
90
sender_id: None,
91
sender_name: None,
92
sent_at: None,
93
content_html: String::new(),
94
}
95
}
96
65
97
pub fn text(&self) -> String {
66
98
let mut text = String::new();
67
99
push_plain(&mut text, &html_to_spans(&self.content_html));
@@ -80,7 +112,13 @@ impl ForwardInfo {
80
112
.as_deref()
81
113
.map(|time| format!(" <span>{}</span>", escape_html(time)))
82
114
.unwrap_or_default();
83
let content = MENTION_ID.replace_all(&self.content_html, "<at>");
115
let content = match self.state {
116
ForwardState::Ready => MENTION_ID.replace_all(&self.content_html, "<at>"),
117
ForwardState::Loading => format!("<p><em>{FORWARD_LOADING_TEXT}</em></p>").into(),
118
ForwardState::Unavailable => {
119
format!("<p><em>{FORWARD_UNAVAILABLE_TEXT}</em></p>").into()
120
}
121
};
84
122
format!(
85
123
"<blockquote itemscope=\"\" itemtype=\"http://{FORWARD_ITEMTYPE}\" itemid=\"{}\">{sender}{time}{content}</blockquote>",
86
124
escape_html(&self.message_id),
@@ -117,11 +155,29 @@ pub fn is_forwarded(record: &MessageRecord) -> bool {
117
155
!record.deleted && (record.body_html.contains(FORWARD_ITEMTYPE) || !forwards(record).is_empty())
118
156
}
119
157
120
/// A forward attachment cached before its content was kept.
158
fn is_stale_forward(attachment: &AttachmentInfo) -> bool {
159
attachment.content_type.as_deref() == Some(FORWARDED_CONTENT_TYPE)
160
&& attachment.content.is_none()
161
&& !attachment.unavailable
162
}
163
164
/// A forward attachment cached before its content was kept, and not given up on.
121
165
pub(crate) fn lacks_forward_content(record: &MessageRecord) -> bool {
122
attachments(record).iter().any(|attachment| {
123
attachment.content_type.as_deref() == Some(FORWARDED_CONTENT_TYPE)
124
&& attachment.content.is_none()
166
attachments(record).iter().any(is_stale_forward)
167
}
168
169
/// `record` with each stale forward marked as unavailable, so it is not fetched again.
170
pub(crate) fn mark_forwards_unavailable(record: &MessageRecord) -> Option<MessageRecord> {
171
let mut stored = attachments(record);
172
let mut changed = false;
173
for attachment in stored.iter_mut().filter(|attachment| is_stale_forward(attachment)) {
174
attachment.unavailable = true;
175
changed = true;
176
}
177
let attachments_json = serde_json::to_string(&stored).ok()?;
178
changed.then(|| MessageRecord {
179
attachments_json,
180
..record.clone()
125
181
})
126
182
}
127
183
@@ -272,7 +328,33 @@ mod tests {
272
328
assert!(!lacks_forward_content(&record));
273
329
record.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"1792149081221","content":null}]"#.to_owned();
274
330
assert!(lacks_forward_content(&record));
275
assert!(forwards(&record).is_empty());
331
let found = forwards(&record);
332
assert_eq!(found.len(), 1);
333
assert_eq!(found[0].state, ForwardState::Loading);
334
assert!(forwarded_texts(&record).is_empty());
335
}
336
337
fn quote_text(record: &MessageRecord) -> String {
338
let spans = linked_message_spans_with(record, &|_| None, &no_forward_header);
339
let [Span::BlockQuote(children)] = spans.as_slice() else {
340
panic!("expected one forward blockquote, got {spans:?}");
341
};
342
plain(children)
343
}
344
345
#[test]
346
fn a_forward_without_content_shows_a_loading_line_until_it_is_given_up() {
347
let mut record = forwarded_record();
348
record.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"1792149081221","content":null}]"#.to_owned();
349
assert!(is_forwarded(&record));
350
assert_eq!(quote_text(&record).trim(), FORWARD_LOADING_TEXT);
351
352
let given_up = mark_forwards_unavailable(&record).unwrap();
353
assert!(!lacks_forward_content(&given_up));
354
assert_eq!(forwards(&given_up)[0].state, ForwardState::Unavailable);
355
assert_eq!(quote_text(&given_up).trim(), FORWARD_UNAVAILABLE_TEXT);
356
assert!(mark_forwards_unavailable(&given_up).is_none());
357
assert!(edit_preserved(&given_up).kept.is_empty());
276
358
}
277
359
278
360
#[test]
@@ -11,13 +11,24 @@ use crate::stored::{AttachmentInfo, attachments, push_plain};11
11
12
pub const FORWARDED_CONTENT_TYPE: &str = "forwardedMessageReference";12
pub const FORWARDED_CONTENT_TYPE: &str = "forwardedMessageReference";13
pub(crate) const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";13
pub(crate) const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";14
pub const FORWARD_LOADING_TEXT: &str = "Loading forwarded message";15
pub const FORWARD_UNAVAILABLE_TEXT: &str = "Original message not available";14
16
15
static MENTION_ID: LazyLock<Regex> =17
static MENTION_ID: LazyLock<Regex> =16
LazyLock::new(|| Regex::new(r"<at\b[^>]*>").expect("mention tag pattern"));18
LazyLock::new(|| Regex::new(r"<at\b[^>]*>").expect("mention tag pattern"));17
19
20
#[derive(Debug, Clone, Copy, PartialEq, Eq)]21
pub enum ForwardState {22
Ready,23
/// Cached without its original; the heal fetches it.24
Loading,25
Unavailable,26
}27
18
/// The original message carried by a Graph `forwardedMessageReference` attachment.28
/// The original message carried by a Graph `forwardedMessageReference` attachment.19
#[derive(Debug, Clone, PartialEq, Eq)]29
#[derive(Debug, Clone, PartialEq, Eq)]20
pub struct ForwardInfo {30
pub struct ForwardInfo {31
pub state: ForwardState,21
pub attachment_id: Option<String>,32
pub attachment_id: Option<String>,22
pub message_id: String,33
pub message_id: String,23
pub conversation_id: Option<String>,34
pub conversation_id: Option<String>,@@ -43,9 +54,13 @@ impl ForwardInfo {43
if attachment.content_type.as_deref() != Some(FORWARDED_CONTENT_TYPE) {54
if attachment.content_type.as_deref() != Some(FORWARDED_CONTENT_TYPE) {44
return None;55
return None;45
}56
}46
let content: ForwardContent = serde_json::from_str(attachment.content.as_deref()?).ok()?;57
let Some(raw) = attachment.content.as_deref() else {58
return Some(ForwardInfo::without_content(attachment));59
};60
let content: ForwardContent = serde_json::from_str(raw).ok()?;47
let sender = content.original_message_sender.as_ref();61
let sender = content.original_message_sender.as_ref();48
Some(ForwardInfo {62
Some(ForwardInfo {63
state: ForwardState::Ready,49
message_id: content64
message_id: content50
.original_message_id65
.original_message_id51
.or_else(|| attachment.id.clone())?,66
.or_else(|| attachment.id.clone())?,@@ -62,6 +77,23 @@ impl ForwardInfo {62
})77
})63
}78
}64
79
80
fn without_content(attachment: &AttachmentInfo) -> ForwardInfo {81
ForwardInfo {82
state: if attachment.unavailable {83
ForwardState::Unavailable84
} else {85
ForwardState::Loading86
},87
attachment_id: attachment.id.clone(),88
message_id: attachment.id.clone().unwrap_or_default(),89
conversation_id: None,90
sender_id: None,91
sender_name: None,92
sent_at: None,93
content_html: String::new(),94
}95
}96
65
pub fn text(&self) -> String {97
pub fn text(&self) -> String {66
let mut text = String::new();98
let mut text = String::new();67
push_plain(&mut text, &html_to_spans(&self.content_html));99
push_plain(&mut text, &html_to_spans(&self.content_html));@@ -80,7 +112,13 @@ impl ForwardInfo {80
.as_deref()112
.as_deref()81
.map(|time| format!(" <span>{}</span>", escape_html(time)))113
.map(|time| format!(" <span>{}</span>", escape_html(time)))82
.unwrap_or_default();114
.unwrap_or_default();83
let content = MENTION_ID.replace_all(&self.content_html, "<at>");115
let content = match self.state {116
ForwardState::Ready => MENTION_ID.replace_all(&self.content_html, "<at>"),117
ForwardState::Loading => format!("<p><em>{FORWARD_LOADING_TEXT}</em></p>").into(),118
ForwardState::Unavailable => {119
format!("<p><em>{FORWARD_UNAVAILABLE_TEXT}</em></p>").into()120
}121
};84
format!(122
format!(85
"<blockquote itemscope=\"\" itemtype=\"http://{FORWARD_ITEMTYPE}\" itemid=\"{}\">{sender}{time}{content}</blockquote>",123
"<blockquote itemscope=\"\" itemtype=\"http://{FORWARD_ITEMTYPE}\" itemid=\"{}\">{sender}{time}{content}</blockquote>",86
escape_html(&self.message_id),124
escape_html(&self.message_id),@@ -117,11 +155,29 @@ pub fn is_forwarded(record: &MessageRecord) -> bool {117
!record.deleted && (record.body_html.contains(FORWARD_ITEMTYPE) || !forwards(record).is_empty())155
!record.deleted && (record.body_html.contains(FORWARD_ITEMTYPE) || !forwards(record).is_empty())118
}156
}119
157
120
/// A forward attachment cached before its content was kept.158
fn is_stale_forward(attachment: &AttachmentInfo) -> bool {159
attachment.content_type.as_deref() == Some(FORWARDED_CONTENT_TYPE)160
&& attachment.content.is_none()161
&& !attachment.unavailable162
}163
164
/// A forward attachment cached before its content was kept, and not given up on.121
pub(crate) fn lacks_forward_content(record: &MessageRecord) -> bool {165
pub(crate) fn lacks_forward_content(record: &MessageRecord) -> bool {122
attachments(record).iter().any(|attachment| {166
attachments(record).iter().any(is_stale_forward)123
attachment.content_type.as_deref() == Some(FORWARDED_CONTENT_TYPE)167
}124
&& attachment.content.is_none()168
169
/// `record` with each stale forward marked as unavailable, so it is not fetched again.170
pub(crate) fn mark_forwards_unavailable(record: &MessageRecord) -> Option<MessageRecord> {171
let mut stored = attachments(record);172
let mut changed = false;173
for attachment in stored.iter_mut().filter(|attachment| is_stale_forward(attachment)) {174
attachment.unavailable = true;175
changed = true;176
}177
let attachments_json = serde_json::to_string(&stored).ok()?;178
changed.then(|| MessageRecord {179
attachments_json,180
..record.clone()125
})181
})126
}182
}127
183
@@ -272,7 +328,33 @@ mod tests {272
assert!(!lacks_forward_content(&record));328
assert!(!lacks_forward_content(&record));273
record.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"1792149081221","content":null}]"#.to_owned();329
record.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"1792149081221","content":null}]"#.to_owned();274
assert!(lacks_forward_content(&record));330
assert!(lacks_forward_content(&record));275
assert!(forwards(&record).is_empty());331
let found = forwards(&record);332
assert_eq!(found.len(), 1);333
assert_eq!(found[0].state, ForwardState::Loading);334
assert!(forwarded_texts(&record).is_empty());335
}336
337
fn quote_text(record: &MessageRecord) -> String {338
let spans = linked_message_spans_with(record, &|_| None, &no_forward_header);339
let [Span::BlockQuote(children)] = spans.as_slice() else {340
panic!("expected one forward blockquote, got {spans:?}");341
};342
plain(children)343
}344
345
#[test]346
fn a_forward_without_content_shows_a_loading_line_until_it_is_given_up() {347
let mut record = forwarded_record();348
record.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"1792149081221","content":null}]"#.to_owned();349
assert!(is_forwarded(&record));350
assert_eq!(quote_text(&record).trim(), FORWARD_LOADING_TEXT);351
352
let given_up = mark_forwards_unavailable(&record).unwrap();353
assert!(!lacks_forward_content(&given_up));354
assert_eq!(forwards(&given_up)[0].state, ForwardState::Unavailable);355
assert_eq!(quote_text(&given_up).trim(), FORWARD_UNAVAILABLE_TEXT);356
assert!(mark_forwards_unavailable(&given_up).is_none());357
assert!(edit_preserved(&given_up).kept.is_empty());276
}358
}277
359
278
#[test]360
#[test]@@ -142,7 +142,8 @@ pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
142
142
pub use scheduled::NOTES_CHAT_ID;
143
143
pub use skin_tone::{skin_tone, store_account_skin_tone};
144
144
pub use forwarded::{
145
FORWARDED_CONTENT_TYPE, ForwardHeader, ForwardInfo, forwarded_texts, forwards, is_forwarded,
145
FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,
146
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
146
147
};
147
148
pub use spans::{FontSize, Span, html_to_spans};
148
149
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
@@ -142,7 +142,8 @@ pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};142
pub use scheduled::NOTES_CHAT_ID;142
pub use scheduled::NOTES_CHAT_ID;143
pub use skin_tone::{skin_tone, store_account_skin_tone};143
pub use skin_tone::{skin_tone, store_account_skin_tone};144
pub use forwarded::{144
pub use forwarded::{145
FORWARDED_CONTENT_TYPE, ForwardHeader, ForwardInfo, forwarded_texts, forwards, is_forwarded,145
FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,146
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,146
};147
};147
pub use spans::{FontSize, Span, html_to_spans};148
pub use spans::{FontSize, Span, html_to_spans};148
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};149
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};@@ -239,6 +239,7 @@ pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {
239
239
Some("messageReference" | FORWARDED_CONTENT_TYPE)
240
240
)
241
241
}),
242
unavailable: false,
242
243
}
243
244
}
244
245
@@ -239,6 +239,7 @@ pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {239
Some("messageReference" | FORWARDED_CONTENT_TYPE)239
Some("messageReference" | FORWARDED_CONTENT_TYPE)240
)240
)241
}),241
}),242
unavailable: false,242
}243
}243
}244
}244
245
@@ -28,6 +28,9 @@ pub struct AttachmentInfo {
28
28
/// Raw content, kept only for quotes and cards so an edit can send them back unchanged.
29
29
#[serde(default)]
30
30
pub content: Option<String>,
31
/// A forward whose original Graph did not return; it is not fetched again.
32
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
33
pub unavailable: bool,
31
34
}
32
35
33
36
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -1048,6 +1051,7 @@ mod tests {
1048
1051
quote: None,
1049
1052
id: None,
1050
1053
content: None,
1054
unavailable: false,
1051
1055
}
1052
1056
.file_kind()
1053
1057
};
@@ -28,6 +28,9 @@ pub struct AttachmentInfo {28
/// Raw content, kept only for quotes and cards so an edit can send them back unchanged.28
/// Raw content, kept only for quotes and cards so an edit can send them back unchanged.29
#[serde(default)]29
#[serde(default)]30
pub content: Option<String>,30
pub content: Option<String>,31
/// A forward whose original Graph did not return; it is not fetched again.32
#[serde(default, skip_serializing_if = "std::ops::Not::not")]33
pub unavailable: bool,31
}34
}32
35
33
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]36
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]@@ -1048,6 +1051,7 @@ mod tests {1048
quote: None,1051
quote: None,1049
id: None,1052
id: None,1050
content: None,1053
content: None,1054
unavailable: false,1051
}1055
}1052
.file_kind()1056
.file_kind()1053
};1057
};@@ -4761,3 +4761,99 @@ async fn a_forward_cached_without_its_content_is_read_again_once() {
4761
4761
engine.fetch_newer(CHAT).await.unwrap();
4762
4762
assert_eq!(reads(&fake), 1);
4763
4763
}
4764
4765
const STALE_FORWARD: &str = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"orig-1","content":null}]"#;
4766
4767
fn stale_forward(conversation_id: &str, message_id: &str, minute: i64) -> store::MessageRecord {
4768
let mut stale =
4769
teams_core::message_record(conversation_id, &forwarded_message(message_id, minute))
4770
.unwrap();
4771
stale.attachments_json = STALE_FORWARD.to_owned();
4772
stale
4773
}
4774
4775
fn forwarded_message_without_original(id: &str, minute: i64) -> Message {
4776
let mut message = forwarded_message(id, minute);
4777
message.attachments[0].content = None;
4778
message
4779
}
4780
4781
fn forward_state(store: &Store, conversation_id: &str, message_id: &str) -> teams_core::ForwardState {
4782
let record = store
4783
.messages_by_id(conversation_id, &[message_id.to_owned()])
4784
.unwrap()
4785
.remove(message_id)
4786
.unwrap();
4787
teams_core::forwards(&record)[0].state
4788
}
4789
4790
#[tokio::test]
4791
async fn a_forward_graph_returns_without_its_original_is_not_read_again() {
4792
let fake = Arc::new(Fake::default());
4793
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
4794
let store = Arc::new(Store::open_in_memory().unwrap());
4795
let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());
4796
engine.refresh_sidebar().await.unwrap();
4797
let mut messages = numbered(11);
4798
messages.push(forwarded_message_without_original("m0000", 0));
4799
fake.set_chat_messages(messages);
4800
store.upsert_messages(&[stale_forward(CHAT, "m0000", 0)]).unwrap();
4801
assert_eq!(forward_state(&store, CHAT, "m0000"), teams_core::ForwardState::Loading);
4802
4803
engine.fetch_newer(CHAT).await.unwrap();
4804
4805
assert_eq!(forward_state(&store, CHAT, "m0000"), teams_core::ForwardState::Unavailable);
4806
let next_session = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());
4807
next_session.fetch_newer(CHAT).await.unwrap();
4808
let reads = fake
4809
.calls()
4810
.iter()
4811
.filter(|call| *call == "chat_message m0000")
4812
.count();
4813
assert_eq!(reads, 1);
4814
}
4815
4816
#[tokio::test]
4817
async fn the_background_heal_reads_the_newest_chat_first_and_skips_healthy_chats() {
4818
const OLDER: &str = "19:older@thread.v2";
4819
const HEALTHY: &str = "19:healthy@thread.v2";
4820
let fake = Arc::new(Fake::default());
4821
*fake.chats.lock().unwrap() = vec![
4822
chat(OLDER, Some("Older"), 2, 2, ME, false),
4823
chat(CHAT, Some("Newer"), 9, 9, ME, false),
4824
chat(HEALTHY, Some("Healthy"), 12, 12, ME, false),
4825
];
4826
let store = Arc::new(Store::open_in_memory().unwrap());
4827
let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());
4828
engine.refresh_sidebar().await.unwrap();
4829
fake.set_chat_messages(vec![
4830
forwarded_message("f-older", 1),
4831
forwarded_message("f-newer", 8),
4832
]);
4833
let healthy = teams_core::message_record(HEALTHY, &forwarded_message("f-healthy", 11)).unwrap();
4834
store
4835
.upsert_messages(&[
4836
stale_forward(OLDER, "f-older", 1),
4837
stale_forward(CHAT, "f-newer", 8),
4838
healthy,
4839
])
4840
.unwrap();
4841
let mut events = engine.subscribe();
4842
4843
engine.heal_all_forwards(std::time::Duration::ZERO).await;
4844
4845
let reads: Vec<String> = fake
4846
.calls()
4847
.into_iter()
4848
.filter(|call| call.starts_with("chat_message "))
4849
.collect();
4850
assert_eq!(reads, ["chat_message f-newer", "chat_message f-older"]);
4851
assert_eq!(forward_state(&store, OLDER, "f-older"), teams_core::ForwardState::Ready);
4852
let mut changed = Vec::new();
4853
while let Ok(event) = events.try_recv() {
4854
if let CoreEvent::MessagesChanged { conversation_id } = event {
4855
changed.push(conversation_id);
4856
}
4857
}
4858
assert_eq!(changed, [CHAT, OLDER]);
4859
}
@@ -4761,3 +4761,99 @@ async fn a_forward_cached_without_its_content_is_read_again_once() {4761
engine.fetch_newer(CHAT).await.unwrap();4761
engine.fetch_newer(CHAT).await.unwrap();4762
assert_eq!(reads(&fake), 1);4762
assert_eq!(reads(&fake), 1);4763
}4763
}4764
4765
const STALE_FORWARD: &str = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"orig-1","content":null}]"#;4766
4767
fn stale_forward(conversation_id: &str, message_id: &str, minute: i64) -> store::MessageRecord {4768
let mut stale =4769
teams_core::message_record(conversation_id, &forwarded_message(message_id, minute))4770
.unwrap();4771
stale.attachments_json = STALE_FORWARD.to_owned();4772
stale4773
}4774
4775
fn forwarded_message_without_original(id: &str, minute: i64) -> Message {4776
let mut message = forwarded_message(id, minute);4777
message.attachments[0].content = None;4778
message4779
}4780
4781
fn forward_state(store: &Store, conversation_id: &str, message_id: &str) -> teams_core::ForwardState {4782
let record = store4783
.messages_by_id(conversation_id, &[message_id.to_owned()])4784
.unwrap()4785
.remove(message_id)4786
.unwrap();4787
teams_core::forwards(&record)[0].state4788
}4789
4790
#[tokio::test]4791
async fn a_forward_graph_returns_without_its_original_is_not_read_again() {4792
let fake = Arc::new(Fake::default());4793
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];4794
let store = Arc::new(Store::open_in_memory().unwrap());4795
let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());4796
engine.refresh_sidebar().await.unwrap();4797
let mut messages = numbered(11);4798
messages.push(forwarded_message_without_original("m0000", 0));4799
fake.set_chat_messages(messages);4800
store.upsert_messages(&[stale_forward(CHAT, "m0000", 0)]).unwrap();4801
assert_eq!(forward_state(&store, CHAT, "m0000"), teams_core::ForwardState::Loading);4802
4803
engine.fetch_newer(CHAT).await.unwrap();4804
4805
assert_eq!(forward_state(&store, CHAT, "m0000"), teams_core::ForwardState::Unavailable);4806
let next_session = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());4807
next_session.fetch_newer(CHAT).await.unwrap();4808
let reads = fake4809
.calls()4810
.iter()4811
.filter(|call| *call == "chat_message m0000")4812
.count();4813
assert_eq!(reads, 1);4814
}4815
4816
#[tokio::test]4817
async fn the_background_heal_reads_the_newest_chat_first_and_skips_healthy_chats() {4818
const OLDER: &str = "19:older@thread.v2";4819
const HEALTHY: &str = "19:healthy@thread.v2";4820
let fake = Arc::new(Fake::default());4821
*fake.chats.lock().unwrap() = vec![4822
chat(OLDER, Some("Older"), 2, 2, ME, false),4823
chat(CHAT, Some("Newer"), 9, 9, ME, false),4824
chat(HEALTHY, Some("Healthy"), 12, 12, ME, false),4825
];4826
let store = Arc::new(Store::open_in_memory().unwrap());4827
let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());4828
engine.refresh_sidebar().await.unwrap();4829
fake.set_chat_messages(vec![4830
forwarded_message("f-older", 1),4831
forwarded_message("f-newer", 8),4832
]);4833
let healthy = teams_core::message_record(HEALTHY, &forwarded_message("f-healthy", 11)).unwrap();4834
store4835
.upsert_messages(&[4836
stale_forward(OLDER, "f-older", 1),4837
stale_forward(CHAT, "f-newer", 8),4838
healthy,4839
])4840
.unwrap();4841
let mut events = engine.subscribe();4842
4843
engine.heal_all_forwards(std::time::Duration::ZERO).await;4844
4845
let reads: Vec<String> = fake4846
.calls()4847
.into_iter()4848
.filter(|call| call.starts_with("chat_message "))4849
.collect();4850
assert_eq!(reads, ["chat_message f-newer", "chat_message f-older"]);4851
assert_eq!(forward_state(&store, OLDER, "f-older"), teams_core::ForwardState::Ready);4852
let mut changed = Vec::new();4853
while let Ok(event) = events.try_recv() {4854
if let CoreEvent::MessagesChanged { conversation_id } = event {4855
changed.push(conversation_id);4856
}4857
}4858
assert_eq!(changed, [CHAT, OLDER]);4859
}@@ -269,6 +269,28 @@ impl Store {
269
269
Ok(messages)
270
270
}
271
271
272
/// Chats, newest first, holding an attachment of `content_type` without content that is not marked unavailable.
273
pub fn conversations_with_stale_attachments(&self, content_type: &str) -> Result<Vec<String>> {
274
let connection = self.lock()?;
275
let mut statement = connection.prepare_cached(
276
"SELECT chats.id FROM chats
277
WHERE EXISTS (
278
SELECT 1 FROM messages, json_each(messages.attachments_json) AS attachment
279
WHERE messages.conversation_id = chats.id
280
AND instr(messages.attachments_json, ?1) > 0
281
AND json_extract(attachment.value, '$.content_type') = ?2
282
AND json_extract(attachment.value, '$.content') IS NULL
283
AND NOT coalesce(json_extract(attachment.value, '$.unavailable'), 0)
284
)
285
ORDER BY chats.last_message_at DESC",
286
)?;
287
let needle = format!("\"content_type\":\"{content_type}\"");
288
let conversation_ids = statement
289
.query_map(params![needle, content_type], |row| row.get(0))?
290
.collect::<rusqlite::Result<Vec<String>>>()?;
291
Ok(conversation_ids)
292
}
293
272
294
pub fn messages_by_id(
273
295
&self,
274
296
conversation_id: &str,
@@ -269,6 +269,28 @@ impl Store {269
Ok(messages)269
Ok(messages)270
}270
}271
271
272
/// Chats, newest first, holding an attachment of `content_type` without content that is not marked unavailable.273
pub fn conversations_with_stale_attachments(&self, content_type: &str) -> Result<Vec<String>> {274
let connection = self.lock()?;275
let mut statement = connection.prepare_cached(276
"SELECT chats.id FROM chats277
WHERE EXISTS (278
SELECT 1 FROM messages, json_each(messages.attachments_json) AS attachment279
WHERE messages.conversation_id = chats.id280
AND instr(messages.attachments_json, ?1) > 0281
AND json_extract(attachment.value, '$.content_type') = ?2282
AND json_extract(attachment.value, '$.content') IS NULL283
AND NOT coalesce(json_extract(attachment.value, '$.unavailable'), 0)284
)285
ORDER BY chats.last_message_at DESC",286
)?;287
let needle = format!("\"content_type\":\"{content_type}\"");288
let conversation_ids = statement289
.query_map(params![needle, content_type], |row| row.get(0))?290
.collect::<rusqlite::Result<Vec<String>>>()?;291
Ok(conversation_ids)292
}293
272
pub fn messages_by_id(294
pub fn messages_by_id(273
&self,295
&self,274
conversation_id: &str,296
conversation_id: &str,