BlueGit

ict rusty-teams

Files

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

app_state.rs

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