BlueGit

ict rusty-teams

fix(notes): own avatar, Hide, sticky Mark as unread, placeholder and empty state for the notes chat

- empty state "This is your space" with Teams strings and own avatar (Teams enableEmptySelfChatAvatar variant; prod default is an illustration)
- start row avatar uses the member name, own initials in the notes chat
- Mark as unread on 48:notes writes the chatsvc consumptionHorizonBookmark like Teams; Mark as read clears it (0;now;0)
- Hide in the notes row menu: chatsvc unpinnedTime + historyHiddenTime like Teams setChatVisibility; Undo clears both; hidden until a newer note
- notes chat missing from the chatsvc listing shows a placeholder "<name> (You)" like Teams' self chat lie
- deviation: hidden history before historyHiddenTime still shows after a new note (no "Show hidden chat history")
- deviation: bookmark carries the message id, Teams the clientmessageid

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

metis Daniel Däschle · pushed by metis

Authored 2026-11-04 · 3 weeks ago

Hash
b68bc7963c75189d2a3df1ad2c29f00413626239
Parent
85b65c2b
12 files changed +413 −38
crates/app-state/src/rows.rs +2 −0
@@ -178,6 +178,8 @@ pub struct MessageRow {
178 178 pub struct StartInfo {
179 179 pub title: String,
180 180 pub user_id: Option<String>,
181 pub avatar_name: String,
182 pub notes: bool,
181 183 }
182 184
183 185 pub const START_KEY: &str = "conversation-start";
@@ -178,6 +178,8 @@ pub struct MessageRow {
178pub struct StartInfo {
178pub struct StartInfo {
179 pub title: String,
179 pub title: String,
180 pub user_id: Option<String>,
180 pub user_id: Option<String>,
181 pub avatar_name: String,
182 pub notes: bool,
181}
183}
182
184
183pub const START_KEY: &str = "conversation-start";
185pub const START_KEY: &str = "conversation-start";
crates/app/src/views/conversation.rs +34 −14
@@ -18,7 +18,7 @@ use gpui_kit::prelude::FluentBuilder as _;
18 18 use gpui_kit::*;
19 19 use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget, is_bot_id};
20 20 use teams_core::{
21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,
21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, is_notes_chat, without_islands,
22 22 };
23 23
24 24 mod channel_details;
@@ -35,6 +35,7 @@ pub use forward_select::{
35 35 FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG, FORWARD_FOOTER_TAG,
36 36 };
37 37 mod jump;
38 mod notes_space;
38 39 mod pins;
39 40 mod proposal;
40 41 mod recap;
@@ -1477,23 +1478,37 @@ impl ConversationView {
1477 1478 fn start_info(&self, cx: &App) -> Option<StartInfo> {
1478 1479 let current = self.current.as_ref()?;
1479 1480 let app = self.app.read(cx);
1480 let user_id = match &current.selection {
1481 Selection::Chat(chat_id) => app
1482 .sidebar
1483 .chats
1484 .iter()
1485 .find(|chat| &chat.id == chat_id)
1486 .filter(|chat| is_one_on_one(chat))
1487 .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next())
1488 .and_then(|(user_id, _)| user_id),
1489 Selection::Channel(_) => None,
1481 let (user_id, member_name, notes) = match &current.selection {
1482 Selection::Chat(chat_id) => {
1483 let member = app
1484 .sidebar
1485 .chats
1486 .iter()
1487 .find(|chat| &chat.id == chat_id)
1488 .filter(|chat| is_one_on_one(chat))
1489 .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next());
1490 let (user_id, name) = member.unzip();
1491 (user_id.flatten(), name, is_notes_chat(chat_id))
1492 }
1493 Selection::Channel(_) => (None, None, false),
1490 1494 };
1491 1495 Some(StartInfo {
1492 1496 title: current.title.clone(),
1493 1497 user_id,
1498 avatar_name: member_name
1499 .filter(|name| !name.is_empty())
1500 .unwrap_or_else(|| current.title.clone()),
1501 notes,
1494 1502 })
1495 1503 }
1496 1504
1505 fn notes_space(&self) -> Option<StartInfo> {
1506 match self.rows.borrow().as_slice() {
1507 [Row::Start(start)] if start.notes => Some(start.clone()),
1508 _ => None,
1509 }
1510 }
1511
1497 1512 fn watch_feed_scroll(&mut self, cx: &mut Context<Self>) {
1498 1513 let scroller_id = self.scroller.entity_id();
1499 1514 if self
@@ -3701,9 +3716,12 @@ impl Render for ConversationView {
3701 3716 },
3702 3717 56.,
3703 3718 ),
3704 user_id => {
3705 person_avatar(&state.directory, user_id, &start.title, 56.)
3706 }
3719 user_id => person_avatar(
3720 &state.directory,
3721 user_id,
3722 &start.avatar_name,
3723 56.,
3724 ),
3707 3725 })
3708 3726 .child(
3709 3727 div()
@@ -3806,6 +3824,8 @@ impl Render for ConversationView {
3806 3824 self.render_shared(cx)
3807 3825 } else if self.recap_active() {
3808 3826 self.render_recap(cx)
3827 } else if let Some(start) = self.notes_space() {
3828 notes_space::render_notes_space(&self.app.read(cx).directory, &start)
3809 3829 } else if empty_channel {
3810 3830 div()
3811 3831 .size_full()
@@ -18,7 +18,7 @@ use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::*;
18use gpui_kit::*;
19use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget, is_bot_id};
19use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget, is_bot_id};
20use teams_core::{
20use teams_core::{
21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,
21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, is_notes_chat, without_islands,
22};
22};
23
23
24mod channel_details;
24mod channel_details;
@@ -35,6 +35,7 @@ pub use forward_select::{
35 FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG, FORWARD_FOOTER_TAG,
35 FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG, FORWARD_FOOTER_TAG,
36};
36};
37mod jump;
37mod jump;
38mod notes_space;
38mod pins;
39mod pins;
39mod proposal;
40mod proposal;
40mod recap;
41mod recap;
@@ -1477,23 +1478,37 @@ impl ConversationView {
1477 fn start_info(&self, cx: &App) -> Option<StartInfo> {
1478 fn start_info(&self, cx: &App) -> Option<StartInfo> {
1478 let current = self.current.as_ref()?;
1479 let current = self.current.as_ref()?;
1479 let app = self.app.read(cx);
1480 let app = self.app.read(cx);
1480 let user_id = match &current.selection {
1481 let (user_id, member_name, notes) = match &current.selection {
1481 Selection::Chat(chat_id) => app
1482 Selection::Chat(chat_id) => {
1482 .sidebar
1483 let member = app
1483 .chats
1484 .sidebar
1484 .iter()
1485 .chats
1485 .find(|chat| &chat.id == chat_id)
1486 .iter()
1486 .filter(|chat| is_one_on_one(chat))
1487 .find(|chat| &chat.id == chat_id)
1487 .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next())
1488 .filter(|chat| is_one_on_one(chat))
1488 .and_then(|(user_id, _)| user_id),
1489 .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next());
1489 Selection::Channel(_) => None,
1490 let (user_id, name) = member.unzip();
1491 (user_id.flatten(), name, is_notes_chat(chat_id))
1492 }
1493 Selection::Channel(_) => (None, None, false),
1490 };
1494 };
1491 Some(StartInfo {
1495 Some(StartInfo {
1492 title: current.title.clone(),
1496 title: current.title.clone(),
1493 user_id,
1497 user_id,
1498 avatar_name: member_name
1499 .filter(|name| !name.is_empty())
1500 .unwrap_or_else(|| current.title.clone()),
1501 notes,
1494 })
1502 })
1495 }
1503 }
1496
1504
1505 fn notes_space(&self) -> Option<StartInfo> {
1506 match self.rows.borrow().as_slice() {
1507 [Row::Start(start)] if start.notes => Some(start.clone()),
1508 _ => None,
1509 }
1510 }
1511
1497 fn watch_feed_scroll(&mut self, cx: &mut Context<Self>) {
1512 fn watch_feed_scroll(&mut self, cx: &mut Context<Self>) {
1498 let scroller_id = self.scroller.entity_id();
1513 let scroller_id = self.scroller.entity_id();
1499 if self
1514 if self
@@ -3701,9 +3716,12 @@ impl Render for ConversationView {
3701 },
3716 },
3702 56.,
3717 56.,
3703 ),
3718 ),
3704 user_id => {
3719 user_id => person_avatar(
3705 person_avatar(&state.directory, user_id, &start.title, 56.)
3720 &state.directory,
3706 }
3721 user_id,
3722 &start.avatar_name,
3723 56.,
3724 ),
3707 })
3725 })
3708 .child(
3726 .child(
3709 div()
3727 div()
@@ -3806,6 +3824,8 @@ impl Render for ConversationView {
3806 self.render_shared(cx)
3824 self.render_shared(cx)
3807 } else if self.recap_active() {
3825 } else if self.recap_active() {
3808 self.render_recap(cx)
3826 self.render_recap(cx)
3827 } else if let Some(start) = self.notes_space() {
3828 notes_space::render_notes_space(&self.app.read(cx).directory, &start)
3809 } else if empty_channel {
3829 } else if empty_channel {
3810 div()
3830 div()
3811 .size_full()
3831 .size_full()
crates/app/src/views/conversation/notes_space.rs added +48 −0
@@ -0,0 +1,48 @@
1 use gpui_kit::component::v_flex;
2 use gpui_kit::*;
3
4 use crate::data::Directory;
5 use crate::rows::StartInfo;
6 use crate::theme;
7 use crate::views::avatar::person_avatar;
8
9 const NOTES_SPACE_TITLE: &str = "This is your space";
10 const NOTES_SPACE_TEXT: &str = "This chat is just for you...with you. Use it for drafts, send files to yourself, or get to know chat features a little better.";
11 const NOTES_SPACE_AVATAR_SIZE: f32 = 72.;
12 const NOTES_SPACE_TEXT_WIDTH: f32 = 360.;
13
14 pub(super) fn render_notes_space(directory: &Directory, start: &StartInfo) -> AnyElement {
15 v_flex()
16 .size_full()
17 .items_center()
18 .justify_center()
19 .gap(px(12.))
20 .px(px(16.))
21 .child(person_avatar(
22 directory,
23 start.user_id.as_deref(),
24 &start.avatar_name,
25 NOTES_SPACE_AVATAR_SIZE,
26 ))
27 .child(
28 v_flex()
29 .items_center()
30 .gap(px(4.))
31 .max_w(px(NOTES_SPACE_TEXT_WIDTH))
32 .child(
33 div()
34 .text_size(px(16.))
35 .font_weight(FontWeight::BOLD)
36 .text_color(theme::text())
37 .child(NOTES_SPACE_TITLE),
38 )
39 .child(
40 div()
41 .text_center()
42 .text_size(px(13.))
43 .text_color(theme::text_muted())
44 .child(NOTES_SPACE_TEXT),
45 ),
46 )
47 .into_any_element()
48 }
@@ -0,0 +1,48 @@
1use gpui_kit::component::v_flex;
2use gpui_kit::*;
3
4use crate::data::Directory;
5use crate::rows::StartInfo;
6use crate::theme;
7use crate::views::avatar::person_avatar;
8
9const NOTES_SPACE_TITLE: &str = "This is your space";
10const NOTES_SPACE_TEXT: &str = "This chat is just for you...with you. Use it for drafts, send files to yourself, or get to know chat features a little better.";
11const NOTES_SPACE_AVATAR_SIZE: f32 = 72.;
12const NOTES_SPACE_TEXT_WIDTH: f32 = 360.;
13
14pub(super) fn render_notes_space(directory: &Directory, start: &StartInfo) -> AnyElement {
15 v_flex()
16 .size_full()
17 .items_center()
18 .justify_center()
19 .gap(px(12.))
20 .px(px(16.))
21 .child(person_avatar(
22 directory,
23 start.user_id.as_deref(),
24 &start.avatar_name,
25 NOTES_SPACE_AVATAR_SIZE,
26 ))
27 .child(
28 v_flex()
29 .items_center()
30 .gap(px(4.))
31 .max_w(px(NOTES_SPACE_TEXT_WIDTH))
32 .child(
33 div()
34 .text_size(px(16.))
35 .font_weight(FontWeight::BOLD)
36 .text_color(theme::text())
37 .child(NOTES_SPACE_TITLE),
38 )
39 .child(
40 div()
41 .text_center()
42 .text_size(px(13.))
43 .text_color(theme::text_muted())
44 .child(NOTES_SPACE_TEXT),
45 ),
46 )
47 .into_any_element()
48}
crates/app/src/views/sidebar.rs +10 −8
@@ -218,8 +218,16 @@ fn chat_menu(
218 218 });
219 219 }),
220 220 );
221 let hide_item = PopupMenuItem::new("Hide")
222 .icon(menu_icon(IconName::EyeOff))
223 .on_click(move |_, _, cx| {
224 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
225 });
221 226 if notes {
222 return popup.item(pop_out_item(context, target));
227 return popup
228 .item(pop_out_item(context, target))
229 .separator()
230 .item(hide_item);
223 231 }
224 232 popup = popup.item(
225 233 PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
@@ -235,13 +243,7 @@ fn chat_menu(
235 243 popup = chat_notifications_submenu(popup, window, cx, context, target)
236 244 .item(pop_out_item(context, target))
237 245 .separator()
238 .item(
239 PopupMenuItem::new("Hide")
240 .icon(menu_icon(IconName::EyeOff))
241 .on_click(move |_, _, cx| {
242 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
243 }),
244 );
246 .item(hide_item);
245 247 if !target.is_group {
246 248 let remove_state = context.state.clone();
247 249 let remove_id = target.id.clone();
@@ -218,8 +218,16 @@ fn chat_menu(
218 });
218 });
219 }),
219 }),
220 );
220 );
221 let hide_item = PopupMenuItem::new("Hide")
222 .icon(menu_icon(IconName::EyeOff))
223 .on_click(move |_, _, cx| {
224 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
225 });
221 if notes {
226 if notes {
222 return popup.item(pop_out_item(context, target));
227 return popup
228 .item(pop_out_item(context, target))
229 .separator()
230 .item(hide_item);
223 }
231 }
224 popup = popup.item(
232 popup = popup.item(
225 PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
233 PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
@@ -235,13 +243,7 @@ fn chat_menu(
235 popup = chat_notifications_submenu(popup, window, cx, context, target)
243 popup = chat_notifications_submenu(popup, window, cx, context, target)
236 .item(pop_out_item(context, target))
244 .item(pop_out_item(context, target))
237 .separator()
245 .separator()
238 .item(
246 .item(hide_item);
239 PopupMenuItem::new("Hide")
240 .icon(menu_icon(IconName::EyeOff))
241 .on_click(move |_, _, cx| {
242 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
243 }),
244 );
245 if !target.is_group {
247 if !target.is_group {
246 let remove_state = context.state.clone();
248 let remove_state = context.state.clone();
247 let remove_id = target.id.clone();
249 let remove_id = target.id.clone();
crates/chatsvc/src/conversations.rs +118 −6
@@ -14,6 +14,8 @@ const PAGE_SIZE: usize = 200;
14 14 const MAX_PAGES: usize = 100;
15 15 const ALERTS_OFF: &str = "false";
16 16 const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
17 const HIDDEN_TIME_PROPERTY: &str = "unpinnedTime";
18 const HISTORY_HIDDEN_TIME_PROPERTY: &str = "historyHiddenTime";
17 19
18 20 #[derive(Debug, Clone, PartialEq, Eq, Default)]
19 21 pub struct ConversationState {
@@ -22,6 +24,7 @@ pub struct ConversationState {
22 24 pub hidden: Option<bool>,
23 25 pub read: ReadHorizon,
24 26 pub history_cleared_ms: Option<i64>,
27 pub hidden_at_ms: Option<i64>,
25 28 pub notification_settings: Option<String>,
26 29 }
27 30
@@ -135,16 +138,42 @@ impl<T: MessageTransport> Conversations<T> {
135 138 }
136 139
137 140 pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
141 self.put_property(conversation_id, read_horizon::PROPERTY_NAME, json!(horizon))
142 .await
143 }
144
145 /// Teams' "Mark as unread": a bookmark marks the conversation unread even when the last message is my own.
146 pub async fn set_read_bookmark(&self, conversation_id: &str, bookmark: &str) -> Result<()> {
147 self.put_property(
148 conversation_id,
149 read_horizon::BOOKMARK_PROPERTY_NAME,
150 json!(bookmark),
151 )
152 .await
153 }
154
155 /// Teams' chat "Hide" (`setChatVisibility`): hidden until a newer message; `None` shows it again.
156 pub async fn set_hidden_at(&self, conversation_id: &str, hidden_at_ms: Option<i64>) -> Result<()> {
157 self.put_property(conversation_id, HIDDEN_TIME_PROPERTY, json!(hidden_at_ms))
158 .await?;
159 let history_hidden = hidden_at_ms.map(|millis| millis.to_string());
160 self.put_property(
161 conversation_id,
162 HISTORY_HIDDEN_TIME_PROPERTY,
163 json!(history_hidden),
164 )
165 .await
166 }
167
168 async fn put_property(&self, conversation_id: &str, name: &str, value: Value) -> Result<()> {
138 169 let url = format!(
139 "{}/{}/properties?name={}",
170 "{}/{}/properties?name={name}",
140 171 self.base_url,
141 encode(conversation_id),
142 read_horizon::PROPERTY_NAME
172 encode(conversation_id)
143 173 );
144 let body = json!({ read_horizon::PROPERTY_NAME: horizon });
145 174 let answer = self
146 175 .transport
147 .send(Request::with_body(Method::Put, url, body))
176 .send(Request::with_body(Method::Put, url, json!({ name: value })))
148 177 .await?;
149 178 ensure_success(&answer)
150 179 }
@@ -184,7 +213,18 @@ pub fn clear_history_request(
184 213 }
185 214
186 215 fn history_cleared_ms(conversation: &Value) -> Option<i64> {
187 let value = &conversation["properties"][CLEAR_HISTORY_PROPERTY];
216 millis_property(conversation, CLEAR_HISTORY_PROPERTY)
217 }
218
219 fn hidden_at_ms(conversation: &Value) -> Option<i64> {
220 [HIDDEN_TIME_PROPERTY, HISTORY_HIDDEN_TIME_PROPERTY]
221 .into_iter()
222 .filter_map(|name| millis_property(conversation, name))
223 .max()
224 }
225
226 fn millis_property(conversation: &Value, name: &str) -> Option<i64> {
227 let value = &conversation["properties"][name];
188 228 value
189 229 .as_i64()
190 230 .or_else(|| value.as_str()?.parse().ok())
@@ -245,6 +285,7 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
245 285 .as_str()
246 286 .map(str::to_owned),
247 287 history_cleared_ms: history_cleared_ms(conversation),
288 hidden_at_ms: hidden_at_ms(conversation),
248 289 })
249 290 })
250 291 .collect())
@@ -525,6 +566,77 @@ mod tests {
525 566 );
526 567 }
527 568
569 #[tokio::test]
570 async fn set_read_bookmark_puts_the_bookmark_property() {
571 let transport = canned(vec![(200, Value::Null)]);
572 Conversations::with_transport(&transport, "emea")
573 .set_read_bookmark("48:notes", "8;10;9")
574 .await
575 .unwrap();
576 let requests = transport.requests.lock().unwrap();
577 assert_eq!(requests[0].method, Method::Put);
578 assert_eq!(
579 requests[0].url,
580 format!("{BASE}/48%3Anotes/properties?name=consumptionHorizonBookmark")
581 );
582 assert_eq!(
583 requests[0].body,
584 Some(json!({"consumptionHorizonBookmark": "8;10;9"}))
585 );
586 }
587
588 #[tokio::test]
589 async fn hide_puts_the_hidden_time_as_number_and_the_history_time_as_text() {
590 let transport = canned(vec![(200, Value::Null); 4]);
591 let conversations = Conversations::with_transport(&transport, "emea");
592 conversations.set_hidden_at("48:notes", Some(42)).await.unwrap();
593 conversations.set_hidden_at("48:notes", None).await.unwrap();
594 let requests = transport.requests.lock().unwrap();
595 let writes: Vec<(String, Option<Value>)> = requests
596 .iter()
597 .map(|request| (request.url.replace(BASE, ""), request.body.clone()))
598 .collect();
599 assert_eq!(
600 writes,
601 [
602 (
603 "/48%3Anotes/properties?name=unpinnedTime".to_owned(),
604 Some(json!({"unpinnedTime": 42}))
605 ),
606 (
607 "/48%3Anotes/properties?name=historyHiddenTime".to_owned(),
608 Some(json!({"historyHiddenTime": "42"}))
609 ),
610 (
611 "/48%3Anotes/properties?name=unpinnedTime".to_owned(),
612 Some(json!({"unpinnedTime": null}))
613 ),
614 (
615 "/48%3Anotes/properties?name=historyHiddenTime".to_owned(),
616 Some(json!({"historyHiddenTime": null}))
617 ),
618 ]
619 );
620 }
621
622 #[tokio::test]
623 async fn states_carry_the_newest_hidden_time() {
624 let transport = canned(vec![(
625 200,
626 json!({"conversations": [
627 {"id": "48:notes", "properties": {"unpinnedTime": 30, "historyHiddenTime": "40"}},
628 {"id": "19:b", "properties": {"unpinnedTime": "50"}},
629 {"id": "19:c", "properties": {}},
630 ]}),
631 )]);
632 let states = Conversations::with_transport(&transport, "emea")
633 .conversation_states()
634 .await
635 .unwrap();
636 let hidden: Vec<Option<i64>> = states.iter().map(|state| state.hidden_at_ms).collect();
637 assert_eq!(hidden, [Some(40), Some(50), None]);
638 }
639
528 640 #[tokio::test]
529 641 async fn chat_notifications_put_the_settings_then_alerts() {
530 642 let transport = canned(vec![(200, Value::Null), (200, Value::Null)]);
@@ -14,6 +14,8 @@ const PAGE_SIZE: usize = 200;
14const MAX_PAGES: usize = 100;
14const MAX_PAGES: usize = 100;
15const ALERTS_OFF: &str = "false";
15const ALERTS_OFF: &str = "false";
16const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
16const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
17const HIDDEN_TIME_PROPERTY: &str = "unpinnedTime";
18const HISTORY_HIDDEN_TIME_PROPERTY: &str = "historyHiddenTime";
17
19
18#[derive(Debug, Clone, PartialEq, Eq, Default)]
20#[derive(Debug, Clone, PartialEq, Eq, Default)]
19pub struct ConversationState {
21pub struct ConversationState {
@@ -22,6 +24,7 @@ pub struct ConversationState {
22 pub hidden: Option<bool>,
24 pub hidden: Option<bool>,
23 pub read: ReadHorizon,
25 pub read: ReadHorizon,
24 pub history_cleared_ms: Option<i64>,
26 pub history_cleared_ms: Option<i64>,
27 pub hidden_at_ms: Option<i64>,
25 pub notification_settings: Option<String>,
28 pub notification_settings: Option<String>,
26}
29}
27
30
@@ -135,16 +138,42 @@ impl<T: MessageTransport> Conversations<T> {
135 }
138 }
136
139
137 pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
140 pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
141 self.put_property(conversation_id, read_horizon::PROPERTY_NAME, json!(horizon))
142 .await
143 }
144
145 /// Teams' "Mark as unread": a bookmark marks the conversation unread even when the last message is my own.
146 pub async fn set_read_bookmark(&self, conversation_id: &str, bookmark: &str) -> Result<()> {
147 self.put_property(
148 conversation_id,
149 read_horizon::BOOKMARK_PROPERTY_NAME,
150 json!(bookmark),
151 )
152 .await
153 }
154
155 /// Teams' chat "Hide" (`setChatVisibility`): hidden until a newer message; `None` shows it again.
156 pub async fn set_hidden_at(&self, conversation_id: &str, hidden_at_ms: Option<i64>) -> Result<()> {
157 self.put_property(conversation_id, HIDDEN_TIME_PROPERTY, json!(hidden_at_ms))
158 .await?;
159 let history_hidden = hidden_at_ms.map(|millis| millis.to_string());
160 self.put_property(
161 conversation_id,
162 HISTORY_HIDDEN_TIME_PROPERTY,
163 json!(history_hidden),
164 )
165 .await
166 }
167
168 async fn put_property(&self, conversation_id: &str, name: &str, value: Value) -> Result<()> {
138 let url = format!(
169 let url = format!(
139 "{}/{}/properties?name={}",
170 "{}/{}/properties?name={name}",
140 self.base_url,
171 self.base_url,
141 encode(conversation_id),
172 encode(conversation_id)
142 read_horizon::PROPERTY_NAME
143 );
173 );
144 let body = json!({ read_horizon::PROPERTY_NAME: horizon });
145 let answer = self
174 let answer = self
146 .transport
175 .transport
147 .send(Request::with_body(Method::Put, url, body))
176 .send(Request::with_body(Method::Put, url, json!({ name: value })))
148 .await?;
177 .await?;
149 ensure_success(&answer)
178 ensure_success(&answer)
150 }
179 }
@@ -184,7 +213,18 @@ pub fn clear_history_request(
184}
213}
185
214
186fn history_cleared_ms(conversation: &Value) -> Option<i64> {
215fn history_cleared_ms(conversation: &Value) -> Option<i64> {
187 let value = &conversation["properties"][CLEAR_HISTORY_PROPERTY];
216 millis_property(conversation, CLEAR_HISTORY_PROPERTY)
217}
218
219fn hidden_at_ms(conversation: &Value) -> Option<i64> {
220 [HIDDEN_TIME_PROPERTY, HISTORY_HIDDEN_TIME_PROPERTY]
221 .into_iter()
222 .filter_map(|name| millis_property(conversation, name))
223 .max()
224}
225
226fn millis_property(conversation: &Value, name: &str) -> Option<i64> {
227 let value = &conversation["properties"][name];
188 value
228 value
189 .as_i64()
229 .as_i64()
190 .or_else(|| value.as_str()?.parse().ok())
230 .or_else(|| value.as_str()?.parse().ok())
@@ -245,6 +285,7 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
245 .as_str()
285 .as_str()
246 .map(str::to_owned),
286 .map(str::to_owned),
247 history_cleared_ms: history_cleared_ms(conversation),
287 history_cleared_ms: history_cleared_ms(conversation),
288 hidden_at_ms: hidden_at_ms(conversation),
248 })
289 })
249 })
290 })
250 .collect())
291 .collect())
@@ -525,6 +566,77 @@ mod tests {
525 );
566 );
526 }
567 }
527
568
569 #[tokio::test]
570 async fn set_read_bookmark_puts_the_bookmark_property() {
571 let transport = canned(vec![(200, Value::Null)]);
572 Conversations::with_transport(&transport, "emea")
573 .set_read_bookmark("48:notes", "8;10;9")
574 .await
575 .unwrap();
576 let requests = transport.requests.lock().unwrap();
577 assert_eq!(requests[0].method, Method::Put);
578 assert_eq!(
579 requests[0].url,
580 format!("{BASE}/48%3Anotes/properties?name=consumptionHorizonBookmark")
581 );
582 assert_eq!(
583 requests[0].body,
584 Some(json!({"consumptionHorizonBookmark": "8;10;9"}))
585 );
586 }
587
588 #[tokio::test]
589 async fn hide_puts_the_hidden_time_as_number_and_the_history_time_as_text() {
590 let transport = canned(vec![(200, Value::Null); 4]);
591 let conversations = Conversations::with_transport(&transport, "emea");
592 conversations.set_hidden_at("48:notes", Some(42)).await.unwrap();
593 conversations.set_hidden_at("48:notes", None).await.unwrap();
594 let requests = transport.requests.lock().unwrap();
595 let writes: Vec<(String, Option<Value>)> = requests
596 .iter()
597 .map(|request| (request.url.replace(BASE, ""), request.body.clone()))
598 .collect();
599 assert_eq!(
600 writes,
601 [
602 (
603 "/48%3Anotes/properties?name=unpinnedTime".to_owned(),
604 Some(json!({"unpinnedTime": 42}))
605 ),
606 (
607 "/48%3Anotes/properties?name=historyHiddenTime".to_owned(),
608 Some(json!({"historyHiddenTime": "42"}))
609 ),
610 (
611 "/48%3Anotes/properties?name=unpinnedTime".to_owned(),
612 Some(json!({"unpinnedTime": null}))
613 ),
614 (
615 "/48%3Anotes/properties?name=historyHiddenTime".to_owned(),
616 Some(json!({"historyHiddenTime": null}))
617 ),
618 ]
619 );
620 }
621
622 #[tokio::test]
623 async fn states_carry_the_newest_hidden_time() {
624 let transport = canned(vec![(
625 200,
626 json!({"conversations": [
627 {"id": "48:notes", "properties": {"unpinnedTime": 30, "historyHiddenTime": "40"}},
628 {"id": "19:b", "properties": {"unpinnedTime": "50"}},
629 {"id": "19:c", "properties": {}},
630 ]}),
631 )]);
632 let states = Conversations::with_transport(&transport, "emea")
633 .conversation_states()
634 .await
635 .unwrap();
636 let hidden: Vec<Option<i64>> = states.iter().map(|state| state.hidden_at_ms).collect();
637 assert_eq!(hidden, [Some(40), Some(50), None]);
638 }
639
528 #[tokio::test]
640 #[tokio::test]
529 async fn chat_notifications_put_the_settings_then_alerts() {
641 async fn chat_notifications_put_the_settings_then_alerts() {
530 let transport = canned(vec![(200, Value::Null), (200, Value::Null)]);
642 let transport = canned(vec![(200, Value::Null), (200, Value::Null)]);
crates/chatsvc/src/read_horizon.rs +29 −0
@@ -2,6 +2,7 @@ use chrono::{DateTime, Utc};
2 2 use serde_json::Value;
3 3
4 4 pub const PROPERTY_NAME: &str = "consumptionhorizon";
5 pub const BOOKMARK_PROPERTY_NAME: &str = "consumptionHorizonBookmark";
5 6
6 7 /// Read state of one conversation as chatsvc lists it, judged like the Teams worker (`hasUnreadMessages`).
7 8 #[derive(Debug, Clone, PartialEq, Eq, Default)]
@@ -71,6 +72,20 @@ pub fn read_up_to(last_message_at: DateTime<Utc>, now: DateTime<Utc>) -> String
71 72 )
72 73 }
73 74
75 /// Teams' unread bookmark on a message: one millisecond before its arrival, now, its id.
76 pub fn bookmark_at(message_arrived_at: DateTime<Utc>, message_id: &str, now: DateTime<Utc>) -> String {
77 format!(
78 "{};{};{message_id}",
79 message_arrived_at.timestamp_millis() - 1,
80 now.timestamp_millis()
81 )
82 }
83
84 /// The value Teams writes to clear the bookmark when a conversation is read.
85 pub fn cleared_bookmark(now: DateTime<Utc>) -> String {
86 format!("0;{};0", now.timestamp_millis())
87 }
88
74 89 struct ParsedHorizon {
75 90 arrival_ms: i64,
76 91 timestamp_ms: i64,
@@ -237,4 +252,18 @@ mod tests {
237 252 let now = DateTime::from_timestamp_millis(1792190000000).unwrap();
238 253 assert_eq!(read_up_to(last, now), "1792182658901;1792190000000;0");
239 254 }
255
256 #[test]
257 fn own_note_marked_unread_by_bookmark_is_unread_until_the_bookmark_is_cleared() {
258 let arrived = DateTime::from_timestamp_millis(1792182658901).unwrap();
259 let now = DateTime::from_timestamp_millis(1792190000000).unwrap();
260 let bookmark = bookmark_at(arrived, "1792182658901", now);
261 assert_eq!(bookmark, "1792182658900;1792190000000;1792182658901");
262 let last = Some(("2026-10-16T21:10:58.901Z", ME));
263 let marked = conversation(Some("1792182658901;1;0"), Some(&bookmark), last);
264 assert!(unread(&marked));
265 let cleared = cleared_bookmark(now);
266 assert_eq!(cleared, "0;1792190000000;0");
267 assert!(!unread(&conversation(Some("1792182658901;1;0"), Some(&cleared), last)));
268 }
240 269 }
@@ -2,6 +2,7 @@ use chrono::{DateTime, Utc};
2use serde_json::Value;
2use serde_json::Value;
3
3
4pub const PROPERTY_NAME: &str = "consumptionhorizon";
4pub const PROPERTY_NAME: &str = "consumptionhorizon";
5pub const BOOKMARK_PROPERTY_NAME: &str = "consumptionHorizonBookmark";
5
6
6/// Read state of one conversation as chatsvc lists it, judged like the Teams worker (`hasUnreadMessages`).
7/// Read state of one conversation as chatsvc lists it, judged like the Teams worker (`hasUnreadMessages`).
7#[derive(Debug, Clone, PartialEq, Eq, Default)]
8#[derive(Debug, Clone, PartialEq, Eq, Default)]
@@ -71,6 +72,20 @@ pub fn read_up_to(last_message_at: DateTime<Utc>, now: DateTime<Utc>) -> String
71 )
72 )
72}
73}
73
74
75/// Teams' unread bookmark on a message: one millisecond before its arrival, now, its id.
76pub fn bookmark_at(message_arrived_at: DateTime<Utc>, message_id: &str, now: DateTime<Utc>) -> String {
77 format!(
78 "{};{};{message_id}",
79 message_arrived_at.timestamp_millis() - 1,
80 now.timestamp_millis()
81 )
82}
83
84/// The value Teams writes to clear the bookmark when a conversation is read.
85pub fn cleared_bookmark(now: DateTime<Utc>) -> String {
86 format!("0;{};0", now.timestamp_millis())
87}
88
74struct ParsedHorizon {
89struct ParsedHorizon {
75 arrival_ms: i64,
90 arrival_ms: i64,
76 timestamp_ms: i64,
91 timestamp_ms: i64,
@@ -237,4 +252,18 @@ mod tests {
237 let now = DateTime::from_timestamp_millis(1792190000000).unwrap();
252 let now = DateTime::from_timestamp_millis(1792190000000).unwrap();
238 assert_eq!(read_up_to(last, now), "1792182658901;1792190000000;0");
253 assert_eq!(read_up_to(last, now), "1792182658901;1792190000000;0");
239 }
254 }
255
256 #[test]
257 fn own_note_marked_unread_by_bookmark_is_unread_until_the_bookmark_is_cleared() {
258 let arrived = DateTime::from_timestamp_millis(1792182658901).unwrap();
259 let now = DateTime::from_timestamp_millis(1792190000000).unwrap();
260 let bookmark = bookmark_at(arrived, "1792182658901", now);
261 assert_eq!(bookmark, "1792182658900;1792190000000;1792182658901");
262 let last = Some(("2026-10-16T21:10:58.901Z", ME));
263 let marked = conversation(Some("1792182658901;1;0"), Some(&bookmark), last);
264 assert!(unread(&marked));
265 let cleared = cleared_bookmark(now);
266 assert_eq!(cleared, "0;1792190000000;0");
267 assert!(!unread(&conversation(Some("1792182658901;1;0"), Some(&cleared), last)));
268 }
240}
269}
crates/core/src/actions.rs +46 −7
@@ -1,4 +1,4 @@
1 use chatsvc::ConversationRef;
1 use chatsvc::{ConversationRef, read_horizon};
2 2 use chrono::{DateTime, Duration, Utc};
3 3 use graph::{
4 4 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
@@ -14,6 +14,7 @@ use crate::links::LinkPreview;
14 14 use crate::mapping::message_record;
15 15 use crate::markdown::markdown_to_html;
16 16 use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
17 use crate::notes_chat::is_notes_chat;
17 18 use crate::remote::Remote;
18 19 use crate::scheduled::NOTES_CHAT_ID;
19 20 use crate::teams_quote::{chatsvc_mention_html, quote_reply_properties, teams_quote};
@@ -399,7 +400,13 @@ impl<R: Remote> SyncEngine<R> {
399 400 self.remote
400 401 .mark_chat_read(conversation_id, &user_id, &tenant_id)
401 402 .await?;
402 self.store.mark_chat_read(conversation_id, Utc::now())?;
403 let now = Utc::now();
404 if is_notes_chat(conversation_id) {
405 self.remote
406 .set_read_bookmark(conversation_id, &read_horizon::cleared_bookmark(now))
407 .await?;
408 }
409 self.store.mark_chat_read(conversation_id, now)?;
403 410 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
404 411 Ok(())
405 412 }
@@ -451,16 +458,35 @@ impl<R: Remote> SyncEngine<R> {
451 458 message_created_at: DateTime<Utc>,
452 459 ) -> Result<()> {
453 460 let last_read_at = message_created_at - Duration::milliseconds(1);
454 let user_id = self.my_user_id().await?;
455 let tenant_id = self.my_tenant_id(chat_id).await?;
456 self.remote
457 .mark_chat_unread(chat_id, &user_id, &tenant_id, last_read_at)
458 .await?;
461 if is_notes_chat(chat_id) {
462 let bookmark = read_horizon::bookmark_at(
463 message_created_at,
464 &self.message_id_at(chat_id, message_created_at)?,
465 Utc::now(),
466 );
467 self.remote.set_read_bookmark(chat_id, &bookmark).await?;
468 } else {
469 let user_id = self.my_user_id().await?;
470 let tenant_id = self.my_tenant_id(chat_id).await?;
471 self.remote
472 .mark_chat_unread(chat_id, &user_id, &tenant_id, last_read_at)
473 .await?;
474 }
459 475 self.store.mark_chat_unread(chat_id, last_read_at)?;
460 476 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
461 477 Ok(())
462 478 }
463 479
480 fn message_id_at(&self, chat_id: &str, created_at: DateTime<Utc>) -> Result<String> {
481 Ok(self
482 .store
483 .messages_between(chat_id, created_at, created_at)?
484 .into_iter()
485 .next()
486 .map(|message| message.message_id)
487 .unwrap_or_else(|| created_at.timestamp_millis().to_string()))
488 }
489
464 490 pub async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
465 491 self.remote.set_chat_muted(chat_id, muted).await?;
466 492 self.store.set_chat_muted(chat_id, muted)?;
@@ -483,6 +509,14 @@ impl<R: Remote> SyncEngine<R> {
483 509 }
484 510
485 511 pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
512 if is_notes_chat(chat_id) {
513 self.remote
514 .set_chat_hidden_at(chat_id, Some(Utc::now().timestamp_millis()))
515 .await?;
516 self.store.remove_chats(&[chat_id.to_owned()])?;
517 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
518 return Ok(());
519 }
486 520 let user_id = self.my_user_id().await?;
487 521 let tenant_id = self.my_tenant_id(chat_id).await?;
488 522 self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
@@ -498,6 +532,11 @@ impl<R: Remote> SyncEngine<R> {
498 532 }
499 533
500 534 pub async fn unhide_chat(&self, chat_id: &str) -> Result<()> {
535 if is_notes_chat(chat_id) {
536 self.remote.set_chat_hidden_at(chat_id, None).await?;
537 self.refresh_sidebar_full().await?;
538 return Ok(());
539 }
501 540 let user_id = self.my_user_id().await?;
502 541 let tenant_id = self.my_tenant_id(chat_id).await?;
503 542 self.remote
@@ -1,4 +1,4 @@
1use chatsvc::ConversationRef;
1use chatsvc::{ConversationRef, read_horizon};
2use chrono::{DateTime, Duration, Utc};
2use chrono::{DateTime, Duration, Utc};
3use graph::{
3use graph::{
4 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
4 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
@@ -14,6 +14,7 @@ use crate::links::LinkPreview;
14use crate::mapping::message_record;
14use crate::mapping::message_record;
15use crate::markdown::markdown_to_html;
15use crate::markdown::markdown_to_html;
16use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
16use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
17use crate::notes_chat::is_notes_chat;
17use crate::remote::Remote;
18use crate::remote::Remote;
18use crate::scheduled::NOTES_CHAT_ID;
19use crate::scheduled::NOTES_CHAT_ID;
19use crate::teams_quote::{chatsvc_mention_html, quote_reply_properties, teams_quote};
20use crate::teams_quote::{chatsvc_mention_html, quote_reply_properties, teams_quote};
@@ -399,7 +400,13 @@ impl<R: Remote> SyncEngine<R> {
399 self.remote
400 self.remote
400 .mark_chat_read(conversation_id, &user_id, &tenant_id)
401 .mark_chat_read(conversation_id, &user_id, &tenant_id)
401 .await?;
402 .await?;
402 self.store.mark_chat_read(conversation_id, Utc::now())?;
403 let now = Utc::now();
404 if is_notes_chat(conversation_id) {
405 self.remote
406 .set_read_bookmark(conversation_id, &read_horizon::cleared_bookmark(now))
407 .await?;
408 }
409 self.store.mark_chat_read(conversation_id, now)?;
403 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
410 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
404 Ok(())
411 Ok(())
405 }
412 }
@@ -451,16 +458,35 @@ impl<R: Remote> SyncEngine<R> {
451 message_created_at: DateTime<Utc>,
458 message_created_at: DateTime<Utc>,
452 ) -> Result<()> {
459 ) -> Result<()> {
453 let last_read_at = message_created_at - Duration::milliseconds(1);
460 let last_read_at = message_created_at - Duration::milliseconds(1);
454 let user_id = self.my_user_id().await?;
461 if is_notes_chat(chat_id) {
455 let tenant_id = self.my_tenant_id(chat_id).await?;
462 let bookmark = read_horizon::bookmark_at(
456 self.remote
463 message_created_at,
457 .mark_chat_unread(chat_id, &user_id, &tenant_id, last_read_at)
464 &self.message_id_at(chat_id, message_created_at)?,
458 .await?;
465 Utc::now(),
466 );
467 self.remote.set_read_bookmark(chat_id, &bookmark).await?;
468 } else {
469 let user_id = self.my_user_id().await?;
470 let tenant_id = self.my_tenant_id(chat_id).await?;
471 self.remote
472 .mark_chat_unread(chat_id, &user_id, &tenant_id, last_read_at)
473 .await?;
474 }
459 self.store.mark_chat_unread(chat_id, last_read_at)?;
475 self.store.mark_chat_unread(chat_id, last_read_at)?;
460 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
476 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
461 Ok(())
477 Ok(())
462 }
478 }
463
479
480 fn message_id_at(&self, chat_id: &str, created_at: DateTime<Utc>) -> Result<String> {
481 Ok(self
482 .store
483 .messages_between(chat_id, created_at, created_at)?
484 .into_iter()
485 .next()
486 .map(|message| message.message_id)
487 .unwrap_or_else(|| created_at.timestamp_millis().to_string()))
488 }
489
464 pub async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
490 pub async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
465 self.remote.set_chat_muted(chat_id, muted).await?;
491 self.remote.set_chat_muted(chat_id, muted).await?;
466 self.store.set_chat_muted(chat_id, muted)?;
492 self.store.set_chat_muted(chat_id, muted)?;
@@ -483,6 +509,14 @@ impl<R: Remote> SyncEngine<R> {
483 }
509 }
484
510
485 pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
511 pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
512 if is_notes_chat(chat_id) {
513 self.remote
514 .set_chat_hidden_at(chat_id, Some(Utc::now().timestamp_millis()))
515 .await?;
516 self.store.remove_chats(&[chat_id.to_owned()])?;
517 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
518 return Ok(());
519 }
486 let user_id = self.my_user_id().await?;
520 let user_id = self.my_user_id().await?;
487 let tenant_id = self.my_tenant_id(chat_id).await?;
521 let tenant_id = self.my_tenant_id(chat_id).await?;
488 self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
522 self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
@@ -498,6 +532,11 @@ impl<R: Remote> SyncEngine<R> {
498 }
532 }
499
533
500 pub async fn unhide_chat(&self, chat_id: &str) -> Result<()> {
534 pub async fn unhide_chat(&self, chat_id: &str) -> Result<()> {
535 if is_notes_chat(chat_id) {
536 self.remote.set_chat_hidden_at(chat_id, None).await?;
537 self.refresh_sidebar_full().await?;
538 return Ok(());
539 }
501 let user_id = self.my_user_id().await?;
540 let user_id = self.my_user_id().await?;
502 let tenant_id = self.my_tenant_id(chat_id).await?;
541 let tenant_id = self.my_tenant_id(chat_id).await?;
503 self.remote
542 self.remote
crates/core/src/channel_mentions.rs +1 −0
@@ -64,6 +64,7 @@ mod tests {
64 64 },
65 65 notification_settings: None,
66 66 history_cleared_ms: None,
67 hidden_at_ms: None,
67 68 }
68 69 }
69 70
@@ -64,6 +64,7 @@ mod tests {
64 },
64 },
65 notification_settings: None,
65 notification_settings: None,
66 history_cleared_ms: None,
66 history_cleared_ms: None,
67 hidden_at_ms: None,
67 }
68 }
68 }
69 }
69
70
crates/core/src/hidden_chats.rs +1 −0
@@ -194,6 +194,7 @@ mod tests {
194 194 read: chatsvc::ReadHorizon::default(),
195 195 notification_settings: None,
196 196 history_cleared_ms: None,
197 hidden_at_ms: None,
197 198 },
198 199 )])
199 200 }
@@ -194,6 +194,7 @@ mod tests {
194 read: chatsvc::ReadHorizon::default(),
194 read: chatsvc::ReadHorizon::default(),
195 notification_settings: None,
195 notification_settings: None,
196 history_cleared_ms: None,
196 history_cleared_ms: None,
197 hidden_at_ms: None,
197 },
198 },
198 )])
199 )])
199 }
200 }
crates/core/src/notes_chat.rs +29 −3
@@ -50,6 +50,14 @@ pub(crate) fn notes_chat_record(
50 50 record
51 51 }
52 52
53 /// Teams lists a hidden chat again once a message is newer than the hide time.
54 fn is_hidden(state: &ConversationState) -> bool {
55 state.hidden == Some(true)
56 || state
57 .hidden_at_ms
58 .is_some_and(|hidden_at_ms| hidden_at_ms >= state.read.last_message_ms)
59 }
60
53 61 fn needs_messages(record: &ChatRecord) -> bool {
54 62 record.last_message_at.is_some()
55 63 && record.last_message_preview.is_none()
@@ -73,17 +81,22 @@ impl<R: Remote> SyncEngine<R> {
73 81 let Some(states) = states else {
74 82 return stored.map(|stored| stored.id);
75 83 };
84 let placeholder = ConversationState {
85 id: NOTES_CHAT_ID.to_owned(),
86 ..ConversationState::default()
87 };
76 88 let state = states
77 89 .iter()
78 .find(|state| is_notes_chat(&state.id) && state.hidden != Some(true));
79 let Some(state) = state else {
90 .find(|state| is_notes_chat(&state.id))
91 .unwrap_or(&placeholder);
92 if is_hidden(state) {
80 93 if stored.is_some()
81 94 && let Err(error) = self.store.remove_chats(&[NOTES_CHAT_ID.to_owned()])
82 95 {
83 96 self.report(format!("cannot remove the notes chat: {error}"));
84 97 }
85 98 return None;
86 };
99 }
87 100 let display_name = self.me().map(|me| me.display_name).unwrap_or_default();
88 101 let record = notes_chat_record(state, my_user_id, &display_name, stored.as_ref());
89 102 if let Err(error) = self.store.upsert_chats(std::slice::from_ref(&record)) {
@@ -118,6 +131,7 @@ mod tests {
118 131 },
119 132 notification_settings: None,
120 133 history_cleared_ms: None,
134 hidden_at_ms: None,
121 135 }
122 136 }
123 137
@@ -150,6 +164,18 @@ mod tests {
150 164 assert!(needs_messages(&newer));
151 165 }
152 166
167 #[test]
168 fn a_hidden_notes_chat_comes_back_with_a_newer_note() {
169 let mut hidden = state(9, 9, "me");
170 hidden.hidden_at_ms = Some(9);
171 assert!(is_hidden(&hidden));
172 hidden.read.last_message_ms = 10;
173 assert!(!is_hidden(&hidden));
174 hidden.hidden = Some(true);
175 assert!(is_hidden(&hidden));
176 assert!(!is_hidden(&state(9, 9, "me")));
177 }
178
153 179 #[test]
154 180 fn an_empty_notes_chat_needs_no_message_read() {
155 181 let record = notes_chat_record(&state(0, 0, "me"), "me", "Ada", None);
@@ -50,6 +50,14 @@ pub(crate) fn notes_chat_record(
50 record
50 record
51}
51}
52
52
53/// Teams lists a hidden chat again once a message is newer than the hide time.
54fn is_hidden(state: &ConversationState) -> bool {
55 state.hidden == Some(true)
56 || state
57 .hidden_at_ms
58 .is_some_and(|hidden_at_ms| hidden_at_ms >= state.read.last_message_ms)
59}
60
53fn needs_messages(record: &ChatRecord) -> bool {
61fn needs_messages(record: &ChatRecord) -> bool {
54 record.last_message_at.is_some()
62 record.last_message_at.is_some()
55 && record.last_message_preview.is_none()
63 && record.last_message_preview.is_none()
@@ -73,17 +81,22 @@ impl<R: Remote> SyncEngine<R> {
73 let Some(states) = states else {
81 let Some(states) = states else {
74 return stored.map(|stored| stored.id);
82 return stored.map(|stored| stored.id);
75 };
83 };
84 let placeholder = ConversationState {
85 id: NOTES_CHAT_ID.to_owned(),
86 ..ConversationState::default()
87 };
76 let state = states
88 let state = states
77 .iter()
89 .iter()
78 .find(|state| is_notes_chat(&state.id) && state.hidden != Some(true));
90 .find(|state| is_notes_chat(&state.id))
79 let Some(state) = state else {
91 .unwrap_or(&placeholder);
92 if is_hidden(state) {
80 if stored.is_some()
93 if stored.is_some()
81 && let Err(error) = self.store.remove_chats(&[NOTES_CHAT_ID.to_owned()])
94 && let Err(error) = self.store.remove_chats(&[NOTES_CHAT_ID.to_owned()])
82 {
95 {
83 self.report(format!("cannot remove the notes chat: {error}"));
96 self.report(format!("cannot remove the notes chat: {error}"));
84 }
97 }
85 return None;
98 return None;
86 };
99 }
87 let display_name = self.me().map(|me| me.display_name).unwrap_or_default();
100 let display_name = self.me().map(|me| me.display_name).unwrap_or_default();
88 let record = notes_chat_record(state, my_user_id, &display_name, stored.as_ref());
101 let record = notes_chat_record(state, my_user_id, &display_name, stored.as_ref());
89 if let Err(error) = self.store.upsert_chats(std::slice::from_ref(&record)) {
102 if let Err(error) = self.store.upsert_chats(std::slice::from_ref(&record)) {
@@ -118,6 +131,7 @@ mod tests {
118 },
131 },
119 notification_settings: None,
132 notification_settings: None,
120 history_cleared_ms: None,
133 history_cleared_ms: None,
134 hidden_at_ms: None,
121 }
135 }
122 }
136 }
123
137
@@ -150,6 +164,18 @@ mod tests {
150 assert!(needs_messages(&newer));
164 assert!(needs_messages(&newer));
151 }
165 }
152
166
167 #[test]
168 fn a_hidden_notes_chat_comes_back_with_a_newer_note() {
169 let mut hidden = state(9, 9, "me");
170 hidden.hidden_at_ms = Some(9);
171 assert!(is_hidden(&hidden));
172 hidden.read.last_message_ms = 10;
173 assert!(!is_hidden(&hidden));
174 hidden.hidden = Some(true);
175 assert!(is_hidden(&hidden));
176 assert!(!is_hidden(&state(9, 9, "me")));
177 }
178
153 #[test]
179 #[test]
154 fn an_empty_notes_chat_needs_no_message_read() {
180 fn an_empty_notes_chat_needs_no_message_read() {
155 let record = notes_chat_record(&state(0, 0, "me"), "me", "Ada", None);
181 let record = notes_chat_record(&state(0, 0, "me"), "me", "Ada", None);
crates/core/src/remote.rs +18 −0
@@ -155,6 +155,12 @@ pub trait Remote {
155 155 }
156 156 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
157 157 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
158 async fn set_read_bookmark(&self, _conversation_id: &str, _bookmark: &str) -> Result<()> {
159 Err(Error::Unsupported("marking the notes chat as unread"))
160 }
161 async fn set_chat_hidden_at(&self, _chat_id: &str, _hidden_at_ms: Option<i64>) -> Result<()> {
162 Err(Error::Unsupported("hiding the notes chat"))
163 }
158 164 async fn set_channel_notifications(
159 165 &self,
160 166 channel_id: &str,
@@ -815,6 +821,18 @@ impl Remote for Graph {
815 821 .await?)
816 822 }
817 823
824 async fn set_read_bookmark(&self, conversation_id: &str, bookmark: &str) -> Result<()> {
825 Ok(Conversations::new(self.session())
826 .set_read_bookmark(conversation_id, bookmark)
827 .await?)
828 }
829
830 async fn set_chat_hidden_at(&self, chat_id: &str, hidden_at_ms: Option<i64>) -> Result<()> {
831 Ok(Conversations::new(self.session())
832 .set_hidden_at(chat_id, hidden_at_ms)
833 .await?)
834 }
835
818 836 async fn set_channel_notifications(
819 837 &self,
820 838 channel_id: &str,
@@ -155,6 +155,12 @@ pub trait Remote {
155 }
155 }
156 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
156 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
157 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
157 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
158 async fn set_read_bookmark(&self, _conversation_id: &str, _bookmark: &str) -> Result<()> {
159 Err(Error::Unsupported("marking the notes chat as unread"))
160 }
161 async fn set_chat_hidden_at(&self, _chat_id: &str, _hidden_at_ms: Option<i64>) -> Result<()> {
162 Err(Error::Unsupported("hiding the notes chat"))
163 }
158 async fn set_channel_notifications(
164 async fn set_channel_notifications(
159 &self,
165 &self,
160 channel_id: &str,
166 channel_id: &str,
@@ -815,6 +821,18 @@ impl Remote for Graph {
815 .await?)
821 .await?)
816 }
822 }
817
823
824 async fn set_read_bookmark(&self, conversation_id: &str, bookmark: &str) -> Result<()> {
825 Ok(Conversations::new(self.session())
826 .set_read_bookmark(conversation_id, bookmark)
827 .await?)
828 }
829
830 async fn set_chat_hidden_at(&self, chat_id: &str, hidden_at_ms: Option<i64>) -> Result<()> {
831 Ok(Conversations::new(self.session())
832 .set_hidden_at(chat_id, hidden_at_ms)
833 .await?)
834 }
835
818 async fn set_channel_notifications(
836 async fn set_channel_notifications(
819 &self,
837 &self,
820 channel_id: &str,
838 channel_id: &str,
crates/core/tests/engine.rs +77 −0
@@ -605,6 +605,7 @@ impl Remote for Handle {
605 605 read: chatsvc::ReadHorizon::default(),
606 606 notification_settings: None,
607 607 history_cleared_ms: None,
608 hidden_at_ms: None,
608 609 })
609 610 .collect();
610 611 states.extend(
@@ -617,6 +618,7 @@ impl Remote for Handle {
617 618 read: chatsvc::ReadHorizon::default(),
618 619 notification_settings: None,
619 620 history_cleared_ms: None,
621 hidden_at_ms: None,
620 622 }),
621 623 );
622 624 let read = self.read_states.lock().unwrap().clone();
@@ -629,6 +631,7 @@ impl Remote for Handle {
629 631 read,
630 632 notification_settings: None,
631 633 history_cleared_ms: None,
634 hidden_at_ms: None,
632 635 }),
633 636 );
634 637 Ok(states)
@@ -644,6 +647,17 @@ impl Remote for Handle {
644 647 Ok(())
645 648 }
646 649
650 async fn set_read_bookmark(&self, conversation_id: &str, bookmark: &str) -> Result<()> {
651 self.record(format!("read bookmark {conversation_id} {bookmark}"));
652 Ok(())
653 }
654
655 async fn set_chat_hidden_at(&self, chat_id: &str, hidden_at_ms: Option<i64>) -> Result<()> {
656 let hidden = hidden_at_ms.map_or("none".to_owned(), |_| "now".to_owned());
657 self.record(format!("hidden at {chat_id} {hidden}"));
658 Ok(())
659 }
660
647 661 async fn set_channel_notifications(
648 662 &self,
649 663 channel_id: &str,
@@ -5448,9 +5462,72 @@ async fn a_new_note_refreshes_the_line_and_an_unlisted_notes_chat_leaves_the_sid
5448 5462
5449 5463 fake.read_states.lock().unwrap().clear();
5450 5464 engine.refresh_sidebar().await.unwrap();
5465 let placeholder = engine.store().chat(NOTES_CHAT_ID).unwrap().unwrap();
5466 assert_eq!(placeholder.title, "Me Myself (You)");
5467 assert_eq!(placeholder.last_message_at, None);
5468 assert_eq!(placeholder.last_message_preview, None);
5469
5470 fake.hidden_states
5471 .lock()
5472 .unwrap()
5473 .push((NOTES_CHAT_ID.to_owned(), true));
5474 engine.refresh_sidebar().await.unwrap();
5451 5475 assert!(engine.store().chat(NOTES_CHAT_ID).unwrap().is_none());
5452 5476 }
5453 5477
5478 #[tokio::test]
5479 async fn marking_an_own_note_unread_sets_the_chatsvc_bookmark_and_reading_clears_it() {
5480 let fake = Arc::new(Fake::default());
5481 *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
5482 list_notes_chat(&fake, 20);
5483 fake.set_chat_messages(vec![own_note(1, 20, "<p>plan</p>")]);
5484 let engine = engine_with(&fake, small_pages());
5485 engine.refresh_sidebar().await.unwrap();
5486
5487 engine.mark_unread(NOTES_CHAT_ID).await.unwrap();
5488 engine.mark_read(NOTES_CHAT_ID).await.unwrap();
5489
5490 let arrived_ms = (base() + Duration::minutes(20)).timestamp_millis();
5491 let calls = fake.calls();
5492 let bookmarks: Vec<&String> = calls
5493 .iter()
5494 .filter(|call| call.starts_with("read bookmark "))
5495 .collect();
5496 assert_eq!(bookmarks.len(), 2, "{calls:?}");
5497 let marked = bookmarks[0].strip_prefix("read bookmark 48:notes ").unwrap();
5498 let fields: Vec<&str> = marked.split(';').collect();
5499 assert_eq!(fields[0], (arrived_ms - 1).to_string());
5500 assert_eq!(fields[2], "m0001");
5501 let cleared = bookmarks[1].strip_prefix("read bookmark 48:notes ").unwrap();
5502 assert!(cleared.starts_with("0;") && cleared.ends_with(";0"), "{cleared}");
5503 assert!(!calls.iter().any(|call| call.starts_with("mark_unread")), "{calls:?}");
5504 }
5505
5506 #[tokio::test]
5507 async fn hiding_the_notes_chat_writes_the_chatsvc_hide_time_and_undo_clears_it() {
5508 let fake = Arc::new(Fake::default());
5509 list_notes_chat(&fake, 20);
5510 fake.set_chat_messages(vec![own_note(1, 20, "<p>plan</p>")]);
5511 let engine = engine_with(&fake, small_pages());
5512 engine.refresh_sidebar().await.unwrap();
5513
5514 engine.hide_chat(NOTES_CHAT_ID).await.unwrap();
5515 assert!(engine.store().chat(NOTES_CHAT_ID).unwrap().is_none());
5516 engine.unhide_chat(NOTES_CHAT_ID).await.unwrap();
5517
5518 let calls = fake.calls();
5519 let hides: Vec<&String> = calls
5520 .iter()
5521 .filter(|call| call.starts_with("hidden at ") || call.starts_with("hide"))
5522 .collect();
5523 assert_eq!(
5524 hides,
5525 ["hidden at 48:notes now", "hidden at 48:notes none"],
5526 "{calls:?}"
5527 );
5528 assert!(engine.store().chat(NOTES_CHAT_ID).unwrap().is_some());
5529 }
5530
5454 5531 #[tokio::test]
5455 5532 async fn marking_the_notes_chat_read_takes_the_tenant_from_another_chat() {
5456 5533 let fake = Arc::new(Fake::default());
@@ -605,6 +605,7 @@ impl Remote for Handle {
605 read: chatsvc::ReadHorizon::default(),
605 read: chatsvc::ReadHorizon::default(),
606 notification_settings: None,
606 notification_settings: None,
607 history_cleared_ms: None,
607 history_cleared_ms: None,
608 hidden_at_ms: None,
608 })
609 })
609 .collect();
610 .collect();
610 states.extend(
611 states.extend(
@@ -617,6 +618,7 @@ impl Remote for Handle {
617 read: chatsvc::ReadHorizon::default(),
618 read: chatsvc::ReadHorizon::default(),
618 notification_settings: None,
619 notification_settings: None,
619 history_cleared_ms: None,
620 history_cleared_ms: None,
621 hidden_at_ms: None,
620 }),
622 }),
621 );
623 );
622 let read = self.read_states.lock().unwrap().clone();
624 let read = self.read_states.lock().unwrap().clone();
@@ -629,6 +631,7 @@ impl Remote for Handle {
629 read,
631 read,
630 notification_settings: None,
632 notification_settings: None,
631 history_cleared_ms: None,
633 history_cleared_ms: None,
634 hidden_at_ms: None,
632 }),
635 }),
633 );
636 );
634 Ok(states)
637 Ok(states)
@@ -644,6 +647,17 @@ impl Remote for Handle {
644 Ok(())
647 Ok(())
645 }
648 }
646
649
650 async fn set_read_bookmark(&self, conversation_id: &str, bookmark: &str) -> Result<()> {
651 self.record(format!("read bookmark {conversation_id} {bookmark}"));
652 Ok(())
653 }
654
655 async fn set_chat_hidden_at(&self, chat_id: &str, hidden_at_ms: Option<i64>) -> Result<()> {
656 let hidden = hidden_at_ms.map_or("none".to_owned(), |_| "now".to_owned());
657 self.record(format!("hidden at {chat_id} {hidden}"));
658 Ok(())
659 }
660
647 async fn set_channel_notifications(
661 async fn set_channel_notifications(
648 &self,
662 &self,
649 channel_id: &str,
663 channel_id: &str,
@@ -5448,9 +5462,72 @@ async fn a_new_note_refreshes_the_line_and_an_unlisted_notes_chat_leaves_the_sid
5448
5462
5449 fake.read_states.lock().unwrap().clear();
5463 fake.read_states.lock().unwrap().clear();
5450 engine.refresh_sidebar().await.unwrap();
5464 engine.refresh_sidebar().await.unwrap();
5465 let placeholder = engine.store().chat(NOTES_CHAT_ID).unwrap().unwrap();
5466 assert_eq!(placeholder.title, "Me Myself (You)");
5467 assert_eq!(placeholder.last_message_at, None);
5468 assert_eq!(placeholder.last_message_preview, None);
5469
5470 fake.hidden_states
5471 .lock()
5472 .unwrap()
5473 .push((NOTES_CHAT_ID.to_owned(), true));
5474 engine.refresh_sidebar().await.unwrap();
5451 assert!(engine.store().chat(NOTES_CHAT_ID).unwrap().is_none());
5475 assert!(engine.store().chat(NOTES_CHAT_ID).unwrap().is_none());
5452}
5476}
5453
5477
5478#[tokio::test]
5479async fn marking_an_own_note_unread_sets_the_chatsvc_bookmark_and_reading_clears_it() {
5480 let fake = Arc::new(Fake::default());
5481 *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
5482 list_notes_chat(&fake, 20);
5483 fake.set_chat_messages(vec![own_note(1, 20, "<p>plan</p>")]);
5484 let engine = engine_with(&fake, small_pages());
5485 engine.refresh_sidebar().await.unwrap();
5486
5487 engine.mark_unread(NOTES_CHAT_ID).await.unwrap();
5488 engine.mark_read(NOTES_CHAT_ID).await.unwrap();
5489
5490 let arrived_ms = (base() + Duration::minutes(20)).timestamp_millis();
5491 let calls = fake.calls();
5492 let bookmarks: Vec<&String> = calls
5493 .iter()
5494 .filter(|call| call.starts_with("read bookmark "))
5495 .collect();
5496 assert_eq!(bookmarks.len(), 2, "{calls:?}");
5497 let marked = bookmarks[0].strip_prefix("read bookmark 48:notes ").unwrap();
5498 let fields: Vec<&str> = marked.split(';').collect();
5499 assert_eq!(fields[0], (arrived_ms - 1).to_string());
5500 assert_eq!(fields[2], "m0001");
5501 let cleared = bookmarks[1].strip_prefix("read bookmark 48:notes ").unwrap();
5502 assert!(cleared.starts_with("0;") && cleared.ends_with(";0"), "{cleared}");
5503 assert!(!calls.iter().any(|call| call.starts_with("mark_unread")), "{calls:?}");
5504}
5505
5506#[tokio::test]
5507async fn hiding_the_notes_chat_writes_the_chatsvc_hide_time_and_undo_clears_it() {
5508 let fake = Arc::new(Fake::default());
5509 list_notes_chat(&fake, 20);
5510 fake.set_chat_messages(vec![own_note(1, 20, "<p>plan</p>")]);
5511 let engine = engine_with(&fake, small_pages());
5512 engine.refresh_sidebar().await.unwrap();
5513
5514 engine.hide_chat(NOTES_CHAT_ID).await.unwrap();
5515 assert!(engine.store().chat(NOTES_CHAT_ID).unwrap().is_none());
5516 engine.unhide_chat(NOTES_CHAT_ID).await.unwrap();
5517
5518 let calls = fake.calls();
5519 let hides: Vec<&String> = calls
5520 .iter()
5521 .filter(|call| call.starts_with("hidden at ") || call.starts_with("hide"))
5522 .collect();
5523 assert_eq!(
5524 hides,
5525 ["hidden at 48:notes now", "hidden at 48:notes none"],
5526 "{calls:?}"
5527 );
5528 assert!(engine.store().chat(NOTES_CHAT_ID).unwrap().is_some());
5529}
5530
5454#[tokio::test]
5531#[tokio::test]
5455async fn marking_the_notes_chat_read_takes_the_tenant_from_another_chat() {
5532async fn marking_the_notes_chat_read_takes_the_tenant_from_another_chat() {
5456 let fake = Arc::new(Fake::default());
5533 let fake = Arc::new(Fake::default());