BlueGit

ict rusty-teams

feat(chat): remove chat history and rename group chat like Teams

- chat list menu "Remove chat history" for 1:1, meeting and bot chats (groups offer Leave, as in Teams), dialog "Remove chat history?", PUT users/ME/conversations/{id}/properties?name=clearHistoryTime with last message time + 1
- chats with clearHistoryTime at or after the last message stay hidden until a newer message
- pencil "Name group chat" next to the group title (member only), popover Group name / Cancel / Save, 250 chars, no ':'
- rename writes PUT threads/{id}/properties?name=topic, empty removes the name
- system line "X changed the group name to Y." / "X removed the group name for this conversation." from Graph chatRenamedEventMessageDetail
- demo mode updates locally and adds the rename line
- deviations: tenant policy allowUserDeleteChat is not read (assumed on), local draft is not removed

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
3f80bacf61f49cd0b6e3191d27c0cbf487183492
Parent
969d630b
14 files changed +646 −12
crates/app-state/src/chat_actions.rs +74 −5
@@ -1,8 +1,8 @@
1 1 use std::future::Future;
2 2
3 use chatsvc::HistoryShare;
3 4 use chrono::{DateTime, Duration, Local, Offset, Utc};
4 5 use gpui_kit::*;
5 use chatsvc::HistoryShare;
6 6 use store::{ChannelNotifications, ChatRecord, MemberRecord};
7 7 use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};
8 8
@@ -255,9 +255,7 @@ impl AppState {
255 255 };
256 256 let mut with_members = chat.clone();
257 257 merge_members(&mut with_members.members, &people);
258 let _ = self
259 .store
260 .upsert_chats(std::slice::from_ref(&with_members));
258 let _ = self.store.upsert_chats(std::slice::from_ref(&with_members));
261 259 self.reload_sidebar(cx);
262 260 let Some(engine) = engine_or_demo else {
263 261 self.add_demo_roster_line(chat_id, &people, share, cx);
@@ -302,19 +300,90 @@ impl AppState {
302 300 HistoryShare::Days(days) => SharedHistory::Days(days),
303 301 HistoryShare::All => SharedHistory::All,
304 302 },
303 topic: None,
305 304 };
305 self.store_demo_roster_line(chat_id, &event, cx);
306 }
307
308 fn store_demo_roster_line(
309 &mut self,
310 chat_id: &str,
311 event: &RosterEvent,
312 cx: &mut Context<Self>,
313 ) {
306 314 let now = Utc::now();
307 315 let record = crate::demo::roster_record(
308 316 chat_id,
309 317 &format!("demo-roster-{}", now.timestamp_millis()),
310 318 now,
311 &event,
319 event,
312 320 );
313 321 let _ = self.store.upsert_messages(std::slice::from_ref(&record));
314 322 cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));
315 323 cx.notify();
316 324 }
317 325
326 /// Teams' "Remove chat history": hidden for me only until a newer message arrives.
327 pub fn remove_chat_history(&mut self, chat_id: &str, cx: &mut Context<Self>) {
328 let Some(chat) = self.chat_record(chat_id) else {
329 return;
330 };
331 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
332 return;
333 };
334 self.remove_chat_locally(chat_id, cx);
335 let Some(engine) = engine_or_demo else {
336 return;
337 };
338 let owned_id = chat_id.to_owned();
339 self.run_chat_action(
340 "Remove chat history",
341 async move { engine.remove_chat_history(&owned_id).await },
342 move |state, cx| state.restore_chat_locally(&chat, cx),
343 |_, _| {},
344 cx,
345 );
346 }
347
348 pub fn rename_chat(&mut self, chat_id: &str, topic: &str, cx: &mut Context<Self>) {
349 let Some(chat) = self.chat_record(chat_id) else {
350 return;
351 };
352 let topic = topic.trim().to_owned();
353 if topic == chat.title.trim() || chatsvc::topic_problem(&topic).is_some() {
354 return;
355 }
356 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
357 return;
358 };
359 let mut renamed = chat.clone();
360 renamed.title = topic.clone();
361 let _ = self.store.upsert_chats(std::slice::from_ref(&renamed));
362 self.reload_sidebar(cx);
363 let Some(engine) = engine_or_demo else {
364 let me = self.directory.me.as_ref();
365 let event = RosterEvent {
366 change: RosterChange::Renamed,
367 initiator_id: me.map(|person| person.user_id.clone()),
368 initiator_name: me.map(|person| person.display_name.clone()),
369 member_ids: Vec::new(),
370 member_names: Vec::new(),
371 history: SharedHistory::None,
372 topic: (!topic.is_empty()).then(|| topic.clone()),
373 };
374 self.store_demo_roster_line(chat_id, &event, cx);
375 return;
376 };
377 let owned_id = chat_id.to_owned();
378 self.run_chat_action(
379 "Rename group chat",
380 async move { engine.rename_chat(&owned_id, &topic).await },
381 move |state, cx| state.restore_chat_locally(&chat, cx),
382 |_, _| {},
383 cx,
384 );
385 }
386
318 387 /// Teams turns adding people to a 1:1 into a new group chat draft with everyone.
319 388 pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {
320 389 self.new_chat_people = people;
@@ -1,8 +1,8 @@
1use std::future::Future;
1use std::future::Future;
2
2
3use chatsvc::HistoryShare;
3use chrono::{DateTime, Duration, Local, Offset, Utc};
4use chrono::{DateTime, Duration, Local, Offset, Utc};
4use gpui_kit::*;
5use gpui_kit::*;
5use chatsvc::HistoryShare;
6use store::{ChannelNotifications, ChatRecord, MemberRecord};
6use store::{ChannelNotifications, ChatRecord, MemberRecord};
7use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};
7use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};
8
8
@@ -255,9 +255,7 @@ impl AppState {
255 };
255 };
256 let mut with_members = chat.clone();
256 let mut with_members = chat.clone();
257 merge_members(&mut with_members.members, &people);
257 merge_members(&mut with_members.members, &people);
258 let _ = self
258 let _ = self.store.upsert_chats(std::slice::from_ref(&with_members));
259 .store
260 .upsert_chats(std::slice::from_ref(&with_members));
261 self.reload_sidebar(cx);
259 self.reload_sidebar(cx);
262 let Some(engine) = engine_or_demo else {
260 let Some(engine) = engine_or_demo else {
263 self.add_demo_roster_line(chat_id, &people, share, cx);
261 self.add_demo_roster_line(chat_id, &people, share, cx);
@@ -302,19 +300,90 @@ impl AppState {
302 HistoryShare::Days(days) => SharedHistory::Days(days),
300 HistoryShare::Days(days) => SharedHistory::Days(days),
303 HistoryShare::All => SharedHistory::All,
301 HistoryShare::All => SharedHistory::All,
304 },
302 },
303 topic: None,
305 };
304 };
305 self.store_demo_roster_line(chat_id, &event, cx);
306 }
307
308 fn store_demo_roster_line(
309 &mut self,
310 chat_id: &str,
311 event: &RosterEvent,
312 cx: &mut Context<Self>,
313 ) {
306 let now = Utc::now();
314 let now = Utc::now();
307 let record = crate::demo::roster_record(
315 let record = crate::demo::roster_record(
308 chat_id,
316 chat_id,
309 &format!("demo-roster-{}", now.timestamp_millis()),
317 &format!("demo-roster-{}", now.timestamp_millis()),
310 now,
318 now,
311 &event,
319 event,
312 );
320 );
313 let _ = self.store.upsert_messages(std::slice::from_ref(&record));
321 let _ = self.store.upsert_messages(std::slice::from_ref(&record));
314 cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));
322 cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));
315 cx.notify();
323 cx.notify();
316 }
324 }
317
325
326 /// Teams' "Remove chat history": hidden for me only until a newer message arrives.
327 pub fn remove_chat_history(&mut self, chat_id: &str, cx: &mut Context<Self>) {
328 let Some(chat) = self.chat_record(chat_id) else {
329 return;
330 };
331 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
332 return;
333 };
334 self.remove_chat_locally(chat_id, cx);
335 let Some(engine) = engine_or_demo else {
336 return;
337 };
338 let owned_id = chat_id.to_owned();
339 self.run_chat_action(
340 "Remove chat history",
341 async move { engine.remove_chat_history(&owned_id).await },
342 move |state, cx| state.restore_chat_locally(&chat, cx),
343 |_, _| {},
344 cx,
345 );
346 }
347
348 pub fn rename_chat(&mut self, chat_id: &str, topic: &str, cx: &mut Context<Self>) {
349 let Some(chat) = self.chat_record(chat_id) else {
350 return;
351 };
352 let topic = topic.trim().to_owned();
353 if topic == chat.title.trim() || chatsvc::topic_problem(&topic).is_some() {
354 return;
355 }
356 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
357 return;
358 };
359 let mut renamed = chat.clone();
360 renamed.title = topic.clone();
361 let _ = self.store.upsert_chats(std::slice::from_ref(&renamed));
362 self.reload_sidebar(cx);
363 let Some(engine) = engine_or_demo else {
364 let me = self.directory.me.as_ref();
365 let event = RosterEvent {
366 change: RosterChange::Renamed,
367 initiator_id: me.map(|person| person.user_id.clone()),
368 initiator_name: me.map(|person| person.display_name.clone()),
369 member_ids: Vec::new(),
370 member_names: Vec::new(),
371 history: SharedHistory::None,
372 topic: (!topic.is_empty()).then(|| topic.clone()),
373 };
374 self.store_demo_roster_line(chat_id, &event, cx);
375 return;
376 };
377 let owned_id = chat_id.to_owned();
378 self.run_chat_action(
379 "Rename group chat",
380 async move { engine.rename_chat(&owned_id, &topic).await },
381 move |state, cx| state.restore_chat_locally(&chat, cx),
382 |_, _| {},
383 cx,
384 );
385 }
386
318 /// Teams turns adding people to a 1:1 into a new group chat draft with everyone.
387 /// Teams turns adding people to a 1:1 into a new group chat draft with everyone.
319 pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {
388 pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {
320 self.new_chat_people = people;
389 self.new_chat_people = people;
crates/app/src/views/conversation.rs +26 −6
@@ -40,6 +40,7 @@ use super::call_controls::header_call_controls;
40 40 use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
41 41 use super::chat_members::members_popover;
42 42 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
43 use super::group_name::group_name_button;
43 44 use super::message_actions::{Action, DelegateEntry, MessageMenu};
44 45 use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
45 46 use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
@@ -3283,6 +3284,7 @@ impl ConversationView {
3283 3284 let mut lead: Option<AnyElement> = None;
3284 3285 let mut subline = String::new();
3285 3286 let mut stack: Option<AnyElement> = None;
3287 let mut rename: Option<AnyElement> = None;
3286 3288 match &current.selection {
3287 3289 Selection::Chat(chat_id) => {
3288 3290 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
@@ -3318,6 +3320,15 @@ impl ConversationView {
3318 3320 stack = Some(add_people_button(&self.app, chat_id));
3319 3321 }
3320 3322 } else {
3323 if chat.kind == GROUP_KIND
3324 && me.is_some_and(|me| {
3325 chat.members
3326 .iter()
3327 .any(|member| member.user_id.as_deref() == Some(&me.user_id))
3328 })
3329 {
3330 rename = Some(group_name_button(&self.app, chat_id, &chat.title));
3331 }
3321 3332 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3322 3333 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3323 3334 subline = format!("{} participants", chat.members.len());
@@ -3420,12 +3431,19 @@ impl ConversationView {
3420 3431 .overflow_hidden()
3421 3432 .gap(px(1.))
3422 3433 .child(
3423 div()
3424 .truncate()
3425 .text_size(px(15.))
3426 .font_weight(FontWeight::SEMIBOLD)
3427 .text_color(theme::text())
3428 .child(current.title.clone()),
3434 h_flex()
3435 .min_w_0()
3436 .gap(px(2.))
3437 .items_center()
3438 .child(
3439 div()
3440 .truncate()
3441 .text_size(px(15.))
3442 .font_weight(FontWeight::SEMIBOLD)
3443 .text_color(theme::text())
3444 .child(current.title.clone()),
3445 )
3446 .children(rename),
3429 3447 )
3430 3448 .when(!subline.is_empty(), |column| {
3431 3449 column.child(
@@ -3442,6 +3460,8 @@ impl ConversationView {
3442 3460 }
3443 3461 }
3444 3462
3463 const GROUP_KIND: &str = "group";
3464
3445 3465 impl Render for ConversationView {
3446 3466 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3447 3467 let background = theme::surface();
@@ -40,6 +40,7 @@ use super::call_controls::header_call_controls;
40use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
40use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
41use super::chat_members::members_popover;
41use super::chat_members::members_popover;
42use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
42use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
43use super::group_name::group_name_button;
43use super::message_actions::{Action, DelegateEntry, MessageMenu};
44use super::message_actions::{Action, DelegateEntry, MessageMenu};
44use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
45use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
45use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
46use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
@@ -3283,6 +3284,7 @@ impl ConversationView {
3283 let mut lead: Option<AnyElement> = None;
3284 let mut lead: Option<AnyElement> = None;
3284 let mut subline = String::new();
3285 let mut subline = String::new();
3285 let mut stack: Option<AnyElement> = None;
3286 let mut stack: Option<AnyElement> = None;
3287 let mut rename: Option<AnyElement> = None;
3286 match &current.selection {
3288 match &current.selection {
3287 Selection::Chat(chat_id) => {
3289 Selection::Chat(chat_id) => {
3288 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
3290 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
@@ -3318,6 +3320,15 @@ impl ConversationView {
3318 stack = Some(add_people_button(&self.app, chat_id));
3320 stack = Some(add_people_button(&self.app, chat_id));
3319 }
3321 }
3320 } else {
3322 } else {
3323 if chat.kind == GROUP_KIND
3324 && me.is_some_and(|me| {
3325 chat.members
3326 .iter()
3327 .any(|member| member.user_id.as_deref() == Some(&me.user_id))
3328 })
3329 {
3330 rename = Some(group_name_button(&self.app, chat_id, &chat.title));
3331 }
3321 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3332 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3322 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3333 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3323 subline = format!("{} participants", chat.members.len());
3334 subline = format!("{} participants", chat.members.len());
@@ -3420,12 +3431,19 @@ impl ConversationView {
3420 .overflow_hidden()
3431 .overflow_hidden()
3421 .gap(px(1.))
3432 .gap(px(1.))
3422 .child(
3433 .child(
3423 div()
3434 h_flex()
3424 .truncate()
3435 .min_w_0()
3425 .text_size(px(15.))
3436 .gap(px(2.))
3426 .font_weight(FontWeight::SEMIBOLD)
3437 .items_center()
3427 .text_color(theme::text())
3438 .child(
3428 .child(current.title.clone()),
3439 div()
3440 .truncate()
3441 .text_size(px(15.))
3442 .font_weight(FontWeight::SEMIBOLD)
3443 .text_color(theme::text())
3444 .child(current.title.clone()),
3445 )
3446 .children(rename),
3429 )
3447 )
3430 .when(!subline.is_empty(), |column| {
3448 .when(!subline.is_empty(), |column| {
3431 column.child(
3449 column.child(
@@ -3442,6 +3460,8 @@ impl ConversationView {
3442 }
3460 }
3443}
3461}
3444
3462
3463const GROUP_KIND: &str = "group";
3464
3445impl Render for ConversationView {
3465impl Render for ConversationView {
3446 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3466 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3447 let background = theme::surface();
3467 let background = theme::surface();
crates/app/src/views/group_name.rs added +196 −0
@@ -0,0 +1,196 @@
1 use std::cell::RefCell;
2 use std::rc::Rc;
3
4 use chatsvc::{INVALID_TOPIC_CHARACTER, MAX_TOPIC_LENGTH, TopicProblem, topic_problem};
5 use gpui_kit::assets::IconName;
6 use gpui_kit::base::PopoverState;
7 use gpui_kit::component::button::{Button, ButtonVariants as _};
8 use gpui_kit::component::input::{Input, InputEvent, InputState};
9 use gpui_kit::component::popover::Popover;
10 use gpui_kit::component::{Disableable as _, h_flex, v_flex};
11 use gpui_kit::prelude::FluentBuilder as _;
12 use gpui_kit::*;
13
14 use super::widgets::icon;
15 use crate::app_state::AppState;
16 use crate::theme;
17
18 const BUTTON_TOOLTIP: &str = "Name group chat";
19 const FIELD_LABEL: &str = "Group name";
20 const PLACEHOLDER: &str = "Type a group name";
21 const FORM_WIDTH: f32 = 300.;
22 const FORM_PADDING: f32 = 12.;
23 const FORM_GAP: f32 = 8.;
24 const LABEL_SIZE: f32 = 12.;
25 const ICON_SIZE: f32 = 16.;
26
27 pub fn problem_text(problem: TopicProblem) -> String {
28 match problem {
29 TopicProblem::TooLong => {
30 format!("Your group name can't be longer than {MAX_TOPIC_LENGTH} characters.")
31 }
32 TopicProblem::InvalidCharacter => {
33 format!("'{INVALID_TOPIC_CHARACTER}' is not a valid character in group names.")
34 }
35 }
36 }
37
38 struct GroupNameForm {
39 app: Entity<AppState>,
40 chat_id: String,
41 input: Entity<InputState>,
42 popover: WeakEntity<PopoverState>,
43 _subscription: Subscription,
44 }
45
46 impl GroupNameForm {
47 fn new(
48 app: Entity<AppState>,
49 chat_id: String,
50 title: String,
51 popover: WeakEntity<PopoverState>,
52 window: &mut Window,
53 cx: &mut Context<Self>,
54 ) -> Self {
55 let input = cx.new(|cx| {
56 let mut state = InputState::new(window, cx).placeholder(PLACEHOLDER);
57 state.set_value(title, window, cx);
58 state
59 });
60 input.update(cx, |state, cx| state.focus(window, cx));
61 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
62 GroupNameForm {
63 app,
64 chat_id,
65 input,
66 popover,
67 _subscription: subscription,
68 }
69 }
70
71 fn on_input_event(
72 &mut self,
73 _: &Entity<InputState>,
74 event: &InputEvent,
75 window: &mut Window,
76 cx: &mut Context<Self>,
77 ) {
78 match event {
79 InputEvent::Change => cx.notify(),
80 InputEvent::PressEnter { .. } => self.save(window, cx),
81 _ => {}
82 }
83 }
84
85 fn problem(&self, cx: &App) -> Option<TopicProblem> {
86 topic_problem(self.input.read(cx).value().trim())
87 }
88
89 fn close(&self, window: &mut Window, cx: &mut App) {
90 self.popover
91 .update(cx, |state, cx| state.dismiss(window, cx))
92 .ok();
93 }
94
95 fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
96 if self.problem(cx).is_some() {
97 return;
98 }
99 let topic = self.input.read(cx).value().trim().to_owned();
100 let chat_id = self.chat_id.clone();
101 self.app
102 .update(cx, |state, cx| state.rename_chat(&chat_id, &topic, cx));
103 self.close(window, cx);
104 }
105 }
106
107 impl Render for GroupNameForm {
108 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
109 let problem = self.problem(cx);
110 v_flex()
111 .w(px(FORM_WIDTH))
112 .p(px(FORM_PADDING))
113 .gap(px(FORM_GAP))
114 .child(
115 div()
116 .text_size(px(LABEL_SIZE))
117 .text_color(theme::text_soft())
118 .child(FIELD_LABEL),
119 )
120 .child(Input::new(&self.input))
121 .when_some(problem, |form, problem| {
122 form.child(
123 div()
124 .text_size(px(LABEL_SIZE))
125 .text_color(theme::red_soft())
126 .child(problem_text(problem)),
127 )
128 })
129 .child(
130 h_flex()
131 .justify_end()
132 .gap(px(FORM_GAP))
133 .child(
134 Button::new("group-name-cancel")
135 .label("Cancel")
136 .on_click(cx.listener(|form, _, window, cx| form.close(window, cx))),
137 )
138 .child(
139 Button::new("group-name-save")
140 .primary()
141 .label("Save")
142 .disabled(problem.is_some())
143 .on_click(cx.listener(|form, _, window, cx| form.save(window, cx))),
144 ),
145 )
146 }
147 }
148
149 pub fn group_name_button(app: &Entity<AppState>, chat_id: &str, title: &str) -> AnyElement {
150 let (app, chat_id, title) = (app.clone(), chat_id.to_owned(), title.to_owned());
151 let form: Rc<RefCell<Option<Entity<GroupNameForm>>>> = Rc::default();
152 let reset = form.clone();
153 Popover::new("group-name")
154 .anchor(Anchor::TopLeft)
155 .p(px(0.))
156 .trigger(
157 Button::new("group-name-button")
158 .ghost()
159 .compact()
160 .tooltip(BUTTON_TOOLTIP)
161 .child(icon(IconName::Pencil, ICON_SIZE, theme::text_soft())),
162 )
163 .on_open_change(move |open, _, _| {
164 if !*open {
165 reset.borrow_mut().take();
166 }
167 })
168 .content(move |_, window, cx| {
169 if let Some(existing) = form.borrow().clone() {
170 return existing;
171 }
172 let popover = cx.entity().downgrade();
173 let (app, chat_id, title) = (app.clone(), chat_id.clone(), title.clone());
174 let created = cx.new(|cx| GroupNameForm::new(app, chat_id, title, popover, window, cx));
175 *form.borrow_mut() = Some(created.clone());
176 created
177 })
178 .into_any_element()
179 }
180
181 #[cfg(test)]
182 mod tests {
183 use super::{TopicProblem, problem_text};
184
185 #[test]
186 fn problems_use_the_teams_wording() {
187 assert_eq!(
188 problem_text(TopicProblem::TooLong),
189 "Your group name can't be longer than 250 characters."
190 );
191 assert_eq!(
192 problem_text(TopicProblem::InvalidCharacter),
193 "':' is not a valid character in group names."
194 );
195 }
196 }
@@ -0,0 +1,196 @@
1use std::cell::RefCell;
2use std::rc::Rc;
3
4use chatsvc::{INVALID_TOPIC_CHARACTER, MAX_TOPIC_LENGTH, TopicProblem, topic_problem};
5use gpui_kit::assets::IconName;
6use gpui_kit::base::PopoverState;
7use gpui_kit::component::button::{Button, ButtonVariants as _};
8use gpui_kit::component::input::{Input, InputEvent, InputState};
9use gpui_kit::component::popover::Popover;
10use gpui_kit::component::{Disableable as _, h_flex, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
13
14use super::widgets::icon;
15use crate::app_state::AppState;
16use crate::theme;
17
18const BUTTON_TOOLTIP: &str = "Name group chat";
19const FIELD_LABEL: &str = "Group name";
20const PLACEHOLDER: &str = "Type a group name";
21const FORM_WIDTH: f32 = 300.;
22const FORM_PADDING: f32 = 12.;
23const FORM_GAP: f32 = 8.;
24const LABEL_SIZE: f32 = 12.;
25const ICON_SIZE: f32 = 16.;
26
27pub fn problem_text(problem: TopicProblem) -> String {
28 match problem {
29 TopicProblem::TooLong => {
30 format!("Your group name can't be longer than {MAX_TOPIC_LENGTH} characters.")
31 }
32 TopicProblem::InvalidCharacter => {
33 format!("'{INVALID_TOPIC_CHARACTER}' is not a valid character in group names.")
34 }
35 }
36}
37
38struct GroupNameForm {
39 app: Entity<AppState>,
40 chat_id: String,
41 input: Entity<InputState>,
42 popover: WeakEntity<PopoverState>,
43 _subscription: Subscription,
44}
45
46impl GroupNameForm {
47 fn new(
48 app: Entity<AppState>,
49 chat_id: String,
50 title: String,
51 popover: WeakEntity<PopoverState>,
52 window: &mut Window,
53 cx: &mut Context<Self>,
54 ) -> Self {
55 let input = cx.new(|cx| {
56 let mut state = InputState::new(window, cx).placeholder(PLACEHOLDER);
57 state.set_value(title, window, cx);
58 state
59 });
60 input.update(cx, |state, cx| state.focus(window, cx));
61 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
62 GroupNameForm {
63 app,
64 chat_id,
65 input,
66 popover,
67 _subscription: subscription,
68 }
69 }
70
71 fn on_input_event(
72 &mut self,
73 _: &Entity<InputState>,
74 event: &InputEvent,
75 window: &mut Window,
76 cx: &mut Context<Self>,
77 ) {
78 match event {
79 InputEvent::Change => cx.notify(),
80 InputEvent::PressEnter { .. } => self.save(window, cx),
81 _ => {}
82 }
83 }
84
85 fn problem(&self, cx: &App) -> Option<TopicProblem> {
86 topic_problem(self.input.read(cx).value().trim())
87 }
88
89 fn close(&self, window: &mut Window, cx: &mut App) {
90 self.popover
91 .update(cx, |state, cx| state.dismiss(window, cx))
92 .ok();
93 }
94
95 fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
96 if self.problem(cx).is_some() {
97 return;
98 }
99 let topic = self.input.read(cx).value().trim().to_owned();
100 let chat_id = self.chat_id.clone();
101 self.app
102 .update(cx, |state, cx| state.rename_chat(&chat_id, &topic, cx));
103 self.close(window, cx);
104 }
105}
106
107impl Render for GroupNameForm {
108 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
109 let problem = self.problem(cx);
110 v_flex()
111 .w(px(FORM_WIDTH))
112 .p(px(FORM_PADDING))
113 .gap(px(FORM_GAP))
114 .child(
115 div()
116 .text_size(px(LABEL_SIZE))
117 .text_color(theme::text_soft())
118 .child(FIELD_LABEL),
119 )
120 .child(Input::new(&self.input))
121 .when_some(problem, |form, problem| {
122 form.child(
123 div()
124 .text_size(px(LABEL_SIZE))
125 .text_color(theme::red_soft())
126 .child(problem_text(problem)),
127 )
128 })
129 .child(
130 h_flex()
131 .justify_end()
132 .gap(px(FORM_GAP))
133 .child(
134 Button::new("group-name-cancel")
135 .label("Cancel")
136 .on_click(cx.listener(|form, _, window, cx| form.close(window, cx))),
137 )
138 .child(
139 Button::new("group-name-save")
140 .primary()
141 .label("Save")
142 .disabled(problem.is_some())
143 .on_click(cx.listener(|form, _, window, cx| form.save(window, cx))),
144 ),
145 )
146 }
147}
148
149pub fn group_name_button(app: &Entity<AppState>, chat_id: &str, title: &str) -> AnyElement {
150 let (app, chat_id, title) = (app.clone(), chat_id.to_owned(), title.to_owned());
151 let form: Rc<RefCell<Option<Entity<GroupNameForm>>>> = Rc::default();
152 let reset = form.clone();
153 Popover::new("group-name")
154 .anchor(Anchor::TopLeft)
155 .p(px(0.))
156 .trigger(
157 Button::new("group-name-button")
158 .ghost()
159 .compact()
160 .tooltip(BUTTON_TOOLTIP)
161 .child(icon(IconName::Pencil, ICON_SIZE, theme::text_soft())),
162 )
163 .on_open_change(move |open, _, _| {
164 if !*open {
165 reset.borrow_mut().take();
166 }
167 })
168 .content(move |_, window, cx| {
169 if let Some(existing) = form.borrow().clone() {
170 return existing;
171 }
172 let popover = cx.entity().downgrade();
173 let (app, chat_id, title) = (app.clone(), chat_id.clone(), title.clone());
174 let created = cx.new(|cx| GroupNameForm::new(app, chat_id, title, popover, window, cx));
175 *form.borrow_mut() = Some(created.clone());
176 created
177 })
178 .into_any_element()
179}
180
181#[cfg(test)]
182mod tests {
183 use super::{TopicProblem, problem_text};
184
185 #[test]
186 fn problems_use_the_teams_wording() {
187 assert_eq!(
188 problem_text(TopicProblem::TooLong),
189 "Your group name can't be longer than 250 characters."
190 );
191 assert_eq!(
192 problem_text(TopicProblem::InvalidCharacter),
193 "':' is not a valid character in group names."
194 );
195 }
196}
crates/app/src/views/mod.rs +1 −0
@@ -43,6 +43,7 @@ pub mod emoji_popup;
43 43 pub mod format_toolbar;
44 44 pub mod forward_dialog;
45 45 pub mod fun_picker;
46 pub mod group_name;
46 47 pub mod image_menu;
47 48 pub mod image_viewer;
48 49 pub mod join_dialog;
@@ -43,6 +43,7 @@ pub mod emoji_popup;
43pub mod format_toolbar;
43pub mod format_toolbar;
44pub mod forward_dialog;
44pub mod forward_dialog;
45pub mod fun_picker;
45pub mod fun_picker;
46pub mod group_name;
46pub mod image_menu;
47pub mod image_menu;
47pub mod image_viewer;
48pub mod image_viewer;
48pub mod join_dialog;
49pub mod join_dialog;
crates/app/src/views/sidebar.rs +45 −0
@@ -229,6 +229,17 @@ fn chat_menu(
229 229 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
230 230 }),
231 231 );
232 if !target.is_group {
233 let remove_state = context.state.clone();
234 let remove_id = target.id.clone();
235 popup = popup.item(
236 PopupMenuItem::new(REMOVE_HISTORY_LABEL)
237 .icon(menu_icon(IconName::Trash))
238 .on_click(move |_, window, cx| {
239 confirm_remove_history(&remove_state, &remove_id, window, cx);
240 }),
241 );
242 }
232 243 if target.is_group {
233 244 let leave_state = context.state.clone();
234 245 let leave_id = target.id.clone();
@@ -440,6 +451,40 @@ fn leave_description(member_count: usize) -> String {
440 451 format!("{who} {verb} that you left. You can only come back if someone adds you.")
441 452 }
442 453
454 const REMOVE_HISTORY_LABEL: &str = "Remove chat history";
455 const REMOVE_HISTORY_TITLE: &str = "Remove chat history?";
456 const REMOVE_HISTORY_TEXT: &str =
457 "This will remove the chat from your list and search. It affects you only.";
458
459 fn confirm_remove_history(
460 state: &Entity<AppState>,
461 chat_id: &str,
462 window: &mut Window,
463 cx: &mut App,
464 ) {
465 let state = state.clone();
466 let chat_id = chat_id.to_owned();
467 window.open_alert_dialog(cx, move |alert, _, _| {
468 let state = state.clone();
469 let chat_id = chat_id.clone();
470 let cancel = Button::new("remove-history-cancel")
471 .label("Cancel")
472 .on_click(|_, window, cx| window.close_dialog(cx));
473 let remove = Button::new("remove-history-confirm")
474 .label("Remove")
475 .primary()
476 .on_click(move |_, window, cx| {
477 state.update(cx, |state, cx| state.remove_chat_history(&chat_id, cx));
478 window.close_dialog(cx);
479 });
480 alert
481 .title(REMOVE_HISTORY_TITLE)
482 .description(REMOVE_HISTORY_TEXT)
483 .footer(DialogFooter::new().child(cancel).child(remove))
484 .on_ok(|_, _, _| false)
485 });
486 }
487
443 488 pub(crate) fn confirm_leave(
444 489 state: &Entity<AppState>,
445 490 chat_id: &str,
@@ -229,6 +229,17 @@ fn chat_menu(
229 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
229 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
230 }),
230 }),
231 );
231 );
232 if !target.is_group {
233 let remove_state = context.state.clone();
234 let remove_id = target.id.clone();
235 popup = popup.item(
236 PopupMenuItem::new(REMOVE_HISTORY_LABEL)
237 .icon(menu_icon(IconName::Trash))
238 .on_click(move |_, window, cx| {
239 confirm_remove_history(&remove_state, &remove_id, window, cx);
240 }),
241 );
242 }
232 if target.is_group {
243 if target.is_group {
233 let leave_state = context.state.clone();
244 let leave_state = context.state.clone();
234 let leave_id = target.id.clone();
245 let leave_id = target.id.clone();
@@ -440,6 +451,40 @@ fn leave_description(member_count: usize) -> String {
440 format!("{who} {verb} that you left. You can only come back if someone adds you.")
451 format!("{who} {verb} that you left. You can only come back if someone adds you.")
441}
452}
442
453
454const REMOVE_HISTORY_LABEL: &str = "Remove chat history";
455const REMOVE_HISTORY_TITLE: &str = "Remove chat history?";
456const REMOVE_HISTORY_TEXT: &str =
457 "This will remove the chat from your list and search. It affects you only.";
458
459fn confirm_remove_history(
460 state: &Entity<AppState>,
461 chat_id: &str,
462 window: &mut Window,
463 cx: &mut App,
464) {
465 let state = state.clone();
466 let chat_id = chat_id.to_owned();
467 window.open_alert_dialog(cx, move |alert, _, _| {
468 let state = state.clone();
469 let chat_id = chat_id.clone();
470 let cancel = Button::new("remove-history-cancel")
471 .label("Cancel")
472 .on_click(|_, window, cx| window.close_dialog(cx));
473 let remove = Button::new("remove-history-confirm")
474 .label("Remove")
475 .primary()
476 .on_click(move |_, window, cx| {
477 state.update(cx, |state, cx| state.remove_chat_history(&chat_id, cx));
478 window.close_dialog(cx);
479 });
480 alert
481 .title(REMOVE_HISTORY_TITLE)
482 .description(REMOVE_HISTORY_TEXT)
483 .footer(DialogFooter::new().child(cancel).child(remove))
484 .on_ok(|_, _, _| false)
485 });
486}
487
443pub(crate) fn confirm_leave(
488pub(crate) fn confirm_leave(
444 state: &Entity<AppState>,
489 state: &Entity<AppState>,
445 chat_id: &str,
490 chat_id: &str,
crates/chatsvc/src/conversations.rs +86 −0
@@ -10,6 +10,7 @@ use crate::read_horizon::{self, ReadHorizon};
10 10 const PAGE_SIZE: usize = 200;
11 11 const MAX_PAGES: usize = 100;
12 12 const ALERTS_OFF: &str = "false";
13 const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
13 14
14 15 #[derive(Debug, Clone, PartialEq, Eq)]
15 16 pub struct ConversationState {
@@ -17,6 +18,7 @@ pub struct ConversationState {
17 18 pub muted: bool,
18 19 pub hidden: Option<bool>,
19 20 pub read: ReadHorizon,
21 pub history_cleared_ms: Option<i64>,
20 22 }
21 23
22 24 pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
@@ -84,6 +86,19 @@ impl<T: MessageTransport> Conversations<T> {
84 86 ensure_success(&answer)
85 87 }
86 88
89 /// Teams' "Remove chat history": everything up to this time disappears for the current user only.
90 pub async fn clear_history(&self, conversation_id: &str, cleared_until_ms: i64) -> Result<()> {
91 let answer = self
92 .transport
93 .send(clear_history_request(
94 &self.base_url,
95 conversation_id,
96 cleared_until_ms,
97 ))
98 .await?;
99 ensure_success(&answer)
100 }
101
87 102 pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
88 103 let url = format!(
89 104 "{}/{}/properties?name={}",
@@ -118,6 +133,29 @@ impl<T: MessageTransport> Conversations<T> {
118 133 }
119 134 }
120 135
136 pub fn clear_history_request(
137 base_url: &str,
138 conversation_id: &str,
139 cleared_until_ms: i64,
140 ) -> Request {
141 Request::with_body(
142 Method::Put,
143 format!(
144 "{base_url}/{}/properties?name={CLEAR_HISTORY_PROPERTY}",
145 encode(conversation_id)
146 ),
147 json!({ CLEAR_HISTORY_PROPERTY: cleared_until_ms }),
148 )
149 }
150
151 fn history_cleared_ms(conversation: &Value) -> Option<i64> {
152 let value = &conversation["properties"][CLEAR_HISTORY_PROPERTY];
153 value
154 .as_i64()
155 .or_else(|| value.as_str()?.parse().ok())
156 .filter(|millis| *millis > 0)
157 }
158
121 159 /// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.
122 160 pub fn thread_url(region: &str, thread_id: &str) -> String {
123 161 format!(
@@ -167,6 +205,7 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
167 205 muted,
168 206 hidden: hidden_flag(conversation),
169 207 read: ReadHorizon::from_conversation(conversation),
208 history_cleared_ms: history_cleared_ms(conversation),
170 209 })
171 210 })
172 211 .collect())
@@ -211,6 +250,7 @@ mod tests {
211 250 muted,
212 251 hidden: None,
213 252 read: ReadHorizon::default(),
253 history_cleared_ms: None,
214 254 }
215 255 }
216 256
@@ -383,6 +423,52 @@ mod tests {
383 423 assert!(states[0].read.is_unread("8:orgid:me"));
384 424 }
385 425
426 #[tokio::test]
427 async fn clear_history_puts_the_time_as_a_number() {
428 let transport = canned(vec![(200, Value::Null)]);
429 Conversations::with_transport(&transport, "emea")
430 .clear_history("19:a_b@unq.gbl.spaces", 1_792_200_000_001)
431 .await
432 .unwrap();
433 let requests = transport.requests.lock().unwrap();
434 assert_eq!(requests[0].method, Method::Put);
435 assert_eq!(
436 requests[0].url,
437 format!("{BASE}/19%3Aa_b%40unq.gbl.spaces/properties?name=clearHistoryTime")
438 );
439 assert_eq!(
440 requests[0].body,
441 Some(json!({"clearHistoryTime": 1_792_200_000_001_i64}))
442 );
443 }
444
445 #[tokio::test]
446 async fn states_carry_the_clear_history_time_as_text_or_number() {
447 let transport = canned(vec![(
448 200,
449 json!({
450 "conversations": [
451 {"id": "19:a", "properties": {"clearHistoryTime": "1792200000001"}},
452 {"id": "19:b", "properties": {"clearHistoryTime": 1_792_200_000_002_i64}},
453 {"id": "19:c", "properties": {"clearHistoryTime": "0"}},
454 {"id": "19:d"},
455 ],
456 }),
457 )]);
458 let states = Conversations::with_transport(&transport, "emea")
459 .conversation_states()
460 .await
461 .unwrap();
462 let cleared: Vec<Option<i64>> = states
463 .iter()
464 .map(|state| state.history_cleared_ms)
465 .collect();
466 assert_eq!(
467 cleared,
468 [Some(1_792_200_000_001), Some(1_792_200_000_002), None, None]
469 );
470 }
471
386 472 #[tokio::test]
387 473 async fn set_read_horizon_puts_the_consumption_horizon_property() {
388 474 let transport = canned(vec![(200, Value::Null)]);
@@ -10,6 +10,7 @@ use crate::read_horizon::{self, ReadHorizon};
10const PAGE_SIZE: usize = 200;
10const PAGE_SIZE: usize = 200;
11const MAX_PAGES: usize = 100;
11const MAX_PAGES: usize = 100;
12const ALERTS_OFF: &str = "false";
12const ALERTS_OFF: &str = "false";
13const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
13
14
14#[derive(Debug, Clone, PartialEq, Eq)]
15#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct ConversationState {
16pub struct ConversationState {
@@ -17,6 +18,7 @@ pub struct ConversationState {
17 pub muted: bool,
18 pub muted: bool,
18 pub hidden: Option<bool>,
19 pub hidden: Option<bool>,
19 pub read: ReadHorizon,
20 pub read: ReadHorizon,
21 pub history_cleared_ms: Option<i64>,
20}
22}
21
23
22pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
24pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
@@ -84,6 +86,19 @@ impl<T: MessageTransport> Conversations<T> {
84 ensure_success(&answer)
86 ensure_success(&answer)
85 }
87 }
86
88
89 /// Teams' "Remove chat history": everything up to this time disappears for the current user only.
90 pub async fn clear_history(&self, conversation_id: &str, cleared_until_ms: i64) -> Result<()> {
91 let answer = self
92 .transport
93 .send(clear_history_request(
94 &self.base_url,
95 conversation_id,
96 cleared_until_ms,
97 ))
98 .await?;
99 ensure_success(&answer)
100 }
101
87 pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
102 pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
88 let url = format!(
103 let url = format!(
89 "{}/{}/properties?name={}",
104 "{}/{}/properties?name={}",
@@ -118,6 +133,29 @@ impl<T: MessageTransport> Conversations<T> {
118 }
133 }
119}
134}
120
135
136pub fn clear_history_request(
137 base_url: &str,
138 conversation_id: &str,
139 cleared_until_ms: i64,
140) -> Request {
141 Request::with_body(
142 Method::Put,
143 format!(
144 "{base_url}/{}/properties?name={CLEAR_HISTORY_PROPERTY}",
145 encode(conversation_id)
146 ),
147 json!({ CLEAR_HISTORY_PROPERTY: cleared_until_ms }),
148 )
149}
150
151fn history_cleared_ms(conversation: &Value) -> Option<i64> {
152 let value = &conversation["properties"][CLEAR_HISTORY_PROPERTY];
153 value
154 .as_i64()
155 .or_else(|| value.as_str()?.parse().ok())
156 .filter(|millis| *millis > 0)
157}
158
121/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.
159/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.
122pub fn thread_url(region: &str, thread_id: &str) -> String {
160pub fn thread_url(region: &str, thread_id: &str) -> String {
123 format!(
161 format!(
@@ -167,6 +205,7 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
167 muted,
205 muted,
168 hidden: hidden_flag(conversation),
206 hidden: hidden_flag(conversation),
169 read: ReadHorizon::from_conversation(conversation),
207 read: ReadHorizon::from_conversation(conversation),
208 history_cleared_ms: history_cleared_ms(conversation),
170 })
209 })
171 })
210 })
172 .collect())
211 .collect())
@@ -211,6 +250,7 @@ mod tests {
211 muted,
250 muted,
212 hidden: None,
251 hidden: None,
213 read: ReadHorizon::default(),
252 read: ReadHorizon::default(),
253 history_cleared_ms: None,
214 }
254 }
215 }
255 }
216
256
@@ -383,6 +423,52 @@ mod tests {
383 assert!(states[0].read.is_unread("8:orgid:me"));
423 assert!(states[0].read.is_unread("8:orgid:me"));
384 }
424 }
385
425
426 #[tokio::test]
427 async fn clear_history_puts_the_time_as_a_number() {
428 let transport = canned(vec![(200, Value::Null)]);
429 Conversations::with_transport(&transport, "emea")
430 .clear_history("19:a_b@unq.gbl.spaces", 1_792_200_000_001)
431 .await
432 .unwrap();
433 let requests = transport.requests.lock().unwrap();
434 assert_eq!(requests[0].method, Method::Put);
435 assert_eq!(
436 requests[0].url,
437 format!("{BASE}/19%3Aa_b%40unq.gbl.spaces/properties?name=clearHistoryTime")
438 );
439 assert_eq!(
440 requests[0].body,
441 Some(json!({"clearHistoryTime": 1_792_200_000_001_i64}))
442 );
443 }
444
445 #[tokio::test]
446 async fn states_carry_the_clear_history_time_as_text_or_number() {
447 let transport = canned(vec![(
448 200,
449 json!({
450 "conversations": [
451 {"id": "19:a", "properties": {"clearHistoryTime": "1792200000001"}},
452 {"id": "19:b", "properties": {"clearHistoryTime": 1_792_200_000_002_i64}},
453 {"id": "19:c", "properties": {"clearHistoryTime": "0"}},
454 {"id": "19:d"},
455 ],
456 }),
457 )]);
458 let states = Conversations::with_transport(&transport, "emea")
459 .conversation_states()
460 .await
461 .unwrap();
462 let cleared: Vec<Option<i64>> = states
463 .iter()
464 .map(|state| state.history_cleared_ms)
465 .collect();
466 assert_eq!(
467 cleared,
468 [Some(1_792_200_000_001), Some(1_792_200_000_002), None, None]
469 );
470 }
471
386 #[tokio::test]
472 #[tokio::test]
387 async fn set_read_horizon_puts_the_consumption_horizon_property() {
473 async fn set_read_horizon_puts_the_consumption_horizon_property() {
388 let transport = canned(vec![(200, Value::Null)]);
474 let transport = canned(vec![(200, Value::Null)]);
crates/chatsvc/src/lib.rs +4 −1
@@ -55,7 +55,10 @@ pub use language_settings::{
55 55 };
56 56 pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
57 57 pub use mask::mask_conversation_id;
58 pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};
58 pub use members::{
59 HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
60 TopicProblem, topic_problem,
61 };
59 62 pub use messages::{ConversationRef, Messages};
60 63 pub use pins::{
61 64 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
@@ -55,7 +55,10 @@ pub use language_settings::{
55};
55};
56pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
56pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
57pub use mask::mask_conversation_id;
57pub use mask::mask_conversation_id;
58pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};
58pub use members::{
59 HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
60 TopicProblem, topic_problem,
61};
59pub use messages::{ConversationRef, Messages};
62pub use messages::{ConversationRef, Messages};
60pub use pins::{
63pub use pins::{
61 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
64 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
crates/chatsvc/src/members.rs +66 −0
@@ -8,6 +8,9 @@ use crate::pins::DEFAULT_REGION;
8 8 const ORGID_PREFIX: &str = "8:orgid:";
9 9 const MEMBER_ROLE: &str = "Admin";
10 10 const DAY_MS: i64 = 86_400_000;
11 const TOPIC_PROPERTY: &str = "topic";
12 pub const MAX_TOPIC_LENGTH: usize = 250;
13 pub const INVALID_TOPIC_CHARACTER: char = ':';
11 14 pub const MAX_HISTORY_DAYS: u32 = 999;
12 15
13 16 /// How much chat history new members see, as the Teams add-people dialog offers it.
@@ -80,6 +83,35 @@ pub fn remove_member_request(region: &str, thread_id: &str, user_id: &str) -> Re
80 83 ))
81 84 }
82 85
86 /// Teams renames a group chat by setting the thread property `topic`; an empty topic removes the name.
87 pub fn topic_request(region: &str, thread_id: &str, topic: &str) -> Request {
88 Request::with_body(
89 Method::Put,
90 format!(
91 "{}/{}/properties?name={TOPIC_PROPERTY}",
92 threads_url(region),
93 encode(thread_id)
94 ),
95 json!({ TOPIC_PROPERTY: topic }),
96 )
97 }
98
99 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
100 pub enum TopicProblem {
101 TooLong,
102 InvalidCharacter,
103 }
104
105 pub fn topic_problem(topic: &str) -> Option<TopicProblem> {
106 if topic.chars().count() > MAX_TOPIC_LENGTH {
107 Some(TopicProblem::TooLong)
108 } else if topic.contains(INVALID_TOPIC_CHARACTER) {
109 Some(TopicProblem::InvalidCharacter)
110 } else {
111 None
112 }
113 }
114
83 115 pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {
84 116 transport: T,
85 117 region: String,
@@ -114,6 +146,11 @@ impl<T: MessageTransport> ThreadMembers<T> {
114 146 let request = remove_member_request(&self.region, thread_id, user_id);
115 147 ensure_success(&self.transport.send(request).await?)
116 148 }
149
150 pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {
151 let request = topic_request(&self.region, thread_id, topic);
152 ensure_success(&self.transport.send(request).await?)
153 }
117 154 }
118 155
119 156 #[cfg(test)]
@@ -124,6 +161,35 @@ mod tests {
124 161
125 162 use super::*;
126 163
164 #[test]
165 fn topic_is_put_as_the_thread_property() {
166 let request = topic_request("emea", THREAD, "Release crew");
167 assert_eq!(request.method, Method::Put);
168 assert_eq!(
169 request.url,
170 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads/19%3Aabc%40thread.v2/properties?name=topic"
171 );
172 assert_eq!(request.body, Some(json!({"topic": "Release crew"})));
173 assert_eq!(
174 topic_request("emea", THREAD, "").body,
175 Some(json!({"topic": ""}))
176 );
177 }
178
179 #[test]
180 fn topic_rules_follow_teams() {
181 assert_eq!(topic_problem("Release crew"), None);
182 assert_eq!(topic_problem(&"a".repeat(MAX_TOPIC_LENGTH)), None);
183 assert_eq!(
184 topic_problem(&"a".repeat(MAX_TOPIC_LENGTH + 1)),
185 Some(TopicProblem::TooLong)
186 );
187 assert_eq!(
188 topic_problem("Team: ops"),
189 Some(TopicProblem::InvalidCharacter)
190 );
191 }
192
127 193 const NOW: i64 = 1_792_200_000_000;
128 194 const THREAD: &str = "19:abc@thread.v2";
129 195
@@ -8,6 +8,9 @@ use crate::pins::DEFAULT_REGION;
8const ORGID_PREFIX: &str = "8:orgid:";
8const ORGID_PREFIX: &str = "8:orgid:";
9const MEMBER_ROLE: &str = "Admin";
9const MEMBER_ROLE: &str = "Admin";
10const DAY_MS: i64 = 86_400_000;
10const DAY_MS: i64 = 86_400_000;
11const TOPIC_PROPERTY: &str = "topic";
12pub const MAX_TOPIC_LENGTH: usize = 250;
13pub const INVALID_TOPIC_CHARACTER: char = ':';
11pub const MAX_HISTORY_DAYS: u32 = 999;
14pub const MAX_HISTORY_DAYS: u32 = 999;
12
15
13/// How much chat history new members see, as the Teams add-people dialog offers it.
16/// How much chat history new members see, as the Teams add-people dialog offers it.
@@ -80,6 +83,35 @@ pub fn remove_member_request(region: &str, thread_id: &str, user_id: &str) -> Re
80 ))
83 ))
81}
84}
82
85
86/// Teams renames a group chat by setting the thread property `topic`; an empty topic removes the name.
87pub fn topic_request(region: &str, thread_id: &str, topic: &str) -> Request {
88 Request::with_body(
89 Method::Put,
90 format!(
91 "{}/{}/properties?name={TOPIC_PROPERTY}",
92 threads_url(region),
93 encode(thread_id)
94 ),
95 json!({ TOPIC_PROPERTY: topic }),
96 )
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum TopicProblem {
101 TooLong,
102 InvalidCharacter,
103}
104
105pub fn topic_problem(topic: &str) -> Option<TopicProblem> {
106 if topic.chars().count() > MAX_TOPIC_LENGTH {
107 Some(TopicProblem::TooLong)
108 } else if topic.contains(INVALID_TOPIC_CHARACTER) {
109 Some(TopicProblem::InvalidCharacter)
110 } else {
111 None
112 }
113}
114
83pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {
115pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {
84 transport: T,
116 transport: T,
85 region: String,
117 region: String,
@@ -114,6 +146,11 @@ impl<T: MessageTransport> ThreadMembers<T> {
114 let request = remove_member_request(&self.region, thread_id, user_id);
146 let request = remove_member_request(&self.region, thread_id, user_id);
115 ensure_success(&self.transport.send(request).await?)
147 ensure_success(&self.transport.send(request).await?)
116 }
148 }
149
150 pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {
151 let request = topic_request(&self.region, thread_id, topic);
152 ensure_success(&self.transport.send(request).await?)
153 }
117}
154}
118
155
119#[cfg(test)]
156#[cfg(test)]
@@ -124,6 +161,35 @@ mod tests {
124
161
125 use super::*;
162 use super::*;
126
163
164 #[test]
165 fn topic_is_put_as_the_thread_property() {
166 let request = topic_request("emea", THREAD, "Release crew");
167 assert_eq!(request.method, Method::Put);
168 assert_eq!(
169 request.url,
170 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads/19%3Aabc%40thread.v2/properties?name=topic"
171 );
172 assert_eq!(request.body, Some(json!({"topic": "Release crew"})));
173 assert_eq!(
174 topic_request("emea", THREAD, "").body,
175 Some(json!({"topic": ""}))
176 );
177 }
178
179 #[test]
180 fn topic_rules_follow_teams() {
181 assert_eq!(topic_problem("Release crew"), None);
182 assert_eq!(topic_problem(&"a".repeat(MAX_TOPIC_LENGTH)), None);
183 assert_eq!(
184 topic_problem(&"a".repeat(MAX_TOPIC_LENGTH + 1)),
185 Some(TopicProblem::TooLong)
186 );
187 assert_eq!(
188 topic_problem("Team: ops"),
189 Some(TopicProblem::InvalidCharacter)
190 );
191 }
192
127 const NOW: i64 = 1_792_200_000_000;
193 const NOW: i64 = 1_792_200_000_000;
128 const THREAD: &str = "19:abc@thread.v2";
194 const THREAD: &str = "19:abc@thread.v2";
129
195
crates/core/src/actions.rs +29 −0
@@ -9,6 +9,7 @@ use store::MessageRecord;
9 9 use crate::engine::{Conversation, META_USER_ID, SyncEngine};
10 10 use crate::error::{Error, Result};
11 11 use crate::external_image::external_image_url;
12 use crate::hidden_chats::cleared_until_ms;
12 13 use crate::links::LinkPreview;
13 14 use crate::mapping::message_record;
14 15 use crate::markdown::markdown_to_html;
@@ -470,6 +471,34 @@ impl<R: Remote> SyncEngine<R> {
470 471 Ok(())
471 472 }
472 473
474 /// Teams' "Remove chat history": the chat stays hidden until a message newer than the last one.
475 pub async fn remove_chat_history(&self, chat_id: &str) -> Result<()> {
476 let last_message_at = self
477 .store
478 .chat(chat_id)?
479 .and_then(|chat| chat.last_message_at);
480 let cleared_until_ms = cleared_until_ms(last_message_at, Utc::now());
481 self.remote
482 .clear_chat_history(chat_id, cleared_until_ms)
483 .await?;
484 self.with_locally_hidden(|locally| {
485 locally.hide(chat_id, last_message_at.unwrap_or_else(Utc::now))
486 })?;
487 self.store.remove_chats(&[chat_id.to_owned()])?;
488 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
489 Ok(())
490 }
491
492 pub async fn rename_chat(&self, chat_id: &str, topic: &str) -> Result<()> {
493 self.remote.set_chat_topic(chat_id, topic).await?;
494 if let Some(mut chat) = self.store.chat(chat_id)? {
495 chat.title = topic.to_owned();
496 self.store.upsert_chats(std::slice::from_ref(&chat))?;
497 }
498 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
499 Ok(())
500 }
501
473 502 pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
474 503 let user_id = self.my_user_id().await?;
475 504 self.remote.remove_chat_member(chat_id, &user_id).await?;
@@ -9,6 +9,7 @@ use store::MessageRecord;
9use crate::engine::{Conversation, META_USER_ID, SyncEngine};
9use crate::engine::{Conversation, META_USER_ID, SyncEngine};
10use crate::error::{Error, Result};
10use crate::error::{Error, Result};
11use crate::external_image::external_image_url;
11use crate::external_image::external_image_url;
12use crate::hidden_chats::cleared_until_ms;
12use crate::links::LinkPreview;
13use crate::links::LinkPreview;
13use crate::mapping::message_record;
14use crate::mapping::message_record;
14use crate::markdown::markdown_to_html;
15use crate::markdown::markdown_to_html;
@@ -470,6 +471,34 @@ impl<R: Remote> SyncEngine<R> {
470 Ok(())
471 Ok(())
471 }
472 }
472
473
474 /// Teams' "Remove chat history": the chat stays hidden until a message newer than the last one.
475 pub async fn remove_chat_history(&self, chat_id: &str) -> Result<()> {
476 let last_message_at = self
477 .store
478 .chat(chat_id)?
479 .and_then(|chat| chat.last_message_at);
480 let cleared_until_ms = cleared_until_ms(last_message_at, Utc::now());
481 self.remote
482 .clear_chat_history(chat_id, cleared_until_ms)
483 .await?;
484 self.with_locally_hidden(|locally| {
485 locally.hide(chat_id, last_message_at.unwrap_or_else(Utc::now))
486 })?;
487 self.store.remove_chats(&[chat_id.to_owned()])?;
488 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
489 Ok(())
490 }
491
492 pub async fn rename_chat(&self, chat_id: &str, topic: &str) -> Result<()> {
493 self.remote.set_chat_topic(chat_id, topic).await?;
494 if let Some(mut chat) = self.store.chat(chat_id)? {
495 chat.title = topic.to_owned();
496 self.store.upsert_chats(std::slice::from_ref(&chat))?;
497 }
498 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
499 Ok(())
500 }
501
473 pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
502 pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
474 let user_id = self.my_user_id().await?;
503 let user_id = self.my_user_id().await?;
475 self.remote.remove_chat_member(chat_id, &user_id).await?;
504 self.remote.remove_chat_member(chat_id, &user_id).await?;
crates/core/src/hidden_chats.rs +56 −0
@@ -112,6 +112,12 @@ pub(crate) fn resolve_hidden(
112 112 return false;
113 113 }
114 114 }
115 let cleared_until_ms = states
116 .get(&chat.id)
117 .and_then(|state| state.history_cleared_ms);
118 if history_cleared(chat, cleared_until_ms) {
119 return true;
120 }
115 121 if reported == Some(true) {
116 122 locally.hidden_after.remove(&chat.id);
117 123 return true;
@@ -129,6 +135,19 @@ pub(crate) fn resolve_hidden(
129 135 reported.unwrap_or_else(|| graph_hidden(chat))
130 136 }
131 137
138 /// Teams stores the last message time plus one millisecond, or now when the chat has no message.
139 pub(crate) fn cleared_until_ms(last_message_at: Option<DateTime<Utc>>, now: DateTime<Utc>) -> i64 {
140 last_message_at.map_or(now.timestamp_millis(), |last| last.timestamp_millis() + 1)
141 }
142
143 /// Teams hides a chat whose history was removed until a newer message arrives.
144 pub(crate) fn history_cleared(chat: &Chat, cleared_until_ms: Option<i64>) -> bool {
145 cleared_until_ms.is_some_and(|cleared_until_ms| {
146 chat.last_message_time()
147 .is_none_or(|newest| newest.timestamp_millis() <= cleared_until_ms)
148 })
149 }
150
132 151 impl<R: Remote> SyncEngine<R> {
133 152 pub(crate) fn with_locally_hidden<T>(
134 153 &self,
@@ -173,10 +192,47 @@ mod tests {
173 192 muted: false,
174 193 hidden,
175 194 read: chatsvc::ReadHorizon::default(),
195 history_cleared_ms: None,
176 196 },
177 197 )])
178 198 }
179 199
200 #[test]
201 fn removed_history_ends_one_millisecond_after_the_last_message() {
202 let last = at("2026-10-01T10:00:00Z");
203 assert_eq!(
204 cleared_until_ms(Some(last), now()),
205 last.timestamp_millis() + 1
206 );
207 assert_eq!(cleared_until_ms(None, now()), now().timestamp_millis());
208 }
209
210 #[test]
211 fn removed_history_hides_the_chat_until_a_newer_message() {
212 let mut locally = LocallyHidden::default();
213 let cleared_ms = at("2026-10-01T10:00:00Z").timestamp_millis() + 1;
214 let mut cleared = states(Some(false));
215 cleared.get_mut("19:a").unwrap().history_cleared_ms = Some(cleared_ms);
216 assert!(resolve_hidden(
217 &chat(Some("2026-10-01T10:00:00Z"), false),
218 &cleared,
219 &mut locally,
220 now()
221 ));
222 assert!(resolve_hidden(
223 &chat(None, false),
224 &cleared,
225 &mut locally,
226 now()
227 ));
228 assert!(!resolve_hidden(
229 &chat(Some("2026-10-02T08:00:00Z"), false),
230 &cleared,
231 &mut locally,
232 now()
233 ));
234 }
235
180 236 fn hidden_after(text: &str) -> LocallyHidden {
181 237 let mut locally = LocallyHidden::default();
182 238 locally.hide("19:a", at(text));
@@ -112,6 +112,12 @@ pub(crate) fn resolve_hidden(
112 return false;
112 return false;
113 }
113 }
114 }
114 }
115 let cleared_until_ms = states
116 .get(&chat.id)
117 .and_then(|state| state.history_cleared_ms);
118 if history_cleared(chat, cleared_until_ms) {
119 return true;
120 }
115 if reported == Some(true) {
121 if reported == Some(true) {
116 locally.hidden_after.remove(&chat.id);
122 locally.hidden_after.remove(&chat.id);
117 return true;
123 return true;
@@ -129,6 +135,19 @@ pub(crate) fn resolve_hidden(
129 reported.unwrap_or_else(|| graph_hidden(chat))
135 reported.unwrap_or_else(|| graph_hidden(chat))
130}
136}
131
137
138/// Teams stores the last message time plus one millisecond, or now when the chat has no message.
139pub(crate) fn cleared_until_ms(last_message_at: Option<DateTime<Utc>>, now: DateTime<Utc>) -> i64 {
140 last_message_at.map_or(now.timestamp_millis(), |last| last.timestamp_millis() + 1)
141}
142
143/// Teams hides a chat whose history was removed until a newer message arrives.
144pub(crate) fn history_cleared(chat: &Chat, cleared_until_ms: Option<i64>) -> bool {
145 cleared_until_ms.is_some_and(|cleared_until_ms| {
146 chat.last_message_time()
147 .is_none_or(|newest| newest.timestamp_millis() <= cleared_until_ms)
148 })
149}
150
132impl<R: Remote> SyncEngine<R> {
151impl<R: Remote> SyncEngine<R> {
133 pub(crate) fn with_locally_hidden<T>(
152 pub(crate) fn with_locally_hidden<T>(
134 &self,
153 &self,
@@ -173,10 +192,47 @@ mod tests {
173 muted: false,
192 muted: false,
174 hidden,
193 hidden,
175 read: chatsvc::ReadHorizon::default(),
194 read: chatsvc::ReadHorizon::default(),
195 history_cleared_ms: None,
176 },
196 },
177 )])
197 )])
178 }
198 }
179
199
200 #[test]
201 fn removed_history_ends_one_millisecond_after_the_last_message() {
202 let last = at("2026-10-01T10:00:00Z");
203 assert_eq!(
204 cleared_until_ms(Some(last), now()),
205 last.timestamp_millis() + 1
206 );
207 assert_eq!(cleared_until_ms(None, now()), now().timestamp_millis());
208 }
209
210 #[test]
211 fn removed_history_hides_the_chat_until_a_newer_message() {
212 let mut locally = LocallyHidden::default();
213 let cleared_ms = at("2026-10-01T10:00:00Z").timestamp_millis() + 1;
214 let mut cleared = states(Some(false));
215 cleared.get_mut("19:a").unwrap().history_cleared_ms = Some(cleared_ms);
216 assert!(resolve_hidden(
217 &chat(Some("2026-10-01T10:00:00Z"), false),
218 &cleared,
219 &mut locally,
220 now()
221 ));
222 assert!(resolve_hidden(
223 &chat(None, false),
224 &cleared,
225 &mut locally,
226 now()
227 ));
228 assert!(!resolve_hidden(
229 &chat(Some("2026-10-02T08:00:00Z"), false),
230 &cleared,
231 &mut locally,
232 now()
233 ));
234 }
235
180 fn hidden_after(text: &str) -> LocallyHidden {
236 fn hidden_after(text: &str) -> LocallyHidden {
181 let mut locally = LocallyHidden::default();
237 let mut locally = LocallyHidden::default();
182 locally.hide("19:a", at(text));
238 locally.hide("19:a", at(text));
crates/core/src/notes_chat.rs +1 −0
@@ -116,6 +116,7 @@ mod tests {
116 116 last_message_from: Some(format!("8:orgid:{from}")),
117 117 ..ReadHorizon::default()
118 118 },
119 history_cleared_ms: None,
119 120 }
120 121 }
121 122
@@ -116,6 +116,7 @@ mod tests {
116 last_message_from: Some(format!("8:orgid:{from}")),
116 last_message_from: Some(format!("8:orgid:{from}")),
117 ..ReadHorizon::default()
117 ..ReadHorizon::default()
118 },
118 },
119 history_cleared_ms: None,
119 }
120 }
120 }
121 }
121
122
crates/core/src/remote.rs +18 −0
@@ -134,6 +134,12 @@ pub trait Remote {
134 134 share: HistoryShare,
135 135 ) -> Result<()>;
136 136 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
137 async fn clear_chat_history(&self, _chat_id: &str, _cleared_until_ms: i64) -> Result<()> {
138 Err(Error::Unsupported("removing chat history"))
139 }
140 async fn set_chat_topic(&self, _chat_id: &str, _topic: &str) -> Result<()> {
141 Err(Error::Unsupported("renaming a chat"))
142 }
137 143 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
138 144 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
139 145 async fn set_channel_notifications(
@@ -699,6 +705,18 @@ impl Remote for Graph {
699 705 .await?)
700 706 }
701 707
708 async fn clear_chat_history(&self, chat_id: &str, cleared_until_ms: i64) -> Result<()> {
709 Ok(Conversations::new(self.session())
710 .clear_history(chat_id, cleared_until_ms)
711 .await?)
712 }
713
714 async fn set_chat_topic(&self, chat_id: &str, topic: &str) -> Result<()> {
715 Ok(ThreadMembers::new(self.session())
716 .set_topic(chat_id, topic)
717 .await?)
718 }
719
702 720 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
703 721 Ok(Conversations::new(self.session())
704 722 .set_alerts(chat_id, !muted)
@@ -134,6 +134,12 @@ pub trait Remote {
134 share: HistoryShare,
134 share: HistoryShare,
135 ) -> Result<()>;
135 ) -> Result<()>;
136 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
136 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
137 async fn clear_chat_history(&self, _chat_id: &str, _cleared_until_ms: i64) -> Result<()> {
138 Err(Error::Unsupported("removing chat history"))
139 }
140 async fn set_chat_topic(&self, _chat_id: &str, _topic: &str) -> Result<()> {
141 Err(Error::Unsupported("renaming a chat"))
142 }
137 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
143 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
138 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
144 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
139 async fn set_channel_notifications(
145 async fn set_channel_notifications(
@@ -699,6 +705,18 @@ impl Remote for Graph {
699 .await?)
705 .await?)
700 }
706 }
701
707
708 async fn clear_chat_history(&self, chat_id: &str, cleared_until_ms: i64) -> Result<()> {
709 Ok(Conversations::new(self.session())
710 .clear_history(chat_id, cleared_until_ms)
711 .await?)
712 }
713
714 async fn set_chat_topic(&self, chat_id: &str, topic: &str) -> Result<()> {
715 Ok(ThreadMembers::new(self.session())
716 .set_topic(chat_id, topic)
717 .await?)
718 }
719
702 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
720 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
703 Ok(Conversations::new(self.session())
721 Ok(Conversations::new(self.session())
704 .set_alerts(chat_id, !muted)
722 .set_alerts(chat_id, !muted)
crates/core/src/roster_event.rs +41 −0
@@ -6,6 +6,7 @@ use store::{MemberRecord, MessageRecord};
6 6 const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
7 7 const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";
8 8 const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";
9 const CHAT_RENAMED_TYPE: &str = "#microsoft.graph.chatRenamedEventMessageDetail";
9 10 const UNRESOLVED_NAME_PREFIX: &str = "orgid:";
10 11 const DAY_SECONDS: i64 = 86_400;
11 12
@@ -14,6 +15,7 @@ pub enum RosterChange {
14 15 Added,
15 16 Removed,
16 17 Left,
18 Renamed,
17 19 }
18 20
19 21 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
@@ -33,6 +35,8 @@ pub struct RosterEvent {
33 35 pub member_names: Vec<Option<String>>,
34 36 #[serde(default)]
35 37 pub history: SharedHistory,
38 #[serde(default)]
39 pub topic: Option<String>,
36 40 }
37 41
38 42 #[derive(Serialize, Deserialize)]
@@ -67,6 +71,7 @@ impl RosterEvent {
67 71 MEMBERS_LEFT_TYPE => RosterChange::Left,
68 72 MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,
69 73 MEMBERS_DELETED_TYPE => RosterChange::Removed,
74 CHAT_RENAMED_TYPE => RosterChange::Renamed,
70 75 _ => return None,
71 76 };
72 77 let history = match change {
@@ -86,6 +91,12 @@ impl RosterEvent {
86 91 member_ids,
87 92 member_names,
88 93 history,
94 topic: (change == RosterChange::Renamed)
95 .then(|| detail.get("chatDisplayName").and_then(Value::as_str))
96 .flatten()
97 .map(str::trim)
98 .filter(|topic| !topic.is_empty())
99 .map(str::to_owned),
89 100 })
90 101 }
91 102
@@ -114,6 +125,10 @@ impl RosterEvent {
114 125 let targets = join_targets(&targets);
115 126 match self.change {
116 127 RosterChange::Left => format!("{initiator} left the chat."),
128 RosterChange::Renamed => match &self.topic {
129 Some(topic) => format!("{initiator} changed the group name to {topic}."),
130 None => format!("{initiator} removed the group name for this conversation."),
131 },
117 132 RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),
118 133 RosterChange::Added => match self.history {
119 134 SharedHistory::None => format!("{initiator} added {targets} to the chat."),
@@ -210,6 +225,32 @@ mod tests {
210 225 name.or(user_id).unwrap_or("Unknown").to_owned()
211 226 }
212 227
228 #[test]
229 fn a_rename_reads_like_teams() {
230 let renamed = |name: Value| {
231 RosterEvent::from_graph(
232 &json!({
233 "@odata.type": CHAT_RENAMED_TYPE,
234 "chatDisplayName": name,
235 "initiator": {"user": {"id": "me", "displayName": "Daniel"}},
236 }),
237 created(),
238 )
239 .unwrap()
240 };
241 let event = renamed(json!("Release crew"));
242 assert_eq!(event.change, RosterChange::Renamed);
243 assert_eq!(
244 event.text(plain_names),
245 "Daniel changed the group name to Release crew."
246 );
247 assert_eq!(RosterEvent::from_json(&event.to_json()).unwrap(), event);
248 assert_eq!(
249 renamed(json!(null)).text(plain_names),
250 "Daniel removed the group name for this conversation."
251 );
252 }
253
213 254 #[test]
214 255 fn added_without_history_reads_like_teams() {
215 256 let event = added(
@@ -6,6 +6,7 @@ use store::{MemberRecord, MessageRecord};
6const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
6const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
7const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";
7const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";
8const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";
8const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";
9const CHAT_RENAMED_TYPE: &str = "#microsoft.graph.chatRenamedEventMessageDetail";
9const UNRESOLVED_NAME_PREFIX: &str = "orgid:";
10const UNRESOLVED_NAME_PREFIX: &str = "orgid:";
10const DAY_SECONDS: i64 = 86_400;
11const DAY_SECONDS: i64 = 86_400;
11
12
@@ -14,6 +15,7 @@ pub enum RosterChange {
14 Added,
15 Added,
15 Removed,
16 Removed,
16 Left,
17 Left,
18 Renamed,
17}
19}
18
20
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
@@ -33,6 +35,8 @@ pub struct RosterEvent {
33 pub member_names: Vec<Option<String>>,
35 pub member_names: Vec<Option<String>>,
34 #[serde(default)]
36 #[serde(default)]
35 pub history: SharedHistory,
37 pub history: SharedHistory,
38 #[serde(default)]
39 pub topic: Option<String>,
36}
40}
37
41
38#[derive(Serialize, Deserialize)]
42#[derive(Serialize, Deserialize)]
@@ -67,6 +71,7 @@ impl RosterEvent {
67 MEMBERS_LEFT_TYPE => RosterChange::Left,
71 MEMBERS_LEFT_TYPE => RosterChange::Left,
68 MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,
72 MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,
69 MEMBERS_DELETED_TYPE => RosterChange::Removed,
73 MEMBERS_DELETED_TYPE => RosterChange::Removed,
74 CHAT_RENAMED_TYPE => RosterChange::Renamed,
70 _ => return None,
75 _ => return None,
71 };
76 };
72 let history = match change {
77 let history = match change {
@@ -86,6 +91,12 @@ impl RosterEvent {
86 member_ids,
91 member_ids,
87 member_names,
92 member_names,
88 history,
93 history,
94 topic: (change == RosterChange::Renamed)
95 .then(|| detail.get("chatDisplayName").and_then(Value::as_str))
96 .flatten()
97 .map(str::trim)
98 .filter(|topic| !topic.is_empty())
99 .map(str::to_owned),
89 })
100 })
90 }
101 }
91
102
@@ -114,6 +125,10 @@ impl RosterEvent {
114 let targets = join_targets(&targets);
125 let targets = join_targets(&targets);
115 match self.change {
126 match self.change {
116 RosterChange::Left => format!("{initiator} left the chat."),
127 RosterChange::Left => format!("{initiator} left the chat."),
128 RosterChange::Renamed => match &self.topic {
129 Some(topic) => format!("{initiator} changed the group name to {topic}."),
130 None => format!("{initiator} removed the group name for this conversation."),
131 },
117 RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),
132 RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),
118 RosterChange::Added => match self.history {
133 RosterChange::Added => match self.history {
119 SharedHistory::None => format!("{initiator} added {targets} to the chat."),
134 SharedHistory::None => format!("{initiator} added {targets} to the chat."),
@@ -210,6 +225,32 @@ mod tests {
210 name.or(user_id).unwrap_or("Unknown").to_owned()
225 name.or(user_id).unwrap_or("Unknown").to_owned()
211 }
226 }
212
227
228 #[test]
229 fn a_rename_reads_like_teams() {
230 let renamed = |name: Value| {
231 RosterEvent::from_graph(
232 &json!({
233 "@odata.type": CHAT_RENAMED_TYPE,
234 "chatDisplayName": name,
235 "initiator": {"user": {"id": "me", "displayName": "Daniel"}},
236 }),
237 created(),
238 )
239 .unwrap()
240 };
241 let event = renamed(json!("Release crew"));
242 assert_eq!(event.change, RosterChange::Renamed);
243 assert_eq!(
244 event.text(plain_names),
245 "Daniel changed the group name to Release crew."
246 );
247 assert_eq!(RosterEvent::from_json(&event.to_json()).unwrap(), event);
248 assert_eq!(
249 renamed(json!(null)).text(plain_names),
250 "Daniel removed the group name for this conversation."
251 );
252 }
253
213 #[test]
254 #[test]
214 fn added_without_history_reads_like_teams() {
255 fn added_without_history_reads_like_teams() {
215 let event = added(
256 let event = added(
crates/core/tests/engine.rs +3 −0
@@ -582,6 +582,7 @@ impl Remote for Handle {
582 582 muted,
583 583 hidden: None,
584 584 read: chatsvc::ReadHorizon::default(),
585 history_cleared_ms: None,
585 586 })
586 587 .collect();
587 588 states.extend(
@@ -592,6 +593,7 @@ impl Remote for Handle {
592 593 muted: false,
593 594 hidden: Some(hidden),
594 595 read: chatsvc::ReadHorizon::default(),
596 history_cleared_ms: None,
595 597 }),
596 598 );
597 599 let read = self.read_states.lock().unwrap().clone();
@@ -602,6 +604,7 @@ impl Remote for Handle {
602 604 muted: false,
603 605 hidden: None,
604 606 read,
607 history_cleared_ms: None,
605 608 }),
606 609 );
607 610 Ok(states)
@@ -582,6 +582,7 @@ impl Remote for Handle {
582 muted,
582 muted,
583 hidden: None,
583 hidden: None,
584 read: chatsvc::ReadHorizon::default(),
584 read: chatsvc::ReadHorizon::default(),
585 history_cleared_ms: None,
585 })
586 })
586 .collect();
587 .collect();
587 states.extend(
588 states.extend(
@@ -592,6 +593,7 @@ impl Remote for Handle {
592 muted: false,
593 muted: false,
593 hidden: Some(hidden),
594 hidden: Some(hidden),
594 read: chatsvc::ReadHorizon::default(),
595 read: chatsvc::ReadHorizon::default(),
596 history_cleared_ms: None,
595 }),
597 }),
596 );
598 );
597 let read = self.read_states.lock().unwrap().clone();
599 let read = self.read_states.lock().unwrap().clone();
@@ -602,6 +604,7 @@ impl Remote for Handle {
602 muted: false,
604 muted: false,
603 hidden: None,
605 hidden: None,
604 read,
606 read,
607 history_cleared_ms: None,
605 }),
608 }),
606 );
609 );
607 Ok(states)
610 Ok(states)