BlueGit

ict rusty-teams

Files

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

app_state.rs

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