Merge remote-tracking branch 'origin/main' into feat/substrate-search
# Conflicts: # crates/core/tests/engine.rs
@@ -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
);@@ -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
}
@@ -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
}@@ -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]@@ -145,7 +145,8 @@ pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
145
145
pub use scheduled::NOTES_CHAT_ID;
146
146
pub use skin_tone::{skin_tone, store_account_skin_tone};
147
147
pub use forwarded::{
148
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,
149
150
};
150
151
pub use spans::{FontSize, Span, html_to_spans};
151
152
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
@@ -145,7 +145,8 @@ pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};145
pub use scheduled::NOTES_CHAT_ID;145
pub use scheduled::NOTES_CHAT_ID;146
pub use skin_tone::{skin_tone, store_account_skin_tone};146
pub use skin_tone::{skin_tone, store_account_skin_tone};147
pub use forwarded::{147
pub use forwarded::{148
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,149
};150
};150
pub use spans::{FontSize, Span, html_to_spans};151
pub use spans::{FontSize, Span, html_to_spans};151
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};152
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};@@ -239,6 +239,7 @@ pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {
239
239
Some("messageReference" | FORWARDED_CONTENT_TYPE)
240
240
)
241
241
}),
242
unavailable: false,
242
243
}
243
244
}
244
245
@@ -239,6 +239,7 @@ pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {239
Some("messageReference" | FORWARDED_CONTENT_TYPE)239
Some("messageReference" | FORWARDED_CONTENT_TYPE)240
)240
)241
}),241
}),242
unavailable: false,242
}243
}243
}244
}244
245
@@ -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)?@@ -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
};@@ -3872,6 +3872,27 @@ async fn one_on_one_read_up_to_horizon() {
3872
3872
);
3873
3873
}
3874
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
3875
3896
#[tokio::test]
3876
3897
async fn horizon_equal_to_creation_time_counts_as_read() {
3877
3898
let fake = Arc::new(Fake::default());
@@ -4777,3 +4798,99 @@ async fn server_search_is_anchored_to_my_user_and_tenant() {
4777
4798
};
4778
4799
assert_eq!(identities, [expected.clone(), expected]);
4779
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
}
@@ -3872,6 +3872,27 @@ async fn one_on_one_read_up_to_horizon() {3872
);3872
);3873
}3873
}3874
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
3875
#[tokio::test]3896
#[tokio::test]3876
async fn horizon_equal_to_creation_time_counts_as_read() {3897
async fn horizon_equal_to_creation_time_counts_as_read() {3877
let fake = Arc::new(Fake::default());3898
let fake = Arc::new(Fake::default());@@ -4777,3 +4798,99 @@ async fn server_search_is_anchored_to_my_user_and_tenant() {4777
};4798
};4778
assert_eq!(identities, [expected.clone(), expected]);4799
assert_eq!(identities, [expected.clone(), expected]);4779
}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, is_bot_id,
33
OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,
34
SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, 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, is_bot_id,34
SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, 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
);@@ -110,6 +110,14 @@ pub struct RecentScope {
110
110
pub after: DateTime<Utc>,
111
111
}
112
112
113
/// The last read position of one conversation member, as chatsvc reports it.
114
#[derive(Debug, Clone, PartialEq, Eq)]
115
pub struct ReadHorizonRecord {
116
pub member_id: String,
117
pub read_until: DateTime<Utc>,
118
pub read_at: Option<DateTime<Utc>>,
119
}
120
113
121
#[derive(Debug, Clone, PartialEq)]
114
122
pub struct SyncState {
115
123
pub newest_seen: Option<DateTime<Utc>>,
@@ -110,6 +110,14 @@ pub struct RecentScope {110
pub after: DateTime<Utc>,110
pub after: DateTime<Utc>,111
}111
}112
112
113
/// The last read position of one conversation member, as chatsvc reports it.114
#[derive(Debug, Clone, PartialEq, Eq)]115
pub struct ReadHorizonRecord {116
pub member_id: String,117
pub read_until: DateTime<Utc>,118
pub read_at: Option<DateTime<Utc>>,119
}120
113
#[derive(Debug, Clone, PartialEq)]121
#[derive(Debug, Clone, PartialEq)]114
pub struct SyncState {122
pub struct SyncState {115
pub newest_seen: Option<DateTime<Utc>>,123
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,
6
MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,
7
TeamRecord,
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]
@@ -1413,7 +1414,7 @@ fn migration_to_v20_adds_the_call_event_column() {
1413
1414
.unwrap();
1414
1415
}
1415
1416
let store = Store::open(&path).unwrap();
1416
assert_eq!(store.schema_version().unwrap(), 21);
1417
assert_eq!(store.schema_version().unwrap(), 22);
1417
1418
let old = store.messages("c", None, 10).unwrap();
1418
1419
assert_eq!(old[0].call_event_json, None);
1419
1420
assert!(store.sync_state("c").unwrap().is_none());
@@ -1457,8 +1458,51 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1457
1458
.unwrap();
1458
1459
}
1459
1460
let store = Store::open(&path).unwrap();
1460
assert_eq!(store.schema_version().unwrap(), 21);
1461
assert_eq!(store.schema_version().unwrap(), 22);
1461
1462
assert!(store.sync_state("c").unwrap().is_none());
1462
1463
assert!(store.sync_state("channel").unwrap().is_none());
1463
1464
assert!(store.sync_state("other").unwrap().is_some());
1464
1465
}
1466
1467
fn horizon(member_id: &str, read_minute: u32, at_minute: Option<u32>) -> ReadHorizonRecord {
1468
ReadHorizonRecord {
1469
member_id: member_id.to_owned(),
1470
read_until: at(read_minute),
1471
read_at: at_minute.map(at),
1472
}
1473
}
1474
1475
#[test]
1476
fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1477
let directory = tempfile::tempdir().unwrap();
1478
let path = directory.path().join("old.sqlite3");
1479
{
1480
let store = Store::open(&path).unwrap();
1481
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1482
drop(store);
1483
Connection::open(&path)
1484
.unwrap()
1485
.execute_batch("DROP TABLE read_horizons; PRAGMA user_version = 21")
1486
.unwrap();
1487
}
1488
let store = Store::open(&path).unwrap();
1489
assert_eq!(store.schema_version().unwrap(), 22);
1490
assert!(store.read_horizons("c").unwrap().is_empty());
1491
let horizons = [horizon("8:orgid:ada", 3, Some(4)), horizon("8:orgid:bob", 2, None)];
1492
store.set_read_horizons("c", &horizons).unwrap();
1493
drop(store);
1494
let reopened = Store::open(&path).unwrap();
1495
assert_eq!(reopened.read_horizons("c").unwrap(), horizons);
1496
}
1497
1498
#[test]
1499
fn setting_read_horizons_replaces_the_conversation_only() {
1500
let store = Store::open_in_memory().unwrap();
1501
let first = [horizon("8:orgid:ada", 3, None), horizon("8:orgid:bob", 2, None)];
1502
store.set_read_horizons("c", &first).unwrap();
1503
store.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)]).unwrap();
1504
let second = [horizon("8:orgid:ada", 5, Some(6))];
1505
store.set_read_horizons("c", &second).unwrap();
1506
assert_eq!(store.read_horizons("c").unwrap(), second);
1507
assert_eq!(store.read_horizons("other").unwrap().len(), 1);
1508
}
@@ -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,6
MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,7
TeamRecord,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]@@ -1413,7 +1414,7 @@ fn migration_to_v20_adds_the_call_event_column() {1413
.unwrap();1414
.unwrap();1414
}1415
}1415
let store = Store::open(&path).unwrap();1416
let store = Store::open(&path).unwrap();1416
assert_eq!(store.schema_version().unwrap(), 21);1417
assert_eq!(store.schema_version().unwrap(), 22);1417
let old = store.messages("c", None, 10).unwrap();1418
let old = store.messages("c", None, 10).unwrap();1418
assert_eq!(old[0].call_event_json, None);1419
assert_eq!(old[0].call_event_json, None);1419
assert!(store.sync_state("c").unwrap().is_none());1420
assert!(store.sync_state("c").unwrap().is_none());@@ -1457,8 +1458,51 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {1457
.unwrap();1458
.unwrap();1458
}1459
}1459
let store = Store::open(&path).unwrap();1460
let store = Store::open(&path).unwrap();1460
assert_eq!(store.schema_version().unwrap(), 21);1461
assert_eq!(store.schema_version().unwrap(), 22);1461
assert!(store.sync_state("c").unwrap().is_none());1462
assert!(store.sync_state("c").unwrap().is_none());1462
assert!(store.sync_state("channel").unwrap().is_none());1463
assert!(store.sync_state("channel").unwrap().is_none());1463
assert!(store.sync_state("other").unwrap().is_some());1464
assert!(store.sync_state("other").unwrap().is_some());1464
}1465
}1466
1467
fn horizon(member_id: &str, read_minute: u32, at_minute: Option<u32>) -> ReadHorizonRecord {1468
ReadHorizonRecord {1469
member_id: member_id.to_owned(),1470
read_until: at(read_minute),1471
read_at: at_minute.map(at),1472
}1473
}1474
1475
#[test]1476
fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {1477
let directory = tempfile::tempdir().unwrap();1478
let path = directory.path().join("old.sqlite3");1479
{1480
let store = Store::open(&path).unwrap();1481
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();1482
drop(store);1483
Connection::open(&path)1484
.unwrap()1485
.execute_batch("DROP TABLE read_horizons; PRAGMA user_version = 21")1486
.unwrap();1487
}1488
let store = Store::open(&path).unwrap();1489
assert_eq!(store.schema_version().unwrap(), 22);1490
assert!(store.read_horizons("c").unwrap().is_empty());1491
let horizons = [horizon("8:orgid:ada", 3, Some(4)), horizon("8:orgid:bob", 2, None)];1492
store.set_read_horizons("c", &horizons).unwrap();1493
drop(store);1494
let reopened = Store::open(&path).unwrap();1495
assert_eq!(reopened.read_horizons("c").unwrap(), horizons);1496
}1497
1498
#[test]1499
fn setting_read_horizons_replaces_the_conversation_only() {1500
let store = Store::open_in_memory().unwrap();1501
let first = [horizon("8:orgid:ada", 3, None), horizon("8:orgid:bob", 2, None)];1502
store.set_read_horizons("c", &first).unwrap();1503
store.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)]).unwrap();1504
let second = [horizon("8:orgid:ada", 5, Some(6))];1505
store.set_read_horizons("c", &second).unwrap();1506
assert_eq!(store.read_horizons("c").unwrap(), second);1507
assert_eq!(store.read_horizons("other").unwrap().len(), 1);1508
}