BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / app_state.rs

app_state.rs

app_state.rs 46.7 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3use std::time::Instant;
4
5use chatsvc::TypingEvent;
6use chrono::{DateTime, Utc};
7use gpui_kit::*;
8use store::{ChatRecord, Sidebar, Store};
9use teams_core::{
10 ChatApp, ChatSection, ChatSectionSettings, CoreEvent, ImageRef, PinnedMessage, PresenceStatus,
11 ScheduledDraft,
12};
13
14use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
15use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
16use crate::card_state::{CardState, TaskDialogState};
17use crate::data::{self, Directory};
18use crate::forward_selection::ForwardSelection;
19use crate::image_view_gallery::ViewerRequest;
20use crate::local_previews::{LocalPreview, load_local_previews};
21use crate::message_actions::{ForwardSource, SavedSet};
22use crate::notice::Notice;
23use crate::notify::LateArrivals;
24use crate::profile_state::{ProfileCache, ProfileRequest};
25use crate::translation::TranslationState;
26use crate::typing::TypingState;
27use calling::meeting::LiveMeeting;
28
29const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
30const RECENT_MESSAGES_FOR_TYPING: usize = 5;
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum Selection {
34 Chat(String),
35 Channel(String),
36}
37
38impl Selection {
39 pub fn conversation_id(&self) -> &str {
40 match self {
41 Selection::Chat(id) | Selection::Channel(id) => id,
42 }
43 }
44}
45
46pub enum AppEvent {
47 Sidebar,
48 Activity,
49 Selection,
50 Messages(String),
51 Images(Vec<String>),
52 Jump,
53 Status,
54 Directory,
55 Cards(String),
56 TaskDialog,
57 Typing,
58 LocalPreviews,
59 Outbox(String),
60 Scheduled,
61 Pins(String),
62 Saved,
63 CallHistory,
64 Translation,
65 Forward,
66 ForwardSelection,
67 ImageViewer,
68 StatusMessage,
69 Settings(crate::settings_section::SettingsSection),
70 Profile,
71 Call,
72 Ring,
73 LiveMeeting,
74 MissedCall(MissedCall),
75 MeetingReminder,
76 MeetingChime,
77 CallTone(chatsvc::sounds::CallTone),
78 SoundSettings,
79 ChatSettings,
80 FollowedStatus {
81 user_id: String,
82 text: &'static str,
83 },
84}
85
86#[derive(Debug, Clone, Copy, Default)]
87pub struct Mode {
88 pub demo: bool,
89 pub read_only: bool,
90 pub demo_sync: Option<std::time::Duration>,
91}
92
93pub struct AppState {
94 pub store: Arc<Store>,
95 pub engine: Option<Arc<Engine>>,
96 pub sidebar: Sidebar,
97 pub favorite_ids: Vec<String>,
98 pub selection: Option<Selection>,
99 pub late_arrivals: LateArrivals,
100 pub acked_urgent: std::collections::HashSet<String>,
101 pub new_chat: bool,
102 pub new_chat_people: Vec<store::MemberRecord>,
103 pub connection: ConnectionState,
104 pub live: LiveState,
105 pub last_sync: Option<DateTime<Utc>>,
106 pub mode: Mode,
107 pub directory: Directory,
108 pub collapsed: HashSet<String>,
109 pub expanded_lists: HashSet<String>,
110 pub start_on_channels: bool,
111 pub pending_jump: Option<(String, String)>,
112 pub cards: CardState,
113 pub task_dialog: Option<TaskDialogState>,
114 pub bot_apps: HashMap<String, Vec<ChatApp>>,
115 pub bot_apps_pending: HashSet<String>,
116 pub notice: Option<Notice>,
117 pub connection_banner: crate::connection_banner::BannerTiming,
118 pub live_retry: Option<Arc<tokio::sync::Notify>>,
119 pub notice_count: u64,
120 pub followed_presence: Vec<crate::presence_follow::FollowedPerson>,
121 pub followed_changes: Vec<(String, &'static str)>,
122 pub keep_unread: Option<String>,
123 pub restorable_deletes: crate::restorable_deletes::RestorableDeletes,
124 pub typing: TypingState,
125 typing_timer_running: bool,
126 pub local_previews: HashMap<String, LocalPreview>,
127 pub scheduled: Vec<ScheduledDraft>,
128 pub scheduled_polling: bool,
129 pub saved: SavedSet,
130 pub call_history: Vec<teams_core::CallLogEntry>,
131 pub calendar_events: Vec<chatsvc::CalendarEvent>,
132 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
133 pub calls_list: crate::call::CallsList,
134 pub pins: HashMap<String, Vec<PinnedMessage>>,
135 pub post_follows: crate::post_follow::PostFollows,
136 pub forward_request: Option<ForwardSource>,
137 pub forward_selection: Option<ForwardSelection>,
138 pub image_viewer_request: Option<ViewerRequest>,
139 pub own_status: PresenceStatus,
140 pub own_email: String,
141 pub own_time_zone: Option<String>,
142 pub own_time_zone_requested: bool,
143 pub status_menu_open: bool,
144 pub status_message_request: bool,
145 pub profiles: ProfileCache,
146 pub profile_request: Option<ProfileRequest>,
147 pub call: Option<ActiveCall>,
148 pub held_call: Option<ActiveCall>,
149 pub call_end: Option<crate::call::end_screen::CallEndScreen>,
150 pub call_media: Option<Entity<CallMedia>>,
151 pub call_launcher: Option<Arc<CallLauncher>>,
152 pub call_count: u64,
153 pub call_share_sound: bool,
154 pub recording_policy: teams_core::RecordingPolicy,
155 pub allow_priority_messages: bool,
156 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
157 pub chat_settings: teams_core::ChatSettingsDocument,
158 pub markdown_mode: bool,
159 pub actions_on_right_click: bool,
160 pub web_calls: bool,
161 pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,
162 pub own_tenant: Option<String>,
163 pub call_share_motion: bool,
164 pub call_share_standout: bool,
165 pub call_report_enabled: bool,
166 pub call_strip_width: f32,
167 pub call_view: crate::call::ViewSettings,
168 pub call_background: crate::call::BackgroundPick,
169 pub call_camera: calling::DeviceChoice,
170 pub call_input: calling::DeviceChoice,
171 pub call_output: calling::DeviceChoice,
172 pub call_mic: calling::MicSettings,
173 pub call_effects: calling::CameraEffects,
174 pub meet_now_pending: bool,
175 pub prejoin: Option<crate::call::PendingJoin>,
176 pub prejoin_count: u64,
177 pub join_options: crate::call::JoinOptions,
178 pub rsvp_send_response: bool,
179 pub meeting_toasts: crate::call::MeetingToasts,
180 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
181 pub call_backgrounds: crate::call::BackgroundLibrary,
182 pub transfer_picker: Option<AnyView>,
183 pub transcript_panel: Option<AnyView>,
184 pub rings: Rings,
185 pub live_meetings: HashMap<String, LiveMeeting>,
186 pub live_refreshing: HashSet<String>,
187 pub translation: TranslationState,
188 pub section_changes: crate::section_actions::SectionChanges,
189}
190
191pub struct AppHandle(pub Entity<AppState>);
192
193impl Global for AppHandle {}
194
195impl EventEmitter<AppEvent> for AppState {}
196
197pub fn selection_for(sidebar: &Sidebar, conversation_id: &str) -> Option<Selection> {
198 if sidebar.chats.iter().any(|chat| chat.id == conversation_id) {
199 return Some(Selection::Chat(conversation_id.to_owned()));
200 }
201 sidebar
202 .teams
203 .iter()
204 .flat_map(|team| team.channels.iter())
205 .any(|channel| channel.id == conversation_id)
206 .then(|| Selection::Channel(conversation_id.to_owned()))
207}
208
209pub fn chat_title(chat: &ChatRecord) -> String {
210 chat.display_title()
211}
212
213pub fn composer_name(sidebar: &Sidebar, selection: &Selection) -> String {
214 let unnamed_group = match selection {
215 Selection::Chat(id) => sidebar.chats.iter().any(|chat| {
216 &chat.id == id
217 && chat.title.trim().is_empty()
218 && !chat.kind.eq_ignore_ascii_case("oneOnOne")
219 }),
220 Selection::Channel(_) => false,
221 };
222 if unnamed_group {
223 String::new()
224 } else {
225 selection_title(sidebar, selection)
226 }
227}
228
229pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
230 match selection {
231 Selection::Chat(id) => sidebar
232 .chats
233 .iter()
234 .find(|chat| &chat.id == id)
235 .map(chat_title)
236 .unwrap_or_else(|| "Chat".to_owned()),
237 Selection::Channel(id) => sidebar
238 .teams
239 .iter()
240 .find_map(|team| {
241 team.channels
242 .iter()
243 .find(|channel| &channel.id == id)
244 .map(|channel| format!("{} / {}", team.team.name, channel.name))
245 })
246 .unwrap_or_else(|| "Channel".to_owned()),
247 }
248}
249
250impl AppState {
251 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
252 let sidebar = store.sidebar().unwrap_or_default();
253 let chat_settings = teams_core::stored_chat_settings(&store);
254 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
255 let actions_on_right_click =
256 crate::chat_settings_actions::stored_actions_on_right_click(&store);
257 let web_calls = crate::call::web_call::stored_web_calls(&store);
258 let mut state = AppState {
259 store,
260 engine: None,
261 sidebar,
262 favorite_ids: Vec::new(),
263 selection: None,
264 late_arrivals: LateArrivals::default(),
265 acked_urgent: Default::default(),
266 new_chat: false,
267 new_chat_people: Vec::new(),
268 connection: if mode.demo {
269 ConnectionState::Online
270 } else {
271 ConnectionState::Connecting
272 },
273 live: LiveState::Off,
274 last_sync: None,
275 mode,
276 directory: Directory::default(),
277 collapsed: HashSet::new(),
278 expanded_lists: HashSet::new(),
279 start_on_channels: false,
280 pending_jump: None,
281 cards: CardState::default(),
282 task_dialog: None,
283 bot_apps: HashMap::new(),
284 bot_apps_pending: HashSet::new(),
285 notice: None,
286 connection_banner: Default::default(),
287 live_retry: None,
288 notice_count: 0,
289 followed_presence: Vec::new(),
290 followed_changes: Vec::new(),
291 keep_unread: None,
292 restorable_deletes: Default::default(),
293 typing: TypingState::default(),
294 typing_timer_running: false,
295 local_previews: HashMap::new(),
296 scheduled: Vec::new(),
297 scheduled_polling: false,
298 saved: SavedSet::default(),
299 call_history: Vec::new(),
300 calendar_events: Vec::new(),
301 calendar_nudge: None,
302 calls_list: crate::call::CallsList::default(),
303 pins: HashMap::new(),
304 post_follows: Default::default(),
305 forward_request: None,
306 forward_selection: None,
307 image_viewer_request: None,
308 own_status: PresenceStatus::default(),
309 own_email: String::new(),
310 own_time_zone: None,
311 own_time_zone_requested: false,
312 status_menu_open: false,
313 status_message_request: false,
314 profiles: ProfileCache::new(),
315 profile_request: None,
316 call: None,
317 call_end: None,
318 held_call: None,
319 call_media: None,
320 call_launcher: None,
321 call_count: 0,
322 call_share_sound: false,
323 recording_policy: teams_core::RecordingPolicy::default(),
324 allow_priority_messages: true,
325 account_sounds: None,
326 chat_settings,
327 markdown_mode,
328 actions_on_right_click,
329 web_calls,
330 demo_chat_desktop: HashMap::new(),
331 own_tenant: None,
332 call_share_motion: false,
333 call_share_standout: false,
334 call_report_enabled: true,
335 call_strip_width: crate::call::STRIP_DEFAULT_WIDTH,
336 call_view: crate::call::ViewSettings::default(),
337 call_background: crate::call::BackgroundPick::None,
338 call_camera: calling::DeviceChoice::SystemDefault,
339 call_input: calling::DeviceChoice::SystemDefault,
340 call_output: calling::DeviceChoice::SystemDefault,
341 call_mic: calling::MicSettings::default(),
342 call_effects: calling::CameraEffects::default(),
343 meet_now_pending: false,
344 prejoin: None,
345 prejoin_count: 0,
346 join_options: crate::call::JoinOptions::default(),
347 rsvp_send_response: true,
348 meeting_toasts: crate::call::MeetingToasts::default(),
349 demo_meetings: Vec::new(),
350 call_backgrounds: if mode.demo {
351 crate::call::demo_library()
352 } else {
353 crate::call::BackgroundLibrary::new(crate::call::default_cache_directory())
354 },
355 transfer_picker: None,
356 transcript_panel: None,
357 rings: Rings::default(),
358 live_meetings: HashMap::new(),
359 live_refreshing: HashSet::new(),
360 translation: TranslationState::default(),
361 section_changes: crate::section_actions::SectionChanges::default(),
362 };
363 state.local_previews = load_local_previews(&state.store);
364 state.followed_presence = crate::presence_follow::load_followed(&state.store);
365 state.collapsed = state.load_collapsed();
366 state.call_share_sound = crate::call::load_share_sound(&state.store);
367 state.call_share_motion = crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY);
368 state.call_share_standout = crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY);
369 state.call_report_enabled = crate::call::load_report_enabled(&state.store);
370 state.call_strip_width = crate::call::load_strip_width(&state.store);
371 state.call_view = crate::call::ViewSettings::load(&state.store);
372 state.call_background = crate::call::load_background(&state.store);
373 state.call_camera = crate::call::load_camera(&state.store);
374 state.call_input = crate::call::load_input(&state.store);
375 state.call_output = crate::call::load_output(&state.store);
376 crate::call::apply_sound_output(&state.call_output);
377 state.call_mic = crate::call::load_mic(&state.store);
378 state.call_effects = crate::call::load_camera_effects(&state.store);
379 state.join_options = crate::call::load_join_options(&state.store);
380 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
381 state.load_cached_translation_settings();
382 if !mode.demo {
383 state.directory.load_cached_presence(&state.store);
384 state.reload_directory();
385 }
386 state
387 }
388
389 fn load_collapsed(&self) -> HashSet<String> {
390 self.store
391 .meta(COLLAPSED_META_KEY)
392 .ok()
393 .flatten()
394 .map(|value| {
395 value
396 .lines()
397 .map(str::to_owned)
398 .filter(|id| !id.is_empty())
399 .collect()
400 })
401 .unwrap_or_default()
402 }
403
404 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
405 if data::is_pending_folder(section_id) {
406 return;
407 }
408 let now_collapsed = self.collapsed.insert(section_id.to_owned());
409 if !now_collapsed {
410 self.collapsed.remove(section_id);
411 }
412 self.save_collapsed();
413 self.sync_folder_expanded(section_id, !now_collapsed);
414 cx.emit(AppEvent::Sidebar);
415 cx.notify();
416 }
417
418 pub fn older_chats(&self) -> (bool, bool) {
419 self.engine.as_ref().map_or((false, false), |engine| {
420 (engine.has_older_chats(), engine.is_loading_older_chats())
421 })
422 }
423
424 pub fn request_older_chats(&self) {
425 let Some(engine) = self.engine.clone() else {
426 return;
427 };
428 if !engine.has_older_chats() || engine.is_loading_older_chats() {
429 return;
430 }
431 drop(crate::runtime::spawn(async move {
432 if let Err(error) = engine.load_older_chats().await {
433 crate::diagnostics::record(format!("sync: older chats not loaded: {error}"));
434 }
435 }));
436 }
437
438 pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) {
439 if !self.expanded_lists.remove(section_id) {
440 self.expanded_lists.insert(section_id.to_owned());
441 }
442 cx.emit(AppEvent::Sidebar);
443 cx.notify();
444 }
445
446 fn save_collapsed(&self) {
447 let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect();
448 ids.sort_unstable();
449 let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n"));
450 }
451
452 fn sync_folder_expanded(&mut self, folder_id: &str, expanded: bool) {
453 let Some(folder) = self
454 .directory
455 .folders
456 .iter_mut()
457 .find(|folder| folder.id == folder_id && folder.expanded.is_some())
458 else {
459 return;
460 };
461 folder.expanded = Some(expanded);
462 let _ = self.store.set_folder_expanded(folder_id, expanded);
463 if let Some(engine) = self.engine.clone().filter(|_| !self.mode.read_only) {
464 let folder_id = folder_id.to_owned();
465 drop(crate::runtime::spawn(async move {
466 engine.set_folder_expanded(&folder_id, expanded).await
467 }));
468 }
469 }
470
471 fn adopt_folder_expanded(&mut self) {
472 let snapshot = self.collapsed.clone();
473 for folder in &self.directory.folders {
474 match folder.expanded {
475 Some(true) => {
476 self.collapsed.remove(&folder.id);
477 }
478 Some(false) => {
479 self.collapsed.insert(folder.id.clone());
480 }
481 None => {}
482 }
483 }
484 if self.collapsed != snapshot {
485 self.save_collapsed();
486 }
487 }
488
489 pub fn set_chat_section(
490 &mut self,
491 section: ChatSection,
492 enabled: bool,
493 cx: &mut Context<Self>,
494 ) {
495 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
496 return;
497 };
498 let previous = self.directory.section_settings;
499 let mut updated = previous;
500 updated.set(section, enabled);
501 self.apply_section_settings(updated, cx);
502 let Some(engine) = engine_or_demo else {
503 return;
504 };
505 self.run_chat_action(
506 "Chat list setting",
507 async move { engine.set_section_enabled(section, enabled).await },
508 move |state, cx| state.apply_section_settings(previous, cx),
509 |_, _| {},
510 cx,
511 );
512 }
513
514 pub fn set_skin_tone(&mut self, tone: u8, cx: &mut Context<Self>) {
515 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
516 return;
517 };
518 let previous = teams_core::skin_tone(&self.store);
519 let _ = teams_core::store_account_skin_tone(&self.store, tone);
520 let Some(engine) = engine_or_demo else {
521 return;
522 };
523 self.run_chat_action(
524 "Skin tone",
525 async move { engine.set_skin_tone(tone).await },
526 move |state, _| {
527 let _ = teams_core::store_account_skin_tone(&state.store, previous);
528 },
529 |_, _| {},
530 cx,
531 );
532 }
533
534 fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) {
535 self.directory.section_settings = settings;
536 let _ = teams_core::store_section_settings(&self.store, &settings);
537 cx.emit(AppEvent::Sidebar);
538 cx.notify();
539 }
540
541 pub fn reload_directory(&mut self) {
542 self.directory.me = data::me(&self.store);
543 self.own_email = self
544 .store
545 .meta("me_email")
546 .ok()
547 .flatten()
548 .unwrap_or_default();
549 self.directory.folders = data::folders(&self.store, &self.favorite_ids);
550 self.reapply_section_changes();
551 self.directory.section_settings = teams_core::stored_section_settings(&self.store);
552 self.adopt_folder_expanded();
553 self.directory.pinned_channels = data::pinned_channels(&self.store);
554 if self.directory.pinned_channels.is_empty() {
555 let known: HashSet<&str> = self
556 .sidebar
557 .teams
558 .iter()
559 .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str()))
560 .collect();
561 self.directory.pinned_channels = self
562 .favorite_ids
563 .iter()
564 .filter(|id| known.contains(id.as_str()))
565 .cloned()
566 .collect();
567 }
568 self.resolve_pending_avatars();
569 self.sync_presence();
570 self.directory.unread_counts = match &self.engine {
571 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
572 None => Default::default(),
573 };
574 self.directory.unread_importance = match &self.engine {
575 Some(engine) => data::unread_importance(engine, &self.sidebar.chats),
576 None => Default::default(),
577 };
578 }
579
580 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
581 let wanted = self.directory.missing_avatars(user_ids);
582 if wanted.is_empty() {
583 return;
584 }
585 let mut changed = false;
586 let mut uncached = Vec::new();
587 for user_id in wanted {
588 match data::cached_avatar(&self.store, &user_id) {
589 Some(cached) => {
590 self.directory.set_avatar(&user_id, cached);
591 changed = true;
592 }
593 None => uncached.push(user_id),
594 }
595 }
596 if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) {
597 self.directory.mark_avatars_pending(&uncached);
598 let done = data::fetch_avatars(&engine, uncached);
599 self.on_done(done, cx, |state, cx| {
600 state.resolve_pending_avatars();
601 cx.emit(AppEvent::Directory);
602 cx.notify();
603 });
604 changed = true;
605 }
606 if changed {
607 cx.emit(AppEvent::Directory);
608 cx.notify();
609 }
610 }
611
612 pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) {
613 let Some(engine) = self.engine.clone() else {
614 return;
615 };
616 let wanted = self
617 .directory
618 .images_to_request(images.iter().map(|image| image.url.clone()));
619 let mut changed = false;
620 for image in images
621 .into_iter()
622 .filter(|image| wanted.contains(&image.url))
623 {
624 match engine.image_path(&image) {
625 Some(path) => {
626 self.directory.set_image(&image.url, &path);
627 changed = true;
628 }
629 None => {
630 let done = data::fetch_image(&engine, image.clone());
631 cx.spawn(async move |this, cx| {
632 let failure = match done.await {
633 Ok(Ok(())) => None,
634 Ok(Err(error)) => Some(error),
635 Err(_) => Some("cancelled".to_owned()),
636 };
637 if let Some(failure) = failure {
638 let host = image.url.split("://").nth(1).and_then(|rest| rest.split('/').next()).unwrap_or_default();
639 log::warn!("image from {host} not loaded: {failure}");
640 this.update(cx, |state, cx| {
641 state.directory.mark_image_failed(&image.url);
642 cx.notify();
643 })
644 .ok();
645 }
646 })
647 .detach();
648 }
649 }
650 }
651 if changed {
652 cx.emit(AppEvent::Images(wanted));
653 cx.notify();
654 }
655 }
656
657 pub fn jump_to_message(
658 &mut self,
659 selection: Selection,
660 message_id: String,
661 cx: &mut Context<Self>,
662 ) {
663 self.pending_jump = Some((selection.conversation_id().to_owned(), message_id));
664 if self.selection.as_ref() == Some(&selection) {
665 cx.emit(AppEvent::Jump);
666 } else {
667 self.select(selection, cx);
668 }
669 }
670
671 fn on_done(
672 &self,
673 done: data::Done,
674 cx: &mut Context<Self>,
675 then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
676 ) {
677 cx.spawn(async move |this, cx| {
678 let _ = done.await;
679 this.update(cx, |state, cx| then(state, cx)).ok();
680 })
681 .detach();
682 }
683
684 fn resolve_pending_avatars(&mut self) {
685 for user_id in self.directory.pending_avatars() {
686 if let Some(cached) = data::cached_avatar(&self.store, &user_id) {
687 self.directory.set_avatar(&user_id, cached);
688 }
689 }
690 }
691
692 fn sync_presence(&mut self) -> Vec<String> {
693 let Some(engine) = self.engine.clone() else {
694 return Vec::new();
695 };
696 self.directory
697 .requested_presence_ids()
698 .into_iter()
699 .filter(|user_id| {
700 let Some(kind) = data::presence_kind(&engine, user_id) else {
701 return false;
702 };
703 let activity_changed = self
704 .directory
705 .set_activity(user_id, data::presence_activity(&engine, user_id));
706 let previous = self.directory.presence_of(user_id);
707 let changed = self.directory.set_presence(user_id, kind);
708 if changed {
709 self.note_followed_change(user_id, previous, kind);
710 }
711 changed || activity_changed
712 })
713 .collect()
714 }
715
716 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
717 let now = Instant::now();
718 let pushed = self.live == LiveState::Live;
719 let wanted = self.directory.stale_presence(user_ids, now, pushed);
720 if wanted.is_empty() {
721 return;
722 }
723 self.directory.mark_presence_pending(&wanted);
724 if let Some(engine) = self.engine.clone() {
725 self.directory.mark_presence_requested(&wanted, now);
726 drop(data::watch_presence(&engine, wanted.clone()));
727 let done = data::refresh_presence(&engine, wanted.clone());
728 self.on_done(done, cx, move |state, cx| {
729 state.sync_presence();
730 state.announce_followed_changes(cx);
731 state.directory.save_presence(&state.store, &wanted);
732 state.directory.settle_presence(&wanted);
733 cx.emit(AppEvent::Directory);
734 cx.notify();
735 });
736 }
737 }
738
739 pub fn move_chat(
740 &mut self,
741 conversation_id: &str,
742 folder_id: Option<&str>,
743 cx: &mut Context<Self>,
744 ) {
745 self.place_chat(conversation_id, folder_id, None, cx);
746 }
747
748 pub fn drop_chat_on(
749 &mut self,
750 conversation_id: &str,
751 target_conversation_id: &str,
752 folder_id: &str,
753 cx: &mut Context<Self>,
754 ) {
755 if conversation_id == target_conversation_id {
756 return;
757 }
758 let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else {
759 return;
760 };
761 self.place_chat(conversation_id, Some(folder_id), Some(slot), cx);
762 }
763
764 pub fn place_chat(
765 &mut self,
766 conversation_id: &str,
767 folder_id: Option<&str>,
768 index: Option<usize>,
769 cx: &mut Context<Self>,
770 ) {
771 if self.mode.read_only {
772 return;
773 }
774 let previous_folder = self
775 .directory
776 .folder_of(conversation_id)
777 .map(|folder| folder.id.clone());
778 self.directory.place(conversation_id, folder_id, index);
779 if let Some(engine) = self.engine.clone() {
780 let previous = previous_folder.clone();
781 let done = match (folder_id, previous.as_deref()) {
782 (Some(folder_id), _) => Some(data::move_to_folder(
783 &engine,
784 conversation_id,
785 folder_id,
786 index,
787 )),
788 (None, Some(previous)) => {
789 Some(data::remove_from_folder(&engine, conversation_id, previous))
790 }
791 (None, None) => None,
792 };
793 if let Some(done) = done {
794 self.on_done(done, cx, |state, cx| {
795 state.reload_directory();
796 cx.emit(AppEvent::Sidebar);
797 cx.notify();
798 });
799 }
800 }
801 cx.emit(AppEvent::Sidebar);
802 cx.notify();
803 }
804
805 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
806 if self.keeps_unread(conversation_id) {
807 self.keep_unread = None;
808 }
809 if self.mode.demo {
810 if let Some(chat) = self
811 .sidebar
812 .chats
813 .iter()
814 .find(|chat| chat.id == conversation_id)
815 {
816 let mut read = chat.clone();
817 read.unread = false;
818 let _ = self.store.upsert_chats(&[read]);
819 self.reload_sidebar(cx);
820 }
821 return;
822 }
823 if self.mode.read_only {
824 return;
825 }
826 if let Some(engine) = self.engine.clone() {
827 let _ = self
828 .store
829 .mark_chat_read(conversation_id, chrono::Utc::now());
830 self.reload_sidebar(cx);
831 let conversation_id = conversation_id.to_owned();
832 drop(crate::runtime::spawn(async move {
833 engine.mark_read(&conversation_id).await
834 }));
835 }
836 }
837
838 pub fn mark_channel_read(&mut self, channel_id: &str, cx: &mut Context<Self>) {
839 if self.mode.read_only {
840 return;
841 }
842 let _ = self.store.mark_channel_read(channel_id);
843 self.reload_sidebar(cx);
844 if self.mode.demo {
845 return;
846 }
847 if let Some(engine) = self.engine.clone() {
848 let channel_id = channel_id.to_owned();
849 drop(crate::runtime::spawn(async move {
850 engine.mark_read(&channel_id).await
851 }));
852 }
853 }
854
855 pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) {
856 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
857 return;
858 };
859 let previous_unread: Vec<store::ChannelReadState> = self
860 .sidebar
861 .teams
862 .iter()
863 .flat_map(|team| team.channels.iter())
864 .map(|channel| store::ChannelReadState {
865 channel_id: channel.id.clone(),
866 unread: channel.unread,
867 last_message_at: None,
868 read_until: None,
869 })
870 .collect();
871 let previous_mentions: Vec<(String, store::ChannelMentions)> = self
872 .sidebar
873 .teams
874 .iter()
875 .flat_map(|team| team.mentions.iter())
876 .map(|(channel_id, mentions)| (channel_id.clone(), *mentions))
877 .collect();
878 let _ = self.store.mark_all_channels_read();
879 self.reload_sidebar(cx);
880 let Some(engine) = engine_or_demo else {
881 return;
882 };
883 self.run_chat_action(
884 "Mark all as read",
885 async move { engine.mark_all_channels_read().await },
886 move |state, cx| {
887 let _ = state.store.apply_channel_read_states(&previous_unread);
888 let _ = state.store.replace_channel_mentions(&previous_mentions);
889 state.reload_sidebar(cx);
890 },
891 |_, _| {},
892 cx,
893 );
894 }
895
896 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
897 self.new_chat = true;
898 self.show_call(false, cx);
899 cx.emit(AppEvent::Selection);
900 cx.notify();
901 }
902
903 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
904 if !self.new_chat {
905 return;
906 }
907 self.new_chat = false;
908 cx.emit(AppEvent::Selection);
909 cx.notify();
910 }
911
912 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
913 self.show_call(false, cx);
914 self.cancel_prejoin(cx);
915 self.call_end = None;
916 let was_drafting = std::mem::take(&mut self.new_chat);
917 if !was_drafting && self.selection.as_ref() == Some(&selection) {
918 return;
919 }
920 let conversation_id = selection.conversation_id().to_owned();
921 self.selection = Some(selection);
922 self.keep_unread = None;
923 self.forward_selection = None;
924 cx.emit(AppEvent::Selection);
925 cx.notify();
926 self.refresh_live_meeting(&conversation_id, cx);
927 self.refresh_language_stamps(&conversation_id, cx);
928 }
929
930 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
931 let is_me = self
932 .directory
933 .me
934 .as_ref()
935 .is_some_and(|me| me.user_id == event.user_id);
936 if is_me {
937 return;
938 }
939 if event.active {
940 let display_name = match event.display_name.trim() {
941 "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id))
942 .remove(&event.user_id)
943 .unwrap_or_default(),
944 _ => event.display_name.clone(),
945 };
946 self.typing.start(
947 &event.conversation_id,
948 &event.user_id,
949 &display_name,
950 Instant::now(),
951 event.received_at,
952 );
953 self.request_avatars(vec![event.user_id.clone()], cx);
954 self.schedule_typing_expiry(cx);
955 } else {
956 self.typing.clear(&event.conversation_id, &event.user_id);
957 }
958 cx.emit(AppEvent::Typing);
959 cx.notify();
960 }
961
962 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
963 if !self.typing.is_active(conversation_id) {
964 return;
965 }
966 let Ok(recent) = self
967 .store
968 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
969 else {
970 return;
971 };
972 let mut changed = false;
973 for message in recent {
974 if let Some(sender_id) = message.sender_id.as_deref() {
975 changed |= self
976 .typing
977 .message_from(conversation_id, sender_id, message.created_at);
978 }
979 }
980 if changed {
981 cx.emit(AppEvent::Typing);
982 cx.notify();
983 }
984 }
985
986 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
987 if self.typing_timer_running {
988 return;
989 }
990 self.typing_timer_running = true;
991 cx.spawn(async move |this, cx| {
992 loop {
993 let next = this.update(cx, |state, _| {
994 let next = state.typing.next_expiry();
995 state.typing_timer_running = next.is_some();
996 next
997 });
998 let Ok(Some(next)) = next else { return };
999 cx.background_executor()
1000 .timer(next.saturating_duration_since(Instant::now()))
1001 .await;
1002 let alive = this.update(cx, |state, cx| {
1003 if state.typing.expire(Instant::now()) {
1004 cx.emit(AppEvent::Typing);
1005 cx.notify();
1006 }
1007 });
1008 if alive.is_err() {
1009 return;
1010 }
1011 }
1012 })
1013 .detach();
1014 }
1015
1016 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
1017 if let Ok(sidebar) = self.store.sidebar() {
1018 self.sidebar = sidebar;
1019 self.apply_bot_titles();
1020 }
1021 self.calls_list.invalidate();
1022 if !self.mode.demo {
1023 self.reload_directory();
1024 self.load_own_time_zone(cx);
1025 }
1026 cx.emit(AppEvent::Sidebar);
1027 cx.notify();
1028 }
1029
1030 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
1031 match event {
1032 BackendEvent::Connection(connection) => {
1033 self.connection = connection;
1034 self.refresh_connection_banner(cx);
1035 cx.emit(AppEvent::Status);
1036 }
1037 BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry),
1038 BackendEvent::Calls(launcher) => {
1039 launcher.set_default_camera(self.call_camera.clone());
1040 self.call_launcher = Some(launcher);
1041 self.load_own_time_zone(cx);
1042 }
1043 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
1044 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
1045 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
1046 BackendEvent::ThreadChanged(conversation_id) => {
1047 self.on_thread_changed(&conversation_id, cx)
1048 }
1049 BackendEvent::Engine(engine) => {
1050 crate::agent_api::engine_ready(engine.clone(), cx);
1051 self.engine = Some(engine);
1052 self.resend_outbox(cx);
1053 self.refresh_scheduled(cx);
1054 self.refresh_translation_settings(cx);
1055 self.refresh_recording_policy(cx);
1056 self.refresh_messaging_policy(cx);
1057 self.refresh_sound_settings(cx);
1058 self.refresh_chat_settings(cx);
1059 let waiting = self.directory.waiting_presence_ids();
1060 self.request_presence(waiting, cx);
1061 self.watch_followed_presence(cx);
1062 self.refresh_own_status(cx);
1063 cx.emit(AppEvent::Status);
1064 }
1065 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
1066 BackendEvent::Core(CoreEvent::ActivityChanged) => cx.emit(AppEvent::Activity),
1067 BackendEvent::Core(
1068 CoreEvent::MessagesChanged { conversation_id }
1069 | CoreEvent::ReceiptsChanged { conversation_id },
1070 ) => {
1071 self.clear_typists_who_sent(&conversation_id, cx);
1072 self.refresh_language_stamps(&conversation_id, cx);
1073 cx.emit(AppEvent::Messages(conversation_id));
1074 }
1075 BackendEvent::Core(CoreEvent::MessagesStoredLate {
1076 conversation_id,
1077 message_ids,
1078 }) => self.late_arrivals.insert(&conversation_id, message_ids),
1079 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
1080 self.refresh_pins(&conversation_id, cx);
1081 }
1082 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
1083 if let Some(engine) = &self.engine {
1084 for key in &keys {
1085 let image = ImageRef {
1086 id: String::new(),
1087 url: key.clone(),
1088 width: None,
1089 height: None,
1090 alt: None,
1091 };
1092 if let Some(path) = engine.image_path(&image) {
1093 self.directory.set_image(key, &path);
1094 }
1095 }
1096 }
1097 cx.emit(AppEvent::Images(keys));
1098 }
1099 BackendEvent::Core(CoreEvent::PresenceChanged) => {
1100 let changed = self.sync_presence();
1101 self.announce_followed_changes(cx);
1102 self.directory.save_presence(&self.store, &changed);
1103 cx.emit(AppEvent::Directory);
1104 cx.notify();
1105 }
1106 BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {
1107 self.apply_own_status(status, cx);
1108 self.reload_directory();
1109 }
1110 BackendEvent::Core(_) => {
1111 if !self.mode.demo {
1112 self.reload_directory();
1113 }
1114 cx.emit(AppEvent::Directory);
1115 }
1116 BackendEvent::Typing(event) => self.apply_typing(event, cx),
1117 BackendEvent::Live(live) => {
1118 self.live = live;
1119 self.refresh_connection_banner(cx);
1120 cx.emit(AppEvent::Status);
1121 }
1122 BackendEvent::Favorites(ids) => {
1123 self.favorite_ids = ids;
1124 if !self.mode.demo {
1125 self.reload_directory();
1126 }
1127 cx.emit(AppEvent::Sidebar);
1128 }
1129 BackendEvent::Synced(time) => {
1130 if self.last_sync.is_none() {
1131 self.refresh_saved(cx);
1132 }
1133 self.last_sync = Some(time);
1134 cx.emit(AppEvent::Status);
1135 }
1136 }
1137 cx.notify();
1138 }
1139}
1140
1141#[cfg(test)]
1142mod tests {
1143 use std::sync::Arc;
1144
1145 use chatsvc::TypingEvent;
1146 use chrono::{Duration, Utc};
1147 use gpui_kit::{AppContext as _, TestAppContext};
1148 use store::{
1149 ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord,
1150 };
1151 use teams_core::CoreEvent;
1152
1153 use super::{AppState, Mode, Selection, chat_title, selection_for, selection_title};
1154 use crate::backend::BackendEvent;
1155 use crate::data::Person;
1156 use store::Sidebar;
1157
1158 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
1159 ChatRecord {
1160 id: id.into(),
1161 kind: "group".into(),
1162 title: title.into(),
1163 member_summary: "Member".into(),
1164 last_message_at: None,
1165 last_read_at: None,
1166 unread,
1167 ..Default::default()
1168 }
1169 }
1170
1171 #[test]
1172 fn selection_kind_follows_sidebar() {
1173 assert_eq!(
1174 selection_for(&sidebar(), "c1"),
1175 Some(Selection::Chat("c1".into()))
1176 );
1177 assert_eq!(
1178 selection_for(&sidebar(), "ch"),
1179 Some(Selection::Channel("ch".into()))
1180 );
1181 assert_eq!(selection_for(&sidebar(), "x"), None);
1182 }
1183
1184 fn sidebar() -> Sidebar {
1185 Sidebar {
1186 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
1187 teams: vec![SidebarTeam {
1188 team: TeamRecord {
1189 id: "t".into(),
1190 name: "Team".into(),
1191 },
1192 channels: vec![ChannelRecord {
1193 id: "ch".into(),
1194 team_id: "t".into(),
1195 name: "General".into(),
1196 membership_type: None,
1197 last_message_at: None,
1198 unread: false,
1199 }],
1200 hidden: false,
1201 hidden_channel_ids: Vec::new(),
1202 notifications: Default::default(),
1203 mentions: Default::default(),
1204 }],
1205 }
1206 }
1207
1208 #[test]
1209 fn empty_chat_title_falls_back_to_members() {
1210 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
1211 }
1212
1213 #[test]
1214 fn selection_titles() {
1215 assert_eq!(
1216 selection_title(&sidebar(), &Selection::Channel("ch".into())),
1217 "Team / General"
1218 );
1219 assert_eq!(
1220 selection_title(&sidebar(), &Selection::Chat("c1".into())),
1221 "First"
1222 );
1223 }
1224
1225 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
1226 BackendEvent::Typing(TypingEvent {
1227 conversation_id: "c1".into(),
1228 user_id: user_id.into(),
1229 display_name: format!("Name {user_id}"),
1230 active,
1231 received_at: Utc::now(),
1232 })
1233 }
1234
1235 #[gpui_kit::test]
1236 fn toggle_collapsed_ignores_pending_sections(cx: &mut TestAppContext) {
1237 cx.update(gpui_kit::init);
1238 let store = Arc::new(Store::open_in_memory().unwrap());
1239 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1240 cx.update(|cx| {
1241 app.update(cx, |state, cx| {
1242 state.toggle_collapsed("pending-section:1", cx);
1243 assert!(state.collapsed.is_empty());
1244 })
1245 });
1246 }
1247
1248 #[gpui_kit::test]
1249 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
1250 cx.update(gpui_kit::init);
1251 let store = Arc::new(Store::open_in_memory().unwrap());
1252 let app = cx.update(|cx| {
1253 cx.new(|_| {
1254 let mut state = AppState::new(store.clone(), Mode::default());
1255 state.directory.me = Some(Person {
1256 user_id: "me".into(),
1257 display_name: "Me".into(),
1258 });
1259 state
1260 })
1261 });
1262 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
1263 cx.update(|cx| {
1264 app.update(cx, |state, cx| {
1265 state.apply(typing_event("me", true), cx);
1266 state.apply(typing_event("ada", true), cx);
1267 })
1268 });
1269 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
1270
1271 let message = MessageRecord {
1272 conversation_id: "c1".into(),
1273 message_id: "m1".into(),
1274 sender_id: Some("ada".into()),
1275 created_at: Utc::now() + Duration::seconds(1),
1276 ..Default::default()
1277 };
1278 store.upsert_messages(&[message]).unwrap();
1279 cx.update(|cx| {
1280 app.update(cx, |state, cx| {
1281 state.apply(
1282 BackendEvent::Core(CoreEvent::MessagesChanged {
1283 conversation_id: "c1".into(),
1284 }),
1285 cx,
1286 )
1287 })
1288 });
1289 assert!(names(cx).is_empty());
1290
1291 cx.update(|cx| {
1292 app.update(cx, |state, cx| {
1293 state.apply(typing_event("ada", true), cx);
1294 state.apply(typing_event("ada", false), cx);
1295 })
1296 });
1297 assert!(names(cx).is_empty());
1298 }
1299
1300 #[gpui_kit::test]
1301 fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) {
1302 cx.update(gpui_kit::init);
1303 let store = Arc::new(Store::open_in_memory().unwrap());
1304 let app = cx.update(|cx| {
1305 cx.new(|_| {
1306 let mut state = AppState::new(store.clone(), Mode::default());
1307 let mut member_chat = chat("c1", "First", false);
1308 member_chat.members = vec![MemberRecord {
1309 user_id: Some("ada".into()),
1310 display_name: "Ada Lovelace".into(),
1311 }];
1312 state.sidebar.chats = vec![member_chat];
1313 state
1314 })
1315 });
1316 cx.update(|cx| {
1317 app.update(cx, |state, cx| {
1318 state.apply(
1319 BackendEvent::Typing(TypingEvent {
1320 conversation_id: "c1".into(),
1321 user_id: "ada".into(),
1322 display_name: String::new(),
1323 active: true,
1324 received_at: Utc::now(),
1325 }),
1326 cx,
1327 )
1328 })
1329 });
1330 assert_eq!(
1331 cx.update(|cx| app.read(cx).typing.names("c1")),
1332 vec!["Ada Lovelace".to_owned()]
1333 );
1334 }
1335}