BlueGit

ict rusty-teams

feat(sidebar): highlight unread channels like Teams

- read channel unread state from the chatsvc consumption horizon (Teams worker rule), refreshed every sync
- opening a channel writes the consumption horizon like Teams
- unread shown channels: bold + Foreground1, read: regular + Foreground3; collapsed team with unread channel: semibold
- drop the non-Teams unread dots on channel and team rows; rail dot only for shown channels
- team metadata refresh no longer resets channel read state

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
dee4819fcf17be78d8e9780f3bf9f835a92ee117
Parent
fc36d5c6
14 files changed +627 −54
crates/app-state/src/app_state.rs +17 −0
@@ -735,6 +735,23 @@ impl AppState {
735 735 }
736 736 }
737 737
738 pub fn mark_channel_read(&mut self, channel_id: &str, cx: &mut Context<Self>) {
739 if self.mode.read_only {
740 return;
741 }
742 let _ = self.store.mark_channel_read(channel_id);
743 self.reload_sidebar(cx);
744 if self.mode.demo {
745 return;
746 }
747 if let Some(engine) = self.engine.clone() {
748 let channel_id = channel_id.to_owned();
749 drop(crate::runtime::spawn(async move {
750 engine.mark_read(&channel_id).await
751 }));
752 }
753 }
754
738 755 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
739 756 self.new_chat = true;
740 757 self.show_call(false, cx);
@@ -735,6 +735,23 @@ impl AppState {
735 }
735 }
736 }
736 }
737
737
738 pub fn mark_channel_read(&mut self, channel_id: &str, cx: &mut Context<Self>) {
739 if self.mode.read_only {
740 return;
741 }
742 let _ = self.store.mark_channel_read(channel_id);
743 self.reload_sidebar(cx);
744 if self.mode.demo {
745 return;
746 }
747 if let Some(engine) = self.engine.clone() {
748 let channel_id = channel_id.to_owned();
749 drop(crate::runtime::spawn(async move {
750 engine.mark_read(&channel_id).await
751 }));
752 }
753 }
754
738 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
755 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
739 self.new_chat = true;
756 self.new_chat = true;
740 self.show_call(false, cx);
757 self.show_call(false, cx);
crates/app-state/src/sidebar_model.rs +122 −1
@@ -210,11 +210,71 @@ pub fn unread_chat_count(chats: &[ChatRecord]) -> u32 {
210 210 .count() as u32
211 211 }
212 212
213 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
214 pub enum NameWeight {
215 Regular,
216 Semibold,
217 Bold,
218 }
219
220 /// Teams channel list: `highlighted` is colorNeutralForeground1, otherwise colorNeutralForeground3.
221 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
222 pub struct NameStyle {
223 pub weight: NameWeight,
224 pub highlighted: bool,
225 }
226
227 impl NameStyle {
228 const PLAIN: NameStyle = NameStyle {
229 weight: NameWeight::Regular,
230 highlighted: false,
231 };
232 }
233
234 pub fn channel_name_style(unread: bool, shown: bool, selected: bool) -> NameStyle {
235 if !unread || !shown {
236 return NameStyle::PLAIN;
237 }
238 NameStyle {
239 weight: if selected {
240 NameWeight::Regular
241 } else {
242 NameWeight::Bold
243 },
244 highlighted: true,
245 }
246 }
247
248 pub fn team_has_unread(team: &SidebarTeam) -> bool {
249 team.channels
250 .iter()
251 .any(|channel| channel.unread && !team.hidden_channel_ids.contains(&channel.id))
252 }
253
254 pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle {
255 if expanded || !team_has_unread(team) {
256 return NameStyle::PLAIN;
257 }
258 NameStyle {
259 weight: NameWeight::Semibold,
260 highlighted: true,
261 }
262 }
263
264 pub fn channel_unread(sidebar: &Sidebar, channel_id: &str) -> bool {
265 sidebar
266 .teams
267 .iter()
268 .flat_map(|team| team.channels.iter())
269 .any(|channel| channel.id == channel_id && channel.unread)
270 }
271
213 272 pub fn any_unread_channel(sidebar: &Sidebar) -> bool {
214 273 sidebar
215 274 .teams
216 275 .iter()
217 .any(|team| team.channels.iter().any(|channel| channel.unread))
276 .filter(|team| !team.hidden)
277 .any(team_has_unread)
218 278 }
219 279
220 280 pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
@@ -674,6 +734,67 @@ mod tests {
674 734 }
675 735 }
676 736
737 fn with_unread(mut entry: SidebarTeam, unread_ids: &[&str]) -> SidebarTeam {
738 for channel in &mut entry.channels {
739 channel.unread = unread_ids.contains(&channel.id.as_str());
740 }
741 entry
742 }
743
744 #[test]
745 fn unread_shown_channel_is_bold_and_highlighted() {
746 let bold = NameStyle {
747 weight: NameWeight::Bold,
748 highlighted: true,
749 };
750 let plain = NameStyle {
751 weight: NameWeight::Regular,
752 highlighted: false,
753 };
754 assert_eq!(channel_name_style(true, true, false), bold);
755 assert_eq!(channel_name_style(false, true, false), plain);
756 assert_eq!(channel_name_style(true, false, false), plain);
757 assert_eq!(
758 channel_name_style(true, true, true),
759 NameStyle {
760 weight: NameWeight::Regular,
761 highlighted: true,
762 }
763 );
764 }
765
766 #[test]
767 fn collapsed_team_with_an_unread_shown_channel_is_semibold() {
768 let entry = with_unread(team("t1", false, &["a", "b"], &["b"]), &["a"]);
769 let semibold = NameStyle {
770 weight: NameWeight::Semibold,
771 highlighted: true,
772 };
773 assert_eq!(team_name_style(&entry, false), semibold);
774 assert_eq!(team_name_style(&entry, true), NameStyle::PLAIN);
775 let only_hidden = with_unread(team("t1", false, &["a", "b"], &["b"]), &["b"]);
776 assert_eq!(team_name_style(&only_hidden, false), NameStyle::PLAIN);
777 }
778
779 #[test]
780 fn rail_dot_counts_shown_channels_of_shown_teams_only() {
781 let sidebar = |teams: Vec<SidebarTeam>| Sidebar {
782 teams,
783 ..Sidebar::default()
784 };
785 let hidden_channel = with_unread(team("t1", false, &["a", "b"], &["b"]), &["b"]);
786 let hidden_team = with_unread(team("t2", true, &["c"], &[]), &["c"]);
787 assert!(!any_unread_channel(&sidebar(vec![
788 hidden_channel,
789 hidden_team
790 ])));
791 let shown = with_unread(team("t1", false, &["a"], &[]), &["a"]);
792 let both = sidebar(vec![shown]);
793 assert!(any_unread_channel(&both));
794 assert!(channel_unread(&both, "a"));
795 assert!(!channel_unread(&both, "missing"));
796 }
797
677 798 #[test]
678 799 fn visible_channels_list_pinned_first_then_open_teams() {
679 800 let teams = [
@@ -210,11 +210,71 @@ pub fn unread_chat_count(chats: &[ChatRecord]) -> u32 {
210 .count() as u32
210 .count() as u32
211}
211}
212
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
214pub enum NameWeight {
215 Regular,
216 Semibold,
217 Bold,
218}
219
220/// Teams channel list: `highlighted` is colorNeutralForeground1, otherwise colorNeutralForeground3.
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub struct NameStyle {
223 pub weight: NameWeight,
224 pub highlighted: bool,
225}
226
227impl NameStyle {
228 const PLAIN: NameStyle = NameStyle {
229 weight: NameWeight::Regular,
230 highlighted: false,
231 };
232}
233
234pub fn channel_name_style(unread: bool, shown: bool, selected: bool) -> NameStyle {
235 if !unread || !shown {
236 return NameStyle::PLAIN;
237 }
238 NameStyle {
239 weight: if selected {
240 NameWeight::Regular
241 } else {
242 NameWeight::Bold
243 },
244 highlighted: true,
245 }
246}
247
248pub fn team_has_unread(team: &SidebarTeam) -> bool {
249 team.channels
250 .iter()
251 .any(|channel| channel.unread && !team.hidden_channel_ids.contains(&channel.id))
252}
253
254pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle {
255 if expanded || !team_has_unread(team) {
256 return NameStyle::PLAIN;
257 }
258 NameStyle {
259 weight: NameWeight::Semibold,
260 highlighted: true,
261 }
262}
263
264pub fn channel_unread(sidebar: &Sidebar, channel_id: &str) -> bool {
265 sidebar
266 .teams
267 .iter()
268 .flat_map(|team| team.channels.iter())
269 .any(|channel| channel.id == channel_id && channel.unread)
270}
271
213pub fn any_unread_channel(sidebar: &Sidebar) -> bool {
272pub fn any_unread_channel(sidebar: &Sidebar) -> bool {
214 sidebar
273 sidebar
215 .teams
274 .teams
216 .iter()
275 .iter()
217 .any(|team| team.channels.iter().any(|channel| channel.unread))
276 .filter(|team| !team.hidden)
277 .any(team_has_unread)
218}
278}
219
279
220pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
280pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
@@ -674,6 +734,67 @@ mod tests {
674 }
734 }
675 }
735 }
676
736
737 fn with_unread(mut entry: SidebarTeam, unread_ids: &[&str]) -> SidebarTeam {
738 for channel in &mut entry.channels {
739 channel.unread = unread_ids.contains(&channel.id.as_str());
740 }
741 entry
742 }
743
744 #[test]
745 fn unread_shown_channel_is_bold_and_highlighted() {
746 let bold = NameStyle {
747 weight: NameWeight::Bold,
748 highlighted: true,
749 };
750 let plain = NameStyle {
751 weight: NameWeight::Regular,
752 highlighted: false,
753 };
754 assert_eq!(channel_name_style(true, true, false), bold);
755 assert_eq!(channel_name_style(false, true, false), plain);
756 assert_eq!(channel_name_style(true, false, false), plain);
757 assert_eq!(
758 channel_name_style(true, true, true),
759 NameStyle {
760 weight: NameWeight::Regular,
761 highlighted: true,
762 }
763 );
764 }
765
766 #[test]
767 fn collapsed_team_with_an_unread_shown_channel_is_semibold() {
768 let entry = with_unread(team("t1", false, &["a", "b"], &["b"]), &["a"]);
769 let semibold = NameStyle {
770 weight: NameWeight::Semibold,
771 highlighted: true,
772 };
773 assert_eq!(team_name_style(&entry, false), semibold);
774 assert_eq!(team_name_style(&entry, true), NameStyle::PLAIN);
775 let only_hidden = with_unread(team("t1", false, &["a", "b"], &["b"]), &["b"]);
776 assert_eq!(team_name_style(&only_hidden, false), NameStyle::PLAIN);
777 }
778
779 #[test]
780 fn rail_dot_counts_shown_channels_of_shown_teams_only() {
781 let sidebar = |teams: Vec<SidebarTeam>| Sidebar {
782 teams,
783 ..Sidebar::default()
784 };
785 let hidden_channel = with_unread(team("t1", false, &["a", "b"], &["b"]), &["b"]);
786 let hidden_team = with_unread(team("t2", true, &["c"], &[]), &["c"]);
787 assert!(!any_unread_channel(&sidebar(vec![
788 hidden_channel,
789 hidden_team
790 ])));
791 let shown = with_unread(team("t1", false, &["a"], &[]), &["a"]);
792 let both = sidebar(vec![shown]);
793 assert!(any_unread_channel(&both));
794 assert!(channel_unread(&both, "a"));
795 assert!(!channel_unread(&both, "missing"));
796 }
797
677 #[test]
798 #[test]
678 fn visible_channels_list_pinned_first_then_open_teams() {
799 fn visible_channels_list_pinned_first_then_open_teams() {
679 let teams = [
800 let teams = [
crates/app/src/views/conversation.rs +17 −11
@@ -71,7 +71,7 @@ use crate::rows::{
71 71 };
72 72 use crate::runtime;
73 73 use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
74 use crate::sidebar_model::{AvatarSpec, Face};
74 use crate::sidebar_model::{AvatarSpec, Face, channel_unread};
75 75 use crate::theme;
76 76 use crate::translation::TranslationLine;
77 77 use crate::typing::typing_tooltip;
@@ -1896,24 +1896,30 @@ impl ConversationView {
1896 1896 if state.viewing_call() && !self.pinned {
1897 1897 return;
1898 1898 }
1899 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone())
1900 else {
1899 let Some(selection) = self.current.as_ref().map(|c| c.selection.clone()) else {
1901 1900 return;
1902 1901 };
1903 1902 if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only {
1904 1903 return;
1905 1904 }
1906 let unread = state
1907 .sidebar
1908 .chats
1909 .iter()
1910 .any(|chat| chat.id == chat_id && chat.unread)
1911 && !state.keeps_unread(&chat_id);
1905 let unread = match &selection {
1906 Selection::Chat(chat_id) => {
1907 state
1908 .sidebar
1909 .chats
1910 .iter()
1911 .any(|chat| &chat.id == chat_id && chat.unread)
1912 && !state.keeps_unread(chat_id)
1913 }
1914 Selection::Channel(channel_id) => channel_unread(&state.sidebar, channel_id),
1915 };
1912 1916 let Some(plan) = plan_read(self.window_active, unread, trigger) else {
1913 1917 return;
1914 1918 };
1915 self.app
1916 .update(cx, |state, cx| state.mark_chat_read(&chat_id, cx));
1919 self.app.update(cx, |state, cx| match &selection {
1920 Selection::Chat(chat_id) => state.mark_chat_read(chat_id, cx),
1921 Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),
1922 });
1917 1923 if plan.clear_divider
1918 1924 && let Some(current) = self.current.as_mut()
1919 1925 && current.first_unread.take().is_some()
@@ -71,7 +71,7 @@ use crate::rows::{
71};
71};
72use crate::runtime;
72use crate::runtime;
73use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
73use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
74use crate::sidebar_model::{AvatarSpec, Face};
74use crate::sidebar_model::{AvatarSpec, Face, channel_unread};
75use crate::theme;
75use crate::theme;
76use crate::translation::TranslationLine;
76use crate::translation::TranslationLine;
77use crate::typing::typing_tooltip;
77use crate::typing::typing_tooltip;
@@ -1896,24 +1896,30 @@ impl ConversationView {
1896 if state.viewing_call() && !self.pinned {
1896 if state.viewing_call() && !self.pinned {
1897 return;
1897 return;
1898 }
1898 }
1899 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone())
1899 let Some(selection) = self.current.as_ref().map(|c| c.selection.clone()) else {
1900 else {
1901 return;
1900 return;
1902 };
1901 };
1903 if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only {
1902 if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only {
1904 return;
1903 return;
1905 }
1904 }
1906 let unread = state
1905 let unread = match &selection {
1907 .sidebar
1906 Selection::Chat(chat_id) => {
1908 .chats
1907 state
1909 .iter()
1908 .sidebar
1910 .any(|chat| chat.id == chat_id && chat.unread)
1909 .chats
1911 && !state.keeps_unread(&chat_id);
1910 .iter()
1911 .any(|chat| &chat.id == chat_id && chat.unread)
1912 && !state.keeps_unread(chat_id)
1913 }
1914 Selection::Channel(channel_id) => channel_unread(&state.sidebar, channel_id),
1915 };
1912 let Some(plan) = plan_read(self.window_active, unread, trigger) else {
1916 let Some(plan) = plan_read(self.window_active, unread, trigger) else {
1913 return;
1917 return;
1914 };
1918 };
1915 self.app
1919 self.app.update(cx, |state, cx| match &selection {
1916 .update(cx, |state, cx| state.mark_chat_read(&chat_id, cx));
1920 Selection::Chat(chat_id) => state.mark_chat_read(chat_id, cx),
1921 Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),
1922 });
1917 if plan.clear_divider
1923 if plan.clear_divider
1918 && let Some(current) = self.current.as_mut()
1924 && let Some(current) = self.current.as_mut()
1919 && current.first_unread.take().is_some()
1925 && current.first_unread.take().is_some()
crates/app/src/views/sidebar.rs +41 −38
@@ -19,7 +19,7 @@ use super::avatar::{spec_avatar, square_avatar, with_presence};
19 19 use super::calls_tab::calls_body;
20 20 use super::saved_panel::SavedPanel;
21 21 use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
22 use super::widgets::{count_badge, dot, icon, page_header, unread_marker};
22 use super::widgets::{count_badge, icon, page_header, unread_marker};
23 23 use crate::agents::AgentsPanel;
24 24 use crate::app_state::{AppEvent, AppState, Selection};
25 25 use crate::chat_actions::TITLE_LIMIT;
@@ -28,9 +28,10 @@ use crate::format;
28 28 use crate::local_previews::LocalPreview;
29 29 use crate::notice::truncated;
30 30 use crate::sidebar_model::{
31 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section,
32 SectionInput, SectionKind, Step, build_sections, older_chats_trigger_resets, step_id,
33 visible_channel_ids, wants_older_chats,
31 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, NameStyle,
32 NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,
33 channel_name_style, older_chats_trigger_resets, step_id, team_name_style, visible_channel_ids,
34 wants_older_chats,
34 35 };
35 36 use crate::theme;
36 37 use app_ui_kit::layout::SIDEBAR_WIDTH;
@@ -1220,6 +1221,7 @@ impl SidebarView {
1220 1221 notifications: ChannelNotifications,
1221 1222 ) -> AnyElement {
1222 1223 let unread = channel.unread;
1224 let name_style = channel_name_style(unread, true, selected);
1223 1225 let state = self.state.clone();
1224 1226 let menu_state = self.state.clone();
1225 1227 let menu_channel_id = channel_id.to_owned();
@@ -1259,12 +1261,8 @@ impl SidebarView {
1259 1261 .min_w_0()
1260 1262 .truncate()
1261 1263 .text_size(px(13.5))
1262 .font_weight(if unread {
1263 FontWeight::BOLD
1264 } else {
1265 FontWeight::NORMAL
1266 })
1267 .text_color(theme::text())
1264 .font_weight(name_weight(name_style))
1265 .text_color(name_color(name_style))
1268 1266 .child(format!("{} / {}", team.name, channel.name)),
1269 1267 )
1270 1268 .children(notification_badge(notifications.level))
@@ -1281,19 +1279,15 @@ impl SidebarView {
1281 1279 ),
1282 1280 )
1283 1281 .child(
1284 h_flex()
1285 .gap(px(8.))
1286 .items_center()
1287 .child(
1288 div()
1289 .flex_1()
1290 .min_w_0()
1291 .truncate()
1292 .text_size(px(12.))
1293 .text_color(theme::text_muted())
1294 .child(team.name.clone()),
1295 )
1296 .when(unread, |line| line.child(dot(7.))),
1282 h_flex().gap(px(8.)).items_center().child(
1283 div()
1284 .flex_1()
1285 .min_w_0()
1286 .truncate()
1287 .text_size(px(12.))
1288 .text_color(theme::text_muted())
1289 .child(team.name.clone()),
1290 ),
1297 1291 ),
1298 1292 )
1299 1293 .on_click(move |_, _, cx| {
@@ -1335,7 +1329,7 @@ impl SidebarView {
1335 1329 ) -> Div {
1336 1330 let team_id = entry.team.id.clone();
1337 1331 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1338 let unread = entry.channels.iter().any(|channel| channel.unread);
1332 let name_style = team_name_style(entry, expanded);
1339 1333 let toggle_id = team_id.clone();
1340 1334 list = list.child(
1341 1335 h_flex()
@@ -1364,15 +1358,10 @@ impl SidebarView {
1364 1358 .min_w_0()
1365 1359 .truncate()
1366 1360 .text_size(px(13.5))
1367 .font_weight(if unread || expanded {
1368 FontWeight::SEMIBOLD
1369 } else {
1370 FontWeight::NORMAL
1371 })
1372 .text_color(theme::text())
1361 .font_weight(name_weight(name_style))
1362 .text_color(name_color(name_style))
1373 1363 .child(entry.team.name.clone()),
1374 1364 )
1375 .when(unread && !expanded, |row| row.child(dot(7.)))
1376 1365 .on_click(cx.listener(move |this, _, _, cx| {
1377 1366 if !this.collapsed_teams.remove(&toggle_id) {
1378 1367 this.collapsed_teams.insert(toggle_id.clone());
@@ -1395,6 +1384,7 @@ impl SidebarView {
1395 1384 list = list.child(self.team_channel_row(
1396 1385 channel,
1397 1386 is_selected(channel),
1387 channel_name_style(channel.unread, !is_hidden(channel), is_selected(channel)),
1398 1388 entry.channel_notifications(&channel.id),
1399 1389 ));
1400 1390 }
@@ -1425,6 +1415,7 @@ impl SidebarView {
1425 1415 list = list.child(self.team_channel_row(
1426 1416 channel,
1427 1417 false,
1418 channel_name_style(channel.unread, false, false),
1428 1419 entry.channel_notifications(&channel.id),
1429 1420 ));
1430 1421 }
@@ -1473,6 +1464,7 @@ impl SidebarView {
1473 1464 &self,
1474 1465 channel: &ChannelRecord,
1475 1466 is_selected: bool,
1467 name_style: NameStyle,
1476 1468 notifications: ChannelNotifications,
1477 1469 ) -> impl IntoElement {
1478 1470 let state = self.state.clone();
@@ -1508,16 +1500,11 @@ impl SidebarView {
1508 1500 .min_w_0()
1509 1501 .truncate()
1510 1502 .text_size(px(13.5))
1511 .font_weight(if channel.unread {
1512 FontWeight::BOLD
1513 } else {
1514 FontWeight::NORMAL
1515 })
1516 .text_color(theme::text())
1503 .font_weight(name_weight(name_style))
1504 .text_color(name_color(name_style))
1517 1505 .child(channel.name.clone()),
1518 1506 )
1519 1507 .children(notification_badge(notifications.level))
1520 .when(channel.unread, |row| row.child(dot(7.)))
1521 1508 .on_click(move |_, _, cx| {
1522 1509 let selection = selection.clone();
1523 1510 state.update(cx, |state, cx| state.select(selection, cx));
@@ -1607,6 +1594,22 @@ impl SidebarView {
1607 1594 }
1608 1595 }
1609 1596
1597 fn name_weight(style: NameStyle) -> FontWeight {
1598 match style.weight {
1599 NameWeight::Regular => FontWeight::NORMAL,
1600 NameWeight::Semibold => FontWeight::SEMIBOLD,
1601 NameWeight::Bold => FontWeight::BOLD,
1602 }
1603 }
1604
1605 fn name_color(style: NameStyle) -> Hsla {
1606 if style.highlighted {
1607 theme::text()
1608 } else {
1609 theme::text_muted()
1610 }
1611 }
1612
1610 1613 fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1611 1614 let name = match level {
1612 1615 ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
@@ -19,7 +19,7 @@ use super::avatar::{spec_avatar, square_avatar, with_presence};
19use super::calls_tab::calls_body;
19use super::calls_tab::calls_body;
20use super::saved_panel::SavedPanel;
20use super::saved_panel::SavedPanel;
21use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
21use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
22use super::widgets::{count_badge, dot, icon, page_header, unread_marker};
22use super::widgets::{count_badge, icon, page_header, unread_marker};
23use crate::agents::AgentsPanel;
23use crate::agents::AgentsPanel;
24use crate::app_state::{AppEvent, AppState, Selection};
24use crate::app_state::{AppEvent, AppState, Selection};
25use crate::chat_actions::TITLE_LIMIT;
25use crate::chat_actions::TITLE_LIMIT;
@@ -28,9 +28,10 @@ use crate::format;
28use crate::local_previews::LocalPreview;
28use crate::local_previews::LocalPreview;
29use crate::notice::truncated;
29use crate::notice::truncated;
30use crate::sidebar_model::{
30use crate::sidebar_model::{
31 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section,
31 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, NameStyle,
32 SectionInput, SectionKind, Step, build_sections, older_chats_trigger_resets, step_id,
32 NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,
33 visible_channel_ids, wants_older_chats,
33 channel_name_style, older_chats_trigger_resets, step_id, team_name_style, visible_channel_ids,
34 wants_older_chats,
34};
35};
35use crate::theme;
36use crate::theme;
36use app_ui_kit::layout::SIDEBAR_WIDTH;
37use app_ui_kit::layout::SIDEBAR_WIDTH;
@@ -1220,6 +1221,7 @@ impl SidebarView {
1220 notifications: ChannelNotifications,
1221 notifications: ChannelNotifications,
1221 ) -> AnyElement {
1222 ) -> AnyElement {
1222 let unread = channel.unread;
1223 let unread = channel.unread;
1224 let name_style = channel_name_style(unread, true, selected);
1223 let state = self.state.clone();
1225 let state = self.state.clone();
1224 let menu_state = self.state.clone();
1226 let menu_state = self.state.clone();
1225 let menu_channel_id = channel_id.to_owned();
1227 let menu_channel_id = channel_id.to_owned();
@@ -1259,12 +1261,8 @@ impl SidebarView {
1259 .min_w_0()
1261 .min_w_0()
1260 .truncate()
1262 .truncate()
1261 .text_size(px(13.5))
1263 .text_size(px(13.5))
1262 .font_weight(if unread {
1264 .font_weight(name_weight(name_style))
1263 FontWeight::BOLD
1265 .text_color(name_color(name_style))
1264 } else {
1265 FontWeight::NORMAL
1266 })
1267 .text_color(theme::text())
1268 .child(format!("{} / {}", team.name, channel.name)),
1266 .child(format!("{} / {}", team.name, channel.name)),
1269 )
1267 )
1270 .children(notification_badge(notifications.level))
1268 .children(notification_badge(notifications.level))
@@ -1281,19 +1279,15 @@ impl SidebarView {
1281 ),
1279 ),
1282 )
1280 )
1283 .child(
1281 .child(
1284 h_flex()
1282 h_flex().gap(px(8.)).items_center().child(
1285 .gap(px(8.))
1283 div()
1286 .items_center()
1284 .flex_1()
1287 .child(
1285 .min_w_0()
1288 div()
1286 .truncate()
1289 .flex_1()
1287 .text_size(px(12.))
1290 .min_w_0()
1288 .text_color(theme::text_muted())
1291 .truncate()
1289 .child(team.name.clone()),
1292 .text_size(px(12.))
1290 ),
1293 .text_color(theme::text_muted())
1294 .child(team.name.clone()),
1295 )
1296 .when(unread, |line| line.child(dot(7.))),
1297 ),
1291 ),
1298 )
1292 )
1299 .on_click(move |_, _, cx| {
1293 .on_click(move |_, _, cx| {
@@ -1335,7 +1329,7 @@ impl SidebarView {
1335 ) -> Div {
1329 ) -> Div {
1336 let team_id = entry.team.id.clone();
1330 let team_id = entry.team.id.clone();
1337 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1331 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1338 let unread = entry.channels.iter().any(|channel| channel.unread);
1332 let name_style = team_name_style(entry, expanded);
1339 let toggle_id = team_id.clone();
1333 let toggle_id = team_id.clone();
1340 list = list.child(
1334 list = list.child(
1341 h_flex()
1335 h_flex()
@@ -1364,15 +1358,10 @@ impl SidebarView {
1364 .min_w_0()
1358 .min_w_0()
1365 .truncate()
1359 .truncate()
1366 .text_size(px(13.5))
1360 .text_size(px(13.5))
1367 .font_weight(if unread || expanded {
1361 .font_weight(name_weight(name_style))
1368 FontWeight::SEMIBOLD
1362 .text_color(name_color(name_style))
1369 } else {
1370 FontWeight::NORMAL
1371 })
1372 .text_color(theme::text())
1373 .child(entry.team.name.clone()),
1363 .child(entry.team.name.clone()),
1374 )
1364 )
1375 .when(unread && !expanded, |row| row.child(dot(7.)))
1376 .on_click(cx.listener(move |this, _, _, cx| {
1365 .on_click(cx.listener(move |this, _, _, cx| {
1377 if !this.collapsed_teams.remove(&toggle_id) {
1366 if !this.collapsed_teams.remove(&toggle_id) {
1378 this.collapsed_teams.insert(toggle_id.clone());
1367 this.collapsed_teams.insert(toggle_id.clone());
@@ -1395,6 +1384,7 @@ impl SidebarView {
1395 list = list.child(self.team_channel_row(
1384 list = list.child(self.team_channel_row(
1396 channel,
1385 channel,
1397 is_selected(channel),
1386 is_selected(channel),
1387 channel_name_style(channel.unread, !is_hidden(channel), is_selected(channel)),
1398 entry.channel_notifications(&channel.id),
1388 entry.channel_notifications(&channel.id),
1399 ));
1389 ));
1400 }
1390 }
@@ -1425,6 +1415,7 @@ impl SidebarView {
1425 list = list.child(self.team_channel_row(
1415 list = list.child(self.team_channel_row(
1426 channel,
1416 channel,
1427 false,
1417 false,
1418 channel_name_style(channel.unread, false, false),
1428 entry.channel_notifications(&channel.id),
1419 entry.channel_notifications(&channel.id),
1429 ));
1420 ));
1430 }
1421 }
@@ -1473,6 +1464,7 @@ impl SidebarView {
1473 &self,
1464 &self,
1474 channel: &ChannelRecord,
1465 channel: &ChannelRecord,
1475 is_selected: bool,
1466 is_selected: bool,
1467 name_style: NameStyle,
1476 notifications: ChannelNotifications,
1468 notifications: ChannelNotifications,
1477 ) -> impl IntoElement {
1469 ) -> impl IntoElement {
1478 let state = self.state.clone();
1470 let state = self.state.clone();
@@ -1508,16 +1500,11 @@ impl SidebarView {
1508 .min_w_0()
1500 .min_w_0()
1509 .truncate()
1501 .truncate()
1510 .text_size(px(13.5))
1502 .text_size(px(13.5))
1511 .font_weight(if channel.unread {
1503 .font_weight(name_weight(name_style))
1512 FontWeight::BOLD
1504 .text_color(name_color(name_style))
1513 } else {
1514 FontWeight::NORMAL
1515 })
1516 .text_color(theme::text())
1517 .child(channel.name.clone()),
1505 .child(channel.name.clone()),
1518 )
1506 )
1519 .children(notification_badge(notifications.level))
1507 .children(notification_badge(notifications.level))
1520 .when(channel.unread, |row| row.child(dot(7.)))
1521 .on_click(move |_, _, cx| {
1508 .on_click(move |_, _, cx| {
1522 let selection = selection.clone();
1509 let selection = selection.clone();
1523 state.update(cx, |state, cx| state.select(selection, cx));
1510 state.update(cx, |state, cx| state.select(selection, cx));
@@ -1607,6 +1594,22 @@ impl SidebarView {
1607 }
1594 }
1608}
1595}
1609
1596
1597fn name_weight(style: NameStyle) -> FontWeight {
1598 match style.weight {
1599 NameWeight::Regular => FontWeight::NORMAL,
1600 NameWeight::Semibold => FontWeight::SEMIBOLD,
1601 NameWeight::Bold => FontWeight::BOLD,
1602 }
1603}
1604
1605fn name_color(style: NameStyle) -> Hsla {
1606 if style.highlighted {
1607 theme::text()
1608 } else {
1609 theme::text_muted()
1610 }
1611}
1612
1610fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1613fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1611 let name = match level {
1614 let name = match level {
1612 ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
1615 ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
crates/chatsvc/src/conversations.rs +59 −0
@@ -5,6 +5,7 @@ use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};
5 5 use crate::error::{Error, Result};
6 6 use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
7 7 use crate::pins::DEFAULT_REGION;
8 use crate::read_horizon::{self, ReadHorizon};
8 9
9 10 const PAGE_SIZE: usize = 200;
10 11 const MAX_PAGES: usize = 100;
@@ -15,6 +16,7 @@ pub struct ConversationState {
15 16 pub id: String,
16 17 pub muted: bool,
17 18 pub hidden: Option<bool>,
19 pub read: ReadHorizon,
18 20 }
19 21
20 22 pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
@@ -82,6 +84,21 @@ impl<T: MessageTransport> Conversations<T> {
82 84 ensure_success(&answer)
83 85 }
84 86
87 pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
88 let url = format!(
89 "{}/{}/properties?name={}",
90 self.base_url,
91 encode(conversation_id),
92 read_horizon::PROPERTY_NAME
93 );
94 let body = json!({ read_horizon::PROPERTY_NAME: horizon });
95 let answer = self
96 .transport
97 .send(Request::with_body(Method::Put, url, body))
98 .await?;
99 ensure_success(&answer)
100 }
101
85 102 pub async fn set_channel_notifications(
86 103 &self,
87 104 channel_id: &str,
@@ -141,6 +158,7 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
141 158 id: id.to_owned(),
142 159 muted,
143 160 hidden: hidden_flag(conversation),
161 read: ReadHorizon::from_conversation(conversation),
144 162 })
145 163 })
146 164 .collect())
@@ -184,6 +202,7 @@ mod tests {
184 202 id: id.to_owned(),
185 203 muted,
186 204 hidden: None,
205 read: ReadHorizon::default(),
187 206 }
188 207 }
189 208
@@ -319,4 +338,44 @@ mod tests {
319 338 assert_eq!(requests[0].body, Some(json!({"alerts": "false"})));
320 339 assert_eq!(requests[1].body, Some(json!({"alerts": "true"})));
321 340 }
341
342 #[tokio::test]
343 async fn states_carry_the_read_horizon() {
344 let transport = canned(vec![(
345 200,
346 json!({
347 "conversations": [{
348 "id": "19:a",
349 "properties": {"consumptionhorizon": "5;6;7"},
350 "lastMessage": {"originalarrivaltime": "1970-01-01T00:00:00.009Z", "from": "x/contacts/8:orgid:b"},
351 }],
352 }),
353 )]);
354 let states = Conversations::with_transport(&transport, "emea")
355 .conversation_states()
356 .await
357 .unwrap();
358 assert_eq!(states[0].read.consumed_until_ms, 5);
359 assert_eq!(states[0].read.last_message_ms, 9);
360 assert!(states[0].read.is_unread("8:orgid:me"));
361 }
362
363 #[tokio::test]
364 async fn set_read_horizon_puts_the_consumption_horizon_property() {
365 let transport = canned(vec![(200, Value::Null)]);
366 Conversations::with_transport(&transport, "emea")
367 .set_read_horizon("19:a@thread.skype", "9;10;0")
368 .await
369 .unwrap();
370 let requests = transport.requests.lock().unwrap();
371 assert_eq!(requests[0].method, Method::Put);
372 assert_eq!(
373 requests[0].url,
374 format!("{BASE}/19%3Aa%40thread.skype/properties?name=consumptionhorizon")
375 );
376 assert_eq!(
377 requests[0].body,
378 Some(json!({"consumptionhorizon": "9;10;0"}))
379 );
380 }
322 381 }
@@ -5,6 +5,7 @@ use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};
5use crate::error::{Error, Result};
5use crate::error::{Error, Result};
6use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
6use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
7use crate::pins::DEFAULT_REGION;
7use crate::pins::DEFAULT_REGION;
8use crate::read_horizon::{self, ReadHorizon};
8
9
9const PAGE_SIZE: usize = 200;
10const PAGE_SIZE: usize = 200;
10const MAX_PAGES: usize = 100;
11const MAX_PAGES: usize = 100;
@@ -15,6 +16,7 @@ pub struct ConversationState {
15 pub id: String,
16 pub id: String,
16 pub muted: bool,
17 pub muted: bool,
17 pub hidden: Option<bool>,
18 pub hidden: Option<bool>,
19 pub read: ReadHorizon,
18}
20}
19
21
20pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
22pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
@@ -82,6 +84,21 @@ impl<T: MessageTransport> Conversations<T> {
82 ensure_success(&answer)
84 ensure_success(&answer)
83 }
85 }
84
86
87 pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
88 let url = format!(
89 "{}/{}/properties?name={}",
90 self.base_url,
91 encode(conversation_id),
92 read_horizon::PROPERTY_NAME
93 );
94 let body = json!({ read_horizon::PROPERTY_NAME: horizon });
95 let answer = self
96 .transport
97 .send(Request::with_body(Method::Put, url, body))
98 .await?;
99 ensure_success(&answer)
100 }
101
85 pub async fn set_channel_notifications(
102 pub async fn set_channel_notifications(
86 &self,
103 &self,
87 channel_id: &str,
104 channel_id: &str,
@@ -141,6 +158,7 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
141 id: id.to_owned(),
158 id: id.to_owned(),
142 muted,
159 muted,
143 hidden: hidden_flag(conversation),
160 hidden: hidden_flag(conversation),
161 read: ReadHorizon::from_conversation(conversation),
144 })
162 })
145 })
163 })
146 .collect())
164 .collect())
@@ -184,6 +202,7 @@ mod tests {
184 id: id.to_owned(),
202 id: id.to_owned(),
185 muted,
203 muted,
186 hidden: None,
204 hidden: None,
205 read: ReadHorizon::default(),
187 }
206 }
188 }
207 }
189
208
@@ -319,4 +338,44 @@ mod tests {
319 assert_eq!(requests[0].body, Some(json!({"alerts": "false"})));
338 assert_eq!(requests[0].body, Some(json!({"alerts": "false"})));
320 assert_eq!(requests[1].body, Some(json!({"alerts": "true"})));
339 assert_eq!(requests[1].body, Some(json!({"alerts": "true"})));
321 }
340 }
341
342 #[tokio::test]
343 async fn states_carry_the_read_horizon() {
344 let transport = canned(vec![(
345 200,
346 json!({
347 "conversations": [{
348 "id": "19:a",
349 "properties": {"consumptionhorizon": "5;6;7"},
350 "lastMessage": {"originalarrivaltime": "1970-01-01T00:00:00.009Z", "from": "x/contacts/8:orgid:b"},
351 }],
352 }),
353 )]);
354 let states = Conversations::with_transport(&transport, "emea")
355 .conversation_states()
356 .await
357 .unwrap();
358 assert_eq!(states[0].read.consumed_until_ms, 5);
359 assert_eq!(states[0].read.last_message_ms, 9);
360 assert!(states[0].read.is_unread("8:orgid:me"));
361 }
362
363 #[tokio::test]
364 async fn set_read_horizon_puts_the_consumption_horizon_property() {
365 let transport = canned(vec![(200, Value::Null)]);
366 Conversations::with_transport(&transport, "emea")
367 .set_read_horizon("19:a@thread.skype", "9;10;0")
368 .await
369 .unwrap();
370 let requests = transport.requests.lock().unwrap();
371 assert_eq!(requests[0].method, Method::Put);
372 assert_eq!(
373 requests[0].url,
374 format!("{BASE}/19%3Aa%40thread.skype/properties?name=consumptionhorizon")
375 );
376 assert_eq!(
377 requests[0].body,
378 Some(json!({"consumptionhorizon": "9;10;0"}))
379 );
380 }
322}
381}
crates/chatsvc/src/lib.rs +2 −0
@@ -15,6 +15,7 @@ pub mod messages;
15 15 pub mod pins;
16 16 pub mod presence;
17 17 pub mod reactions;
18 pub mod read_horizon;
18 19 pub mod recap;
19 20 pub mod realtime;
20 21 pub mod recording_policy;
@@ -35,6 +36,7 @@ pub use cards::{
35 36 };
36 37 pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
37 38 pub use conversations::{ConversationState, Conversations};
39 pub use read_horizon::ReadHorizon;
38 40 pub use drafts::{ScheduledDraft, ScheduledDrafts};
39 41 pub use error::{Error, Result};
40 42 pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
@@ -15,6 +15,7 @@ pub mod messages;
15pub mod pins;
15pub mod pins;
16pub mod presence;
16pub mod presence;
17pub mod reactions;
17pub mod reactions;
18pub mod read_horizon;
18pub mod recap;
19pub mod recap;
19pub mod realtime;
20pub mod realtime;
20pub mod recording_policy;
21pub mod recording_policy;
@@ -35,6 +36,7 @@ pub use cards::{
35};
36};
36pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
37pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
37pub use conversations::{ConversationState, Conversations};
38pub use conversations::{ConversationState, Conversations};
39pub use read_horizon::ReadHorizon;
38pub use drafts::{ScheduledDraft, ScheduledDrafts};
40pub use drafts::{ScheduledDraft, ScheduledDrafts};
39pub use error::{Error, Result};
41pub use error::{Error, Result};
40pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
42pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
crates/chatsvc/src/read_horizon.rs added +201 −0
@@ -0,0 +1,201 @@
1 use chrono::{DateTime, Utc};
2 use serde_json::Value;
3
4 pub const PROPERTY_NAME: &str = "consumptionhorizon";
5
6 /// Read state of one conversation as chatsvc lists it, judged like the Teams worker (`hasUnreadMessages`).
7 #[derive(Debug, Clone, PartialEq, Eq, Default)]
8 pub struct ReadHorizon {
9 pub consumed_until_ms: i64,
10 pub bookmark_ms: i64,
11 pub bookmark_message_set: bool,
12 pub last_message_ms: i64,
13 pub last_message_from: Option<String>,
14 }
15
16 impl ReadHorizon {
17 pub fn from_conversation(conversation: &Value) -> Self {
18 let properties = &conversation["properties"];
19 let horizon = parse_horizon(properties["consumptionhorizon"].as_str());
20 let bookmark = parse_horizon(properties["consumptionHorizonBookmark"].as_str());
21 let last_message = &conversation["lastMessage"];
22 ReadHorizon {
23 consumed_until_ms: horizon.arrival_ms,
24 bookmark_ms: bookmark.arrival_ms,
25 bookmark_message_set: bookmark.message_set,
26 last_message_ms: last_message_ms(conversation),
27 last_message_from: last_message["from"]
28 .as_str()
29 .and_then(|from| from.rsplit('/').next())
30 .filter(|from| !from.is_empty())
31 .map(str::to_owned),
32 }
33 }
34
35 pub fn is_unread(&self, my_user_id: &str) -> bool {
36 if self.bookmark_ms != 0 && self.bookmark_message_set {
37 return true;
38 }
39 let unread = self.bookmark_ms != 0 || self.last_message_ms > self.consumed_until_ms;
40 let from_me = self
41 .last_message_from
42 .as_deref()
43 .is_some_and(|from| !my_user_id.is_empty() && from.contains(my_user_id));
44 unread && !from_me
45 }
46
47 pub fn last_message_at(&self) -> Option<DateTime<Utc>> {
48 (self.last_message_ms > 0)
49 .then(|| DateTime::from_timestamp_millis(self.last_message_ms))
50 .flatten()
51 }
52 }
53
54 /// The value Teams writes when a conversation is read: last arrival time, now, client message id.
55 pub fn read_up_to(last_message_at: DateTime<Utc>, now: DateTime<Utc>) -> String {
56 format!(
57 "{};{};0",
58 last_message_at.timestamp_millis(),
59 now.timestamp_millis()
60 )
61 }
62
63 struct ParsedHorizon {
64 arrival_ms: i64,
65 message_set: bool,
66 }
67
68 fn parse_horizon(text: Option<&str>) -> ParsedHorizon {
69 let parts: Vec<&str> = text.unwrap_or_default().split(';').collect();
70 let number = |part: &str| part.trim().parse::<i64>().ok();
71 let unset = ParsedHorizon {
72 arrival_ms: 0,
73 message_set: false,
74 };
75 let [arrival, timestamp, message_id] = parts.as_slice() else {
76 return unset;
77 };
78 let message_id = message_id.trim();
79 match (number(arrival), number(timestamp)) {
80 (Some(arrival_ms), Some(_)) if !message_id.is_empty() => ParsedHorizon {
81 arrival_ms,
82 message_set: message_id != "0",
83 },
84 _ => unset,
85 }
86 }
87
88 fn last_message_ms(conversation: &Value) -> i64 {
89 if let Some(time) = conversation["lastMessageTimeUtc"].as_i64() {
90 return time;
91 }
92 conversation["lastMessage"]["originalarrivaltime"]
93 .as_str()
94 .and_then(|text| DateTime::parse_from_rfc3339(text).ok())
95 .map_or(0, |time| time.timestamp_millis())
96 }
97
98 #[cfg(test)]
99 mod tests {
100 use serde_json::json;
101
102 use super::*;
103
104 const ME: &str = "8:orgid:me";
105
106 fn conversation(
107 horizon: Option<&str>,
108 bookmark: Option<&str>,
109 last: Option<(&str, &str)>,
110 ) -> Value {
111 json!({
112 "id": "19:channel@thread.skype",
113 "properties": {
114 "consumptionhorizon": horizon,
115 "consumptionHorizonBookmark": bookmark,
116 },
117 "lastMessage": last.map(|(arrival, from)| json!({
118 "originalarrivaltime": arrival,
119 "from": format!("https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/contacts/{from}"),
120 })).unwrap_or_else(|| json!({})),
121 })
122 }
123
124 fn unread(value: &Value) -> bool {
125 ReadHorizon::from_conversation(value).is_unread(ME)
126 }
127
128 #[test]
129 fn message_after_the_horizon_is_unread() {
130 let value = conversation(
131 Some("1791884440747;1791885752824;1131155174560809354"),
132 None,
133 Some(("2026-10-16T09:42:25.6780000Z", "8:orgid:other")),
134 );
135 assert!(unread(&value));
136 }
137
138 #[test]
139 fn message_at_or_before_the_horizon_is_read() {
140 let value = conversation(
141 Some("1792171970947;1792171971513;1792171970879"),
142 Some(""),
143 Some(("2026-10-16T17:32:50.9470000Z", "8:orgid:other")),
144 );
145 assert!(!unread(&value));
146 }
147
148 #[test]
149 fn missing_horizon_counts_every_message_as_unread() {
150 let value = conversation(None, None, Some(("2026-10-16T20:30:58.901Z", "28:bot")));
151 assert!(unread(&value));
152 }
153
154 #[test]
155 fn channel_without_messages_is_read() {
156 assert!(!unread(&conversation(None, None, None)));
157 }
158
159 #[test]
160 fn own_last_message_is_read() {
161 let value = conversation(Some("1;2;3"), None, Some(("2026-10-16T09:42:25.678Z", ME)));
162 assert!(!unread(&value));
163 }
164
165 #[test]
166 fn bookmark_with_a_message_marks_unread_even_for_own_message() {
167 let value = conversation(
168 Some("1792171970947;1792171971513;1"),
169 Some("1792171970000;1792171971513;42"),
170 Some(("2026-10-16T17:32:50.9470000Z", ME)),
171 );
172 assert!(unread(&value));
173 }
174
175 #[test]
176 fn empty_bookmark_from_teams_is_ignored() {
177 let value = conversation(
178 Some("1792171970947;1792171971513;1"),
179 Some("0;1697436994849;0"),
180 Some(("2026-10-16T17:32:50.9470000Z", "8:orgid:other")),
181 );
182 assert!(!unread(&value));
183 }
184
185 #[test]
186 fn malformed_horizon_counts_as_none() {
187 let value = conversation(
188 Some("garbage"),
189 None,
190 Some(("2026-10-16T09:42:25.678Z", "8:orgid:other")),
191 );
192 assert!(unread(&value));
193 }
194
195 #[test]
196 fn read_value_carries_the_last_arrival_and_now() {
197 let last = DateTime::from_timestamp_millis(1792182658901).unwrap();
198 let now = DateTime::from_timestamp_millis(1792190000000).unwrap();
199 assert_eq!(read_up_to(last, now), "1792182658901;1792190000000;0");
200 }
201 }
@@ -0,0 +1,201 @@
1use chrono::{DateTime, Utc};
2use serde_json::Value;
3
4pub const PROPERTY_NAME: &str = "consumptionhorizon";
5
6/// Read state of one conversation as chatsvc lists it, judged like the Teams worker (`hasUnreadMessages`).
7#[derive(Debug, Clone, PartialEq, Eq, Default)]
8pub struct ReadHorizon {
9 pub consumed_until_ms: i64,
10 pub bookmark_ms: i64,
11 pub bookmark_message_set: bool,
12 pub last_message_ms: i64,
13 pub last_message_from: Option<String>,
14}
15
16impl ReadHorizon {
17 pub fn from_conversation(conversation: &Value) -> Self {
18 let properties = &conversation["properties"];
19 let horizon = parse_horizon(properties["consumptionhorizon"].as_str());
20 let bookmark = parse_horizon(properties["consumptionHorizonBookmark"].as_str());
21 let last_message = &conversation["lastMessage"];
22 ReadHorizon {
23 consumed_until_ms: horizon.arrival_ms,
24 bookmark_ms: bookmark.arrival_ms,
25 bookmark_message_set: bookmark.message_set,
26 last_message_ms: last_message_ms(conversation),
27 last_message_from: last_message["from"]
28 .as_str()
29 .and_then(|from| from.rsplit('/').next())
30 .filter(|from| !from.is_empty())
31 .map(str::to_owned),
32 }
33 }
34
35 pub fn is_unread(&self, my_user_id: &str) -> bool {
36 if self.bookmark_ms != 0 && self.bookmark_message_set {
37 return true;
38 }
39 let unread = self.bookmark_ms != 0 || self.last_message_ms > self.consumed_until_ms;
40 let from_me = self
41 .last_message_from
42 .as_deref()
43 .is_some_and(|from| !my_user_id.is_empty() && from.contains(my_user_id));
44 unread && !from_me
45 }
46
47 pub fn last_message_at(&self) -> Option<DateTime<Utc>> {
48 (self.last_message_ms > 0)
49 .then(|| DateTime::from_timestamp_millis(self.last_message_ms))
50 .flatten()
51 }
52}
53
54/// The value Teams writes when a conversation is read: last arrival time, now, client message id.
55pub fn read_up_to(last_message_at: DateTime<Utc>, now: DateTime<Utc>) -> String {
56 format!(
57 "{};{};0",
58 last_message_at.timestamp_millis(),
59 now.timestamp_millis()
60 )
61}
62
63struct ParsedHorizon {
64 arrival_ms: i64,
65 message_set: bool,
66}
67
68fn parse_horizon(text: Option<&str>) -> ParsedHorizon {
69 let parts: Vec<&str> = text.unwrap_or_default().split(';').collect();
70 let number = |part: &str| part.trim().parse::<i64>().ok();
71 let unset = ParsedHorizon {
72 arrival_ms: 0,
73 message_set: false,
74 };
75 let [arrival, timestamp, message_id] = parts.as_slice() else {
76 return unset;
77 };
78 let message_id = message_id.trim();
79 match (number(arrival), number(timestamp)) {
80 (Some(arrival_ms), Some(_)) if !message_id.is_empty() => ParsedHorizon {
81 arrival_ms,
82 message_set: message_id != "0",
83 },
84 _ => unset,
85 }
86}
87
88fn last_message_ms(conversation: &Value) -> i64 {
89 if let Some(time) = conversation["lastMessageTimeUtc"].as_i64() {
90 return time;
91 }
92 conversation["lastMessage"]["originalarrivaltime"]
93 .as_str()
94 .and_then(|text| DateTime::parse_from_rfc3339(text).ok())
95 .map_or(0, |time| time.timestamp_millis())
96}
97
98#[cfg(test)]
99mod tests {
100 use serde_json::json;
101
102 use super::*;
103
104 const ME: &str = "8:orgid:me";
105
106 fn conversation(
107 horizon: Option<&str>,
108 bookmark: Option<&str>,
109 last: Option<(&str, &str)>,
110 ) -> Value {
111 json!({
112 "id": "19:channel@thread.skype",
113 "properties": {
114 "consumptionhorizon": horizon,
115 "consumptionHorizonBookmark": bookmark,
116 },
117 "lastMessage": last.map(|(arrival, from)| json!({
118 "originalarrivaltime": arrival,
119 "from": format!("https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/contacts/{from}"),
120 })).unwrap_or_else(|| json!({})),
121 })
122 }
123
124 fn unread(value: &Value) -> bool {
125 ReadHorizon::from_conversation(value).is_unread(ME)
126 }
127
128 #[test]
129 fn message_after_the_horizon_is_unread() {
130 let value = conversation(
131 Some("1791884440747;1791885752824;1131155174560809354"),
132 None,
133 Some(("2026-10-16T09:42:25.6780000Z", "8:orgid:other")),
134 );
135 assert!(unread(&value));
136 }
137
138 #[test]
139 fn message_at_or_before_the_horizon_is_read() {
140 let value = conversation(
141 Some("1792171970947;1792171971513;1792171970879"),
142 Some(""),
143 Some(("2026-10-16T17:32:50.9470000Z", "8:orgid:other")),
144 );
145 assert!(!unread(&value));
146 }
147
148 #[test]
149 fn missing_horizon_counts_every_message_as_unread() {
150 let value = conversation(None, None, Some(("2026-10-16T20:30:58.901Z", "28:bot")));
151 assert!(unread(&value));
152 }
153
154 #[test]
155 fn channel_without_messages_is_read() {
156 assert!(!unread(&conversation(None, None, None)));
157 }
158
159 #[test]
160 fn own_last_message_is_read() {
161 let value = conversation(Some("1;2;3"), None, Some(("2026-10-16T09:42:25.678Z", ME)));
162 assert!(!unread(&value));
163 }
164
165 #[test]
166 fn bookmark_with_a_message_marks_unread_even_for_own_message() {
167 let value = conversation(
168 Some("1792171970947;1792171971513;1"),
169 Some("1792171970000;1792171971513;42"),
170 Some(("2026-10-16T17:32:50.9470000Z", ME)),
171 );
172 assert!(unread(&value));
173 }
174
175 #[test]
176 fn empty_bookmark_from_teams_is_ignored() {
177 let value = conversation(
178 Some("1792171970947;1792171971513;1"),
179 Some("0;1697436994849;0"),
180 Some(("2026-10-16T17:32:50.9470000Z", "8:orgid:other")),
181 );
182 assert!(!unread(&value));
183 }
184
185 #[test]
186 fn malformed_horizon_counts_as_none() {
187 let value = conversation(
188 Some("garbage"),
189 None,
190 Some(("2026-10-16T09:42:25.678Z", "8:orgid:other")),
191 );
192 assert!(unread(&value));
193 }
194
195 #[test]
196 fn read_value_carries_the_last_arrival_and_now() {
197 let last = DateTime::from_timestamp_millis(1792182658901).unwrap();
198 let now = DateTime::from_timestamp_millis(1792190000000).unwrap();
199 assert_eq!(read_up_to(last, now), "1792182658901;1792190000000;0");
200 }
201}
crates/core/src/actions.rs +20 −2
@@ -359,8 +359,8 @@ impl<R: Remote> SyncEngine<R> {
359 359 }
360 360
361 361 pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {
362 if !matches!(self.resolve(conversation_id).await?, Conversation::Chat) {
363 return Err(Error::Unsupported("marking a channel as read"));
362 if let Conversation::Channel { .. } = self.resolve(conversation_id).await? {
363 return self.mark_channel_read(conversation_id).await;
364 364 }
365 365 let user_id = self.my_user_id().await?;
366 366 let tenant_id = self.my_tenant_id(conversation_id).await?;
@@ -372,6 +372,24 @@ impl<R: Remote> SyncEngine<R> {
372 372 Ok(())
373 373 }
374 374
375 async fn mark_channel_read(&self, channel_id: &str) -> Result<()> {
376 let now = Utc::now();
377 let last_message_at = self
378 .store
379 .channel(channel_id)?
380 .and_then(|channel| channel.last_message_at)
381 .unwrap_or(now);
382 self.remote
383 .set_read_horizon(
384 channel_id,
385 &chatsvc::read_horizon::read_up_to(last_message_at, now),
386 )
387 .await?;
388 self.store.mark_channel_read(channel_id)?;
389 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
390 Ok(())
391 }
392
375 393 pub async fn mark_unread(&self, chat_id: &str) -> Result<()> {
376 394 let last_message_at = self
377 395 .store
@@ -359,8 +359,8 @@ impl<R: Remote> SyncEngine<R> {
359 }
359 }
360
360
361 pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {
361 pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {
362 if !matches!(self.resolve(conversation_id).await?, Conversation::Chat) {
362 if let Conversation::Channel { .. } = self.resolve(conversation_id).await? {
363 return Err(Error::Unsupported("marking a channel as read"));
363 return self.mark_channel_read(conversation_id).await;
364 }
364 }
365 let user_id = self.my_user_id().await?;
365 let user_id = self.my_user_id().await?;
366 let tenant_id = self.my_tenant_id(conversation_id).await?;
366 let tenant_id = self.my_tenant_id(conversation_id).await?;
@@ -372,6 +372,24 @@ impl<R: Remote> SyncEngine<R> {
372 Ok(())
372 Ok(())
373 }
373 }
374
374
375 async fn mark_channel_read(&self, channel_id: &str) -> Result<()> {
376 let now = Utc::now();
377 let last_message_at = self
378 .store
379 .channel(channel_id)?
380 .and_then(|channel| channel.last_message_at)
381 .unwrap_or(now);
382 self.remote
383 .set_read_horizon(
384 channel_id,
385 &chatsvc::read_horizon::read_up_to(last_message_at, now),
386 )
387 .await?;
388 self.store.mark_channel_read(channel_id)?;
389 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
390 Ok(())
391 }
392
375 pub async fn mark_unread(&self, chat_id: &str) -> Result<()> {
393 pub async fn mark_unread(&self, chat_id: &str) -> Result<()> {
376 let last_message_at = self
394 let last_message_at = self
377 .store
395 .store
crates/core/src/hidden_chats.rs +1 −0
@@ -172,6 +172,7 @@ mod tests {
172 172 id: "19:a".to_owned(),
173 173 muted: false,
174 174 hidden,
175 read: chatsvc::ReadHorizon::default(),
175 176 },
176 177 )])
177 178 }
@@ -172,6 +172,7 @@ mod tests {
172 id: "19:a".to_owned(),
172 id: "19:a".to_owned(),
173 muted: false,
173 muted: false,
174 hidden,
174 hidden,
175 read: chatsvc::ReadHorizon::default(),
175 },
176 },
176 )])
177 )])
177 }
178 }
crates/core/src/remote.rs +7 −0
@@ -123,6 +123,7 @@ pub trait Remote {
123 123 async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
124 124 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
125 125 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
126 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
126 127 async fn set_channel_notifications(
127 128 &self,
128 129 channel_id: &str,
@@ -636,6 +637,12 @@ impl Remote for Graph {
636 637 .await?)
637 638 }
638 639
640 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
641 Ok(Conversations::new(self.session())
642 .set_read_horizon(conversation_id, horizon)
643 .await?)
644 }
645
639 646 async fn set_channel_notifications(
640 647 &self,
641 648 channel_id: &str,
@@ -123,6 +123,7 @@ pub trait Remote {
123 async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
123 async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
124 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
124 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
125 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
125 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
126 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
126 async fn set_channel_notifications(
127 async fn set_channel_notifications(
127 &self,
128 &self,
128 channel_id: &str,
129 channel_id: &str,
@@ -636,6 +637,12 @@ impl Remote for Graph {
636 .await?)
637 .await?)
637 }
638 }
638
639
640 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
641 Ok(Conversations::new(self.session())
642 .set_read_horizon(conversation_id, horizon)
643 .await?)
644 }
645
639 async fn set_channel_notifications(
646 async fn set_channel_notifications(
640 &self,
647 &self,
641 channel_id: &str,
648 channel_id: &str,
crates/core/src/sidebar_sync.rs +20 −0
@@ -92,6 +92,7 @@ impl<R: Remote> SyncEngine<R> {
92 92 page = self.remote.chats_at(&link).await?;
93 93 }
94 94 self.store.remove_chats(&hidden_ids)?;
95 self.apply_channel_read_states(states.as_deref(), &my_user_id);
95 96 self.apply_muted_chats(states);
96 97 if full {
97 98 if complete {
@@ -138,6 +139,25 @@ impl<R: Remote> SyncEngine<R> {
138 139 Ok(())
139 140 }
140 141
142 fn apply_channel_read_states(&self, states: Option<&[ConversationState]>, my_user_id: &str) {
143 let Some(states) = states else {
144 return;
145 };
146 let read_states: Vec<_> = states
147 .iter()
148 .map(|state| {
149 (
150 state.id.clone(),
151 state.read.is_unread(my_user_id),
152 state.read.last_message_at(),
153 )
154 })
155 .collect();
156 if let Err(error) = self.store.apply_channel_read_states(&read_states) {
157 self.report(format!("cannot refresh unread channels: {error}"));
158 }
159 }
160
141 161 fn apply_muted_chats(&self, states: Option<Vec<ConversationState>>) {
142 162 let Some(states) = states else {
143 163 return;
@@ -92,6 +92,7 @@ impl<R: Remote> SyncEngine<R> {
92 page = self.remote.chats_at(&link).await?;
92 page = self.remote.chats_at(&link).await?;
93 }
93 }
94 self.store.remove_chats(&hidden_ids)?;
94 self.store.remove_chats(&hidden_ids)?;
95 self.apply_channel_read_states(states.as_deref(), &my_user_id);
95 self.apply_muted_chats(states);
96 self.apply_muted_chats(states);
96 if full {
97 if full {
97 if complete {
98 if complete {
@@ -138,6 +139,25 @@ impl<R: Remote> SyncEngine<R> {
138 Ok(())
139 Ok(())
139 }
140 }
140
141
142 fn apply_channel_read_states(&self, states: Option<&[ConversationState]>, my_user_id: &str) {
143 let Some(states) = states else {
144 return;
145 };
146 let read_states: Vec<_> = states
147 .iter()
148 .map(|state| {
149 (
150 state.id.clone(),
151 state.read.is_unread(my_user_id),
152 state.read.last_message_at(),
153 )
154 })
155 .collect();
156 if let Err(error) = self.store.apply_channel_read_states(&read_states) {
157 self.report(format!("cannot refresh unread channels: {error}"));
158 }
159 }
160
141 fn apply_muted_chats(&self, states: Option<Vec<ConversationState>>) {
161 fn apply_muted_chats(&self, states: Option<Vec<ConversationState>>) {
142 let Some(states) = states else {
162 let Some(states) = states else {
143 return;
163 return;
crates/core/tests/engine.rs +50 −0
@@ -117,6 +117,7 @@ struct Fake {
117 117 invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,
118 118 muted_states: Mutex<Vec<(String, bool)>>,
119 119 hidden_states: Mutex<Vec<(String, bool)>>,
120 read_states: Mutex<Vec<(String, chatsvc::ReadHorizon)>>,
120 121 chats_fail: Mutex<bool>,
121 122 muted_fails: Mutex<bool>,
122 123 link_pages: Mutex<Vec<chatsvc::MessageLinks>>,
@@ -525,6 +526,7 @@ impl Remote for Handle {
525 526 id,
526 527 muted,
527 528 hidden: None,
529 read: chatsvc::ReadHorizon::default(),
528 530 })
529 531 .collect();
530 532 states.extend(
@@ -534,6 +536,17 @@ impl Remote for Handle {
534 536 id,
535 537 muted: false,
536 538 hidden: Some(hidden),
539 read: chatsvc::ReadHorizon::default(),
540 }),
541 );
542 let read = self.read_states.lock().unwrap().clone();
543 states.extend(
544 read.into_iter()
545 .map(|(id, read)| chatsvc::ConversationState {
546 id,
547 muted: false,
548 hidden: None,
549 read,
537 550 }),
538 551 );
539 552 Ok(states)
@@ -544,6 +557,11 @@ impl Remote for Handle {
544 557 Ok(())
545 558 }
546 559
560 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
561 self.record(format!("read horizon {conversation_id} {horizon}"));
562 Ok(())
563 }
564
547 565 async fn set_channel_notifications(
548 566 &self,
549 567 channel_id: &str,
@@ -1019,6 +1037,38 @@ async fn refresh_sidebar_fills_chats_teams_and_channels() {
1019 1037 assert_eq!(sidebar.teams[0].channels[0].name, "General");
1020 1038 }
1021 1039
1040 #[tokio::test]
1041 async fn channel_unread_comes_from_the_read_horizon_and_opening_marks_it_read() {
1042 let fake = Arc::new(Fake::default());
1043 *fake.teams.lock().unwrap() =
1044 vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()];
1045 fake.read_states.lock().unwrap().push((
1046 CHANNEL.to_owned(),
1047 chatsvc::ReadHorizon {
1048 consumed_until_ms: 5,
1049 last_message_ms: 9,
1050 last_message_from: Some("8:orgid:user-ada".to_owned()),
1051 ..chatsvc::ReadHorizon::default()
1052 },
1053 ));
1054 let engine = engine_with(&fake, SyncConfig::default());
1055 engine.refresh_sidebar().await.unwrap();
1056 engine.refresh_sidebar().await.unwrap();
1057 let channel = engine.store().channel(CHANNEL).unwrap().unwrap();
1058 assert!(channel.unread);
1059 assert_eq!(channel.last_message_at, DateTime::from_timestamp_millis(9));
1060
1061 engine.mark_read(CHANNEL).await.unwrap();
1062
1063 assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);
1064 let call = fake.calls().last().unwrap().clone();
1065 assert!(
1066 call.starts_with(&format!("read horizon {CHANNEL} 9;")),
1067 "{call}"
1068 );
1069 assert!(call.ends_with(";0"), "{call}");
1070 }
1071
1022 1072 #[tokio::test]
1023 1073 async fn refresh_sidebar_marks_muted_chats_and_keeps_flags_when_the_lookup_fails() {
1024 1074 let fake = Arc::new(Fake::default());
@@ -117,6 +117,7 @@ struct Fake {
117 invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,
117 invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,
118 muted_states: Mutex<Vec<(String, bool)>>,
118 muted_states: Mutex<Vec<(String, bool)>>,
119 hidden_states: Mutex<Vec<(String, bool)>>,
119 hidden_states: Mutex<Vec<(String, bool)>>,
120 read_states: Mutex<Vec<(String, chatsvc::ReadHorizon)>>,
120 chats_fail: Mutex<bool>,
121 chats_fail: Mutex<bool>,
121 muted_fails: Mutex<bool>,
122 muted_fails: Mutex<bool>,
122 link_pages: Mutex<Vec<chatsvc::MessageLinks>>,
123 link_pages: Mutex<Vec<chatsvc::MessageLinks>>,
@@ -525,6 +526,7 @@ impl Remote for Handle {
525 id,
526 id,
526 muted,
527 muted,
527 hidden: None,
528 hidden: None,
529 read: chatsvc::ReadHorizon::default(),
528 })
530 })
529 .collect();
531 .collect();
530 states.extend(
532 states.extend(
@@ -534,6 +536,17 @@ impl Remote for Handle {
534 id,
536 id,
535 muted: false,
537 muted: false,
536 hidden: Some(hidden),
538 hidden: Some(hidden),
539 read: chatsvc::ReadHorizon::default(),
540 }),
541 );
542 let read = self.read_states.lock().unwrap().clone();
543 states.extend(
544 read.into_iter()
545 .map(|(id, read)| chatsvc::ConversationState {
546 id,
547 muted: false,
548 hidden: None,
549 read,
537 }),
550 }),
538 );
551 );
539 Ok(states)
552 Ok(states)
@@ -544,6 +557,11 @@ impl Remote for Handle {
544 Ok(())
557 Ok(())
545 }
558 }
546
559
560 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
561 self.record(format!("read horizon {conversation_id} {horizon}"));
562 Ok(())
563 }
564
547 async fn set_channel_notifications(
565 async fn set_channel_notifications(
548 &self,
566 &self,
549 channel_id: &str,
567 channel_id: &str,
@@ -1019,6 +1037,38 @@ async fn refresh_sidebar_fills_chats_teams_and_channels() {
1019 assert_eq!(sidebar.teams[0].channels[0].name, "General");
1037 assert_eq!(sidebar.teams[0].channels[0].name, "General");
1020}
1038}
1021
1039
1040#[tokio::test]
1041async fn channel_unread_comes_from_the_read_horizon_and_opening_marks_it_read() {
1042 let fake = Arc::new(Fake::default());
1043 *fake.teams.lock().unwrap() =
1044 vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()];
1045 fake.read_states.lock().unwrap().push((
1046 CHANNEL.to_owned(),
1047 chatsvc::ReadHorizon {
1048 consumed_until_ms: 5,
1049 last_message_ms: 9,
1050 last_message_from: Some("8:orgid:user-ada".to_owned()),
1051 ..chatsvc::ReadHorizon::default()
1052 },
1053 ));
1054 let engine = engine_with(&fake, SyncConfig::default());
1055 engine.refresh_sidebar().await.unwrap();
1056 engine.refresh_sidebar().await.unwrap();
1057 let channel = engine.store().channel(CHANNEL).unwrap().unwrap();
1058 assert!(channel.unread);
1059 assert_eq!(channel.last_message_at, DateTime::from_timestamp_millis(9));
1060
1061 engine.mark_read(CHANNEL).await.unwrap();
1062
1063 assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);
1064 let call = fake.calls().last().unwrap().clone();
1065 assert!(
1066 call.starts_with(&format!("read horizon {CHANNEL} 9;")),
1067 "{call}"
1068 );
1069 assert!(call.ends_with(";0"), "{call}");
1070}
1071
1022#[tokio::test]
1072#[tokio::test]
1023async fn refresh_sidebar_marks_muted_chats_and_keeps_flags_when_the_lookup_fails() {
1073async fn refresh_sidebar_marks_muted_chats_and_keeps_flags_when_the_lookup_fails() {
1024 let fake = Arc::new(Fake::default());
1074 let fake = Arc::new(Fake::default());
crates/store/src/teams.rs +32 −2
@@ -1,3 +1,4 @@
1 use chrono::{DateTime, Utc};
1 2 use rusqlite::{OptionalExtension, Row, params};
2 3
3 4 use crate::error::Result;
@@ -31,8 +32,7 @@ impl Store {
31 32 VALUES (?1, ?2, ?3, ?4, ?5, ?6)
32 33 ON CONFLICT (id) DO UPDATE SET
33 34 team_id = excluded.team_id, name = excluded.name, membership_type = excluded.membership_type,
34 last_message_at = COALESCE(excluded.last_message_at, channels.last_message_at),
35 unread = excluded.unread",
35 last_message_at = COALESCE(excluded.last_message_at, channels.last_message_at)",
36 36 )?;
37 37 for channel in channels {
38 38 upsert.execute(params![
@@ -48,6 +48,36 @@ impl Store {
48 48 Ok(transaction.commit()?)
49 49 }
50 50
51 /// Read state comes from chatsvc only; channel metadata refreshes leave it alone.
52 pub fn apply_channel_read_states(
53 &self,
54 states: &[(String, bool, Option<DateTime<Utc>>)],
55 ) -> Result<()> {
56 let mut connection = self.lock()?;
57 let transaction = connection.transaction()?;
58 {
59 let mut update = transaction.prepare_cached(
60 "UPDATE channels SET unread = ?2,
61 last_message_at = COALESCE(?3, last_message_at)
62 WHERE id = ?1",
63 )?;
64 for (channel_id, unread, last_message_at) in states {
65 update.execute(params![
66 channel_id,
67 unread,
68 optional_to_millis(*last_message_at)
69 ])?;
70 }
71 }
72 Ok(transaction.commit()?)
73 }
74
75 pub fn mark_channel_read(&self, channel_id: &str) -> Result<()> {
76 self.lock()?
77 .execute("UPDATE channels SET unread = 0 WHERE id = ?1", [channel_id])?;
78 Ok(())
79 }
80
51 81 pub fn remove_teams_except(&self, kept_team_ids: &[String]) -> Result<usize> {
52 82 let mut connection = self.lock()?;
53 83 let transaction = connection.transaction()?;
@@ -1,3 +1,4 @@
1use chrono::{DateTime, Utc};
1use rusqlite::{OptionalExtension, Row, params};
2use rusqlite::{OptionalExtension, Row, params};
2
3
3use crate::error::Result;
4use crate::error::Result;
@@ -31,8 +32,7 @@ impl Store {
31 VALUES (?1, ?2, ?3, ?4, ?5, ?6)
32 VALUES (?1, ?2, ?3, ?4, ?5, ?6)
32 ON CONFLICT (id) DO UPDATE SET
33 ON CONFLICT (id) DO UPDATE SET
33 team_id = excluded.team_id, name = excluded.name, membership_type = excluded.membership_type,
34 team_id = excluded.team_id, name = excluded.name, membership_type = excluded.membership_type,
34 last_message_at = COALESCE(excluded.last_message_at, channels.last_message_at),
35 last_message_at = COALESCE(excluded.last_message_at, channels.last_message_at)",
35 unread = excluded.unread",
36 )?;
36 )?;
37 for channel in channels {
37 for channel in channels {
38 upsert.execute(params![
38 upsert.execute(params![
@@ -48,6 +48,36 @@ impl Store {
48 Ok(transaction.commit()?)
48 Ok(transaction.commit()?)
49 }
49 }
50
50
51 /// Read state comes from chatsvc only; channel metadata refreshes leave it alone.
52 pub fn apply_channel_read_states(
53 &self,
54 states: &[(String, bool, Option<DateTime<Utc>>)],
55 ) -> Result<()> {
56 let mut connection = self.lock()?;
57 let transaction = connection.transaction()?;
58 {
59 let mut update = transaction.prepare_cached(
60 "UPDATE channels SET unread = ?2,
61 last_message_at = COALESCE(?3, last_message_at)
62 WHERE id = ?1",
63 )?;
64 for (channel_id, unread, last_message_at) in states {
65 update.execute(params![
66 channel_id,
67 unread,
68 optional_to_millis(*last_message_at)
69 ])?;
70 }
71 }
72 Ok(transaction.commit()?)
73 }
74
75 pub fn mark_channel_read(&self, channel_id: &str) -> Result<()> {
76 self.lock()?
77 .execute("UPDATE channels SET unread = 0 WHERE id = ?1", [channel_id])?;
78 Ok(())
79 }
80
51 pub fn remove_teams_except(&self, kept_team_ids: &[String]) -> Result<usize> {
81 pub fn remove_teams_except(&self, kept_team_ids: &[String]) -> Result<usize> {
52 let mut connection = self.lock()?;
82 let mut connection = self.lock()?;
53 let transaction = connection.transaction()?;
83 let transaction = connection.transaction()?;
crates/store/tests/store.rs +38 −0
@@ -427,6 +427,44 @@ fn channel_upsert_keeps_known_last_message_time() {
427 427 );
428 428 }
429 429
430 #[test]
431 fn channel_read_state_survives_a_metadata_refresh() {
432 let store = Store::open_in_memory().unwrap();
433 store
434 .upsert_teams(&[TeamRecord {
435 id: "t1".to_owned(),
436 name: "A".to_owned(),
437 }])
438 .unwrap();
439 let channel = ChannelRecord {
440 id: "c1".to_owned(),
441 team_id: "t1".to_owned(),
442 name: "General".to_owned(),
443 membership_type: None,
444 last_message_at: None,
445 unread: false,
446 };
447 store
448 .upsert_channels(std::slice::from_ref(&channel))
449 .unwrap();
450 store
451 .apply_channel_read_states(&[
452 ("c1".to_owned(), true, Some(at(9))),
453 ("unknown".to_owned(), true, None),
454 ])
455 .unwrap();
456 store
457 .upsert_channels(std::slice::from_ref(&channel))
458 .unwrap();
459 let stored = store.channel("c1").unwrap().unwrap();
460 assert!(stored.unread);
461 assert_eq!(stored.last_message_at, Some(at(9)));
462 assert!(store.channel("unknown").unwrap().is_none());
463
464 store.mark_channel_read("c1").unwrap();
465 assert!(!store.channel("c1").unwrap().unwrap().unread);
466 }
467
430 468 #[test]
431 469 fn pruning_removes_departed_teams_and_channels() {
432 470 let store = Store::open_in_memory().unwrap();
@@ -427,6 +427,44 @@ fn channel_upsert_keeps_known_last_message_time() {
427 );
427 );
428}
428}
429
429
430#[test]
431fn channel_read_state_survives_a_metadata_refresh() {
432 let store = Store::open_in_memory().unwrap();
433 store
434 .upsert_teams(&[TeamRecord {
435 id: "t1".to_owned(),
436 name: "A".to_owned(),
437 }])
438 .unwrap();
439 let channel = ChannelRecord {
440 id: "c1".to_owned(),
441 team_id: "t1".to_owned(),
442 name: "General".to_owned(),
443 membership_type: None,
444 last_message_at: None,
445 unread: false,
446 };
447 store
448 .upsert_channels(std::slice::from_ref(&channel))
449 .unwrap();
450 store
451 .apply_channel_read_states(&[
452 ("c1".to_owned(), true, Some(at(9))),
453 ("unknown".to_owned(), true, None),
454 ])
455 .unwrap();
456 store
457 .upsert_channels(std::slice::from_ref(&channel))
458 .unwrap();
459 let stored = store.channel("c1").unwrap().unwrap();
460 assert!(stored.unread);
461 assert_eq!(stored.last_message_at, Some(at(9)));
462 assert!(store.channel("unknown").unwrap().is_none());
463
464 store.mark_channel_read("c1").unwrap();
465 assert!(!store.channel("c1").unwrap().unwrap().unread);
466}
467
430#[test]
468#[test]
431fn pruning_removes_departed_teams_and_channels() {
469fn pruning_removes_departed_teams_and_channels() {
432 let store = Store::open_in_memory().unwrap();
470 let store = Store::open_in_memory().unwrap();