Merge remote-tracking branch 'origin/main' into fix/members-row-height
# Conflicts: # crates/store/src/lib.rs # crates/store/tests/store.rs
@@ -15,7 +15,7 @@ Feature parity with the Microsoft Teams desktop client.
15
15
| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |
16
16
| [Channels](#channels) | 100 % | 7 | 0 | 0 |
17
17
| [Notifications](#notifications) | 89 % | 8 | 0 | 1 |
18
| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |
18
| [Search and navigation](#search-and-navigation) | 92 % | 5 | 1 | 0 |
19
19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20
20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21
21
| [Calls and meetings](#calls-and-meetings) | 62 % | 15 | 18 | 6 |
@@ -138,6 +138,7 @@ Feature parity with the Microsoft Teams desktop client.
138
138
| Ctrl+K switcher over chats, channels, people | Done | |
139
139
| Full-text search over cached messages | Done | |
140
140
| Jump to a message from search | Done | |
141
| Server search over the full history like Teams | Partial | Substrate search client in the engine (typeahead, results by tab, find in chat, KQL filters); palette and results page still use the local index |
141
142
| Esc closes the open conversation or editor | Done | Back to the channel keeps the feed position |
142
143
| Keyboard shortcuts like Teams | Done | Ctrl+1 Activity, 2 Chats, 3 Channels, 4 Saved; Alt+Up/Down previous and next chat or channel in the visible list, also while typing; calls Ctrl+Shift+A accept, D decline, H hang up, O camera, E share menu, K raise hand, Y lobby, M mute, J join from a meeting reminder, Space held with Ctrl to talk while muted, F11 full screen, Alt+Shift+A / V start an audio / video call in the open chat; Ctrl+. lists all shortcuts. Ctrl+5..9 not used |
143
144
@@ -225,7 +226,6 @@ After parity. Not counted in the parity score.
225
226
| Feature | Why |
226
227
|---|---|
227
228
| Personal apps in the app bar | Outside chat and channels |
228
| Server-side search | The local index answers faster |
229
229
| Copilot, intelligent recap, AI notes, Facilitator, Interpreter | Needs a Microsoft 365 Copilot licence; left out on purpose |
230
230
| Teams Premium features (translated captions, watermark, E2EE meetings, templates, branding) | Needs a Teams Premium licence |
231
231
| Phone system: dial pad, park, forwarding, voicemail, delegation, queues | Needs a Teams Phone licence; none on the test account |
@@ -15,7 +15,7 @@ Feature parity with the Microsoft Teams desktop client.15
| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |15
| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |16
| [Channels](#channels) | 100 % | 7 | 0 | 0 |16
| [Channels](#channels) | 100 % | 7 | 0 | 0 |17
| [Notifications](#notifications) | 89 % | 8 | 0 | 1 |17
| [Notifications](#notifications) | 89 % | 8 | 0 | 1 |18
| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |18
| [Search and navigation](#search-and-navigation) | 92 % | 5 | 1 | 0 |19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |21
| [Calls and meetings](#calls-and-meetings) | 62 % | 15 | 18 | 6 |21
| [Calls and meetings](#calls-and-meetings) | 62 % | 15 | 18 | 6 |@@ -138,6 +138,7 @@ Feature parity with the Microsoft Teams desktop client.138
| Ctrl+K switcher over chats, channels, people | Done | |138
| Ctrl+K switcher over chats, channels, people | Done | |139
| Full-text search over cached messages | Done | |139
| Full-text search over cached messages | Done | |140
| Jump to a message from search | Done | |140
| Jump to a message from search | Done | |141
| Server search over the full history like Teams | Partial | Substrate search client in the engine (typeahead, results by tab, find in chat, KQL filters); palette and results page still use the local index |141
| Esc closes the open conversation or editor | Done | Back to the channel keeps the feed position |142
| Esc closes the open conversation or editor | Done | Back to the channel keeps the feed position |142
| Keyboard shortcuts like Teams | Done | Ctrl+1 Activity, 2 Chats, 3 Channels, 4 Saved; Alt+Up/Down previous and next chat or channel in the visible list, also while typing; calls Ctrl+Shift+A accept, D decline, H hang up, O camera, E share menu, K raise hand, Y lobby, M mute, J join from a meeting reminder, Space held with Ctrl to talk while muted, F11 full screen, Alt+Shift+A / V start an audio / video call in the open chat; Ctrl+. lists all shortcuts. Ctrl+5..9 not used |143
| Keyboard shortcuts like Teams | Done | Ctrl+1 Activity, 2 Chats, 3 Channels, 4 Saved; Alt+Up/Down previous and next chat or channel in the visible list, also while typing; calls Ctrl+Shift+A accept, D decline, H hang up, O camera, E share menu, K raise hand, Y lobby, M mute, J join from a meeting reminder, Space held with Ctrl to talk while muted, F11 full screen, Alt+Shift+A / V start an audio / video call in the open chat; Ctrl+. lists all shortcuts. Ctrl+5..9 not used |143
144
@@ -225,7 +226,6 @@ After parity. Not counted in the parity score.225
| Feature | Why |226
| Feature | Why |226
|---|---|227
|---|---|227
| Personal apps in the app bar | Outside chat and channels |228
| Personal apps in the app bar | Outside chat and channels |228
| Server-side search | The local index answers faster |229
| Copilot, intelligent recap, AI notes, Facilitator, Interpreter | Needs a Microsoft 365 Copilot licence; left out on purpose |229
| Copilot, intelligent recap, AI notes, Facilitator, Interpreter | Needs a Microsoft 365 Copilot licence; left out on purpose |230
| Teams Premium features (translated captions, watermark, E2EE meetings, templates, branding) | Needs a Teams Premium licence |230
| Teams Premium features (translated captions, watermark, E2EE meetings, templates, branding) | Needs a Teams Premium licence |231
| Phone system: dial pad, park, forwarding, voicemail, delegation, queues | Needs a Teams Phone licence; none on the test account |231
| Phone system: dial pad, park, forwarding, voicemail, delegation, queues | Needs a Teams Phone licence; none on the test account |@@ -104,6 +104,8 @@ pub struct AppState {
104
104
pub bot_apps: HashMap<String, Vec<ChatApp>>,
105
105
pub bot_apps_pending: HashSet<String>,
106
106
pub notice: Option<Notice>,
107
pub connection_banner: crate::connection_banner::BannerTiming,
108
pub live_retry: Option<Arc<tokio::sync::Notify>>,
107
109
pub notice_count: u64,
108
110
pub keep_unread: Option<String>,
109
111
pub typing: TypingState,
@@ -253,6 +255,8 @@ impl AppState {
253
255
bot_apps: HashMap::new(),
254
256
bot_apps_pending: HashSet::new(),
255
257
notice: None,
258
connection_banner: Default::default(),
259
live_retry: None,
256
260
notice_count: 0,
257
261
keep_unread: None,
258
262
typing: TypingState::default(),
@@ -898,8 +902,10 @@ impl AppState {
898
902
match event {
899
903
BackendEvent::Connection(connection) => {
900
904
self.connection = connection;
905
self.refresh_connection_banner(cx);
901
906
cx.emit(AppEvent::Status);
902
907
}
908
BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry),
903
909
BackendEvent::Calls(launcher) => {
904
910
launcher.set_default_camera(self.call_camera.clone());
905
911
self.call_launcher = Some(launcher);
@@ -976,6 +982,7 @@ impl AppState {
976
982
BackendEvent::Typing(event) => self.apply_typing(event, cx),
977
983
BackendEvent::Live(live) => {
978
984
self.live = live;
985
self.refresh_connection_banner(cx);
979
986
cx.emit(AppEvent::Status);
980
987
}
981
988
BackendEvent::Favorites(ids) => {
@@ -104,6 +104,8 @@ pub struct AppState {104
pub bot_apps: HashMap<String, Vec<ChatApp>>,104
pub bot_apps: HashMap<String, Vec<ChatApp>>,105
pub bot_apps_pending: HashSet<String>,105
pub bot_apps_pending: HashSet<String>,106
pub notice: Option<Notice>,106
pub notice: Option<Notice>,107
pub connection_banner: crate::connection_banner::BannerTiming,108
pub live_retry: Option<Arc<tokio::sync::Notify>>,107
pub notice_count: u64,109
pub notice_count: u64,108
pub keep_unread: Option<String>,110
pub keep_unread: Option<String>,109
pub typing: TypingState,111
pub typing: TypingState,@@ -253,6 +255,8 @@ impl AppState {253
bot_apps: HashMap::new(),255
bot_apps: HashMap::new(),254
bot_apps_pending: HashSet::new(),256
bot_apps_pending: HashSet::new(),255
notice: None,257
notice: None,258
connection_banner: Default::default(),259
live_retry: None,256
notice_count: 0,260
notice_count: 0,257
keep_unread: None,261
keep_unread: None,258
typing: TypingState::default(),262
typing: TypingState::default(),@@ -898,8 +902,10 @@ impl AppState {898
match event {902
match event {899
BackendEvent::Connection(connection) => {903
BackendEvent::Connection(connection) => {900
self.connection = connection;904
self.connection = connection;905
self.refresh_connection_banner(cx);901
cx.emit(AppEvent::Status);906
cx.emit(AppEvent::Status);902
}907
}908
BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry),903
BackendEvent::Calls(launcher) => {909
BackendEvent::Calls(launcher) => {904
launcher.set_default_camera(self.call_camera.clone());910
launcher.set_default_camera(self.call_camera.clone());905
self.call_launcher = Some(launcher);911
self.call_launcher = Some(launcher);@@ -976,6 +982,7 @@ impl AppState {976
BackendEvent::Typing(event) => self.apply_typing(event, cx),982
BackendEvent::Typing(event) => self.apply_typing(event, cx),977
BackendEvent::Live(live) => {983
BackendEvent::Live(live) => {978
self.live = live;984
self.live = live;985
self.refresh_connection_banner(cx);979
cx.emit(AppEvent::Status);986
cx.emit(AppEvent::Status);980
}987
}981
BackendEvent::Favorites(ids) => {988
BackendEvent::Favorites(ids) => {@@ -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);
@@ -68,6 +69,7 @@ pub enum BackendEvent {
68
69
Typing(TypingEvent),
69
70
Favorites(Vec<String>),
70
71
Synced(DateTime<Utc>),
72
LiveRetry(Arc<Notify>),
71
73
}
72
74
73
75
type EventSender = mpsc::UnboundedSender<BackendEvent>;
@@ -166,6 +168,8 @@ async fn supervise(
166
168
let (nudge, nudges) = mpsc::unbounded_channel();
167
169
let resend = Arc::new(Notify::new());
168
170
let link = presence_link::start(&session, activity.clone(), resend.clone());
171
let live_retry = Arc::new(Notify::new());
172
let _ = events.send(BackendEvent::LiveRetry(live_retry.clone()));
169
173
tokio::spawn(realtime_loop(
170
174
session.clone(),
171
175
engine.clone(),
@@ -174,6 +178,7 @@ async fn supervise(
174
178
activity,
175
179
resend,
176
180
link,
181
live_retry,
177
182
));
178
183
tokio::spawn(calendar_loop(session.clone(), events.clone()));
179
184
tokio::spawn(pins_loop(session, events.clone()));
@@ -201,6 +206,7 @@ async fn refresh_loop(
201
206
mut nudges: mpsc::UnboundedReceiver<()>,
202
207
) {
203
208
let mut interval = tokio::time::interval(REFRESH_INTERVAL);
209
let mut forwards_healing = false;
204
210
loop {
205
211
tokio::select! {
206
212
_ = interval.tick() => {}
@@ -214,6 +220,10 @@ async fn refresh_loop(
214
220
}
215
221
match engine.refresh_sidebar().await {
216
222
Ok(_) => {
223
if !std::mem::replace(&mut forwards_healing, true) {
224
let engine = engine.clone();
225
tokio::spawn(async move { engine.heal_all_forwards(FORWARD_HEAL_PAUSE).await });
226
}
217
227
if let Err(error) = engine.refresh_folders().await {
218
228
crate::diagnostics::record(format!(
219
229
"sync: chat folders and channel layout not refreshed: {error}"
@@ -238,6 +248,7 @@ async fn realtime_loop(
238
248
mut activity: watch::Receiver<bool>,
239
249
resend: Arc<Notify>,
240
250
link: mpsc::UnboundedSender<LinkSignal>,
251
live_retry: Arc<Notify>,
241
252
) {
242
253
loop {
243
254
let _ = events.send(BackendEvent::Live(LiveState::Connecting));
@@ -314,7 +325,10 @@ async fn realtime_loop(
314
325
let _ = link.send(LinkSignal::Disconnected);
315
326
}
316
327
}
317
tokio::time::sleep(REALTIME_RETRY).await;
328
tokio::select! {
329
_ = tokio::time::sleep(REALTIME_RETRY) => {}
330
_ = live_retry.notified() => {}
331
}
318
332
}
319
333
}
320
334
@@ -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);@@ -68,6 +69,7 @@ pub enum BackendEvent {68
Typing(TypingEvent),69
Typing(TypingEvent),69
Favorites(Vec<String>),70
Favorites(Vec<String>),70
Synced(DateTime<Utc>),71
Synced(DateTime<Utc>),72
LiveRetry(Arc<Notify>),71
}73
}72
74
73
type EventSender = mpsc::UnboundedSender<BackendEvent>;75
type EventSender = mpsc::UnboundedSender<BackendEvent>;@@ -166,6 +168,8 @@ async fn supervise(166
let (nudge, nudges) = mpsc::unbounded_channel();168
let (nudge, nudges) = mpsc::unbounded_channel();167
let resend = Arc::new(Notify::new());169
let resend = Arc::new(Notify::new());168
let link = presence_link::start(&session, activity.clone(), resend.clone());170
let link = presence_link::start(&session, activity.clone(), resend.clone());171
let live_retry = Arc::new(Notify::new());172
let _ = events.send(BackendEvent::LiveRetry(live_retry.clone()));169
tokio::spawn(realtime_loop(173
tokio::spawn(realtime_loop(170
session.clone(),174
session.clone(),171
engine.clone(),175
engine.clone(),@@ -174,6 +178,7 @@ async fn supervise(174
activity,178
activity,175
resend,179
resend,176
link,180
link,181
live_retry,177
));182
));178
tokio::spawn(calendar_loop(session.clone(), events.clone()));183
tokio::spawn(calendar_loop(session.clone(), events.clone()));179
tokio::spawn(pins_loop(session, events.clone()));184
tokio::spawn(pins_loop(session, events.clone()));@@ -201,6 +206,7 @@ async fn refresh_loop(201
mut nudges: mpsc::UnboundedReceiver<()>,206
mut nudges: mpsc::UnboundedReceiver<()>,202
) {207
) {203
let mut interval = tokio::time::interval(REFRESH_INTERVAL);208
let mut interval = tokio::time::interval(REFRESH_INTERVAL);209
let mut forwards_healing = false;204
loop {210
loop {205
tokio::select! {211
tokio::select! {206
_ = interval.tick() => {}212
_ = interval.tick() => {}@@ -214,6 +220,10 @@ async fn refresh_loop(214
}220
}215
match engine.refresh_sidebar().await {221
match engine.refresh_sidebar().await {216
Ok(_) => {222
Ok(_) => {223
if !std::mem::replace(&mut forwards_healing, true) {224
let engine = engine.clone();225
tokio::spawn(async move { engine.heal_all_forwards(FORWARD_HEAL_PAUSE).await });226
}217
if let Err(error) = engine.refresh_folders().await {227
if let Err(error) = engine.refresh_folders().await {218
crate::diagnostics::record(format!(228
crate::diagnostics::record(format!(219
"sync: chat folders and channel layout not refreshed: {error}"229
"sync: chat folders and channel layout not refreshed: {error}"@@ -238,6 +248,7 @@ async fn realtime_loop(238
mut activity: watch::Receiver<bool>,248
mut activity: watch::Receiver<bool>,239
resend: Arc<Notify>,249
resend: Arc<Notify>,240
link: mpsc::UnboundedSender<LinkSignal>,250
link: mpsc::UnboundedSender<LinkSignal>,251
live_retry: Arc<Notify>,241
) {252
) {242
loop {253
loop {243
let _ = events.send(BackendEvent::Live(LiveState::Connecting));254
let _ = events.send(BackendEvent::Live(LiveState::Connecting));@@ -314,7 +325,10 @@ async fn realtime_loop(314
let _ = link.send(LinkSignal::Disconnected);325
let _ = link.send(LinkSignal::Disconnected);315
}326
}316
}327
}317
tokio::time::sleep(REALTIME_RETRY).await;328
tokio::select! {329
_ = tokio::time::sleep(REALTIME_RETRY) => {}330
_ = live_retry.notified() => {}331
}318
}332
}319
}333
}320
334
@@ -0,0 +1,244 @@
1
use std::time::{Duration, Instant};
2
3
use chrono::{DateTime, Local, Utc};
4
use gpui_kit::*;
5
6
use crate::app_state::AppState;
7
use crate::backend::{ConnectionState, LiveState};
8
9
pub const SHOW_AFTER: Duration = Duration::from_secs(4);
10
pub const MIN_VISIBLE: Duration = Duration::from_secs(3);
11
const OFFLINE_TEXT: &str =
12
"Something went wrong while connecting to Teams. Reconnect to keep the conversation going.";
13
const DEMO_OFFLINE_VARIABLE: &str = "TEAMS_DEMO_OFFLINE";
14
const DEMO_LAST_SYNC_AGO: chrono::Duration = chrono::Duration::minutes(12);
15
16
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17
pub enum BannerKind {
18
Connecting,
19
Reconnecting,
20
Offline,
21
SignIn,
22
LiveUnavailable,
23
}
24
25
#[derive(Debug, Clone, PartialEq, Eq)]
26
pub struct BannerText {
27
pub text: String,
28
pub detail: Option<String>,
29
pub retry: bool,
30
}
31
32
/// What is wrong right now; `None` while live or while only missed messages are being synced.
33
pub fn banner_kind(connection: &ConnectionState, live: LiveState) -> Option<BannerKind> {
34
match connection {
35
ConnectionState::Connecting => return Some(BannerKind::Connecting),
36
ConnectionState::LoginRequired => return Some(BannerKind::SignIn),
37
ConnectionState::NoBrowser | ConnectionState::NoAppTab | ConnectionState::Failed(_) => {
38
return Some(BannerKind::Offline);
39
}
40
ConnectionState::Online => {}
41
}
42
match live {
43
LiveState::Off | LiveState::Live | LiveState::MessageLoss => None,
44
LiveState::Connecting => Some(BannerKind::Connecting),
45
LiveState::Reconnecting => Some(BannerKind::Reconnecting),
46
LiveState::Failed => Some(BannerKind::LiveUnavailable),
47
}
48
}
49
50
pub fn banner_text(kind: BannerKind, last_sync: Option<DateTime<Utc>>) -> BannerText {
51
let text = |text: &str| BannerText {
52
text: text.to_owned(),
53
detail: None,
54
retry: false,
55
};
56
match kind {
57
BannerKind::Connecting => text("Connecting..."),
58
BannerKind::Reconnecting => text("Reconnecting..."),
59
BannerKind::Offline => BannerText {
60
detail: last_sync
61
.map(|time| format!("Last synced {}", time.with_timezone(&Local).format("%H:%M"))),
62
..text(OFFLINE_TEXT)
63
},
64
BannerKind::SignIn => text("Sign-in required. Sign in to Teams in the window that opened."),
65
BannerKind::LiveUnavailable => BannerText {
66
retry: true,
67
..text("Live updates unavailable")
68
},
69
}
70
}
71
72
/// Shows a bad state only once it lasted `SHOW_AFTER`, and keeps a shown banner at least `MIN_VISIBLE`.
73
#[derive(Debug, Default)]
74
pub struct BannerTiming {
75
bad_since: Option<Instant>,
76
shown: Option<(BannerKind, Instant)>,
77
}
78
79
impl BannerTiming {
80
pub fn visible(&self) -> Option<BannerKind> {
81
self.shown.map(|(kind, _)| kind)
82
}
83
84
/// Returns when to check again, if the visible banner may change without a new state.
85
pub fn update(&mut self, wanted: Option<BannerKind>, now: Instant) -> Option<Duration> {
86
match wanted {
87
Some(kind) => {
88
let bad_since = *self.bad_since.get_or_insert(now);
89
if let Some((shown_kind, _)) = self.shown.as_mut() {
90
*shown_kind = kind;
91
return None;
92
}
93
let waited = now.duration_since(bad_since);
94
if waited >= SHOW_AFTER {
95
self.shown = Some((kind, now));
96
return None;
97
}
98
Some(SHOW_AFTER - waited)
99
}
100
None => {
101
self.bad_since = None;
102
let (_, shown_at) = self.shown?;
103
let visible_for = now.duration_since(shown_at);
104
if visible_for >= MIN_VISIBLE {
105
self.shown = None;
106
return None;
107
}
108
Some(MIN_VISIBLE - visible_for)
109
}
110
}
111
}
112
}
113
114
impl AppState {
115
pub fn refresh_connection_banner(&mut self, cx: &mut Context<Self>) {
116
let wanted = if self.mode.demo {
117
let offline = std::env::var_os(DEMO_OFFLINE_VARIABLE).is_some();
118
if offline {
119
self.last_sync
120
.get_or_insert_with(|| Utc::now() - DEMO_LAST_SYNC_AGO);
121
}
122
offline.then_some(BannerKind::Offline)
123
} else {
124
banner_kind(&self.connection, self.live)
125
};
126
let before = self.connection_banner.visible();
127
let recheck = self.connection_banner.update(wanted, Instant::now());
128
if let Some(wait) = recheck {
129
cx.spawn(async move |this, cx| {
130
cx.background_executor().timer(wait).await;
131
this.update(cx, |state, cx| state.refresh_connection_banner(cx))
132
.ok();
133
})
134
.detach();
135
}
136
if self.connection_banner.visible() != before {
137
cx.emit(crate::app_state::AppEvent::Status);
138
cx.notify();
139
}
140
}
141
142
pub fn connection_banner_text(&self) -> Option<BannerText> {
143
self.connection_banner
144
.visible()
145
.map(|kind| banner_text(kind, self.last_sync))
146
}
147
148
pub fn retry_live(&mut self) {
149
if let Some(retry) = &self.live_retry {
150
retry.notify_one();
151
}
152
}
153
}
154
155
#[cfg(test)]
156
mod tests {
157
use std::time::{Duration, Instant};
158
159
use chrono::Utc;
160
161
use super::{BannerKind, BannerTiming, MIN_VISIBLE, SHOW_AFTER, banner_kind, banner_text};
162
use crate::backend::{ConnectionState, LiveState};
163
164
#[test]
165
fn a_short_bad_state_never_shows() {
166
let mut timing = BannerTiming::default();
167
let start = Instant::now();
168
assert_eq!(
169
timing.update(Some(BannerKind::Reconnecting), start),
170
Some(SHOW_AFTER)
171
);
172
assert_eq!(timing.update(None, start + Duration::from_secs(2)), None);
173
assert_eq!(timing.visible(), None);
174
}
175
176
#[test]
177
fn a_lasting_bad_state_shows_after_the_delay() {
178
let mut timing = BannerTiming::default();
179
let start = Instant::now();
180
timing.update(Some(BannerKind::Reconnecting), start);
181
let wait = timing.update(Some(BannerKind::Offline), start + Duration::from_secs(1));
182
assert_eq!(wait, Some(SHOW_AFTER - Duration::from_secs(1)));
183
assert_eq!(
184
timing.update(Some(BannerKind::Offline), start + SHOW_AFTER),
185
None
186
);
187
assert_eq!(timing.visible(), Some(BannerKind::Offline));
188
}
189
190
#[test]
191
fn a_shown_banner_stays_for_the_minimum_then_goes() {
192
let mut timing = BannerTiming::default();
193
let start = Instant::now();
194
timing.update(Some(BannerKind::Offline), start);
195
let shown_at = start + SHOW_AFTER;
196
timing.update(Some(BannerKind::Offline), shown_at);
197
let back = shown_at + Duration::from_secs(1);
198
assert_eq!(
199
timing.update(None, back),
200
Some(MIN_VISIBLE - Duration::from_secs(1))
201
);
202
assert_eq!(timing.visible(), Some(BannerKind::Offline));
203
assert_eq!(timing.update(None, shown_at + MIN_VISIBLE), None);
204
assert_eq!(timing.visible(), None);
205
}
206
207
#[test]
208
fn a_new_bad_state_while_shown_changes_the_text_at_once() {
209
let mut timing = BannerTiming::default();
210
let start = Instant::now();
211
timing.update(Some(BannerKind::Offline), start);
212
timing.update(Some(BannerKind::Offline), start + SHOW_AFTER);
213
timing.update(None, start + SHOW_AFTER);
214
timing.update(Some(BannerKind::Reconnecting), start + SHOW_AFTER);
215
assert_eq!(timing.visible(), Some(BannerKind::Reconnecting));
216
}
217
218
#[test]
219
fn live_and_missed_messages_need_no_banner() {
220
let online = ConnectionState::Online;
221
assert_eq!(banner_kind(&online, LiveState::Live), None);
222
assert_eq!(banner_kind(&online, LiveState::MessageLoss), None);
223
assert_eq!(
224
banner_kind(&online, LiveState::Failed),
225
Some(BannerKind::LiveUnavailable)
226
);
227
assert_eq!(
228
banner_kind(&ConnectionState::LoginRequired, LiveState::Live),
229
Some(BannerKind::SignIn)
230
);
231
assert_eq!(
232
banner_kind(&ConnectionState::Failed("x".into()), LiveState::Off),
233
Some(BannerKind::Offline)
234
);
235
}
236
237
#[test]
238
fn the_offline_banner_names_the_last_sync() {
239
let text = banner_text(BannerKind::Offline, Some(Utc::now()));
240
assert!(text.detail.unwrap().starts_with("Last synced "));
241
assert!(banner_text(BannerKind::Offline, None).detail.is_none());
242
assert!(banner_text(BannerKind::LiveUnavailable, None).retry);
243
}
244
}
@@ -0,0 +1,244 @@1
use std::time::{Duration, Instant};2
3
use chrono::{DateTime, Local, Utc};4
use gpui_kit::*;5
6
use crate::app_state::AppState;7
use crate::backend::{ConnectionState, LiveState};8
9
pub const SHOW_AFTER: Duration = Duration::from_secs(4);10
pub const MIN_VISIBLE: Duration = Duration::from_secs(3);11
const OFFLINE_TEXT: &str =12
"Something went wrong while connecting to Teams. Reconnect to keep the conversation going.";13
const DEMO_OFFLINE_VARIABLE: &str = "TEAMS_DEMO_OFFLINE";14
const DEMO_LAST_SYNC_AGO: chrono::Duration = chrono::Duration::minutes(12);15
16
#[derive(Debug, Clone, Copy, PartialEq, Eq)]17
pub enum BannerKind {18
Connecting,19
Reconnecting,20
Offline,21
SignIn,22
LiveUnavailable,23
}24
25
#[derive(Debug, Clone, PartialEq, Eq)]26
pub struct BannerText {27
pub text: String,28
pub detail: Option<String>,29
pub retry: bool,30
}31
32
/// What is wrong right now; `None` while live or while only missed messages are being synced.33
pub fn banner_kind(connection: &ConnectionState, live: LiveState) -> Option<BannerKind> {34
match connection {35
ConnectionState::Connecting => return Some(BannerKind::Connecting),36
ConnectionState::LoginRequired => return Some(BannerKind::SignIn),37
ConnectionState::NoBrowser | ConnectionState::NoAppTab | ConnectionState::Failed(_) => {38
return Some(BannerKind::Offline);39
}40
ConnectionState::Online => {}41
}42
match live {43
LiveState::Off | LiveState::Live | LiveState::MessageLoss => None,44
LiveState::Connecting => Some(BannerKind::Connecting),45
LiveState::Reconnecting => Some(BannerKind::Reconnecting),46
LiveState::Failed => Some(BannerKind::LiveUnavailable),47
}48
}49
50
pub fn banner_text(kind: BannerKind, last_sync: Option<DateTime<Utc>>) -> BannerText {51
let text = |text: &str| BannerText {52
text: text.to_owned(),53
detail: None,54
retry: false,55
};56
match kind {57
BannerKind::Connecting => text("Connecting..."),58
BannerKind::Reconnecting => text("Reconnecting..."),59
BannerKind::Offline => BannerText {60
detail: last_sync61
.map(|time| format!("Last synced {}", time.with_timezone(&Local).format("%H:%M"))),62
..text(OFFLINE_TEXT)63
},64
BannerKind::SignIn => text("Sign-in required. Sign in to Teams in the window that opened."),65
BannerKind::LiveUnavailable => BannerText {66
retry: true,67
..text("Live updates unavailable")68
},69
}70
}71
72
/// Shows a bad state only once it lasted `SHOW_AFTER`, and keeps a shown banner at least `MIN_VISIBLE`.73
#[derive(Debug, Default)]74
pub struct BannerTiming {75
bad_since: Option<Instant>,76
shown: Option<(BannerKind, Instant)>,77
}78
79
impl BannerTiming {80
pub fn visible(&self) -> Option<BannerKind> {81
self.shown.map(|(kind, _)| kind)82
}83
84
/// Returns when to check again, if the visible banner may change without a new state.85
pub fn update(&mut self, wanted: Option<BannerKind>, now: Instant) -> Option<Duration> {86
match wanted {87
Some(kind) => {88
let bad_since = *self.bad_since.get_or_insert(now);89
if let Some((shown_kind, _)) = self.shown.as_mut() {90
*shown_kind = kind;91
return None;92
}93
let waited = now.duration_since(bad_since);94
if waited >= SHOW_AFTER {95
self.shown = Some((kind, now));96
return None;97
}98
Some(SHOW_AFTER - waited)99
}100
None => {101
self.bad_since = None;102
let (_, shown_at) = self.shown?;103
let visible_for = now.duration_since(shown_at);104
if visible_for >= MIN_VISIBLE {105
self.shown = None;106
return None;107
}108
Some(MIN_VISIBLE - visible_for)109
}110
}111
}112
}113
114
impl AppState {115
pub fn refresh_connection_banner(&mut self, cx: &mut Context<Self>) {116
let wanted = if self.mode.demo {117
let offline = std::env::var_os(DEMO_OFFLINE_VARIABLE).is_some();118
if offline {119
self.last_sync120
.get_or_insert_with(|| Utc::now() - DEMO_LAST_SYNC_AGO);121
}122
offline.then_some(BannerKind::Offline)123
} else {124
banner_kind(&self.connection, self.live)125
};126
let before = self.connection_banner.visible();127
let recheck = self.connection_banner.update(wanted, Instant::now());128
if let Some(wait) = recheck {129
cx.spawn(async move |this, cx| {130
cx.background_executor().timer(wait).await;131
this.update(cx, |state, cx| state.refresh_connection_banner(cx))132
.ok();133
})134
.detach();135
}136
if self.connection_banner.visible() != before {137
cx.emit(crate::app_state::AppEvent::Status);138
cx.notify();139
}140
}141
142
pub fn connection_banner_text(&self) -> Option<BannerText> {143
self.connection_banner144
.visible()145
.map(|kind| banner_text(kind, self.last_sync))146
}147
148
pub fn retry_live(&mut self) {149
if let Some(retry) = &self.live_retry {150
retry.notify_one();151
}152
}153
}154
155
#[cfg(test)]156
mod tests {157
use std::time::{Duration, Instant};158
159
use chrono::Utc;160
161
use super::{BannerKind, BannerTiming, MIN_VISIBLE, SHOW_AFTER, banner_kind, banner_text};162
use crate::backend::{ConnectionState, LiveState};163
164
#[test]165
fn a_short_bad_state_never_shows() {166
let mut timing = BannerTiming::default();167
let start = Instant::now();168
assert_eq!(169
timing.update(Some(BannerKind::Reconnecting), start),170
Some(SHOW_AFTER)171
);172
assert_eq!(timing.update(None, start + Duration::from_secs(2)), None);173
assert_eq!(timing.visible(), None);174
}175
176
#[test]177
fn a_lasting_bad_state_shows_after_the_delay() {178
let mut timing = BannerTiming::default();179
let start = Instant::now();180
timing.update(Some(BannerKind::Reconnecting), start);181
let wait = timing.update(Some(BannerKind::Offline), start + Duration::from_secs(1));182
assert_eq!(wait, Some(SHOW_AFTER - Duration::from_secs(1)));183
assert_eq!(184
timing.update(Some(BannerKind::Offline), start + SHOW_AFTER),185
None186
);187
assert_eq!(timing.visible(), Some(BannerKind::Offline));188
}189
190
#[test]191
fn a_shown_banner_stays_for_the_minimum_then_goes() {192
let mut timing = BannerTiming::default();193
let start = Instant::now();194
timing.update(Some(BannerKind::Offline), start);195
let shown_at = start + SHOW_AFTER;196
timing.update(Some(BannerKind::Offline), shown_at);197
let back = shown_at + Duration::from_secs(1);198
assert_eq!(199
timing.update(None, back),200
Some(MIN_VISIBLE - Duration::from_secs(1))201
);202
assert_eq!(timing.visible(), Some(BannerKind::Offline));203
assert_eq!(timing.update(None, shown_at + MIN_VISIBLE), None);204
assert_eq!(timing.visible(), None);205
}206
207
#[test]208
fn a_new_bad_state_while_shown_changes_the_text_at_once() {209
let mut timing = BannerTiming::default();210
let start = Instant::now();211
timing.update(Some(BannerKind::Offline), start);212
timing.update(Some(BannerKind::Offline), start + SHOW_AFTER);213
timing.update(None, start + SHOW_AFTER);214
timing.update(Some(BannerKind::Reconnecting), start + SHOW_AFTER);215
assert_eq!(timing.visible(), Some(BannerKind::Reconnecting));216
}217
218
#[test]219
fn live_and_missed_messages_need_no_banner() {220
let online = ConnectionState::Online;221
assert_eq!(banner_kind(&online, LiveState::Live), None);222
assert_eq!(banner_kind(&online, LiveState::MessageLoss), None);223
assert_eq!(224
banner_kind(&online, LiveState::Failed),225
Some(BannerKind::LiveUnavailable)226
);227
assert_eq!(228
banner_kind(&ConnectionState::LoginRequired, LiveState::Live),229
Some(BannerKind::SignIn)230
);231
assert_eq!(232
banner_kind(&ConnectionState::Failed("x".into()), LiveState::Off),233
Some(BannerKind::Offline)234
);235
}236
237
#[test]238
fn the_offline_banner_names_the_last_sync() {239
let text = banner_text(BannerKind::Offline, Some(Utc::now()));240
assert!(text.detail.unwrap().starts_with("Last synced "));241
assert!(banner_text(BannerKind::Offline, None).detail.is_none());242
assert!(banner_text(BannerKind::LiveUnavailable, None).retry);243
}244
}@@ -1637,6 +1637,16 @@ fn release_messages() -> Vec<MessageRecord> {
1637
1637
"[]",
1638
1638
false,
1639
1639
),
1640
message(
1641
chat,
1642
"m5e",
1643
None,
1644
jonas,
1645
at(0, 12, 40),
1646
"<p>Context from the old planning chat.</p><attachment id=\"1789000000000\"></attachment>",
1647
r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"id":"1789000000000","content":null,"unavailable":true}]"#,
1648
false,
1649
),
1640
1650
message(
1641
1651
chat,
1642
1652
"m6",
@@ -1637,6 +1637,16 @@ fn release_messages() -> Vec<MessageRecord> {1637
"[]",1637
"[]",1638
false,1638
false,1639
),1639
),1640
message(1641
chat,1642
"m5e",1643
None,1644
jonas,1645
at(0, 12, 40),1646
"<p>Context from the old planning chat.</p><attachment id=\"1789000000000\"></attachment>",1647
r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"id":"1789000000000","content":null,"unavailable":true}]"#,1648
false,1649
),1640
message(1650
message(1641
chat,1651
chat,1642
"m6",1652
"m6",@@ -11,6 +11,7 @@ pub mod card_refresh;
11
11
pub mod card_state;
12
12
pub mod chat_actions;
13
13
pub mod chat_members;
14
pub mod connection_banner;
14
15
pub mod data;
15
16
pub mod demo;
16
17
pub mod demo_meetings;
@@ -11,6 +11,7 @@ pub mod card_refresh;11
pub mod card_state;11
pub mod card_state;12
pub mod chat_actions;12
pub mod chat_actions;13
pub mod chat_members;13
pub mod chat_members;14
pub mod connection_banner;14
pub mod data;15
pub mod data;15
pub mod demo;16
pub mod demo;16
pub mod demo_meetings;17
pub mod demo_meetings;@@ -89,9 +89,9 @@ pub fn bubble_corners(own: bool, series: Series) -> Corners {
89
89
pub enum Receipt {
90
90
#[default]
91
91
Hidden,
92
Pending,
93
92
Sent,
94
93
Read,
94
ReadLive,
95
95
}
96
96
97
97
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -89,9 +89,9 @@ pub fn bubble_corners(own: bool, series: Series) -> Corners {89
pub enum Receipt {89
pub enum Receipt {90
#[default]90
#[default]91
Hidden,91
Hidden,92
Pending,93
Sent,92
Sent,94
Read,93
Read,94
ReadLive,95
}95
}96
96
97
#[derive(Debug, Clone, Copy, PartialEq, Eq)]97
#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -193,7 +193,6 @@ mod frames {
193
193
"shell/islands/rail",
194
194
"shell/islands/sidebar",
195
195
"shell/islands/main",
196
"shell/status-bar",
197
196
];
198
197
const CALL_GUARDED: &[&str] = &[
199
198
"shell/islands/main/call-header",
@@ -193,7 +193,6 @@ mod frames {193
"shell/islands/rail",193
"shell/islands/rail",194
"shell/islands/sidebar",194
"shell/islands/sidebar",195
"shell/islands/main",195
"shell/islands/main",196
"shell/status-bar",197
];196
];198
const CALL_GUARDED: &[&str] = &[197
const CALL_GUARDED: &[&str] = &[199
"shell/islands/main/call-header",198
"shell/islands/main/call-header",@@ -0,0 +1,64 @@
1
use gpui_kit::assets::IconName;
2
use gpui_kit::component::h_flex;
3
use gpui_kit::prelude::FluentBuilder as _;
4
use gpui_kit::*;
5
6
use super::widgets::icon;
7
use crate::connection_banner::BannerText;
8
use crate::theme;
9
use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH};
10
11
const BANNER_HEIGHT: f32 = 32.;
12
const BANNER_TEXT_SIZE: f32 = 12.;
13
const BANNER_ICON_SIZE: f32 = 14.;
14
15
pub fn render_connection_banner(
16
banner: BannerText,
17
on_retry: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
18
) -> impl IntoElement {
19
h_flex()
20
.debug_selector(|| "shell/connection-banner".into())
21
.flex_none()
22
.h(px(BANNER_HEIGHT))
23
.ml(px(RAIL_WIDTH))
24
.mr(px(ISLAND_GAP))
25
.mb(px(ISLAND_GAP))
26
.px(px(12.))
27
.gap(px(8.))
28
.items_center()
29
.rounded(px(8.))
30
.border_1()
31
.border_color(theme::amber().opacity(0.45))
32
.bg(theme::amber().opacity(0.14))
33
.text_size(px(BANNER_TEXT_SIZE))
34
.text_color(theme::text())
35
.child(icon(
36
IconName::TriangleAlert,
37
BANNER_ICON_SIZE,
38
theme::amber(),
39
))
40
.child(div().min_w_0().truncate().child(banner.text))
41
.children(banner.detail.map(|detail| {
42
div()
43
.flex_none()
44
.text_color(theme::text_muted())
45
.child(detail)
46
}))
47
.when(banner.retry, |row| {
48
row.child(
49
div()
50
.id("connection-banner-retry")
51
.flex_none()
52
.ml_auto()
53
.px(px(8.))
54
.py(px(2.))
55
.rounded(px(4.))
56
.cursor_pointer()
57
.font_weight(FontWeight::SEMIBOLD)
58
.text_color(theme::accent_text())
59
.hover(|button| button.bg(theme::row_hover()))
60
.child("Retry")
61
.on_click(on_retry),
62
)
63
})
64
}
@@ -0,0 +1,64 @@1
use gpui_kit::assets::IconName;2
use gpui_kit::component::h_flex;3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::*;5
6
use super::widgets::icon;7
use crate::connection_banner::BannerText;8
use crate::theme;9
use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH};10
11
const BANNER_HEIGHT: f32 = 32.;12
const BANNER_TEXT_SIZE: f32 = 12.;13
const BANNER_ICON_SIZE: f32 = 14.;14
15
pub fn render_connection_banner(16
banner: BannerText,17
on_retry: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,18
) -> impl IntoElement {19
h_flex()20
.debug_selector(|| "shell/connection-banner".into())21
.flex_none()22
.h(px(BANNER_HEIGHT))23
.ml(px(RAIL_WIDTH))24
.mr(px(ISLAND_GAP))25
.mb(px(ISLAND_GAP))26
.px(px(12.))27
.gap(px(8.))28
.items_center()29
.rounded(px(8.))30
.border_1()31
.border_color(theme::amber().opacity(0.45))32
.bg(theme::amber().opacity(0.14))33
.text_size(px(BANNER_TEXT_SIZE))34
.text_color(theme::text())35
.child(icon(36
IconName::TriangleAlert,37
BANNER_ICON_SIZE,38
theme::amber(),39
))40
.child(div().min_w_0().truncate().child(banner.text))41
.children(banner.detail.map(|detail| {42
div()43
.flex_none()44
.text_color(theme::text_muted())45
.child(detail)46
}))47
.when(banner.retry, |row| {48
row.child(49
div()50
.id("connection-banner-retry")51
.flex_none()52
.ml_auto()53
.px(px(8.))54
.py(px(2.))55
.rounded(px(4.))56
.cursor_pointer()57
.font_weight(FontWeight::SEMIBOLD)58
.text_color(theme::accent_text())59
.hover(|button| button.bg(theme::row_hover()))60
.child("Retry")61
.on_click(on_retry),62
)63
})64
}@@ -26,6 +26,7 @@ mod feed;
26
26
mod pins;
27
27
mod proposal;
28
28
mod recap;
29
mod receipt_fade;
29
30
mod render_env;
30
31
mod scheduled;
31
32
mod shared;
@@ -219,6 +220,7 @@ pub struct ConversationView {
219
220
agent_layouts: HashMap<String, (usize, bool)>,
220
221
agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
221
222
reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
223
receipt_fade: receipt_fade::ReceiptFade,
222
224
_subscriptions: Vec<Subscription>,
223
225
}
224
226
@@ -546,6 +548,7 @@ impl ConversationView {
546
548
agent_layouts: HashMap::new(),
547
549
agent_runs: Rc::new(RefCell::new(HashMap::new())),
548
550
reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
551
receipt_fade: receipt_fade::ReceiptFade::default(),
549
552
_subscriptions: subscriptions,
550
553
};
551
554
if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
@@ -1538,7 +1541,10 @@ impl ConversationView {
1538
1541
} else {
1539
1542
rows.extend(local.into_iter().map(|row| Row::Message(Box::new(row))));
1540
1543
}
1541
let receipts = self.receipts(&records, cx);
1544
let mut receipts = self.receipts(&records, cx);
1545
if self.track_receipt_fades(&mut receipts) {
1546
self.schedule_fade_end(cx);
1547
}
1542
1548
for row in rows.iter_mut() {
1543
1549
if let Row::Message(message) = row
1544
1550
&& message.own
@@ -1830,18 +1836,12 @@ impl ConversationView {
1830
1836
1831
1837
fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1832
1838
let state = self.app.read(cx);
1833
let receipts_syncing = self
1834
.current
1835
.as_ref()
1836
.is_some_and(|current| current.sync.receipts);
1837
1839
if state.mode.demo {
1838
1840
let read_ids = crate::demo::read_message_ids(records);
1839
1841
return records
1840
1842
.iter()
1841
1843
.map(|record| {
1842
let receipt = if receipts_syncing {
1843
Receipt::Pending
1844
} else if read_ids.contains(&record.message_id) {
1844
let receipt = if read_ids.contains(&record.message_id) {
1845
1845
Receipt::Read
1846
1846
} else {
1847
1847
Receipt::Sent
@@ -1853,24 +1853,39 @@ impl ConversationView {
1853
1853
let Some(engine) = state.engine.as_ref() else {
1854
1854
return HashMap::new();
1855
1855
};
1856
let unknown = if receipts_syncing {
1857
Receipt::Pending
1858
} else {
1859
Receipt::Hidden
1860
};
1861
1856
records
1862
1857
.iter()
1863
1858
.map(|record| {
1864
1859
let receipt = match engine.receipt_state_for(record) {
1865
1860
teams_core::ReceiptState::Read { .. } => Receipt::Read,
1866
1861
teams_core::ReceiptState::Sent => Receipt::Sent,
1867
teams_core::ReceiptState::Unknown => unknown,
1862
teams_core::ReceiptState::Unknown => Receipt::Hidden,
1868
1863
};
1869
1864
(record.message_id.clone(), receipt)
1870
1865
})
1871
1866
.collect()
1872
1867
}
1873
1868
1869
fn track_receipt_fades(&mut self, receipts: &mut HashMap<String, Receipt>) -> bool {
1870
let Some(current) = self.current.as_ref() else {
1871
return false;
1872
};
1873
let settled = !current.sync.receipts;
1874
let conversation_id = current.selection.conversation_id().to_owned();
1875
self.receipt_fade
1876
.apply(&conversation_id, settled, receipts, Instant::now())
1877
}
1878
1879
fn schedule_fade_end(&mut self, cx: &mut Context<Self>) {
1880
cx.spawn(async move |this, cx| {
1881
cx.background_executor()
1882
.timer(receipt_fade::RECEIPT_FADE)
1883
.await;
1884
this.update(cx, |this, cx| this.rebuild(false, cx)).ok();
1885
})
1886
.detach();
1887
}
1888
1874
1889
fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) {
1875
1890
let state = self.app.read(cx);
1876
1891
let (Some(engine), Some(Selection::Chat(chat_id))) = (
@@ -26,6 +26,7 @@ mod feed;26
mod pins;26
mod pins;27
mod proposal;27
mod proposal;28
mod recap;28
mod recap;29
mod receipt_fade;29
mod render_env;30
mod render_env;30
mod scheduled;31
mod scheduled;31
mod shared;32
mod shared;@@ -219,6 +220,7 @@ pub struct ConversationView {219
agent_layouts: HashMap<String, (usize, bool)>,220
agent_layouts: HashMap<String, (usize, bool)>,220
agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,221
agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,221
reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,222
reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,223
receipt_fade: receipt_fade::ReceiptFade,222
_subscriptions: Vec<Subscription>,224
_subscriptions: Vec<Subscription>,223
}225
}224
226
@@ -546,6 +548,7 @@ impl ConversationView {546
agent_layouts: HashMap::new(),548
agent_layouts: HashMap::new(),547
agent_runs: Rc::new(RefCell::new(HashMap::new())),549
agent_runs: Rc::new(RefCell::new(HashMap::new())),548
reaction_proposals: Rc::new(RefCell::new(HashMap::new())),550
reaction_proposals: Rc::new(RefCell::new(HashMap::new())),551
receipt_fade: receipt_fade::ReceiptFade::default(),549
_subscriptions: subscriptions,552
_subscriptions: subscriptions,550
};553
};551
if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {554
if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {@@ -1538,7 +1541,10 @@ impl ConversationView {1538
} else {1541
} else {1539
rows.extend(local.into_iter().map(|row| Row::Message(Box::new(row))));1542
rows.extend(local.into_iter().map(|row| Row::Message(Box::new(row))));1540
}1543
}1541
let receipts = self.receipts(&records, cx);1544
let mut receipts = self.receipts(&records, cx);1545
if self.track_receipt_fades(&mut receipts) {1546
self.schedule_fade_end(cx);1547
}1542
for row in rows.iter_mut() {1548
for row in rows.iter_mut() {1543
if let Row::Message(message) = row1549
if let Row::Message(message) = row1544
&& message.own1550
&& message.own@@ -1830,18 +1836,12 @@ impl ConversationView {1830
1836
1831
fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {1837
fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {1832
let state = self.app.read(cx);1838
let state = self.app.read(cx);1833
let receipts_syncing = self1834
.current1835
.as_ref()1836
.is_some_and(|current| current.sync.receipts);1837
if state.mode.demo {1839
if state.mode.demo {1838
let read_ids = crate::demo::read_message_ids(records);1840
let read_ids = crate::demo::read_message_ids(records);1839
return records1841
return records1840
.iter()1842
.iter()1841
.map(|record| {1843
.map(|record| {1842
let receipt = if receipts_syncing {1844
let receipt = if read_ids.contains(&record.message_id) {1843
Receipt::Pending1844
} else if read_ids.contains(&record.message_id) {1845
Receipt::Read1845
Receipt::Read1846
} else {1846
} else {1847
Receipt::Sent1847
Receipt::Sent@@ -1853,24 +1853,39 @@ impl ConversationView {1853
let Some(engine) = state.engine.as_ref() else {1853
let Some(engine) = state.engine.as_ref() else {1854
return HashMap::new();1854
return HashMap::new();1855
};1855
};1856
let unknown = if receipts_syncing {1857
Receipt::Pending1858
} else {1859
Receipt::Hidden1860
};1861
records1856
records1862
.iter()1857
.iter()1863
.map(|record| {1858
.map(|record| {1864
let receipt = match engine.receipt_state_for(record) {1859
let receipt = match engine.receipt_state_for(record) {1865
teams_core::ReceiptState::Read { .. } => Receipt::Read,1860
teams_core::ReceiptState::Read { .. } => Receipt::Read,1866
teams_core::ReceiptState::Sent => Receipt::Sent,1861
teams_core::ReceiptState::Sent => Receipt::Sent,1867
teams_core::ReceiptState::Unknown => unknown,1862
teams_core::ReceiptState::Unknown => Receipt::Hidden,1868
};1863
};1869
(record.message_id.clone(), receipt)1864
(record.message_id.clone(), receipt)1870
})1865
})1871
.collect()1866
.collect()1872
}1867
}1873
1868
1869
fn track_receipt_fades(&mut self, receipts: &mut HashMap<String, Receipt>) -> bool {1870
let Some(current) = self.current.as_ref() else {1871
return false;1872
};1873
let settled = !current.sync.receipts;1874
let conversation_id = current.selection.conversation_id().to_owned();1875
self.receipt_fade1876
.apply(&conversation_id, settled, receipts, Instant::now())1877
}1878
1879
fn schedule_fade_end(&mut self, cx: &mut Context<Self>) {1880
cx.spawn(async move |this, cx| {1881
cx.background_executor()1882
.timer(receipt_fade::RECEIPT_FADE)1883
.await;1884
this.update(cx, |this, cx| this.rebuild(false, cx)).ok();1885
})1886
.detach();1887
}1888
1874
fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) {1889
fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) {1875
let state = self.app.read(cx);1890
let state = self.app.read(cx);1876
let (Some(engine), Some(Selection::Chat(chat_id))) = (1891
let (Some(engine), Some(Selection::Chat(chat_id))) = (@@ -0,0 +1,111 @@
1
use std::collections::HashMap;
2
use std::time::{Duration, Instant};
3
4
use crate::rows::Receipt;
5
6
pub(super) const RECEIPT_FADE: Duration = Duration::from_millis(600);
7
8
/// Marks a receipt that turned from sent to read while the chat was open, never one seen on first paint.
9
#[derive(Default)]
10
pub(super) struct ReceiptFade {
11
conversation_id: String,
12
previous: HashMap<String, Receipt>,
13
fading: HashMap<String, Instant>,
14
}
15
16
impl ReceiptFade {
17
/// Returns true when a new fade started, so the caller can rebuild once it is over.
18
pub(super) fn apply(
19
&mut self,
20
conversation_id: &str,
21
settled: bool,
22
receipts: &mut HashMap<String, Receipt>,
23
now: Instant,
24
) -> bool {
25
if self.conversation_id != conversation_id || !settled {
26
self.conversation_id = conversation_id.to_owned();
27
self.previous.clear();
28
self.fading.clear();
29
if !settled {
30
return false;
31
}
32
}
33
let mut started = false;
34
let baseline_known = !self.previous.is_empty();
35
for (message_id, receipt) in receipts.iter() {
36
if baseline_known
37
&& *receipt == Receipt::Read
38
&& self.previous.get(message_id) == Some(&Receipt::Sent)
39
{
40
self.fading.insert(message_id.clone(), now);
41
started = true;
42
}
43
}
44
self.fading
45
.retain(|_, since| now.duration_since(*since) < RECEIPT_FADE);
46
self.previous.clone_from(receipts);
47
for (message_id, receipt) in receipts.iter_mut() {
48
if *receipt == Receipt::Read && self.fading.contains_key(message_id) {
49
*receipt = Receipt::ReadLive;
50
}
51
}
52
started
53
}
54
}
55
56
#[cfg(test)]
57
mod tests {
58
use super::*;
59
60
fn receipts(entries: &[(&str, Receipt)]) -> HashMap<String, Receipt> {
61
entries
62
.iter()
63
.map(|(id, receipt)| ((*id).to_owned(), *receipt))
64
.collect()
65
}
66
67
#[test]
68
fn the_first_paint_never_fades() {
69
let mut fade = ReceiptFade::default();
70
let now = Instant::now();
71
let mut first = receipts(&[("a", Receipt::Read)]);
72
assert!(!fade.apply("chat", true, &mut first, now));
73
assert_eq!(first["a"], Receipt::Read);
74
}
75
76
#[test]
77
fn a_change_while_receipts_load_does_not_fade() {
78
let mut fade = ReceiptFade::default();
79
let now = Instant::now();
80
let mut cached = receipts(&[("a", Receipt::Sent)]);
81
fade.apply("chat", false, &mut cached, now);
82
let mut fetched = receipts(&[("a", Receipt::Read)]);
83
assert!(!fade.apply("chat", true, &mut fetched, now));
84
assert_eq!(fetched["a"], Receipt::Read);
85
}
86
87
#[test]
88
fn a_live_sent_to_read_change_fades_once() {
89
let mut fade = ReceiptFade::default();
90
let now = Instant::now();
91
let mut baseline = receipts(&[("a", Receipt::Sent), ("b", Receipt::Sent)]);
92
fade.apply("chat", true, &mut baseline, now);
93
let mut live = receipts(&[("a", Receipt::Read), ("b", Receipt::Sent)]);
94
assert!(fade.apply("chat", true, &mut live, now));
95
assert_eq!(live["a"], Receipt::ReadLive);
96
assert_eq!(live["b"], Receipt::Sent);
97
let mut later = receipts(&[("a", Receipt::Read), ("b", Receipt::Sent)]);
98
assert!(!fade.apply("chat", true, &mut later, now + RECEIPT_FADE));
99
assert_eq!(later["a"], Receipt::Read);
100
}
101
102
#[test]
103
fn switching_chats_drops_the_baseline() {
104
let mut fade = ReceiptFade::default();
105
let now = Instant::now();
106
let mut first_chat = receipts(&[("a", Receipt::Sent)]);
107
fade.apply("one", true, &mut first_chat, now);
108
let mut other_chat = receipts(&[("a", Receipt::Read)]);
109
assert!(!fade.apply("two", true, &mut other_chat, now));
110
}
111
}
@@ -0,0 +1,111 @@1
use std::collections::HashMap;2
use std::time::{Duration, Instant};3
4
use crate::rows::Receipt;5
6
pub(super) const RECEIPT_FADE: Duration = Duration::from_millis(600);7
8
/// Marks a receipt that turned from sent to read while the chat was open, never one seen on first paint.9
#[derive(Default)]10
pub(super) struct ReceiptFade {11
conversation_id: String,12
previous: HashMap<String, Receipt>,13
fading: HashMap<String, Instant>,14
}15
16
impl ReceiptFade {17
/// Returns true when a new fade started, so the caller can rebuild once it is over.18
pub(super) fn apply(19
&mut self,20
conversation_id: &str,21
settled: bool,22
receipts: &mut HashMap<String, Receipt>,23
now: Instant,24
) -> bool {25
if self.conversation_id != conversation_id || !settled {26
self.conversation_id = conversation_id.to_owned();27
self.previous.clear();28
self.fading.clear();29
if !settled {30
return false;31
}32
}33
let mut started = false;34
let baseline_known = !self.previous.is_empty();35
for (message_id, receipt) in receipts.iter() {36
if baseline_known37
&& *receipt == Receipt::Read38
&& self.previous.get(message_id) == Some(&Receipt::Sent)39
{40
self.fading.insert(message_id.clone(), now);41
started = true;42
}43
}44
self.fading45
.retain(|_, since| now.duration_since(*since) < RECEIPT_FADE);46
self.previous.clone_from(receipts);47
for (message_id, receipt) in receipts.iter_mut() {48
if *receipt == Receipt::Read && self.fading.contains_key(message_id) {49
*receipt = Receipt::ReadLive;50
}51
}52
started53
}54
}55
56
#[cfg(test)]57
mod tests {58
use super::*;59
60
fn receipts(entries: &[(&str, Receipt)]) -> HashMap<String, Receipt> {61
entries62
.iter()63
.map(|(id, receipt)| ((*id).to_owned(), *receipt))64
.collect()65
}66
67
#[test]68
fn the_first_paint_never_fades() {69
let mut fade = ReceiptFade::default();70
let now = Instant::now();71
let mut first = receipts(&[("a", Receipt::Read)]);72
assert!(!fade.apply("chat", true, &mut first, now));73
assert_eq!(first["a"], Receipt::Read);74
}75
76
#[test]77
fn a_change_while_receipts_load_does_not_fade() {78
let mut fade = ReceiptFade::default();79
let now = Instant::now();80
let mut cached = receipts(&[("a", Receipt::Sent)]);81
fade.apply("chat", false, &mut cached, now);82
let mut fetched = receipts(&[("a", Receipt::Read)]);83
assert!(!fade.apply("chat", true, &mut fetched, now));84
assert_eq!(fetched["a"], Receipt::Read);85
}86
87
#[test]88
fn a_live_sent_to_read_change_fades_once() {89
let mut fade = ReceiptFade::default();90
let now = Instant::now();91
let mut baseline = receipts(&[("a", Receipt::Sent), ("b", Receipt::Sent)]);92
fade.apply("chat", true, &mut baseline, now);93
let mut live = receipts(&[("a", Receipt::Read), ("b", Receipt::Sent)]);94
assert!(fade.apply("chat", true, &mut live, now));95
assert_eq!(live["a"], Receipt::ReadLive);96
assert_eq!(live["b"], Receipt::Sent);97
let mut later = receipts(&[("a", Receipt::Read), ("b", Receipt::Sent)]);98
assert!(!fade.apply("chat", true, &mut later, now + RECEIPT_FADE));99
assert_eq!(later["a"], Receipt::Read);100
}101
102
#[test]103
fn switching_chats_drops_the_baseline() {104
let mut fade = ReceiptFade::default();105
let now = Instant::now();106
let mut first_chat = receipts(&[("a", Receipt::Sent)]);107
fade.apply("one", true, &mut first_chat, now);108
let mut other_chat = receipts(&[("a", Receipt::Read)]);109
assert!(!fade.apply("two", true, &mut other_chat, now));110
}111
}@@ -50,13 +50,15 @@ const SERIES_START_GAP: f32 = 8.;
50
50
pub(super) const BODY_SIZE: f32 = 13.5;
51
51
const MAX_WIDTH_RATIO: f32 = 0.7;
52
52
const NARROW_BUBBLE_WIDTH: f32 = 300.;
53
const REACTION_FOOTER_HEIGHT: f32 = 24.;
53
const BUBBLE_PADDING_Y: f32 = 8.;
54
const META_BOTTOM_INSET: f32 = 4.;
54
55
const META_SIZE: f32 = 11.;
55
56
const META_CHECK_SIZE: f32 = 15.;
56
57
const SAVED_MARK_SIZE: f32 = 12.;
57
58
const FORWARDED_SIZE: f32 = 11.;
58
59
const FIGURE_SPACE_WIDTH: f32 = 7.4;
59
60
const PULSE_PERIOD: Duration = Duration::from_millis(1600);
61
const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);
60
62
const SKELETON_LINE_HEIGHT: f32 = 20.;
61
63
62
64
pub struct DeliveryActions {
@@ -156,7 +158,7 @@ fn bubble(
156
158
.rounded_br(px(corners.bottom_right))
157
159
.rounded_bl(px(corners.bottom_left))
158
160
.px(px(12.))
159
.py(px(8.))
161
.py(px(BUBBLE_PADDING_Y))
160
162
})
161
163
.text_size(px(BODY_SIZE))
162
164
.line_height(relative(1.45));
@@ -267,9 +269,8 @@ fn bubble(
267
269
)
268
270
.child(
269
271
h_flex()
270
.h(px(REACTION_FOOTER_HEIGHT))
271
272
.flex_none()
272
.items_center()
273
.mb(px(META_BOTTOM_INSET - BUBBLE_PADDING_Y))
273
274
.child(bubble_meta(row, own, saved)),
274
275
),
275
276
);
@@ -282,7 +283,7 @@ fn bubble(
282
283
div()
283
284
.absolute()
284
285
.right(px(8.))
285
.bottom(px(4.))
286
.bottom(px(META_BOTTOM_INSET))
286
287
.child(bubble_meta(row, own, saved)),
287
288
);
288
289
}
@@ -365,13 +366,16 @@ fn bubble_meta(row: &MessageRow, own: bool, saved: bool) -> Div {
365
366
own && row.delivery == Delivery::Delivered,
366
367
|meta| match row.receipt {
367
368
Receipt::Hidden => meta,
368
Receipt::Pending => meta.child(receipt_slot(tint).relative().top(px(1.))),
369
369
Receipt::Sent => meta.child(on_baseline(symbol("done", META_CHECK_SIZE, tint))),
370
370
Receipt::Read => meta.child(on_baseline(symbol(
371
371
"done_all",
372
372
META_CHECK_SIZE,
373
373
theme::own_read(),
374
374
))),
375
Receipt::ReadLive => meta.child(receipt_fade_in(
376
&row.key,
377
on_baseline(symbol("done_all", META_CHECK_SIZE, theme::own_read())),
378
)),
375
379
},
376
380
)
377
381
}
@@ -390,20 +394,12 @@ fn pulse<E: IntoElement + Styled + 'static>(id: &'static str, element: E) -> Ani
390
394
)
391
395
}
392
396
393
fn receipt_slot(tint: Hsla) -> Div {
394
h_flex()
395
.size(px(META_CHECK_SIZE))
396
.flex_none()
397
.items_center()
398
.justify_center()
399
.child(pulse(
400
"receipt-slot",
401
div()
402
.w(px(13.))
403
.h(px(4.))
404
.rounded(px(2.))
405
.bg(tint.opacity(0.5)),
406
))
397
fn receipt_fade_in(message_key: &str, check: Div) -> AnimationElement<Div> {
398
check.with_animation(
399
SharedString::from(format!("receipt-fade/{message_key}")),
400
Animation::new(RECEIPT_FADE_PERIOD).with_easing(ease_in_out),
401
|check, delta| check.opacity(0.25 + 0.75 * delta),
402
)
407
403
}
408
404
409
405
pub fn render_skeleton_row(skeleton: &Skeleton, index: usize) -> AnyElement {
@@ -50,13 +50,15 @@ const SERIES_START_GAP: f32 = 8.;50
pub(super) const BODY_SIZE: f32 = 13.5;50
pub(super) const BODY_SIZE: f32 = 13.5;51
const MAX_WIDTH_RATIO: f32 = 0.7;51
const MAX_WIDTH_RATIO: f32 = 0.7;52
const NARROW_BUBBLE_WIDTH: f32 = 300.;52
const NARROW_BUBBLE_WIDTH: f32 = 300.;53
const REACTION_FOOTER_HEIGHT: f32 = 24.;53
const BUBBLE_PADDING_Y: f32 = 8.;54
const META_BOTTOM_INSET: f32 = 4.;54
const META_SIZE: f32 = 11.;55
const META_SIZE: f32 = 11.;55
const META_CHECK_SIZE: f32 = 15.;56
const META_CHECK_SIZE: f32 = 15.;56
const SAVED_MARK_SIZE: f32 = 12.;57
const SAVED_MARK_SIZE: f32 = 12.;57
const FORWARDED_SIZE: f32 = 11.;58
const FORWARDED_SIZE: f32 = 11.;58
const FIGURE_SPACE_WIDTH: f32 = 7.4;59
const FIGURE_SPACE_WIDTH: f32 = 7.4;59
const PULSE_PERIOD: Duration = Duration::from_millis(1600);60
const PULSE_PERIOD: Duration = Duration::from_millis(1600);61
const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);60
const SKELETON_LINE_HEIGHT: f32 = 20.;62
const SKELETON_LINE_HEIGHT: f32 = 20.;61
63
62
pub struct DeliveryActions {64
pub struct DeliveryActions {@@ -156,7 +158,7 @@ fn bubble(156
.rounded_br(px(corners.bottom_right))158
.rounded_br(px(corners.bottom_right))157
.rounded_bl(px(corners.bottom_left))159
.rounded_bl(px(corners.bottom_left))158
.px(px(12.))160
.px(px(12.))159
.py(px(8.))161
.py(px(BUBBLE_PADDING_Y))160
})162
})161
.text_size(px(BODY_SIZE))163
.text_size(px(BODY_SIZE))162
.line_height(relative(1.45));164
.line_height(relative(1.45));@@ -267,9 +269,8 @@ fn bubble(267
)269
)268
.child(270
.child(269
h_flex()271
h_flex()270
.h(px(REACTION_FOOTER_HEIGHT))271
.flex_none()272
.flex_none()272
.items_center()273
.mb(px(META_BOTTOM_INSET - BUBBLE_PADDING_Y))273
.child(bubble_meta(row, own, saved)),274
.child(bubble_meta(row, own, saved)),274
),275
),275
);276
);@@ -282,7 +283,7 @@ fn bubble(282
div()283
div()283
.absolute()284
.absolute()284
.right(px(8.))285
.right(px(8.))285
.bottom(px(4.))286
.bottom(px(META_BOTTOM_INSET))286
.child(bubble_meta(row, own, saved)),287
.child(bubble_meta(row, own, saved)),287
);288
);288
}289
}@@ -365,13 +366,16 @@ fn bubble_meta(row: &MessageRow, own: bool, saved: bool) -> Div {365
own && row.delivery == Delivery::Delivered,366
own && row.delivery == Delivery::Delivered,366
|meta| match row.receipt {367
|meta| match row.receipt {367
Receipt::Hidden => meta,368
Receipt::Hidden => meta,368
Receipt::Pending => meta.child(receipt_slot(tint).relative().top(px(1.))),369
Receipt::Sent => meta.child(on_baseline(symbol("done", META_CHECK_SIZE, tint))),369
Receipt::Sent => meta.child(on_baseline(symbol("done", META_CHECK_SIZE, tint))),370
Receipt::Read => meta.child(on_baseline(symbol(370
Receipt::Read => meta.child(on_baseline(symbol(371
"done_all",371
"done_all",372
META_CHECK_SIZE,372
META_CHECK_SIZE,373
theme::own_read(),373
theme::own_read(),374
))),374
))),375
Receipt::ReadLive => meta.child(receipt_fade_in(376
&row.key,377
on_baseline(symbol("done_all", META_CHECK_SIZE, theme::own_read())),378
)),375
},379
},376
)380
)377
}381
}@@ -390,20 +394,12 @@ fn pulse<E: IntoElement + Styled + 'static>(id: &'static str, element: E) -> Ani390
)394
)391
}395
}392
396
393
fn receipt_slot(tint: Hsla) -> Div {397
fn receipt_fade_in(message_key: &str, check: Div) -> AnimationElement<Div> {394
h_flex()398
check.with_animation(395
.size(px(META_CHECK_SIZE))399
SharedString::from(format!("receipt-fade/{message_key}")),396
.flex_none()400
Animation::new(RECEIPT_FADE_PERIOD).with_easing(ease_in_out),397
.items_center()401
|check, delta| check.opacity(0.25 + 0.75 * delta),398
.justify_center()402
)399
.child(pulse(400
"receipt-slot",401
div()402
.w(px(13.))403
.h(px(4.))404
.rounded(px(2.))405
.bg(tint.opacity(0.5)),406
))407
}403
}408
404
409
pub fn render_skeleton_row(skeleton: &Skeleton, index: usize) -> AnyElement {405
pub fn render_skeleton_row(skeleton: &Skeleton, index: usize) -> AnyElement {@@ -34,6 +34,7 @@ pub mod card_table;
34
34
pub mod card_widgets;
35
35
pub mod chat_members;
36
36
pub mod composer;
37
pub mod connection_banner;
37
38
pub mod conversation;
38
39
pub mod dialog_overlay;
39
40
pub mod emoji_popup;
@@ -48,6 +49,7 @@ pub mod link_preview;
48
49
pub mod message_actions;
49
50
pub mod message_row;
50
51
pub mod new_chat;
52
pub mod notice_toast;
51
53
pub mod new_meeting_dialog;
52
54
pub mod pin_banner;
53
55
pub mod post_card;
@@ -68,7 +70,6 @@ pub mod shell;
68
70
pub mod shortcuts;
69
71
pub mod shortcuts_dialog;
70
72
pub mod sidebar;
71
pub mod status_bar;
72
73
pub mod status_menu;
73
74
pub mod status_message_dialog;
74
75
pub mod switcher;
@@ -34,6 +34,7 @@ pub mod card_table;34
pub mod card_widgets;34
pub mod card_widgets;35
pub mod chat_members;35
pub mod chat_members;36
pub mod composer;36
pub mod composer;37
pub mod connection_banner;37
pub mod conversation;38
pub mod conversation;38
pub mod dialog_overlay;39
pub mod dialog_overlay;39
pub mod emoji_popup;40
pub mod emoji_popup;@@ -48,6 +49,7 @@ pub mod link_preview;48
pub mod message_actions;49
pub mod message_actions;49
pub mod message_row;50
pub mod message_row;50
pub mod new_chat;51
pub mod new_chat;52
pub mod notice_toast;51
pub mod new_meeting_dialog;53
pub mod new_meeting_dialog;52
pub mod pin_banner;54
pub mod pin_banner;53
pub mod post_card;55
pub mod post_card;@@ -68,7 +70,6 @@ pub mod shell;68
pub mod shortcuts;70
pub mod shortcuts;69
pub mod shortcuts_dialog;71
pub mod shortcuts_dialog;70
pub mod sidebar;72
pub mod sidebar;71
pub mod status_bar;72
pub mod status_menu;73
pub mod status_menu;73
pub mod status_message_dialog;74
pub mod status_message_dialog;74
pub mod switcher;75
pub mod switcher;@@ -0,0 +1,91 @@
1
use gpui_kit::component::WindowExt as _;
2
use gpui_kit::component::button::{Button, ButtonVariants as _};
3
use gpui_kit::component::notification::Notification;
4
use gpui_kit::*;
5
6
use crate::app_state::AppState;
7
use crate::notice::Notice;
8
9
struct NoticeToast;
10
struct UpdateFailedToast;
11
12
/// Mirrors `AppState::notice` as a toast bottom right; the state keeps the 6 s lifetime.
13
#[derive(Default)]
14
pub struct NoticeToasts {
15
shown: Option<u64>,
16
update_failure: Option<String>,
17
}
18
19
fn toast_placement() -> Anchor {
20
Anchor::BottomRight
21
}
22
23
impl NoticeToasts {
24
pub fn sync(
25
&mut self,
26
app: &Entity<AppState>,
27
notice: Option<&Notice>,
28
window: &mut Window,
29
cx: &mut App,
30
) {
31
let current = notice.map(|notice| notice.id);
32
if current == self.shown {
33
return;
34
}
35
if let Some(previous) = self.shown.take() {
36
window.defer(cx, move |window, cx| {
37
window.remove_notification1::<NoticeToast>(previous, cx)
38
});
39
}
40
let Some(notice) = notice else {
41
return;
42
};
43
self.shown = Some(notice.id);
44
let mut toast = Notification::new()
45
.id1::<NoticeToast>(notice.id)
46
.placement(toast_placement())
47
.message(notice.text.clone())
48
.autohide(false);
49
if let Some(action) = notice.action.as_ref() {
50
let label = SharedString::from(action.label.clone());
51
let app = app.clone();
52
toast = toast.action(move |_, _, _| {
53
let app = app.clone();
54
Button::new("notice-toast-action")
55
.primary()
56
.label(label.clone())
57
.on_click(move |_, _, cx| {
58
app.update(cx, |state, cx| state.run_notice_action(cx))
59
})
60
});
61
}
62
let dismiss = app.clone();
63
let notice_id = notice.id;
64
toast = toast.on_close(move |_, cx| {
65
dismiss.update(cx, |state, cx| {
66
if state
67
.notice
68
.as_ref()
69
.is_some_and(|notice| notice.id == notice_id)
70
{
71
state.dismiss_notice(cx);
72
}
73
})
74
});
75
window.defer(cx, move |window, cx| window.push_notification(toast, cx));
76
}
77
78
pub fn update_failed(&mut self, message: Option<&str>, window: &mut Window, cx: &mut App) {
79
if message == self.update_failure.as_deref() {
80
return;
81
}
82
self.update_failure = message.map(str::to_owned);
83
let Some(message) = message else {
84
return;
85
};
86
let toast = Notification::error(format!("Update failed: {message}"))
87
.id::<UpdateFailedToast>()
88
.placement(toast_placement());
89
window.defer(cx, move |window, cx| window.push_notification(toast, cx));
90
}
91
}
@@ -0,0 +1,91 @@1
use gpui_kit::component::WindowExt as _;2
use gpui_kit::component::button::{Button, ButtonVariants as _};3
use gpui_kit::component::notification::Notification;4
use gpui_kit::*;5
6
use crate::app_state::AppState;7
use crate::notice::Notice;8
9
struct NoticeToast;10
struct UpdateFailedToast;11
12
/// Mirrors `AppState::notice` as a toast bottom right; the state keeps the 6 s lifetime.13
#[derive(Default)]14
pub struct NoticeToasts {15
shown: Option<u64>,16
update_failure: Option<String>,17
}18
19
fn toast_placement() -> Anchor {20
Anchor::BottomRight21
}22
23
impl NoticeToasts {24
pub fn sync(25
&mut self,26
app: &Entity<AppState>,27
notice: Option<&Notice>,28
window: &mut Window,29
cx: &mut App,30
) {31
let current = notice.map(|notice| notice.id);32
if current == self.shown {33
return;34
}35
if let Some(previous) = self.shown.take() {36
window.defer(cx, move |window, cx| {37
window.remove_notification1::<NoticeToast>(previous, cx)38
});39
}40
let Some(notice) = notice else {41
return;42
};43
self.shown = Some(notice.id);44
let mut toast = Notification::new()45
.id1::<NoticeToast>(notice.id)46
.placement(toast_placement())47
.message(notice.text.clone())48
.autohide(false);49
if let Some(action) = notice.action.as_ref() {50
let label = SharedString::from(action.label.clone());51
let app = app.clone();52
toast = toast.action(move |_, _, _| {53
let app = app.clone();54
Button::new("notice-toast-action")55
.primary()56
.label(label.clone())57
.on_click(move |_, _, cx| {58
app.update(cx, |state, cx| state.run_notice_action(cx))59
})60
});61
}62
let dismiss = app.clone();63
let notice_id = notice.id;64
toast = toast.on_close(move |_, cx| {65
dismiss.update(cx, |state, cx| {66
if state67
.notice68
.as_ref()69
.is_some_and(|notice| notice.id == notice_id)70
{71
state.dismiss_notice(cx);72
}73
})74
});75
window.defer(cx, move |window, cx| window.push_notification(toast, cx));76
}77
78
pub fn update_failed(&mut self, message: Option<&str>, window: &mut Window, cx: &mut App) {79
if message == self.update_failure.as_deref() {80
return;81
}82
self.update_failure = message.map(str::to_owned);83
let Some(message) = message else {84
return;85
};86
let toast = Notification::error(format!("Update failed: {message}"))87
.id::<UpdateFailedToast>()88
.placement(toast_placement());89
window.defer(cx, move |window, cx| window.push_notification(toast, cx));90
}91
}@@ -29,11 +29,12 @@ use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
29
29
use super::sidebar::SidebarView;
30
30
use app_ui_kit::render::hooks::RenderHooks;
31
31
use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
32
use super::status_bar::render_status_bar;
32
use super::connection_banner::render_connection_banner;
33
use super::notice_toast::NoticeToasts;
33
34
use super::status_menu::own_status_button;
34
35
use super::status_message_dialog::{StatusMessageDialog, StatusMessageDialogEvent};
35
36
use super::switcher::{Switcher, SwitcherEvent, candidates_from};
36
use super::title_bar::render_title_bar;
37
use super::title_bar::{mode_label, render_title_bar, update_button};
37
38
use crate::activity::ActivityCenter;
38
39
use crate::agents::{AgentRunsEvent, StartDialog, StartDialogEvent, StartRequest};
39
40
use crate::app_state::{AppEvent, AppState, Selection, selection_for};
@@ -105,6 +106,8 @@ fn jump_to_quoted(message_id: String, cx: &mut App) {
105
106
});
106
107
}
107
108
109
const DEMO_UPDATE_VARIABLE: &str = "TEAMS_DEMO_UPDATE";
110
108
111
pub struct AppShell {
109
112
state: Entity<AppState>,
110
113
rail: Entity<RailView>,
@@ -127,6 +130,7 @@ pub struct AppShell {
127
130
window_was_fullscreen: bool,
128
131
open_target: Option<OpenTarget>,
129
132
update: UpdateStatus,
133
toasts: NoticeToasts,
130
134
user_input: Arc<UserInput>,
131
135
_subscription: Subscription,
132
136
call_mini: Entity<CallMiniView>,
@@ -310,6 +314,7 @@ impl AppShell {
310
314
window_was_fullscreen: false,
311
315
open_target,
312
316
update: UpdateStatus::UpToDate,
317
toasts: NoticeToasts::default(),
313
318
user_input,
314
319
_subscription: subscription,
315
320
call_mini,
@@ -321,6 +326,12 @@ impl AppShell {
321
326
_activation_observation: activation_observation,
322
327
};
323
328
shell.apply_open_target(cx);
329
shell
330
.state
331
.update(cx, |state, cx| state.refresh_connection_banner(cx));
332
if shell.state.read(cx).mode.demo && std::env::var_os(DEMO_UPDATE_VARIABLE).is_some() {
333
shell.update = UpdateStatus::Ready;
334
}
324
335
let Startup {
325
336
switcher_query,
326
337
composer_text,
@@ -829,6 +840,13 @@ impl Render for AppShell {
829
840
let chat_thread = self.state.read(cx).call_chat_thread();
830
841
self.sync_call_chat(chat_thread, window, cx);
831
842
self.sync_prejoin(window, cx);
843
let notice = self.state.read(cx).notice.clone();
844
self.toasts.sync(&self.state, notice.as_ref(), window, cx);
845
let update_failure = match &self.update {
846
UpdateStatus::Failed(message) => Some(message.clone()),
847
_ => None,
848
};
849
self.toasts.update_failed(update_failure.as_deref(), window, cx);
832
850
let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone().into());
833
851
let state = self.state.read(cx);
834
852
let call_fullscreen = state.call_fullscreen();
@@ -858,16 +876,20 @@ impl Render for AppShell {
858
876
.is_some_and(|call| !call.viewing)
859
877
.then(|| self.call_mini.clone());
860
878
let stage_overlay = render_stage_overlay(&self.state, state);
861
let status = render_status_bar(
862
state,
863
&self.update,
864
cx.listener(|this, _, _, cx| this.restart_into_update(cx)),
865
cx.listener(|this, _, _, cx| {
866
this.state
867
.update(cx, |state, cx| state.run_notice_action(cx))
868
}),
869
);
879
let banner = state.connection_banner_text().map(|banner| {
880
render_connection_banner(
881
banner,
882
cx.listener(|this, _, _, cx| {
883
this.state.update(cx, |state, _| state.retry_live())
884
}),
885
)
886
});
870
887
let title_bar = render_title_bar(
888
mode_label(state.mode),
889
update_button(
890
&self.update,
891
cx.listener(|this, _, _, cx| this.restart_into_update(cx)),
892
),
871
893
own_status_button(&self.state, state),
872
894
cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),
873
895
);
@@ -1015,8 +1037,8 @@ impl Render for AppShell {
1015
1037
.debug_selector(|| "shell".into())
1016
1038
.size_full()
1017
1039
.child(title_bar)
1018
.child(self.islands(call_view, show_sidebar))
1019
.child(status),
1040
.children(banner)
1041
.child(self.islands(call_view, show_sidebar)),
1020
1042
)
1021
1043
.children(call_mini)
1022
1044
.children(call_overlay)
@@ -29,11 +29,12 @@ use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};29
use super::sidebar::SidebarView;29
use super::sidebar::SidebarView;30
use app_ui_kit::render::hooks::RenderHooks;30
use app_ui_kit::render::hooks::RenderHooks;31
use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};31
use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};32
use super::status_bar::render_status_bar;32
use super::connection_banner::render_connection_banner;33
use super::notice_toast::NoticeToasts;33
use super::status_menu::own_status_button;34
use super::status_menu::own_status_button;34
use super::status_message_dialog::{StatusMessageDialog, StatusMessageDialogEvent};35
use super::status_message_dialog::{StatusMessageDialog, StatusMessageDialogEvent};35
use super::switcher::{Switcher, SwitcherEvent, candidates_from};36
use super::switcher::{Switcher, SwitcherEvent, candidates_from};36
use super::title_bar::render_title_bar;37
use super::title_bar::{mode_label, render_title_bar, update_button};37
use crate::activity::ActivityCenter;38
use crate::activity::ActivityCenter;38
use crate::agents::{AgentRunsEvent, StartDialog, StartDialogEvent, StartRequest};39
use crate::agents::{AgentRunsEvent, StartDialog, StartDialogEvent, StartRequest};39
use crate::app_state::{AppEvent, AppState, Selection, selection_for};40
use crate::app_state::{AppEvent, AppState, Selection, selection_for};@@ -105,6 +106,8 @@ fn jump_to_quoted(message_id: String, cx: &mut App) {105
});106
});106
}107
}107
108
109
const DEMO_UPDATE_VARIABLE: &str = "TEAMS_DEMO_UPDATE";110
108
pub struct AppShell {111
pub struct AppShell {109
state: Entity<AppState>,112
state: Entity<AppState>,110
rail: Entity<RailView>,113
rail: Entity<RailView>,@@ -127,6 +130,7 @@ pub struct AppShell {127
window_was_fullscreen: bool,130
window_was_fullscreen: bool,128
open_target: Option<OpenTarget>,131
open_target: Option<OpenTarget>,129
update: UpdateStatus,132
update: UpdateStatus,133
toasts: NoticeToasts,130
user_input: Arc<UserInput>,134
user_input: Arc<UserInput>,131
_subscription: Subscription,135
_subscription: Subscription,132
call_mini: Entity<CallMiniView>,136
call_mini: Entity<CallMiniView>,@@ -310,6 +314,7 @@ impl AppShell {310
window_was_fullscreen: false,314
window_was_fullscreen: false,311
open_target,315
open_target,312
update: UpdateStatus::UpToDate,316
update: UpdateStatus::UpToDate,317
toasts: NoticeToasts::default(),313
user_input,318
user_input,314
_subscription: subscription,319
_subscription: subscription,315
call_mini,320
call_mini,@@ -321,6 +326,12 @@ impl AppShell {321
_activation_observation: activation_observation,326
_activation_observation: activation_observation,322
};327
};323
shell.apply_open_target(cx);328
shell.apply_open_target(cx);329
shell330
.state331
.update(cx, |state, cx| state.refresh_connection_banner(cx));332
if shell.state.read(cx).mode.demo && std::env::var_os(DEMO_UPDATE_VARIABLE).is_some() {333
shell.update = UpdateStatus::Ready;334
}324
let Startup {335
let Startup {325
switcher_query,336
switcher_query,326
composer_text,337
composer_text,@@ -829,6 +840,13 @@ impl Render for AppShell {829
let chat_thread = self.state.read(cx).call_chat_thread();840
let chat_thread = self.state.read(cx).call_chat_thread();830
self.sync_call_chat(chat_thread, window, cx);841
self.sync_call_chat(chat_thread, window, cx);831
self.sync_prejoin(window, cx);842
self.sync_prejoin(window, cx);843
let notice = self.state.read(cx).notice.clone();844
self.toasts.sync(&self.state, notice.as_ref(), window, cx);845
let update_failure = match &self.update {846
UpdateStatus::Failed(message) => Some(message.clone()),847
_ => None,848
};849
self.toasts.update_failed(update_failure.as_deref(), window, cx);832
let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone().into());850
let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone().into());833
let state = self.state.read(cx);851
let state = self.state.read(cx);834
let call_fullscreen = state.call_fullscreen();852
let call_fullscreen = state.call_fullscreen();@@ -858,16 +876,20 @@ impl Render for AppShell {858
.is_some_and(|call| !call.viewing)876
.is_some_and(|call| !call.viewing)859
.then(|| self.call_mini.clone());877
.then(|| self.call_mini.clone());860
let stage_overlay = render_stage_overlay(&self.state, state);878
let stage_overlay = render_stage_overlay(&self.state, state);861
let status = render_status_bar(879
let banner = state.connection_banner_text().map(|banner| {862
state,880
render_connection_banner(863
&self.update,881
banner,864
cx.listener(|this, _, _, cx| this.restart_into_update(cx)),882
cx.listener(|this, _, _, cx| {865
cx.listener(|this, _, _, cx| {883
this.state.update(cx, |state, _| state.retry_live())866
this.state884
}),867
.update(cx, |state, cx| state.run_notice_action(cx))885
)868
}),886
});869
);870
let title_bar = render_title_bar(887
let title_bar = render_title_bar(888
mode_label(state.mode),889
update_button(890
&self.update,891
cx.listener(|this, _, _, cx| this.restart_into_update(cx)),892
),871
own_status_button(&self.state, state),893
own_status_button(&self.state, state),872
cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),894
cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),873
);895
);@@ -1015,8 +1037,8 @@ impl Render for AppShell {1015
.debug_selector(|| "shell".into())1037
.debug_selector(|| "shell".into())1016
.size_full()1038
.size_full()1017
.child(title_bar)1039
.child(title_bar)1018
.child(self.islands(call_view, show_sidebar))1040
.children(banner)1019
.child(status),1041
.child(self.islands(call_view, show_sidebar)),1020
)1042
)1021
.children(call_mini)1043
.children(call_mini)1022
.children(call_overlay)1044
.children(call_overlay)@@ -1,214 +0,0 @@
1
use chrono::{DateTime, Local, Utc};
2
use gpui_kit::component::{h_flex, tooltip::Tooltip};
3
use gpui_kit::*;
4
5
use crate::app_state::{AppState, Mode};
6
use crate::backend::{ConnectionState, LiveState};
7
use crate::format;
8
use crate::theme;
9
use crate::updater::{self, UpdateStatus};
10
11
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12
pub enum Tone {
13
Good,
14
Warn,
15
Bad,
16
}
17
18
pub fn connection_text(connection: &ConnectionState, mode: Mode) -> (String, Tone) {
19
if mode.demo {
20
return ("Demo data".to_owned(), Tone::Warn);
21
}
22
match connection {
23
ConnectionState::Connecting => ("Connecting".to_owned(), Tone::Warn),
24
ConnectionState::Online => ("Connected".to_owned(), Tone::Good),
25
ConnectionState::NoBrowser => ("Browser not running".to_owned(), Tone::Bad),
26
ConnectionState::NoAppTab => ("Teams not loaded".to_owned(), Tone::Bad),
27
ConnectionState::LoginRequired => ("Sign-in required".to_owned(), Tone::Bad),
28
ConnectionState::Failed(message) => (format!("Error: {message}"), Tone::Bad),
29
}
30
}
31
32
pub fn live_text(live: LiveState) -> Option<(&'static str, Tone)> {
33
match live {
34
LiveState::Off => None,
35
LiveState::Connecting => Some(("Live: connecting", Tone::Warn)),
36
LiveState::Live => Some(("Live", Tone::Good)),
37
LiveState::Reconnecting => Some(("Live: reconnecting", Tone::Warn)),
38
LiveState::MessageLoss => Some(("Live: missed messages, syncing", Tone::Warn)),
39
LiveState::Failed => Some(("Live: unavailable", Tone::Bad)),
40
}
41
}
42
43
pub fn sync_text(last_sync: Option<DateTime<Utc>>) -> String {
44
match last_sync {
45
Some(time) => format!("Synced {}", time.with_timezone(&Local).format("%H:%M")),
46
None => "Not synced yet".to_owned(),
47
}
48
}
49
50
fn tone_color(tone: Tone) -> Hsla {
51
match tone {
52
Tone::Good => theme::green(),
53
Tone::Warn => theme::amber(),
54
Tone::Bad => theme::red(),
55
}
56
}
57
58
pub fn render_status_bar(
59
state: &AppState,
60
update: &UpdateStatus,
61
on_restart: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
62
on_notice_action: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
63
) -> impl IntoElement {
64
let (connection, connection_tone) = connection_text(&state.connection, state.mode);
65
let item = |label: String, tone: Tone| {
66
h_flex()
67
.gap(px(6.))
68
.items_center()
69
.child(div().size(px(7.)).rounded_full().bg(tone_color(tone)))
70
.child(label)
71
};
72
let live = live_text(state.live);
73
let mut bar = h_flex()
74
.debug_selector(|| "shell/status-bar".into())
75
.w_full()
76
.h(px(24.))
77
.flex_none()
78
.px(px(12.))
79
.gap(px(14.))
80
.items_center()
81
.text_size(px(11.))
82
.bg(theme::background())
83
.text_color(theme::text_muted());
84
match live {
85
Some((label, tone)) if connection_tone == Tone::Good => {
86
bar = bar.child(item(label.to_owned(), tone))
87
}
88
_ => bar = bar.child(item(connection, connection_tone)),
89
}
90
bar = bar.child(div().child(sync_text(state.last_sync)));
91
if state.mode.read_only {
92
bar = bar.child(div().text_color(theme::amber()).child("Read-only"));
93
}
94
match update {
95
UpdateStatus::UpToDate => {}
96
UpdateStatus::Ready => {
97
bar = bar.child(
98
div()
99
.id("update-restart")
100
.px(px(8.))
101
.rounded(px(4.))
102
.bg(theme::accent())
103
.text_color(theme::on_accent())
104
.cursor_pointer()
105
.hover(|button| button.bg(theme::accent_text()))
106
.child("Update ready - Restart")
107
.on_click(on_restart),
108
)
109
}
110
UpdateStatus::Installing => {
111
bar = bar.child(
112
div()
113
.text_color(theme::accent_text())
114
.child("Restarting..."),
115
)
116
}
117
UpdateStatus::Failed(message) => {
118
bar = bar.child(
119
div()
120
.text_color(theme::red())
121
.child(format!("Update failed: {message}")),
122
)
123
}
124
}
125
if let Some(notice) = &state.notice {
126
bar = bar.child(
127
h_flex()
128
.min_w_0()
129
.gap(px(8.))
130
.items_center()
131
.text_color(theme::amber())
132
.child(div().min_w_0().truncate().child(notice.text.clone()))
133
.children(notice.action.as_ref().map(|action| {
134
div()
135
.id("notice-action")
136
.flex_none()
137
.px(px(6.))
138
.rounded(px(4.))
139
.cursor_pointer()
140
.font_weight(FontWeight::SEMIBOLD)
141
.text_color(theme::accent_text())
142
.hover(|button| button.bg(theme::row_hover()))
143
.child(action.label.clone())
144
.on_click(on_notice_action)
145
})),
146
);
147
}
148
let full_version = updater::running_version();
149
bar.child(
150
div()
151
.id("build-version")
152
.ml_auto()
153
.tooltip(move |window, cx| Tooltip::new(full_version).build(window, cx))
154
.child(format::short_version(
155
full_version,
156
env!("CARGO_PKG_VERSION"),
157
)),
158
)
159
}
160
161
#[cfg(test)]
162
mod tests {
163
use super::{Tone, connection_text, live_text, sync_text};
164
use crate::app_state::Mode;
165
use crate::backend::{ConnectionState, LiveState};
166
use chrono::Utc;
167
168
#[test]
169
fn states_map_to_text_and_tone() {
170
let mode = Mode::default();
171
assert_eq!(
172
connection_text(&ConnectionState::Online, mode).1,
173
Tone::Good
174
);
175
assert_eq!(
176
connection_text(&ConnectionState::LoginRequired, mode).0,
177
"Sign-in required"
178
);
179
assert_eq!(
180
connection_text(&ConnectionState::Connecting, mode).1,
181
Tone::Warn
182
);
183
assert!(
184
connection_text(&ConnectionState::Failed("x".into()), mode)
185
.0
186
.contains('x')
187
);
188
}
189
190
#[test]
191
fn demo_mode_overrides_the_connection() {
192
let mode = Mode {
193
demo: true,
194
read_only: false,
195
demo_sync: None,
196
};
197
assert_eq!(
198
connection_text(&ConnectionState::NoBrowser, mode).0,
199
"Demo data"
200
);
201
}
202
203
#[test]
204
fn live_off_has_no_label() {
205
assert_eq!(live_text(LiveState::Off), None);
206
assert_eq!(live_text(LiveState::Live).unwrap().1, Tone::Good);
207
}
208
209
#[test]
210
fn sync_text_without_sync() {
211
assert_eq!(sync_text(None), "Not synced yet");
212
assert!(sync_text(Some(Utc::now())).starts_with("Synced "));
213
}
214
}
@@ -1,214 +0,0 @@1
use chrono::{DateTime, Local, Utc};2
use gpui_kit::component::{h_flex, tooltip::Tooltip};3
use gpui_kit::*;4
5
use crate::app_state::{AppState, Mode};6
use crate::backend::{ConnectionState, LiveState};7
use crate::format;8
use crate::theme;9
use crate::updater::{self, UpdateStatus};10
11
#[derive(Debug, Clone, Copy, PartialEq, Eq)]12
pub enum Tone {13
Good,14
Warn,15
Bad,16
}17
18
pub fn connection_text(connection: &ConnectionState, mode: Mode) -> (String, Tone) {19
if mode.demo {20
return ("Demo data".to_owned(), Tone::Warn);21
}22
match connection {23
ConnectionState::Connecting => ("Connecting".to_owned(), Tone::Warn),24
ConnectionState::Online => ("Connected".to_owned(), Tone::Good),25
ConnectionState::NoBrowser => ("Browser not running".to_owned(), Tone::Bad),26
ConnectionState::NoAppTab => ("Teams not loaded".to_owned(), Tone::Bad),27
ConnectionState::LoginRequired => ("Sign-in required".to_owned(), Tone::Bad),28
ConnectionState::Failed(message) => (format!("Error: {message}"), Tone::Bad),29
}30
}31
32
pub fn live_text(live: LiveState) -> Option<(&'static str, Tone)> {33
match live {34
LiveState::Off => None,35
LiveState::Connecting => Some(("Live: connecting", Tone::Warn)),36
LiveState::Live => Some(("Live", Tone::Good)),37
LiveState::Reconnecting => Some(("Live: reconnecting", Tone::Warn)),38
LiveState::MessageLoss => Some(("Live: missed messages, syncing", Tone::Warn)),39
LiveState::Failed => Some(("Live: unavailable", Tone::Bad)),40
}41
}42
43
pub fn sync_text(last_sync: Option<DateTime<Utc>>) -> String {44
match last_sync {45
Some(time) => format!("Synced {}", time.with_timezone(&Local).format("%H:%M")),46
None => "Not synced yet".to_owned(),47
}48
}49
50
fn tone_color(tone: Tone) -> Hsla {51
match tone {52
Tone::Good => theme::green(),53
Tone::Warn => theme::amber(),54
Tone::Bad => theme::red(),55
}56
}57
58
pub fn render_status_bar(59
state: &AppState,60
update: &UpdateStatus,61
on_restart: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,62
on_notice_action: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,63
) -> impl IntoElement {64
let (connection, connection_tone) = connection_text(&state.connection, state.mode);65
let item = |label: String, tone: Tone| {66
h_flex()67
.gap(px(6.))68
.items_center()69
.child(div().size(px(7.)).rounded_full().bg(tone_color(tone)))70
.child(label)71
};72
let live = live_text(state.live);73
let mut bar = h_flex()74
.debug_selector(|| "shell/status-bar".into())75
.w_full()76
.h(px(24.))77
.flex_none()78
.px(px(12.))79
.gap(px(14.))80
.items_center()81
.text_size(px(11.))82
.bg(theme::background())83
.text_color(theme::text_muted());84
match live {85
Some((label, tone)) if connection_tone == Tone::Good => {86
bar = bar.child(item(label.to_owned(), tone))87
}88
_ => bar = bar.child(item(connection, connection_tone)),89
}90
bar = bar.child(div().child(sync_text(state.last_sync)));91
if state.mode.read_only {92
bar = bar.child(div().text_color(theme::amber()).child("Read-only"));93
}94
match update {95
UpdateStatus::UpToDate => {}96
UpdateStatus::Ready => {97
bar = bar.child(98
div()99
.id("update-restart")100
.px(px(8.))101
.rounded(px(4.))102
.bg(theme::accent())103
.text_color(theme::on_accent())104
.cursor_pointer()105
.hover(|button| button.bg(theme::accent_text()))106
.child("Update ready - Restart")107
.on_click(on_restart),108
)109
}110
UpdateStatus::Installing => {111
bar = bar.child(112
div()113
.text_color(theme::accent_text())114
.child("Restarting..."),115
)116
}117
UpdateStatus::Failed(message) => {118
bar = bar.child(119
div()120
.text_color(theme::red())121
.child(format!("Update failed: {message}")),122
)123
}124
}125
if let Some(notice) = &state.notice {126
bar = bar.child(127
h_flex()128
.min_w_0()129
.gap(px(8.))130
.items_center()131
.text_color(theme::amber())132
.child(div().min_w_0().truncate().child(notice.text.clone()))133
.children(notice.action.as_ref().map(|action| {134
div()135
.id("notice-action")136
.flex_none()137
.px(px(6.))138
.rounded(px(4.))139
.cursor_pointer()140
.font_weight(FontWeight::SEMIBOLD)141
.text_color(theme::accent_text())142
.hover(|button| button.bg(theme::row_hover()))143
.child(action.label.clone())144
.on_click(on_notice_action)145
})),146
);147
}148
let full_version = updater::running_version();149
bar.child(150
div()151
.id("build-version")152
.ml_auto()153
.tooltip(move |window, cx| Tooltip::new(full_version).build(window, cx))154
.child(format::short_version(155
full_version,156
env!("CARGO_PKG_VERSION"),157
)),158
)159
}160
161
#[cfg(test)]162
mod tests {163
use super::{Tone, connection_text, live_text, sync_text};164
use crate::app_state::Mode;165
use crate::backend::{ConnectionState, LiveState};166
use chrono::Utc;167
168
#[test]169
fn states_map_to_text_and_tone() {170
let mode = Mode::default();171
assert_eq!(172
connection_text(&ConnectionState::Online, mode).1,173
Tone::Good174
);175
assert_eq!(176
connection_text(&ConnectionState::LoginRequired, mode).0,177
"Sign-in required"178
);179
assert_eq!(180
connection_text(&ConnectionState::Connecting, mode).1,181
Tone::Warn182
);183
assert!(184
connection_text(&ConnectionState::Failed("x".into()), mode)185
.0186
.contains('x')187
);188
}189
190
#[test]191
fn demo_mode_overrides_the_connection() {192
let mode = Mode {193
demo: true,194
read_only: false,195
demo_sync: None,196
};197
assert_eq!(198
connection_text(&ConnectionState::NoBrowser, mode).0,199
"Demo data"200
);201
}202
203
#[test]204
fn live_off_has_no_label() {205
assert_eq!(live_text(LiveState::Off), None);206
assert_eq!(live_text(LiveState::Live).unwrap().1, Tone::Good);207
}208
209
#[test]210
fn sync_text_without_sync() {211
assert_eq!(sync_text(None), "Not synced yet");212
assert!(sync_text(Some(Utc::now())).starts_with("Synced "));213
}214
}@@ -2,10 +2,13 @@ use std::sync::{Arc, OnceLock};
2
2
3
3
use gpui_kit::assets::IconName;
4
4
use gpui_kit::component::{TitleBar, h_flex};
5
use gpui_kit::prelude::FluentBuilder as _;
5
6
use gpui_kit::*;
6
7
7
8
use super::widgets::icon;
9
use crate::app_state::Mode;
8
10
use crate::theme;
11
use crate::updater::UpdateStatus;
9
12
10
13
pub const TITLE_BAR_HEIGHT: f32 = 40.;
11
14
const SEARCH_WIDTH: f32 = 380.;
@@ -20,7 +23,76 @@ fn app_icon() -> Arc<Image> {
20
23
.clone()
21
24
}
22
25
26
fn mode_pill(label: &'static str) -> Div {
27
div()
28
.debug_selector(|| "shell/title-bar/mode-pill".into())
29
.flex_none()
30
.px(px(8.))
31
.h(px(18.))
32
.flex()
33
.items_center()
34
.rounded_full()
35
.border_1()
36
.border_color(theme::amber().opacity(0.5))
37
.bg(theme::amber().opacity(0.14))
38
.text_size(px(11.))
39
.font_weight(FontWeight::SEMIBOLD)
40
.text_color(theme::amber())
41
.child(label)
42
}
43
44
pub fn mode_label(mode: Mode) -> Option<&'static str> {
45
if mode.demo {
46
Some("Demo")
47
} else if mode.read_only {
48
Some("Read-only")
49
} else {
50
None
51
}
52
}
53
54
pub fn update_button(
55
update: &UpdateStatus,
56
on_restart: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
57
) -> Option<AnyElement> {
58
let installing = match update {
59
UpdateStatus::Ready => false,
60
UpdateStatus::Installing => true,
61
UpdateStatus::UpToDate | UpdateStatus::Failed(_) => return None,
62
};
63
Some(
64
div()
65
.id("title-update-restart")
66
.debug_selector(|| "shell/title-bar/update".into())
67
.flex_none()
68
.h(px(24.))
69
.px(px(10.))
70
.flex()
71
.items_center()
72
.rounded(px(6.))
73
.bg(theme::accent())
74
.text_color(theme::on_accent())
75
.text_size(px(12.))
76
.font_weight(FontWeight::SEMIBOLD)
77
.when(!installing, |button| {
78
button
79
.cursor_pointer()
80
.hover(|button| button.bg(theme::accent_text()))
81
.on_click(on_restart)
82
})
83
.when(installing, |button| button.opacity(0.7))
84
.child(if installing {
85
"Restarting..."
86
} else {
87
"Restart to update"
88
})
89
.into_any_element(),
90
)
91
}
92
23
93
pub fn render_title_bar(
94
mode_label: Option<&'static str>,
95
update: Option<AnyElement>,
24
96
own: Option<AnyElement>,
25
97
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
26
98
) -> impl IntoElement {
@@ -68,7 +140,9 @@ pub fn render_title_bar(
68
140
.text_color(theme::text())
69
141
.child(app_base::APP_NAME),
70
142
)
143
.children(mode_label.map(mode_pill))
71
144
.child(div().flex_1().flex().justify_center().child(search))
145
.children(update)
72
146
.children(own)
73
147
.child(div().w(px(4.))),
74
148
);
@@ -2,10 +2,13 @@ use std::sync::{Arc, OnceLock};2
2
3
use gpui_kit::assets::IconName;3
use gpui_kit::assets::IconName;4
use gpui_kit::component::{TitleBar, h_flex};4
use gpui_kit::component::{TitleBar, h_flex};5
use gpui_kit::prelude::FluentBuilder as _;5
use gpui_kit::*;6
use gpui_kit::*;6
7
7
use super::widgets::icon;8
use super::widgets::icon;9
use crate::app_state::Mode;8
use crate::theme;10
use crate::theme;11
use crate::updater::UpdateStatus;9
12
10
pub const TITLE_BAR_HEIGHT: f32 = 40.;13
pub const TITLE_BAR_HEIGHT: f32 = 40.;11
const SEARCH_WIDTH: f32 = 380.;14
const SEARCH_WIDTH: f32 = 380.;@@ -20,7 +23,76 @@ fn app_icon() -> Arc<Image> {20
.clone()23
.clone()21
}24
}22
25
26
fn mode_pill(label: &'static str) -> Div {27
div()28
.debug_selector(|| "shell/title-bar/mode-pill".into())29
.flex_none()30
.px(px(8.))31
.h(px(18.))32
.flex()33
.items_center()34
.rounded_full()35
.border_1()36
.border_color(theme::amber().opacity(0.5))37
.bg(theme::amber().opacity(0.14))38
.text_size(px(11.))39
.font_weight(FontWeight::SEMIBOLD)40
.text_color(theme::amber())41
.child(label)42
}43
44
pub fn mode_label(mode: Mode) -> Option<&'static str> {45
if mode.demo {46
Some("Demo")47
} else if mode.read_only {48
Some("Read-only")49
} else {50
None51
}52
}53
54
pub fn update_button(55
update: &UpdateStatus,56
on_restart: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,57
) -> Option<AnyElement> {58
let installing = match update {59
UpdateStatus::Ready => false,60
UpdateStatus::Installing => true,61
UpdateStatus::UpToDate | UpdateStatus::Failed(_) => return None,62
};63
Some(64
div()65
.id("title-update-restart")66
.debug_selector(|| "shell/title-bar/update".into())67
.flex_none()68
.h(px(24.))69
.px(px(10.))70
.flex()71
.items_center()72
.rounded(px(6.))73
.bg(theme::accent())74
.text_color(theme::on_accent())75
.text_size(px(12.))76
.font_weight(FontWeight::SEMIBOLD)77
.when(!installing, |button| {78
button79
.cursor_pointer()80
.hover(|button| button.bg(theme::accent_text()))81
.on_click(on_restart)82
})83
.when(installing, |button| button.opacity(0.7))84
.child(if installing {85
"Restarting..."86
} else {87
"Restart to update"88
})89
.into_any_element(),90
)91
}92
23
pub fn render_title_bar(93
pub fn render_title_bar(94
mode_label: Option<&'static str>,95
update: Option<AnyElement>,24
own: Option<AnyElement>,96
own: Option<AnyElement>,25
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,97
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,26
) -> impl IntoElement {98
) -> impl IntoElement {@@ -68,7 +140,9 @@ pub fn render_title_bar(68
.text_color(theme::text())140
.text_color(theme::text())69
.child(app_base::APP_NAME),141
.child(app_base::APP_NAME),70
)142
)143
.children(mode_label.map(mode_pill))71
.child(div().flex_1().flex().justify_center().child(search))144
.child(div().flex_1().flex().justify_center().child(search))145
.children(update)72
.children(own)146
.children(own)73
.child(div().w(px(4.))),147
.child(div().w(px(4.))),74
);148
);@@ -0,0 +1,109 @@
1
use chatsvc::substrate_search::{
2
MessageFilter, QueryRequest, QueryResults, QueryScope, SearchIdentity, SearchSession,
3
SubstrateSearch, Suggestions,
4
};
5
use session::{DEFAULT_ENDPOINT, Method, Scope, Session};
6
7
fn print_suggestions(label: &str, suggestions: &Suggestions) {
8
println!(
9
"# {label}: people {} chats {} channels {} teams {} messages {} files {} events {} texts {} best {}",
10
suggestions.people.len(),
11
suggestions.chats.len(),
12
suggestions.channels.len(),
13
suggestions.teams.len(),
14
suggestions.messages.len(),
15
suggestions.files.len(),
16
suggestions.events.len(),
17
suggestions.texts.len(),
18
suggestions.best_matches.len()
19
);
20
}
21
22
fn print_results(label: &str, results: &QueryResults) {
23
println!(
24
"# {label}: messages {}/{} people {}/{} chats {}/{} channels {}/{} files {}/{}",
25
results.messages.items.len(),
26
results.messages.total,
27
results.people.items.len(),
28
results.people.total,
29
results.chats.items.len(),
30
results.chats.total,
31
results.channels.items.len(),
32
results.channels.total,
33
results.files.items.len(),
34
results.files.total
35
);
36
}
37
38
#[tokio::main]
39
async fn main() {
40
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
41
let text = std::env::args()
42
.nth(1)
43
.unwrap_or_else(|| "release".to_owned());
44
let session = Session::connect(&endpoint).await.expect("browser");
45
let graph_scope = Scope::graph("User.Read");
46
let me = session
47
.request(
48
Method::Get,
49
"https://graph.microsoft.com/v1.0/me?$select=id",
50
&graph_scope,
51
None,
52
)
53
.await
54
.expect("me");
55
let organization = session
56
.request(
57
Method::Get,
58
"https://graph.microsoft.com/v1.0/organization?$select=id",
59
&graph_scope,
60
None,
61
)
62
.await
63
.expect("organization");
64
let identity = SearchIdentity {
65
user_id: me.body["id"].as_str().expect("user id").to_owned(),
66
tenant_id: organization.body["value"][0]["id"]
67
.as_str()
68
.expect("tenant id")
69
.to_owned(),
70
};
71
let search = SubstrateSearch::new(&session, identity);
72
let search_session = SearchSession::new();
73
match search.init(&search_session).await {
74
Ok(()) => println!("# init: ok"),
75
Err(error) => println!("# init: {error}"),
76
}
77
match search.suggestions(&search_session, "").await {
78
Ok(suggestions) => print_suggestions("zero query", &suggestions),
79
Err(error) => println!("# zero query: {error}"),
80
}
81
let typeahead = search.suggestions(&search_session, &text).await;
82
match &typeahead {
83
Ok(suggestions) => print_suggestions("typeahead", suggestions),
84
Err(error) => println!("# typeahead: {error}"),
85
}
86
for scope in [QueryScope::All, QueryScope::Messages, QueryScope::People] {
87
match search
88
.query(&search_session, &QueryRequest::new(&text, scope))
89
.await
90
{
91
Ok(results) => print_results(&format!("query {scope:?}"), &results),
92
Err(error) => println!("# query {scope:?}: {error}"),
93
}
94
}
95
let chat_thread = typeahead.ok().and_then(|suggestions| {
96
suggestions
97
.messages
98
.first()
99
.map(|hit| hit.conversation_id.clone())
100
});
101
if let Some(thread_id) = chat_thread {
102
let request = QueryRequest::new(&text, QueryScope::Messages)
103
.with_filters(vec![MessageFilter::InChat { thread_id }]);
104
match search.query(&search_session, &request).await {
105
Ok(results) => print_results("find in chat", &results),
106
Err(error) => println!("# find in chat: {error}"),
107
}
108
}
109
}
@@ -0,0 +1,109 @@1
use chatsvc::substrate_search::{2
MessageFilter, QueryRequest, QueryResults, QueryScope, SearchIdentity, SearchSession,3
SubstrateSearch, Suggestions,4
};5
use session::{DEFAULT_ENDPOINT, Method, Scope, Session};6
7
fn print_suggestions(label: &str, suggestions: &Suggestions) {8
println!(9
"# {label}: people {} chats {} channels {} teams {} messages {} files {} events {} texts {} best {}",10
suggestions.people.len(),11
suggestions.chats.len(),12
suggestions.channels.len(),13
suggestions.teams.len(),14
suggestions.messages.len(),15
suggestions.files.len(),16
suggestions.events.len(),17
suggestions.texts.len(),18
suggestions.best_matches.len()19
);20
}21
22
fn print_results(label: &str, results: &QueryResults) {23
println!(24
"# {label}: messages {}/{} people {}/{} chats {}/{} channels {}/{} files {}/{}",25
results.messages.items.len(),26
results.messages.total,27
results.people.items.len(),28
results.people.total,29
results.chats.items.len(),30
results.chats.total,31
results.channels.items.len(),32
results.channels.total,33
results.files.items.len(),34
results.files.total35
);36
}37
38
#[tokio::main]39
async fn main() {40
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());41
let text = std::env::args()42
.nth(1)43
.unwrap_or_else(|| "release".to_owned());44
let session = Session::connect(&endpoint).await.expect("browser");45
let graph_scope = Scope::graph("User.Read");46
let me = session47
.request(48
Method::Get,49
"https://graph.microsoft.com/v1.0/me?$select=id",50
&graph_scope,51
None,52
)53
.await54
.expect("me");55
let organization = session56
.request(57
Method::Get,58
"https://graph.microsoft.com/v1.0/organization?$select=id",59
&graph_scope,60
None,61
)62
.await63
.expect("organization");64
let identity = SearchIdentity {65
user_id: me.body["id"].as_str().expect("user id").to_owned(),66
tenant_id: organization.body["value"][0]["id"]67
.as_str()68
.expect("tenant id")69
.to_owned(),70
};71
let search = SubstrateSearch::new(&session, identity);72
let search_session = SearchSession::new();73
match search.init(&search_session).await {74
Ok(()) => println!("# init: ok"),75
Err(error) => println!("# init: {error}"),76
}77
match search.suggestions(&search_session, "").await {78
Ok(suggestions) => print_suggestions("zero query", &suggestions),79
Err(error) => println!("# zero query: {error}"),80
}81
let typeahead = search.suggestions(&search_session, &text).await;82
match &typeahead {83
Ok(suggestions) => print_suggestions("typeahead", suggestions),84
Err(error) => println!("# typeahead: {error}"),85
}86
for scope in [QueryScope::All, QueryScope::Messages, QueryScope::People] {87
match search88
.query(&search_session, &QueryRequest::new(&text, scope))89
.await90
{91
Ok(results) => print_results(&format!("query {scope:?}"), &results),92
Err(error) => println!("# query {scope:?}: {error}"),93
}94
}95
let chat_thread = typeahead.ok().and_then(|suggestions| {96
suggestions97
.messages98
.first()99
.map(|hit| hit.conversation_id.clone())100
});101
if let Some(thread_id) = chat_thread {102
let request = QueryRequest::new(&text, QueryScope::Messages)103
.with_filters(vec![MessageFilter::InChat { thread_id }]);104
match search.query(&search_session, &request).await {105
Ok(results) => print_results("find in chat", &results),106
Err(error) => println!("# find in chat: {error}"),107
}108
}109
}@@ -26,6 +26,7 @@ pub mod saved;
26
26
pub mod settings;
27
27
pub mod sound_settings;
28
28
pub mod sounds;
29
pub mod substrate_search;
29
30
pub mod transcripts;
30
31
pub mod translate;
31
32
pub mod window;
@@ -79,6 +80,10 @@ pub use receipts::{MemberHorizon, Receipts};
79
80
pub use recording_policy::{RecordingPolicy, parse_recording_policy};
80
81
pub use saved::SavedMessage;
81
82
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
83
pub use substrate_search::{
84
QueryRequest, QueryResults, QueryScope, SearchIdentity, SearchSession, SubstrateSearch,
85
Suggestions,
86
};
82
87
pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};
83
88
pub use translate::{
84
89
Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
@@ -26,6 +26,7 @@ pub mod saved;26
pub mod settings;26
pub mod settings;27
pub mod sound_settings;27
pub mod sound_settings;28
pub mod sounds;28
pub mod sounds;29
pub mod substrate_search;29
pub mod transcripts;30
pub mod transcripts;30
pub mod translate;31
pub mod translate;31
pub mod window;32
pub mod window;@@ -79,6 +80,10 @@ pub use receipts::{MemberHorizon, Receipts};79
pub use recording_policy::{RecordingPolicy, parse_recording_policy};80
pub use recording_policy::{RecordingPolicy, parse_recording_policy};80
pub use saved::SavedMessage;81
pub use saved::SavedMessage;81
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};82
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};83
pub use substrate_search::{84
QueryRequest, QueryResults, QueryScope, SearchIdentity, SearchSession, SubstrateSearch,85
Suggestions,86
};82
pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};87
pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};83
pub use translate::{88
pub use translate::{84
Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,89
Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,@@ -0,0 +1,63 @@
1
use std::ops::Range;
2
3
const HIT_START: &str = "<c0>";
4
const HIT_END: &str = "</c0>";
5
const ELLIPSIS: &str = "<ddd/>";
6
7
#[derive(Debug, Clone, Default, PartialEq, Eq)]
8
pub struct HighlightedText {
9
pub text: String,
10
pub hits: Vec<Range<usize>>,
11
}
12
13
pub fn split_highlights(summary: &str) -> HighlightedText {
14
let mut highlighted = HighlightedText::default();
15
let mut rest = summary;
16
let mut hit_start: Option<usize> = None;
17
while !rest.is_empty() {
18
if let Some(after) = rest.strip_prefix(HIT_START) {
19
hit_start.get_or_insert(highlighted.text.len());
20
rest = after;
21
} else if let Some(after) = rest.strip_prefix(HIT_END) {
22
if let Some(start) = hit_start
23
.take()
24
.filter(|start| *start < highlighted.text.len())
25
{
26
highlighted.hits.push(start..highlighted.text.len());
27
}
28
rest = after;
29
} else if let Some(after) = rest.strip_prefix(ELLIPSIS) {
30
highlighted.text.push_str("...");
31
rest = after;
32
} else {
33
let next = rest.chars().next().unwrap_or_default();
34
highlighted.text.push(next);
35
rest = &rest[next.len_utf8()..];
36
}
37
}
38
highlighted
39
}
40
41
#[cfg(test)]
42
mod tests {
43
use super::*;
44
45
#[test]
46
fn hit_markers_become_byte_ranges_over_the_plain_text() {
47
let highlighted = split_highlights("Grüße an <c0>Christian</c0> und <c0>Anna</c0>");
48
assert_eq!(highlighted.text, "Grüße an Christian und Anna");
49
let words: Vec<&str> = highlighted
50
.hits
51
.iter()
52
.map(|hit| &highlighted.text[hit.clone()])
53
.collect();
54
assert_eq!(words, ["Christian", "Anna"]);
55
}
56
57
#[test]
58
fn ellipsis_marker_and_unclosed_hit_are_tolerated() {
59
let highlighted = split_highlights("<ddd/>end of <c0>text");
60
assert_eq!(highlighted.text, "...end of text");
61
assert!(highlighted.hits.is_empty());
62
}
63
}
@@ -0,0 +1,63 @@1
use std::ops::Range;2
3
const HIT_START: &str = "<c0>";4
const HIT_END: &str = "</c0>";5
const ELLIPSIS: &str = "<ddd/>";6
7
#[derive(Debug, Clone, Default, PartialEq, Eq)]8
pub struct HighlightedText {9
pub text: String,10
pub hits: Vec<Range<usize>>,11
}12
13
pub fn split_highlights(summary: &str) -> HighlightedText {14
let mut highlighted = HighlightedText::default();15
let mut rest = summary;16
let mut hit_start: Option<usize> = None;17
while !rest.is_empty() {18
if let Some(after) = rest.strip_prefix(HIT_START) {19
hit_start.get_or_insert(highlighted.text.len());20
rest = after;21
} else if let Some(after) = rest.strip_prefix(HIT_END) {22
if let Some(start) = hit_start23
.take()24
.filter(|start| *start < highlighted.text.len())25
{26
highlighted.hits.push(start..highlighted.text.len());27
}28
rest = after;29
} else if let Some(after) = rest.strip_prefix(ELLIPSIS) {30
highlighted.text.push_str("...");31
rest = after;32
} else {33
let next = rest.chars().next().unwrap_or_default();34
highlighted.text.push(next);35
rest = &rest[next.len_utf8()..];36
}37
}38
highlighted39
}40
41
#[cfg(test)]42
mod tests {43
use super::*;44
45
#[test]46
fn hit_markers_become_byte_ranges_over_the_plain_text() {47
let highlighted = split_highlights("Grüße an <c0>Christian</c0> und <c0>Anna</c0>");48
assert_eq!(highlighted.text, "Grüße an Christian und Anna");49
let words: Vec<&str> = highlighted50
.hits51
.iter()52
.map(|hit| &highlighted.text[hit.clone()])53
.collect();54
assert_eq!(words, ["Christian", "Anna"]);55
}56
57
#[test]58
fn ellipsis_marker_and_unclosed_hit_are_tolerated() {59
let highlighted = split_highlights("<ddd/>end of <c0>text");60
assert_eq!(highlighted.text, "...end of text");61
assert!(highlighted.hits.is_empty());62
}63
}@@ -0,0 +1,91 @@
1
const NOT_SOFT_DELETED: &str = "NOT (isClientSoftDeleted:TRUE)";
2
const SENDER_MRI_FIELD: &str =
3
"Extension_SkypeSpaces_ConversationPost_Extension_FromSkypeInternalId_String";
4
const THREAD_TYPE_FIELD: &str =
5
"Extension_SkypeSpaces_ConversationPost_Extension_ThreadType_String";
6
7
#[derive(Debug, Clone, PartialEq, Eq)]
8
pub enum MessageFilter {
9
InChat { thread_id: String },
10
MentionsMe,
11
HasAttachment,
12
FromSender { mri: String },
13
}
14
15
impl MessageFilter {
16
fn kql(&self, user_id: &str) -> String {
17
match self {
18
MessageFilter::InChat { thread_id } => {
19
format!("clientthreadid:{thread_id} AND NOT ({THREAD_TYPE_FIELD}:(topic OR space))")
20
}
21
MessageFilter::MentionsMe => format!("mentions:{}", user_id.replace('-', "")),
22
MessageFilter::HasAttachment => "hasattachment:yes".to_owned(),
23
MessageFilter::FromSender { mri } => format!("({SENDER_MRI_FIELD}:{mri})"),
24
}
25
}
26
}
27
28
pub fn message_query_string(text: &str, filters: &[MessageFilter], user_id: &str) -> String {
29
let mut clauses = vec![NOT_SOFT_DELETED.to_owned()];
30
clauses.extend(filters.iter().map(|filter| filter.kql(user_id)));
31
let text = text.trim();
32
if !text.is_empty() {
33
clauses.push(text.to_owned());
34
}
35
clauses.join(" AND ")
36
}
37
38
#[cfg(test)]
39
mod tests {
40
use super::*;
41
42
#[test]
43
fn plain_text_excludes_soft_deleted_messages_like_teams() {
44
assert_eq!(
45
message_query_string("christian", &[], "user"),
46
"NOT (isClientSoftDeleted:TRUE) AND christian"
47
);
48
}
49
50
#[test]
51
fn mentions_me_uses_the_object_id_without_dashes() {
52
let query = message_query_string(
53
"release",
54
&[MessageFilter::MentionsMe, MessageFilter::HasAttachment],
55
"0a1b2c3d-0000-1111-2222-333344445555",
56
);
57
assert_eq!(
58
query,
59
"NOT (isClientSoftDeleted:TRUE) AND mentions:0a1b2c3d000011112222333344445555 AND hasattachment:yes AND release"
60
);
61
}
62
63
#[test]
64
fn in_chat_scopes_to_the_thread_and_skips_channel_posts() {
65
let query = message_query_string(
66
"",
67
&[MessageFilter::InChat {
68
thread_id: "19:abc@thread.v2".to_owned(),
69
}],
70
"user",
71
);
72
assert_eq!(
73
query,
74
"NOT (isClientSoftDeleted:TRUE) AND clientthreadid:19:abc@thread.v2 AND NOT (Extension_SkypeSpaces_ConversationPost_Extension_ThreadType_String:(topic OR space))"
75
);
76
}
77
78
#[test]
79
fn sender_filter_matches_the_exact_mri() {
80
let query = message_query_string(
81
"x",
82
&[MessageFilter::FromSender {
83
mri: "8:orgid:abc".to_owned(),
84
}],
85
"user",
86
);
87
assert!(query.contains(
88
"(Extension_SkypeSpaces_ConversationPost_Extension_FromSkypeInternalId_String:8:orgid:abc)"
89
));
90
}
91
}
@@ -0,0 +1,91 @@1
const NOT_SOFT_DELETED: &str = "NOT (isClientSoftDeleted:TRUE)";2
const SENDER_MRI_FIELD: &str =3
"Extension_SkypeSpaces_ConversationPost_Extension_FromSkypeInternalId_String";4
const THREAD_TYPE_FIELD: &str =5
"Extension_SkypeSpaces_ConversationPost_Extension_ThreadType_String";6
7
#[derive(Debug, Clone, PartialEq, Eq)]8
pub enum MessageFilter {9
InChat { thread_id: String },10
MentionsMe,11
HasAttachment,12
FromSender { mri: String },13
}14
15
impl MessageFilter {16
fn kql(&self, user_id: &str) -> String {17
match self {18
MessageFilter::InChat { thread_id } => {19
format!("clientthreadid:{thread_id} AND NOT ({THREAD_TYPE_FIELD}:(topic OR space))")20
}21
MessageFilter::MentionsMe => format!("mentions:{}", user_id.replace('-', "")),22
MessageFilter::HasAttachment => "hasattachment:yes".to_owned(),23
MessageFilter::FromSender { mri } => format!("({SENDER_MRI_FIELD}:{mri})"),24
}25
}26
}27
28
pub fn message_query_string(text: &str, filters: &[MessageFilter], user_id: &str) -> String {29
let mut clauses = vec![NOT_SOFT_DELETED.to_owned()];30
clauses.extend(filters.iter().map(|filter| filter.kql(user_id)));31
let text = text.trim();32
if !text.is_empty() {33
clauses.push(text.to_owned());34
}35
clauses.join(" AND ")36
}37
38
#[cfg(test)]39
mod tests {40
use super::*;41
42
#[test]43
fn plain_text_excludes_soft_deleted_messages_like_teams() {44
assert_eq!(45
message_query_string("christian", &[], "user"),46
"NOT (isClientSoftDeleted:TRUE) AND christian"47
);48
}49
50
#[test]51
fn mentions_me_uses_the_object_id_without_dashes() {52
let query = message_query_string(53
"release",54
&[MessageFilter::MentionsMe, MessageFilter::HasAttachment],55
"0a1b2c3d-0000-1111-2222-333344445555",56
);57
assert_eq!(58
query,59
"NOT (isClientSoftDeleted:TRUE) AND mentions:0a1b2c3d000011112222333344445555 AND hasattachment:yes AND release"60
);61
}62
63
#[test]64
fn in_chat_scopes_to_the_thread_and_skips_channel_posts() {65
let query = message_query_string(66
"",67
&[MessageFilter::InChat {68
thread_id: "19:abc@thread.v2".to_owned(),69
}],70
"user",71
);72
assert_eq!(73
query,74
"NOT (isClientSoftDeleted:TRUE) AND clientthreadid:19:abc@thread.v2 AND NOT (Extension_SkypeSpaces_ConversationPost_Extension_ThreadType_String:(topic OR space))"75
);76
}77
78
#[test]79
fn sender_filter_matches_the_exact_mri() {80
let query = message_query_string(81
"x",82
&[MessageFilter::FromSender {83
mri: "8:orgid:abc".to_owned(),84
}],85
"user",86
);87
assert!(query.contains(88
"(Extension_SkypeSpaces_ConversationPost_Extension_FromSkypeInternalId_String:8:orgid:abc)"89
));90
}91
}@@ -0,0 +1,208 @@
1
mod highlight;
2
mod kql;
3
mod model;
4
mod request;
5
6
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
7
use session::{ApiResponse, Method, Request, Scope, Session};
8
9
use crate::error::{Error, Result};
10
use crate::pins::{CsaTransport, SessionTransport};
11
12
pub use highlight::{HighlightedText, split_highlights};
13
pub use kql::{MessageFilter, message_query_string};
14
pub use model::{
15
BestMatch, ChatMember, QueryResults, ResultPage, SearchChannel, SearchChat, SearchEvent,
16
SearchFile, SearchMessage, SearchPerson, SearchTeam, SearchText, Suggestions,
17
parse_query_results, parse_suggestions,
18
};
19
pub use request::{QueryRequest, QueryScope};
20
21
pub const SUBSTRATE: &str = "https://substrate.office.com";
22
pub const SUBSTRATE_SEARCH_SCOPE: &str = "SubstrateSearch-Internal.ReadWrite";
23
const SCENARIO: &str = "powerbar";
24
const SUGGESTION_CLIENT_VERSION: &str = "T2.1";
25
const QUERY_CLIENT_VERSION: &str = "1";
26
const SUGGESTION_FLIGHTS: &str = "IncludeHistoryInBMDynamic,PeopleKeywordAsTextSuggestion,TDPeopleSynthetic,EnableKql,EnableSelfSuggestion";
27
const SUGGESTION_SET_FLIGHTS: &str = "EnableMessageImageSearch,EnableTeamsChannelDomainPowerbar";
28
29
/// Without the anchor mailbox headers Substrate answers 200 with empty result sets.
30
#[derive(Debug, Clone, PartialEq, Eq)]
31
pub struct SearchIdentity {
32
pub user_id: String,
33
pub tenant_id: String,
34
}
35
36
/// One search session per opened search box: Teams sends the same cvid for every keystroke.
37
#[derive(Debug, Clone, PartialEq, Eq)]
38
pub struct SearchSession {
39
correlation_id: String,
40
}
41
42
impl SearchSession {
43
pub fn new() -> Self {
44
SearchSession {
45
correlation_id: new_id(),
46
}
47
}
48
49
pub fn correlation_id(&self) -> &str {
50
&self.correlation_id
51
}
52
}
53
54
impl Default for SearchSession {
55
fn default() -> Self {
56
SearchSession::new()
57
}
58
}
59
60
pub struct SubstrateSearch<T: CsaTransport = SessionTransport> {
61
transport: T,
62
identity: SearchIdentity,
63
base_url: String,
64
}
65
66
impl SubstrateSearch<SessionTransport> {
67
pub fn new(session: &Session, identity: SearchIdentity) -> Self {
68
let transport =
69
SessionTransport::with_scope(session, Scope::new(SUBSTRATE, SUBSTRATE_SEARCH_SCOPE));
70
SubstrateSearch::with_transport(transport, identity, SUBSTRATE)
71
}
72
}
73
74
impl<T: CsaTransport> SubstrateSearch<T> {
75
pub fn with_transport(transport: T, identity: SearchIdentity, base_url: &str) -> Self {
76
SubstrateSearch {
77
transport,
78
identity,
79
base_url: base_url.trim_end_matches('/').to_owned(),
80
}
81
}
82
83
pub async fn init(&self, search_session: &SearchSession) -> Result<()> {
84
let url = format!(
85
"{}/search/api/v2/init?cvid={}&scenario={SCENARIO}",
86
self.base_url,
87
search_session.correlation_id()
88
);
89
let answer = self
90
.send(Request::get(url), search_session, SUGGESTION_CLIENT_VERSION)
91
.await?;
92
ensure_success(&answer)
93
}
94
95
/// An empty text returns the zero-query state: top people, recent searches, chats.
96
pub async fn suggestions(
97
&self,
98
search_session: &SearchSession,
99
text: &str,
100
) -> Result<Suggestions> {
101
let logical_id = new_id();
102
let correlation_id = search_session.correlation_id();
103
let mut request = if text.trim().is_empty() {
104
Request::get(format!(
105
"{}/search/api/v1/suggestions?scenario={SCENARIO}&query=&cvid={correlation_id}&logicalId={logical_id}",
106
self.base_url
107
))
108
} else {
109
Request::with_body(
110
Method::Post,
111
format!(
112
"{}/search/api/v1/suggestions?scenario={SCENARIO}&setflight={}",
113
self.base_url,
114
utf8_percent_encode(SUGGESTION_SET_FLIGHTS, NON_ALPHANUMERIC)
115
),
116
request::suggestion_body(text, correlation_id, &logical_id),
117
)
118
};
119
request
120
.headers
121
.push(("x-client-flights".to_owned(), SUGGESTION_FLIGHTS.to_owned()));
122
let answer = self
123
.send(request, search_session, SUGGESTION_CLIENT_VERSION)
124
.await?;
125
ensure_success(&answer)?;
126
Ok(parse_suggestions(&answer.body))
127
}
128
129
pub async fn query(
130
&self,
131
search_session: &SearchSession,
132
query: &QueryRequest,
133
) -> Result<QueryResults> {
134
let body = request::query_body(
135
query,
136
&self.identity.user_id,
137
search_session.correlation_id(),
138
&new_id(),
139
);
140
let request = Request::with_body(
141
Method::Post,
142
format!("{}/searchservice/api/v2/query", self.base_url),
143
body,
144
);
145
let answer = self
146
.send(request, search_session, QUERY_CLIENT_VERSION)
147
.await?;
148
ensure_success(&answer)?;
149
Ok(parse_query_results(&answer.body))
150
}
151
152
async fn send(
153
&self,
154
mut request: Request,
155
search_session: &SearchSession,
156
client_version: &str,
157
) -> Result<ApiResponse> {
158
request
159
.headers
160
.extend(self.headers(search_session, client_version));
161
self.transport.send(request).await
162
}
163
164
fn headers(
165
&self,
166
search_session: &SearchSession,
167
client_version: &str,
168
) -> Vec<(String, String)> {
169
let SearchIdentity { user_id, tenant_id } = &self.identity;
170
vec![
171
("x-client-version".to_owned(), client_version.to_owned()),
172
("X-ClientType".to_owned(), "MicrosoftTeams".to_owned()),
173
("X-ClientScenario".to_owned(), "TeamsSearch".to_owned()),
174
("client-request-id".to_owned(), new_id()),
175
(
176
"client-session-id".to_owned(),
177
search_session.correlation_id().to_owned(),
178
),
179
(
180
"x-anchormailbox".to_owned(),
181
format!("Oid:{user_id}@{tenant_id}"),
182
),
183
(
184
"x-routingparameter-sessionkey".to_owned(),
185
format!("OID:{user_id}@{tenant_id}"),
186
),
187
]
188
}
189
}
190
191
fn ensure_success(answer: &ApiResponse) -> Result<()> {
192
if answer.is_success() {
193
Ok(())
194
} else {
195
Err(Error::Session(session::Error::api(
196
answer.status,
197
"substrate search",
198
answer.body.clone(),
199
)))
200
}
201
}
202
203
fn new_id() -> String {
204
uuid::Uuid::new_v4().to_string()
205
}
206
207
#[cfg(test)]
208
mod tests;
@@ -0,0 +1,208 @@1
mod highlight;2
mod kql;3
mod model;4
mod request;5
6
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};7
use session::{ApiResponse, Method, Request, Scope, Session};8
9
use crate::error::{Error, Result};10
use crate::pins::{CsaTransport, SessionTransport};11
12
pub use highlight::{HighlightedText, split_highlights};13
pub use kql::{MessageFilter, message_query_string};14
pub use model::{15
BestMatch, ChatMember, QueryResults, ResultPage, SearchChannel, SearchChat, SearchEvent,16
SearchFile, SearchMessage, SearchPerson, SearchTeam, SearchText, Suggestions,17
parse_query_results, parse_suggestions,18
};19
pub use request::{QueryRequest, QueryScope};20
21
pub const SUBSTRATE: &str = "https://substrate.office.com";22
pub const SUBSTRATE_SEARCH_SCOPE: &str = "SubstrateSearch-Internal.ReadWrite";23
const SCENARIO: &str = "powerbar";24
const SUGGESTION_CLIENT_VERSION: &str = "T2.1";25
const QUERY_CLIENT_VERSION: &str = "1";26
const SUGGESTION_FLIGHTS: &str = "IncludeHistoryInBMDynamic,PeopleKeywordAsTextSuggestion,TDPeopleSynthetic,EnableKql,EnableSelfSuggestion";27
const SUGGESTION_SET_FLIGHTS: &str = "EnableMessageImageSearch,EnableTeamsChannelDomainPowerbar";28
29
/// Without the anchor mailbox headers Substrate answers 200 with empty result sets.30
#[derive(Debug, Clone, PartialEq, Eq)]31
pub struct SearchIdentity {32
pub user_id: String,33
pub tenant_id: String,34
}35
36
/// One search session per opened search box: Teams sends the same cvid for every keystroke.37
#[derive(Debug, Clone, PartialEq, Eq)]38
pub struct SearchSession {39
correlation_id: String,40
}41
42
impl SearchSession {43
pub fn new() -> Self {44
SearchSession {45
correlation_id: new_id(),46
}47
}48
49
pub fn correlation_id(&self) -> &str {50
&self.correlation_id51
}52
}53
54
impl Default for SearchSession {55
fn default() -> Self {56
SearchSession::new()57
}58
}59
60
pub struct SubstrateSearch<T: CsaTransport = SessionTransport> {61
transport: T,62
identity: SearchIdentity,63
base_url: String,64
}65
66
impl SubstrateSearch<SessionTransport> {67
pub fn new(session: &Session, identity: SearchIdentity) -> Self {68
let transport =69
SessionTransport::with_scope(session, Scope::new(SUBSTRATE, SUBSTRATE_SEARCH_SCOPE));70
SubstrateSearch::with_transport(transport, identity, SUBSTRATE)71
}72
}73
74
impl<T: CsaTransport> SubstrateSearch<T> {75
pub fn with_transport(transport: T, identity: SearchIdentity, base_url: &str) -> Self {76
SubstrateSearch {77
transport,78
identity,79
base_url: base_url.trim_end_matches('/').to_owned(),80
}81
}82
83
pub async fn init(&self, search_session: &SearchSession) -> Result<()> {84
let url = format!(85
"{}/search/api/v2/init?cvid={}&scenario={SCENARIO}",86
self.base_url,87
search_session.correlation_id()88
);89
let answer = self90
.send(Request::get(url), search_session, SUGGESTION_CLIENT_VERSION)91
.await?;92
ensure_success(&answer)93
}94
95
/// An empty text returns the zero-query state: top people, recent searches, chats.96
pub async fn suggestions(97
&self,98
search_session: &SearchSession,99
text: &str,100
) -> Result<Suggestions> {101
let logical_id = new_id();102
let correlation_id = search_session.correlation_id();103
let mut request = if text.trim().is_empty() {104
Request::get(format!(105
"{}/search/api/v1/suggestions?scenario={SCENARIO}&query=&cvid={correlation_id}&logicalId={logical_id}",106
self.base_url107
))108
} else {109
Request::with_body(110
Method::Post,111
format!(112
"{}/search/api/v1/suggestions?scenario={SCENARIO}&setflight={}",113
self.base_url,114
utf8_percent_encode(SUGGESTION_SET_FLIGHTS, NON_ALPHANUMERIC)115
),116
request::suggestion_body(text, correlation_id, &logical_id),117
)118
};119
request120
.headers121
.push(("x-client-flights".to_owned(), SUGGESTION_FLIGHTS.to_owned()));122
let answer = self123
.send(request, search_session, SUGGESTION_CLIENT_VERSION)124
.await?;125
ensure_success(&answer)?;126
Ok(parse_suggestions(&answer.body))127
}128
129
pub async fn query(130
&self,131
search_session: &SearchSession,132
query: &QueryRequest,133
) -> Result<QueryResults> {134
let body = request::query_body(135
query,136
&self.identity.user_id,137
search_session.correlation_id(),138
&new_id(),139
);140
let request = Request::with_body(141
Method::Post,142
format!("{}/searchservice/api/v2/query", self.base_url),143
body,144
);145
let answer = self146
.send(request, search_session, QUERY_CLIENT_VERSION)147
.await?;148
ensure_success(&answer)?;149
Ok(parse_query_results(&answer.body))150
}151
152
async fn send(153
&self,154
mut request: Request,155
search_session: &SearchSession,156
client_version: &str,157
) -> Result<ApiResponse> {158
request159
.headers160
.extend(self.headers(search_session, client_version));161
self.transport.send(request).await162
}163
164
fn headers(165
&self,166
search_session: &SearchSession,167
client_version: &str,168
) -> Vec<(String, String)> {169
let SearchIdentity { user_id, tenant_id } = &self.identity;170
vec![171
("x-client-version".to_owned(), client_version.to_owned()),172
("X-ClientType".to_owned(), "MicrosoftTeams".to_owned()),173
("X-ClientScenario".to_owned(), "TeamsSearch".to_owned()),174
("client-request-id".to_owned(), new_id()),175
(176
"client-session-id".to_owned(),177
search_session.correlation_id().to_owned(),178
),179
(180
"x-anchormailbox".to_owned(),181
format!("Oid:{user_id}@{tenant_id}"),182
),183
(184
"x-routingparameter-sessionkey".to_owned(),185
format!("OID:{user_id}@{tenant_id}"),186
),187
]188
}189
}190
191
fn ensure_success(answer: &ApiResponse) -> Result<()> {192
if answer.is_success() {193
Ok(())194
} else {195
Err(Error::Session(session::Error::api(196
answer.status,197
"substrate search",198
answer.body.clone(),199
)))200
}201
}202
203
fn new_id() -> String {204
uuid::Uuid::new_v4().to_string()205
}206
207
#[cfg(test)]208
mod tests;@@ -0,0 +1,524 @@
1
use chrono::{DateTime, Utc};
2
use serde::Deserialize;
3
use serde_json::Value;
4
5
const READ_FLAG: &str = "IsRead";
6
const MESSAGE_ID_MARKER: &str = ";messageid=";
7
8
#[derive(Debug, Clone, Default, PartialEq)]
9
pub struct Suggestions {
10
pub people: Vec<SearchPerson>,
11
pub chats: Vec<SearchChat>,
12
pub channels: Vec<SearchChannel>,
13
pub teams: Vec<SearchTeam>,
14
pub messages: Vec<SearchMessage>,
15
pub files: Vec<SearchFile>,
16
pub events: Vec<SearchEvent>,
17
pub texts: Vec<SearchText>,
18
pub best_matches: Vec<BestMatch>,
19
}
20
21
#[derive(Debug, Clone, Default, PartialEq)]
22
pub struct QueryResults {
23
pub messages: ResultPage<SearchMessage>,
24
pub people: ResultPage<SearchPerson>,
25
pub chats: ResultPage<SearchChat>,
26
pub channels: ResultPage<SearchChannel>,
27
pub files: ResultPage<SearchFile>,
28
pub search_terms: Vec<String>,
29
}
30
31
#[derive(Debug, Clone, PartialEq)]
32
pub struct ResultPage<T> {
33
pub total: u64,
34
pub more_available: bool,
35
pub items: Vec<T>,
36
}
37
38
impl<T> Default for ResultPage<T> {
39
fn default() -> Self {
40
ResultPage {
41
total: 0,
42
more_available: false,
43
items: Vec::new(),
44
}
45
}
46
}
47
48
#[derive(Debug, Clone, PartialEq, Eq)]
49
pub struct BestMatch {
50
pub group: String,
51
pub reference_id: String,
52
}
53
54
#[derive(Debug, Clone, Default, PartialEq, Eq)]
55
pub struct SearchPerson {
56
pub reference_id: Option<String>,
57
pub user_id: Option<String>,
58
pub mri: Option<String>,
59
pub display_name: String,
60
pub given_name: Option<String>,
61
pub surname: Option<String>,
62
pub email_addresses: Vec<String>,
63
pub user_principal_name: Option<String>,
64
pub job_title: Option<String>,
65
pub department: Option<String>,
66
pub company_name: Option<String>,
67
pub office_location: Option<String>,
68
pub people_subtype: Option<String>,
69
}
70
71
#[derive(Debug, Clone, Default, PartialEq, Eq)]
72
pub struct ChatMember {
73
pub display_name: String,
74
pub mri: Option<String>,
75
}
76
77
#[derive(Debug, Clone, Default, PartialEq)]
78
pub struct SearchChat {
79
pub reference_id: Option<String>,
80
pub thread_id: String,
81
pub name: Option<String>,
82
pub thread_type: Option<String>,
83
pub last_message_at: Option<DateTime<Utc>>,
84
pub total_members: u32,
85
pub members: Vec<ChatMember>,
86
pub matching_members: Vec<ChatMember>,
87
}
88
89
#[derive(Debug, Clone, Default, PartialEq, Eq)]
90
pub struct SearchChannel {
91
pub reference_id: Option<String>,
92
pub thread_id: String,
93
pub name: String,
94
pub team_name: Option<String>,
95
pub team_id: Option<String>,
96
pub channel_type: Option<String>,
97
}
98
99
#[derive(Debug, Clone, Default, PartialEq, Eq)]
100
pub struct SearchTeam {
101
pub reference_id: Option<String>,
102
pub thread_id: Option<String>,
103
pub team_id: Option<String>,
104
pub name: String,
105
}
106
107
#[derive(Debug, Clone, Default, PartialEq)]
108
pub struct SearchMessage {
109
pub reference_id: Option<String>,
110
pub conversation_id: String,
111
pub message_id: String,
112
pub root_message_id: Option<String>,
113
pub sent_at: Option<DateTime<Utc>>,
114
pub sender_name: Option<String>,
115
pub sender_address: Option<String>,
116
pub sender_mri: Option<String>,
117
pub preview: String,
118
pub highlighted_summary: Option<String>,
119
pub thread_type: Option<String>,
120
pub thread_sub_type: Option<String>,
121
pub is_read: Option<bool>,
122
pub is_mentioned: bool,
123
pub has_attachments: bool,
124
}
125
126
#[derive(Debug, Clone, Default, PartialEq)]
127
pub struct SearchFile {
128
pub reference_id: Option<String>,
129
pub name: String,
130
pub extension: Option<String>,
131
pub size: Option<u64>,
132
pub url: Option<String>,
133
pub author: Option<String>,
134
pub modified_at: Option<DateTime<Utc>>,
135
pub shared_at: Option<DateTime<Utc>>,
136
}
137
138
#[derive(Debug, Clone, Default, PartialEq)]
139
pub struct SearchEvent {
140
pub reference_id: Option<String>,
141
pub subject: String,
142
pub organizer_name: Option<String>,
143
pub start: Option<DateTime<Utc>>,
144
pub end: Option<DateTime<Utc>>,
145
pub location: Option<String>,
146
pub teams_meeting_url: Option<String>,
147
pub web_link: Option<String>,
148
}
149
150
#[derive(Debug, Clone, Default, PartialEq, Eq)]
151
pub struct SearchText {
152
pub reference_id: Option<String>,
153
pub text: String,
154
pub query_text: Option<String>,
155
pub kind: Option<String>,
156
}
157
158
#[derive(Deserialize, Default)]
159
#[serde(rename_all = "PascalCase", default)]
160
struct WireSuggestions {
161
groups: Vec<WireGroup>,
162
layout_hints: WireLayoutHints,
163
}
164
165
#[derive(Deserialize, Default)]
166
#[serde(rename_all = "PascalCase", default)]
167
struct WireGroup {
168
#[serde(rename = "Type")]
169
group_type: String,
170
suggestions: Vec<Value>,
171
}
172
173
#[derive(Deserialize, Default)]
174
#[serde(rename_all = "PascalCase", default)]
175
struct WireLayoutHints {
176
best_match_suggestions: Vec<WireBestMatch>,
177
}
178
179
#[derive(Deserialize, Default)]
180
#[serde(rename_all = "PascalCase", default)]
181
struct WireBestMatch {
182
group: String,
183
reference_id: String,
184
}
185
186
#[derive(Deserialize, Default)]
187
#[serde(rename_all = "PascalCase", default)]
188
struct WireQuery {
189
entity_sets: Vec<WireEntitySet>,
190
search_terms: Vec<String>,
191
}
192
193
#[derive(Deserialize, Default)]
194
#[serde(rename_all = "PascalCase", default)]
195
struct WireEntitySet {
196
entity_type: String,
197
result_sets: Vec<WireResultSet>,
198
}
199
200
#[derive(Deserialize, Default)]
201
#[serde(rename_all = "PascalCase", default)]
202
struct WireResultSet {
203
total: u64,
204
more_results_available: bool,
205
results: Vec<WireResult>,
206
}
207
208
#[derive(Deserialize, Default)]
209
#[serde(rename_all = "PascalCase", default)]
210
struct WireResult {
211
reference_id: Option<String>,
212
hit_highlighted_summary: Option<String>,
213
source: Value,
214
}
215
216
pub fn parse_suggestions(body: &Value) -> Suggestions {
217
let wire: WireSuggestions = WireSuggestions::deserialize(body).unwrap_or_default();
218
let mut suggestions = Suggestions {
219
best_matches: wire
220
.layout_hints
221
.best_match_suggestions
222
.into_iter()
223
.map(|hint| BestMatch {
224
group: hint.group,
225
reference_id: hint.reference_id,
226
})
227
.collect(),
228
..Suggestions::default()
229
};
230
for group in wire.groups {
231
let items = group.suggestions.iter();
232
match group.group_type.as_str() {
233
"People" => suggestions
234
.people
235
.extend(items.filter_map(|item| person(item))),
236
"Chat" => suggestions
237
.chats
238
.extend(items.filter_map(|item| chat(item))),
239
"Channel" => suggestions
240
.channels
241
.extend(items.filter_map(|item| channel(item))),
242
"Team" => suggestions
243
.teams
244
.extend(items.filter_map(|item| team(item))),
245
"Message" => suggestions
246
.messages
247
.extend(items.filter_map(|item| message(item, None))),
248
"File" => suggestions
249
.files
250
.extend(items.filter_map(|item| file(item))),
251
"Event" => suggestions
252
.events
253
.extend(items.filter_map(|item| event(item))),
254
"Text" => suggestions
255
.texts
256
.extend(items.filter_map(|item| text(item))),
257
_ => {}
258
}
259
}
260
suggestions
261
}
262
263
pub fn parse_query_results(body: &Value) -> QueryResults {
264
let wire: WireQuery = WireQuery::deserialize(body).unwrap_or_default();
265
let mut results = QueryResults {
266
search_terms: wire.search_terms,
267
..QueryResults::default()
268
};
269
for entity_set in wire.entity_sets {
270
for result_set in entity_set.result_sets {
271
match entity_set.entity_type.as_str() {
272
"Message" => fill(&mut results.messages, &result_set, |result| {
273
message(&result.source, result.hit_highlighted_summary.clone())
274
}),
275
"People" => fill(&mut results.people, &result_set, |result| {
276
person(&result.source)
277
}),
278
"Chat" => fill(&mut results.chats, &result_set, |result| {
279
chat(&result.source)
280
}),
281
"TeamsChannel" | "Channel" => fill(&mut results.channels, &result_set, |result| {
282
channel(&result.source)
283
}),
284
"File" => fill(&mut results.files, &result_set, |result| {
285
file(&result.source)
286
}),
287
_ => {}
288
}
289
}
290
}
291
results
292
}
293
294
fn fill<T>(
295
page: &mut ResultPage<T>,
296
result_set: &WireResultSet,
297
convert: impl Fn(&WireResult) -> Option<T>,
298
) {
299
page.total = page.total.max(result_set.total);
300
page.more_available |= result_set.more_results_available;
301
page.items.extend(
302
result_set
303
.results
304
.iter()
305
.filter_map(|result| convert(&with_reference(result))),
306
);
307
}
308
309
fn with_reference(result: &WireResult) -> WireResult {
310
let mut source = result.source.clone();
311
if let (Some(fields), Some(reference_id)) = (source.as_object_mut(), &result.reference_id) {
312
fields
313
.entry("ReferenceId")
314
.or_insert_with(|| Value::String(reference_id.clone()));
315
}
316
WireResult {
317
reference_id: result.reference_id.clone(),
318
hit_highlighted_summary: result.hit_highlighted_summary.clone(),
319
source,
320
}
321
}
322
323
fn string(value: &Value, key: &str) -> Option<String> {
324
value
325
.get(key)
326
.and_then(Value::as_str)
327
.filter(|text| !text.is_empty())
328
.map(str::to_owned)
329
}
330
331
fn time(value: &Value, key: &str) -> Option<DateTime<Utc>> {
332
value
333
.get(key)
334
.and_then(Value::as_str)
335
.and_then(|text| DateTime::parse_from_rfc3339(text).ok())
336
.map(|parsed| parsed.with_timezone(&Utc))
337
}
338
339
fn strings(value: &Value, key: &str) -> Vec<String> {
340
value
341
.get(key)
342
.and_then(Value::as_array)
343
.map(|items| {
344
items
345
.iter()
346
.filter_map(Value::as_str)
347
.map(str::to_owned)
348
.collect()
349
})
350
.unwrap_or_default()
351
}
352
353
fn members(value: &Value, key: &str) -> Vec<ChatMember> {
354
value
355
.get(key)
356
.and_then(Value::as_array)
357
.map(|items| {
358
items
359
.iter()
360
.filter_map(|member| {
361
Some(ChatMember {
362
display_name: string(member, "DisplayName")?,
363
mri: string(member, "MRI"),
364
})
365
})
366
.collect()
367
})
368
.unwrap_or_default()
369
}
370
371
fn person(value: &Value) -> Option<SearchPerson> {
372
Some(SearchPerson {
373
reference_id: string(value, "ReferenceId"),
374
user_id: string(value, "ExternalDirectoryObjectId"),
375
mri: string(value, "MRI"),
376
display_name: string(value, "DisplayName")?,
377
given_name: string(value, "GivenName"),
378
surname: string(value, "Surname"),
379
email_addresses: strings(value, "EmailAddresses"),
380
user_principal_name: string(value, "UserPrincipalName"),
381
job_title: string(value, "JobTitle"),
382
department: string(value, "Department"),
383
company_name: string(value, "CompanyName"),
384
office_location: string(value, "OfficeLocation"),
385
people_subtype: string(value, "PeopleSubtype"),
386
})
387
}
388
389
fn chat(value: &Value) -> Option<SearchChat> {
390
Some(SearchChat {
391
reference_id: string(value, "ReferenceId"),
392
thread_id: string(value, "ThreadId")?,
393
name: string(value, "Name"),
394
thread_type: string(value, "ThreadType"),
395
last_message_at: time(value, "LastMessageTime"),
396
total_members: value
397
.get("TotalChatMembersCount")
398
.and_then(Value::as_u64)
399
.and_then(|count| u32::try_from(count).ok())
400
.unwrap_or_default(),
401
members: members(value, "ChatMembers"),
402
matching_members: members(value, "MatchingMembers"),
403
})
404
}
405
406
fn channel(value: &Value) -> Option<SearchChannel> {
407
Some(SearchChannel {
408
reference_id: string(value, "ReferenceId"),
409
thread_id: string(value, "ThreadId")?,
410
name: string(value, "Name")?,
411
team_name: string(value, "TeamName"),
412
team_id: string(value, "GroupId"),
413
channel_type: string(value, "ChannelType"),
414
})
415
}
416
417
fn team(value: &Value) -> Option<SearchTeam> {
418
Some(SearchTeam {
419
reference_id: string(value, "ReferenceId"),
420
thread_id: string(value, "ThreadId"),
421
team_id: string(value, "GroupId"),
422
name: string(value, "Name")?,
423
})
424
}
425
426
fn message(value: &Value, highlighted_summary: Option<String>) -> Option<SearchMessage> {
427
let extensions = value.get("Extensions").unwrap_or(&Value::Null);
428
let conversation_id = string(value, "ClientThreadId")?;
429
let message_id = string(value, "InternetMessageId")?;
430
let sender = value
431
.get("From")
432
.or_else(|| value.get("Sender"))
433
.unwrap_or(&Value::Null);
434
let sender_email = sender.get("EmailAddress").unwrap_or(&Value::Null);
435
let root_message_id = string(value, "ParentMessageId")
436
.or_else(|| {
437
string(
438
extensions,
439
"SkypeSpaces_ConversationPost_Extension_ParentMessageId",
440
)
441
})
442
.or_else(|| {
443
string(value, "ClientConversationId").and_then(|id| {
444
id.split_once(MESSAGE_ID_MARKER)
445
.map(|(_, root)| root.to_owned())
446
})
447
});
448
let metadata = strings(value, "Metadata");
449
Some(SearchMessage {
450
reference_id: string(value, "ReferenceId"),
451
conversation_id,
452
message_id,
453
root_message_id,
454
sent_at: time(value, "DateTimeSent"),
455
sender_name: string(sender_email, "Name"),
456
sender_address: string(sender_email, "Address"),
457
sender_mri: string(sender, "MRI").or_else(|| {
458
string(
459
extensions,
460
"SkypeSpaces_ConversationPost_Extension_FromSkypeInternalId",
461
)
462
}),
463
preview: string(value, "Preview").unwrap_or_default(),
464
highlighted_summary,
465
thread_type: string(value, "ThreadType").or_else(|| {
466
string(
467
extensions,
468
"SkypeSpaces_ConversationPost_Extension_ThreadType",
469
)
470
}),
471
thread_sub_type: string(value, "ThreadSubType"),
472
is_read: value
473
.get("Metadata")
474
.map(|_| metadata.iter().any(|flag| flag == READ_FLAG)),
475
is_mentioned: value
476
.pointer("/MentionsPreview/IsMentioned")
477
.and_then(Value::as_bool)
478
.unwrap_or_default(),
479
has_attachments: value
480
.get("HasAttachments")
481
.and_then(Value::as_bool)
482
.unwrap_or_default(),
483
})
484
}
485
486
fn file(value: &Value) -> Option<SearchFile> {
487
Some(SearchFile {
488
reference_id: string(value, "ReferenceId"),
489
name: string(value, "FileName")
490
.or_else(|| string(value, "Filename"))
491
.or_else(|| string(value, "Title"))?,
492
extension: string(value, "FileExtension"),
493
size: value
494
.get("FileSize")
495
.or_else(|| value.get("Size"))
496
.and_then(Value::as_u64),
497
url: string(value, "AccessUrl").or_else(|| string(value, "Path")),
498
author: string(value, "Author"),
499
modified_at: time(value, "DateModified").or_else(|| time(value, "LastModifiedTime")),
500
shared_at: time(value, "SharedDateTime"),
501
})
502
}
503
504
fn event(value: &Value) -> Option<SearchEvent> {
505
Some(SearchEvent {
506
reference_id: string(value, "ReferenceId"),
507
subject: string(value, "Subject")?,
508
organizer_name: string(value, "OrganizerName"),
509
start: time(value, "Start"),
510
end: time(value, "End"),
511
location: string(value, "Location"),
512
teams_meeting_url: string(value, "SkypeTeamsMeetingUrl"),
513
web_link: string(value, "WebLink"),
514
})
515
}
516
517
fn text(value: &Value) -> Option<SearchText> {
518
Some(SearchText {
519
reference_id: string(value, "ReferenceId"),
520
text: string(value, "Text")?,
521
query_text: string(value, "QueryText"),
522
kind: string(value, "TextSuggestionType"),
523
})
524
}
@@ -0,0 +1,524 @@1
use chrono::{DateTime, Utc};2
use serde::Deserialize;3
use serde_json::Value;4
5
const READ_FLAG: &str = "IsRead";6
const MESSAGE_ID_MARKER: &str = ";messageid=";7
8
#[derive(Debug, Clone, Default, PartialEq)]9
pub struct Suggestions {10
pub people: Vec<SearchPerson>,11
pub chats: Vec<SearchChat>,12
pub channels: Vec<SearchChannel>,13
pub teams: Vec<SearchTeam>,14
pub messages: Vec<SearchMessage>,15
pub files: Vec<SearchFile>,16
pub events: Vec<SearchEvent>,17
pub texts: Vec<SearchText>,18
pub best_matches: Vec<BestMatch>,19
}20
21
#[derive(Debug, Clone, Default, PartialEq)]22
pub struct QueryResults {23
pub messages: ResultPage<SearchMessage>,24
pub people: ResultPage<SearchPerson>,25
pub chats: ResultPage<SearchChat>,26
pub channels: ResultPage<SearchChannel>,27
pub files: ResultPage<SearchFile>,28
pub search_terms: Vec<String>,29
}30
31
#[derive(Debug, Clone, PartialEq)]32
pub struct ResultPage<T> {33
pub total: u64,34
pub more_available: bool,35
pub items: Vec<T>,36
}37
38
impl<T> Default for ResultPage<T> {39
fn default() -> Self {40
ResultPage {41
total: 0,42
more_available: false,43
items: Vec::new(),44
}45
}46
}47
48
#[derive(Debug, Clone, PartialEq, Eq)]49
pub struct BestMatch {50
pub group: String,51
pub reference_id: String,52
}53
54
#[derive(Debug, Clone, Default, PartialEq, Eq)]55
pub struct SearchPerson {56
pub reference_id: Option<String>,57
pub user_id: Option<String>,58
pub mri: Option<String>,59
pub display_name: String,60
pub given_name: Option<String>,61
pub surname: Option<String>,62
pub email_addresses: Vec<String>,63
pub user_principal_name: Option<String>,64
pub job_title: Option<String>,65
pub department: Option<String>,66
pub company_name: Option<String>,67
pub office_location: Option<String>,68
pub people_subtype: Option<String>,69
}70
71
#[derive(Debug, Clone, Default, PartialEq, Eq)]72
pub struct ChatMember {73
pub display_name: String,74
pub mri: Option<String>,75
}76
77
#[derive(Debug, Clone, Default, PartialEq)]78
pub struct SearchChat {79
pub reference_id: Option<String>,80
pub thread_id: String,81
pub name: Option<String>,82
pub thread_type: Option<String>,83
pub last_message_at: Option<DateTime<Utc>>,84
pub total_members: u32,85
pub members: Vec<ChatMember>,86
pub matching_members: Vec<ChatMember>,87
}88
89
#[derive(Debug, Clone, Default, PartialEq, Eq)]90
pub struct SearchChannel {91
pub reference_id: Option<String>,92
pub thread_id: String,93
pub name: String,94
pub team_name: Option<String>,95
pub team_id: Option<String>,96
pub channel_type: Option<String>,97
}98
99
#[derive(Debug, Clone, Default, PartialEq, Eq)]100
pub struct SearchTeam {101
pub reference_id: Option<String>,102
pub thread_id: Option<String>,103
pub team_id: Option<String>,104
pub name: String,105
}106
107
#[derive(Debug, Clone, Default, PartialEq)]108
pub struct SearchMessage {109
pub reference_id: Option<String>,110
pub conversation_id: String,111
pub message_id: String,112
pub root_message_id: Option<String>,113
pub sent_at: Option<DateTime<Utc>>,114
pub sender_name: Option<String>,115
pub sender_address: Option<String>,116
pub sender_mri: Option<String>,117
pub preview: String,118
pub highlighted_summary: Option<String>,119
pub thread_type: Option<String>,120
pub thread_sub_type: Option<String>,121
pub is_read: Option<bool>,122
pub is_mentioned: bool,123
pub has_attachments: bool,124
}125
126
#[derive(Debug, Clone, Default, PartialEq)]127
pub struct SearchFile {128
pub reference_id: Option<String>,129
pub name: String,130
pub extension: Option<String>,131
pub size: Option<u64>,132
pub url: Option<String>,133
pub author: Option<String>,134
pub modified_at: Option<DateTime<Utc>>,135
pub shared_at: Option<DateTime<Utc>>,136
}137
138
#[derive(Debug, Clone, Default, PartialEq)]139
pub struct SearchEvent {140
pub reference_id: Option<String>,141
pub subject: String,142
pub organizer_name: Option<String>,143
pub start: Option<DateTime<Utc>>,144
pub end: Option<DateTime<Utc>>,145
pub location: Option<String>,146
pub teams_meeting_url: Option<String>,147
pub web_link: Option<String>,148
}149
150
#[derive(Debug, Clone, Default, PartialEq, Eq)]151
pub struct SearchText {152
pub reference_id: Option<String>,153
pub text: String,154
pub query_text: Option<String>,155
pub kind: Option<String>,156
}157
158
#[derive(Deserialize, Default)]159
#[serde(rename_all = "PascalCase", default)]160
struct WireSuggestions {161
groups: Vec<WireGroup>,162
layout_hints: WireLayoutHints,163
}164
165
#[derive(Deserialize, Default)]166
#[serde(rename_all = "PascalCase", default)]167
struct WireGroup {168
#[serde(rename = "Type")]169
group_type: String,170
suggestions: Vec<Value>,171
}172
173
#[derive(Deserialize, Default)]174
#[serde(rename_all = "PascalCase", default)]175
struct WireLayoutHints {176
best_match_suggestions: Vec<WireBestMatch>,177
}178
179
#[derive(Deserialize, Default)]180
#[serde(rename_all = "PascalCase", default)]181
struct WireBestMatch {182
group: String,183
reference_id: String,184
}185
186
#[derive(Deserialize, Default)]187
#[serde(rename_all = "PascalCase", default)]188
struct WireQuery {189
entity_sets: Vec<WireEntitySet>,190
search_terms: Vec<String>,191
}192
193
#[derive(Deserialize, Default)]194
#[serde(rename_all = "PascalCase", default)]195
struct WireEntitySet {196
entity_type: String,197
result_sets: Vec<WireResultSet>,198
}199
200
#[derive(Deserialize, Default)]201
#[serde(rename_all = "PascalCase", default)]202
struct WireResultSet {203
total: u64,204
more_results_available: bool,205
results: Vec<WireResult>,206
}207
208
#[derive(Deserialize, Default)]209
#[serde(rename_all = "PascalCase", default)]210
struct WireResult {211
reference_id: Option<String>,212
hit_highlighted_summary: Option<String>,213
source: Value,214
}215
216
pub fn parse_suggestions(body: &Value) -> Suggestions {217
let wire: WireSuggestions = WireSuggestions::deserialize(body).unwrap_or_default();218
let mut suggestions = Suggestions {219
best_matches: wire220
.layout_hints221
.best_match_suggestions222
.into_iter()223
.map(|hint| BestMatch {224
group: hint.group,225
reference_id: hint.reference_id,226
})227
.collect(),228
..Suggestions::default()229
};230
for group in wire.groups {231
let items = group.suggestions.iter();232
match group.group_type.as_str() {233
"People" => suggestions234
.people235
.extend(items.filter_map(|item| person(item))),236
"Chat" => suggestions237
.chats238
.extend(items.filter_map(|item| chat(item))),239
"Channel" => suggestions240
.channels241
.extend(items.filter_map(|item| channel(item))),242
"Team" => suggestions243
.teams244
.extend(items.filter_map(|item| team(item))),245
"Message" => suggestions246
.messages247
.extend(items.filter_map(|item| message(item, None))),248
"File" => suggestions249
.files250
.extend(items.filter_map(|item| file(item))),251
"Event" => suggestions252
.events253
.extend(items.filter_map(|item| event(item))),254
"Text" => suggestions255
.texts256
.extend(items.filter_map(|item| text(item))),257
_ => {}258
}259
}260
suggestions261
}262
263
pub fn parse_query_results(body: &Value) -> QueryResults {264
let wire: WireQuery = WireQuery::deserialize(body).unwrap_or_default();265
let mut results = QueryResults {266
search_terms: wire.search_terms,267
..QueryResults::default()268
};269
for entity_set in wire.entity_sets {270
for result_set in entity_set.result_sets {271
match entity_set.entity_type.as_str() {272
"Message" => fill(&mut results.messages, &result_set, |result| {273
message(&result.source, result.hit_highlighted_summary.clone())274
}),275
"People" => fill(&mut results.people, &result_set, |result| {276
person(&result.source)277
}),278
"Chat" => fill(&mut results.chats, &result_set, |result| {279
chat(&result.source)280
}),281
"TeamsChannel" | "Channel" => fill(&mut results.channels, &result_set, |result| {282
channel(&result.source)283
}),284
"File" => fill(&mut results.files, &result_set, |result| {285
file(&result.source)286
}),287
_ => {}288
}289
}290
}291
results292
}293
294
fn fill<T>(295
page: &mut ResultPage<T>,296
result_set: &WireResultSet,297
convert: impl Fn(&WireResult) -> Option<T>,298
) {299
page.total = page.total.max(result_set.total);300
page.more_available |= result_set.more_results_available;301
page.items.extend(302
result_set303
.results304
.iter()305
.filter_map(|result| convert(&with_reference(result))),306
);307
}308
309
fn with_reference(result: &WireResult) -> WireResult {310
let mut source = result.source.clone();311
if let (Some(fields), Some(reference_id)) = (source.as_object_mut(), &result.reference_id) {312
fields313
.entry("ReferenceId")314
.or_insert_with(|| Value::String(reference_id.clone()));315
}316
WireResult {317
reference_id: result.reference_id.clone(),318
hit_highlighted_summary: result.hit_highlighted_summary.clone(),319
source,320
}321
}322
323
fn string(value: &Value, key: &str) -> Option<String> {324
value325
.get(key)326
.and_then(Value::as_str)327
.filter(|text| !text.is_empty())328
.map(str::to_owned)329
}330
331
fn time(value: &Value, key: &str) -> Option<DateTime<Utc>> {332
value333
.get(key)334
.and_then(Value::as_str)335
.and_then(|text| DateTime::parse_from_rfc3339(text).ok())336
.map(|parsed| parsed.with_timezone(&Utc))337
}338
339
fn strings(value: &Value, key: &str) -> Vec<String> {340
value341
.get(key)342
.and_then(Value::as_array)343
.map(|items| {344
items345
.iter()346
.filter_map(Value::as_str)347
.map(str::to_owned)348
.collect()349
})350
.unwrap_or_default()351
}352
353
fn members(value: &Value, key: &str) -> Vec<ChatMember> {354
value355
.get(key)356
.and_then(Value::as_array)357
.map(|items| {358
items359
.iter()360
.filter_map(|member| {361
Some(ChatMember {362
display_name: string(member, "DisplayName")?,363
mri: string(member, "MRI"),364
})365
})366
.collect()367
})368
.unwrap_or_default()369
}370
371
fn person(value: &Value) -> Option<SearchPerson> {372
Some(SearchPerson {373
reference_id: string(value, "ReferenceId"),374
user_id: string(value, "ExternalDirectoryObjectId"),375
mri: string(value, "MRI"),376
display_name: string(value, "DisplayName")?,377
given_name: string(value, "GivenName"),378
surname: string(value, "Surname"),379
email_addresses: strings(value, "EmailAddresses"),380
user_principal_name: string(value, "UserPrincipalName"),381
job_title: string(value, "JobTitle"),382
department: string(value, "Department"),383
company_name: string(value, "CompanyName"),384
office_location: string(value, "OfficeLocation"),385
people_subtype: string(value, "PeopleSubtype"),386
})387
}388
389
fn chat(value: &Value) -> Option<SearchChat> {390
Some(SearchChat {391
reference_id: string(value, "ReferenceId"),392
thread_id: string(value, "ThreadId")?,393
name: string(value, "Name"),394
thread_type: string(value, "ThreadType"),395
last_message_at: time(value, "LastMessageTime"),396
total_members: value397
.get("TotalChatMembersCount")398
.and_then(Value::as_u64)399
.and_then(|count| u32::try_from(count).ok())400
.unwrap_or_default(),401
members: members(value, "ChatMembers"),402
matching_members: members(value, "MatchingMembers"),403
})404
}405
406
fn channel(value: &Value) -> Option<SearchChannel> {407
Some(SearchChannel {408
reference_id: string(value, "ReferenceId"),409
thread_id: string(value, "ThreadId")?,410
name: string(value, "Name")?,411
team_name: string(value, "TeamName"),412
team_id: string(value, "GroupId"),413
channel_type: string(value, "ChannelType"),414
})415
}416
417
fn team(value: &Value) -> Option<SearchTeam> {418
Some(SearchTeam {419
reference_id: string(value, "ReferenceId"),420
thread_id: string(value, "ThreadId"),421
team_id: string(value, "GroupId"),422
name: string(value, "Name")?,423
})424
}425
426
fn message(value: &Value, highlighted_summary: Option<String>) -> Option<SearchMessage> {427
let extensions = value.get("Extensions").unwrap_or(&Value::Null);428
let conversation_id = string(value, "ClientThreadId")?;429
let message_id = string(value, "InternetMessageId")?;430
let sender = value431
.get("From")432
.or_else(|| value.get("Sender"))433
.unwrap_or(&Value::Null);434
let sender_email = sender.get("EmailAddress").unwrap_or(&Value::Null);435
let root_message_id = string(value, "ParentMessageId")436
.or_else(|| {437
string(438
extensions,439
"SkypeSpaces_ConversationPost_Extension_ParentMessageId",440
)441
})442
.or_else(|| {443
string(value, "ClientConversationId").and_then(|id| {444
id.split_once(MESSAGE_ID_MARKER)445
.map(|(_, root)| root.to_owned())446
})447
});448
let metadata = strings(value, "Metadata");449
Some(SearchMessage {450
reference_id: string(value, "ReferenceId"),451
conversation_id,452
message_id,453
root_message_id,454
sent_at: time(value, "DateTimeSent"),455
sender_name: string(sender_email, "Name"),456
sender_address: string(sender_email, "Address"),457
sender_mri: string(sender, "MRI").or_else(|| {458
string(459
extensions,460
"SkypeSpaces_ConversationPost_Extension_FromSkypeInternalId",461
)462
}),463
preview: string(value, "Preview").unwrap_or_default(),464
highlighted_summary,465
thread_type: string(value, "ThreadType").or_else(|| {466
string(467
extensions,468
"SkypeSpaces_ConversationPost_Extension_ThreadType",469
)470
}),471
thread_sub_type: string(value, "ThreadSubType"),472
is_read: value473
.get("Metadata")474
.map(|_| metadata.iter().any(|flag| flag == READ_FLAG)),475
is_mentioned: value476
.pointer("/MentionsPreview/IsMentioned")477
.and_then(Value::as_bool)478
.unwrap_or_default(),479
has_attachments: value480
.get("HasAttachments")481
.and_then(Value::as_bool)482
.unwrap_or_default(),483
})484
}485
486
fn file(value: &Value) -> Option<SearchFile> {487
Some(SearchFile {488
reference_id: string(value, "ReferenceId"),489
name: string(value, "FileName")490
.or_else(|| string(value, "Filename"))491
.or_else(|| string(value, "Title"))?,492
extension: string(value, "FileExtension"),493
size: value494
.get("FileSize")495
.or_else(|| value.get("Size"))496
.and_then(Value::as_u64),497
url: string(value, "AccessUrl").or_else(|| string(value, "Path")),498
author: string(value, "Author"),499
modified_at: time(value, "DateModified").or_else(|| time(value, "LastModifiedTime")),500
shared_at: time(value, "SharedDateTime"),501
})502
}503
504
fn event(value: &Value) -> Option<SearchEvent> {505
Some(SearchEvent {506
reference_id: string(value, "ReferenceId"),507
subject: string(value, "Subject")?,508
organizer_name: string(value, "OrganizerName"),509
start: time(value, "Start"),510
end: time(value, "End"),511
location: string(value, "Location"),512
teams_meeting_url: string(value, "SkypeTeamsMeetingUrl"),513
web_link: string(value, "WebLink"),514
})515
}516
517
fn text(value: &Value) -> Option<SearchText> {518
Some(SearchText {519
reference_id: string(value, "ReferenceId"),520
text: string(value, "Text")?,521
query_text: string(value, "QueryText"),522
kind: string(value, "TextSuggestionType"),523
})524
}@@ -0,0 +1,371 @@
1
use serde_json::{Value, json};
2
3
use super::kql::{MessageFilter, message_query_string};
4
5
const APP_NAME: &str = "Microsoft Teams";
6
const SCENARIO: &str = "powerbar";
7
const TIME_ZONE: &str = "Europe/Berlin";
8
const FORM_FACTOR: &str = "general.web.reactSearch";
9
const TAB_PAGE_SIZE: usize = 25;
10
const TAB_TOP_RESULTS: usize = 5;
11
const MESSAGE_FIELDS: [&str; 8] = [
12
"Extension_SkypeSpaces_ConversationPost_Extension_FromSkypeInternalId_String",
13
"Extension_SkypeSpaces_ConversationPost_Extension_FileData_String",
14
"Extension_SkypeSpaces_ConversationPost_Extension_ThreadType_String",
15
"Extension_SkypeSpaces_ConversationPost_Extension_SkypeGroupId_String",
16
"Extension_SkypeSpaces_ConversationPost_Extension_SenderTenantId_String",
17
"Extension_SkypeSpaces_ConversationPost_Extension_ParentMessageId_String",
18
"Extension_SkypeSpaces_ConversationPost_Extension_ImageSrc_String",
19
"Extension_SkypeSpaces_ConversationPost_Extension_AmsReferences_StringArray",
20
];
21
const PEOPLE_FIELDS: [&str; 18] = [
22
"Id",
23
"MRI",
24
"DisplayName",
25
"EmailAddresses",
26
"PeopleType",
27
"PeopleSubtype",
28
"Phones",
29
"UserPrincipalName",
30
"GivenName",
31
"Surname",
32
"CompanyName",
33
"JobTitle",
34
"ImAddress",
35
"ExternalDirectoryObjectId",
36
"Department",
37
"OfficeLocation",
38
"HomeTenantName",
39
"MTOLabel",
40
];
41
42
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43
pub enum QueryScope {
44
All,
45
Messages,
46
People,
47
Chats,
48
Channels,
49
Files,
50
}
51
52
#[derive(Debug, Clone, PartialEq, Eq)]
53
pub struct QueryRequest {
54
pub text: String,
55
pub scope: QueryScope,
56
pub filters: Vec<MessageFilter>,
57
pub from: usize,
58
pub size: usize,
59
}
60
61
impl QueryRequest {
62
pub fn new(text: impl Into<String>, scope: QueryScope) -> Self {
63
QueryRequest {
64
text: text.into(),
65
scope,
66
filters: Vec::new(),
67
from: 0,
68
size: TAB_PAGE_SIZE,
69
}
70
}
71
72
pub fn with_filters(mut self, filters: Vec<MessageFilter>) -> Self {
73
self.filters = filters;
74
self
75
}
76
77
pub fn page(mut self, from: usize) -> Self {
78
self.from = from;
79
self
80
}
81
82
fn is_contextual(&self) -> bool {
83
self.filters
84
.iter()
85
.any(|filter| matches!(filter, MessageFilter::InChat { .. }))
86
}
87
88
fn query_type(&self) -> &'static str {
89
if self.is_contextual() {
90
return "ContextualTypeahead";
91
}
92
match self.scope {
93
QueryScope::All => "All",
94
QueryScope::Messages => "Messages",
95
QueryScope::People => "People",
96
QueryScope::Chats => "Chats",
97
QueryScope::Channels => "Channels",
98
QueryScope::Files => "Files",
99
}
100
}
101
}
102
103
pub(super) fn suggestion_body(text: &str, correlation_id: &str, logical_id: &str) -> Value {
104
let query = json!({
105
"QueryString": text,
106
"DisplayQueryString": text,
107
"NormalizedQueryString": text,
108
});
109
let entity = |entity_type: &str, size: usize| json!({"EntityType": entity_type, "Size": size, "Query": query});
110
let mut people = entity("People", 5);
111
people["Fields"] = json!(&PEOPLE_FIELDS[..15]);
112
people["Filter"] = people_filter();
113
people["Provenances"] = json!(["Mailbox", "Directory"]);
114
people["From"] = json!(0);
115
let mut channel = entity("Channel", 4);
116
channel["Filter"] = json!({"Or": [
117
{"Term": {"ChannelType": "Standard"}},
118
{"Term": {"ChannelType": "Shared"}},
119
]});
120
json!({
121
"EntityRequests": [
122
people,
123
entity("File", 3),
124
entity("Chat", 5),
125
entity("Team", 3),
126
channel,
127
entity("Text", 2),
128
entity("Message", 11),
129
entity("Event", 3),
130
],
131
"Scenario": {
132
"Name": SCENARIO,
133
"Dimensions": [{"DimensionName": "QueryType", "DimensionValue": "PeopleCentricSearch"}],
134
},
135
"Cvid": correlation_id,
136
"LogicalId": logical_id,
137
"AppName": APP_NAME,
138
"dataSource": "personScoped",
139
})
140
}
141
142
pub(super) fn query_body(
143
request: &QueryRequest,
144
user_id: &str,
145
correlation_id: &str,
146
logical_id: &str,
147
) -> Value {
148
let plain_query = json!({"queryString": request.text, "displayQueryString": request.text});
149
let entity_requests: Vec<Value> = match request.scope {
150
QueryScope::All => vec![
151
message_entity(request, user_id, 3, 3),
152
file_entity(&plain_query, 0, 3),
153
people_entity(&plain_query, 0, 8),
154
plain_entity("Chat", &plain_query, 0, 3),
155
plain_entity("TeamsChannel", &plain_query, 0, 3),
156
],
157
QueryScope::Messages => vec![message_entity(
158
request,
159
user_id,
160
request.size,
161
if request.from == 0 {
162
TAB_TOP_RESULTS
163
} else {
164
0
165
},
166
)],
167
QueryScope::People => vec![people_entity(&plain_query, request.from, request.size)],
168
QueryScope::Chats => vec![plain_entity(
169
"Chat",
170
&plain_query,
171
request.from,
172
request.size,
173
)],
174
QueryScope::Channels => vec![plain_entity(
175
"TeamsChannel",
176
&plain_query,
177
request.from,
178
request.size,
179
)],
180
QueryScope::Files => vec![file_entity(&plain_query, request.from, request.size)],
181
};
182
json!({
183
"EntityRequests": entity_requests,
184
"QueryAlterationOptions": {
185
"EnableAlteration": true,
186
"EnableSuggestion": true,
187
"SupportedRecourseDisplayTypes": ["Suggestion"],
188
},
189
"scenario": {
190
"Name": SCENARIO,
191
"Dimensions": [
192
{"DimensionName": "QueryType", "DimensionValue": request.query_type()},
193
{"DimensionName": "FormFactor", "DimensionValue": FORM_FACTOR},
194
],
195
},
196
"cvid": correlation_id,
197
"logicalId": logical_id,
198
"timezone": TIME_ZONE,
199
})
200
}
201
202
fn message_entity(
203
request: &QueryRequest,
204
user_id: &str,
205
size: usize,
206
top_results_count: usize,
207
) -> Value {
208
let query_string = message_query_string(&request.text, &request.filters, user_id);
209
let mut entity = json!({
210
"entityType": "Message",
211
"contentSources": ["Teams"],
212
"propertySet": "Optimized",
213
"fields": MESSAGE_FIELDS,
214
"query": {"queryString": query_string, "displayQueryString": request.text},
215
"from": request.from,
216
"size": size,
217
});
218
if top_results_count > 0 {
219
entity["topResultsCount"] = json!(top_results_count);
220
}
221
entity
222
}
223
224
fn people_entity(query: &Value, from: usize, size: usize) -> Value {
225
json!({
226
"entityType": "People",
227
"contentSources": ["Exchange"],
228
"Fields": PEOPLE_FIELDS,
229
"Filter": people_filter(),
230
"query": query,
231
"from": from,
232
"size": size,
233
})
234
}
235
236
fn file_entity(query: &Value, from: usize, size: usize) -> Value {
237
json!({
238
"entityType": "File",
239
"contentSources": ["OneDriveBusiness", "Exchange"],
240
"query": query,
241
"from": from,
242
"size": size,
243
})
244
}
245
246
fn plain_entity(entity_type: &str, query: &Value, from: usize, size: usize) -> Value {
247
json!({
248
"entityType": entity_type,
249
"contentSources": ["Teams"],
250
"query": query,
251
"from": from,
252
"size": size,
253
})
254
}
255
256
fn people_filter() -> Value {
257
let any_term = |field: &str, values: &[&str]| {
258
let terms: Vec<Value> = values
259
.iter()
260
.map(|value| json!({"Term": {field: value}}))
261
.collect();
262
json!({"Or": terms})
263
};
264
json!({"And": [
265
any_term("PeopleType", &["Person", "Other"]),
266
any_term(
267
"PeopleSubtype",
268
&["OrganizationUser", "MTOUser", "PersonalContact", "Guest"],
269
),
270
any_term("Flags", &["NonHidden"]),
271
]})
272
}
273
274
#[cfg(test)]
275
mod tests {
276
use super::*;
277
278
#[test]
279
fn suggestions_ask_for_every_domain_in_teams_order() {
280
let body = suggestion_body("chr", "session", "request");
281
let types: Vec<&str> = body["EntityRequests"]
282
.as_array()
283
.unwrap()
284
.iter()
285
.map(|entity| entity["EntityType"].as_str().unwrap())
286
.collect();
287
assert_eq!(
288
types,
289
[
290
"People", "File", "Chat", "Team", "Channel", "Text", "Message", "Event"
291
]
292
);
293
assert_eq!(body["Cvid"], "session");
294
assert_eq!(body["LogicalId"], "request");
295
assert_eq!(body["EntityRequests"][0]["Query"]["QueryString"], "chr");
296
assert_eq!(
297
body["EntityRequests"][0]["Provenances"],
298
json!(["Mailbox", "Directory"])
299
);
300
}
301
302
#[test]
303
fn all_scope_uses_the_teams_section_sizes() {
304
let request = QueryRequest::new("release", QueryScope::All);
305
let body = query_body(&request, "user", "session", "request");
306
let sizes: Vec<(String, u64)> = body["EntityRequests"]
307
.as_array()
308
.unwrap()
309
.iter()
310
.map(|entity| {
311
(
312
entity["entityType"].as_str().unwrap().to_owned(),
313
entity["size"].as_u64().unwrap(),
314
)
315
})
316
.collect();
317
assert_eq!(
318
sizes,
319
[
320
("Message".to_owned(), 3),
321
("File".to_owned(), 3),
322
("People".to_owned(), 8),
323
("Chat".to_owned(), 3),
324
("TeamsChannel".to_owned(), 3),
325
]
326
);
327
assert_eq!(
328
body["EntityRequests"][0]["query"]["queryString"],
329
"NOT (isClientSoftDeleted:TRUE) AND release"
330
);
331
assert_eq!(
332
body["EntityRequests"][0]["query"]["displayQueryString"],
333
"release"
334
);
335
assert_eq!(body["scenario"]["Dimensions"][0]["DimensionValue"], "All");
336
}
337
338
#[test]
339
fn messages_tab_pages_by_25_with_top_results_on_the_first_page_only() {
340
let first = query_body(
341
&QueryRequest::new("x", QueryScope::Messages),
342
"user",
343
"session",
344
"request",
345
);
346
assert_eq!(first["EntityRequests"][0]["size"], 25);
347
assert_eq!(first["EntityRequests"][0]["topResultsCount"], 5);
348
let second = query_body(
349
&QueryRequest::new("x", QueryScope::Messages).page(25),
350
"user",
351
"session",
352
"request",
353
);
354
assert_eq!(second["EntityRequests"][0]["from"], 25);
355
assert!(second["EntityRequests"][0].get("topResultsCount").is_none());
356
}
357
358
#[test]
359
fn find_in_chat_is_a_contextual_query() {
360
let request = QueryRequest::new("x", QueryScope::Messages).with_filters(vec![
361
MessageFilter::InChat {
362
thread_id: "19:abc@thread.v2".to_owned(),
363
},
364
]);
365
let body = query_body(&request, "user", "session", "request");
366
assert_eq!(
367
body["scenario"]["Dimensions"][0]["DimensionValue"],
368
"ContextualTypeahead"
369
);
370
}
371
}
@@ -0,0 +1,371 @@1
use serde_json::{Value, json};2
3
use super::kql::{MessageFilter, message_query_string};4
5
const APP_NAME: &str = "Microsoft Teams";6
const SCENARIO: &str = "powerbar";7
const TIME_ZONE: &str = "Europe/Berlin";8
const FORM_FACTOR: &str = "general.web.reactSearch";9
const TAB_PAGE_SIZE: usize = 25;10
const TAB_TOP_RESULTS: usize = 5;11
const MESSAGE_FIELDS: [&str; 8] = [12
"Extension_SkypeSpaces_ConversationPost_Extension_FromSkypeInternalId_String",13
"Extension_SkypeSpaces_ConversationPost_Extension_FileData_String",14
"Extension_SkypeSpaces_ConversationPost_Extension_ThreadType_String",15
"Extension_SkypeSpaces_ConversationPost_Extension_SkypeGroupId_String",16
"Extension_SkypeSpaces_ConversationPost_Extension_SenderTenantId_String",17
"Extension_SkypeSpaces_ConversationPost_Extension_ParentMessageId_String",18
"Extension_SkypeSpaces_ConversationPost_Extension_ImageSrc_String",19
"Extension_SkypeSpaces_ConversationPost_Extension_AmsReferences_StringArray",20
];21
const PEOPLE_FIELDS: [&str; 18] = [22
"Id",23
"MRI",24
"DisplayName",25
"EmailAddresses",26
"PeopleType",27
"PeopleSubtype",28
"Phones",29
"UserPrincipalName",30
"GivenName",31
"Surname",32
"CompanyName",33
"JobTitle",34
"ImAddress",35
"ExternalDirectoryObjectId",36
"Department",37
"OfficeLocation",38
"HomeTenantName",39
"MTOLabel",40
];41
42
#[derive(Debug, Clone, Copy, PartialEq, Eq)]43
pub enum QueryScope {44
All,45
Messages,46
People,47
Chats,48
Channels,49
Files,50
}51
52
#[derive(Debug, Clone, PartialEq, Eq)]53
pub struct QueryRequest {54
pub text: String,55
pub scope: QueryScope,56
pub filters: Vec<MessageFilter>,57
pub from: usize,58
pub size: usize,59
}60
61
impl QueryRequest {62
pub fn new(text: impl Into<String>, scope: QueryScope) -> Self {63
QueryRequest {64
text: text.into(),65
scope,66
filters: Vec::new(),67
from: 0,68
size: TAB_PAGE_SIZE,69
}70
}71
72
pub fn with_filters(mut self, filters: Vec<MessageFilter>) -> Self {73
self.filters = filters;74
self75
}76
77
pub fn page(mut self, from: usize) -> Self {78
self.from = from;79
self80
}81
82
fn is_contextual(&self) -> bool {83
self.filters84
.iter()85
.any(|filter| matches!(filter, MessageFilter::InChat { .. }))86
}87
88
fn query_type(&self) -> &'static str {89
if self.is_contextual() {90
return "ContextualTypeahead";91
}92
match self.scope {93
QueryScope::All => "All",94
QueryScope::Messages => "Messages",95
QueryScope::People => "People",96
QueryScope::Chats => "Chats",97
QueryScope::Channels => "Channels",98
QueryScope::Files => "Files",99
}100
}101
}102
103
pub(super) fn suggestion_body(text: &str, correlation_id: &str, logical_id: &str) -> Value {104
let query = json!({105
"QueryString": text,106
"DisplayQueryString": text,107
"NormalizedQueryString": text,108
});109
let entity = |entity_type: &str, size: usize| json!({"EntityType": entity_type, "Size": size, "Query": query});110
let mut people = entity("People", 5);111
people["Fields"] = json!(&PEOPLE_FIELDS[..15]);112
people["Filter"] = people_filter();113
people["Provenances"] = json!(["Mailbox", "Directory"]);114
people["From"] = json!(0);115
let mut channel = entity("Channel", 4);116
channel["Filter"] = json!({"Or": [117
{"Term": {"ChannelType": "Standard"}},118
{"Term": {"ChannelType": "Shared"}},119
]});120
json!({121
"EntityRequests": [122
people,123
entity("File", 3),124
entity("Chat", 5),125
entity("Team", 3),126
channel,127
entity("Text", 2),128
entity("Message", 11),129
entity("Event", 3),130
],131
"Scenario": {132
"Name": SCENARIO,133
"Dimensions": [{"DimensionName": "QueryType", "DimensionValue": "PeopleCentricSearch"}],134
},135
"Cvid": correlation_id,136
"LogicalId": logical_id,137
"AppName": APP_NAME,138
"dataSource": "personScoped",139
})140
}141
142
pub(super) fn query_body(143
request: &QueryRequest,144
user_id: &str,145
correlation_id: &str,146
logical_id: &str,147
) -> Value {148
let plain_query = json!({"queryString": request.text, "displayQueryString": request.text});149
let entity_requests: Vec<Value> = match request.scope {150
QueryScope::All => vec![151
message_entity(request, user_id, 3, 3),152
file_entity(&plain_query, 0, 3),153
people_entity(&plain_query, 0, 8),154
plain_entity("Chat", &plain_query, 0, 3),155
plain_entity("TeamsChannel", &plain_query, 0, 3),156
],157
QueryScope::Messages => vec![message_entity(158
request,159
user_id,160
request.size,161
if request.from == 0 {162
TAB_TOP_RESULTS163
} else {164
0165
},166
)],167
QueryScope::People => vec![people_entity(&plain_query, request.from, request.size)],168
QueryScope::Chats => vec![plain_entity(169
"Chat",170
&plain_query,171
request.from,172
request.size,173
)],174
QueryScope::Channels => vec![plain_entity(175
"TeamsChannel",176
&plain_query,177
request.from,178
request.size,179
)],180
QueryScope::Files => vec![file_entity(&plain_query, request.from, request.size)],181
};182
json!({183
"EntityRequests": entity_requests,184
"QueryAlterationOptions": {185
"EnableAlteration": true,186
"EnableSuggestion": true,187
"SupportedRecourseDisplayTypes": ["Suggestion"],188
},189
"scenario": {190
"Name": SCENARIO,191
"Dimensions": [192
{"DimensionName": "QueryType", "DimensionValue": request.query_type()},193
{"DimensionName": "FormFactor", "DimensionValue": FORM_FACTOR},194
],195
},196
"cvid": correlation_id,197
"logicalId": logical_id,198
"timezone": TIME_ZONE,199
})200
}201
202
fn message_entity(203
request: &QueryRequest,204
user_id: &str,205
size: usize,206
top_results_count: usize,207
) -> Value {208
let query_string = message_query_string(&request.text, &request.filters, user_id);209
let mut entity = json!({210
"entityType": "Message",211
"contentSources": ["Teams"],212
"propertySet": "Optimized",213
"fields": MESSAGE_FIELDS,214
"query": {"queryString": query_string, "displayQueryString": request.text},215
"from": request.from,216
"size": size,217
});218
if top_results_count > 0 {219
entity["topResultsCount"] = json!(top_results_count);220
}221
entity222
}223
224
fn people_entity(query: &Value, from: usize, size: usize) -> Value {225
json!({226
"entityType": "People",227
"contentSources": ["Exchange"],228
"Fields": PEOPLE_FIELDS,229
"Filter": people_filter(),230
"query": query,231
"from": from,232
"size": size,233
})234
}235
236
fn file_entity(query: &Value, from: usize, size: usize) -> Value {237
json!({238
"entityType": "File",239
"contentSources": ["OneDriveBusiness", "Exchange"],240
"query": query,241
"from": from,242
"size": size,243
})244
}245
246
fn plain_entity(entity_type: &str, query: &Value, from: usize, size: usize) -> Value {247
json!({248
"entityType": entity_type,249
"contentSources": ["Teams"],250
"query": query,251
"from": from,252
"size": size,253
})254
}255
256
fn people_filter() -> Value {257
let any_term = |field: &str, values: &[&str]| {258
let terms: Vec<Value> = values259
.iter()260
.map(|value| json!({"Term": {field: value}}))261
.collect();262
json!({"Or": terms})263
};264
json!({"And": [265
any_term("PeopleType", &["Person", "Other"]),266
any_term(267
"PeopleSubtype",268
&["OrganizationUser", "MTOUser", "PersonalContact", "Guest"],269
),270
any_term("Flags", &["NonHidden"]),271
]})272
}273
274
#[cfg(test)]275
mod tests {276
use super::*;277
278
#[test]279
fn suggestions_ask_for_every_domain_in_teams_order() {280
let body = suggestion_body("chr", "session", "request");281
let types: Vec<&str> = body["EntityRequests"]282
.as_array()283
.unwrap()284
.iter()285
.map(|entity| entity["EntityType"].as_str().unwrap())286
.collect();287
assert_eq!(288
types,289
[290
"People", "File", "Chat", "Team", "Channel", "Text", "Message", "Event"291
]292
);293
assert_eq!(body["Cvid"], "session");294
assert_eq!(body["LogicalId"], "request");295
assert_eq!(body["EntityRequests"][0]["Query"]["QueryString"], "chr");296
assert_eq!(297
body["EntityRequests"][0]["Provenances"],298
json!(["Mailbox", "Directory"])299
);300
}301
302
#[test]303
fn all_scope_uses_the_teams_section_sizes() {304
let request = QueryRequest::new("release", QueryScope::All);305
let body = query_body(&request, "user", "session", "request");306
let sizes: Vec<(String, u64)> = body["EntityRequests"]307
.as_array()308
.unwrap()309
.iter()310
.map(|entity| {311
(312
entity["entityType"].as_str().unwrap().to_owned(),313
entity["size"].as_u64().unwrap(),314
)315
})316
.collect();317
assert_eq!(318
sizes,319
[320
("Message".to_owned(), 3),321
("File".to_owned(), 3),322
("People".to_owned(), 8),323
("Chat".to_owned(), 3),324
("TeamsChannel".to_owned(), 3),325
]326
);327
assert_eq!(328
body["EntityRequests"][0]["query"]["queryString"],329
"NOT (isClientSoftDeleted:TRUE) AND release"330
);331
assert_eq!(332
body["EntityRequests"][0]["query"]["displayQueryString"],333
"release"334
);335
assert_eq!(body["scenario"]["Dimensions"][0]["DimensionValue"], "All");336
}337
338
#[test]339
fn messages_tab_pages_by_25_with_top_results_on_the_first_page_only() {340
let first = query_body(341
&QueryRequest::new("x", QueryScope::Messages),342
"user",343
"session",344
"request",345
);346
assert_eq!(first["EntityRequests"][0]["size"], 25);347
assert_eq!(first["EntityRequests"][0]["topResultsCount"], 5);348
let second = query_body(349
&QueryRequest::new("x", QueryScope::Messages).page(25),350
"user",351
"session",352
"request",353
);354
assert_eq!(second["EntityRequests"][0]["from"], 25);355
assert!(second["EntityRequests"][0].get("topResultsCount").is_none());356
}357
358
#[test]359
fn find_in_chat_is_a_contextual_query() {360
let request = QueryRequest::new("x", QueryScope::Messages).with_filters(vec![361
MessageFilter::InChat {362
thread_id: "19:abc@thread.v2".to_owned(),363
},364
]);365
let body = query_body(&request, "user", "session", "request");366
assert_eq!(367
body["scenario"]["Dimensions"][0]["DimensionValue"],368
"ContextualTypeahead"369
);370
}371
}@@ -0,0 +1,236 @@
1
use std::collections::VecDeque;
2
use std::sync::Mutex;
3
4
use serde_json::{Value, json};
5
use session::{ApiResponse, Method, Request};
6
7
use super::*;
8
9
const SUGGESTIONS: &str = include_str!("../../tests/fixtures/substrate_search/suggestions.json");
10
const QUERY: &str = include_str!("../../tests/fixtures/substrate_search/query.json");
11
const USER_ID: &str = "11111111-2222-3333-4444-555555555555";
12
13
#[derive(Default)]
14
struct Recorder {
15
requests: Mutex<Vec<Request>>,
16
answers: Mutex<VecDeque<ApiResponse>>,
17
}
18
19
impl Recorder {
20
fn answering(status: u16, body: Value) -> Self {
21
let recorder = Recorder::default();
22
recorder.answers.lock().unwrap().push_back(ApiResponse {
23
status,
24
body,
25
retry_after: None,
26
});
27
recorder
28
}
29
30
fn only_request(&self) -> Request {
31
let requests = self.requests.lock().unwrap();
32
assert_eq!(requests.len(), 1);
33
requests[0].clone()
34
}
35
}
36
37
impl CsaTransport for &Recorder {
38
async fn send(&self, request: Request) -> Result<ApiResponse> {
39
self.requests.lock().unwrap().push(request);
40
Ok(self
41
.answers
42
.lock()
43
.unwrap()
44
.pop_front()
45
.expect("no answer left"))
46
}
47
}
48
49
fn client(recorder: &Recorder) -> SubstrateSearch<&Recorder> {
50
let identity = SearchIdentity {
51
user_id: USER_ID.to_owned(),
52
tenant_id: "tenant".to_owned(),
53
};
54
SubstrateSearch::with_transport(recorder, identity, "https://substrate.test/")
55
}
56
57
fn header<'a>(request: &'a Request, name: &str) -> Option<&'a str> {
58
request
59
.headers
60
.iter()
61
.find(|(key, _)| key.eq_ignore_ascii_case(name))
62
.map(|(_, value)| value.as_str())
63
}
64
65
fn fixture(text: &str) -> Value {
66
serde_json::from_str(text).unwrap()
67
}
68
69
#[tokio::test]
70
async fn typeahead_posts_the_entity_requests_with_teams_headers() {
71
let recorder = Recorder::answering(200, fixture(SUGGESTIONS));
72
let search_session = SearchSession::new();
73
client(&recorder)
74
.suggestions(&search_session, "eri")
75
.await
76
.unwrap();
77
let request = recorder.only_request();
78
assert_eq!(request.method, Method::Post);
79
assert_eq!(
80
request.url,
81
"https://substrate.test/search/api/v1/suggestions?scenario=powerbar&setflight=EnableMessageImageSearch%2CEnableTeamsChannelDomainPowerbar"
82
);
83
let body = request.body.clone().unwrap();
84
assert_eq!(body["Cvid"], search_session.correlation_id());
85
assert_eq!(body["EntityRequests"][0]["Query"]["QueryString"], "eri");
86
assert_eq!(header(&request, "x-client-version"), Some("T2.1"));
87
assert_eq!(header(&request, "X-ClientType"), Some("MicrosoftTeams"));
88
assert_eq!(
89
header(&request, "x-anchormailbox"),
90
Some(format!("Oid:{USER_ID}@tenant").as_str())
91
);
92
assert_eq!(
93
header(&request, "x-routingparameter-sessionkey"),
94
Some(format!("OID:{USER_ID}@tenant").as_str())
95
);
96
assert!(header(&request, "x-client-flights").is_some());
97
}
98
99
#[tokio::test]
100
async fn empty_text_asks_for_the_zero_query_state() {
101
let recorder = Recorder::answering(200, json!({"Groups": []}));
102
let search_session = SearchSession::new();
103
client(&recorder)
104
.suggestions(&search_session, " ")
105
.await
106
.unwrap();
107
let request = recorder.only_request();
108
assert_eq!(request.method, Method::Get);
109
assert!(request.url.starts_with(&format!(
110
"https://substrate.test/search/api/v1/suggestions?scenario=powerbar&query=&cvid={}&logicalId=",
111
search_session.correlation_id()
112
)));
113
}
114
115
#[tokio::test]
116
async fn query_posts_to_the_search_service_with_version_one() {
117
let recorder = Recorder::answering(200, fixture(QUERY));
118
let results = client(&recorder)
119
.query(
120
&SearchSession::new(),
121
&QueryRequest::new("erika", QueryScope::Messages)
122
.with_filters(vec![MessageFilter::MentionsMe]),
123
)
124
.await
125
.unwrap();
126
let request = recorder.only_request();
127
assert_eq!(
128
request.url,
129
"https://substrate.test/searchservice/api/v2/query"
130
);
131
assert_eq!(header(&request, "x-client-version"), Some("1"));
132
assert_eq!(
133
request.body.clone().unwrap()["EntityRequests"][0]["query"]["queryString"],
134
"NOT (isClientSoftDeleted:TRUE) AND mentions:11111111222233334444555555555555 AND erika"
135
);
136
assert_eq!(results.messages.total, 22770);
137
}
138
139
#[tokio::test]
140
async fn init_warms_up_with_the_session_cvid() {
141
let recorder = Recorder::answering(200, json!({}));
142
let search_session = SearchSession::new();
143
client(&recorder).init(&search_session).await.unwrap();
144
assert_eq!(
145
recorder.only_request().url,
146
format!(
147
"https://substrate.test/search/api/v2/init?cvid={}&scenario=powerbar",
148
search_session.correlation_id()
149
)
150
);
151
}
152
153
#[tokio::test]
154
async fn failed_answer_is_an_error() {
155
let recorder = Recorder::answering(401, json!({"error": "denied"}));
156
let outcome = client(&recorder)
157
.suggestions(&SearchSession::new(), "x")
158
.await;
159
assert!(outcome.is_err());
160
}
161
162
#[test]
163
fn suggestions_fixture_parses_every_group() {
164
let suggestions = parse_suggestions(&fixture(SUGGESTIONS));
165
let person = &suggestions.people[0];
166
assert_eq!(person.display_name, "Erika Mustermann");
167
assert_eq!(person.user_id.as_deref(), Some(USER_ID));
168
assert_eq!(person.job_title.as_deref(), Some("Engineer"));
169
assert_eq!(person.email_addresses, ["erika.mustermann@contoso.example"]);
170
171
let chat = &suggestions.chats[0];
172
assert_eq!(chat.thread_id, "19:group01@thread.v2");
173
assert_eq!(chat.name, None);
174
assert_eq!(chat.total_members, 3);
175
assert_eq!(chat.members.len(), 2);
176
assert_eq!(chat.matching_members[0].display_name, "Erika Mustermann");
177
178
assert_eq!(
179
suggestions.channels[0].team_name.as_deref(),
180
Some("Platform")
181
);
182
assert_eq!(suggestions.teams[0].name, "Platform");
183
184
let read = &suggestions.messages[0];
185
assert_eq!(read.conversation_id, "19:group01@thread.v2");
186
assert_eq!(read.message_id, "1760600081000");
187
assert_eq!(read.sender_name.as_deref(), Some("Max Muster"));
188
assert_eq!(read.sender_mri.as_deref(), Some("8:orgid:aaaa"));
189
assert_eq!(read.is_read, Some(true));
190
assert_eq!(suggestions.messages[1].is_read, Some(false));
191
192
assert_eq!(suggestions.files[0].name, "Roadmap.docx");
193
assert_eq!(suggestions.files[0].size, Some(2048));
194
assert_eq!(suggestions.events[0].subject, "Release sync");
195
assert_eq!(suggestions.texts[0].kind.as_deref(), Some("PeopleAsText"));
196
assert_eq!(suggestions.best_matches.len(), 2);
197
assert_eq!(suggestions.best_matches[0].group, "People");
198
}
199
200
#[test]
201
fn query_fixture_maps_channel_replies_to_their_root() {
202
let results = parse_query_results(&fixture(QUERY));
203
assert_eq!(results.search_terms, ["erika"]);
204
assert_eq!(
205
results.people.items[0].office_location.as_deref(),
206
Some("Building 1")
207
);
208
assert!(results.chats.more_available);
209
assert_eq!(results.chats.items[0].reference_id.as_deref(), Some("q.2"));
210
211
let message = &results.messages.items[0];
212
assert_eq!(message.conversation_id, "19:channel01@thread.tacv2");
213
assert_eq!(message.message_id, "1760600000000");
214
assert_eq!(message.root_message_id.as_deref(), Some("1760500000000"));
215
assert_eq!(message.thread_type.as_deref(), Some("topic"));
216
assert_eq!(message.sender_mri.as_deref(), Some("8:orgid:aaaa"));
217
assert_eq!(message.sender_name.as_deref(), Some("Max Muster"));
218
assert!(message.is_mentioned);
219
assert!(message.has_attachments);
220
assert_eq!(message.is_read, None);
221
let highlighted = split_highlights(message.highlighted_summary.as_deref().unwrap());
222
assert_eq!(&highlighted.text[highlighted.hits[0].clone()], "Erika");
223
224
assert_eq!(results.files.total, 393);
225
assert_eq!(results.files.items[0].name, "Notes");
226
assert_eq!(results.files.items[0].size, Some(12));
227
}
228
229
#[test]
230
fn unknown_shape_parses_to_empty_results() {
231
assert_eq!(parse_suggestions(&json!([])), Suggestions::default());
232
assert_eq!(
233
parse_query_results(&json!({"EntitySets": 3})),
234
QueryResults::default()
235
);
236
}
@@ -0,0 +1,236 @@1
use std::collections::VecDeque;2
use std::sync::Mutex;3
4
use serde_json::{Value, json};5
use session::{ApiResponse, Method, Request};6
7
use super::*;8
9
const SUGGESTIONS: &str = include_str!("../../tests/fixtures/substrate_search/suggestions.json");10
const QUERY: &str = include_str!("../../tests/fixtures/substrate_search/query.json");11
const USER_ID: &str = "11111111-2222-3333-4444-555555555555";12
13
#[derive(Default)]14
struct Recorder {15
requests: Mutex<Vec<Request>>,16
answers: Mutex<VecDeque<ApiResponse>>,17
}18
19
impl Recorder {20
fn answering(status: u16, body: Value) -> Self {21
let recorder = Recorder::default();22
recorder.answers.lock().unwrap().push_back(ApiResponse {23
status,24
body,25
retry_after: None,26
});27
recorder28
}29
30
fn only_request(&self) -> Request {31
let requests = self.requests.lock().unwrap();32
assert_eq!(requests.len(), 1);33
requests[0].clone()34
}35
}36
37
impl CsaTransport for &Recorder {38
async fn send(&self, request: Request) -> Result<ApiResponse> {39
self.requests.lock().unwrap().push(request);40
Ok(self41
.answers42
.lock()43
.unwrap()44
.pop_front()45
.expect("no answer left"))46
}47
}48
49
fn client(recorder: &Recorder) -> SubstrateSearch<&Recorder> {50
let identity = SearchIdentity {51
user_id: USER_ID.to_owned(),52
tenant_id: "tenant".to_owned(),53
};54
SubstrateSearch::with_transport(recorder, identity, "https://substrate.test/")55
}56
57
fn header<'a>(request: &'a Request, name: &str) -> Option<&'a str> {58
request59
.headers60
.iter()61
.find(|(key, _)| key.eq_ignore_ascii_case(name))62
.map(|(_, value)| value.as_str())63
}64
65
fn fixture(text: &str) -> Value {66
serde_json::from_str(text).unwrap()67
}68
69
#[tokio::test]70
async fn typeahead_posts_the_entity_requests_with_teams_headers() {71
let recorder = Recorder::answering(200, fixture(SUGGESTIONS));72
let search_session = SearchSession::new();73
client(&recorder)74
.suggestions(&search_session, "eri")75
.await76
.unwrap();77
let request = recorder.only_request();78
assert_eq!(request.method, Method::Post);79
assert_eq!(80
request.url,81
"https://substrate.test/search/api/v1/suggestions?scenario=powerbar&setflight=EnableMessageImageSearch%2CEnableTeamsChannelDomainPowerbar"82
);83
let body = request.body.clone().unwrap();84
assert_eq!(body["Cvid"], search_session.correlation_id());85
assert_eq!(body["EntityRequests"][0]["Query"]["QueryString"], "eri");86
assert_eq!(header(&request, "x-client-version"), Some("T2.1"));87
assert_eq!(header(&request, "X-ClientType"), Some("MicrosoftTeams"));88
assert_eq!(89
header(&request, "x-anchormailbox"),90
Some(format!("Oid:{USER_ID}@tenant").as_str())91
);92
assert_eq!(93
header(&request, "x-routingparameter-sessionkey"),94
Some(format!("OID:{USER_ID}@tenant").as_str())95
);96
assert!(header(&request, "x-client-flights").is_some());97
}98
99
#[tokio::test]100
async fn empty_text_asks_for_the_zero_query_state() {101
let recorder = Recorder::answering(200, json!({"Groups": []}));102
let search_session = SearchSession::new();103
client(&recorder)104
.suggestions(&search_session, " ")105
.await106
.unwrap();107
let request = recorder.only_request();108
assert_eq!(request.method, Method::Get);109
assert!(request.url.starts_with(&format!(110
"https://substrate.test/search/api/v1/suggestions?scenario=powerbar&query=&cvid={}&logicalId=",111
search_session.correlation_id()112
)));113
}114
115
#[tokio::test]116
async fn query_posts_to_the_search_service_with_version_one() {117
let recorder = Recorder::answering(200, fixture(QUERY));118
let results = client(&recorder)119
.query(120
&SearchSession::new(),121
&QueryRequest::new("erika", QueryScope::Messages)122
.with_filters(vec![MessageFilter::MentionsMe]),123
)124
.await125
.unwrap();126
let request = recorder.only_request();127
assert_eq!(128
request.url,129
"https://substrate.test/searchservice/api/v2/query"130
);131
assert_eq!(header(&request, "x-client-version"), Some("1"));132
assert_eq!(133
request.body.clone().unwrap()["EntityRequests"][0]["query"]["queryString"],134
"NOT (isClientSoftDeleted:TRUE) AND mentions:11111111222233334444555555555555 AND erika"135
);136
assert_eq!(results.messages.total, 22770);137
}138
139
#[tokio::test]140
async fn init_warms_up_with_the_session_cvid() {141
let recorder = Recorder::answering(200, json!({}));142
let search_session = SearchSession::new();143
client(&recorder).init(&search_session).await.unwrap();144
assert_eq!(145
recorder.only_request().url,146
format!(147
"https://substrate.test/search/api/v2/init?cvid={}&scenario=powerbar",148
search_session.correlation_id()149
)150
);151
}152
153
#[tokio::test]154
async fn failed_answer_is_an_error() {155
let recorder = Recorder::answering(401, json!({"error": "denied"}));156
let outcome = client(&recorder)157
.suggestions(&SearchSession::new(), "x")158
.await;159
assert!(outcome.is_err());160
}161
162
#[test]163
fn suggestions_fixture_parses_every_group() {164
let suggestions = parse_suggestions(&fixture(SUGGESTIONS));165
let person = &suggestions.people[0];166
assert_eq!(person.display_name, "Erika Mustermann");167
assert_eq!(person.user_id.as_deref(), Some(USER_ID));168
assert_eq!(person.job_title.as_deref(), Some("Engineer"));169
assert_eq!(person.email_addresses, ["erika.mustermann@contoso.example"]);170
171
let chat = &suggestions.chats[0];172
assert_eq!(chat.thread_id, "19:group01@thread.v2");173
assert_eq!(chat.name, None);174
assert_eq!(chat.total_members, 3);175
assert_eq!(chat.members.len(), 2);176
assert_eq!(chat.matching_members[0].display_name, "Erika Mustermann");177
178
assert_eq!(179
suggestions.channels[0].team_name.as_deref(),180
Some("Platform")181
);182
assert_eq!(suggestions.teams[0].name, "Platform");183
184
let read = &suggestions.messages[0];185
assert_eq!(read.conversation_id, "19:group01@thread.v2");186
assert_eq!(read.message_id, "1760600081000");187
assert_eq!(read.sender_name.as_deref(), Some("Max Muster"));188
assert_eq!(read.sender_mri.as_deref(), Some("8:orgid:aaaa"));189
assert_eq!(read.is_read, Some(true));190
assert_eq!(suggestions.messages[1].is_read, Some(false));191
192
assert_eq!(suggestions.files[0].name, "Roadmap.docx");193
assert_eq!(suggestions.files[0].size, Some(2048));194
assert_eq!(suggestions.events[0].subject, "Release sync");195
assert_eq!(suggestions.texts[0].kind.as_deref(), Some("PeopleAsText"));196
assert_eq!(suggestions.best_matches.len(), 2);197
assert_eq!(suggestions.best_matches[0].group, "People");198
}199
200
#[test]201
fn query_fixture_maps_channel_replies_to_their_root() {202
let results = parse_query_results(&fixture(QUERY));203
assert_eq!(results.search_terms, ["erika"]);204
assert_eq!(205
results.people.items[0].office_location.as_deref(),206
Some("Building 1")207
);208
assert!(results.chats.more_available);209
assert_eq!(results.chats.items[0].reference_id.as_deref(), Some("q.2"));210
211
let message = &results.messages.items[0];212
assert_eq!(message.conversation_id, "19:channel01@thread.tacv2");213
assert_eq!(message.message_id, "1760600000000");214
assert_eq!(message.root_message_id.as_deref(), Some("1760500000000"));215
assert_eq!(message.thread_type.as_deref(), Some("topic"));216
assert_eq!(message.sender_mri.as_deref(), Some("8:orgid:aaaa"));217
assert_eq!(message.sender_name.as_deref(), Some("Max Muster"));218
assert!(message.is_mentioned);219
assert!(message.has_attachments);220
assert_eq!(message.is_read, None);221
let highlighted = split_highlights(message.highlighted_summary.as_deref().unwrap());222
assert_eq!(&highlighted.text[highlighted.hits[0].clone()], "Erika");223
224
assert_eq!(results.files.total, 393);225
assert_eq!(results.files.items[0].name, "Notes");226
assert_eq!(results.files.items[0].size, Some(12));227
}228
229
#[test]230
fn unknown_shape_parses_to_empty_results() {231
assert_eq!(parse_suggestions(&json!([])), Suggestions::default());232
assert_eq!(233
parse_query_results(&json!({"EntitySets": 3})),234
QueryResults::default()235
);236
}@@ -0,0 +1,27 @@
1
{
2
"ApiVersion": "v2",
3
"EntitySets": [
4
{"EntityType": "People", "ResultSets": [{"Total": 1, "MoreResultsAvailable": false, "Results": [
5
{"Id": "r1", "ReferenceId": "q.1", "Rank": 1, "Type": "People", "Source": {
6
"DisplayName": "Erika Mustermann", "EmailAddresses": ["erika.mustermann@contoso.example"], "JobTitle": "Engineer",
7
"OfficeLocation": "Building 1", "MRI": "8:orgid:11111111-2222-3333-4444-555555555555",
8
"ExternalDirectoryObjectId": "11111111-2222-3333-4444-555555555555", "PeopleSubtype": "OrganizationUser"}}]}]},
9
{"EntityType": "Chat", "ResultSets": [{"Total": 3, "MoreResultsAvailable": true, "Results": [
10
{"ReferenceId": "q.2", "Source": {"ThreadId": "19:group01@thread.v2", "ThreadType": "Chat", "Name": "Release crew",
11
"TotalChatMembersCount": 3, "LastMessageTime": "2026-10-16T07:34:41Z", "ChatMembers": [], "MatchingMembers": []}}]}]},
12
{"EntityType": "Message", "ResultSets": [{"Total": 22770, "MoreResultsAvailable": true, "Results": [
13
{"ReferenceId": "q.3", "HitHighlightedSummary": "Ask <c0>Erika</c0> about the release", "ContentSource": "Teams", "Type": "Message", "Source": {
14
"ClientThreadId": "19:channel01@thread.tacv2", "ClientConversationId": "19:channel01@thread.tacv2;messageid=1760500000000",
15
"InternetMessageId": "1760600000000", "DateTimeSent": "2026-10-16T05:00:00Z", "Preview": "Ask Erika about the release",
16
"HasAttachments": true, "MentionsPreview": {"IsMentioned": true},
17
"Sender": {"EmailAddress": {"Name": "Max Muster", "Address": "max.muster@contoso.example"}},
18
"Extensions": {"SkypeSpaces_ConversationPost_Extension_FromSkypeInternalId": "8:orgid:aaaa",
19
"SkypeSpaces_ConversationPost_Extension_ParentMessageId": "1760500000000",
20
"SkypeSpaces_ConversationPost_Extension_ThreadType": "topic"}}}]}]},
21
{"EntityType": "File", "ResultSets": [{"Total": 393, "MoreResultsAvailable": true, "Results": [
22
{"ReferenceId": "q.4", "Source": {"Filename": "Notes", "FileExtension": "txt", "Size": 12, "Path": "https://contoso.example/Notes.txt",
23
"Author": "Max Muster", "LastModifiedTime": "2026-10-01T08:00:00Z"}}]}]}
24
],
25
"SearchTerms": ["erika"],
26
"Instrumentation": {"TraceId": "trace"}
27
}
@@ -0,0 +1,27 @@1
{2
"ApiVersion": "v2",3
"EntitySets": [4
{"EntityType": "People", "ResultSets": [{"Total": 1, "MoreResultsAvailable": false, "Results": [5
{"Id": "r1", "ReferenceId": "q.1", "Rank": 1, "Type": "People", "Source": {6
"DisplayName": "Erika Mustermann", "EmailAddresses": ["erika.mustermann@contoso.example"], "JobTitle": "Engineer",7
"OfficeLocation": "Building 1", "MRI": "8:orgid:11111111-2222-3333-4444-555555555555",8
"ExternalDirectoryObjectId": "11111111-2222-3333-4444-555555555555", "PeopleSubtype": "OrganizationUser"}}]}]},9
{"EntityType": "Chat", "ResultSets": [{"Total": 3, "MoreResultsAvailable": true, "Results": [10
{"ReferenceId": "q.2", "Source": {"ThreadId": "19:group01@thread.v2", "ThreadType": "Chat", "Name": "Release crew",11
"TotalChatMembersCount": 3, "LastMessageTime": "2026-10-16T07:34:41Z", "ChatMembers": [], "MatchingMembers": []}}]}]},12
{"EntityType": "Message", "ResultSets": [{"Total": 22770, "MoreResultsAvailable": true, "Results": [13
{"ReferenceId": "q.3", "HitHighlightedSummary": "Ask <c0>Erika</c0> about the release", "ContentSource": "Teams", "Type": "Message", "Source": {14
"ClientThreadId": "19:channel01@thread.tacv2", "ClientConversationId": "19:channel01@thread.tacv2;messageid=1760500000000",15
"InternetMessageId": "1760600000000", "DateTimeSent": "2026-10-16T05:00:00Z", "Preview": "Ask Erika about the release",16
"HasAttachments": true, "MentionsPreview": {"IsMentioned": true},17
"Sender": {"EmailAddress": {"Name": "Max Muster", "Address": "max.muster@contoso.example"}},18
"Extensions": {"SkypeSpaces_ConversationPost_Extension_FromSkypeInternalId": "8:orgid:aaaa",19
"SkypeSpaces_ConversationPost_Extension_ParentMessageId": "1760500000000",20
"SkypeSpaces_ConversationPost_Extension_ThreadType": "topic"}}}]}]},21
{"EntityType": "File", "ResultSets": [{"Total": 393, "MoreResultsAvailable": true, "Results": [22
{"ReferenceId": "q.4", "Source": {"Filename": "Notes", "FileExtension": "txt", "Size": 12, "Path": "https://contoso.example/Notes.txt",23
"Author": "Max Muster", "LastModifiedTime": "2026-10-01T08:00:00Z"}}]}]}24
],25
"SearchTerms": ["erika"],26
"Instrumentation": {"TraceId": "trace"}27
}@@ -0,0 +1,53 @@
1
{
2
"Groups": [
3
{"Type": "People", "Suggestions": [
4
{"Id": "p1", "ReferenceId": "ref.4000.43", "DisplayName": "Erika Mustermann", "GivenName": "Erika", "Surname": "Mustermann",
5
"EmailAddresses": ["erika.mustermann@contoso.example"], "UserPrincipalName": "erika.mustermann@contoso.example",
6
"JobTitle": "Engineer", "Department": "R&D", "CompanyName": "Contoso", "MRI": "8:orgid:11111111-2222-3333-4444-555555555555",
7
"ExternalDirectoryObjectId": "11111111-2222-3333-4444-555555555555", "PeopleType": "Person", "PeopleSubtype": "OrganizationUser",
8
"PropertyHits": ["DisplayName"], "QueryText": "eri", "Text": "Erika Mustermann"}
9
]},
10
{"Type": "Chat", "Suggestions": [
11
{"ReferenceId": "ref.4000.47", "EntityType": "Chat", "ThreadId": "19:group01@thread.v2", "ThreadType": "Chat", "Name": "",
12
"LastMessageTime": "2026-10-16T07:34:41Z", "TotalChatMembersCount": 3,
13
"ChatMembers": [{"DisplayName": "Erika Mustermann", "MRI": "8:orgid:11111111-2222-3333-4444-555555555555"}, {"DisplayName": "Max Muster", "MRI": "8:orgid:aaaa"}],
14
"MatchingMembers": [{"DisplayName": "Erika Mustermann", "GivenName": "Erika", "Surname": "Mustermann", "MRI": "8:orgid:11111111-2222-3333-4444-555555555555"}],
15
"PropertyHits": ["Members"], "Text": ""}
16
]},
17
{"Type": "Channel", "Suggestions": [
18
{"ReferenceId": "ref.4000.51", "EntityType": "Channel", "ThreadId": "19:channel01@thread.tacv2", "Name": "General", "TeamName": "Platform",
19
"GroupId": "team-group-id", "ChannelType": "Standard", "PropertyHits": [], "Text": "General"}
20
]},
21
{"Type": "Team", "Suggestions": [
22
{"ReferenceId": "ref.4000.52", "EntityType": "Team", "ThreadId": "19:team01@thread.tacv2", "GroupId": "team-group-id", "Name": "Platform", "Text": "Platform"}
23
]},
24
{"Type": "Message", "Suggestions": [
25
{"ReferenceId": "ref.4000.60", "Id": "opaque", "ClientThreadId": "19:group01@thread.v2",
26
"ClientConversationId": "19:group01@thread.v2;messageid=1760600081000", "InternetMessageId": "1760600081000",
27
"ParentMessageId": "1760600081000", "DateTimeSent": "2026-10-16T07:34:41Z", "Preview": "Can Erika review the release?",
28
"From": {"EmailAddress": {"Name": "Max Muster", "Address": "max.muster@contoso.example"}, "MRI": "8:orgid:aaaa"},
29
"ThreadType": "Chat", "ThreadSubType": "NamedGroupChat", "Metadata": ["IsRead"], "RecipientsCount": 3, "ToPreview": [{"DisplayName": "Erika Mustermann"}]},
30
{"ReferenceId": "ref.4000.61", "Id": "opaque2", "ClientThreadId": "19:group01@thread.v2",
31
"ClientConversationId": "19:group01@thread.v2;messageid=1760600090000", "InternetMessageId": "1760600090000",
32
"DateTimeSent": "2026-10-16T07:40:00Z", "Preview": "unread one",
33
"From": {"EmailAddress": {"Name": "Max Muster", "Address": "max.muster@contoso.example"}, "MRI": "8:orgid:aaaa"},
34
"ThreadType": "Chat", "ThreadSubType": "NamedGroupChat", "Metadata": []}
35
]},
36
{"Type": "File", "Suggestions": [
37
{"ReferenceId": "ref.4000.70", "FileName": "Roadmap.docx", "FileExtension": "docx", "FileSize": 2048,
38
"AccessUrl": "https://contoso.example/Roadmap.docx", "Author": "Erika Mustermann", "DateModified": "2026-10-10T10:00:00Z",
39
"SharedDateTime": "2026-10-11T10:00:00Z", "From": {"EmailAddress": {"Name": "Erika Mustermann"}}}
40
]},
41
{"Type": "Event", "Suggestions": [
42
{"ReferenceId": "ref.4000.80", "Subject": "Release sync", "OrganizerName": "Erika Mustermann", "Start": "2026-10-20T09:00:00Z",
43
"End": "2026-10-20T09:30:00Z", "Location": "Microsoft Teams Meeting", "SkypeTeamsMeetingUrl": "https://teams.example/l/meetup-join/x",
44
"WebLink": "https://outlook.example/event", "Attendees": [], "ResponseStatus": {"Response": "Accepted", "Time": "2026-10-01T00:00:00Z"}}
45
]},
46
{"Type": "Text", "Suggestions": [
47
{"ReferenceId": "ref.4000.90", "Text": "Messages from Erika Mustermann", "QueryText": "eri", "TextSuggestionType": "PeopleAsText"}
48
]},
49
{"Type": "CatalogApp", "Suggestions": [{"Title": "ignored"}]}
50
],
51
"LayoutHints": {"BestMatchSuggestions": [{"Group": "People", "ReferenceId": "ref.4000.43"}, {"Group": "Chat", "ReferenceId": "ref.4000.47"}]},
52
"Instrumentation": {"TraceId": "trace"}
53
}
@@ -0,0 +1,53 @@1
{2
"Groups": [3
{"Type": "People", "Suggestions": [4
{"Id": "p1", "ReferenceId": "ref.4000.43", "DisplayName": "Erika Mustermann", "GivenName": "Erika", "Surname": "Mustermann",5
"EmailAddresses": ["erika.mustermann@contoso.example"], "UserPrincipalName": "erika.mustermann@contoso.example",6
"JobTitle": "Engineer", "Department": "R&D", "CompanyName": "Contoso", "MRI": "8:orgid:11111111-2222-3333-4444-555555555555",7
"ExternalDirectoryObjectId": "11111111-2222-3333-4444-555555555555", "PeopleType": "Person", "PeopleSubtype": "OrganizationUser",8
"PropertyHits": ["DisplayName"], "QueryText": "eri", "Text": "Erika Mustermann"}9
]},10
{"Type": "Chat", "Suggestions": [11
{"ReferenceId": "ref.4000.47", "EntityType": "Chat", "ThreadId": "19:group01@thread.v2", "ThreadType": "Chat", "Name": "",12
"LastMessageTime": "2026-10-16T07:34:41Z", "TotalChatMembersCount": 3,13
"ChatMembers": [{"DisplayName": "Erika Mustermann", "MRI": "8:orgid:11111111-2222-3333-4444-555555555555"}, {"DisplayName": "Max Muster", "MRI": "8:orgid:aaaa"}],14
"MatchingMembers": [{"DisplayName": "Erika Mustermann", "GivenName": "Erika", "Surname": "Mustermann", "MRI": "8:orgid:11111111-2222-3333-4444-555555555555"}],15
"PropertyHits": ["Members"], "Text": ""}16
]},17
{"Type": "Channel", "Suggestions": [18
{"ReferenceId": "ref.4000.51", "EntityType": "Channel", "ThreadId": "19:channel01@thread.tacv2", "Name": "General", "TeamName": "Platform",19
"GroupId": "team-group-id", "ChannelType": "Standard", "PropertyHits": [], "Text": "General"}20
]},21
{"Type": "Team", "Suggestions": [22
{"ReferenceId": "ref.4000.52", "EntityType": "Team", "ThreadId": "19:team01@thread.tacv2", "GroupId": "team-group-id", "Name": "Platform", "Text": "Platform"}23
]},24
{"Type": "Message", "Suggestions": [25
{"ReferenceId": "ref.4000.60", "Id": "opaque", "ClientThreadId": "19:group01@thread.v2",26
"ClientConversationId": "19:group01@thread.v2;messageid=1760600081000", "InternetMessageId": "1760600081000",27
"ParentMessageId": "1760600081000", "DateTimeSent": "2026-10-16T07:34:41Z", "Preview": "Can Erika review the release?",28
"From": {"EmailAddress": {"Name": "Max Muster", "Address": "max.muster@contoso.example"}, "MRI": "8:orgid:aaaa"},29
"ThreadType": "Chat", "ThreadSubType": "NamedGroupChat", "Metadata": ["IsRead"], "RecipientsCount": 3, "ToPreview": [{"DisplayName": "Erika Mustermann"}]},30
{"ReferenceId": "ref.4000.61", "Id": "opaque2", "ClientThreadId": "19:group01@thread.v2",31
"ClientConversationId": "19:group01@thread.v2;messageid=1760600090000", "InternetMessageId": "1760600090000",32
"DateTimeSent": "2026-10-16T07:40:00Z", "Preview": "unread one",33
"From": {"EmailAddress": {"Name": "Max Muster", "Address": "max.muster@contoso.example"}, "MRI": "8:orgid:aaaa"},34
"ThreadType": "Chat", "ThreadSubType": "NamedGroupChat", "Metadata": []}35
]},36
{"Type": "File", "Suggestions": [37
{"ReferenceId": "ref.4000.70", "FileName": "Roadmap.docx", "FileExtension": "docx", "FileSize": 2048,38
"AccessUrl": "https://contoso.example/Roadmap.docx", "Author": "Erika Mustermann", "DateModified": "2026-10-10T10:00:00Z",39
"SharedDateTime": "2026-10-11T10:00:00Z", "From": {"EmailAddress": {"Name": "Erika Mustermann"}}}40
]},41
{"Type": "Event", "Suggestions": [42
{"ReferenceId": "ref.4000.80", "Subject": "Release sync", "OrganizerName": "Erika Mustermann", "Start": "2026-10-20T09:00:00Z",43
"End": "2026-10-20T09:30:00Z", "Location": "Microsoft Teams Meeting", "SkypeTeamsMeetingUrl": "https://teams.example/l/meetup-join/x",44
"WebLink": "https://outlook.example/event", "Attendees": [], "ResponseStatus": {"Response": "Accepted", "Time": "2026-10-01T00:00:00Z"}}45
]},46
{"Type": "Text", "Suggestions": [47
{"ReferenceId": "ref.4000.90", "Text": "Messages from Erika Mustermann", "QueryText": "eri", "TextSuggestionType": "PeopleAsText"}48
]},49
{"Type": "CatalogApp", "Suggestions": [{"Title": "ignored"}]}50
],51
"LayoutHints": {"BestMatchSuggestions": [{"Group": "People", "ReferenceId": "ref.4000.43"}, {"Group": "Chat", "ReferenceId": "ref.4000.47"}]},52
"Instrumentation": {"TraceId": "trace"}53
}@@ -196,15 +196,23 @@ impl<R: Remote> SyncEngine<R> {
196
196
}
197
197
198
198
pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> {
199
let mut delta = match self.resolve(conversation_id).await? {
200
Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,
201
Conversation::Channel { team_id } => {
202
self.fetch_newer_channel(&team_id, conversation_id).await?
199
let heal = async {
200
if self.heal_forwards(conversation_id).await {
201
self.announce(conversation_id, true);
203
202
}
204
203
};
204
let fetch = async {
205
Ok::<_, Error>(match self.resolve(conversation_id).await? {
206
Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,
207
Conversation::Channel { team_id } => {
208
self.fetch_newer_channel(&team_id, conversation_id).await?
209
}
210
})
211
};
212
let (fetched, ()) = tokio::join!(fetch, heal);
213
let mut delta = fetched?;
205
214
let cache_changed = self.attach_delta_links(conversation_id, &mut delta).await
206
| self.backfill_links(conversation_id).await
207
| self.heal_forwards(conversation_id).await;
215
| self.backfill_links(conversation_id).await;
208
216
self.announce(conversation_id, !delta.is_empty() || cache_changed);
209
217
Ok(delta)
210
218
}
@@ -339,6 +347,24 @@ impl<R: Remote> SyncEngine<R> {
339
347
Ok(tenant.clone())
340
348
}
341
349
350
pub(crate) async fn my_tenant_id_from_any_chat(&self) -> Result<String> {
351
if let Some(tenant) = self.my_tenant_id.get() {
352
return Ok(tenant.clone());
353
}
354
if let Some(cached) = self.store.meta(META_TENANT_ID)? {
355
return Ok(cached);
356
}
357
let any_chat_id = self
358
.store
359
.sidebar()?
360
.chats
361
.into_iter()
362
.next()
363
.map(|chat| chat.id)
364
.ok_or(Error::Unsupported("a tenant id without a known chat"))?;
365
self.my_tenant_id(&any_chat_id).await
366
}
367
342
368
pub(crate) async fn resolve(&self, conversation_id: &str) -> Result<Conversation> {
343
369
match self.resolve_stored(conversation_id) {
344
370
Err(Error::UnknownConversation(_)) => self.fetch_unknown_chat(conversation_id).await,
@@ -196,15 +196,23 @@ impl<R: Remote> SyncEngine<R> {196
}196
}197
197
198
pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> {198
pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> {199
let mut delta = match self.resolve(conversation_id).await? {199
let heal = async {200
Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,200
if self.heal_forwards(conversation_id).await {201
Conversation::Channel { team_id } => {201
self.announce(conversation_id, true);202
self.fetch_newer_channel(&team_id, conversation_id).await?203
}202
}204
};203
};204
let fetch = async {205
Ok::<_, Error>(match self.resolve(conversation_id).await? {206
Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,207
Conversation::Channel { team_id } => {208
self.fetch_newer_channel(&team_id, conversation_id).await?209
}210
})211
};212
let (fetched, ()) = tokio::join!(fetch, heal);213
let mut delta = fetched?;205
let cache_changed = self.attach_delta_links(conversation_id, &mut delta).await214
let cache_changed = self.attach_delta_links(conversation_id, &mut delta).await206
| self.backfill_links(conversation_id).await215
| self.backfill_links(conversation_id).await;207
| self.heal_forwards(conversation_id).await;208
self.announce(conversation_id, !delta.is_empty() || cache_changed);216
self.announce(conversation_id, !delta.is_empty() || cache_changed);209
Ok(delta)217
Ok(delta)210
}218
}@@ -339,6 +347,24 @@ impl<R: Remote> SyncEngine<R> {339
Ok(tenant.clone())347
Ok(tenant.clone())340
}348
}341
349
350
pub(crate) async fn my_tenant_id_from_any_chat(&self) -> Result<String> {351
if let Some(tenant) = self.my_tenant_id.get() {352
return Ok(tenant.clone());353
}354
if let Some(cached) = self.store.meta(META_TENANT_ID)? {355
return Ok(cached);356
}357
let any_chat_id = self358
.store359
.sidebar()?360
.chats361
.into_iter()362
.next()363
.map(|chat| chat.id)364
.ok_or(Error::Unsupported("a tenant id without a known chat"))?;365
self.my_tenant_id(&any_chat_id).await366
}367
342
pub(crate) async fn resolve(&self, conversation_id: &str) -> Result<Conversation> {368
pub(crate) async fn resolve(&self, conversation_id: &str) -> Result<Conversation> {343
match self.resolve_stored(conversation_id) {369
match self.resolve_stored(conversation_id) {344
Err(Error::UnknownConversation(_)) => self.fetch_unknown_chat(conversation_id).await,370
Err(Error::UnknownConversation(_)) => self.fetch_unknown_chat(conversation_id).await,@@ -1,43 +1,155 @@
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
/// Once per chat and session, for cached forwards stored before their original message was kept.
23
/// Once per conversation and session (again after a failed Graph read), for cached forwards stored before their original message was kept.
8
24
pub(crate) async fn heal_forwards(&self, conversation_id: &str) -> bool {
9
25
let first = self
10
26
.forwards_healed
11
27
.lock()
12
28
.unwrap_or_else(|poisoned| poisoned.into_inner())
13
29
.insert(conversation_id.to_owned());
14
if !first || !matches!(self.resolve_stored(conversation_id), Ok(Conversation::Chat)) {
30
if !first {
15
31
return false;
16
32
}
33
let in_chat = match self.resolve_stored(conversation_id) {
34
Ok(Conversation::Chat) => true,
35
Ok(Conversation::Channel { .. }) => false,
36
Err(_) => return false,
37
};
17
38
let Ok(cached) = self
18
39
.store
19
40
.messages_with_attachment_type(conversation_id, FORWARDED_CONTENT_TYPE)
20
41
else {
21
42
return false;
22
43
};
23
let stale: Vec<String> = cached
24
.iter()
25
.filter(|record| lacks_forward_content(record))
26
.map(|record| record.message_id.clone())
44
let stale_ids: Vec<String> = cached
45
.into_iter()
46
.filter(lacks_forward_content)
47
.map(|record| record.message_id)
27
48
.collect();
28
if stale.is_empty() {
49
if stale_ids.is_empty() {
29
50
return false;
30
51
}
31
let Ok(answers) = self.remote.chat_messages_by_id(conversation_id, &stale).await else {
52
if !in_chat {
53
let given_up = self.given_up_forwards(conversation_id, &stale_ids);
54
return self
55
.ingest(conversation_id, given_up)
56
.is_ok_and(|delta| !delta.is_empty());
57
}
58
let Ok(answers) = self
59
.remote
60
.chat_messages_by_id(conversation_id, &stale_ids)
61
.await
62
else {
63
self.retry_forward_heal(conversation_id);
32
64
return false;
33
65
};
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)
66
let mut healed = Vec::new();
67
let mut given_up_ids = Vec::new();
68
let mut retry = false;
69
for (message_id, answer) in stale_ids.iter().zip(answers) {
70
let fresh = match answer {
71
Ok(message) => message_record(conversation_id, &message),
72
Err(error) if is_gone(&error) => None,
73
Err(_) => {
74
retry = true;
75
continue;
76
}
77
};
78
match fresh {
79
Some(record) if !lacks_forward_content(&record) => healed.push(record),
80
_ => given_up_ids.push(message_id.clone()),
81
}
82
}
83
if retry {
84
self.retry_forward_heal(conversation_id);
85
}
86
self.apply_chat_emotions(conversation_id, &mut healed).await;
87
healed.extend(self.given_up_forwards(conversation_id, &given_up_ids));
88
self.ingest(conversation_id, healed)
41
89
.is_ok_and(|delta| !delta.is_empty())
42
90
}
91
92
fn retry_forward_heal(&self, conversation_id: &str) {
93
self.forwards_healed
94
.lock()
95
.unwrap_or_else(|poisoned| poisoned.into_inner())
96
.remove(conversation_id);
97
}
98
99
/// Read again, as the delta fetch running alongside may have stored a newer version meanwhile.
100
fn given_up_forwards(
101
&self,
102
conversation_id: &str,
103
message_ids: &[String],
104
) -> Vec<MessageRecord> {
105
if message_ids.is_empty() {
106
return Vec::new();
107
}
108
self.store
109
.messages_by_id(conversation_id, message_ids)
110
.map(|current| {
111
current
112
.values()
113
.filter_map(mark_forwards_unavailable)
114
.collect()
115
})
116
.unwrap_or_default()
117
}
118
119
/// Heals every chat that still holds forwards without their original, newest chat first, one Graph batch per chat.
120
pub async fn heal_all_forwards(&self, pause: Duration) {
121
let Ok(conversation_ids) = self
122
.store
123
.conversations_with_stale_attachments(FORWARDED_CONTENT_TYPE)
124
else {
125
return;
126
};
127
for conversation_id in conversation_ids {
128
if self.heal_forwards(&conversation_id).await {
129
self.announce(&conversation_id, true);
130
}
131
tokio::time::sleep(pause).await;
132
}
133
}
134
}
135
136
#[cfg(test)]
137
mod tests {
138
use super::*;
139
140
#[test]
141
fn only_a_definite_graph_answer_gives_a_forward_up() {
142
let api = |status| {
143
Error::Graph(graph::Error::Session(session::Error::api(
144
status,
145
"https://graph.microsoft.com/v1.0/chats/c/messages/m",
146
serde_json::json!({}),
147
)))
148
};
149
assert!(is_gone(&api(404)));
150
assert!(is_gone(&api(403)));
151
assert!(!is_gone(&api(429)));
152
assert!(!is_gone(&api(503)));
153
assert!(!is_gone(&Error::Unsupported("batched message reads")));
154
}
43
155
}
@@ -1,43 +1,155 @@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 conversation and session (again after a failed Graph read), 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 {9
let first = self25
let first = self10
.forwards_healed26
.forwards_healed11
.lock()27
.lock()12
.unwrap_or_else(|poisoned| poisoned.into_inner())28
.unwrap_or_else(|poisoned| poisoned.into_inner())13
.insert(conversation_id.to_owned());29
.insert(conversation_id.to_owned());14
if !first || !matches!(self.resolve_stored(conversation_id), Ok(Conversation::Chat)) {30
if !first {15
return false;31
return false;16
}32
}33
let in_chat = match self.resolve_stored(conversation_id) {34
Ok(Conversation::Chat) => true,35
Ok(Conversation::Channel { .. }) => false,36
Err(_) => return false,37
};17
let Ok(cached) = self38
let Ok(cached) = self18
.store39
.store19
.messages_with_attachment_type(conversation_id, FORWARDED_CONTENT_TYPE)40
.messages_with_attachment_type(conversation_id, FORWARDED_CONTENT_TYPE)20
else {41
else {21
return false;42
return false;22
};43
};23
let stale: Vec<String> = cached44
let stale_ids: Vec<String> = cached24
.iter()45
.into_iter()25
.filter(|record| lacks_forward_content(record))46
.filter(lacks_forward_content)26
.map(|record| record.message_id.clone())47
.map(|record| record.message_id)27
.collect();48
.collect();28
if stale.is_empty() {49
if stale_ids.is_empty() {29
return false;50
return false;30
}51
}31
let Ok(answers) = self.remote.chat_messages_by_id(conversation_id, &stale).await else {52
if !in_chat {53
let given_up = self.given_up_forwards(conversation_id, &stale_ids);54
return self55
.ingest(conversation_id, given_up)56
.is_ok_and(|delta| !delta.is_empty());57
}58
let Ok(answers) = self59
.remote60
.chat_messages_by_id(conversation_id, &stale_ids)61
.await62
else {63
self.retry_forward_heal(conversation_id);32
return false;64
return false;33
};65
};34
let mut records: Vec<_> = answers66
let mut healed = Vec::new();35
.iter()67
let mut given_up_ids = Vec::new();36
.flatten()68
let mut retry = false;37
.filter_map(|message| message_record(conversation_id, message))69
for (message_id, answer) in stale_ids.iter().zip(answers) {38
.collect();70
let fresh = match answer {39
self.apply_chat_emotions(conversation_id, &mut records).await;71
Ok(message) => message_record(conversation_id, &message),40
self.ingest(conversation_id, records)72
Err(error) if is_gone(&error) => None,73
Err(_) => {74
retry = true;75
continue;76
}77
};78
match fresh {79
Some(record) if !lacks_forward_content(&record) => healed.push(record),80
_ => given_up_ids.push(message_id.clone()),81
}82
}83
if retry {84
self.retry_forward_heal(conversation_id);85
}86
self.apply_chat_emotions(conversation_id, &mut healed).await;87
healed.extend(self.given_up_forwards(conversation_id, &given_up_ids));88
self.ingest(conversation_id, healed)41
.is_ok_and(|delta| !delta.is_empty())89
.is_ok_and(|delta| !delta.is_empty())42
}90
}91
92
fn retry_forward_heal(&self, conversation_id: &str) {93
self.forwards_healed94
.lock()95
.unwrap_or_else(|poisoned| poisoned.into_inner())96
.remove(conversation_id);97
}98
99
/// Read again, as the delta fetch running alongside may have stored a newer version meanwhile.100
fn given_up_forwards(101
&self,102
conversation_id: &str,103
message_ids: &[String],104
) -> Vec<MessageRecord> {105
if message_ids.is_empty() {106
return Vec::new();107
}108
self.store109
.messages_by_id(conversation_id, message_ids)110
.map(|current| {111
current112
.values()113
.filter_map(mark_forwards_unavailable)114
.collect()115
})116
.unwrap_or_default()117
}118
119
/// Heals every chat that still holds forwards without their original, newest chat first, one Graph batch per chat.120
pub async fn heal_all_forwards(&self, pause: Duration) {121
let Ok(conversation_ids) = self122
.store123
.conversations_with_stale_attachments(FORWARDED_CONTENT_TYPE)124
else {125
return;126
};127
for conversation_id in conversation_ids {128
if self.heal_forwards(&conversation_id).await {129
self.announce(&conversation_id, true);130
}131
tokio::time::sleep(pause).await;132
}133
}134
}135
136
#[cfg(test)]137
mod tests {138
use super::*;139
140
#[test]141
fn only_a_definite_graph_answer_gives_a_forward_up() {142
let api = |status| {143
Error::Graph(graph::Error::Session(session::Error::api(144
status,145
"https://graph.microsoft.com/v1.0/chats/c/messages/m",146
serde_json::json!({}),147
)))148
};149
assert!(is_gone(&api(404)));150
assert!(is_gone(&api(403)));151
assert!(!is_gone(&api(429)));152
assert!(!is_gone(&api(503)));153
assert!(!is_gone(&Error::Unsupported("batched message reads")));154
}43
}155
}@@ -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]@@ -50,6 +50,7 @@ mod remote;
50
50
mod scheduled;
51
51
mod skin_tone;
52
52
mod search;
53
mod server_search;
53
54
mod sidebar_sync;
54
55
mod spans;
55
56
mod stored;
@@ -97,6 +98,7 @@ pub use chatsvc::{
97
98
WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,
98
99
};
99
100
pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};
101
pub use chatsvc::substrate_search;
100
102
pub use chatsvc::{
101
103
Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,
102
104
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,
@@ -143,7 +145,8 @@ pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
143
145
pub use scheduled::NOTES_CHAT_ID;
144
146
pub use skin_tone::{skin_tone, store_account_skin_tone};
145
147
pub use forwarded::{
146
FORWARDED_CONTENT_TYPE, ForwardHeader, ForwardInfo, forwarded_texts, forwards, is_forwarded,
148
FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,
149
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
147
150
};
148
151
pub use spans::{FontSize, Span, html_to_spans};
149
152
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
@@ -50,6 +50,7 @@ mod remote;50
mod scheduled;50
mod scheduled;51
mod skin_tone;51
mod skin_tone;52
mod search;52
mod search;53
mod server_search;53
mod sidebar_sync;54
mod sidebar_sync;54
mod spans;55
mod spans;55
mod stored;56
mod stored;@@ -97,6 +98,7 @@ pub use chatsvc::{97
WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,98
WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,98
};99
};99
pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};100
pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};101
pub use chatsvc::substrate_search;100
pub use chatsvc::{102
pub use chatsvc::{101
Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,103
Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,102
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,104
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,@@ -143,7 +145,8 @@ pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};143
pub use scheduled::NOTES_CHAT_ID;145
pub use scheduled::NOTES_CHAT_ID;144
pub use skin_tone::{skin_tone, store_account_skin_tone};146
pub use skin_tone::{skin_tone, store_account_skin_tone};145
pub use forwarded::{147
pub use forwarded::{146
FORWARDED_CONTENT_TYPE, ForwardHeader, ForwardInfo, forwarded_texts, forwards, is_forwarded,148
FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,149
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,147
};150
};148
pub use spans::{FontSize, Span, html_to_spans};151
pub use spans::{FontSize, Span, html_to_spans};149
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};152
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};@@ -229,6 +229,7 @@ pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {
229
229
Some("messageReference" | FORWARDED_CONTENT_TYPE)
230
230
)
231
231
}),
232
unavailable: false,
232
233
}
233
234
}
234
235
@@ -229,6 +229,7 @@ pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {229
Some("messageReference" | FORWARDED_CONTENT_TYPE)229
Some("messageReference" | FORWARDED_CONTENT_TYPE)230
)230
)231
}),231
}),232
unavailable: false,232
}233
}233
}234
}234
235
@@ -4,9 +4,9 @@ use std::time::Duration;
4
4
5
5
use chatsvc::{EventKind, MemberHorizon, MessageEvent, StatusEvent, StatusKind};
6
6
use chrono::{DateTime, Utc};
7
use store::MessageRecord;
7
use store::{MessageRecord, ReadHorizonRecord};
8
8
9
use crate::engine::{Conversation, SyncEngine};
9
use crate::engine::{Conversation, META_USER_ID, SyncEngine};
10
10
use crate::error::Result;
11
11
use crate::events::CoreEvent;
12
12
use crate::remote::Remote;
@@ -46,6 +46,7 @@ struct ConversationReceipts {
46
46
pub(crate) struct ReceiptCache {
47
47
conversations: Mutex<HashMap<String, Option<ConversationReceipts>>>,
48
48
pending: Mutex<HashSet<String>>,
49
read_from_store: Mutex<HashSet<String>>,
49
50
pub(crate) debounce: Duration,
50
51
}
51
52
@@ -54,6 +55,7 @@ impl Default for ReceiptCache {
54
55
ReceiptCache {
55
56
conversations: Mutex::new(HashMap::new()),
56
57
pending: Mutex::new(HashSet::new()),
58
read_from_store: Mutex::new(HashSet::new()),
57
59
debounce: DEFAULT_RECEIPT_DEBOUNCE,
58
60
}
59
61
}
@@ -73,9 +75,17 @@ fn user_of(member_id: &str) -> &str {
73
75
member_id.rsplit(':').next().unwrap_or(member_id)
74
76
}
75
77
78
fn stored_horizon(horizon: MemberHorizon) -> ReadHorizonRecord {
79
ReadHorizonRecord {
80
member_id: horizon.member_id,
81
read_until: horizon.read_until,
82
read_at: horizon.read_at,
83
}
84
}
85
76
86
fn build(
77
87
my_user_id: &str,
78
horizons: &[MemberHorizon],
88
horizons: &[ReadHorizonRecord],
79
89
members: &[store::MemberRecord],
80
90
) -> Option<ConversationReceipts> {
81
91
let mut others: Vec<OtherMember> = horizons
@@ -169,8 +179,9 @@ impl<R: Remote> SyncEngine<R> {
169
179
})
170
180
}
171
181
172
/// Memory only, cheap enough to call per rendered message.
182
/// Memory first; the stored horizons of a chat are read once per session, so receipts show before the refresh.
173
183
pub fn receipt_state_for(&self, record: &MessageRecord) -> ReceiptState {
184
self.load_stored_receipts(&record.conversation_id);
174
185
let conversations = locked(&self.receipts.conversations);
175
186
match conversations.get(&record.conversation_id) {
176
187
Some(Some(receipts)) => state_of(receipts, record),
@@ -178,6 +189,31 @@ impl<R: Remote> SyncEngine<R> {
178
189
}
179
190
}
180
191
192
fn load_stored_receipts(&self, conversation_id: &str) {
193
if !locked(&self.receipts.read_from_store).insert(conversation_id.to_owned()) {
194
return;
195
}
196
if locked(&self.receipts.conversations).contains_key(conversation_id) {
197
return;
198
}
199
let Some(cached) = self.stored_receipts(conversation_id) else {
200
return;
201
};
202
locked(&self.receipts.conversations)
203
.entry(conversation_id.to_owned())
204
.or_insert(Some(cached));
205
}
206
207
fn stored_receipts(&self, conversation_id: &str) -> Option<ConversationReceipts> {
208
let horizons = self.store.read_horizons(conversation_id).ok()?;
209
if horizons.is_empty() {
210
return None;
211
}
212
let my_user_id = self.store.meta(META_USER_ID).ok()??;
213
let members = self.store.chat(conversation_id).ok()??.members;
214
build(&my_user_id, &horizons, &members)
215
}
216
181
217
/// Call when a chat opens. Channels are skipped.
182
218
pub async fn refresh_receipts(&self, conversation_id: &str) -> Result<()> {
183
219
if matches!(
@@ -187,7 +223,15 @@ impl<R: Remote> SyncEngine<R> {
187
223
return Ok(());
188
224
}
189
225
let my_user_id = self.my_user_id().await?;
190
let horizons = self.remote.consumption_horizons(conversation_id).await?;
226
let horizons: Vec<ReadHorizonRecord> = self
227
.remote
228
.consumption_horizons(conversation_id)
229
.await?
230
.into_iter()
231
.map(stored_horizon)
232
.collect();
233
self.store.set_read_horizons(conversation_id, &horizons)?;
234
locked(&self.receipts.read_from_store).insert(conversation_id.to_owned());
191
235
let members = self
192
236
.store
193
237
.chat(conversation_id)?
@@ -4,9 +4,9 @@ use std::time::Duration;4
4
5
use chatsvc::{EventKind, MemberHorizon, MessageEvent, StatusEvent, StatusKind};5
use chatsvc::{EventKind, MemberHorizon, MessageEvent, StatusEvent, StatusKind};6
use chrono::{DateTime, Utc};6
use chrono::{DateTime, Utc};7
use store::MessageRecord;7
use store::{MessageRecord, ReadHorizonRecord};8
8
9
use crate::engine::{Conversation, SyncEngine};9
use crate::engine::{Conversation, META_USER_ID, SyncEngine};10
use crate::error::Result;10
use crate::error::Result;11
use crate::events::CoreEvent;11
use crate::events::CoreEvent;12
use crate::remote::Remote;12
use crate::remote::Remote;@@ -46,6 +46,7 @@ struct ConversationReceipts {46
pub(crate) struct ReceiptCache {46
pub(crate) struct ReceiptCache {47
conversations: Mutex<HashMap<String, Option<ConversationReceipts>>>,47
conversations: Mutex<HashMap<String, Option<ConversationReceipts>>>,48
pending: Mutex<HashSet<String>>,48
pending: Mutex<HashSet<String>>,49
read_from_store: Mutex<HashSet<String>>,49
pub(crate) debounce: Duration,50
pub(crate) debounce: Duration,50
}51
}51
52
@@ -54,6 +55,7 @@ impl Default for ReceiptCache {54
ReceiptCache {55
ReceiptCache {55
conversations: Mutex::new(HashMap::new()),56
conversations: Mutex::new(HashMap::new()),56
pending: Mutex::new(HashSet::new()),57
pending: Mutex::new(HashSet::new()),58
read_from_store: Mutex::new(HashSet::new()),57
debounce: DEFAULT_RECEIPT_DEBOUNCE,59
debounce: DEFAULT_RECEIPT_DEBOUNCE,58
}60
}59
}61
}@@ -73,9 +75,17 @@ fn user_of(member_id: &str) -> &str {73
member_id.rsplit(':').next().unwrap_or(member_id)75
member_id.rsplit(':').next().unwrap_or(member_id)74
}76
}75
77
78
fn stored_horizon(horizon: MemberHorizon) -> ReadHorizonRecord {79
ReadHorizonRecord {80
member_id: horizon.member_id,81
read_until: horizon.read_until,82
read_at: horizon.read_at,83
}84
}85
76
fn build(86
fn build(77
my_user_id: &str,87
my_user_id: &str,78
horizons: &[MemberHorizon],88
horizons: &[ReadHorizonRecord],79
members: &[store::MemberRecord],89
members: &[store::MemberRecord],80
) -> Option<ConversationReceipts> {90
) -> Option<ConversationReceipts> {81
let mut others: Vec<OtherMember> = horizons91
let mut others: Vec<OtherMember> = horizons@@ -169,8 +179,9 @@ impl<R: Remote> SyncEngine<R> {169
})179
})170
}180
}171
181
172
/// Memory only, cheap enough to call per rendered message.182
/// Memory first; the stored horizons of a chat are read once per session, so receipts show before the refresh.173
pub fn receipt_state_for(&self, record: &MessageRecord) -> ReceiptState {183
pub fn receipt_state_for(&self, record: &MessageRecord) -> ReceiptState {184
self.load_stored_receipts(&record.conversation_id);174
let conversations = locked(&self.receipts.conversations);185
let conversations = locked(&self.receipts.conversations);175
match conversations.get(&record.conversation_id) {186
match conversations.get(&record.conversation_id) {176
Some(Some(receipts)) => state_of(receipts, record),187
Some(Some(receipts)) => state_of(receipts, record),@@ -178,6 +189,31 @@ impl<R: Remote> SyncEngine<R> {178
}189
}179
}190
}180
191
192
fn load_stored_receipts(&self, conversation_id: &str) {193
if !locked(&self.receipts.read_from_store).insert(conversation_id.to_owned()) {194
return;195
}196
if locked(&self.receipts.conversations).contains_key(conversation_id) {197
return;198
}199
let Some(cached) = self.stored_receipts(conversation_id) else {200
return;201
};202
locked(&self.receipts.conversations)203
.entry(conversation_id.to_owned())204
.or_insert(Some(cached));205
}206
207
fn stored_receipts(&self, conversation_id: &str) -> Option<ConversationReceipts> {208
let horizons = self.store.read_horizons(conversation_id).ok()?;209
if horizons.is_empty() {210
return None;211
}212
let my_user_id = self.store.meta(META_USER_ID).ok()??;213
let members = self.store.chat(conversation_id).ok()??.members;214
build(&my_user_id, &horizons, &members)215
}216
181
/// Call when a chat opens. Channels are skipped.217
/// Call when a chat opens. Channels are skipped.182
pub async fn refresh_receipts(&self, conversation_id: &str) -> Result<()> {218
pub async fn refresh_receipts(&self, conversation_id: &str) -> Result<()> {183
if matches!(219
if matches!(@@ -187,7 +223,15 @@ impl<R: Remote> SyncEngine<R> {187
return Ok(());223
return Ok(());188
}224
}189
let my_user_id = self.my_user_id().await?;225
let my_user_id = self.my_user_id().await?;190
let horizons = self.remote.consumption_horizons(conversation_id).await?;226
let horizons: Vec<ReadHorizonRecord> = self227
.remote228
.consumption_horizons(conversation_id)229
.await?230
.into_iter()231
.map(stored_horizon)232
.collect();233
self.store.set_read_horizons(conversation_id, &horizons)?;234
locked(&self.receipts.read_from_store).insert(conversation_id.to_owned());191
let members = self235
let members = self192
.store236
.store193
.chat(conversation_id)?237
.chat(conversation_id)?@@ -8,6 +8,9 @@ use chatsvc::{
8
8
Translation, TranslationTrigger, Translator, WindowDirection, WorkLocationKind,
9
9
};
10
10
use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
11
use chatsvc::substrate_search::{
12
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
13
};
11
14
use chrono::{DateTime, Utc};
12
15
use graph::{
13
16
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
@@ -438,6 +441,32 @@ pub trait Remote {
438
441
Err(Error::Unsupported("GIF search"))
439
442
}
440
443
444
async fn server_search_init(
445
&self,
446
_identity: &SearchIdentity,
447
_search_session: &SearchSession,
448
) -> Result<()> {
449
Err(Error::Unsupported("server search"))
450
}
451
452
async fn server_suggestions(
453
&self,
454
_identity: &SearchIdentity,
455
_search_session: &SearchSession,
456
_text: &str,
457
) -> Result<Suggestions> {
458
Err(Error::Unsupported("server search"))
459
}
460
461
async fn server_query(
462
&self,
463
_identity: &SearchIdentity,
464
_search_session: &SearchSession,
465
_request: &QueryRequest,
466
) -> Result<QueryResults> {
467
Err(Error::Unsupported("server search"))
468
}
469
441
470
async fn create_scheduled(
442
471
&self,
443
472
_inner_thread_id: &str,
@@ -1092,6 +1121,38 @@ impl Remote for Graph {
1092
1121
Ok(Gifs::new(self.session()).search(query).await?)
1093
1122
}
1094
1123
1124
async fn server_search_init(
1125
&self,
1126
identity: &SearchIdentity,
1127
search_session: &SearchSession,
1128
) -> Result<()> {
1129
Ok(SubstrateSearch::new(self.session(), identity.clone())
1130
.init(search_session)
1131
.await?)
1132
}
1133
1134
async fn server_suggestions(
1135
&self,
1136
identity: &SearchIdentity,
1137
search_session: &SearchSession,
1138
text: &str,
1139
) -> Result<Suggestions> {
1140
Ok(SubstrateSearch::new(self.session(), identity.clone())
1141
.suggestions(search_session, text)
1142
.await?)
1143
}
1144
1145
async fn server_query(
1146
&self,
1147
identity: &SearchIdentity,
1148
search_session: &SearchSession,
1149
request: &QueryRequest,
1150
) -> Result<QueryResults> {
1151
Ok(SubstrateSearch::new(self.session(), identity.clone())
1152
.query(search_session, request)
1153
.await?)
1154
}
1155
1095
1156
async fn create_scheduled(
1096
1157
&self,
1097
1158
inner_thread_id: &str,
@@ -8,6 +8,9 @@ use chatsvc::{8
Translation, TranslationTrigger, Translator, WindowDirection, WorkLocationKind,8
Translation, TranslationTrigger, Translator, WindowDirection, WorkLocationKind,9
};9
};10
use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};10
use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};11
use chatsvc::substrate_search::{12
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,13
};11
use chrono::{DateTime, Utc};14
use chrono::{DateTime, Utc};12
use graph::{15
use graph::{13
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,16
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,@@ -438,6 +441,32 @@ pub trait Remote {438
Err(Error::Unsupported("GIF search"))441
Err(Error::Unsupported("GIF search"))439
}442
}440
443
444
async fn server_search_init(445
&self,446
_identity: &SearchIdentity,447
_search_session: &SearchSession,448
) -> Result<()> {449
Err(Error::Unsupported("server search"))450
}451
452
async fn server_suggestions(453
&self,454
_identity: &SearchIdentity,455
_search_session: &SearchSession,456
_text: &str,457
) -> Result<Suggestions> {458
Err(Error::Unsupported("server search"))459
}460
461
async fn server_query(462
&self,463
_identity: &SearchIdentity,464
_search_session: &SearchSession,465
_request: &QueryRequest,466
) -> Result<QueryResults> {467
Err(Error::Unsupported("server search"))468
}469
441
async fn create_scheduled(470
async fn create_scheduled(442
&self,471
&self,443
_inner_thread_id: &str,472
_inner_thread_id: &str,@@ -1092,6 +1121,38 @@ impl Remote for Graph {1092
Ok(Gifs::new(self.session()).search(query).await?)1121
Ok(Gifs::new(self.session()).search(query).await?)1093
}1122
}1094
1123
1124
async fn server_search_init(1125
&self,1126
identity: &SearchIdentity,1127
search_session: &SearchSession,1128
) -> Result<()> {1129
Ok(SubstrateSearch::new(self.session(), identity.clone())1130
.init(search_session)1131
.await?)1132
}1133
1134
async fn server_suggestions(1135
&self,1136
identity: &SearchIdentity,1137
search_session: &SearchSession,1138
text: &str,1139
) -> Result<Suggestions> {1140
Ok(SubstrateSearch::new(self.session(), identity.clone())1141
.suggestions(search_session, text)1142
.await?)1143
}1144
1145
async fn server_query(1146
&self,1147
identity: &SearchIdentity,1148
search_session: &SearchSession,1149
request: &QueryRequest,1150
) -> Result<QueryResults> {1151
Ok(SubstrateSearch::new(self.session(), identity.clone())1152
.query(search_session, request)1153
.await?)1154
}1155
1095
async fn create_scheduled(1156
async fn create_scheduled(1096
&self,1157
&self,1097
inner_thread_id: &str,1158
inner_thread_id: &str,@@ -0,0 +1,46 @@
1
use chatsvc::substrate_search::{
2
QueryRequest, QueryResults, SearchIdentity, SearchSession, Suggestions,
3
};
4
5
use crate::engine::SyncEngine;
6
use crate::error::Result;
7
use crate::remote::Remote;
8
9
impl<R: Remote> SyncEngine<R> {
10
pub async fn server_search_init(&self, search_session: &SearchSession) -> Result<()> {
11
let identity = self.search_identity().await?;
12
self.remote
13
.server_search_init(&identity, search_session)
14
.await
15
}
16
17
/// An empty text returns the zero-query state (top people, recent searches).
18
pub async fn server_suggestions(
19
&self,
20
search_session: &SearchSession,
21
text: &str,
22
) -> Result<Suggestions> {
23
let identity = self.search_identity().await?;
24
self.remote
25
.server_suggestions(&identity, search_session, text)
26
.await
27
}
28
29
pub async fn server_query(
30
&self,
31
search_session: &SearchSession,
32
request: &QueryRequest,
33
) -> Result<QueryResults> {
34
let identity = self.search_identity().await?;
35
self.remote
36
.server_query(&identity, search_session, request)
37
.await
38
}
39
40
async fn search_identity(&self) -> Result<SearchIdentity> {
41
Ok(SearchIdentity {
42
user_id: self.my_user_id().await?,
43
tenant_id: self.my_tenant_id_from_any_chat().await?,
44
})
45
}
46
}
@@ -0,0 +1,46 @@1
use chatsvc::substrate_search::{2
QueryRequest, QueryResults, SearchIdentity, SearchSession, Suggestions,3
};4
5
use crate::engine::SyncEngine;6
use crate::error::Result;7
use crate::remote::Remote;8
9
impl<R: Remote> SyncEngine<R> {10
pub async fn server_search_init(&self, search_session: &SearchSession) -> Result<()> {11
let identity = self.search_identity().await?;12
self.remote13
.server_search_init(&identity, search_session)14
.await15
}16
17
/// An empty text returns the zero-query state (top people, recent searches).18
pub async fn server_suggestions(19
&self,20
search_session: &SearchSession,21
text: &str,22
) -> Result<Suggestions> {23
let identity = self.search_identity().await?;24
self.remote25
.server_suggestions(&identity, search_session, text)26
.await27
}28
29
pub async fn server_query(30
&self,31
search_session: &SearchSession,32
request: &QueryRequest,33
) -> Result<QueryResults> {34
let identity = self.search_identity().await?;35
self.remote36
.server_query(&identity, search_session, request)37
.await38
}39
40
async fn search_identity(&self) -> Result<SearchIdentity> {41
Ok(SearchIdentity {42
user_id: self.my_user_id().await?,43
tenant_id: self.my_tenant_id_from_any_chat().await?,44
})45
}46
}@@ -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
};@@ -15,6 +15,7 @@ use teams_core::{
15
15
Availability, BoxFuture, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent,
16
16
DeltaPage, Error, FolderChange, FolderKind, FolderSource, MentionCandidate, MentionInput,
17
17
MentionTarget, PersonSource, Remote, RemotePage, Result, SyncConfig, SyncEngine,
18
substrate_search,
18
19
};
19
20
20
21
const ME: &str = "user-me";
@@ -132,6 +133,7 @@ struct Fake {
132
133
note_puts: Mutex<Vec<Option<chatsvc::StatusNote>>>,
133
134
window_answer: Mutex<Option<chatsvc::MessageWindow>>,
134
135
window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
136
search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,
135
137
}
136
138
137
139
impl Fake {
@@ -195,6 +197,20 @@ impl Fake {
195
197
}
196
198
197
199
impl Remote for Handle {
200
async fn server_suggestions(
201
&self,
202
identity: &substrate_search::SearchIdentity,
203
_search_session: &substrate_search::SearchSession,
204
text: &str,
205
) -> Result<substrate_search::Suggestions> {
206
self.search_identities
207
.lock()
208
.unwrap()
209
.push(identity.clone());
210
self.record(format!("server_suggestions:{text}"));
211
Ok(substrate_search::Suggestions::default())
212
}
213
198
214
async fn me(&self) -> Result<User> {
199
215
Ok(serde_json::from_value(json!({"id": ME, "displayName": "Me Myself"})).unwrap())
200
216
}
@@ -3856,6 +3872,27 @@ async fn one_on_one_read_up_to_horizon() {
3856
3872
);
3857
3873
}
3858
3874
3875
#[tokio::test]
3876
async fn stored_horizons_show_receipts_after_a_restart_before_any_refresh() {
3877
let fake = Arc::new(Fake::default());
3878
let engine = receipt_engine(&fake, vec![one_on_one()]).await;
3879
*fake.horizons.lock().unwrap() =
3880
vec![horizon_of("user-me", 3, 3), horizon_of("user-ada", 2, 9)];
3881
engine.refresh_receipts(CHAT).await.unwrap();
3882
let restarted =
3883
SyncEngine::with_config(Handle(fake.clone()), engine.store().clone(), small_pages());
3884
fake.horizons.lock().unwrap().clear();
3885
3886
assert!(matches!(
3887
restarted.receipt_state(CHAT, "m0001"),
3888
teams_core::ReceiptState::Read { .. }
3889
));
3890
assert_eq!(
3891
restarted.receipt_state(CHAT, "m0003"),
3892
teams_core::ReceiptState::Sent
3893
);
3894
}
3895
3859
3896
#[tokio::test]
3860
3897
async fn horizon_equal_to_creation_time_counts_as_read() {
3861
3898
let fake = Arc::new(Fake::default());
@@ -4740,3 +4777,120 @@ async fn a_forward_cached_without_its_content_is_read_again_once() {
4740
4777
engine.fetch_newer(CHAT).await.unwrap();
4741
4778
assert_eq!(reads(&fake), 1);
4742
4779
}
4780
4781
#[tokio::test]
4782
async fn server_search_is_anchored_to_my_user_and_tenant() {
4783
let fake = Arc::new(Fake::default());
4784
let engine = chat_engine(&fake, SyncConfig::default()).await;
4785
let search_session = substrate_search::SearchSession::new();
4786
engine
4787
.server_suggestions(&search_session, "ada")
4788
.await
4789
.unwrap();
4790
engine
4791
.server_suggestions(&search_session, "adam")
4792
.await
4793
.unwrap();
4794
let identities = fake.search_identities.lock().unwrap().clone();
4795
let expected = substrate_search::SearchIdentity {
4796
user_id: ME.to_owned(),
4797
tenant_id: "tenant-1".to_owned(),
4798
};
4799
assert_eq!(identities, [expected.clone(), expected]);
4800
}
4801
4802
const STALE_FORWARD: &str = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"orig-1","content":null}]"#;
4803
4804
fn stale_forward(conversation_id: &str, message_id: &str, minute: i64) -> store::MessageRecord {
4805
let mut stale =
4806
teams_core::message_record(conversation_id, &forwarded_message(message_id, minute))
4807
.unwrap();
4808
stale.attachments_json = STALE_FORWARD.to_owned();
4809
stale
4810
}
4811
4812
fn forwarded_message_without_original(id: &str, minute: i64) -> Message {
4813
let mut message = forwarded_message(id, minute);
4814
message.attachments[0].content = None;
4815
message
4816
}
4817
4818
fn forward_state(store: &Store, conversation_id: &str, message_id: &str) -> teams_core::ForwardState {
4819
let record = store
4820
.messages_by_id(conversation_id, &[message_id.to_owned()])
4821
.unwrap()
4822
.remove(message_id)
4823
.unwrap();
4824
teams_core::forwards(&record)[0].state
4825
}
4826
4827
#[tokio::test]
4828
async fn a_forward_graph_returns_without_its_original_is_not_read_again() {
4829
let fake = Arc::new(Fake::default());
4830
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
4831
let store = Arc::new(Store::open_in_memory().unwrap());
4832
let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());
4833
engine.refresh_sidebar().await.unwrap();
4834
let mut messages = numbered(11);
4835
messages.push(forwarded_message_without_original("m0000", 0));
4836
fake.set_chat_messages(messages);
4837
store.upsert_messages(&[stale_forward(CHAT, "m0000", 0)]).unwrap();
4838
assert_eq!(forward_state(&store, CHAT, "m0000"), teams_core::ForwardState::Loading);
4839
4840
engine.fetch_newer(CHAT).await.unwrap();
4841
4842
assert_eq!(forward_state(&store, CHAT, "m0000"), teams_core::ForwardState::Unavailable);
4843
let next_session = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());
4844
next_session.fetch_newer(CHAT).await.unwrap();
4845
let reads = fake
4846
.calls()
4847
.iter()
4848
.filter(|call| *call == "chat_message m0000")
4849
.count();
4850
assert_eq!(reads, 1);
4851
}
4852
4853
#[tokio::test]
4854
async fn the_background_heal_reads_the_newest_chat_first_and_skips_healthy_chats() {
4855
const OLDER: &str = "19:older@thread.v2";
4856
const HEALTHY: &str = "19:healthy@thread.v2";
4857
let fake = Arc::new(Fake::default());
4858
*fake.chats.lock().unwrap() = vec![
4859
chat(OLDER, Some("Older"), 2, 2, ME, false),
4860
chat(CHAT, Some("Newer"), 9, 9, ME, false),
4861
chat(HEALTHY, Some("Healthy"), 12, 12, ME, false),
4862
];
4863
let store = Arc::new(Store::open_in_memory().unwrap());
4864
let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());
4865
engine.refresh_sidebar().await.unwrap();
4866
fake.set_chat_messages(vec![
4867
forwarded_message("f-older", 1),
4868
forwarded_message("f-newer", 8),
4869
]);
4870
let healthy = teams_core::message_record(HEALTHY, &forwarded_message("f-healthy", 11)).unwrap();
4871
store
4872
.upsert_messages(&[
4873
stale_forward(OLDER, "f-older", 1),
4874
stale_forward(CHAT, "f-newer", 8),
4875
healthy,
4876
])
4877
.unwrap();
4878
let mut events = engine.subscribe();
4879
4880
engine.heal_all_forwards(std::time::Duration::ZERO).await;
4881
4882
let reads: Vec<String> = fake
4883
.calls()
4884
.into_iter()
4885
.filter(|call| call.starts_with("chat_message "))
4886
.collect();
4887
assert_eq!(reads, ["chat_message f-newer", "chat_message f-older"]);
4888
assert_eq!(forward_state(&store, OLDER, "f-older"), teams_core::ForwardState::Ready);
4889
let mut changed = Vec::new();
4890
while let Ok(event) = events.try_recv() {
4891
if let CoreEvent::MessagesChanged { conversation_id } = event {
4892
changed.push(conversation_id);
4893
}
4894
}
4895
assert_eq!(changed, [CHAT, OLDER]);
4896
}
@@ -15,6 +15,7 @@ use teams_core::{15
Availability, BoxFuture, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent,15
Availability, BoxFuture, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent,16
DeltaPage, Error, FolderChange, FolderKind, FolderSource, MentionCandidate, MentionInput,16
DeltaPage, Error, FolderChange, FolderKind, FolderSource, MentionCandidate, MentionInput,17
MentionTarget, PersonSource, Remote, RemotePage, Result, SyncConfig, SyncEngine,17
MentionTarget, PersonSource, Remote, RemotePage, Result, SyncConfig, SyncEngine,18
substrate_search,18
};19
};19
20
20
const ME: &str = "user-me";21
const ME: &str = "user-me";@@ -132,6 +133,7 @@ struct Fake {132
note_puts: Mutex<Vec<Option<chatsvc::StatusNote>>>,133
note_puts: Mutex<Vec<Option<chatsvc::StatusNote>>>,133
window_answer: Mutex<Option<chatsvc::MessageWindow>>,134
window_answer: Mutex<Option<chatsvc::MessageWindow>>,134
window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,135
window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,136
search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,135
}137
}136
138
137
impl Fake {139
impl Fake {@@ -195,6 +197,20 @@ impl Fake {195
}197
}196
198
197
impl Remote for Handle {199
impl Remote for Handle {200
async fn server_suggestions(201
&self,202
identity: &substrate_search::SearchIdentity,203
_search_session: &substrate_search::SearchSession,204
text: &str,205
) -> Result<substrate_search::Suggestions> {206
self.search_identities207
.lock()208
.unwrap()209
.push(identity.clone());210
self.record(format!("server_suggestions:{text}"));211
Ok(substrate_search::Suggestions::default())212
}213
198
async fn me(&self) -> Result<User> {214
async fn me(&self) -> Result<User> {199
Ok(serde_json::from_value(json!({"id": ME, "displayName": "Me Myself"})).unwrap())215
Ok(serde_json::from_value(json!({"id": ME, "displayName": "Me Myself"})).unwrap())200
}216
}@@ -3856,6 +3872,27 @@ async fn one_on_one_read_up_to_horizon() {3856
);3872
);3857
}3873
}3858
3874
3875
#[tokio::test]3876
async fn stored_horizons_show_receipts_after_a_restart_before_any_refresh() {3877
let fake = Arc::new(Fake::default());3878
let engine = receipt_engine(&fake, vec![one_on_one()]).await;3879
*fake.horizons.lock().unwrap() =3880
vec![horizon_of("user-me", 3, 3), horizon_of("user-ada", 2, 9)];3881
engine.refresh_receipts(CHAT).await.unwrap();3882
let restarted =3883
SyncEngine::with_config(Handle(fake.clone()), engine.store().clone(), small_pages());3884
fake.horizons.lock().unwrap().clear();3885
3886
assert!(matches!(3887
restarted.receipt_state(CHAT, "m0001"),3888
teams_core::ReceiptState::Read { .. }3889
));3890
assert_eq!(3891
restarted.receipt_state(CHAT, "m0003"),3892
teams_core::ReceiptState::Sent3893
);3894
}3895
3859
#[tokio::test]3896
#[tokio::test]3860
async fn horizon_equal_to_creation_time_counts_as_read() {3897
async fn horizon_equal_to_creation_time_counts_as_read() {3861
let fake = Arc::new(Fake::default());3898
let fake = Arc::new(Fake::default());@@ -4740,3 +4777,120 @@ async fn a_forward_cached_without_its_content_is_read_again_once() {4740
engine.fetch_newer(CHAT).await.unwrap();4777
engine.fetch_newer(CHAT).await.unwrap();4741
assert_eq!(reads(&fake), 1);4778
assert_eq!(reads(&fake), 1);4742
}4779
}4780
4781
#[tokio::test]4782
async fn server_search_is_anchored_to_my_user_and_tenant() {4783
let fake = Arc::new(Fake::default());4784
let engine = chat_engine(&fake, SyncConfig::default()).await;4785
let search_session = substrate_search::SearchSession::new();4786
engine4787
.server_suggestions(&search_session, "ada")4788
.await4789
.unwrap();4790
engine4791
.server_suggestions(&search_session, "adam")4792
.await4793
.unwrap();4794
let identities = fake.search_identities.lock().unwrap().clone();4795
let expected = substrate_search::SearchIdentity {4796
user_id: ME.to_owned(),4797
tenant_id: "tenant-1".to_owned(),4798
};4799
assert_eq!(identities, [expected.clone(), expected]);4800
}4801
4802
const STALE_FORWARD: &str = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"orig-1","content":null}]"#;4803
4804
fn stale_forward(conversation_id: &str, message_id: &str, minute: i64) -> store::MessageRecord {4805
let mut stale =4806
teams_core::message_record(conversation_id, &forwarded_message(message_id, minute))4807
.unwrap();4808
stale.attachments_json = STALE_FORWARD.to_owned();4809
stale4810
}4811
4812
fn forwarded_message_without_original(id: &str, minute: i64) -> Message {4813
let mut message = forwarded_message(id, minute);4814
message.attachments[0].content = None;4815
message4816
}4817
4818
fn forward_state(store: &Store, conversation_id: &str, message_id: &str) -> teams_core::ForwardState {4819
let record = store4820
.messages_by_id(conversation_id, &[message_id.to_owned()])4821
.unwrap()4822
.remove(message_id)4823
.unwrap();4824
teams_core::forwards(&record)[0].state4825
}4826
4827
#[tokio::test]4828
async fn a_forward_graph_returns_without_its_original_is_not_read_again() {4829
let fake = Arc::new(Fake::default());4830
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];4831
let store = Arc::new(Store::open_in_memory().unwrap());4832
let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());4833
engine.refresh_sidebar().await.unwrap();4834
let mut messages = numbered(11);4835
messages.push(forwarded_message_without_original("m0000", 0));4836
fake.set_chat_messages(messages);4837
store.upsert_messages(&[stale_forward(CHAT, "m0000", 0)]).unwrap();4838
assert_eq!(forward_state(&store, CHAT, "m0000"), teams_core::ForwardState::Loading);4839
4840
engine.fetch_newer(CHAT).await.unwrap();4841
4842
assert_eq!(forward_state(&store, CHAT, "m0000"), teams_core::ForwardState::Unavailable);4843
let next_session = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());4844
next_session.fetch_newer(CHAT).await.unwrap();4845
let reads = fake4846
.calls()4847
.iter()4848
.filter(|call| *call == "chat_message m0000")4849
.count();4850
assert_eq!(reads, 1);4851
}4852
4853
#[tokio::test]4854
async fn the_background_heal_reads_the_newest_chat_first_and_skips_healthy_chats() {4855
const OLDER: &str = "19:older@thread.v2";4856
const HEALTHY: &str = "19:healthy@thread.v2";4857
let fake = Arc::new(Fake::default());4858
*fake.chats.lock().unwrap() = vec![4859
chat(OLDER, Some("Older"), 2, 2, ME, false),4860
chat(CHAT, Some("Newer"), 9, 9, ME, false),4861
chat(HEALTHY, Some("Healthy"), 12, 12, ME, false),4862
];4863
let store = Arc::new(Store::open_in_memory().unwrap());4864
let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());4865
engine.refresh_sidebar().await.unwrap();4866
fake.set_chat_messages(vec![4867
forwarded_message("f-older", 1),4868
forwarded_message("f-newer", 8),4869
]);4870
let healthy = teams_core::message_record(HEALTHY, &forwarded_message("f-healthy", 11)).unwrap();4871
store4872
.upsert_messages(&[4873
stale_forward(OLDER, "f-older", 1),4874
stale_forward(CHAT, "f-newer", 8),4875
healthy,4876
])4877
.unwrap();4878
let mut events = engine.subscribe();4879
4880
engine.heal_all_forwards(std::time::Duration::ZERO).await;4881
4882
let reads: Vec<String> = fake4883
.calls()4884
.into_iter()4885
.filter(|call| call.starts_with("chat_message "))4886
.collect();4887
assert_eq!(reads, ["chat_message f-newer", "chat_message f-older"]);4888
assert_eq!(forward_state(&store, OLDER, "f-older"), teams_core::ForwardState::Ready);4889
let mut changed = Vec::new();4890
while let Ok(event) = events.try_recv() {4891
if let CoreEvent::MessagesChanged { conversation_id } = event {4892
changed.push(conversation_id);4893
}4894
}4895
assert_eq!(changed, [CHAT, OLDER]);4896
}@@ -14,6 +14,7 @@ mod models;
14
14
mod outbox;
15
15
mod presence;
16
16
mod proposals;
17
mod read_horizons;
17
18
mod search;
18
19
mod sidebar;
19
20
mod store;
@@ -29,8 +30,8 @@ pub use models::{
29
30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelNotificationLevel,
30
31
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
31
32
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
32
OutboxRecord, OutboxState, OutboxTarget, RecentScope, SearchHit, Sidebar, SidebarTeam,
33
SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME, is_bot_id,
33
OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,
34
SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME, is_bot_id,
34
35
};
35
36
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
36
37
pub use store::{DATA_DIR_NAME, Store, default_database_path};
@@ -14,6 +14,7 @@ mod models;14
mod outbox;14
mod outbox;15
mod presence;15
mod presence;16
mod proposals;16
mod proposals;17
mod read_horizons;17
mod search;18
mod search;18
mod sidebar;19
mod sidebar;19
mod store;20
mod store;@@ -29,8 +30,8 @@ pub use models::{29
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelNotificationLevel,30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelNotificationLevel,30
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,31
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,31
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,32
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,32
OutboxRecord, OutboxState, OutboxTarget, RecentScope, SearchHit, Sidebar, SidebarTeam,33
OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,33
SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME, is_bot_id,34
SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME, is_bot_id,34
};35
};35
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};36
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};36
pub use store::{DATA_DIR_NAME, Store, default_database_path};37
pub use store::{DATA_DIR_NAME, Store, default_database_path};@@ -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,@@ -93,6 +93,10 @@ const MIGRATIONS: &[Migration] = &[
93
93
script: include_str!("migrations/0021_recording_events.sql"),
94
94
after: None,
95
95
},
96
Migration {
97
script: include_str!("migrations/0022_read_horizons.sql"),
98
after: None,
99
},
96
100
];
97
101
98
102
pub fn latest_version() -> i64 {
@@ -93,6 +93,10 @@ const MIGRATIONS: &[Migration] = &[93
script: include_str!("migrations/0021_recording_events.sql"),93
script: include_str!("migrations/0021_recording_events.sql"),94
after: None,94
after: None,95
},95
},96
Migration {97
script: include_str!("migrations/0022_read_horizons.sql"),98
after: None,99
},96
];100
];97
101
98
pub fn latest_version() -> i64 {102
pub fn latest_version() -> i64 {@@ -0,0 +1,7 @@
1
CREATE TABLE IF NOT EXISTS read_horizons (
2
conversation_id TEXT NOT NULL,
3
member_id TEXT NOT NULL,
4
read_until INTEGER NOT NULL,
5
read_at INTEGER,
6
PRIMARY KEY (conversation_id, member_id)
7
);
@@ -0,0 +1,7 @@1
CREATE TABLE IF NOT EXISTS read_horizons (2
conversation_id TEXT NOT NULL,3
member_id TEXT NOT NULL,4
read_until INTEGER NOT NULL,5
read_at INTEGER,6
PRIMARY KEY (conversation_id, member_id)7
);@@ -111,6 +111,14 @@ pub struct RecentScope {
111
111
pub after: DateTime<Utc>,
112
112
}
113
113
114
/// The last read position of one conversation member, as chatsvc reports it.
115
#[derive(Debug, Clone, PartialEq, Eq)]
116
pub struct ReadHorizonRecord {
117
pub member_id: String,
118
pub read_until: DateTime<Utc>,
119
pub read_at: Option<DateTime<Utc>>,
120
}
121
114
122
#[derive(Debug, Clone, PartialEq)]
115
123
pub struct SyncState {
116
124
pub newest_seen: Option<DateTime<Utc>>,
@@ -111,6 +111,14 @@ pub struct RecentScope {111
pub after: DateTime<Utc>,111
pub after: DateTime<Utc>,112
}112
}113
113
114
/// The last read position of one conversation member, as chatsvc reports it.115
#[derive(Debug, Clone, PartialEq, Eq)]116
pub struct ReadHorizonRecord {117
pub member_id: String,118
pub read_until: DateTime<Utc>,119
pub read_at: Option<DateTime<Utc>>,120
}121
114
#[derive(Debug, Clone, PartialEq)]122
#[derive(Debug, Clone, PartialEq)]115
pub struct SyncState {123
pub struct SyncState {116
pub newest_seen: Option<DateTime<Utc>>,124
pub newest_seen: Option<DateTime<Utc>>,@@ -0,0 +1,56 @@
1
use rusqlite::params;
2
3
use crate::error::Result;
4
use crate::models::ReadHorizonRecord;
5
use crate::store::Store;
6
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
7
8
impl Store {
9
pub fn read_horizons(&self, conversation_id: &str) -> Result<Vec<ReadHorizonRecord>> {
10
let connection = self.lock()?;
11
let mut statement = connection.prepare_cached(
12
"SELECT member_id, read_until, read_at FROM read_horizons
13
WHERE conversation_id = ?1 ORDER BY member_id",
14
)?;
15
let rows = statement.query_map([conversation_id], |row| {
16
Ok(ReadHorizonRecord {
17
member_id: row.get(0)?,
18
read_until: from_millis(row.get(1)?),
19
read_at: optional_from_millis(row.get(2)?),
20
})
21
})?;
22
Ok(rows.collect::<rusqlite::Result<_>>()?)
23
}
24
25
/// Replaces every stored horizon of the conversation.
26
pub fn set_read_horizons(
27
&self,
28
conversation_id: &str,
29
horizons: &[ReadHorizonRecord],
30
) -> Result<()> {
31
let mut connection = self.lock()?;
32
let transaction = connection.transaction()?;
33
transaction.execute(
34
"DELETE FROM read_horizons WHERE conversation_id = ?1",
35
[conversation_id],
36
)?;
37
{
38
let mut statement = transaction.prepare_cached(
39
"INSERT INTO read_horizons (conversation_id, member_id, read_until, read_at)
40
VALUES (?1, ?2, ?3, ?4)
41
ON CONFLICT (conversation_id, member_id) DO UPDATE SET
42
read_until = excluded.read_until, read_at = excluded.read_at",
43
)?;
44
for horizon in horizons {
45
statement.execute(params![
46
conversation_id,
47
horizon.member_id,
48
to_millis(horizon.read_until),
49
optional_to_millis(horizon.read_at),
50
])?;
51
}
52
}
53
transaction.commit()?;
54
Ok(())
55
}
56
}
@@ -0,0 +1,56 @@1
use rusqlite::params;2
3
use crate::error::Result;4
use crate::models::ReadHorizonRecord;5
use crate::store::Store;6
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};7
8
impl Store {9
pub fn read_horizons(&self, conversation_id: &str) -> Result<Vec<ReadHorizonRecord>> {10
let connection = self.lock()?;11
let mut statement = connection.prepare_cached(12
"SELECT member_id, read_until, read_at FROM read_horizons13
WHERE conversation_id = ?1 ORDER BY member_id",14
)?;15
let rows = statement.query_map([conversation_id], |row| {16
Ok(ReadHorizonRecord {17
member_id: row.get(0)?,18
read_until: from_millis(row.get(1)?),19
read_at: optional_from_millis(row.get(2)?),20
})21
})?;22
Ok(rows.collect::<rusqlite::Result<_>>()?)23
}24
25
/// Replaces every stored horizon of the conversation.26
pub fn set_read_horizons(27
&self,28
conversation_id: &str,29
horizons: &[ReadHorizonRecord],30
) -> Result<()> {31
let mut connection = self.lock()?;32
let transaction = connection.transaction()?;33
transaction.execute(34
"DELETE FROM read_horizons WHERE conversation_id = ?1",35
[conversation_id],36
)?;37
{38
let mut statement = transaction.prepare_cached(39
"INSERT INTO read_horizons (conversation_id, member_id, read_until, read_at)40
VALUES (?1, ?2, ?3, ?4)41
ON CONFLICT (conversation_id, member_id) DO UPDATE SET42
read_until = excluded.read_until, read_at = excluded.read_at",43
)?;44
for horizon in horizons {45
statement.execute(params![46
conversation_id,47
horizon.member_id,48
to_millis(horizon.read_until),49
optional_to_millis(horizon.read_at),50
])?;51
}52
}53
transaction.commit()?;54
Ok(())55
}56
}@@ -3,7 +3,8 @@ use rusqlite::Connection;
3
3
use store::{
4
4
AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,
5
5
ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
6
MessageRecord, RecentScope, Store, SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,
6
MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,
7
TeamRecord, UNKNOWN_USER_NAME,
7
8
};
8
9
9
10
#[test]
@@ -545,11 +546,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
545
546
let path = directory.path().join("nested").join("cache.sqlite3");
546
547
{
547
548
let store = Store::open(&path).unwrap();
548
assert_eq!(store.schema_version().unwrap(), 21);
549
assert_eq!(store.schema_version().unwrap(), 22);
549
550
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
550
551
}
551
552
let reopened = Store::open(&path).unwrap();
552
assert_eq!(reopened.schema_version().unwrap(), 21);
553
assert_eq!(reopened.schema_version().unwrap(), 22);
553
554
assert_eq!(reopened.message_count("c").unwrap(), 1);
554
555
drop(reopened);
555
556
let mode: String = rusqlite_open(&path)
@@ -581,7 +582,7 @@ fn old_schema_is_upgraded_in_place() {
581
582
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
582
583
drop(connection);
583
584
let store = Store::open(&path).unwrap();
584
assert_eq!(store.schema_version().unwrap(), 21);
585
assert_eq!(store.schema_version().unwrap(), 22);
585
586
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
586
587
}
587
588
@@ -647,7 +648,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
647
648
let store = Store::open(&path).unwrap();
648
649
let state = store.sync_state("c").unwrap().unwrap();
649
650
assert_eq!(state.delta_link, None);
650
assert_eq!(store.schema_version().unwrap(), 21);
651
assert_eq!(store.schema_version().unwrap(), 22);
651
652
}
652
653
653
654
#[test]
@@ -1420,7 +1421,7 @@ fn migration_to_v20_adds_the_call_event_column() {
1420
1421
.unwrap();
1421
1422
}
1422
1423
let store = Store::open(&path).unwrap();
1423
assert_eq!(store.schema_version().unwrap(), 21);
1424
assert_eq!(store.schema_version().unwrap(), 22);
1424
1425
let old = store.messages("c", None, 10).unwrap();
1425
1426
assert_eq!(old[0].call_event_json, None);
1426
1427
assert!(store.sync_state("c").unwrap().is_none());
@@ -1464,8 +1465,51 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1464
1465
.unwrap();
1465
1466
}
1466
1467
let store = Store::open(&path).unwrap();
1467
assert_eq!(store.schema_version().unwrap(), 21);
1468
assert_eq!(store.schema_version().unwrap(), 22);
1468
1469
assert!(store.sync_state("c").unwrap().is_none());
1469
1470
assert!(store.sync_state("channel").unwrap().is_none());
1470
1471
assert!(store.sync_state("other").unwrap().is_some());
1471
1472
}
1473
1474
fn horizon(member_id: &str, read_minute: u32, at_minute: Option<u32>) -> ReadHorizonRecord {
1475
ReadHorizonRecord {
1476
member_id: member_id.to_owned(),
1477
read_until: at(read_minute),
1478
read_at: at_minute.map(at),
1479
}
1480
}
1481
1482
#[test]
1483
fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1484
let directory = tempfile::tempdir().unwrap();
1485
let path = directory.path().join("old.sqlite3");
1486
{
1487
let store = Store::open(&path).unwrap();
1488
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1489
drop(store);
1490
Connection::open(&path)
1491
.unwrap()
1492
.execute_batch("DROP TABLE read_horizons; PRAGMA user_version = 21")
1493
.unwrap();
1494
}
1495
let store = Store::open(&path).unwrap();
1496
assert_eq!(store.schema_version().unwrap(), 22);
1497
assert!(store.read_horizons("c").unwrap().is_empty());
1498
let horizons = [horizon("8:orgid:ada", 3, Some(4)), horizon("8:orgid:bob", 2, None)];
1499
store.set_read_horizons("c", &horizons).unwrap();
1500
drop(store);
1501
let reopened = Store::open(&path).unwrap();
1502
assert_eq!(reopened.read_horizons("c").unwrap(), horizons);
1503
}
1504
1505
#[test]
1506
fn setting_read_horizons_replaces_the_conversation_only() {
1507
let store = Store::open_in_memory().unwrap();
1508
let first = [horizon("8:orgid:ada", 3, None), horizon("8:orgid:bob", 2, None)];
1509
store.set_read_horizons("c", &first).unwrap();
1510
store.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)]).unwrap();
1511
let second = [horizon("8:orgid:ada", 5, Some(6))];
1512
store.set_read_horizons("c", &second).unwrap();
1513
assert_eq!(store.read_horizons("c").unwrap(), second);
1514
assert_eq!(store.read_horizons("other").unwrap().len(), 1);
1515
}
@@ -3,7 +3,8 @@ use rusqlite::Connection;3
use store::{3
use store::{4
AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,4
AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,5
ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,5
ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,6
MessageRecord, RecentScope, Store, SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,6
MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,7
TeamRecord, UNKNOWN_USER_NAME,7
};8
};8
9
9
#[test]10
#[test]@@ -545,11 +546,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {545
let path = directory.path().join("nested").join("cache.sqlite3");546
let path = directory.path().join("nested").join("cache.sqlite3");546
{547
{547
let store = Store::open(&path).unwrap();548
let store = Store::open(&path).unwrap();548
assert_eq!(store.schema_version().unwrap(), 21);549
assert_eq!(store.schema_version().unwrap(), 22);549
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();550
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();550
}551
}551
let reopened = Store::open(&path).unwrap();552
let reopened = Store::open(&path).unwrap();552
assert_eq!(reopened.schema_version().unwrap(), 21);553
assert_eq!(reopened.schema_version().unwrap(), 22);553
assert_eq!(reopened.message_count("c").unwrap(), 1);554
assert_eq!(reopened.message_count("c").unwrap(), 1);554
drop(reopened);555
drop(reopened);555
let mode: String = rusqlite_open(&path)556
let mode: String = rusqlite_open(&path)@@ -581,7 +582,7 @@ fn old_schema_is_upgraded_in_place() {581
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();582
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();582
drop(connection);583
drop(connection);583
let store = Store::open(&path).unwrap();584
let store = Store::open(&path).unwrap();584
assert_eq!(store.schema_version().unwrap(), 21);585
assert_eq!(store.schema_version().unwrap(), 22);585
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();586
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();586
}587
}587
588
@@ -647,7 +648,7 @@ fn migration_to_v2_keeps_existing_sync_state() {647
let store = Store::open(&path).unwrap();648
let store = Store::open(&path).unwrap();648
let state = store.sync_state("c").unwrap().unwrap();649
let state = store.sync_state("c").unwrap().unwrap();649
assert_eq!(state.delta_link, None);650
assert_eq!(state.delta_link, None);650
assert_eq!(store.schema_version().unwrap(), 21);651
assert_eq!(store.schema_version().unwrap(), 22);651
}652
}652
653
653
#[test]654
#[test]@@ -1420,7 +1421,7 @@ fn migration_to_v20_adds_the_call_event_column() {1420
.unwrap();1421
.unwrap();1421
}1422
}1422
let store = Store::open(&path).unwrap();1423
let store = Store::open(&path).unwrap();1423
assert_eq!(store.schema_version().unwrap(), 21);1424
assert_eq!(store.schema_version().unwrap(), 22);1424
let old = store.messages("c", None, 10).unwrap();1425
let old = store.messages("c", None, 10).unwrap();1425
assert_eq!(old[0].call_event_json, None);1426
assert_eq!(old[0].call_event_json, None);1426
assert!(store.sync_state("c").unwrap().is_none());1427
assert!(store.sync_state("c").unwrap().is_none());@@ -1464,8 +1465,51 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {1464
.unwrap();1465
.unwrap();1465
}1466
}1466
let store = Store::open(&path).unwrap();1467
let store = Store::open(&path).unwrap();1467
assert_eq!(store.schema_version().unwrap(), 21);1468
assert_eq!(store.schema_version().unwrap(), 22);1468
assert!(store.sync_state("c").unwrap().is_none());1469
assert!(store.sync_state("c").unwrap().is_none());1469
assert!(store.sync_state("channel").unwrap().is_none());1470
assert!(store.sync_state("channel").unwrap().is_none());1470
assert!(store.sync_state("other").unwrap().is_some());1471
assert!(store.sync_state("other").unwrap().is_some());1471
}1472
}1473
1474
fn horizon(member_id: &str, read_minute: u32, at_minute: Option<u32>) -> ReadHorizonRecord {1475
ReadHorizonRecord {1476
member_id: member_id.to_owned(),1477
read_until: at(read_minute),1478
read_at: at_minute.map(at),1479
}1480
}1481
1482
#[test]1483
fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {1484
let directory = tempfile::tempdir().unwrap();1485
let path = directory.path().join("old.sqlite3");1486
{1487
let store = Store::open(&path).unwrap();1488
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();1489
drop(store);1490
Connection::open(&path)1491
.unwrap()1492
.execute_batch("DROP TABLE read_horizons; PRAGMA user_version = 21")1493
.unwrap();1494
}1495
let store = Store::open(&path).unwrap();1496
assert_eq!(store.schema_version().unwrap(), 22);1497
assert!(store.read_horizons("c").unwrap().is_empty());1498
let horizons = [horizon("8:orgid:ada", 3, Some(4)), horizon("8:orgid:bob", 2, None)];1499
store.set_read_horizons("c", &horizons).unwrap();1500
drop(store);1501
let reopened = Store::open(&path).unwrap();1502
assert_eq!(reopened.read_horizons("c").unwrap(), horizons);1503
}1504
1505
#[test]1506
fn setting_read_horizons_replaces_the_conversation_only() {1507
let store = Store::open_in_memory().unwrap();1508
let first = [horizon("8:orgid:ada", 3, None), horizon("8:orgid:bob", 2, None)];1509
store.set_read_horizons("c", &first).unwrap();1510
store.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)]).unwrap();1511
let second = [horizon("8:orgid:ada", 5, Some(6))];1512
store.set_read_horizons("c", &second).unwrap();1513
assert_eq!(store.read_horizons("c").unwrap(), second);1514
assert_eq!(store.read_horizons("other").unwrap().len(), 1);1515
}