feat(chat): chat menu with mark as unread, mute, hide and leave
- Menu grouped with icons: Pin, Move to folder | Mark as read/unread, Mute/Unmute | Hide, Leave chat... (red, group chats only) - Mute: chatsvc conversation property alerts=false, read from the first conversations page on every sidebar refresh - Muted chats stay in place with a bell-off icon and a grey badge; no toast, sound or taskbar count unless I am @mentioned - Mark as unread: Graph markChatUnreadForUser one ms before the last message; an open chat stays unread until I leave it - Hide: Graph hideForUser, status bar notice with Undo - Leave: confirm dialog, Enter does not leave; Graph removes my membership - App-level status bar notice with optional action and 6 s timeout; pane notices now use it - Every action is optimistic and reverts with a notice on failure Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -10,6 +10,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
10
10
## Features
11
11
12
12
- Chats and channels, with the Teams pin order, chat folders and hidden teams
13
- Chat menu: pin, move to folder, mark as unread, mute, hide, leave
13
14
- Live updates over the Teams realtime socket, no polling
14
15
- Send, edit, delete, react, quote-reply, @mentions
15
16
- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
@@ -10,6 +10,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R10
## Features10
## Features11
11
12
- Chats and channels, with the Teams pin order, chat folders and hidden teams12
- Chats and channels, with the Teams pin order, chat folders and hidden teams13
- Chat menu: pin, move to folder, mark as unread, mute, hide, leave13
- Live updates over the Teams realtime socket, no polling14
- Live updates over the Teams realtime socket, no polling14
- Send, edit, delete, react, quote-reply, @mentions15
- Send, edit, delete, react, quote-reply, @mentions15
- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste16
- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste@@ -2,19 +2,19 @@
2
2
3
3
Feature parity with the Microsoft Teams desktop client.
4
4
5
**Parity: 59 %** (48 done, 4 partial, 33 missing of 85). Partial counts half.
5
**Parity: 64 %** (52 done, 4 partial, 29 missing of 85). Partial counts half.
6
6
7
7
## By area
8
8
9
9
| Area | Parity | Done | Partial | Missing |
10
10
|---|---|---|---|---|
11
11
| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12
| [Chat list](#chat-list) | 60 % | 6 | 0 | 4 |
12
| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13
13
| [Reading](#reading) | 71 % | 13 | 1 | 5 |
14
14
| [Writing](#writing) | 75 % | 10 | 1 | 3 |
15
15
| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16
16
| [Channels](#channels) | 36 % | 2 | 1 | 4 |
17
| [Notifications](#notifications) | 75 % | 6 | 0 | 2 |
17
| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
18
18
| [Search and navigation](#search-and-navigation) | 75 % | 3 | 0 | 1 |
19
19
| [Presence and people](#presence-and-people) | 50 % | 2 | 0 | 2 |
20
20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
@@ -26,11 +26,10 @@ Feature parity with the Microsoft Teams desktop client.
26
26
|---|---|---|
27
27
| 1 | Channel: new post with subject, post cards | |
28
28
| 2 | Sign in on Linux without Chrome on a debug port | |
29
| 3 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |
30
| 4 | Emoji picker in the composer | Reaction picker exists |
31
| 5 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
32
| 6 | Typing indicator | |
33
| 7 | Unsent messages survive a restart | |
29
| 3 | Emoji picker in the composer | Reaction picker exists |
30
| 4 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
31
| 5 | Typing indicator | |
32
| 6 | Unsent messages survive a restart | |
34
33
35
34
## Sign-in and app
36
35
@@ -53,9 +52,9 @@ Feature parity with the Microsoft Teams desktop client.
53
52
| Hidden teams | Done | |
54
53
| Unread bold, unread count, mention marker | Done | |
55
54
| New chat: 1:1 and group with title | Done | |
56
| Mark as unread | Missing | |
57
| Mute chat | Missing | |
58
| Hide chat, leave chat | Missing | |
55
| Mark as unread | Done | Keeps the open chat unread until you switch |
56
| Mute chat | Done | Synced with Teams, muted rows stay in place with a bell |
57
| Hide chat, leave chat | Done | Hide has Undo; leave only for group chats, with a confirmation |
59
58
| Muted and Meeting chat sections | Missing | Teams rollout Aug-Sep 2026 |
60
59
61
60
## Reading
@@ -132,7 +131,7 @@ Feature parity with the Microsoft Teams desktop client.
132
131
| Quiet during Do not disturb, Focus Assist, calls | Done | |
133
132
| Mentions-only mode, preview off | Done | |
134
133
| Stack of 3, queue, Hide all, fade-out | Done | |
135
| Muted chats stay quiet | Missing | Needs Mute chat |
134
| Muted chats stay quiet | Done | Toast, sound and taskbar badge only for @mentions |
136
135
| Notifications on Linux | Missing | |
137
136
138
137
## Search and navigation
@@ -2,19 +2,19 @@2
2
3
Feature parity with the Microsoft Teams desktop client.3
Feature parity with the Microsoft Teams desktop client.4
4
5
**Parity: 59 %** (48 done, 4 partial, 33 missing of 85). Partial counts half.5
**Parity: 64 %** (52 done, 4 partial, 29 missing of 85). Partial counts half.6
6
7
## By area7
## By area8
8
9
| Area | Parity | Done | Partial | Missing |9
| Area | Parity | Done | Partial | Missing |10
|---|---|---|---|---|10
|---|---|---|---|---|11
| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |11
| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |12
| [Chat list](#chat-list) | 60 % | 6 | 0 | 4 |12
| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |13
| [Reading](#reading) | 71 % | 13 | 1 | 5 |13
| [Reading](#reading) | 71 % | 13 | 1 | 5 |14
| [Writing](#writing) | 75 % | 10 | 1 | 3 |14
| [Writing](#writing) | 75 % | 10 | 1 | 3 |15
| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |15
| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |16
| [Channels](#channels) | 36 % | 2 | 1 | 4 |16
| [Channels](#channels) | 36 % | 2 | 1 | 4 |17
| [Notifications](#notifications) | 75 % | 6 | 0 | 2 |17
| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |18
| [Search and navigation](#search-and-navigation) | 75 % | 3 | 0 | 1 |18
| [Search and navigation](#search-and-navigation) | 75 % | 3 | 0 | 1 |19
| [Presence and people](#presence-and-people) | 50 % | 2 | 0 | 2 |19
| [Presence and people](#presence-and-people) | 50 % | 2 | 0 | 2 |20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |@@ -26,11 +26,10 @@ Feature parity with the Microsoft Teams desktop client.26
|---|---|---|26
|---|---|---|27
| 1 | Channel: new post with subject, post cards | |27
| 1 | Channel: new post with subject, post cards | |28
| 2 | Sign in on Linux without Chrome on a debug port | |28
| 2 | Sign in on Linux without Chrome on a debug port | |29
| 3 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |29
| 3 | Emoji picker in the composer | Reaction picker exists |30
| 4 | Emoji picker in the composer | Reaction picker exists |30
| 4 | Keyboard: Ctrl+1..9, Alt+Up/Down | |31
| 5 | Keyboard: Ctrl+1..9, Alt+Up/Down | |31
| 5 | Typing indicator | |32
| 6 | Typing indicator | |32
| 6 | Unsent messages survive a restart | |33
| 7 | Unsent messages survive a restart | |34
33
35
## Sign-in and app34
## Sign-in and app36
35
@@ -53,9 +52,9 @@ Feature parity with the Microsoft Teams desktop client.53
| Hidden teams | Done | |52
| Hidden teams | Done | |54
| Unread bold, unread count, mention marker | Done | |53
| Unread bold, unread count, mention marker | Done | |55
| New chat: 1:1 and group with title | Done | |54
| New chat: 1:1 and group with title | Done | |56
| Mark as unread | Missing | |55
| Mark as unread | Done | Keeps the open chat unread until you switch |57
| Mute chat | Missing | |56
| Mute chat | Done | Synced with Teams, muted rows stay in place with a bell |58
| Hide chat, leave chat | Missing | |57
| Hide chat, leave chat | Done | Hide has Undo; leave only for group chats, with a confirmation |59
| Muted and Meeting chat sections | Missing | Teams rollout Aug-Sep 2026 |58
| Muted and Meeting chat sections | Missing | Teams rollout Aug-Sep 2026 |60
59
61
## Reading60
## Reading@@ -132,7 +131,7 @@ Feature parity with the Microsoft Teams desktop client.132
| Quiet during Do not disturb, Focus Assist, calls | Done | |131
| Quiet during Do not disturb, Focus Assist, calls | Done | |133
| Mentions-only mode, preview off | Done | |132
| Mentions-only mode, preview off | Done | |134
| Stack of 3, queue, Hide all, fade-out | Done | |133
| Stack of 3, queue, Hide all, fade-out | Done | |135
| Muted chats stay quiet | Missing | Needs Mute chat |134
| Muted chats stay quiet | Done | Toast, sound and taskbar badge only for @mentions |136
| Notifications on Linux | Missing | |135
| Notifications on Linux | Missing | |137
136
138
## Search and navigation137
## Search and navigation@@ -10,6 +10,7 @@ use teams_core::{ChatApp, CoreEvent, ImageRef};
10
10
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
11
11
use crate::card_state::{CardState, TaskDialogState};
12
12
use crate::data::{self, Directory};
13
use crate::notice::Notice;
13
14
use crate::notify;
14
15
15
16
const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
@@ -67,6 +68,9 @@ pub struct AppState {
67
68
pub task_dialog: Option<TaskDialogState>,
68
69
pub bot_apps: HashMap<String, Vec<ChatApp>>,
69
70
pub bot_apps_pending: HashSet<String>,
71
pub notice: Option<Notice>,
72
pub notice_count: u64,
73
pub keep_unread: Option<String>,
70
74
}
71
75
72
76
pub struct AppHandle(pub Entity<AppState>);
@@ -133,6 +137,9 @@ impl AppState {
133
137
task_dialog: None,
134
138
bot_apps: HashMap::new(),
135
139
bot_apps_pending: HashSet::new(),
140
notice: None,
141
notice_count: 0,
142
keep_unread: None,
136
143
};
137
144
state.collapsed = state.load_collapsed();
138
145
state.followed_channels = notify::load_followed_channels(&state.store);
@@ -378,6 +385,9 @@ impl AppState {
378
385
}
379
386
380
387
pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
388
if self.keeps_unread(conversation_id) {
389
self.keep_unread = None;
390
}
381
391
if self.mode.demo {
382
392
if let Some(chat) = self
383
393
.sidebar
@@ -428,6 +438,7 @@ impl AppState {
428
438
return;
429
439
}
430
440
self.selection = Some(selection);
441
self.keep_unread = None;
431
442
cx.emit(AppEvent::Selection);
432
443
cx.notify();
433
444
}
@@ -10,6 +10,7 @@ use teams_core::{ChatApp, CoreEvent, ImageRef};10
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};10
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};11
use crate::card_state::{CardState, TaskDialogState};11
use crate::card_state::{CardState, TaskDialogState};12
use crate::data::{self, Directory};12
use crate::data::{self, Directory};13
use crate::notice::Notice;13
use crate::notify;14
use crate::notify;14
15
15
const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";16
const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";@@ -67,6 +68,9 @@ pub struct AppState {67
pub task_dialog: Option<TaskDialogState>,68
pub task_dialog: Option<TaskDialogState>,68
pub bot_apps: HashMap<String, Vec<ChatApp>>,69
pub bot_apps: HashMap<String, Vec<ChatApp>>,69
pub bot_apps_pending: HashSet<String>,70
pub bot_apps_pending: HashSet<String>,71
pub notice: Option<Notice>,72
pub notice_count: u64,73
pub keep_unread: Option<String>,70
}74
}71
75
72
pub struct AppHandle(pub Entity<AppState>);76
pub struct AppHandle(pub Entity<AppState>);@@ -133,6 +137,9 @@ impl AppState {133
task_dialog: None,137
task_dialog: None,134
bot_apps: HashMap::new(),138
bot_apps: HashMap::new(),135
bot_apps_pending: HashSet::new(),139
bot_apps_pending: HashSet::new(),140
notice: None,141
notice_count: 0,142
keep_unread: None,136
};143
};137
state.collapsed = state.load_collapsed();144
state.collapsed = state.load_collapsed();138
state.followed_channels = notify::load_followed_channels(&state.store);145
state.followed_channels = notify::load_followed_channels(&state.store);@@ -378,6 +385,9 @@ impl AppState {378
}385
}379
386
380
pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {387
pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {388
if self.keeps_unread(conversation_id) {389
self.keep_unread = None;390
}381
if self.mode.demo {391
if self.mode.demo {382
if let Some(chat) = self392
if let Some(chat) = self383
.sidebar393
.sidebar@@ -428,6 +438,7 @@ impl AppState {428
return;438
return;429
}439
}430
self.selection = Some(selection);440
self.selection = Some(selection);441
self.keep_unread = None;431
cx.emit(AppEvent::Selection);442
cx.emit(AppEvent::Selection);432
cx.notify();443
cx.notify();433
}444
}@@ -0,0 +1,230 @@
1
use std::future::Future;
2
3
use chrono::{Duration, Local, Offset, Utc};
4
use gpui_kit::*;
5
use store::ChatRecord;
6
7
use crate::app_state::{AppState, Selection, chat_title};
8
use crate::notice::{NoticeAction, short_error, truncated};
9
use crate::sidebar_model::{SectionInput, build_sections, next_chat_id};
10
11
pub const TITLE_LIMIT: usize = 40;
12
13
impl AppState {
14
pub fn keeps_unread(&self, chat_id: &str) -> bool {
15
self.keep_unread.as_deref() == Some(chat_id)
16
}
17
18
pub fn mark_chat_unread(&mut self, chat_id: &str, cx: &mut Context<Self>) {
19
let Some(chat) = self.chat_record(chat_id) else {
20
return;
21
};
22
let Some(last_message_at) = chat.last_message_at else {
23
return;
24
};
25
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
26
return;
27
};
28
let last_read_at = last_message_at - Duration::milliseconds(1);
29
let _ = self.store.mark_chat_unread(chat_id, last_read_at);
30
if self.selection == Some(Selection::Chat(chat_id.to_owned())) {
31
self.keep_unread = Some(chat_id.to_owned());
32
}
33
self.reload_sidebar(cx);
34
let Some(engine) = engine_or_demo else {
35
return;
36
};
37
let owned_id = chat_id.to_owned();
38
let revert_id = owned_id.clone();
39
let restored_read_at = chat.last_read_at.unwrap_or(last_message_at);
40
self.run_chat_action(
41
"Mark as unread",
42
async move { engine.mark_unread(&owned_id).await },
43
move |state, cx| {
44
let _ = state.store.mark_chat_read(&revert_id, restored_read_at);
45
if state.keep_unread.as_deref() == Some(revert_id.as_str()) {
46
state.keep_unread = None;
47
}
48
state.reload_sidebar(cx);
49
},
50
|_, _| {},
51
cx,
52
);
53
}
54
55
pub fn set_chat_muted(&mut self, chat_id: &str, muted: bool, cx: &mut Context<Self>) {
56
if self.chat_record(chat_id).is_none() {
57
return;
58
}
59
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
60
return;
61
};
62
let _ = self.store.set_chat_muted(chat_id, muted);
63
self.reload_sidebar(cx);
64
let Some(engine) = engine_or_demo else {
65
return;
66
};
67
let owned_id = chat_id.to_owned();
68
let revert_id = owned_id.clone();
69
self.run_chat_action(
70
if muted { "Mute" } else { "Unmute" },
71
async move { engine.set_chat_muted(&owned_id, muted).await },
72
move |state, cx| {
73
let _ = state.store.set_chat_muted(&revert_id, !muted);
74
state.reload_sidebar(cx);
75
},
76
|_, _| {},
77
cx,
78
);
79
}
80
81
pub fn hide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {
82
let Some(chat) = self.chat_record(chat_id) else {
83
return;
84
};
85
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
86
return;
87
};
88
self.remove_chat_locally(chat_id, cx);
89
let Some(engine) = engine_or_demo else {
90
return;
91
};
92
let owned_id = chat_id.to_owned();
93
let undo_id = owned_id.clone();
94
let text = format!("\"{}\" hidden", truncated(&chat_title(&chat), TITLE_LIMIT));
95
self.run_chat_action(
96
"Hide",
97
async move { engine.hide_chat(&owned_id).await },
98
move |state, cx| state.restore_chat_locally(&chat, cx),
99
move |state, cx| {
100
let undo =
101
NoticeAction::new("Undo", move |state, cx| state.unhide_chat(&undo_id, cx));
102
state.raise_notice(text, Some(undo), cx);
103
},
104
cx,
105
);
106
}
107
108
pub fn unhide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {
109
let Some(engine) = self.chat_action_engine(cx).flatten() else {
110
return;
111
};
112
let owned_id = chat_id.to_owned();
113
self.run_chat_action(
114
"Undo",
115
async move { engine.unhide_chat(&owned_id).await },
116
|_, _| {},
117
|_, _| {},
118
cx,
119
);
120
}
121
122
pub fn leave_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {
123
let Some(chat) = self.chat_record(chat_id) else {
124
return;
125
};
126
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
127
return;
128
};
129
self.remove_chat_locally(chat_id, cx);
130
let Some(engine) = engine_or_demo else {
131
return;
132
};
133
let owned_id = chat_id.to_owned();
134
self.run_chat_action(
135
"Leave chat",
136
async move { engine.leave_chat(&owned_id).await },
137
move |state, cx| state.restore_chat_locally(&chat, cx),
138
|_, _| {},
139
cx,
140
);
141
}
142
143
fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
144
self.sidebar
145
.chats
146
.iter()
147
.find(|chat| chat.id == chat_id)
148
.cloned()
149
}
150
151
/// `None` stops the action. `Some(None)` is demo mode, which only changes the local store.
152
fn chat_action_engine(
153
&mut self,
154
cx: &mut Context<Self>,
155
) -> Option<Option<std::sync::Arc<crate::backend::Engine>>> {
156
if self.mode.read_only {
157
self.raise_notice("Read-only mode: chat not changed".to_owned(), None, cx);
158
return None;
159
}
160
match self.engine.clone() {
161
Some(engine) => Some(Some(engine)),
162
None if self.mode.demo => Some(None),
163
None => None,
164
}
165
}
166
167
fn remove_chat_locally(&mut self, chat_id: &str, cx: &mut Context<Self>) {
168
let was_selected = self.selection == Some(Selection::Chat(chat_id.to_owned()));
169
let next = was_selected
170
.then(|| self.next_chat_after(chat_id))
171
.flatten();
172
let _ = self.store.remove_chats(&[chat_id.to_owned()]);
173
self.reload_sidebar(cx);
174
if was_selected {
175
match next {
176
Some(next_id) => self.select(Selection::Chat(next_id), cx),
177
None => {
178
self.selection = None;
179
self.keep_unread = None;
180
cx.emit(crate::app_state::AppEvent::Selection);
181
cx.notify();
182
}
183
}
184
}
185
}
186
187
fn restore_chat_locally(&mut self, chat: &ChatRecord, cx: &mut Context<Self>) {
188
let _ = self.store.upsert_chats(std::slice::from_ref(chat));
189
let _ = self.store.set_chat_muted(&chat.id, chat.muted);
190
self.reload_sidebar(cx);
191
}
192
193
fn next_chat_after(&self, chat_id: &str) -> Option<String> {
194
let input = SectionInput {
195
chats: &self.sidebar.chats,
196
directory: &self.directory,
197
collapsed: &self.collapsed,
198
now: Utc::now(),
199
offset: Local::now().offset().fix(),
200
};
201
next_chat_id(&build_sections(&input), chat_id)
202
}
203
204
fn run_chat_action(
205
&mut self,
206
label: &'static str,
207
call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
208
revert: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
209
on_success: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
210
cx: &mut Context<Self>,
211
) {
212
let receiver = crate::runtime::spawn(call);
213
cx.spawn(async move |this, cx| {
214
let failure = match receiver.await {
215
Ok(Ok(())) => None,
216
Ok(Err(error)) => Some(short_error(&error)),
217
Err(_) => Some("cancelled".to_owned()),
218
};
219
this.update(cx, |state, cx| match failure {
220
None => on_success(state, cx),
221
Some(reason) => {
222
revert(state, cx);
223
state.raise_notice(format!("{label} failed: {reason}"), None, cx);
224
}
225
})
226
.ok();
227
})
228
.detach();
229
}
230
}
@@ -0,0 +1,230 @@1
use std::future::Future;2
3
use chrono::{Duration, Local, Offset, Utc};4
use gpui_kit::*;5
use store::ChatRecord;6
7
use crate::app_state::{AppState, Selection, chat_title};8
use crate::notice::{NoticeAction, short_error, truncated};9
use crate::sidebar_model::{SectionInput, build_sections, next_chat_id};10
11
pub const TITLE_LIMIT: usize = 40;12
13
impl AppState {14
pub fn keeps_unread(&self, chat_id: &str) -> bool {15
self.keep_unread.as_deref() == Some(chat_id)16
}17
18
pub fn mark_chat_unread(&mut self, chat_id: &str, cx: &mut Context<Self>) {19
let Some(chat) = self.chat_record(chat_id) else {20
return;21
};22
let Some(last_message_at) = chat.last_message_at else {23
return;24
};25
let Some(engine_or_demo) = self.chat_action_engine(cx) else {26
return;27
};28
let last_read_at = last_message_at - Duration::milliseconds(1);29
let _ = self.store.mark_chat_unread(chat_id, last_read_at);30
if self.selection == Some(Selection::Chat(chat_id.to_owned())) {31
self.keep_unread = Some(chat_id.to_owned());32
}33
self.reload_sidebar(cx);34
let Some(engine) = engine_or_demo else {35
return;36
};37
let owned_id = chat_id.to_owned();38
let revert_id = owned_id.clone();39
let restored_read_at = chat.last_read_at.unwrap_or(last_message_at);40
self.run_chat_action(41
"Mark as unread",42
async move { engine.mark_unread(&owned_id).await },43
move |state, cx| {44
let _ = state.store.mark_chat_read(&revert_id, restored_read_at);45
if state.keep_unread.as_deref() == Some(revert_id.as_str()) {46
state.keep_unread = None;47
}48
state.reload_sidebar(cx);49
},50
|_, _| {},51
cx,52
);53
}54
55
pub fn set_chat_muted(&mut self, chat_id: &str, muted: bool, cx: &mut Context<Self>) {56
if self.chat_record(chat_id).is_none() {57
return;58
}59
let Some(engine_or_demo) = self.chat_action_engine(cx) else {60
return;61
};62
let _ = self.store.set_chat_muted(chat_id, muted);63
self.reload_sidebar(cx);64
let Some(engine) = engine_or_demo else {65
return;66
};67
let owned_id = chat_id.to_owned();68
let revert_id = owned_id.clone();69
self.run_chat_action(70
if muted { "Mute" } else { "Unmute" },71
async move { engine.set_chat_muted(&owned_id, muted).await },72
move |state, cx| {73
let _ = state.store.set_chat_muted(&revert_id, !muted);74
state.reload_sidebar(cx);75
},76
|_, _| {},77
cx,78
);79
}80
81
pub fn hide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {82
let Some(chat) = self.chat_record(chat_id) else {83
return;84
};85
let Some(engine_or_demo) = self.chat_action_engine(cx) else {86
return;87
};88
self.remove_chat_locally(chat_id, cx);89
let Some(engine) = engine_or_demo else {90
return;91
};92
let owned_id = chat_id.to_owned();93
let undo_id = owned_id.clone();94
let text = format!("\"{}\" hidden", truncated(&chat_title(&chat), TITLE_LIMIT));95
self.run_chat_action(96
"Hide",97
async move { engine.hide_chat(&owned_id).await },98
move |state, cx| state.restore_chat_locally(&chat, cx),99
move |state, cx| {100
let undo =101
NoticeAction::new("Undo", move |state, cx| state.unhide_chat(&undo_id, cx));102
state.raise_notice(text, Some(undo), cx);103
},104
cx,105
);106
}107
108
pub fn unhide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {109
let Some(engine) = self.chat_action_engine(cx).flatten() else {110
return;111
};112
let owned_id = chat_id.to_owned();113
self.run_chat_action(114
"Undo",115
async move { engine.unhide_chat(&owned_id).await },116
|_, _| {},117
|_, _| {},118
cx,119
);120
}121
122
pub fn leave_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {123
let Some(chat) = self.chat_record(chat_id) else {124
return;125
};126
let Some(engine_or_demo) = self.chat_action_engine(cx) else {127
return;128
};129
self.remove_chat_locally(chat_id, cx);130
let Some(engine) = engine_or_demo else {131
return;132
};133
let owned_id = chat_id.to_owned();134
self.run_chat_action(135
"Leave chat",136
async move { engine.leave_chat(&owned_id).await },137
move |state, cx| state.restore_chat_locally(&chat, cx),138
|_, _| {},139
cx,140
);141
}142
143
fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {144
self.sidebar145
.chats146
.iter()147
.find(|chat| chat.id == chat_id)148
.cloned()149
}150
151
/// `None` stops the action. `Some(None)` is demo mode, which only changes the local store.152
fn chat_action_engine(153
&mut self,154
cx: &mut Context<Self>,155
) -> Option<Option<std::sync::Arc<crate::backend::Engine>>> {156
if self.mode.read_only {157
self.raise_notice("Read-only mode: chat not changed".to_owned(), None, cx);158
return None;159
}160
match self.engine.clone() {161
Some(engine) => Some(Some(engine)),162
None if self.mode.demo => Some(None),163
None => None,164
}165
}166
167
fn remove_chat_locally(&mut self, chat_id: &str, cx: &mut Context<Self>) {168
let was_selected = self.selection == Some(Selection::Chat(chat_id.to_owned()));169
let next = was_selected170
.then(|| self.next_chat_after(chat_id))171
.flatten();172
let _ = self.store.remove_chats(&[chat_id.to_owned()]);173
self.reload_sidebar(cx);174
if was_selected {175
match next {176
Some(next_id) => self.select(Selection::Chat(next_id), cx),177
None => {178
self.selection = None;179
self.keep_unread = None;180
cx.emit(crate::app_state::AppEvent::Selection);181
cx.notify();182
}183
}184
}185
}186
187
fn restore_chat_locally(&mut self, chat: &ChatRecord, cx: &mut Context<Self>) {188
let _ = self.store.upsert_chats(std::slice::from_ref(chat));189
let _ = self.store.set_chat_muted(&chat.id, chat.muted);190
self.reload_sidebar(cx);191
}192
193
fn next_chat_after(&self, chat_id: &str) -> Option<String> {194
let input = SectionInput {195
chats: &self.sidebar.chats,196
directory: &self.directory,197
collapsed: &self.collapsed,198
now: Utc::now(),199
offset: Local::now().offset().fix(),200
};201
next_chat_id(&build_sections(&input), chat_id)202
}203
204
fn run_chat_action(205
&mut self,206
label: &'static str,207
call: impl Future<Output = teams_core::Result<()>> + Send + 'static,208
revert: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,209
on_success: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,210
cx: &mut Context<Self>,211
) {212
let receiver = crate::runtime::spawn(call);213
cx.spawn(async move |this, cx| {214
let failure = match receiver.await {215
Ok(Ok(())) => None,216
Ok(Err(error)) => Some(short_error(&error)),217
Err(_) => Some("cancelled".to_owned()),218
};219
this.update(cx, |state, cx| match failure {220
None => on_success(state, cx),221
Some(reason) => {222
revert(state, cx);223
state.raise_notice(format!("{label} failed: {reason}"), None, cx);224
}225
})226
.ok();227
})228
.detach();229
}230
}@@ -9,6 +9,7 @@ mod assets;
9
9
mod avatar_image;
10
10
mod backend;
11
11
mod card_actions;
12
mod chat_actions;
12
13
mod card_state;
13
14
mod data;
14
15
mod demo;
@@ -17,6 +18,7 @@ mod emoji;
17
18
mod format;
18
19
mod frame_log;
19
20
mod fuzzy;
21
mod notice;
20
22
mod notify;
21
23
mod reaction_model;
22
24
mod read_state;
@@ -9,6 +9,7 @@ mod assets;9
mod avatar_image;9
mod avatar_image;10
mod backend;10
mod backend;11
mod card_actions;11
mod card_actions;12
mod chat_actions;12
mod card_state;13
mod card_state;13
mod data;14
mod data;14
mod demo;15
mod demo;@@ -17,6 +18,7 @@ mod emoji;17
mod format;18
mod format;18
mod frame_log;19
mod frame_log;19
mod fuzzy;20
mod fuzzy;21
mod notice;20
mod notify;22
mod notify;21
mod reaction_model;23
mod reaction_model;22
mod read_state;24
mod read_state;@@ -0,0 +1,109 @@
1
use std::rc::Rc;
2
use std::time::Duration;
3
4
use gpui_kit::*;
5
6
use crate::app_state::AppState;
7
8
const NOTICE_DURATION: Duration = Duration::from_secs(6);
9
const MAX_REASON_CHARS: usize = 140;
10
11
type NoticeCallback = Rc<dyn Fn(&mut AppState, &mut Context<AppState>)>;
12
13
#[derive(Clone)]
14
pub struct NoticeAction {
15
pub label: String,
16
pub run: NoticeCallback,
17
}
18
19
impl NoticeAction {
20
pub fn new(label: &str, run: impl Fn(&mut AppState, &mut Context<AppState>) + 'static) -> Self {
21
NoticeAction {
22
label: label.to_owned(),
23
run: Rc::new(run),
24
}
25
}
26
}
27
28
#[derive(Clone)]
29
pub struct Notice {
30
pub id: u64,
31
pub text: String,
32
pub action: Option<NoticeAction>,
33
}
34
35
pub fn short_error(error: &dyn std::fmt::Display) -> String {
36
error.to_string().chars().take(MAX_REASON_CHARS).collect()
37
}
38
39
pub fn truncated(text: &str, limit: usize) -> String {
40
if text.chars().count() <= limit {
41
return text.to_owned();
42
}
43
let kept: String = text.chars().take(limit).collect();
44
format!("{}...", kept.trim_end())
45
}
46
47
impl AppState {
48
pub fn raise_notice(
49
&mut self,
50
text: String,
51
action: Option<NoticeAction>,
52
cx: &mut Context<Self>,
53
) {
54
self.notice_count += 1;
55
let id = self.notice_count;
56
self.notice = Some(Notice { id, text, action });
57
cx.spawn(async move |this, cx| {
58
cx.background_executor().timer(NOTICE_DURATION).await;
59
this.update(cx, |state, cx| {
60
if state.notice.as_ref().is_some_and(|notice| notice.id == id) {
61
state.dismiss_notice(cx);
62
}
63
})
64
.ok();
65
})
66
.detach();
67
cx.emit(crate::app_state::AppEvent::Status);
68
cx.notify();
69
}
70
71
pub fn dismiss_notice(&mut self, cx: &mut Context<Self>) {
72
if self.notice.take().is_some() {
73
cx.emit(crate::app_state::AppEvent::Status);
74
cx.notify();
75
}
76
}
77
78
pub fn run_notice_action(&mut self, cx: &mut Context<Self>) {
79
let Some(notice) = self.notice.take() else {
80
return;
81
};
82
cx.emit(crate::app_state::AppEvent::Status);
83
cx.notify();
84
if let Some(action) = notice.action {
85
(action.run)(self, cx);
86
}
87
}
88
}
89
90
#[cfg(test)]
91
mod tests {
92
use super::{short_error, truncated};
93
94
#[test]
95
fn short_titles_pass_through() {
96
assert_eq!(truncated("Planning", 40), "Planning");
97
}
98
99
#[test]
100
fn long_titles_are_cut_at_the_limit() {
101
let title = "x".repeat(60);
102
assert_eq!(truncated(&title, 40), format!("{}...", "x".repeat(40)));
103
}
104
105
#[test]
106
fn errors_are_capped() {
107
assert_eq!(short_error(&"y".repeat(500)).chars().count(), 140);
108
}
109
}
@@ -0,0 +1,109 @@1
use std::rc::Rc;2
use std::time::Duration;3
4
use gpui_kit::*;5
6
use crate::app_state::AppState;7
8
const NOTICE_DURATION: Duration = Duration::from_secs(6);9
const MAX_REASON_CHARS: usize = 140;10
11
type NoticeCallback = Rc<dyn Fn(&mut AppState, &mut Context<AppState>)>;12
13
#[derive(Clone)]14
pub struct NoticeAction {15
pub label: String,16
pub run: NoticeCallback,17
}18
19
impl NoticeAction {20
pub fn new(label: &str, run: impl Fn(&mut AppState, &mut Context<AppState>) + 'static) -> Self {21
NoticeAction {22
label: label.to_owned(),23
run: Rc::new(run),24
}25
}26
}27
28
#[derive(Clone)]29
pub struct Notice {30
pub id: u64,31
pub text: String,32
pub action: Option<NoticeAction>,33
}34
35
pub fn short_error(error: &dyn std::fmt::Display) -> String {36
error.to_string().chars().take(MAX_REASON_CHARS).collect()37
}38
39
pub fn truncated(text: &str, limit: usize) -> String {40
if text.chars().count() <= limit {41
return text.to_owned();42
}43
let kept: String = text.chars().take(limit).collect();44
format!("{}...", kept.trim_end())45
}46
47
impl AppState {48
pub fn raise_notice(49
&mut self,50
text: String,51
action: Option<NoticeAction>,52
cx: &mut Context<Self>,53
) {54
self.notice_count += 1;55
let id = self.notice_count;56
self.notice = Some(Notice { id, text, action });57
cx.spawn(async move |this, cx| {58
cx.background_executor().timer(NOTICE_DURATION).await;59
this.update(cx, |state, cx| {60
if state.notice.as_ref().is_some_and(|notice| notice.id == id) {61
state.dismiss_notice(cx);62
}63
})64
.ok();65
})66
.detach();67
cx.emit(crate::app_state::AppEvent::Status);68
cx.notify();69
}70
71
pub fn dismiss_notice(&mut self, cx: &mut Context<Self>) {72
if self.notice.take().is_some() {73
cx.emit(crate::app_state::AppEvent::Status);74
cx.notify();75
}76
}77
78
pub fn run_notice_action(&mut self, cx: &mut Context<Self>) {79
let Some(notice) = self.notice.take() else {80
return;81
};82
cx.emit(crate::app_state::AppEvent::Status);83
cx.notify();84
if let Some(action) = notice.action {85
(action.run)(self, cx);86
}87
}88
}89
90
#[cfg(test)]91
mod tests {92
use super::{short_error, truncated};93
94
#[test]95
fn short_titles_pass_through() {96
assert_eq!(truncated("Planning", 40), "Planning");97
}98
99
#[test]100
fn long_titles_are_cut_at_the_limit() {101
let title = "x".repeat(60);102
assert_eq!(truncated(&title, 40), format!("{}...", "x".repeat(40)));103
}104
105
#[test]106
fn errors_are_capped() {107
assert_eq!(short_error(&"y".repeat(500)).chars().count(), 140);108
}109
}@@ -521,7 +521,8 @@ impl NotificationCenter {
521
521
}
522
522
523
523
fn refresh_badge(&mut self, cx: &mut Context<Self>) {
524
let (count, still_unread) = unread_summary(&self.app.read(cx).sidebar);
524
let (count, still_unread) =
525
unread_summary(&self.app.read(cx).sidebar, &self.unread_mentions);
525
526
self.unread_mentions
526
527
.retain(|conversation_id| still_unread.contains(conversation_id));
527
528
let badge = badge_for(count);
@@ -838,18 +839,31 @@ pub fn selection_for(sidebar: &Sidebar, conversation_id: &str) -> Option<Selecti
838
839
.then(|| Selection::Channel(conversation_id.to_owned()))
839
840
}
840
841
841
pub fn unread_summary(sidebar: &Sidebar) -> (usize, HashSet<String>) {
842
pub fn unread_summary(
843
sidebar: &Sidebar,
844
unread_mentions: &HashSet<String>,
845
) -> (usize, HashSet<String>) {
842
846
let chats = sidebar.chats.iter().filter(|chat| chat.unread);
843
847
let channels = sidebar
844
848
.teams
845
849
.iter()
846
850
.flat_map(|team| team.channels.iter())
847
851
.filter(|channel| channel.unread);
852
let silenced_chat_ids: HashSet<&str> = sidebar
853
.chats
854
.iter()
855
.filter(|chat| chat.muted && !unread_mentions.contains(&chat.id))
856
.map(|chat| chat.id.as_str())
857
.collect();
848
858
let ids: HashSet<String> = chats
849
859
.map(|chat| chat.id.clone())
850
860
.chain(channels.map(|channel| channel.id.clone()))
851
861
.collect();
852
(ids.len(), ids)
862
let counted = ids
863
.iter()
864
.filter(|id| !silenced_chat_ids.contains(id.as_str()))
865
.count();
866
(counted, ids)
853
867
}
854
868
855
869
fn demo_incoming() -> Vec<Incoming> {
@@ -922,6 +936,8 @@ fn demo_incoming() -> Vec<Incoming> {
922
936
mod tests {
923
937
use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
924
938
939
use std::collections::HashSet;
940
925
941
use super::{preview_lines, selection_for, unread_summary};
926
942
use crate::app_state::Selection;
927
943
use store::Sidebar;
@@ -961,11 +977,22 @@ mod tests {
961
977
962
978
#[test]
963
979
fn unread_summary_counts_chats_and_channels() {
964
let (count, ids) = unread_summary(&sidebar());
980
let (count, ids) = unread_summary(&sidebar(), &HashSet::new());
965
981
assert_eq!(count, 2);
966
982
assert!(ids.contains("a") && ids.contains("ch"));
967
983
}
968
984
985
#[test]
986
fn muted_chats_only_count_with_an_unread_mention() {
987
let mut quiet = sidebar();
988
quiet.chats[0].muted = true;
989
let (count, ids) = unread_summary(&quiet, &HashSet::new());
990
assert_eq!(count, 1);
991
assert!(ids.contains("a"));
992
let (count, _) = unread_summary(&quiet, &HashSet::from(["a".to_owned()]));
993
assert_eq!(count, 2);
994
}
995
969
996
#[test]
970
997
fn selection_kind_follows_sidebar() {
971
998
assert_eq!(
@@ -521,7 +521,8 @@ impl NotificationCenter {521
}521
}522
522
523
fn refresh_badge(&mut self, cx: &mut Context<Self>) {523
fn refresh_badge(&mut self, cx: &mut Context<Self>) {524
let (count, still_unread) = unread_summary(&self.app.read(cx).sidebar);524
let (count, still_unread) =525
unread_summary(&self.app.read(cx).sidebar, &self.unread_mentions);525
self.unread_mentions526
self.unread_mentions526
.retain(|conversation_id| still_unread.contains(conversation_id));527
.retain(|conversation_id| still_unread.contains(conversation_id));527
let badge = badge_for(count);528
let badge = badge_for(count);@@ -838,18 +839,31 @@ pub fn selection_for(sidebar: &Sidebar, conversation_id: &str) -> Option<Selecti838
.then(|| Selection::Channel(conversation_id.to_owned()))839
.then(|| Selection::Channel(conversation_id.to_owned()))839
}840
}840
841
841
pub fn unread_summary(sidebar: &Sidebar) -> (usize, HashSet<String>) {842
pub fn unread_summary(843
sidebar: &Sidebar,844
unread_mentions: &HashSet<String>,845
) -> (usize, HashSet<String>) {842
let chats = sidebar.chats.iter().filter(|chat| chat.unread);846
let chats = sidebar.chats.iter().filter(|chat| chat.unread);843
let channels = sidebar847
let channels = sidebar844
.teams848
.teams845
.iter()849
.iter()846
.flat_map(|team| team.channels.iter())850
.flat_map(|team| team.channels.iter())847
.filter(|channel| channel.unread);851
.filter(|channel| channel.unread);852
let silenced_chat_ids: HashSet<&str> = sidebar853
.chats854
.iter()855
.filter(|chat| chat.muted && !unread_mentions.contains(&chat.id))856
.map(|chat| chat.id.as_str())857
.collect();848
let ids: HashSet<String> = chats858
let ids: HashSet<String> = chats849
.map(|chat| chat.id.clone())859
.map(|chat| chat.id.clone())850
.chain(channels.map(|channel| channel.id.clone()))860
.chain(channels.map(|channel| channel.id.clone()))851
.collect();861
.collect();852
(ids.len(), ids)862
let counted = ids863
.iter()864
.filter(|id| !silenced_chat_ids.contains(id.as_str()))865
.count();866
(counted, ids)853
}867
}854
868
855
fn demo_incoming() -> Vec<Incoming> {869
fn demo_incoming() -> Vec<Incoming> {@@ -922,6 +936,8 @@ fn demo_incoming() -> Vec<Incoming> {922
mod tests {936
mod tests {923
use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};937
use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};924
938
939
use std::collections::HashSet;940
925
use super::{preview_lines, selection_for, unread_summary};941
use super::{preview_lines, selection_for, unread_summary};926
use crate::app_state::Selection;942
use crate::app_state::Selection;927
use store::Sidebar;943
use store::Sidebar;@@ -961,11 +977,22 @@ mod tests {961
977
962
#[test]978
#[test]963
fn unread_summary_counts_chats_and_channels() {979
fn unread_summary_counts_chats_and_channels() {964
let (count, ids) = unread_summary(&sidebar());980
let (count, ids) = unread_summary(&sidebar(), &HashSet::new());965
assert_eq!(count, 2);981
assert_eq!(count, 2);966
assert!(ids.contains("a") && ids.contains("ch"));982
assert!(ids.contains("a") && ids.contains("ch"));967
}983
}968
984
985
#[test]986
fn muted_chats_only_count_with_an_unread_mention() {987
let mut quiet = sidebar();988
quiet.chats[0].muted = true;989
let (count, ids) = unread_summary(&quiet, &HashSet::new());990
assert_eq!(count, 1);991
assert!(ids.contains("a"));992
let (count, _) = unread_summary(&quiet, &HashSet::from(["a".to_owned()]));993
assert_eq!(count, 2);994
}995
969
#[test]996
#[test]970
fn selection_kind_follows_sidebar() {997
fn selection_kind_follows_sidebar() {971
assert_eq!(998
assert_eq!(@@ -93,12 +93,19 @@ pub fn build_incoming(
93
93
sender_name: record.sender_name.clone().unwrap_or_default(),
94
94
preview: preview_of(record),
95
95
mentions_me: mentions_me(record, my_user_id),
96
muted: false,
96
muted: is_muted_chat(sidebar, &record.conversation_id),
97
97
signals,
98
98
created_at: record.created_at,
99
99
})
100
100
}
101
101
102
fn is_muted_chat(sidebar: &Sidebar, conversation_id: &str) -> bool {
103
sidebar
104
.chats
105
.iter()
106
.any(|chat| chat.id == conversation_id && chat.muted)
107
}
108
102
109
fn chat_context(sidebar: &Sidebar, conversation_id: &str) -> Option<(ChatKind, String)> {
103
110
if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {
104
111
let kind = if chat.kind.eq_ignore_ascii_case("oneOnOne") {
@@ -274,6 +281,19 @@ mod tests {
274
281
}
275
282
}
276
283
284
#[test]
285
fn incoming_in_a_muted_chat_is_marked_muted() {
286
let mut quiet = sidebar();
287
quiet.chats[1].muted = true;
288
let message = record("group", "u1", Utc::now(), "hi");
289
let store = Store::open_in_memory().unwrap();
290
let build = |sidebar: &Sidebar| {
291
build_incoming(&message, &store, sidebar, &HashSet::new(), Some("me")).unwrap()
292
};
293
assert!(build(&quiet).muted);
294
assert!(!build(&sidebar()).muted);
295
}
296
277
297
#[test]
278
298
fn history_before_start_is_ignored() {
279
299
let start = Utc::now();
@@ -93,12 +93,19 @@ pub fn build_incoming(93
sender_name: record.sender_name.clone().unwrap_or_default(),93
sender_name: record.sender_name.clone().unwrap_or_default(),94
preview: preview_of(record),94
preview: preview_of(record),95
mentions_me: mentions_me(record, my_user_id),95
mentions_me: mentions_me(record, my_user_id),96
muted: false,96
muted: is_muted_chat(sidebar, &record.conversation_id),97
signals,97
signals,98
created_at: record.created_at,98
created_at: record.created_at,99
})99
})100
}100
}101
101
102
fn is_muted_chat(sidebar: &Sidebar, conversation_id: &str) -> bool {103
sidebar104
.chats105
.iter()106
.any(|chat| chat.id == conversation_id && chat.muted)107
}108
102
fn chat_context(sidebar: &Sidebar, conversation_id: &str) -> Option<(ChatKind, String)> {109
fn chat_context(sidebar: &Sidebar, conversation_id: &str) -> Option<(ChatKind, String)> {103
if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {110
if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {104
let kind = if chat.kind.eq_ignore_ascii_case("oneOnOne") {111
let kind = if chat.kind.eq_ignore_ascii_case("oneOnOne") {@@ -274,6 +281,19 @@ mod tests {274
}281
}275
}282
}276
283
284
#[test]285
fn incoming_in_a_muted_chat_is_marked_muted() {286
let mut quiet = sidebar();287
quiet.chats[1].muted = true;288
let message = record("group", "u1", Utc::now(), "hi");289
let store = Store::open_in_memory().unwrap();290
let build = |sidebar: &Sidebar| {291
build_incoming(&message, &store, sidebar, &HashSet::new(), Some("me")).unwrap()292
};293
assert!(build(&quiet).muted);294
assert!(!build(&sidebar()).muted);295
}296
277
#[test]297
#[test]278
fn history_before_start_is_ignored() {298
fn history_before_start_is_ignored() {279
let start = Utc::now();299
let start = Utc::now();@@ -15,6 +15,7 @@ pub const OTHERS_ID: &str = "others";
15
15
pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";
16
16
pub const DELETED_PREVIEW: &str = "Message deleted";
17
17
const OWN_PREFIX: &str = "You";
18
const GROUP_KIND: &str = "group";
18
19
19
20
#[derive(Debug, Clone, PartialEq, Eq)]
20
21
pub enum Preview {
@@ -58,6 +59,9 @@ pub struct ChatItem {
58
59
pub time_label: String,
59
60
pub preview: Preview,
60
61
pub unread: Unread,
62
pub muted: bool,
63
pub is_group: bool,
64
pub member_count: usize,
61
65
pub avatar: AvatarSpec,
62
66
pub presence_user: Option<String>,
63
67
pub folder_id: Option<String>,
@@ -176,6 +180,9 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<
176
180
.unwrap_or_default(),
177
181
preview: preview_for(chat, me),
178
182
unread,
183
muted: chat.muted,
184
is_group: chat.kind == GROUP_KIND,
185
member_count: chat.members.len(),
179
186
avatar: avatar_for(chat, me),
180
187
presence_user,
181
188
folder_id: folder_id.map(str::to_owned),
@@ -183,7 +190,10 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<
183
190
}
184
191
185
192
pub fn unread_chat_count(chats: &[ChatRecord]) -> u32 {
186
chats.iter().filter(|chat| chat.unread).count() as u32
193
chats
194
.iter()
195
.filter(|chat| chat.unread && !chat.muted)
196
.count() as u32
187
197
}
188
198
189
199
pub fn any_unread_channel(sidebar: &Sidebar) -> bool {
@@ -238,6 +248,23 @@ pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
238
248
sections
239
249
}
240
250
251
pub fn next_chat_id(sections: &[Section], removed_id: &str) -> Option<String> {
252
let visible: Vec<&str> = sections
253
.iter()
254
.filter(|section| !section.collapsed)
255
.flat_map(|section| section.items.iter().map(|item| item.id.as_str()))
256
.collect();
257
let position = visible.iter().position(|id| *id == removed_id)?;
258
visible
259
.get(position + 1)
260
.or_else(|| {
261
position
262
.checked_sub(1)
263
.and_then(|previous| visible.get(previous))
264
})
265
.map(|id| (*id).to_owned())
266
}
267
241
268
fn section(
242
269
id: String,
243
270
name: String,
@@ -246,7 +273,10 @@ fn section(
246
273
input: &SectionInput<'_>,
247
274
) -> Section {
248
275
let collapsed = input.collapsed.contains(&id);
249
let unread_chats = items.iter().filter(|item| item.unread.is_unread()).count() as u32;
276
let unread_chats = items
277
.iter()
278
.filter(|item| item.unread.is_unread() && !item.muted)
279
.count() as u32;
250
280
Section {
251
281
collapsed,
252
282
count: items.len(),
@@ -322,6 +352,38 @@ mod tests {
322
352
}
323
353
}
324
354
355
#[test]
356
fn next_chat_is_the_following_row_then_the_previous_one() {
357
let chats = [
358
chat("a", "group", false),
359
chat("b", "group", false),
360
chat("c", "group", false),
361
];
362
let directory = Directory::default();
363
let collapsed = HashSet::new();
364
let sections = build_sections(&input(&chats, &directory, &collapsed));
365
assert_eq!(next_chat_id(§ions, "a"), Some("b".to_owned()));
366
assert_eq!(next_chat_id(§ions, "c"), Some("b".to_owned()));
367
assert_eq!(next_chat_id(§ions, "zzz"), None);
368
let single = [chat("a", "group", false)];
369
let sections = build_sections(&input(&single, &directory, &collapsed));
370
assert_eq!(next_chat_id(§ions, "a"), None);
371
}
372
373
#[test]
374
fn muted_chats_stay_out_of_unread_counts() {
375
let mut quiet = chat("a", "group", true);
376
quiet.muted = true;
377
let chats = [quiet, chat("b", "group", true)];
378
assert_eq!(unread_chat_count(&chats), 1);
379
let directory = Directory::default();
380
let collapsed = HashSet::new();
381
let sections = build_sections(&input(&chats, &directory, &collapsed));
382
assert_eq!(sections[0].unread_chats, 1);
383
assert!(sections[0].items[0].muted);
384
assert!(sections[0].items[0].unread.is_unread());
385
}
386
325
387
#[test]
326
388
fn preview_prefix_is_you_for_own_and_first_name_for_groups() {
327
389
let mut group = chat("g", "group", false);
@@ -15,6 +15,7 @@ pub const OTHERS_ID: &str = "others";15
pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";15
pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";16
pub const DELETED_PREVIEW: &str = "Message deleted";16
pub const DELETED_PREVIEW: &str = "Message deleted";17
const OWN_PREFIX: &str = "You";17
const OWN_PREFIX: &str = "You";18
const GROUP_KIND: &str = "group";18
19
19
#[derive(Debug, Clone, PartialEq, Eq)]20
#[derive(Debug, Clone, PartialEq, Eq)]20
pub enum Preview {21
pub enum Preview {@@ -58,6 +59,9 @@ pub struct ChatItem {58
pub time_label: String,59
pub time_label: String,59
pub preview: Preview,60
pub preview: Preview,60
pub unread: Unread,61
pub unread: Unread,62
pub muted: bool,63
pub is_group: bool,64
pub member_count: usize,61
pub avatar: AvatarSpec,65
pub avatar: AvatarSpec,62
pub presence_user: Option<String>,66
pub presence_user: Option<String>,63
pub folder_id: Option<String>,67
pub folder_id: Option<String>,@@ -176,6 +180,9 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<176
.unwrap_or_default(),180
.unwrap_or_default(),177
preview: preview_for(chat, me),181
preview: preview_for(chat, me),178
unread,182
unread,183
muted: chat.muted,184
is_group: chat.kind == GROUP_KIND,185
member_count: chat.members.len(),179
avatar: avatar_for(chat, me),186
avatar: avatar_for(chat, me),180
presence_user,187
presence_user,181
folder_id: folder_id.map(str::to_owned),188
folder_id: folder_id.map(str::to_owned),@@ -183,7 +190,10 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<183
}190
}184
191
185
pub fn unread_chat_count(chats: &[ChatRecord]) -> u32 {192
pub fn unread_chat_count(chats: &[ChatRecord]) -> u32 {186
chats.iter().filter(|chat| chat.unread).count() as u32193
chats194
.iter()195
.filter(|chat| chat.unread && !chat.muted)196
.count() as u32187
}197
}188
198
189
pub fn any_unread_channel(sidebar: &Sidebar) -> bool {199
pub fn any_unread_channel(sidebar: &Sidebar) -> bool {@@ -238,6 +248,23 @@ pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {238
sections248
sections239
}249
}240
250
251
pub fn next_chat_id(sections: &[Section], removed_id: &str) -> Option<String> {252
let visible: Vec<&str> = sections253
.iter()254
.filter(|section| !section.collapsed)255
.flat_map(|section| section.items.iter().map(|item| item.id.as_str()))256
.collect();257
let position = visible.iter().position(|id| *id == removed_id)?;258
visible259
.get(position + 1)260
.or_else(|| {261
position262
.checked_sub(1)263
.and_then(|previous| visible.get(previous))264
})265
.map(|id| (*id).to_owned())266
}267
241
fn section(268
fn section(242
id: String,269
id: String,243
name: String,270
name: String,@@ -246,7 +273,10 @@ fn section(246
input: &SectionInput<'_>,273
input: &SectionInput<'_>,247
) -> Section {274
) -> Section {248
let collapsed = input.collapsed.contains(&id);275
let collapsed = input.collapsed.contains(&id);249
let unread_chats = items.iter().filter(|item| item.unread.is_unread()).count() as u32;276
let unread_chats = items277
.iter()278
.filter(|item| item.unread.is_unread() && !item.muted)279
.count() as u32;250
Section {280
Section {251
collapsed,281
collapsed,252
count: items.len(),282
count: items.len(),@@ -322,6 +352,38 @@ mod tests {322
}352
}323
}353
}324
354
355
#[test]356
fn next_chat_is_the_following_row_then_the_previous_one() {357
let chats = [358
chat("a", "group", false),359
chat("b", "group", false),360
chat("c", "group", false),361
];362
let directory = Directory::default();363
let collapsed = HashSet::new();364
let sections = build_sections(&input(&chats, &directory, &collapsed));365
assert_eq!(next_chat_id(§ions, "a"), Some("b".to_owned()));366
assert_eq!(next_chat_id(§ions, "c"), Some("b".to_owned()));367
assert_eq!(next_chat_id(§ions, "zzz"), None);368
let single = [chat("a", "group", false)];369
let sections = build_sections(&input(&single, &directory, &collapsed));370
assert_eq!(next_chat_id(§ions, "a"), None);371
}372
373
#[test]374
fn muted_chats_stay_out_of_unread_counts() {375
let mut quiet = chat("a", "group", true);376
quiet.muted = true;377
let chats = [quiet, chat("b", "group", true)];378
assert_eq!(unread_chat_count(&chats), 1);379
let directory = Directory::default();380
let collapsed = HashSet::new();381
let sections = build_sections(&input(&chats, &directory, &collapsed));382
assert_eq!(sections[0].unread_chats, 1);383
assert!(sections[0].items[0].muted);384
assert!(sections[0].items[0].unread.is_unread());385
}386
325
#[test]387
#[test]326
fn preview_prefix_is_you_for_own_and_first_name_for_groups() {388
fn preview_prefix_is_you_for_own_and_first_name_for_groups() {327
let mut group = chat("g", "group", false);389
let mut group = chat("g", "group", false);@@ -32,6 +32,7 @@ use crate::backend::Engine;
32
32
use crate::data::{is_one_on_one, others};
33
33
use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
34
34
use crate::emoji;
35
use crate::notice::short_error;
35
36
use crate::reaction_model::UNKNOWN_REACTOR;
36
37
use crate::read_state::{ReadTrigger, plan_read};
37
38
use crate::render::layout_blocks;
@@ -50,7 +51,6 @@ const CHANNEL_OPEN_LIMIT: usize = 300;
50
51
const GROWTH_HEADROOM: usize = 20;
51
52
const META_USER_ID: &str = "me_user_id";
52
53
const PENDING_KEY_PREFIX: &str = "pending-";
53
const MAX_NOTICE_CHARS: usize = 140;
54
54
const DEMO_DOWNLOAD_STEPS: u8 = 10;
55
55
const DEMO_DOWNLOAD_STEP: Duration = Duration::from_millis(100);
56
56
const JUMP_SCAN_LIMIT: usize = 5000;
@@ -184,10 +184,6 @@ fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String,
184
184
}
185
185
}
186
186
187
fn short_error(error: &dyn std::fmt::Display) -> String {
188
error.to_string().chars().take(MAX_NOTICE_CHARS).collect()
189
}
190
191
187
enum DownloadEvent {
192
188
Progress(u8),
193
189
Finished(Result<PathBuf, String>),
@@ -1448,7 +1444,8 @@ impl ConversationView {
1448
1444
.sidebar
1449
1445
.chats
1450
1446
.iter()
1451
.any(|chat| chat.id == chat_id && chat.unread);
1447
.any(|chat| chat.id == chat_id && chat.unread)
1448
&& !state.keeps_unread(&chat_id);
1452
1449
let Some(plan) = plan_read(self.window_active, unread, trigger) else {
1453
1450
return;
1454
1451
};
@@ -2205,8 +2202,9 @@ impl ConversationView {
2205
2202
}
2206
2203
2207
2204
fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
2208
self.notice = Some(message.to_owned());
2209
cx.notify();
2205
self.app.update(cx, |state, cx| {
2206
state.raise_notice(message.to_owned(), None, cx)
2207
});
2210
2208
}
2211
2209
2212
2210
fn report_failure(
@@ -32,6 +32,7 @@ use crate::backend::Engine;32
use crate::data::{is_one_on_one, others};32
use crate::data::{is_one_on_one, others};33
use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};33
use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};34
use crate::emoji;34
use crate::emoji;35
use crate::notice::short_error;35
use crate::reaction_model::UNKNOWN_REACTOR;36
use crate::reaction_model::UNKNOWN_REACTOR;36
use crate::read_state::{ReadTrigger, plan_read};37
use crate::read_state::{ReadTrigger, plan_read};37
use crate::render::layout_blocks;38
use crate::render::layout_blocks;@@ -50,7 +51,6 @@ const CHANNEL_OPEN_LIMIT: usize = 300;50
const GROWTH_HEADROOM: usize = 20;51
const GROWTH_HEADROOM: usize = 20;51
const META_USER_ID: &str = "me_user_id";52
const META_USER_ID: &str = "me_user_id";52
const PENDING_KEY_PREFIX: &str = "pending-";53
const PENDING_KEY_PREFIX: &str = "pending-";53
const MAX_NOTICE_CHARS: usize = 140;54
const DEMO_DOWNLOAD_STEPS: u8 = 10;54
const DEMO_DOWNLOAD_STEPS: u8 = 10;55
const DEMO_DOWNLOAD_STEP: Duration = Duration::from_millis(100);55
const DEMO_DOWNLOAD_STEP: Duration = Duration::from_millis(100);56
const JUMP_SCAN_LIMIT: usize = 5000;56
const JUMP_SCAN_LIMIT: usize = 5000;@@ -184,10 +184,6 @@ fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String,184
}184
}185
}185
}186
186
187
fn short_error(error: &dyn std::fmt::Display) -> String {188
error.to_string().chars().take(MAX_NOTICE_CHARS).collect()189
}190
191
enum DownloadEvent {187
enum DownloadEvent {192
Progress(u8),188
Progress(u8),193
Finished(Result<PathBuf, String>),189
Finished(Result<PathBuf, String>),@@ -1448,7 +1444,8 @@ impl ConversationView {1448
.sidebar1444
.sidebar1449
.chats1445
.chats1450
.iter()1446
.iter()1451
.any(|chat| chat.id == chat_id && chat.unread);1447
.any(|chat| chat.id == chat_id && chat.unread)1448
&& !state.keeps_unread(&chat_id);1452
let Some(plan) = plan_read(self.window_active, unread, trigger) else {1449
let Some(plan) = plan_read(self.window_active, unread, trigger) else {1453
return;1450
return;1454
};1451
};@@ -2205,8 +2202,9 @@ impl ConversationView {2205
}2202
}2206
2203
2207
fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {2204
fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {2208
self.notice = Some(message.to_owned());2205
self.app.update(cx, |state, cx| {2209
cx.notify();2206
state.raise_notice(message.to_owned(), None, cx)2207
});2210
}2208
}2211
2209
2212
fn report_failure(2210
fn report_failure(@@ -301,6 +301,10 @@ impl Render for AppShell {
301
301
state,
302
302
&self.update,
303
303
cx.listener(|this, _, _, cx| this.restart_into_update(cx)),
304
cx.listener(|this, _, _, cx| {
305
this.state
306
.update(cx, |state, cx| state.run_notice_action(cx))
307
}),
304
308
);
305
309
let title_bar = render_title_bar(
306
310
&state.directory,
@@ -301,6 +301,10 @@ impl Render for AppShell {301
state,301
state,302
&self.update,302
&self.update,303
cx.listener(|this, _, _, cx| this.restart_into_update(cx)),303
cx.listener(|this, _, _, cx| this.restart_into_update(cx)),304
cx.listener(|this, _, _, cx| {305
this.state306
.update(cx, |state, cx| state.run_notice_action(cx))307
}),304
);308
);305
let title_bar = render_title_bar(309
let title_bar = render_title_bar(306
&state.directory,310
&state.directory,@@ -2,8 +2,10 @@ use std::collections::HashSet;
2
2
3
3
use chrono::{Local, Offset, Utc};
4
4
use gpui_kit::assets::IconName;
5
use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
6
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
5
use gpui_kit::component::button::{Button, ButtonVariants as _};
6
use gpui_kit::component::dialog::DialogFooter;
7
use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenu, PopupMenuItem};
8
use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
7
9
use gpui_kit::prelude::FluentBuilder as _;
8
10
use gpui_kit::*;
9
11
use store::{ChannelRecord, SidebarTeam, TeamRecord};
@@ -11,8 +13,10 @@ use store::{ChannelRecord, SidebarTeam, TeamRecord};
11
13
use super::avatar::{spec_avatar, square_avatar, with_presence};
12
14
use super::widgets::{count_badge, dot, icon, symbol, unread_marker};
13
15
use crate::app_state::{AppEvent, AppState, Selection};
16
use crate::chat_actions::TITLE_LIMIT;
14
17
use crate::data::{Directory, FolderKind};
15
18
use crate::format;
19
use crate::notice::truncated;
16
20
use crate::sidebar_model::{
17
21
AvatarSpec, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section, SectionInput,
18
22
SectionKind, any_unread_channel, build_sections, unread_chat_count,
@@ -34,6 +38,8 @@ const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
34
38
const TEAM_ROW_HEIGHT: f32 = 40.;
35
39
const REVEAL_ROW_HEIGHT: f32 = 32.;
36
40
const NEW_CHAT_BUTTON_SIZE: f32 = 34.;
41
const MENU_ICON_SIZE: f32 = 15.;
42
const MUTED_ICON_SIZE: f32 = 13.;
37
43
38
44
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39
45
enum SidebarTab {
@@ -66,6 +72,16 @@ impl Render for DragGhost {
66
72
}
67
73
}
68
74
75
struct ChatMenuTarget {
76
id: String,
77
title: String,
78
pinned: bool,
79
unread: bool,
80
muted: bool,
81
is_group: bool,
82
member_count: usize,
83
}
84
69
85
#[derive(Clone)]
70
86
struct MenuContext {
71
87
state: Entity<AppState>,
@@ -73,6 +89,170 @@ struct MenuContext {
73
89
favorites_id: Option<String>,
74
90
}
75
91
92
fn menu_icon(name: IconName) -> gpui_kit::component::Icon {
93
icon(name, MENU_ICON_SIZE, theme::text_muted())
94
}
95
96
fn chat_menu(
97
popup: PopupMenu,
98
window: &mut Window,
99
cx: &mut Context<PopupMenu>,
100
context: &MenuContext,
101
target: &ChatMenuTarget,
102
) -> PopupMenu {
103
let pinned = target.pinned;
104
let pin_state = context.state.clone();
105
let pin_id = target.id.clone();
106
let mut popup = popup.item(
107
PopupMenuItem::new(if pinned { "Unpin" } else { "Pin" })
108
.icon(menu_icon(if pinned {
109
IconName::PinOff
110
} else {
111
IconName::Pin
112
}))
113
.on_click(move |_, _, cx| {
114
pin_state.update(cx, |state, cx| {
115
if pinned {
116
state.move_chat(&pin_id, None, cx);
117
} else {
118
state.pin_chat(&pin_id, cx);
119
}
120
});
121
}),
122
);
123
if !context.folders.is_empty() {
124
let folders = context.folders.clone();
125
let move_state = context.state.clone();
126
let move_id = target.id.clone();
127
popup = popup.submenu_with_icon(
128
Some(menu_icon(IconName::Folder)),
129
"Move to folder",
130
window,
131
cx,
132
move |submenu, _, _| {
133
folders.iter().fold(submenu, |submenu, (folder_id, name)| {
134
let (state, chat_id, folder_id) =
135
(move_state.clone(), move_id.clone(), folder_id.clone());
136
submenu.item(PopupMenuItem::new(name.clone()).on_click(move |_, _, cx| {
137
state.update(cx, |state, cx| {
138
state.move_chat(&chat_id, Some(&folder_id), cx)
139
});
140
}))
141
})
142
},
143
);
144
}
145
let read_state = context.state.clone();
146
let read_id = target.id.clone();
147
let unread = target.unread;
148
let mute_state = context.state.clone();
149
let mute_id = target.id.clone();
150
let muted = target.muted;
151
let hide_state = context.state.clone();
152
let hide_id = target.id.clone();
153
popup = popup
154
.separator()
155
.item(
156
PopupMenuItem::new(if unread {
157
"Mark as read"
158
} else {
159
"Mark as unread"
160
})
161
.icon(menu_icon(if unread {
162
IconName::MailOpen
163
} else {
164
IconName::Mail
165
}))
166
.on_click(move |_, _, cx| {
167
read_state.update(cx, |state, cx| {
168
if unread {
169
state.mark_chat_read(&read_id, cx);
170
} else {
171
state.mark_chat_unread(&read_id, cx);
172
}
173
});
174
}),
175
)
176
.item(
177
PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
178
.icon(menu_icon(if muted {
179
IconName::Bell
180
} else {
181
IconName::BellOff
182
}))
183
.on_click(move |_, _, cx| {
184
mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));
185
}),
186
)
187
.separator()
188
.item(
189
PopupMenuItem::new("Hide")
190
.icon(menu_icon(IconName::EyeOff))
191
.on_click(move |_, _, cx| {
192
hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
193
}),
194
);
195
if target.is_group {
196
let leave_state = context.state.clone();
197
let leave_id = target.id.clone();
198
let title = target.title.clone();
199
let member_count = target.member_count;
200
popup = popup.item(
201
PopupMenuItem::element(|_, _| {
202
div().text_color(theme::red_soft()).child("Leave chat...")
203
})
204
.icon(icon(IconName::LogOut, MENU_ICON_SIZE, theme::red_soft()))
205
.on_click(move |_, window, cx| {
206
confirm_leave(&leave_state, &leave_id, &title, member_count, window, cx);
207
}),
208
);
209
}
210
popup
211
}
212
213
fn leave_description(member_count: usize) -> String {
214
let who = match member_count {
215
0 | 1 => "The other members".to_owned(),
216
2 => "The other member".to_owned(),
217
count => format!("The {} other members", count - 1),
218
};
219
let verb = if member_count == 2 { "sees" } else { "see" };
220
format!("{who} {verb} that you left. You can only come back if someone adds you.")
221
}
222
223
fn confirm_leave(
224
state: &Entity<AppState>,
225
chat_id: &str,
226
title: &str,
227
member_count: usize,
228
window: &mut Window,
229
cx: &mut App,
230
) {
231
let state = state.clone();
232
let chat_id = chat_id.to_owned();
233
let heading = format!("Leave \"{}\"?", truncated(title, TITLE_LIMIT));
234
let description = leave_description(member_count);
235
window.open_alert_dialog(cx, move |alert, _, _| {
236
let state = state.clone();
237
let chat_id = chat_id.clone();
238
let cancel = Button::new("leave-cancel")
239
.label("Cancel")
240
.on_click(|_, window, cx| window.close_dialog(cx));
241
let leave = Button::new("leave-confirm")
242
.label("Leave")
243
.danger()
244
.on_click(move |_, window, cx| {
245
state.update(cx, |state, cx| state.leave_chat(&chat_id, cx));
246
window.close_dialog(cx);
247
});
248
alert
249
.title(heading.clone())
250
.description(description.clone())
251
.footer(DialogFooter::new().child(cancel).child(leave))
252
.on_ok(|_, _, _| false)
253
});
254
}
255
76
256
pub struct SidebarView {
77
257
state: Entity<AppState>,
78
258
tab: SidebarTab,
@@ -362,15 +542,31 @@ impl SidebarView {
362
542
})
363
543
.text_color(theme::text())
364
544
.child(item.title.clone());
365
let time = div()
545
let time = h_flex()
366
546
.flex_none()
547
.gap(px(4.))
548
.items_center()
367
549
.text_size(px(11.))
368
550
.text_color(if unread {
369
551
theme::accent_text()
370
552
} else {
371
553
theme::text_muted()
372
554
})
555
.when(item.muted, |time| {
556
time.child(icon(
557
IconName::BellOff,
558
MUTED_ICON_SIZE,
559
theme::text_faint(),
560
))
561
})
373
562
.child(item.time_label.clone());
563
let preview_color = if item.muted {
564
theme::text_faint()
565
} else if unread {
566
theme::text_strong()
567
} else {
568
theme::text_muted()
569
};
374
570
let preview = preview_text(&item.preview).map(|(text, italic)| {
375
571
let glyph = preview_icon(&text);
376
572
h_flex()
@@ -381,22 +577,8 @@ impl SidebarView {
381
577
.items_center()
382
578
.text_size(px(12.5))
383
579
.when(italic, |preview| preview.italic())
384
.text_color(if unread {
385
theme::text_strong()
386
} else {
387
theme::text_muted()
388
})
389
.children(glyph.map(|name| {
390
icon(
391
name,
392
12.,
393
if unread {
394
theme::text_strong()
395
} else {
396
theme::text_muted()
397
},
398
)
399
}))
580
.text_color(preview_color)
581
.children(glyph.map(|name| icon(name, 12., preview_color)))
400
582
.child(div().truncate().child(text))
401
583
});
402
584
let lines = v_flex()
@@ -416,7 +598,7 @@ impl SidebarView {
416
598
.gap(px(8.))
417
599
.items_center()
418
600
.child(preview.unwrap_or_else(|| div().flex_1()))
419
.children(unread_marker(item.unread)),
601
.children(unread_marker(item.unread, item.muted)),
420
602
);
421
603
let state = self.state.clone();
422
604
let chat_id = item.id.clone();
@@ -426,7 +608,15 @@ impl SidebarView {
426
608
};
427
609
let pinned = menu.favorites_id.is_some() && item.folder_id == menu.favorites_id;
428
610
let menu_context = menu.clone();
429
let menu_chat_id = item.id.clone();
611
let target = ChatMenuTarget {
612
id: item.id.clone(),
613
title: item.title.clone(),
614
pinned,
615
unread,
616
muted: item.muted,
617
is_group: item.is_group,
618
member_count: item.member_count,
619
};
430
620
h_flex()
431
621
.id(SharedString::from(format!("chat-{}", item.id)))
432
622
.mx(px(8.))
@@ -449,49 +639,7 @@ impl SidebarView {
449
639
state.update(cx, |state, cx| state.select(selection, cx));
450
640
})
451
641
.context_menu(move |popup, window, cx| {
452
let context = menu_context.clone();
453
let chat_id = menu_chat_id.clone();
454
let pin_state = context.state.clone();
455
let pin_id = chat_id.clone();
456
let mut popup = popup.item(
457
PopupMenuItem::new(if pinned { "Unpin" } else { "Pin" }).on_click(
458
move |_, _, cx| {
459
pin_state.update(cx, |state, cx| {
460
if pinned {
461
state.move_chat(&pin_id, None, cx);
462
} else {
463
state.pin_chat(&pin_id, cx);
464
}
465
});
466
},
467
),
468
);
469
if !context.folders.is_empty() {
470
let folders = context.folders.clone();
471
let move_state = context.state.clone();
472
let move_id = chat_id.clone();
473
popup = popup.submenu("Move to folder", window, cx, move |submenu, _, _| {
474
folders.iter().fold(submenu, |submenu, (folder_id, name)| {
475
let (state, chat_id, folder_id) =
476
(move_state.clone(), move_id.clone(), folder_id.clone());
477
submenu.item(PopupMenuItem::new(name.clone()).on_click(
478
move |_, _, cx| {
479
state.update(cx, |state, cx| {
480
state.move_chat(&chat_id, Some(&folder_id), cx)
481
});
482
},
483
))
484
})
485
});
486
}
487
let read_state = context.state.clone();
488
popup.item(
489
PopupMenuItem::new("Mark as read")
490
.disabled(!unread)
491
.on_click(move |_, _, cx| {
492
read_state.update(cx, |state, cx| state.mark_chat_read(&chat_id, cx));
493
}),
494
)
642
chat_menu(popup, window, cx, &menu_context, &target)
495
643
})
496
644
.into_any_element()
497
645
}
@@ -1084,3 +1232,18 @@ impl Render for SidebarView {
1084
1232
.child(body)
1085
1233
}
1086
1234
}
1235
1236
#[cfg(test)]
1237
mod tests {
1238
use super::leave_description;
1239
1240
#[test]
1241
fn leave_text_counts_the_other_members() {
1242
assert_eq!(
1243
leave_description(4),
1244
"The 3 other members see that you left. You can only come back if someone adds you."
1245
);
1246
assert!(leave_description(2).starts_with("The other member sees"));
1247
assert!(leave_description(0).starts_with("The other members see"));
1248
}
1249
}
@@ -2,8 +2,10 @@ use std::collections::HashSet;2
2
3
use chrono::{Local, Offset, Utc};3
use chrono::{Local, Offset, Utc};4
use gpui_kit::assets::IconName;4
use gpui_kit::assets::IconName;5
use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};5
use gpui_kit::component::button::{Button, ButtonVariants as _};6
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};6
use gpui_kit::component::dialog::DialogFooter;7
use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenu, PopupMenuItem};8
use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};7
use gpui_kit::prelude::FluentBuilder as _;9
use gpui_kit::prelude::FluentBuilder as _;8
use gpui_kit::*;10
use gpui_kit::*;9
use store::{ChannelRecord, SidebarTeam, TeamRecord};11
use store::{ChannelRecord, SidebarTeam, TeamRecord};@@ -11,8 +13,10 @@ use store::{ChannelRecord, SidebarTeam, TeamRecord};11
use super::avatar::{spec_avatar, square_avatar, with_presence};13
use super::avatar::{spec_avatar, square_avatar, with_presence};12
use super::widgets::{count_badge, dot, icon, symbol, unread_marker};14
use super::widgets::{count_badge, dot, icon, symbol, unread_marker};13
use crate::app_state::{AppEvent, AppState, Selection};15
use crate::app_state::{AppEvent, AppState, Selection};16
use crate::chat_actions::TITLE_LIMIT;14
use crate::data::{Directory, FolderKind};17
use crate::data::{Directory, FolderKind};15
use crate::format;18
use crate::format;19
use crate::notice::truncated;16
use crate::sidebar_model::{20
use crate::sidebar_model::{17
AvatarSpec, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section, SectionInput,21
AvatarSpec, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section, SectionInput,18
SectionKind, any_unread_channel, build_sections, unread_chat_count,22
SectionKind, any_unread_channel, build_sections, unread_chat_count,@@ -34,6 +38,8 @@ const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";34
const TEAM_ROW_HEIGHT: f32 = 40.;38
const TEAM_ROW_HEIGHT: f32 = 40.;35
const REVEAL_ROW_HEIGHT: f32 = 32.;39
const REVEAL_ROW_HEIGHT: f32 = 32.;36
const NEW_CHAT_BUTTON_SIZE: f32 = 34.;40
const NEW_CHAT_BUTTON_SIZE: f32 = 34.;41
const MENU_ICON_SIZE: f32 = 15.;42
const MUTED_ICON_SIZE: f32 = 13.;37
43
38
#[derive(Debug, Clone, Copy, PartialEq, Eq)]44
#[derive(Debug, Clone, Copy, PartialEq, Eq)]39
enum SidebarTab {45
enum SidebarTab {@@ -66,6 +72,16 @@ impl Render for DragGhost {66
}72
}67
}73
}68
74
75
struct ChatMenuTarget {76
id: String,77
title: String,78
pinned: bool,79
unread: bool,80
muted: bool,81
is_group: bool,82
member_count: usize,83
}84
69
#[derive(Clone)]85
#[derive(Clone)]70
struct MenuContext {86
struct MenuContext {71
state: Entity<AppState>,87
state: Entity<AppState>,@@ -73,6 +89,170 @@ struct MenuContext {73
favorites_id: Option<String>,89
favorites_id: Option<String>,74
}90
}75
91
92
fn menu_icon(name: IconName) -> gpui_kit::component::Icon {93
icon(name, MENU_ICON_SIZE, theme::text_muted())94
}95
96
fn chat_menu(97
popup: PopupMenu,98
window: &mut Window,99
cx: &mut Context<PopupMenu>,100
context: &MenuContext,101
target: &ChatMenuTarget,102
) -> PopupMenu {103
let pinned = target.pinned;104
let pin_state = context.state.clone();105
let pin_id = target.id.clone();106
let mut popup = popup.item(107
PopupMenuItem::new(if pinned { "Unpin" } else { "Pin" })108
.icon(menu_icon(if pinned {109
IconName::PinOff110
} else {111
IconName::Pin112
}))113
.on_click(move |_, _, cx| {114
pin_state.update(cx, |state, cx| {115
if pinned {116
state.move_chat(&pin_id, None, cx);117
} else {118
state.pin_chat(&pin_id, cx);119
}120
});121
}),122
);123
if !context.folders.is_empty() {124
let folders = context.folders.clone();125
let move_state = context.state.clone();126
let move_id = target.id.clone();127
popup = popup.submenu_with_icon(128
Some(menu_icon(IconName::Folder)),129
"Move to folder",130
window,131
cx,132
move |submenu, _, _| {133
folders.iter().fold(submenu, |submenu, (folder_id, name)| {134
let (state, chat_id, folder_id) =135
(move_state.clone(), move_id.clone(), folder_id.clone());136
submenu.item(PopupMenuItem::new(name.clone()).on_click(move |_, _, cx| {137
state.update(cx, |state, cx| {138
state.move_chat(&chat_id, Some(&folder_id), cx)139
});140
}))141
})142
},143
);144
}145
let read_state = context.state.clone();146
let read_id = target.id.clone();147
let unread = target.unread;148
let mute_state = context.state.clone();149
let mute_id = target.id.clone();150
let muted = target.muted;151
let hide_state = context.state.clone();152
let hide_id = target.id.clone();153
popup = popup154
.separator()155
.item(156
PopupMenuItem::new(if unread {157
"Mark as read"158
} else {159
"Mark as unread"160
})161
.icon(menu_icon(if unread {162
IconName::MailOpen163
} else {164
IconName::Mail165
}))166
.on_click(move |_, _, cx| {167
read_state.update(cx, |state, cx| {168
if unread {169
state.mark_chat_read(&read_id, cx);170
} else {171
state.mark_chat_unread(&read_id, cx);172
}173
});174
}),175
)176
.item(177
PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })178
.icon(menu_icon(if muted {179
IconName::Bell180
} else {181
IconName::BellOff182
}))183
.on_click(move |_, _, cx| {184
mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));185
}),186
)187
.separator()188
.item(189
PopupMenuItem::new("Hide")190
.icon(menu_icon(IconName::EyeOff))191
.on_click(move |_, _, cx| {192
hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));193
}),194
);195
if target.is_group {196
let leave_state = context.state.clone();197
let leave_id = target.id.clone();198
let title = target.title.clone();199
let member_count = target.member_count;200
popup = popup.item(201
PopupMenuItem::element(|_, _| {202
div().text_color(theme::red_soft()).child("Leave chat...")203
})204
.icon(icon(IconName::LogOut, MENU_ICON_SIZE, theme::red_soft()))205
.on_click(move |_, window, cx| {206
confirm_leave(&leave_state, &leave_id, &title, member_count, window, cx);207
}),208
);209
}210
popup211
}212
213
fn leave_description(member_count: usize) -> String {214
let who = match member_count {215
0 | 1 => "The other members".to_owned(),216
2 => "The other member".to_owned(),217
count => format!("The {} other members", count - 1),218
};219
let verb = if member_count == 2 { "sees" } else { "see" };220
format!("{who} {verb} that you left. You can only come back if someone adds you.")221
}222
223
fn confirm_leave(224
state: &Entity<AppState>,225
chat_id: &str,226
title: &str,227
member_count: usize,228
window: &mut Window,229
cx: &mut App,230
) {231
let state = state.clone();232
let chat_id = chat_id.to_owned();233
let heading = format!("Leave \"{}\"?", truncated(title, TITLE_LIMIT));234
let description = leave_description(member_count);235
window.open_alert_dialog(cx, move |alert, _, _| {236
let state = state.clone();237
let chat_id = chat_id.clone();238
let cancel = Button::new("leave-cancel")239
.label("Cancel")240
.on_click(|_, window, cx| window.close_dialog(cx));241
let leave = Button::new("leave-confirm")242
.label("Leave")243
.danger()244
.on_click(move |_, window, cx| {245
state.update(cx, |state, cx| state.leave_chat(&chat_id, cx));246
window.close_dialog(cx);247
});248
alert249
.title(heading.clone())250
.description(description.clone())251
.footer(DialogFooter::new().child(cancel).child(leave))252
.on_ok(|_, _, _| false)253
});254
}255
76
pub struct SidebarView {256
pub struct SidebarView {77
state: Entity<AppState>,257
state: Entity<AppState>,78
tab: SidebarTab,258
tab: SidebarTab,@@ -362,15 +542,31 @@ impl SidebarView {362
})542
})363
.text_color(theme::text())543
.text_color(theme::text())364
.child(item.title.clone());544
.child(item.title.clone());365
let time = div()545
let time = h_flex()366
.flex_none()546
.flex_none()547
.gap(px(4.))548
.items_center()367
.text_size(px(11.))549
.text_size(px(11.))368
.text_color(if unread {550
.text_color(if unread {369
theme::accent_text()551
theme::accent_text()370
} else {552
} else {371
theme::text_muted()553
theme::text_muted()372
})554
})555
.when(item.muted, |time| {556
time.child(icon(557
IconName::BellOff,558
MUTED_ICON_SIZE,559
theme::text_faint(),560
))561
})373
.child(item.time_label.clone());562
.child(item.time_label.clone());563
let preview_color = if item.muted {564
theme::text_faint()565
} else if unread {566
theme::text_strong()567
} else {568
theme::text_muted()569
};374
let preview = preview_text(&item.preview).map(|(text, italic)| {570
let preview = preview_text(&item.preview).map(|(text, italic)| {375
let glyph = preview_icon(&text);571
let glyph = preview_icon(&text);376
h_flex()572
h_flex()@@ -381,22 +577,8 @@ impl SidebarView {381
.items_center()577
.items_center()382
.text_size(px(12.5))578
.text_size(px(12.5))383
.when(italic, |preview| preview.italic())579
.when(italic, |preview| preview.italic())384
.text_color(if unread {580
.text_color(preview_color)385
theme::text_strong()581
.children(glyph.map(|name| icon(name, 12., preview_color)))386
} else {387
theme::text_muted()388
})389
.children(glyph.map(|name| {390
icon(391
name,392
12.,393
if unread {394
theme::text_strong()395
} else {396
theme::text_muted()397
},398
)399
}))400
.child(div().truncate().child(text))582
.child(div().truncate().child(text))401
});583
});402
let lines = v_flex()584
let lines = v_flex()@@ -416,7 +598,7 @@ impl SidebarView {416
.gap(px(8.))598
.gap(px(8.))417
.items_center()599
.items_center()418
.child(preview.unwrap_or_else(|| div().flex_1()))600
.child(preview.unwrap_or_else(|| div().flex_1()))419
.children(unread_marker(item.unread)),601
.children(unread_marker(item.unread, item.muted)),420
);602
);421
let state = self.state.clone();603
let state = self.state.clone();422
let chat_id = item.id.clone();604
let chat_id = item.id.clone();@@ -426,7 +608,15 @@ impl SidebarView {426
};608
};427
let pinned = menu.favorites_id.is_some() && item.folder_id == menu.favorites_id;609
let pinned = menu.favorites_id.is_some() && item.folder_id == menu.favorites_id;428
let menu_context = menu.clone();610
let menu_context = menu.clone();429
let menu_chat_id = item.id.clone();611
let target = ChatMenuTarget {612
id: item.id.clone(),613
title: item.title.clone(),614
pinned,615
unread,616
muted: item.muted,617
is_group: item.is_group,618
member_count: item.member_count,619
};430
h_flex()620
h_flex()431
.id(SharedString::from(format!("chat-{}", item.id)))621
.id(SharedString::from(format!("chat-{}", item.id)))432
.mx(px(8.))622
.mx(px(8.))@@ -449,49 +639,7 @@ impl SidebarView {449
state.update(cx, |state, cx| state.select(selection, cx));639
state.update(cx, |state, cx| state.select(selection, cx));450
})640
})451
.context_menu(move |popup, window, cx| {641
.context_menu(move |popup, window, cx| {452
let context = menu_context.clone();642
chat_menu(popup, window, cx, &menu_context, &target)453
let chat_id = menu_chat_id.clone();454
let pin_state = context.state.clone();455
let pin_id = chat_id.clone();456
let mut popup = popup.item(457
PopupMenuItem::new(if pinned { "Unpin" } else { "Pin" }).on_click(458
move |_, _, cx| {459
pin_state.update(cx, |state, cx| {460
if pinned {461
state.move_chat(&pin_id, None, cx);462
} else {463
state.pin_chat(&pin_id, cx);464
}465
});466
},467
),468
);469
if !context.folders.is_empty() {470
let folders = context.folders.clone();471
let move_state = context.state.clone();472
let move_id = chat_id.clone();473
popup = popup.submenu("Move to folder", window, cx, move |submenu, _, _| {474
folders.iter().fold(submenu, |submenu, (folder_id, name)| {475
let (state, chat_id, folder_id) =476
(move_state.clone(), move_id.clone(), folder_id.clone());477
submenu.item(PopupMenuItem::new(name.clone()).on_click(478
move |_, _, cx| {479
state.update(cx, |state, cx| {480
state.move_chat(&chat_id, Some(&folder_id), cx)481
});482
},483
))484
})485
});486
}487
let read_state = context.state.clone();488
popup.item(489
PopupMenuItem::new("Mark as read")490
.disabled(!unread)491
.on_click(move |_, _, cx| {492
read_state.update(cx, |state, cx| state.mark_chat_read(&chat_id, cx));493
}),494
)495
})643
})496
.into_any_element()644
.into_any_element()497
}645
}@@ -1084,3 +1232,18 @@ impl Render for SidebarView {1084
.child(body)1232
.child(body)1085
}1233
}1086
}1234
}1235
1236
#[cfg(test)]1237
mod tests {1238
use super::leave_description;1239
1240
#[test]1241
fn leave_text_counts_the_other_members() {1242
assert_eq!(1243
leave_description(4),1244
"The 3 other members see that you left. You can only come back if someone adds you."1245
);1246
assert!(leave_description(2).starts_with("The other member sees"));1247
assert!(leave_description(0).starts_with("The other members see"));1248
}1249
}@@ -59,6 +59,7 @@ pub fn render_status_bar(
59
59
state: &AppState,
60
60
update: &UpdateStatus,
61
61
on_restart: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
62
on_notice_action: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
62
63
) -> impl IntoElement {
63
64
let (connection, connection_tone) = connection_text(&state.connection, state.mode);
64
65
let item = |label: String, tone: Tone| {
@@ -115,6 +116,29 @@ pub fn render_status_bar(
115
116
)
116
117
}
117
118
}
119
if let Some(notice) = &state.notice {
120
bar = bar.child(
121
h_flex()
122
.min_w_0()
123
.gap(px(8.))
124
.items_center()
125
.text_color(theme::amber())
126
.child(div().min_w_0().truncate().child(notice.text.clone()))
127
.children(notice.action.as_ref().map(|action| {
128
div()
129
.id("notice-action")
130
.flex_none()
131
.px(px(6.))
132
.rounded(px(4.))
133
.cursor_pointer()
134
.font_weight(FontWeight::SEMIBOLD)
135
.text_color(theme::accent_text())
136
.hover(|button| button.bg(theme::row_hover()))
137
.child(action.label.clone())
138
.on_click(on_notice_action)
139
})),
140
);
141
}
118
142
let full_version = updater::running_version();
119
143
bar.child(
120
144
div()
@@ -59,6 +59,7 @@ pub fn render_status_bar(59
state: &AppState,59
state: &AppState,60
update: &UpdateStatus,60
update: &UpdateStatus,61
on_restart: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,61
on_restart: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,62
on_notice_action: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,62
) -> impl IntoElement {63
) -> impl IntoElement {63
let (connection, connection_tone) = connection_text(&state.connection, state.mode);64
let (connection, connection_tone) = connection_text(&state.connection, state.mode);64
let item = |label: String, tone: Tone| {65
let item = |label: String, tone: Tone| {@@ -115,6 +116,29 @@ pub fn render_status_bar(115
)116
)116
}117
}117
}118
}119
if let Some(notice) = &state.notice {120
bar = bar.child(121
h_flex()122
.min_w_0()123
.gap(px(8.))124
.items_center()125
.text_color(theme::amber())126
.child(div().min_w_0().truncate().child(notice.text.clone()))127
.children(notice.action.as_ref().map(|action| {128
div()129
.id("notice-action")130
.flex_none()131
.px(px(6.))132
.rounded(px(4.))133
.cursor_pointer()134
.font_weight(FontWeight::SEMIBOLD)135
.text_color(theme::accent_text())136
.hover(|button| button.bg(theme::row_hover()))137
.child(action.label.clone())138
.on_click(on_notice_action)139
})),140
);141
}118
let full_version = updater::running_version();142
let full_version = updater::running_version();119
bar.child(143
bar.child(120
div()144
div()@@ -48,11 +48,12 @@ pub fn dot(size: f32) -> Div {
48
48
.bg(theme::accent())
49
49
}
50
50
51
pub fn unread_marker(unread: Unread) -> Option<Div> {
51
pub fn unread_marker(unread: Unread, muted: bool) -> Option<Div> {
52
52
match unread {
53
53
Unread::None => None,
54
Unread::Dot if muted => Some(dot(8.).bg(theme::badge_muted())),
54
55
Unread::Dot => Some(dot(8.)),
55
Unread::Count(count) => Some(count_badge(count, false)),
56
Unread::Count(count) => Some(count_badge(count, muted)),
56
57
}
57
58
}
58
59
@@ -48,11 +48,12 @@ pub fn dot(size: f32) -> Div {48
.bg(theme::accent())48
.bg(theme::accent())49
}49
}50
50
51
pub fn unread_marker(unread: Unread) -> Option<Div> {51
pub fn unread_marker(unread: Unread, muted: bool) -> Option<Div> {52
match unread {52
match unread {53
Unread::None => None,53
Unread::None => None,54
Unread::Dot if muted => Some(dot(8.).bg(theme::badge_muted())),54
Unread::Dot => Some(dot(8.)),55
Unread::Dot => Some(dot(8.)),55
Unread::Count(count) => Some(count_badge(count, false)),56
Unread::Count(count) => Some(count_badge(count, muted)),56
}57
}57
}58
}58
59
@@ -0,0 +1,183 @@
1
use serde_json::{Value, json};
2
use session::{Method, Request, Session};
3
4
use crate::error::{Error, Result};
5
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
6
use crate::pins::DEFAULT_REGION;
7
8
const PAGE_SIZE: usize = 200;
9
const ALERTS_OFF: &str = "false";
10
11
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
12
transport: T,
13
base_url: String,
14
}
15
16
impl Conversations<SessionMessageTransport> {
17
pub fn new(session: &Session) -> Self {
18
Self::with_region(session, DEFAULT_REGION)
19
}
20
21
pub fn with_region(session: &Session, region: &str) -> Self {
22
Conversations::with_transport(SessionMessageTransport::new(session), region)
23
}
24
}
25
26
impl<T: MessageTransport> Conversations<T> {
27
pub fn with_transport(transport: T, region: &str) -> Self {
28
Conversations {
29
transport,
30
base_url: format!(
31
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations"
32
),
33
}
34
}
35
36
pub fn alerts_url(&self, conversation_id: &str) -> String {
37
format!(
38
"{}/{}/properties?name=alerts",
39
self.base_url,
40
encode(conversation_id)
41
)
42
}
43
44
pub async fn conversation_mute_states(&self) -> Result<Vec<(String, bool)>> {
45
let url = format!(
46
"{}?view=msnp24Equivalent&pageSize={PAGE_SIZE}",
47
self.base_url
48
);
49
let answer = self.transport.send(Request::get(&url)).await?;
50
ensure_success(&answer)?;
51
mute_states_in_page(&answer.body)
52
}
53
54
pub async fn set_alerts(&self, conversation_id: &str, enabled: bool) -> Result<()> {
55
let body = json!({"alerts": if enabled { "true" } else { ALERTS_OFF }});
56
let answer = self
57
.transport
58
.send(Request::with_body(
59
Method::Put,
60
self.alerts_url(conversation_id),
61
body,
62
))
63
.await?;
64
ensure_success(&answer)
65
}
66
}
67
68
fn mute_states_in_page(body: &Value) -> Result<Vec<(String, bool)>> {
69
let conversations = body
70
.get("conversations")
71
.and_then(Value::as_array)
72
.ok_or_else(|| Error::UnexpectedAnswer("no conversations list".into()))?;
73
Ok(conversations
74
.iter()
75
.filter_map(|conversation| {
76
let id = conversation["id"].as_str()?;
77
let muted = conversation["properties"]["alerts"].as_str() == Some(ALERTS_OFF);
78
Some((id.to_owned(), muted))
79
})
80
.collect())
81
}
82
83
#[cfg(test)]
84
mod tests {
85
use std::collections::VecDeque;
86
use std::sync::Mutex;
87
88
use session::ApiResponse;
89
90
use super::*;
91
92
struct Canned {
93
answers: Mutex<VecDeque<(u16, Value)>>,
94
requests: Mutex<Vec<Request>>,
95
}
96
97
impl MessageTransport for &Canned {
98
async fn send(&self, request: Request) -> Result<ApiResponse> {
99
self.requests.lock().unwrap().push(request);
100
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
101
Ok(ApiResponse {
102
status,
103
body,
104
retry_after: None,
105
})
106
}
107
}
108
109
fn canned(answers: Vec<(u16, Value)>) -> Canned {
110
Canned {
111
answers: Mutex::new(answers.into()),
112
requests: Mutex::new(Vec::new()),
113
}
114
}
115
116
const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations";
117
118
#[tokio::test]
119
async fn mute_states_pair_every_conversation_with_its_flag() {
120
let transport = canned(vec![(
121
200,
122
json!({
123
"conversations": [
124
{"id": "19:a", "properties": {"alerts": "false"}},
125
{"id": "19:b", "properties": {"alerts": "true"}},
126
{"id": "19:c", "properties": {}},
127
{"id": "19:d"},
128
],
129
"_metadata": {"backwardLink": "https://example.test/next"},
130
}),
131
)]);
132
let states = Conversations::with_transport(&transport, "emea")
133
.conversation_mute_states()
134
.await
135
.unwrap();
136
assert_eq!(
137
states,
138
vec![
139
("19:a".to_owned(), true),
140
("19:b".to_owned(), false),
141
("19:c".to_owned(), false),
142
("19:d".to_owned(), false),
143
]
144
);
145
let requests = transport.requests.lock().unwrap();
146
assert_eq!(requests.len(), 1);
147
assert_eq!(
148
requests[0].url,
149
format!("{BASE}?view=msnp24Equivalent&pageSize=200")
150
);
151
}
152
153
#[tokio::test]
154
async fn mute_states_fail_on_an_error_status() {
155
let transport = canned(vec![(500, Value::Null)]);
156
let outcome = Conversations::with_transport(&transport, "emea")
157
.conversation_mute_states()
158
.await;
159
assert!(outcome.is_err());
160
}
161
162
#[tokio::test]
163
async fn set_alerts_puts_the_flag_as_text() {
164
let transport = canned(vec![(200, Value::Null), (200, Value::Null)]);
165
let conversations = Conversations::with_transport(&transport, "emea");
166
conversations
167
.set_alerts("19:a@thread.v2", false)
168
.await
169
.unwrap();
170
conversations
171
.set_alerts("19:a@thread.v2", true)
172
.await
173
.unwrap();
174
let requests = transport.requests.lock().unwrap();
175
assert_eq!(requests[0].method, Method::Put);
176
assert_eq!(
177
requests[0].url,
178
format!("{BASE}/19%3Aa%40thread.v2/properties?name=alerts")
179
);
180
assert_eq!(requests[0].body, Some(json!({"alerts": "false"})));
181
assert_eq!(requests[1].body, Some(json!({"alerts": "true"})));
182
}
183
}
@@ -0,0 +1,183 @@1
use serde_json::{Value, json};2
use session::{Method, Request, Session};3
4
use crate::error::{Error, Result};5
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};6
use crate::pins::DEFAULT_REGION;7
8
const PAGE_SIZE: usize = 200;9
const ALERTS_OFF: &str = "false";10
11
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {12
transport: T,13
base_url: String,14
}15
16
impl Conversations<SessionMessageTransport> {17
pub fn new(session: &Session) -> Self {18
Self::with_region(session, DEFAULT_REGION)19
}20
21
pub fn with_region(session: &Session, region: &str) -> Self {22
Conversations::with_transport(SessionMessageTransport::new(session), region)23
}24
}25
26
impl<T: MessageTransport> Conversations<T> {27
pub fn with_transport(transport: T, region: &str) -> Self {28
Conversations {29
transport,30
base_url: format!(31
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations"32
),33
}34
}35
36
pub fn alerts_url(&self, conversation_id: &str) -> String {37
format!(38
"{}/{}/properties?name=alerts",39
self.base_url,40
encode(conversation_id)41
)42
}43
44
pub async fn conversation_mute_states(&self) -> Result<Vec<(String, bool)>> {45
let url = format!(46
"{}?view=msnp24Equivalent&pageSize={PAGE_SIZE}",47
self.base_url48
);49
let answer = self.transport.send(Request::get(&url)).await?;50
ensure_success(&answer)?;51
mute_states_in_page(&answer.body)52
}53
54
pub async fn set_alerts(&self, conversation_id: &str, enabled: bool) -> Result<()> {55
let body = json!({"alerts": if enabled { "true" } else { ALERTS_OFF }});56
let answer = self57
.transport58
.send(Request::with_body(59
Method::Put,60
self.alerts_url(conversation_id),61
body,62
))63
.await?;64
ensure_success(&answer)65
}66
}67
68
fn mute_states_in_page(body: &Value) -> Result<Vec<(String, bool)>> {69
let conversations = body70
.get("conversations")71
.and_then(Value::as_array)72
.ok_or_else(|| Error::UnexpectedAnswer("no conversations list".into()))?;73
Ok(conversations74
.iter()75
.filter_map(|conversation| {76
let id = conversation["id"].as_str()?;77
let muted = conversation["properties"]["alerts"].as_str() == Some(ALERTS_OFF);78
Some((id.to_owned(), muted))79
})80
.collect())81
}82
83
#[cfg(test)]84
mod tests {85
use std::collections::VecDeque;86
use std::sync::Mutex;87
88
use session::ApiResponse;89
90
use super::*;91
92
struct Canned {93
answers: Mutex<VecDeque<(u16, Value)>>,94
requests: Mutex<Vec<Request>>,95
}96
97
impl MessageTransport for &Canned {98
async fn send(&self, request: Request) -> Result<ApiResponse> {99
self.requests.lock().unwrap().push(request);100
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");101
Ok(ApiResponse {102
status,103
body,104
retry_after: None,105
})106
}107
}108
109
fn canned(answers: Vec<(u16, Value)>) -> Canned {110
Canned {111
answers: Mutex::new(answers.into()),112
requests: Mutex::new(Vec::new()),113
}114
}115
116
const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations";117
118
#[tokio::test]119
async fn mute_states_pair_every_conversation_with_its_flag() {120
let transport = canned(vec![(121
200,122
json!({123
"conversations": [124
{"id": "19:a", "properties": {"alerts": "false"}},125
{"id": "19:b", "properties": {"alerts": "true"}},126
{"id": "19:c", "properties": {}},127
{"id": "19:d"},128
],129
"_metadata": {"backwardLink": "https://example.test/next"},130
}),131
)]);132
let states = Conversations::with_transport(&transport, "emea")133
.conversation_mute_states()134
.await135
.unwrap();136
assert_eq!(137
states,138
vec![139
("19:a".to_owned(), true),140
("19:b".to_owned(), false),141
("19:c".to_owned(), false),142
("19:d".to_owned(), false),143
]144
);145
let requests = transport.requests.lock().unwrap();146
assert_eq!(requests.len(), 1);147
assert_eq!(148
requests[0].url,149
format!("{BASE}?view=msnp24Equivalent&pageSize=200")150
);151
}152
153
#[tokio::test]154
async fn mute_states_fail_on_an_error_status() {155
let transport = canned(vec![(500, Value::Null)]);156
let outcome = Conversations::with_transport(&transport, "emea")157
.conversation_mute_states()158
.await;159
assert!(outcome.is_err());160
}161
162
#[tokio::test]163
async fn set_alerts_puts_the_flag_as_text() {164
let transport = canned(vec![(200, Value::Null), (200, Value::Null)]);165
let conversations = Conversations::with_transport(&transport, "emea");166
conversations167
.set_alerts("19:a@thread.v2", false)168
.await169
.unwrap();170
conversations171
.set_alerts("19:a@thread.v2", true)172
.await173
.unwrap();174
let requests = transport.requests.lock().unwrap();175
assert_eq!(requests[0].method, Method::Put);176
assert_eq!(177
requests[0].url,178
format!("{BASE}/19%3Aa%40thread.v2/properties?name=alerts")179
);180
assert_eq!(requests[0].body, Some(json!({"alerts": "false"})));181
assert_eq!(requests[1].body, Some(json!({"alerts": "true"})));182
}183
}@@ -1,4 +1,5 @@
1
1
pub mod cards;
2
pub mod conversations;
2
3
mod error;
3
4
mod mask;
4
5
pub mod messages;
@@ -10,6 +11,7 @@ pub mod receipts;
10
11
pub use cards::{
11
12
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
12
13
};
14
pub use conversations::Conversations;
13
15
pub use error::{Error, Result};
14
16
pub use mask::mask_conversation_id;
15
17
pub use messages::{ConversationRef, Messages};
@@ -1,4 +1,5 @@1
pub mod cards;1
pub mod cards;2
pub mod conversations;2
mod error;3
mod error;3
mod mask;4
mod mask;4
pub mod messages;5
pub mod messages;@@ -10,6 +11,7 @@ pub mod receipts;10
pub use cards::{11
pub use cards::{11
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,12
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,12
};13
};14
pub use conversations::Conversations;13
pub use error::{Error, Result};15
pub use error::{Error, Result};14
pub use mask::mask_conversation_id;16
pub use mask::mask_conversation_id;15
pub use messages::{ConversationRef, Messages};17
pub use messages::{ConversationRef, Messages};@@ -247,7 +247,7 @@ fn edit_body(message_id: &str, html: &str) -> Value {
247
247
})
248
248
}
249
249
250
fn ensure_success(answer: &ApiResponse) -> Result<()> {
250
pub(crate) fn ensure_success(answer: &ApiResponse) -> Result<()> {
251
251
if answer.is_success() {
252
252
Ok(())
253
253
} else {
@@ -247,7 +247,7 @@ fn edit_body(message_id: &str, html: &str) -> Value {247
})247
})248
}248
}249
249
250
fn ensure_success(answer: &ApiResponse) -> Result<()> {250
pub(crate) fn ensure_success(answer: &ApiResponse) -> Result<()> {251
if answer.is_success() {251
if answer.is_success() {252
Ok(())252
Ok(())253
} else {253
} else {@@ -1,4 +1,4 @@
1
use chrono::Utc;
1
use chrono::{Duration, Utc};
2
2
use graph::{
3
3
FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
4
4
};
@@ -346,6 +346,59 @@ impl<R: Remote> SyncEngine<R> {
346
346
Ok(())
347
347
}
348
348
349
pub async fn mark_unread(&self, chat_id: &str) -> Result<()> {
350
let last_message_at = self
351
.store
352
.chat(chat_id)?
353
.and_then(|chat| chat.last_message_at)
354
.ok_or(Error::Unsupported(
355
"marking a chat without messages as unread",
356
))?;
357
let last_read_at = last_message_at - Duration::milliseconds(1);
358
let user_id = self.my_user_id().await?;
359
let tenant_id = self.my_tenant_id(chat_id).await?;
360
self.remote
361
.mark_chat_unread(chat_id, &user_id, &tenant_id, last_read_at)
362
.await?;
363
self.store.mark_chat_unread(chat_id, last_read_at)?;
364
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
365
Ok(())
366
}
367
368
pub async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
369
self.remote.set_chat_muted(chat_id, muted).await?;
370
self.store.set_chat_muted(chat_id, muted)?;
371
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
372
Ok(())
373
}
374
375
pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
376
let user_id = self.my_user_id().await?;
377
let tenant_id = self.my_tenant_id(chat_id).await?;
378
self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
379
self.store.remove_chats(&[chat_id.to_owned()])?;
380
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
381
Ok(())
382
}
383
384
pub async fn unhide_chat(&self, chat_id: &str) -> Result<()> {
385
let user_id = self.my_user_id().await?;
386
let tenant_id = self.my_tenant_id(chat_id).await?;
387
self.remote
388
.unhide_chat(chat_id, &user_id, &tenant_id)
389
.await?;
390
self.refresh_sidebar_full().await?;
391
Ok(())
392
}
393
394
pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
395
let user_id = self.my_user_id().await?;
396
self.remote.leave_chat(chat_id, &user_id).await?;
397
self.store.remove_chats(&[chat_id.to_owned()])?;
398
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
399
Ok(())
400
}
401
349
402
pub async fn set_reaction(
350
403
&self,
351
404
conversation_id: &str,
@@ -1,4 +1,4 @@1
use chrono::Utc;1
use chrono::{Duration, Utc};2
use graph::{2
use graph::{3
FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,3
FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,4
};4
};@@ -346,6 +346,59 @@ impl<R: Remote> SyncEngine<R> {346
Ok(())346
Ok(())347
}347
}348
348
349
pub async fn mark_unread(&self, chat_id: &str) -> Result<()> {350
let last_message_at = self351
.store352
.chat(chat_id)?353
.and_then(|chat| chat.last_message_at)354
.ok_or(Error::Unsupported(355
"marking a chat without messages as unread",356
))?;357
let last_read_at = last_message_at - Duration::milliseconds(1);358
let user_id = self.my_user_id().await?;359
let tenant_id = self.my_tenant_id(chat_id).await?;360
self.remote361
.mark_chat_unread(chat_id, &user_id, &tenant_id, last_read_at)362
.await?;363
self.store.mark_chat_unread(chat_id, last_read_at)?;364
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);365
Ok(())366
}367
368
pub async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {369
self.remote.set_chat_muted(chat_id, muted).await?;370
self.store.set_chat_muted(chat_id, muted)?;371
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);372
Ok(())373
}374
375
pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {376
let user_id = self.my_user_id().await?;377
let tenant_id = self.my_tenant_id(chat_id).await?;378
self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;379
self.store.remove_chats(&[chat_id.to_owned()])?;380
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);381
Ok(())382
}383
384
pub async fn unhide_chat(&self, chat_id: &str) -> Result<()> {385
let user_id = self.my_user_id().await?;386
let tenant_id = self.my_tenant_id(chat_id).await?;387
self.remote388
.unhide_chat(chat_id, &user_id, &tenant_id)389
.await?;390
self.refresh_sidebar_full().await?;391
Ok(())392
}393
394
pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {395
let user_id = self.my_user_id().await?;396
self.remote.leave_chat(chat_id, &user_id).await?;397
self.store.remove_chats(&[chat_id.to_owned()])?;398
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);399
Ok(())400
}401
349
pub async fn set_reaction(402
pub async fn set_reaction(350
&self,403
&self,351
conversation_id: &str,404
conversation_id: &str,@@ -52,6 +52,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> Option<ChatRecord> {
52
52
last_read_at,
53
53
unread: !last_event_system
54
54
&& is_unread(chat.last_message_time(), last_read_at, last_from_me),
55
muted: false,
55
56
members: chat
56
57
.members
57
58
.iter()
@@ -52,6 +52,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> Option<ChatRecord> {52
last_read_at,52
last_read_at,53
unread: !last_event_system53
unread: !last_event_system54
&& is_unread(chat.last_message_time(), last_read_at, last_from_me),54
&& is_unread(chat.last_message_time(), last_read_at, last_from_me),55
muted: false,55
members: chat56
members: chat56
.members57
.members57
.iter()58
.iter()@@ -1,6 +1,6 @@
1
1
use chatsvc::{
2
CardActions, ChatApp, ConversationRef, InvokeRequest, InvokeResponse, MemberHorizon, Messages,
3
Receipts,
2
CardActions, ChatApp, ConversationRef, Conversations, InvokeRequest, InvokeResponse,
3
MemberHorizon, Messages, Receipts,
4
4
};
5
5
use chrono::{DateTime, Utc};
6
6
use graph::{
@@ -106,6 +106,18 @@ pub trait Remote {
106
106
extras: &MessageExtras,
107
107
) -> Result<Message>;
108
108
async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
109
async fn mark_chat_unread(
110
&self,
111
chat_id: &str,
112
user_id: &str,
113
tenant_id: &str,
114
last_read_at: DateTime<Utc>,
115
) -> Result<()>;
116
async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
117
async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
118
async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
119
async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>>;
120
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
109
121
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
110
122
async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
111
123
async fn edit_message(
@@ -362,6 +374,40 @@ impl Remote for Graph {
362
374
Ok(Graph::mark_chat_read(self, chat_id, user_id, tenant_id).await?)
363
375
}
364
376
377
async fn mark_chat_unread(
378
&self,
379
chat_id: &str,
380
user_id: &str,
381
tenant_id: &str,
382
last_read_at: DateTime<Utc>,
383
) -> Result<()> {
384
Ok(Graph::mark_chat_unread(self, chat_id, user_id, tenant_id, last_read_at).await?)
385
}
386
387
async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
388
Ok(Graph::hide_chat(self, chat_id, user_id, tenant_id).await?)
389
}
390
391
async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
392
Ok(Graph::unhide_chat(self, chat_id, user_id, tenant_id).await?)
393
}
394
395
async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()> {
396
Ok(Graph::leave_chat(self, chat_id, user_id).await?)
397
}
398
399
async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>> {
400
Ok(Conversations::new(self.session())
401
.conversation_mute_states()
402
.await?)
403
}
404
405
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
406
Ok(Conversations::new(self.session())
407
.set_alerts(chat_id, !muted)
408
.await?)
409
}
410
365
411
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
366
412
if let Some(key) = chatsvc::emotion_key(reaction_type) {
367
413
return Ok(Messages::new(self.session())
@@ -1,6 +1,6 @@1
use chatsvc::{1
use chatsvc::{2
CardActions, ChatApp, ConversationRef, InvokeRequest, InvokeResponse, MemberHorizon, Messages,2
CardActions, ChatApp, ConversationRef, Conversations, InvokeRequest, InvokeResponse,3
Receipts,3
MemberHorizon, Messages, Receipts,4
};4
};5
use chrono::{DateTime, Utc};5
use chrono::{DateTime, Utc};6
use graph::{6
use graph::{@@ -106,6 +106,18 @@ pub trait Remote {106
extras: &MessageExtras,106
extras: &MessageExtras,107
) -> Result<Message>;107
) -> Result<Message>;108
async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;108
async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;109
async fn mark_chat_unread(110
&self,111
chat_id: &str,112
user_id: &str,113
tenant_id: &str,114
last_read_at: DateTime<Utc>,115
) -> Result<()>;116
async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;117
async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;118
async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;119
async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>>;120
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;109
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;121
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;110
async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;122
async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;111
async fn edit_message(123
async fn edit_message(@@ -362,6 +374,40 @@ impl Remote for Graph {362
Ok(Graph::mark_chat_read(self, chat_id, user_id, tenant_id).await?)374
Ok(Graph::mark_chat_read(self, chat_id, user_id, tenant_id).await?)363
}375
}364
376
377
async fn mark_chat_unread(378
&self,379
chat_id: &str,380
user_id: &str,381
tenant_id: &str,382
last_read_at: DateTime<Utc>,383
) -> Result<()> {384
Ok(Graph::mark_chat_unread(self, chat_id, user_id, tenant_id, last_read_at).await?)385
}386
387
async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {388
Ok(Graph::hide_chat(self, chat_id, user_id, tenant_id).await?)389
}390
391
async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {392
Ok(Graph::unhide_chat(self, chat_id, user_id, tenant_id).await?)393
}394
395
async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()> {396
Ok(Graph::leave_chat(self, chat_id, user_id).await?)397
}398
399
async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>> {400
Ok(Conversations::new(self.session())401
.conversation_mute_states()402
.await?)403
}404
405
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {406
Ok(Conversations::new(self.session())407
.set_alerts(chat_id, !muted)408
.await?)409
}410
365
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {411
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {366
if let Some(key) = chatsvc::emotion_key(reaction_type) {412
if let Some(key) = chatsvc::emotion_key(reaction_type) {367
return Ok(Messages::new(self.session())413
return Ok(Messages::new(self.session())@@ -2,7 +2,7 @@ use chrono::{DateTime, Duration, Utc};
2
2
use store::ChatRecord;
3
3
4
4
use crate::engine::{SidebarSummary, SyncEngine};
5
use crate::error::Result;
5
use crate::error::{Error, Result};
6
6
use crate::events::CoreEvent;
7
7
use crate::mapping::{channel_record, chat_record, team_record};
8
8
use crate::remote::{ChatsPage, Remote};
@@ -81,6 +81,7 @@ impl<R: Remote> SyncEngine<R> {
81
81
page = self.remote.chats_at(&link).await?;
82
82
}
83
83
self.store.remove_chats(&hidden_ids)?;
84
self.refresh_muted_chats().await;
84
85
if full {
85
86
if complete {
86
87
self.store.remove_chats_except(&kept_ids)?;
@@ -90,6 +91,16 @@ impl<R: Remote> SyncEngine<R> {
90
91
Ok(refresh)
91
92
}
92
93
94
async fn refresh_muted_chats(&self) {
95
let outcome = match self.remote.muted_chat_states().await {
96
Ok(states) => self.store.apply_muted_states(&states).map_err(Error::from),
97
Err(error) => Err(error),
98
};
99
if let Err(error) = outcome {
100
self.report(format!("cannot refresh muted chats: {error}"));
101
}
102
}
103
93
104
fn chat_refresh_is_full(&self) -> Result<bool> {
94
105
let last_full = self.store.meta_time(META_CHATS_FULL_AT)?;
95
106
Ok(self.store.chat_count()? == 0
@@ -2,7 +2,7 @@ use chrono::{DateTime, Duration, Utc};2
use store::ChatRecord;2
use store::ChatRecord;3
3
4
use crate::engine::{SidebarSummary, SyncEngine};4
use crate::engine::{SidebarSummary, SyncEngine};5
use crate::error::Result;5
use crate::error::{Error, Result};6
use crate::events::CoreEvent;6
use crate::events::CoreEvent;7
use crate::mapping::{channel_record, chat_record, team_record};7
use crate::mapping::{channel_record, chat_record, team_record};8
use crate::remote::{ChatsPage, Remote};8
use crate::remote::{ChatsPage, Remote};@@ -81,6 +81,7 @@ impl<R: Remote> SyncEngine<R> {81
page = self.remote.chats_at(&link).await?;81
page = self.remote.chats_at(&link).await?;82
}82
}83
self.store.remove_chats(&hidden_ids)?;83
self.store.remove_chats(&hidden_ids)?;84
self.refresh_muted_chats().await;84
if full {85
if full {85
if complete {86
if complete {86
self.store.remove_chats_except(&kept_ids)?;87
self.store.remove_chats_except(&kept_ids)?;@@ -90,6 +91,16 @@ impl<R: Remote> SyncEngine<R> {90
Ok(refresh)91
Ok(refresh)91
}92
}92
93
94
async fn refresh_muted_chats(&self) {95
let outcome = match self.remote.muted_chat_states().await {96
Ok(states) => self.store.apply_muted_states(&states).map_err(Error::from),97
Err(error) => Err(error),98
};99
if let Err(error) = outcome {100
self.report(format!("cannot refresh muted chats: {error}"));101
}102
}103
93
fn chat_refresh_is_full(&self) -> Result<bool> {104
fn chat_refresh_is_full(&self) -> Result<bool> {94
let last_full = self.store.meta_time(META_CHATS_FULL_AT)?;105
let last_full = self.store.meta_time(META_CHATS_FULL_AT)?;95
Ok(self.store.chat_count()? == 0106
Ok(self.store.chat_count()? == 0@@ -91,6 +91,8 @@ struct Fake {
91
91
app_calls: Mutex<usize>,
92
92
invokes: Mutex<Vec<chatsvc::InvokeRequest>>,
93
93
invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,
94
muted_states: Mutex<Vec<(String, bool)>>,
95
muted_fails: Mutex<bool>,
94
96
}
95
97
96
98
impl Fake {
@@ -382,6 +384,47 @@ impl Remote for Handle {
382
384
Ok(())
383
385
}
384
386
387
async fn mark_chat_unread(
388
&self,
389
chat_id: &str,
390
user_id: &str,
391
tenant_id: &str,
392
last_read_at: DateTime<Utc>,
393
) -> Result<()> {
394
self.record(format!(
395
"mark_unread {chat_id} {user_id} {tenant_id} {}",
396
last_read_at.timestamp_millis()
397
));
398
Ok(())
399
}
400
401
async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
402
self.record(format!("hide {chat_id} {user_id} {tenant_id}"));
403
Ok(())
404
}
405
406
async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
407
self.record(format!("unhide {chat_id} {user_id} {tenant_id}"));
408
Ok(())
409
}
410
411
async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()> {
412
self.record(format!("leave {chat_id} {user_id}"));
413
Ok(())
414
}
415
416
async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>> {
417
if *self.muted_fails.lock().unwrap() {
418
return Err(Error::Unsupported("forced failure"));
419
}
420
Ok(self.muted_states.lock().unwrap().clone())
421
}
422
423
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
424
self.record(format!("mute {chat_id} {muted}"));
425
Ok(())
426
}
427
385
428
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
386
429
self.record(format!("set_reaction {} {reaction_type}", describe(target)));
387
430
Ok(())
@@ -681,6 +724,107 @@ async fn refresh_sidebar_fills_chats_teams_and_channels() {
681
724
assert_eq!(sidebar.teams[0].channels[0].name, "General");
682
725
}
683
726
727
#[tokio::test]
728
async fn refresh_sidebar_marks_muted_chats_and_keeps_flags_when_the_lookup_fails() {
729
let fake = Arc::new(Fake::default());
730
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
731
fake.muted_states
732
.lock()
733
.unwrap()
734
.push((CHAT.to_owned(), true));
735
let engine = engine_with(&fake, SyncConfig::default());
736
engine.refresh_sidebar().await.unwrap();
737
assert!(engine.sidebar().unwrap().chats[0].muted);
738
739
*fake.muted_fails.lock().unwrap() = true;
740
fake.muted_states.lock().unwrap().clear();
741
let mut events = engine.subscribe();
742
engine.refresh_sidebar().await.unwrap();
743
assert!(engine.sidebar().unwrap().chats[0].muted);
744
let mut reported = false;
745
while let Ok(event) = events.try_recv() {
746
reported |= matches!(event, CoreEvent::Error { .. });
747
}
748
assert!(reported);
749
750
*fake.muted_fails.lock().unwrap() = false;
751
engine.refresh_sidebar().await.unwrap();
752
assert!(engine.sidebar().unwrap().chats[0].muted);
753
754
fake.muted_states
755
.lock()
756
.unwrap()
757
.push((CHAT.to_owned(), false));
758
engine.refresh_sidebar().await.unwrap();
759
assert!(!engine.sidebar().unwrap().chats[0].muted);
760
}
761
762
#[tokio::test]
763
async fn chat_state_actions_call_remote_and_update_the_store() {
764
let fake = Arc::new(Fake::default());
765
let engine = chat_engine(&fake, small_pages()).await;
766
let mut events = engine.subscribe();
767
768
engine.mark_unread(CHAT).await.unwrap();
769
let last_message_millis = (base() + Duration::minutes(5)).timestamp_millis();
770
assert_eq!(
771
fake.calls().last().unwrap(),
772
&format!(
773
"mark_unread {CHAT} {ME} tenant-1 {}",
774
last_message_millis - 1
775
)
776
);
777
let unread = engine.sidebar().unwrap().chats[0].clone();
778
assert!(unread.unread);
779
assert_eq!(
780
unread.last_read_at.unwrap().timestamp_millis(),
781
last_message_millis - 1
782
);
783
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
784
785
engine.set_chat_muted(CHAT, true).await.unwrap();
786
assert_eq!(fake.calls().last().unwrap(), &format!("mute {CHAT} true"));
787
assert!(engine.sidebar().unwrap().chats[0].muted);
788
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
789
engine.set_chat_muted(CHAT, false).await.unwrap();
790
assert!(!engine.sidebar().unwrap().chats[0].muted);
791
}
792
793
#[tokio::test]
794
async fn hide_removes_the_chat_and_unhide_brings_it_back() {
795
let fake = Arc::new(Fake::default());
796
let engine = chat_engine(&fake, small_pages()).await;
797
let mut events = engine.subscribe();
798
799
engine.hide_chat(CHAT).await.unwrap();
800
assert_eq!(
801
fake.calls().last().unwrap(),
802
&format!("hide {CHAT} {ME} tenant-1")
803
);
804
assert!(engine.sidebar().unwrap().chats.is_empty());
805
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
806
807
engine.unhide_chat(CHAT).await.unwrap();
808
assert_eq!(
809
fake.calls().last().unwrap(),
810
&format!("unhide {CHAT} {ME} tenant-1")
811
);
812
assert_eq!(engine.sidebar().unwrap().chats.len(), 1);
813
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
814
}
815
816
#[tokio::test]
817
async fn leave_removes_the_chat() {
818
let fake = Arc::new(Fake::default());
819
let engine = chat_engine(&fake, small_pages()).await;
820
let mut events = engine.subscribe();
821
822
engine.leave_chat(CHAT).await.unwrap();
823
assert_eq!(fake.calls().last().unwrap(), &format!("leave {CHAT} {ME}"));
824
assert!(engine.sidebar().unwrap().chats.is_empty());
825
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
826
}
827
684
828
#[tokio::test]
685
829
async fn failing_channel_listing_is_reported_not_fatal() {
686
830
let fake = Arc::new(Fake::default());
@@ -91,6 +91,8 @@ struct Fake {91
app_calls: Mutex<usize>,91
app_calls: Mutex<usize>,92
invokes: Mutex<Vec<chatsvc::InvokeRequest>>,92
invokes: Mutex<Vec<chatsvc::InvokeRequest>>,93
invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,93
invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,94
muted_states: Mutex<Vec<(String, bool)>>,95
muted_fails: Mutex<bool>,94
}96
}95
97
96
impl Fake {98
impl Fake {@@ -382,6 +384,47 @@ impl Remote for Handle {382
Ok(())384
Ok(())383
}385
}384
386
387
async fn mark_chat_unread(388
&self,389
chat_id: &str,390
user_id: &str,391
tenant_id: &str,392
last_read_at: DateTime<Utc>,393
) -> Result<()> {394
self.record(format!(395
"mark_unread {chat_id} {user_id} {tenant_id} {}",396
last_read_at.timestamp_millis()397
));398
Ok(())399
}400
401
async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {402
self.record(format!("hide {chat_id} {user_id} {tenant_id}"));403
Ok(())404
}405
406
async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {407
self.record(format!("unhide {chat_id} {user_id} {tenant_id}"));408
Ok(())409
}410
411
async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()> {412
self.record(format!("leave {chat_id} {user_id}"));413
Ok(())414
}415
416
async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>> {417
if *self.muted_fails.lock().unwrap() {418
return Err(Error::Unsupported("forced failure"));419
}420
Ok(self.muted_states.lock().unwrap().clone())421
}422
423
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {424
self.record(format!("mute {chat_id} {muted}"));425
Ok(())426
}427
385
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {428
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {386
self.record(format!("set_reaction {} {reaction_type}", describe(target)));429
self.record(format!("set_reaction {} {reaction_type}", describe(target)));387
Ok(())430
Ok(())@@ -681,6 +724,107 @@ async fn refresh_sidebar_fills_chats_teams_and_channels() {681
assert_eq!(sidebar.teams[0].channels[0].name, "General");724
assert_eq!(sidebar.teams[0].channels[0].name, "General");682
}725
}683
726
727
#[tokio::test]728
async fn refresh_sidebar_marks_muted_chats_and_keeps_flags_when_the_lookup_fails() {729
let fake = Arc::new(Fake::default());730
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];731
fake.muted_states732
.lock()733
.unwrap()734
.push((CHAT.to_owned(), true));735
let engine = engine_with(&fake, SyncConfig::default());736
engine.refresh_sidebar().await.unwrap();737
assert!(engine.sidebar().unwrap().chats[0].muted);738
739
*fake.muted_fails.lock().unwrap() = true;740
fake.muted_states.lock().unwrap().clear();741
let mut events = engine.subscribe();742
engine.refresh_sidebar().await.unwrap();743
assert!(engine.sidebar().unwrap().chats[0].muted);744
let mut reported = false;745
while let Ok(event) = events.try_recv() {746
reported |= matches!(event, CoreEvent::Error { .. });747
}748
assert!(reported);749
750
*fake.muted_fails.lock().unwrap() = false;751
engine.refresh_sidebar().await.unwrap();752
assert!(engine.sidebar().unwrap().chats[0].muted);753
754
fake.muted_states755
.lock()756
.unwrap()757
.push((CHAT.to_owned(), false));758
engine.refresh_sidebar().await.unwrap();759
assert!(!engine.sidebar().unwrap().chats[0].muted);760
}761
762
#[tokio::test]763
async fn chat_state_actions_call_remote_and_update_the_store() {764
let fake = Arc::new(Fake::default());765
let engine = chat_engine(&fake, small_pages()).await;766
let mut events = engine.subscribe();767
768
engine.mark_unread(CHAT).await.unwrap();769
let last_message_millis = (base() + Duration::minutes(5)).timestamp_millis();770
assert_eq!(771
fake.calls().last().unwrap(),772
&format!(773
"mark_unread {CHAT} {ME} tenant-1 {}",774
last_message_millis - 1775
)776
);777
let unread = engine.sidebar().unwrap().chats[0].clone();778
assert!(unread.unread);779
assert_eq!(780
unread.last_read_at.unwrap().timestamp_millis(),781
last_message_millis - 1782
);783
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);784
785
engine.set_chat_muted(CHAT, true).await.unwrap();786
assert_eq!(fake.calls().last().unwrap(), &format!("mute {CHAT} true"));787
assert!(engine.sidebar().unwrap().chats[0].muted);788
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);789
engine.set_chat_muted(CHAT, false).await.unwrap();790
assert!(!engine.sidebar().unwrap().chats[0].muted);791
}792
793
#[tokio::test]794
async fn hide_removes_the_chat_and_unhide_brings_it_back() {795
let fake = Arc::new(Fake::default());796
let engine = chat_engine(&fake, small_pages()).await;797
let mut events = engine.subscribe();798
799
engine.hide_chat(CHAT).await.unwrap();800
assert_eq!(801
fake.calls().last().unwrap(),802
&format!("hide {CHAT} {ME} tenant-1")803
);804
assert!(engine.sidebar().unwrap().chats.is_empty());805
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);806
807
engine.unhide_chat(CHAT).await.unwrap();808
assert_eq!(809
fake.calls().last().unwrap(),810
&format!("unhide {CHAT} {ME} tenant-1")811
);812
assert_eq!(engine.sidebar().unwrap().chats.len(), 1);813
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);814
}815
816
#[tokio::test]817
async fn leave_removes_the_chat() {818
let fake = Arc::new(Fake::default());819
let engine = chat_engine(&fake, small_pages()).await;820
let mut events = engine.subscribe();821
822
engine.leave_chat(CHAT).await.unwrap();823
assert_eq!(fake.calls().last().unwrap(), &format!("leave {CHAT} {ME}"));824
assert!(engine.sidebar().unwrap().chats.is_empty());825
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);826
}827
684
#[tokio::test]828
#[tokio::test]685
async fn failing_channel_listing_is_reported_not_fatal() {829
async fn failing_channel_listing_is_reported_not_fatal() {686
let fake = Arc::new(Fake::default());830
let fake = Arc::new(Fake::default());@@ -10,6 +10,8 @@ pub enum Error {
10
10
ForeignNextLink,
11
11
#[error("cannot decode a binary answer: {0}")]
12
12
Decode(String),
13
#[error("you are not a member of this chat")]
14
NotAMember,
13
15
#[error("cannot upload an empty file")]
14
16
EmptyUpload,
15
17
#[error("upload failed: {0}")]
@@ -10,6 +10,8 @@ pub enum Error {10
ForeignNextLink,10
ForeignNextLink,11
#[error("cannot decode a binary answer: {0}")]11
#[error("cannot decode a binary answer: {0}")]12
Decode(String),12
Decode(String),13
#[error("you are not a member of this chat")]14
NotAMember,13
#[error("cannot upload an empty file")]15
#[error("cannot upload an empty file")]14
EmptyUpload,16
EmptyUpload,15
#[error("upload failed: {0}")]17
#[error("upload failed: {0}")]@@ -15,6 +15,7 @@ pub struct User {
15
15
#[derive(Debug, Clone, Deserialize, PartialEq)]
16
16
#[serde(rename_all = "camelCase")]
17
17
pub struct Member {
18
pub id: Option<String>,
18
19
pub user_id: Option<String>,
19
20
pub tenant_id: Option<String>,
20
21
pub display_name: Option<String>,
@@ -15,6 +15,7 @@ pub struct User {15
#[derive(Debug, Clone, Deserialize, PartialEq)]15
#[derive(Debug, Clone, Deserialize, PartialEq)]16
#[serde(rename_all = "camelCase")]16
#[serde(rename_all = "camelCase")]17
pub struct Member {17
pub struct Member {18
pub id: Option<String>,18
pub user_id: Option<String>,19
pub user_id: Option<String>,19
pub tenant_id: Option<String>,20
pub tenant_id: Option<String>,20
pub display_name: Option<String>,21
pub display_name: Option<String>,@@ -162,6 +162,29 @@ pub fn mark_chat_read(chat_id: &str) -> String {
162
162
)
163
163
}
164
164
165
pub fn mark_chat_unread(chat_id: &str) -> String {
166
format!(
167
"{GRAPH}/v1.0/chats/{}/markChatUnreadForUser",
168
segment(chat_id)
169
)
170
}
171
172
pub fn hide_chat(chat_id: &str) -> String {
173
format!("{GRAPH}/v1.0/chats/{}/hideForUser", segment(chat_id))
174
}
175
176
pub fn unhide_chat(chat_id: &str) -> String {
177
format!("{GRAPH}/v1.0/chats/{}/unhideForUser", segment(chat_id))
178
}
179
180
pub fn chat_member(chat_id: &str, membership_id: &str) -> String {
181
format!(
182
"{GRAPH}/v1.0/chats/{}/members/{}",
183
segment(chat_id),
184
segment(membership_id)
185
)
186
}
187
165
188
pub fn joined_teams() -> String {
166
189
format!("{GRAPH}/v1.0/me/joinedTeams?$select=id,displayName")
167
190
}
@@ -284,6 +307,26 @@ mod tests {
284
307
);
285
308
}
286
309
310
#[test]
311
fn chat_state_write_urls() {
312
assert_eq!(
313
mark_chat_unread("19:abc@thread.v2"),
314
"https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/markChatUnreadForUser"
315
);
316
assert_eq!(
317
hide_chat("19:abc@thread.v2"),
318
"https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/hideForUser"
319
);
320
assert_eq!(
321
unhide_chat("19:abc@thread.v2"),
322
"https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/unhideForUser"
323
);
324
assert_eq!(
325
chat_member("19:abc@thread.v2", "MTox"),
326
"https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/members/MTox"
327
);
328
}
329
287
330
#[test]
288
331
fn chats_url_orders_newest_first() {
289
332
let url = chats(50);
@@ -162,6 +162,29 @@ pub fn mark_chat_read(chat_id: &str) -> String {162
)162
)163
}163
}164
164
165
pub fn mark_chat_unread(chat_id: &str) -> String {166
format!(167
"{GRAPH}/v1.0/chats/{}/markChatUnreadForUser",168
segment(chat_id)169
)170
}171
172
pub fn hide_chat(chat_id: &str) -> String {173
format!("{GRAPH}/v1.0/chats/{}/hideForUser", segment(chat_id))174
}175
176
pub fn unhide_chat(chat_id: &str) -> String {177
format!("{GRAPH}/v1.0/chats/{}/unhideForUser", segment(chat_id))178
}179
180
pub fn chat_member(chat_id: &str, membership_id: &str) -> String {181
format!(182
"{GRAPH}/v1.0/chats/{}/members/{}",183
segment(chat_id),184
segment(membership_id)185
)186
}187
165
pub fn joined_teams() -> String {188
pub fn joined_teams() -> String {166
format!("{GRAPH}/v1.0/me/joinedTeams?$select=id,displayName")189
format!("{GRAPH}/v1.0/me/joinedTeams?$select=id,displayName")167
}190
}@@ -284,6 +307,26 @@ mod tests {284
);307
);285
}308
}286
309
310
#[test]311
fn chat_state_write_urls() {312
assert_eq!(313
mark_chat_unread("19:abc@thread.v2"),314
"https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/markChatUnreadForUser"315
);316
assert_eq!(317
hide_chat("19:abc@thread.v2"),318
"https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/hideForUser"319
);320
assert_eq!(321
unhide_chat("19:abc@thread.v2"),322
"https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/unhideForUser"323
);324
assert_eq!(325
chat_member("19:abc@thread.v2", "MTox"),326
"https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/members/MTox"327
);328
}329
287
#[test]330
#[test]288
fn chats_url_orders_newest_first() {331
fn chats_url_orders_newest_first() {289
let url = chats(50);332
let url = chats(50);@@ -1,9 +1,10 @@
1
use chrono::{DateTime, SecondsFormat, Utc};
1
2
use serde_json::{Value, json};
2
3
use session::{GRAPH, Method, Scope};
3
4
4
5
use crate::client::Graph;
5
use crate::error::Result;
6
use crate::models::{Chat, Message};
6
use crate::error::{Error, Result};
7
use crate::models::{Chat, Member, Message};
7
8
use crate::outgoing::{MessageExtras, OutgoingMention, message_body};
8
9
use crate::target::MessageTarget;
9
10
use crate::urls;
@@ -16,6 +17,24 @@ fn conversation_member(user_id: &str) -> Value {
16
17
})
17
18
}
18
19
20
fn user_body(user_id: &str, tenant_id: &str) -> Value {
21
json!({"user": {"id": user_id, "tenantId": tenant_id}})
22
}
23
24
fn mark_unread_body(user_id: &str, tenant_id: &str, last_read_at: DateTime<Utc>) -> Value {
25
json!({
26
"user": {"id": user_id, "tenantId": tenant_id},
27
"lastMessageReadDateTime": last_read_at.to_rfc3339_opts(SecondsFormat::Millis, true),
28
})
29
}
30
31
fn own_membership_id<'a>(members: &'a [Member], user_id: &str) -> Option<&'a str> {
32
members
33
.iter()
34
.find(|member| member.user_id.as_deref() == Some(user_id))
35
.and_then(|member| member.id.as_deref())
36
}
37
19
38
impl Graph {
20
39
pub async fn send_chat_message(
21
40
&self,
@@ -101,16 +120,64 @@ impl Graph {
101
120
user_id: &str,
102
121
tenant_id: &str,
103
122
) -> Result<()> {
104
let body = json!({"user": {"id": user_id, "tenantId": tenant_id}});
105
123
self.write(
106
124
Method::Post,
107
125
&urls::mark_chat_read(chat_id),
108
126
"Chat.ReadWrite",
127
Some(user_body(user_id, tenant_id)),
128
)
129
.await
130
}
131
132
pub async fn mark_chat_unread(
133
&self,
134
chat_id: &str,
135
user_id: &str,
136
tenant_id: &str,
137
last_read_at: DateTime<Utc>,
138
) -> Result<()> {
139
let body = mark_unread_body(user_id, tenant_id, last_read_at);
140
self.write(
141
Method::Post,
142
&urls::mark_chat_unread(chat_id),
143
"Chat.ReadWrite",
109
144
Some(body),
110
145
)
111
146
.await
112
147
}
113
148
149
pub async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
150
self.write(
151
Method::Post,
152
&urls::hide_chat(chat_id),
153
"Chat.ReadWrite",
154
Some(user_body(user_id, tenant_id)),
155
)
156
.await
157
}
158
159
pub async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
160
self.write(
161
Method::Post,
162
&urls::unhide_chat(chat_id),
163
"Chat.ReadWrite",
164
Some(user_body(user_id, tenant_id)),
165
)
166
.await
167
}
168
169
pub async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()> {
170
let members = self.chat_members(chat_id).await?;
171
let membership_id = own_membership_id(&members, user_id).ok_or(Error::NotAMember)?;
172
self.write(
173
Method::Delete,
174
&urls::chat_member(chat_id, membership_id),
175
"Chat.ReadWrite",
176
None,
177
)
178
.await
179
}
180
114
181
pub async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
115
182
self.write(
116
183
Method::Post,
@@ -223,3 +290,36 @@ impl Graph {
223
290
Ok(())
224
291
}
225
292
}
293
294
#[cfg(test)]
295
mod tests {
296
use chrono::TimeZone;
297
298
use super::*;
299
300
fn member(id: &str, user_id: &str) -> Member {
301
Member {
302
id: Some(id.to_owned()),
303
user_id: Some(user_id.to_owned()),
304
tenant_id: None,
305
display_name: None,
306
email: None,
307
}
308
}
309
310
#[test]
311
fn own_membership_is_found_by_user_id() {
312
let members = [member("m1", "u1"), member("m2", "u2")];
313
assert_eq!(own_membership_id(&members, "u2"), Some("m2"));
314
assert_eq!(own_membership_id(&members, "u3"), None);
315
}
316
317
#[test]
318
fn mark_unread_body_carries_the_read_horizon() {
319
let at = Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, 0).unwrap();
320
let body = mark_unread_body("u1", "t1", at);
321
assert_eq!(body["user"]["id"], "u1");
322
assert_eq!(body["user"]["tenantId"], "t1");
323
assert_eq!(body["lastMessageReadDateTime"], "2026-10-06T09:00:00.000Z");
324
}
325
}
@@ -1,9 +1,10 @@1
use chrono::{DateTime, SecondsFormat, Utc};1
use serde_json::{Value, json};2
use serde_json::{Value, json};2
use session::{GRAPH, Method, Scope};3
use session::{GRAPH, Method, Scope};3
4
4
use crate::client::Graph;5
use crate::client::Graph;5
use crate::error::Result;6
use crate::error::{Error, Result};6
use crate::models::{Chat, Message};7
use crate::models::{Chat, Member, Message};7
use crate::outgoing::{MessageExtras, OutgoingMention, message_body};8
use crate::outgoing::{MessageExtras, OutgoingMention, message_body};8
use crate::target::MessageTarget;9
use crate::target::MessageTarget;9
use crate::urls;10
use crate::urls;@@ -16,6 +17,24 @@ fn conversation_member(user_id: &str) -> Value {16
})17
})17
}18
}18
19
20
fn user_body(user_id: &str, tenant_id: &str) -> Value {21
json!({"user": {"id": user_id, "tenantId": tenant_id}})22
}23
24
fn mark_unread_body(user_id: &str, tenant_id: &str, last_read_at: DateTime<Utc>) -> Value {25
json!({26
"user": {"id": user_id, "tenantId": tenant_id},27
"lastMessageReadDateTime": last_read_at.to_rfc3339_opts(SecondsFormat::Millis, true),28
})29
}30
31
fn own_membership_id<'a>(members: &'a [Member], user_id: &str) -> Option<&'a str> {32
members33
.iter()34
.find(|member| member.user_id.as_deref() == Some(user_id))35
.and_then(|member| member.id.as_deref())36
}37
19
impl Graph {38
impl Graph {20
pub async fn send_chat_message(39
pub async fn send_chat_message(21
&self,40
&self,@@ -101,16 +120,64 @@ impl Graph {101
user_id: &str,120
user_id: &str,102
tenant_id: &str,121
tenant_id: &str,103
) -> Result<()> {122
) -> Result<()> {104
let body = json!({"user": {"id": user_id, "tenantId": tenant_id}});105
self.write(123
self.write(106
Method::Post,124
Method::Post,107
&urls::mark_chat_read(chat_id),125
&urls::mark_chat_read(chat_id),108
"Chat.ReadWrite",126
"Chat.ReadWrite",127
Some(user_body(user_id, tenant_id)),128
)129
.await130
}131
132
pub async fn mark_chat_unread(133
&self,134
chat_id: &str,135
user_id: &str,136
tenant_id: &str,137
last_read_at: DateTime<Utc>,138
) -> Result<()> {139
let body = mark_unread_body(user_id, tenant_id, last_read_at);140
self.write(141
Method::Post,142
&urls::mark_chat_unread(chat_id),143
"Chat.ReadWrite",109
Some(body),144
Some(body),110
)145
)111
.await146
.await112
}147
}113
148
149
pub async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {150
self.write(151
Method::Post,152
&urls::hide_chat(chat_id),153
"Chat.ReadWrite",154
Some(user_body(user_id, tenant_id)),155
)156
.await157
}158
159
pub async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {160
self.write(161
Method::Post,162
&urls::unhide_chat(chat_id),163
"Chat.ReadWrite",164
Some(user_body(user_id, tenant_id)),165
)166
.await167
}168
169
pub async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()> {170
let members = self.chat_members(chat_id).await?;171
let membership_id = own_membership_id(&members, user_id).ok_or(Error::NotAMember)?;172
self.write(173
Method::Delete,174
&urls::chat_member(chat_id, membership_id),175
"Chat.ReadWrite",176
None,177
)178
.await179
}180
114
pub async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {181
pub async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {115
self.write(182
self.write(116
Method::Post,183
Method::Post,@@ -223,3 +290,36 @@ impl Graph {223
Ok(())290
Ok(())224
}291
}225
}292
}293
294
#[cfg(test)]295
mod tests {296
use chrono::TimeZone;297
298
use super::*;299
300
fn member(id: &str, user_id: &str) -> Member {301
Member {302
id: Some(id.to_owned()),303
user_id: Some(user_id.to_owned()),304
tenant_id: None,305
display_name: None,306
email: None,307
}308
}309
310
#[test]311
fn own_membership_is_found_by_user_id() {312
let members = [member("m1", "u1"), member("m2", "u2")];313
assert_eq!(own_membership_id(&members, "u2"), Some("m2"));314
assert_eq!(own_membership_id(&members, "u3"), None);315
}316
317
#[test]318
fn mark_unread_body_carries_the_read_horizon() {319
let at = Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, 0).unwrap();320
let body = mark_unread_body("u1", "t1", at);321
assert_eq!(body["user"]["id"], "u1");322
assert_eq!(body["user"]["tenantId"], "t1");323
assert_eq!(body["lastMessageReadDateTime"], "2026-10-06T09:00:00.000Z");324
}325
}@@ -9,7 +9,7 @@ use crate::store::{Store, json_ids};
9
9
use crate::time::{optional_from_millis, optional_to_millis, to_millis};
10
10
11
11
const CHAT_COLUMNS: &str = "id, kind, title, member_summary, last_message_at, last_read_at, unread, \
12
last_message_preview, last_message_sender_id, last_message_sender_name, last_message_deleted";
12
last_message_preview, last_message_sender_id, last_message_sender_name, last_message_deleted, muted";
13
13
14
14
impl Store {
15
15
pub fn upsert_chats(&self, chats: &[ChatRecord]) -> Result<()> {
@@ -116,6 +116,38 @@ impl Store {
116
116
Ok(())
117
117
}
118
118
119
pub fn mark_chat_unread(&self, chat_id: &str, last_read_at: DateTime<Utc>) -> Result<()> {
120
let connection = self.lock()?;
121
connection.execute(
122
"UPDATE chats SET unread = 1, last_read_at = ?2 WHERE id = ?1",
123
params![chat_id, to_millis(last_read_at)],
124
)?;
125
Ok(())
126
}
127
128
pub fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
129
let connection = self.lock()?;
130
connection.execute(
131
"UPDATE chats SET muted = ?2 WHERE id = ?1",
132
params![chat_id, muted],
133
)?;
134
Ok(())
135
}
136
137
pub fn apply_muted_states(&self, states: &[(String, bool)]) -> Result<()> {
138
let mut connection = self.lock()?;
139
let transaction = connection.transaction()?;
140
{
141
let mut update =
142
transaction.prepare_cached("UPDATE chats SET muted = ?2 WHERE id = ?1")?;
143
for (chat_id, muted) in states {
144
update.execute(params![chat_id, muted])?;
145
}
146
}
147
transaction.commit()?;
148
Ok(())
149
}
150
119
151
/// Applies the preview only when the message is at least as new as the cached last message and differs. Returns whether the row changed.
120
152
pub fn update_chat_preview(
121
153
&self,
@@ -180,6 +212,7 @@ fn chat_from_row(row: &Row<'_>) -> rusqlite::Result<ChatRecord> {
180
212
last_message_sender_id: row.get(8)?,
181
213
last_message_sender_name: row.get(9)?,
182
214
last_message_deleted: row.get(10)?,
215
muted: row.get(11)?,
183
216
last_event_system: false,
184
217
})
185
218
}
@@ -9,7 +9,7 @@ use crate::store::{Store, json_ids};9
use crate::time::{optional_from_millis, optional_to_millis, to_millis};9
use crate::time::{optional_from_millis, optional_to_millis, to_millis};10
10
11
const CHAT_COLUMNS: &str = "id, kind, title, member_summary, last_message_at, last_read_at, unread, \11
const CHAT_COLUMNS: &str = "id, kind, title, member_summary, last_message_at, last_read_at, unread, \12
last_message_preview, last_message_sender_id, last_message_sender_name, last_message_deleted";12
last_message_preview, last_message_sender_id, last_message_sender_name, last_message_deleted, muted";13
13
14
impl Store {14
impl Store {15
pub fn upsert_chats(&self, chats: &[ChatRecord]) -> Result<()> {15
pub fn upsert_chats(&self, chats: &[ChatRecord]) -> Result<()> {@@ -116,6 +116,38 @@ impl Store {116
Ok(())116
Ok(())117
}117
}118
118
119
pub fn mark_chat_unread(&self, chat_id: &str, last_read_at: DateTime<Utc>) -> Result<()> {120
let connection = self.lock()?;121
connection.execute(122
"UPDATE chats SET unread = 1, last_read_at = ?2 WHERE id = ?1",123
params![chat_id, to_millis(last_read_at)],124
)?;125
Ok(())126
}127
128
pub fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {129
let connection = self.lock()?;130
connection.execute(131
"UPDATE chats SET muted = ?2 WHERE id = ?1",132
params![chat_id, muted],133
)?;134
Ok(())135
}136
137
pub fn apply_muted_states(&self, states: &[(String, bool)]) -> Result<()> {138
let mut connection = self.lock()?;139
let transaction = connection.transaction()?;140
{141
let mut update =142
transaction.prepare_cached("UPDATE chats SET muted = ?2 WHERE id = ?1")?;143
for (chat_id, muted) in states {144
update.execute(params![chat_id, muted])?;145
}146
}147
transaction.commit()?;148
Ok(())149
}150
119
/// Applies the preview only when the message is at least as new as the cached last message and differs. Returns whether the row changed.151
/// Applies the preview only when the message is at least as new as the cached last message and differs. Returns whether the row changed.120
pub fn update_chat_preview(152
pub fn update_chat_preview(121
&self,153
&self,@@ -180,6 +212,7 @@ fn chat_from_row(row: &Row<'_>) -> rusqlite::Result<ChatRecord> {180
last_message_sender_id: row.get(8)?,212
last_message_sender_id: row.get(8)?,181
last_message_sender_name: row.get(9)?,213
last_message_sender_name: row.get(9)?,182
last_message_deleted: row.get(10)?,214
last_message_deleted: row.get(10)?,215
muted: row.get(11)?,183
last_event_system: false,216
last_event_system: false,184
})217
})185
}218
}@@ -41,6 +41,10 @@ const MIGRATIONS: &[Migration] = &[
41
41
script: include_str!("migrations/0008_activity.sql"),
42
42
after: None,
43
43
},
44
Migration {
45
script: include_str!("migrations/0009_muted.sql"),
46
after: None,
47
},
44
48
];
45
49
46
50
pub fn latest_version() -> i64 {
@@ -41,6 +41,10 @@ const MIGRATIONS: &[Migration] = &[41
script: include_str!("migrations/0008_activity.sql"),41
script: include_str!("migrations/0008_activity.sql"),42
after: None,42
after: None,43
},43
},44
Migration {45
script: include_str!("migrations/0009_muted.sql"),46
after: None,47
},44
];48
];45
49
46
pub fn latest_version() -> i64 {50
pub fn latest_version() -> i64 {@@ -0,0 +1 @@
1
ALTER TABLE chats ADD COLUMN muted INTEGER NOT NULL DEFAULT 0;
@@ -0,0 +1 @@1
ALTER TABLE chats ADD COLUMN muted INTEGER NOT NULL DEFAULT 0;@@ -15,6 +15,7 @@ pub struct ChatRecord {
15
15
pub last_message_at: Option<DateTime<Utc>>,
16
16
pub last_read_at: Option<DateTime<Utc>>,
17
17
pub unread: bool,
18
pub muted: bool,
18
19
pub members: Vec<MemberRecord>,
19
20
pub last_message_preview: Option<String>,
20
21
pub last_message_sender_id: Option<String>,
@@ -15,6 +15,7 @@ pub struct ChatRecord {15
pub last_message_at: Option<DateTime<Utc>>,15
pub last_message_at: Option<DateTime<Utc>>,16
pub last_read_at: Option<DateTime<Utc>>,16
pub last_read_at: Option<DateTime<Utc>>,17
pub unread: bool,17
pub unread: bool,18
pub muted: bool,18
pub members: Vec<MemberRecord>,19
pub members: Vec<MemberRecord>,19
pub last_message_preview: Option<String>,20
pub last_message_preview: Option<String>,20
pub last_message_sender_id: Option<String>,21
pub last_message_sender_id: Option<String>,@@ -395,11 +395,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
395
395
let path = directory.path().join("nested").join("cache.sqlite3");
396
396
{
397
397
let store = Store::open(&path).unwrap();
398
assert_eq!(store.schema_version().unwrap(), 8);
398
assert_eq!(store.schema_version().unwrap(), 9);
399
399
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
400
400
}
401
401
let reopened = Store::open(&path).unwrap();
402
assert_eq!(reopened.schema_version().unwrap(), 8);
402
assert_eq!(reopened.schema_version().unwrap(), 9);
403
403
assert_eq!(reopened.message_count("c").unwrap(), 1);
404
404
drop(reopened);
405
405
let mode: String = rusqlite_open(&path)
@@ -431,7 +431,7 @@ fn old_schema_is_upgraded_in_place() {
431
431
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 presence; DROP TABLE activity; PRAGMA user_version = 0").unwrap();
432
432
drop(connection);
433
433
let store = Store::open(&path).unwrap();
434
assert_eq!(store.schema_version().unwrap(), 8);
434
assert_eq!(store.schema_version().unwrap(), 9);
435
435
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
436
436
}
437
437
@@ -497,7 +497,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
497
497
let store = Store::open(&path).unwrap();
498
498
let state = store.sync_state("c").unwrap().unwrap();
499
499
assert_eq!(state.delta_link, None);
500
assert_eq!(store.schema_version().unwrap(), 8);
500
assert_eq!(store.schema_version().unwrap(), 9);
501
501
}
502
502
503
503
#[test]
@@ -729,6 +729,7 @@ fn migration_indexes_rows_that_predate_search() {
729
729
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
730
730
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity;
731
731
ALTER TABLE messages DROP COLUMN sender_application_id;
732
ALTER TABLE chats DROP COLUMN muted;
732
733
PRAGMA user_version = 3;",
733
734
)
734
735
.unwrap();
@@ -829,6 +830,64 @@ fn sync_does_not_resurrect_a_locally_read_chat() {
829
830
assert!(store.chat("chat-1").unwrap().unwrap().unread);
830
831
}
831
832
833
#[test]
834
fn mark_chat_unread_sets_the_flag_and_horizon() {
835
let store = Store::open_in_memory().unwrap();
836
store
837
.upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])
838
.unwrap();
839
store.mark_chat_read("chat-1", at(10)).unwrap();
840
841
store.mark_chat_unread("chat-1", at(4)).unwrap();
842
let unread = store.chat("chat-1").unwrap().unwrap();
843
assert!(unread.unread);
844
assert_eq!(unread.last_read_at, Some(at(4)));
845
}
846
847
#[test]
848
fn muted_flag_survives_a_chat_refresh() {
849
let store = Store::open_in_memory().unwrap();
850
store
851
.upsert_chats(&[chat("a", "A", Some(at(1))), chat("b", "B", Some(at(2)))])
852
.unwrap();
853
assert!(!store.chat("a").unwrap().unwrap().muted);
854
855
store.set_chat_muted("a", true).unwrap();
856
store
857
.upsert_chats(&[chat("a", "A", Some(at(3))), chat("b", "B", Some(at(2)))])
858
.unwrap();
859
assert!(store.chat("a").unwrap().unwrap().muted);
860
assert!(!store.chat("b").unwrap().unwrap().muted);
861
862
store.set_chat_muted("a", false).unwrap();
863
assert!(!store.chat("a").unwrap().unwrap().muted);
864
}
865
866
#[test]
867
fn muted_states_touch_only_the_listed_chats() {
868
let store = Store::open_in_memory().unwrap();
869
store
870
.upsert_chats(&[
871
chat("a", "A", Some(at(1))),
872
chat("b", "B", Some(at(2))),
873
chat("c", "C", Some(at(3))),
874
])
875
.unwrap();
876
store.set_chat_muted("a", true).unwrap();
877
store.set_chat_muted("c", true).unwrap();
878
879
store
880
.apply_muted_states(&[
881
("a".to_owned(), false),
882
("b".to_owned(), true),
883
("gone".to_owned(), true),
884
])
885
.unwrap();
886
assert!(!store.chat("a").unwrap().unwrap().muted);
887
assert!(store.chat("b").unwrap().unwrap().muted);
888
assert!(store.chat("c").unwrap().unwrap().muted);
889
}
890
832
891
#[test]
833
892
fn presence_upsert_keeps_the_latest_availability() {
834
893
let store = Store::open_in_memory().unwrap();
@@ -395,11 +395,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {395
let path = directory.path().join("nested").join("cache.sqlite3");395
let path = directory.path().join("nested").join("cache.sqlite3");396
{396
{397
let store = Store::open(&path).unwrap();397
let store = Store::open(&path).unwrap();398
assert_eq!(store.schema_version().unwrap(), 8);398
assert_eq!(store.schema_version().unwrap(), 9);399
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();399
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();400
}400
}401
let reopened = Store::open(&path).unwrap();401
let reopened = Store::open(&path).unwrap();402
assert_eq!(reopened.schema_version().unwrap(), 8);402
assert_eq!(reopened.schema_version().unwrap(), 9);403
assert_eq!(reopened.message_count("c").unwrap(), 1);403
assert_eq!(reopened.message_count("c").unwrap(), 1);404
drop(reopened);404
drop(reopened);405
let mode: String = rusqlite_open(&path)405
let mode: String = rusqlite_open(&path)@@ -431,7 +431,7 @@ fn old_schema_is_upgraded_in_place() {431
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 presence; DROP TABLE activity; PRAGMA user_version = 0").unwrap();431
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 presence; DROP TABLE activity; PRAGMA user_version = 0").unwrap();432
drop(connection);432
drop(connection);433
let store = Store::open(&path).unwrap();433
let store = Store::open(&path).unwrap();434
assert_eq!(store.schema_version().unwrap(), 8);434
assert_eq!(store.schema_version().unwrap(), 9);435
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();435
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();436
}436
}437
437
@@ -497,7 +497,7 @@ fn migration_to_v2_keeps_existing_sync_state() {497
let store = Store::open(&path).unwrap();497
let store = Store::open(&path).unwrap();498
let state = store.sync_state("c").unwrap().unwrap();498
let state = store.sync_state("c").unwrap().unwrap();499
assert_eq!(state.delta_link, None);499
assert_eq!(state.delta_link, None);500
assert_eq!(store.schema_version().unwrap(), 8);500
assert_eq!(store.schema_version().unwrap(), 9);501
}501
}502
502
503
#[test]503
#[test]@@ -729,6 +729,7 @@ fn migration_indexes_rows_that_predate_search() {729
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;729
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;730
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity;730
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity;731
ALTER TABLE messages DROP COLUMN sender_application_id;731
ALTER TABLE messages DROP COLUMN sender_application_id;732
ALTER TABLE chats DROP COLUMN muted;732
PRAGMA user_version = 3;",733
PRAGMA user_version = 3;",733
)734
)734
.unwrap();735
.unwrap();@@ -829,6 +830,64 @@ fn sync_does_not_resurrect_a_locally_read_chat() {829
assert!(store.chat("chat-1").unwrap().unwrap().unread);830
assert!(store.chat("chat-1").unwrap().unwrap().unread);830
}831
}831
832
833
#[test]834
fn mark_chat_unread_sets_the_flag_and_horizon() {835
let store = Store::open_in_memory().unwrap();836
store837
.upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])838
.unwrap();839
store.mark_chat_read("chat-1", at(10)).unwrap();840
841
store.mark_chat_unread("chat-1", at(4)).unwrap();842
let unread = store.chat("chat-1").unwrap().unwrap();843
assert!(unread.unread);844
assert_eq!(unread.last_read_at, Some(at(4)));845
}846
847
#[test]848
fn muted_flag_survives_a_chat_refresh() {849
let store = Store::open_in_memory().unwrap();850
store851
.upsert_chats(&[chat("a", "A", Some(at(1))), chat("b", "B", Some(at(2)))])852
.unwrap();853
assert!(!store.chat("a").unwrap().unwrap().muted);854
855
store.set_chat_muted("a", true).unwrap();856
store857
.upsert_chats(&[chat("a", "A", Some(at(3))), chat("b", "B", Some(at(2)))])858
.unwrap();859
assert!(store.chat("a").unwrap().unwrap().muted);860
assert!(!store.chat("b").unwrap().unwrap().muted);861
862
store.set_chat_muted("a", false).unwrap();863
assert!(!store.chat("a").unwrap().unwrap().muted);864
}865
866
#[test]867
fn muted_states_touch_only_the_listed_chats() {868
let store = Store::open_in_memory().unwrap();869
store870
.upsert_chats(&[871
chat("a", "A", Some(at(1))),872
chat("b", "B", Some(at(2))),873
chat("c", "C", Some(at(3))),874
])875
.unwrap();876
store.set_chat_muted("a", true).unwrap();877
store.set_chat_muted("c", true).unwrap();878
879
store880
.apply_muted_states(&[881
("a".to_owned(), false),882
("b".to_owned(), true),883
("gone".to_owned(), true),884
])885
.unwrap();886
assert!(!store.chat("a").unwrap().unwrap().muted);887
assert!(store.chat("b").unwrap().unwrap().muted);888
assert!(store.chat("c").unwrap().unwrap().muted);889
}890
832
#[test]891
#[test]833
fn presence_upsert_keeps_the_latest_availability() {892
fn presence_upsert_keeps_the_latest_availability() {834
let store = Store::open_in_memory().unwrap();893
let store = Store::open_in_memory().unwrap();