BlueGit

ict rusty-teams

Files

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

app_state.rs

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