BlueGit

ict rusty-teams

Files

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

app_state.rs

app_state.rs 46.3 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 if !matches!(done.await, Ok(Ok(()))) {
633 this.update(cx, |state, cx| {
634 state.directory.mark_image_failed(&image.url);
635 cx.notify();
636 })
637 .ok();
638 }
639 })
640 .detach();
641 }
642 }
643 }
644 if changed {
645 cx.emit(AppEvent::Images(wanted));
646 cx.notify();
647 }
648 }
649
650 pub fn jump_to_message(
651 &mut self,
652 selection: Selection,
653 message_id: String,
654 cx: &mut Context<Self>,
655 ) {
656 self.pending_jump = Some((selection.conversation_id().to_owned(), message_id));
657 if self.selection.as_ref() == Some(&selection) {
658 cx.emit(AppEvent::Jump);
659 } else {
660 self.select(selection, cx);
661 }
662 }
663
664 fn on_done(
665 &self,
666 done: data::Done,
667 cx: &mut Context<Self>,
668 then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
669 ) {
670 cx.spawn(async move |this, cx| {
671 let _ = done.await;
672 this.update(cx, |state, cx| then(state, cx)).ok();
673 })
674 .detach();
675 }
676
677 fn resolve_pending_avatars(&mut self) {
678 for user_id in self.directory.pending_avatars() {
679 if let Some(cached) = data::cached_avatar(&self.store, &user_id) {
680 self.directory.set_avatar(&user_id, cached);
681 }
682 }
683 }
684
685 fn sync_presence(&mut self) -> Vec<String> {
686 let Some(engine) = self.engine.clone() else {
687 return Vec::new();
688 };
689 self.directory
690 .requested_presence_ids()
691 .into_iter()
692 .filter(|user_id| {
693 let Some(kind) = data::presence_kind(&engine, user_id) else {
694 return false;
695 };
696 let activity_changed = self
697 .directory
698 .set_activity(user_id, data::presence_activity(&engine, user_id));
699 let previous = self.directory.presence_of(user_id);
700 let changed = self.directory.set_presence(user_id, kind);
701 if changed {
702 self.note_followed_change(user_id, previous, kind);
703 }
704 changed || activity_changed
705 })
706 .collect()
707 }
708
709 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
710 let now = Instant::now();
711 let pushed = self.live == LiveState::Live;
712 let wanted = self.directory.stale_presence(user_ids, now, pushed);
713 if wanted.is_empty() {
714 return;
715 }
716 self.directory.mark_presence_pending(&wanted);
717 if let Some(engine) = self.engine.clone() {
718 self.directory.mark_presence_requested(&wanted, now);
719 drop(data::watch_presence(&engine, wanted.clone()));
720 let done = data::refresh_presence(&engine, wanted.clone());
721 self.on_done(done, cx, move |state, cx| {
722 state.sync_presence();
723 state.announce_followed_changes(cx);
724 state.directory.save_presence(&state.store, &wanted);
725 state.directory.settle_presence(&wanted);
726 cx.emit(AppEvent::Directory);
727 cx.notify();
728 });
729 }
730 }
731
732 pub fn move_chat(
733 &mut self,
734 conversation_id: &str,
735 folder_id: Option<&str>,
736 cx: &mut Context<Self>,
737 ) {
738 self.place_chat(conversation_id, folder_id, None, cx);
739 }
740
741 pub fn drop_chat_on(
742 &mut self,
743 conversation_id: &str,
744 target_conversation_id: &str,
745 folder_id: &str,
746 cx: &mut Context<Self>,
747 ) {
748 if conversation_id == target_conversation_id {
749 return;
750 }
751 let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else {
752 return;
753 };
754 self.place_chat(conversation_id, Some(folder_id), Some(slot), cx);
755 }
756
757 pub fn place_chat(
758 &mut self,
759 conversation_id: &str,
760 folder_id: Option<&str>,
761 index: Option<usize>,
762 cx: &mut Context<Self>,
763 ) {
764 if self.mode.read_only {
765 return;
766 }
767 let previous_folder = self
768 .directory
769 .folder_of(conversation_id)
770 .map(|folder| folder.id.clone());
771 self.directory.place(conversation_id, folder_id, index);
772 if let Some(engine) = self.engine.clone() {
773 let previous = previous_folder.clone();
774 let done = match (folder_id, previous.as_deref()) {
775 (Some(folder_id), _) => Some(data::move_to_folder(
776 &engine,
777 conversation_id,
778 folder_id,
779 index,
780 )),
781 (None, Some(previous)) => {
782 Some(data::remove_from_folder(&engine, conversation_id, previous))
783 }
784 (None, None) => None,
785 };
786 if let Some(done) = done {
787 self.on_done(done, cx, |state, cx| {
788 state.reload_directory();
789 cx.emit(AppEvent::Sidebar);
790 cx.notify();
791 });
792 }
793 }
794 cx.emit(AppEvent::Sidebar);
795 cx.notify();
796 }
797
798 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
799 if self.keeps_unread(conversation_id) {
800 self.keep_unread = None;
801 }
802 if self.mode.demo {
803 if let Some(chat) = self
804 .sidebar
805 .chats
806 .iter()
807 .find(|chat| chat.id == conversation_id)
808 {
809 let mut read = chat.clone();
810 read.unread = false;
811 let _ = self.store.upsert_chats(&[read]);
812 self.reload_sidebar(cx);
813 }
814 return;
815 }
816 if self.mode.read_only {
817 return;
818 }
819 if let Some(engine) = self.engine.clone() {
820 let _ = self
821 .store
822 .mark_chat_read(conversation_id, chrono::Utc::now());
823 self.reload_sidebar(cx);
824 let conversation_id = conversation_id.to_owned();
825 drop(crate::runtime::spawn(async move {
826 engine.mark_read(&conversation_id).await
827 }));
828 }
829 }
830
831 pub fn mark_channel_read(&mut self, channel_id: &str, cx: &mut Context<Self>) {
832 if self.mode.read_only {
833 return;
834 }
835 let _ = self.store.mark_channel_read(channel_id);
836 self.reload_sidebar(cx);
837 if self.mode.demo {
838 return;
839 }
840 if let Some(engine) = self.engine.clone() {
841 let channel_id = channel_id.to_owned();
842 drop(crate::runtime::spawn(async move {
843 engine.mark_read(&channel_id).await
844 }));
845 }
846 }
847
848 pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) {
849 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
850 return;
851 };
852 let previous_unread: Vec<store::ChannelReadState> = self
853 .sidebar
854 .teams
855 .iter()
856 .flat_map(|team| team.channels.iter())
857 .map(|channel| store::ChannelReadState {
858 channel_id: channel.id.clone(),
859 unread: channel.unread,
860 last_message_at: None,
861 read_until: None,
862 })
863 .collect();
864 let previous_mentions: Vec<(String, store::ChannelMentions)> = self
865 .sidebar
866 .teams
867 .iter()
868 .flat_map(|team| team.mentions.iter())
869 .map(|(channel_id, mentions)| (channel_id.clone(), *mentions))
870 .collect();
871 let _ = self.store.mark_all_channels_read();
872 self.reload_sidebar(cx);
873 let Some(engine) = engine_or_demo else {
874 return;
875 };
876 self.run_chat_action(
877 "Mark all as read",
878 async move { engine.mark_all_channels_read().await },
879 move |state, cx| {
880 let _ = state.store.apply_channel_read_states(&previous_unread);
881 let _ = state.store.replace_channel_mentions(&previous_mentions);
882 state.reload_sidebar(cx);
883 },
884 |_, _| {},
885 cx,
886 );
887 }
888
889 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
890 self.new_chat = true;
891 self.show_call(false, cx);
892 cx.emit(AppEvent::Selection);
893 cx.notify();
894 }
895
896 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
897 if !self.new_chat {
898 return;
899 }
900 self.new_chat = false;
901 cx.emit(AppEvent::Selection);
902 cx.notify();
903 }
904
905 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
906 self.show_call(false, cx);
907 self.cancel_prejoin(cx);
908 self.call_end = None;
909 let was_drafting = std::mem::take(&mut self.new_chat);
910 if !was_drafting && self.selection.as_ref() == Some(&selection) {
911 return;
912 }
913 let conversation_id = selection.conversation_id().to_owned();
914 self.selection = Some(selection);
915 self.keep_unread = None;
916 self.forward_selection = None;
917 cx.emit(AppEvent::Selection);
918 cx.notify();
919 self.refresh_live_meeting(&conversation_id, cx);
920 self.refresh_language_stamps(&conversation_id, cx);
921 }
922
923 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
924 let is_me = self
925 .directory
926 .me
927 .as_ref()
928 .is_some_and(|me| me.user_id == event.user_id);
929 if is_me {
930 return;
931 }
932 if event.active {
933 let display_name = match event.display_name.trim() {
934 "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id))
935 .remove(&event.user_id)
936 .unwrap_or_default(),
937 _ => event.display_name.clone(),
938 };
939 self.typing.start(
940 &event.conversation_id,
941 &event.user_id,
942 &display_name,
943 Instant::now(),
944 event.received_at,
945 );
946 self.request_avatars(vec![event.user_id.clone()], cx);
947 self.schedule_typing_expiry(cx);
948 } else {
949 self.typing.clear(&event.conversation_id, &event.user_id);
950 }
951 cx.emit(AppEvent::Typing);
952 cx.notify();
953 }
954
955 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
956 if !self.typing.is_active(conversation_id) {
957 return;
958 }
959 let Ok(recent) = self
960 .store
961 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
962 else {
963 return;
964 };
965 let mut changed = false;
966 for message in recent {
967 if let Some(sender_id) = message.sender_id.as_deref() {
968 changed |= self
969 .typing
970 .message_from(conversation_id, sender_id, message.created_at);
971 }
972 }
973 if changed {
974 cx.emit(AppEvent::Typing);
975 cx.notify();
976 }
977 }
978
979 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
980 if self.typing_timer_running {
981 return;
982 }
983 self.typing_timer_running = true;
984 cx.spawn(async move |this, cx| {
985 loop {
986 let next = this.update(cx, |state, _| {
987 let next = state.typing.next_expiry();
988 state.typing_timer_running = next.is_some();
989 next
990 });
991 let Ok(Some(next)) = next else { return };
992 cx.background_executor()
993 .timer(next.saturating_duration_since(Instant::now()))
994 .await;
995 let alive = this.update(cx, |state, cx| {
996 if state.typing.expire(Instant::now()) {
997 cx.emit(AppEvent::Typing);
998 cx.notify();
999 }
1000 });
1001 if alive.is_err() {
1002 return;
1003 }
1004 }
1005 })
1006 .detach();
1007 }
1008
1009 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
1010 if let Ok(sidebar) = self.store.sidebar() {
1011 self.sidebar = sidebar;
1012 self.apply_bot_titles();
1013 }
1014 self.calls_list.invalidate();
1015 if !self.mode.demo {
1016 self.reload_directory();
1017 self.load_own_time_zone(cx);
1018 }
1019 cx.emit(AppEvent::Sidebar);
1020 cx.notify();
1021 }
1022
1023 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
1024 match event {
1025 BackendEvent::Connection(connection) => {
1026 self.connection = connection;
1027 self.refresh_connection_banner(cx);
1028 cx.emit(AppEvent::Status);
1029 }
1030 BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry),
1031 BackendEvent::Calls(launcher) => {
1032 launcher.set_default_camera(self.call_camera.clone());
1033 self.call_launcher = Some(launcher);
1034 self.load_own_time_zone(cx);
1035 }
1036 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
1037 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
1038 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
1039 BackendEvent::ThreadChanged(conversation_id) => {
1040 self.on_thread_changed(&conversation_id, cx)
1041 }
1042 BackendEvent::Engine(engine) => {
1043 crate::agent_api::engine_ready(engine.clone(), cx);
1044 self.engine = Some(engine);
1045 self.resend_outbox(cx);
1046 self.refresh_scheduled(cx);
1047 self.refresh_translation_settings(cx);
1048 self.refresh_recording_policy(cx);
1049 self.refresh_messaging_policy(cx);
1050 self.refresh_sound_settings(cx);
1051 self.refresh_chat_settings(cx);
1052 let waiting = self.directory.waiting_presence_ids();
1053 self.request_presence(waiting, cx);
1054 self.watch_followed_presence(cx);
1055 self.refresh_own_status(cx);
1056 cx.emit(AppEvent::Status);
1057 }
1058 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
1059 BackendEvent::Core(CoreEvent::ActivityChanged) => cx.emit(AppEvent::Activity),
1060 BackendEvent::Core(
1061 CoreEvent::MessagesChanged { conversation_id }
1062 | CoreEvent::ReceiptsChanged { conversation_id },
1063 ) => {
1064 self.clear_typists_who_sent(&conversation_id, cx);
1065 self.refresh_language_stamps(&conversation_id, cx);
1066 cx.emit(AppEvent::Messages(conversation_id));
1067 }
1068 BackendEvent::Core(CoreEvent::MessagesStoredLate {
1069 conversation_id,
1070 message_ids,
1071 }) => self.late_arrivals.insert(&conversation_id, message_ids),
1072 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
1073 self.refresh_pins(&conversation_id, cx);
1074 }
1075 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
1076 if let Some(engine) = &self.engine {
1077 for key in &keys {
1078 let image = ImageRef {
1079 id: String::new(),
1080 url: key.clone(),
1081 width: None,
1082 height: None,
1083 alt: None,
1084 };
1085 if let Some(path) = engine.image_path(&image) {
1086 self.directory.set_image(key, &path);
1087 }
1088 }
1089 }
1090 cx.emit(AppEvent::Images(keys));
1091 }
1092 BackendEvent::Core(CoreEvent::PresenceChanged) => {
1093 let changed = self.sync_presence();
1094 self.announce_followed_changes(cx);
1095 self.directory.save_presence(&self.store, &changed);
1096 cx.emit(AppEvent::Directory);
1097 cx.notify();
1098 }
1099 BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {
1100 self.apply_own_status(status, cx);
1101 self.reload_directory();
1102 }
1103 BackendEvent::Core(_) => {
1104 if !self.mode.demo {
1105 self.reload_directory();
1106 }
1107 cx.emit(AppEvent::Directory);
1108 }
1109 BackendEvent::Typing(event) => self.apply_typing(event, cx),
1110 BackendEvent::Live(live) => {
1111 self.live = live;
1112 self.refresh_connection_banner(cx);
1113 cx.emit(AppEvent::Status);
1114 }
1115 BackendEvent::Favorites(ids) => {
1116 self.favorite_ids = ids;
1117 if !self.mode.demo {
1118 self.reload_directory();
1119 }
1120 cx.emit(AppEvent::Sidebar);
1121 }
1122 BackendEvent::Synced(time) => {
1123 if self.last_sync.is_none() {
1124 self.refresh_saved(cx);
1125 }
1126 self.last_sync = Some(time);
1127 cx.emit(AppEvent::Status);
1128 }
1129 }
1130 cx.notify();
1131 }
1132}
1133
1134#[cfg(test)]
1135mod tests {
1136 use std::sync::Arc;
1137
1138 use chatsvc::TypingEvent;
1139 use chrono::{Duration, Utc};
1140 use gpui_kit::{AppContext as _, TestAppContext};
1141 use store::{
1142 ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord,
1143 };
1144 use teams_core::CoreEvent;
1145
1146 use super::{AppState, Mode, Selection, chat_title, selection_for, selection_title};
1147 use crate::backend::BackendEvent;
1148 use crate::data::Person;
1149 use store::Sidebar;
1150
1151 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
1152 ChatRecord {
1153 id: id.into(),
1154 kind: "group".into(),
1155 title: title.into(),
1156 member_summary: "Member".into(),
1157 last_message_at: None,
1158 last_read_at: None,
1159 unread,
1160 ..Default::default()
1161 }
1162 }
1163
1164 #[test]
1165 fn selection_kind_follows_sidebar() {
1166 assert_eq!(
1167 selection_for(&sidebar(), "c1"),
1168 Some(Selection::Chat("c1".into()))
1169 );
1170 assert_eq!(
1171 selection_for(&sidebar(), "ch"),
1172 Some(Selection::Channel("ch".into()))
1173 );
1174 assert_eq!(selection_for(&sidebar(), "x"), None);
1175 }
1176
1177 fn sidebar() -> Sidebar {
1178 Sidebar {
1179 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
1180 teams: vec![SidebarTeam {
1181 team: TeamRecord {
1182 id: "t".into(),
1183 name: "Team".into(),
1184 },
1185 channels: vec![ChannelRecord {
1186 id: "ch".into(),
1187 team_id: "t".into(),
1188 name: "General".into(),
1189 membership_type: None,
1190 last_message_at: None,
1191 unread: false,
1192 }],
1193 hidden: false,
1194 hidden_channel_ids: Vec::new(),
1195 notifications: Default::default(),
1196 mentions: Default::default(),
1197 }],
1198 }
1199 }
1200
1201 #[test]
1202 fn empty_chat_title_falls_back_to_members() {
1203 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
1204 }
1205
1206 #[test]
1207 fn selection_titles() {
1208 assert_eq!(
1209 selection_title(&sidebar(), &Selection::Channel("ch".into())),
1210 "Team / General"
1211 );
1212 assert_eq!(
1213 selection_title(&sidebar(), &Selection::Chat("c1".into())),
1214 "First"
1215 );
1216 }
1217
1218 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
1219 BackendEvent::Typing(TypingEvent {
1220 conversation_id: "c1".into(),
1221 user_id: user_id.into(),
1222 display_name: format!("Name {user_id}"),
1223 active,
1224 received_at: Utc::now(),
1225 })
1226 }
1227
1228 #[gpui_kit::test]
1229 fn toggle_collapsed_ignores_pending_sections(cx: &mut TestAppContext) {
1230 cx.update(gpui_kit::init);
1231 let store = Arc::new(Store::open_in_memory().unwrap());
1232 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1233 cx.update(|cx| {
1234 app.update(cx, |state, cx| {
1235 state.toggle_collapsed("pending-section:1", cx);
1236 assert!(state.collapsed.is_empty());
1237 })
1238 });
1239 }
1240
1241 #[gpui_kit::test]
1242 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
1243 cx.update(gpui_kit::init);
1244 let store = Arc::new(Store::open_in_memory().unwrap());
1245 let app = cx.update(|cx| {
1246 cx.new(|_| {
1247 let mut state = AppState::new(store.clone(), Mode::default());
1248 state.directory.me = Some(Person {
1249 user_id: "me".into(),
1250 display_name: "Me".into(),
1251 });
1252 state
1253 })
1254 });
1255 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
1256 cx.update(|cx| {
1257 app.update(cx, |state, cx| {
1258 state.apply(typing_event("me", true), cx);
1259 state.apply(typing_event("ada", true), cx);
1260 })
1261 });
1262 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
1263
1264 let message = MessageRecord {
1265 conversation_id: "c1".into(),
1266 message_id: "m1".into(),
1267 sender_id: Some("ada".into()),
1268 created_at: Utc::now() + Duration::seconds(1),
1269 ..Default::default()
1270 };
1271 store.upsert_messages(&[message]).unwrap();
1272 cx.update(|cx| {
1273 app.update(cx, |state, cx| {
1274 state.apply(
1275 BackendEvent::Core(CoreEvent::MessagesChanged {
1276 conversation_id: "c1".into(),
1277 }),
1278 cx,
1279 )
1280 })
1281 });
1282 assert!(names(cx).is_empty());
1283
1284 cx.update(|cx| {
1285 app.update(cx, |state, cx| {
1286 state.apply(typing_event("ada", true), cx);
1287 state.apply(typing_event("ada", false), cx);
1288 })
1289 });
1290 assert!(names(cx).is_empty());
1291 }
1292
1293 #[gpui_kit::test]
1294 fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) {
1295 cx.update(gpui_kit::init);
1296 let store = Arc::new(Store::open_in_memory().unwrap());
1297 let app = cx.update(|cx| {
1298 cx.new(|_| {
1299 let mut state = AppState::new(store.clone(), Mode::default());
1300 let mut member_chat = chat("c1", "First", false);
1301 member_chat.members = vec![MemberRecord {
1302 user_id: Some("ada".into()),
1303 display_name: "Ada Lovelace".into(),
1304 }];
1305 state.sidebar.chats = vec![member_chat];
1306 state
1307 })
1308 });
1309 cx.update(|cx| {
1310 app.update(cx, |state, cx| {
1311 state.apply(
1312 BackendEvent::Typing(TypingEvent {
1313 conversation_id: "c1".into(),
1314 user_id: "ada".into(),
1315 display_name: String::new(),
1316 active: true,
1317 received_at: Utc::now(),
1318 }),
1319 cx,
1320 )
1321 })
1322 });
1323 assert_eq!(
1324 cx.update(|cx| app.read(cx).typing.names("c1")),
1325 vec!["Ada Lovelace".to_owned()]
1326 );
1327 }
1328}