BlueGit

ict rusty-teams

Files

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

app_state.rs

22925882 History
app_state.rs 33.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 calling::meeting::LiveMeeting;
17use crate::card_state::{CardState, TaskDialogState};
18use crate::data::{self, Directory};
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::profile_state::{ProfileCache, ProfileRequest};
24use crate::translation::TranslationState;
25use crate::typing::TypingState;
26
27const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
28const RECENT_MESSAGES_FOR_TYPING: usize = 5;
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum Selection {
32 Chat(String),
33 Channel(String),
34}
35
36impl Selection {
37 pub fn conversation_id(&self) -> &str {
38 match self {
39 Selection::Chat(id) | Selection::Channel(id) => id,
40 }
41 }
42}
43
44pub enum AppEvent {
45 Sidebar,
46 Selection,
47 Messages(String),
48 Images(Vec<String>),
49 Jump,
50 Status,
51 Directory,
52 Cards(String),
53 TaskDialog,
54 Typing,
55 LocalPreviews,
56 Outbox(String),
57 Scheduled,
58 Pins(String),
59 Saved,
60 CallHistory,
61 Translation,
62 Forward,
63 ImageViewer,
64 StatusMessage,
65 NotificationSettings,
66 Profile,
67 Call,
68 Ring,
69 LiveMeeting,
70 MissedCall(MissedCall),
71}
72
73#[derive(Debug, Clone, Copy, Default)]
74pub struct Mode {
75 pub demo: bool,
76 pub read_only: bool,
77 pub demo_sync: Option<std::time::Duration>,
78}
79
80pub struct AppState {
81 pub store: Arc<Store>,
82 pub engine: Option<Arc<Engine>>,
83 pub sidebar: Sidebar,
84 pub favorite_ids: Vec<String>,
85 pub selection: Option<Selection>,
86 pub new_chat: bool,
87 pub connection: ConnectionState,
88 pub live: LiveState,
89 pub last_sync: Option<DateTime<Utc>>,
90 pub mode: Mode,
91 pub directory: Directory,
92 pub collapsed: HashSet<String>,
93 pub expanded_lists: HashSet<String>,
94 pub start_on_channels: bool,
95 pub pending_jump: Option<(String, String)>,
96 pub cards: CardState,
97 pub task_dialog: Option<TaskDialogState>,
98 pub bot_apps: HashMap<String, Vec<ChatApp>>,
99 pub bot_apps_pending: HashSet<String>,
100 pub notice: Option<Notice>,
101 pub notice_count: u64,
102 pub keep_unread: Option<String>,
103 pub typing: TypingState,
104 typing_timer_running: bool,
105 pub local_previews: HashMap<String, LocalPreview>,
106 pub scheduled: Vec<ScheduledDraft>,
107 pub scheduled_polling: bool,
108 pub saved: SavedSet,
109 pub call_history: Vec<teams_core::CallLogEntry>,
110 pub calendar_events: Vec<chatsvc::CalendarEvent>,
111 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
112 pub calls_list: crate::call::CallsList,
113 pub pins: HashMap<String, Vec<PinnedMessage>>,
114 pub forward_request: Option<ForwardSource>,
115 pub image_viewer_request: Option<ViewerRequest>,
116 pub own_status: PresenceStatus,
117 pub own_email: String,
118 pub status_menu_open: bool,
119 pub status_message_request: bool,
120 pub profiles: ProfileCache,
121 pub profile_request: Option<ProfileRequest>,
122 pub call: Option<ActiveCall>,
123 pub call_media: Option<Entity<CallMedia>>,
124 pub call_launcher: Option<Arc<CallLauncher>>,
125 pub call_count: u64,
126 pub call_share_sound: bool,
127 pub call_background: crate::call::BackgroundPick,
128 pub call_camera: calling::DeviceChoice,
129 pub meet_now_pending: bool,
130 pub call_backgrounds: crate::call::BackgroundLibrary,
131 pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
132 pub rings: Rings,
133 pub live_meetings: HashMap<String, LiveMeeting>,
134 pub live_refreshing: HashSet<String>,
135 pub translation: TranslationState,
136}
137
138pub struct AppHandle(pub Entity<AppState>);
139
140impl Global for AppHandle {}
141
142impl EventEmitter<AppEvent> for AppState {}
143
144pub fn chat_title(chat: &ChatRecord) -> String {
145 if !chat.title.trim().is_empty() {
146 chat.title.clone()
147 } else if !chat.member_summary.trim().is_empty() {
148 chat.member_summary.clone()
149 } else {
150 "Chat".to_owned()
151 }
152}
153
154pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
155 match selection {
156 Selection::Chat(id) => sidebar
157 .chats
158 .iter()
159 .find(|chat| &chat.id == id)
160 .map(chat_title)
161 .unwrap_or_else(|| "Chat".to_owned()),
162 Selection::Channel(id) => sidebar
163 .teams
164 .iter()
165 .find_map(|team| {
166 team.channels
167 .iter()
168 .find(|channel| &channel.id == id)
169 .map(|channel| format!("{} / {}", team.team.name, channel.name))
170 })
171 .unwrap_or_else(|| "Channel".to_owned()),
172 }
173}
174
175impl AppState {
176 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
177 let sidebar = store.sidebar().unwrap_or_default();
178 let mut state = AppState {
179 store,
180 engine: None,
181 sidebar,
182 favorite_ids: Vec::new(),
183 selection: None,
184 new_chat: false,
185 connection: if mode.demo {
186 ConnectionState::Online
187 } else {
188 ConnectionState::Connecting
189 },
190 live: LiveState::Off,
191 last_sync: None,
192 mode,
193 directory: Directory::default(),
194 collapsed: HashSet::new(),
195 expanded_lists: HashSet::new(),
196 start_on_channels: false,
197 pending_jump: None,
198 cards: CardState::default(),
199 task_dialog: None,
200 bot_apps: HashMap::new(),
201 bot_apps_pending: HashSet::new(),
202 notice: None,
203 notice_count: 0,
204 keep_unread: None,
205 typing: TypingState::default(),
206 typing_timer_running: false,
207 local_previews: HashMap::new(),
208 scheduled: Vec::new(),
209 scheduled_polling: false,
210 saved: SavedSet::default(),
211 call_history: Vec::new(),
212 calendar_events: Vec::new(),
213 calendar_nudge: None,
214 calls_list: crate::call::CallsList::default(),
215 pins: HashMap::new(),
216 forward_request: None,
217 image_viewer_request: None,
218 own_status: PresenceStatus::default(),
219 own_email: String::new(),
220 status_menu_open: false,
221 status_message_request: false,
222 profiles: ProfileCache::new(),
223 profile_request: None,
224 call: None,
225 call_media: None,
226 call_launcher: None,
227 call_count: 0,
228 call_share_sound: false,
229 call_background: crate::call::BackgroundPick::None,
230 call_camera: calling::DeviceChoice::SystemDefault,
231 meet_now_pending: false,
232 call_backgrounds: if mode.demo {
233 crate::call::demo_library()
234 } else {
235 crate::call::BackgroundLibrary::new(crate::call::default_cache_directory())
236 },
237 transfer_picker: None,
238 rings: Rings::default(),
239 live_meetings: HashMap::new(),
240 live_refreshing: HashSet::new(),
241 translation: TranslationState::default(),
242 };
243 state.local_previews = load_local_previews(&state.store);
244 state.collapsed = state.load_collapsed();
245 state.call_share_sound = crate::call::load_share_sound(&state.store);
246 state.call_background = crate::call::load_background(&state.store);
247 state.call_camera = crate::call::load_camera(&state.store);
248 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
249 state.load_cached_translation_settings();
250 if !mode.demo {
251 state.directory.load_cached_presence(&state.store);
252 state.reload_directory();
253 }
254 state
255 }
256
257 fn load_collapsed(&self) -> HashSet<String> {
258 self.store
259 .meta(COLLAPSED_META_KEY)
260 .ok()
261 .flatten()
262 .map(|value| {
263 value
264 .lines()
265 .map(str::to_owned)
266 .filter(|id| !id.is_empty())
267 .collect()
268 })
269 .unwrap_or_default()
270 }
271
272 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
273 let now_collapsed = self.collapsed.insert(section_id.to_owned());
274 if !now_collapsed {
275 self.collapsed.remove(section_id);
276 }
277 self.save_collapsed();
278 self.sync_folder_expanded(section_id, !now_collapsed);
279 cx.emit(AppEvent::Sidebar);
280 cx.notify();
281 }
282
283 pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) {
284 if !self.expanded_lists.remove(section_id) {
285 self.expanded_lists.insert(section_id.to_owned());
286 }
287 cx.emit(AppEvent::Sidebar);
288 cx.notify();
289 }
290
291 fn save_collapsed(&self) {
292 let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect();
293 ids.sort_unstable();
294 let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n"));
295 }
296
297 fn sync_folder_expanded(&mut self, folder_id: &str, expanded: bool) {
298 let Some(folder) = self
299 .directory
300 .folders
301 .iter_mut()
302 .find(|folder| folder.id == folder_id && folder.expanded.is_some())
303 else {
304 return;
305 };
306 folder.expanded = Some(expanded);
307 let _ = self.store.set_folder_expanded(folder_id, expanded);
308 if let Some(engine) = self.engine.clone().filter(|_| !self.mode.read_only) {
309 let folder_id = folder_id.to_owned();
310 drop(crate::runtime::spawn(async move {
311 engine.set_folder_expanded(&folder_id, expanded).await
312 }));
313 }
314 }
315
316 fn adopt_folder_expanded(&mut self) {
317 let snapshot = self.collapsed.clone();
318 for folder in &self.directory.folders {
319 match folder.expanded {
320 Some(true) => {
321 self.collapsed.remove(&folder.id);
322 }
323 Some(false) => {
324 self.collapsed.insert(folder.id.clone());
325 }
326 None => {}
327 }
328 }
329 if self.collapsed != snapshot {
330 self.save_collapsed();
331 }
332 }
333
334 pub fn set_chat_section(
335 &mut self,
336 section: ChatSection,
337 enabled: bool,
338 cx: &mut Context<Self>,
339 ) {
340 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
341 return;
342 };
343 let previous = self.directory.section_settings;
344 let mut updated = previous;
345 updated.set(section, enabled);
346 self.apply_section_settings(updated, cx);
347 let Some(engine) = engine_or_demo else {
348 return;
349 };
350 self.run_chat_action(
351 "Chat list setting",
352 async move { engine.set_section_enabled(section, enabled).await },
353 move |state, cx| state.apply_section_settings(previous, cx),
354 |_, _| {},
355 cx,
356 );
357 }
358
359 fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) {
360 self.directory.section_settings = settings;
361 let _ = teams_core::store_section_settings(&self.store, &settings);
362 cx.emit(AppEvent::Sidebar);
363 cx.notify();
364 }
365
366 pub fn reload_directory(&mut self) {
367 self.directory.me = data::me(&self.store);
368 self.own_email = self
369 .store
370 .meta("me_email")
371 .ok()
372 .flatten()
373 .unwrap_or_default();
374 self.directory.folders = data::folders(&self.store, &self.favorite_ids);
375 self.directory.section_settings = teams_core::stored_section_settings(&self.store);
376 self.adopt_folder_expanded();
377 self.directory.pinned_channels = data::pinned_channels(&self.store);
378 if self.directory.pinned_channels.is_empty() {
379 let known: HashSet<&str> = self
380 .sidebar
381 .teams
382 .iter()
383 .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str()))
384 .collect();
385 self.directory.pinned_channels = self
386 .favorite_ids
387 .iter()
388 .filter(|id| known.contains(id.as_str()))
389 .cloned()
390 .collect();
391 }
392 self.resolve_pending_avatars();
393 self.sync_presence();
394 self.directory.unread_counts = match &self.engine {
395 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
396 None => Default::default(),
397 };
398 }
399
400 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
401 let wanted = self.directory.missing_avatars(user_ids);
402 if wanted.is_empty() {
403 return;
404 }
405 let mut changed = false;
406 let mut uncached = Vec::new();
407 for user_id in wanted {
408 match data::cached_avatar(&self.store, &user_id) {
409 Some(cached) => {
410 self.directory.set_avatar(&user_id, cached);
411 changed = true;
412 }
413 None => uncached.push(user_id),
414 }
415 }
416 if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) {
417 self.directory.mark_avatars_pending(&uncached);
418 let done = data::fetch_avatars(&engine, uncached);
419 self.on_done(done, cx, |state, cx| {
420 state.resolve_pending_avatars();
421 cx.emit(AppEvent::Directory);
422 cx.notify();
423 });
424 changed = true;
425 }
426 if changed {
427 cx.emit(AppEvent::Directory);
428 cx.notify();
429 }
430 }
431
432 pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) {
433 let Some(engine) = self.engine.clone() else {
434 return;
435 };
436 let wanted = self
437 .directory
438 .images_to_request(images.iter().map(|image| image.url.clone()));
439 let mut changed = false;
440 for image in images
441 .into_iter()
442 .filter(|image| wanted.contains(&image.url))
443 {
444 match engine.image_path(&image) {
445 Some(path) => {
446 self.directory.set_image(&image.url, &path);
447 changed = true;
448 }
449 None => {
450 let done = data::fetch_image(&engine, image.clone());
451 cx.spawn(async move |this, cx| {
452 if !matches!(done.await, Ok(Ok(()))) {
453 this.update(cx, |state, cx| {
454 state.directory.mark_image_failed(&image.url);
455 cx.notify();
456 })
457 .ok();
458 }
459 })
460 .detach();
461 }
462 }
463 }
464 if changed {
465 cx.emit(AppEvent::Images(wanted));
466 cx.notify();
467 }
468 }
469
470 pub fn jump_to_message(
471 &mut self,
472 selection: Selection,
473 message_id: String,
474 cx: &mut Context<Self>,
475 ) {
476 self.pending_jump = Some((selection.conversation_id().to_owned(), message_id));
477 if self.selection.as_ref() == Some(&selection) {
478 cx.emit(AppEvent::Jump);
479 } else {
480 self.select(selection, cx);
481 }
482 }
483
484 fn on_done(
485 &self,
486 done: data::Done,
487 cx: &mut Context<Self>,
488 then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
489 ) {
490 cx.spawn(async move |this, cx| {
491 let _ = done.await;
492 this.update(cx, |state, cx| then(state, cx)).ok();
493 })
494 .detach();
495 }
496
497 fn resolve_pending_avatars(&mut self) {
498 for user_id in self.directory.pending_avatars() {
499 if let Some(cached) = data::cached_avatar(&self.store, &user_id) {
500 self.directory.set_avatar(&user_id, cached);
501 }
502 }
503 }
504
505 fn sync_presence(&mut self) -> Vec<String> {
506 let Some(engine) = self.engine.clone() else {
507 return Vec::new();
508 };
509 self.directory
510 .requested_presence_ids()
511 .into_iter()
512 .filter(|user_id| {
513 let Some(kind) = data::presence_kind(&engine, user_id) else {
514 return false;
515 };
516 let activity_changed = self
517 .directory
518 .set_activity(user_id, data::presence_activity(&engine, user_id));
519 self.directory.set_presence(user_id, kind) || activity_changed
520 })
521 .collect()
522 }
523
524 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
525 let now = Instant::now();
526 let pushed = self.live == LiveState::Live;
527 let wanted = self.directory.stale_presence(user_ids, now, pushed);
528 if wanted.is_empty() {
529 return;
530 }
531 self.directory.mark_presence_pending(&wanted);
532 if let Some(engine) = self.engine.clone() {
533 self.directory.mark_presence_requested(&wanted, now);
534 drop(data::watch_presence(&engine, wanted.clone()));
535 let done = data::refresh_presence(&engine, wanted.clone());
536 self.on_done(done, cx, move |state, cx| {
537 state.sync_presence();
538 state.directory.save_presence(&state.store, &wanted);
539 state.directory.settle_presence(&wanted);
540 cx.emit(AppEvent::Directory);
541 cx.notify();
542 });
543 }
544 }
545
546 pub fn move_chat(
547 &mut self,
548 conversation_id: &str,
549 folder_id: Option<&str>,
550 cx: &mut Context<Self>,
551 ) {
552 if self.mode.read_only {
553 return;
554 }
555 let previous_folder = self
556 .directory
557 .folder_of(conversation_id)
558 .map(|folder| folder.id.clone());
559 self.directory.assign(conversation_id, folder_id);
560 if let Some(engine) = self.engine.clone() {
561 let previous = previous_folder.clone();
562 let done = match (folder_id, previous.as_deref()) {
563 (Some(folder_id), _) => {
564 Some(data::move_to_folder(&engine, conversation_id, folder_id))
565 }
566 (None, Some(previous)) => {
567 Some(data::remove_from_folder(&engine, conversation_id, previous))
568 }
569 (None, None) => None,
570 };
571 if let Some(done) = done {
572 self.on_done(done, cx, |state, cx| {
573 state.reload_directory();
574 cx.emit(AppEvent::Sidebar);
575 cx.notify();
576 });
577 }
578 }
579 cx.emit(AppEvent::Sidebar);
580 cx.notify();
581 }
582
583 pub fn pin_chat(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
584 let favorites = self.directory.favorites().map(|folder| folder.id.clone());
585 self.move_chat(conversation_id, favorites.as_deref(), cx);
586 }
587
588 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
589 if self.keeps_unread(conversation_id) {
590 self.keep_unread = None;
591 }
592 if self.mode.demo {
593 if let Some(chat) = self
594 .sidebar
595 .chats
596 .iter()
597 .find(|chat| chat.id == conversation_id)
598 {
599 let mut read = chat.clone();
600 read.unread = false;
601 let _ = self.store.upsert_chats(&[read]);
602 self.reload_sidebar(cx);
603 }
604 return;
605 }
606 if self.mode.read_only {
607 return;
608 }
609 if let Some(engine) = self.engine.clone() {
610 let _ = self
611 .store
612 .mark_chat_read(conversation_id, chrono::Utc::now());
613 self.reload_sidebar(cx);
614 let conversation_id = conversation_id.to_owned();
615 drop(crate::runtime::spawn(async move {
616 engine.mark_read(&conversation_id).await
617 }));
618 }
619 }
620
621 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
622 self.new_chat = true;
623 self.show_call(false, cx);
624 cx.emit(AppEvent::Selection);
625 cx.notify();
626 }
627
628 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
629 if !self.new_chat {
630 return;
631 }
632 self.new_chat = false;
633 cx.emit(AppEvent::Selection);
634 cx.notify();
635 }
636
637 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
638 self.show_call(false, cx);
639 let was_drafting = std::mem::take(&mut self.new_chat);
640 if !was_drafting && self.selection.as_ref() == Some(&selection) {
641 return;
642 }
643 let conversation_id = selection.conversation_id().to_owned();
644 self.selection = Some(selection);
645 self.keep_unread = None;
646 cx.emit(AppEvent::Selection);
647 cx.notify();
648 self.refresh_live_meeting(&conversation_id, cx);
649 self.refresh_language_stamps(&conversation_id, cx);
650 }
651
652 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
653 let is_me = self
654 .directory
655 .me
656 .as_ref()
657 .is_some_and(|me| me.user_id == event.user_id);
658 if is_me {
659 return;
660 }
661 if event.active {
662 let display_name = match event.display_name.trim() {
663 "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id))
664 .remove(&event.user_id)
665 .unwrap_or_default(),
666 _ => event.display_name.clone(),
667 };
668 self.typing.start(
669 &event.conversation_id,
670 &event.user_id,
671 &display_name,
672 Instant::now(),
673 event.received_at,
674 );
675 self.request_avatars(vec![event.user_id.clone()], cx);
676 self.schedule_typing_expiry(cx);
677 } else {
678 self.typing.clear(&event.conversation_id, &event.user_id);
679 }
680 cx.emit(AppEvent::Typing);
681 cx.notify();
682 }
683
684 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
685 if !self.typing.is_active(conversation_id) {
686 return;
687 }
688 let Ok(recent) = self
689 .store
690 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
691 else {
692 return;
693 };
694 let mut changed = false;
695 for message in recent {
696 if let Some(sender_id) = message.sender_id.as_deref() {
697 changed |= self
698 .typing
699 .message_from(conversation_id, sender_id, message.created_at);
700 }
701 }
702 if changed {
703 cx.emit(AppEvent::Typing);
704 cx.notify();
705 }
706 }
707
708 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
709 if self.typing_timer_running {
710 return;
711 }
712 self.typing_timer_running = true;
713 cx.spawn(async move |this, cx| {
714 loop {
715 let next = this.update(cx, |state, _| {
716 let next = state.typing.next_expiry();
717 state.typing_timer_running = next.is_some();
718 next
719 });
720 let Ok(Some(next)) = next else { return };
721 cx.background_executor()
722 .timer(next.saturating_duration_since(Instant::now()))
723 .await;
724 let alive = this.update(cx, |state, cx| {
725 if state.typing.expire(Instant::now()) {
726 cx.emit(AppEvent::Typing);
727 cx.notify();
728 }
729 });
730 if alive.is_err() {
731 return;
732 }
733 }
734 })
735 .detach();
736 }
737
738 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
739 if let Ok(sidebar) = self.store.sidebar() {
740 self.sidebar = sidebar;
741 self.apply_bot_titles();
742 }
743 self.calls_list.invalidate();
744 if !self.mode.demo {
745 self.reload_directory();
746 }
747 cx.emit(AppEvent::Sidebar);
748 cx.notify();
749 }
750
751 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
752 match event {
753 BackendEvent::Connection(connection) => {
754 self.connection = connection;
755 cx.emit(AppEvent::Status);
756 }
757 BackendEvent::Calls(launcher) => {
758 launcher.set_default_camera(self.call_camera.clone());
759 self.call_launcher = Some(launcher);
760 }
761 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
762 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
763 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
764 BackendEvent::ThreadChanged(conversation_id) => self.on_thread_changed(&conversation_id, cx),
765 BackendEvent::Engine(engine) => {
766 self.engine = Some(engine);
767 self.resend_outbox(cx);
768 self.refresh_scheduled(cx);
769 self.refresh_translation_settings(cx);
770 let waiting = self.directory.waiting_presence_ids();
771 self.request_presence(waiting, cx);
772 self.refresh_own_status(cx);
773 cx.emit(AppEvent::Status);
774 }
775 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx),
776 BackendEvent::Core(
777 CoreEvent::MessagesChanged { conversation_id }
778 | CoreEvent::ReceiptsChanged { conversation_id },
779 ) => {
780 self.clear_typists_who_sent(&conversation_id, cx);
781 self.refresh_language_stamps(&conversation_id, cx);
782 cx.emit(AppEvent::Messages(conversation_id));
783 }
784 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
785 self.refresh_pins(&conversation_id, cx);
786 }
787 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
788 if let Some(engine) = &self.engine {
789 for key in &keys {
790 let image = ImageRef {
791 id: String::new(),
792 url: key.clone(),
793 width: None,
794 height: None,
795 };
796 if let Some(path) = engine.image_path(&image) {
797 self.directory.set_image(key, &path);
798 }
799 }
800 }
801 cx.emit(AppEvent::Images(keys));
802 }
803 BackendEvent::Core(CoreEvent::PresenceChanged) => {
804 let changed = self.sync_presence();
805 self.directory.save_presence(&self.store, &changed);
806 cx.emit(AppEvent::Directory);
807 cx.notify();
808 }
809 BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {
810 self.apply_own_status(status, cx);
811 self.reload_directory();
812 }
813 BackendEvent::Core(_) => {
814 if !self.mode.demo {
815 self.reload_directory();
816 }
817 cx.emit(AppEvent::Directory);
818 }
819 BackendEvent::Typing(event) => self.apply_typing(event, cx),
820 BackendEvent::Live(live) => {
821 self.live = live;
822 cx.emit(AppEvent::Status);
823 }
824 BackendEvent::Favorites(ids) => {
825 self.favorite_ids = ids;
826 if !self.mode.demo {
827 self.reload_directory();
828 }
829 cx.emit(AppEvent::Sidebar);
830 }
831 BackendEvent::Synced(time) => {
832 if self.last_sync.is_none() {
833 self.refresh_saved(cx);
834 }
835 self.last_sync = Some(time);
836 cx.emit(AppEvent::Status);
837 }
838 }
839 cx.notify();
840 }
841}
842
843#[cfg(test)]
844mod tests {
845 use std::sync::Arc;
846
847 use chatsvc::TypingEvent;
848 use chrono::{Duration, Utc};
849 use gpui_kit::{AppContext as _, TestAppContext};
850 use store::{
851 ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord,
852 };
853 use teams_core::CoreEvent;
854
855 use super::{AppState, Mode, Selection, chat_title, selection_title};
856 use crate::backend::BackendEvent;
857 use crate::data::Person;
858 use store::Sidebar;
859
860 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
861 ChatRecord {
862 id: id.into(),
863 kind: "group".into(),
864 title: title.into(),
865 member_summary: "Member".into(),
866 last_message_at: None,
867 last_read_at: None,
868 unread,
869 ..Default::default()
870 }
871 }
872
873 fn sidebar() -> Sidebar {
874 Sidebar {
875 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
876 teams: vec![SidebarTeam {
877 team: TeamRecord {
878 id: "t".into(),
879 name: "Team".into(),
880 },
881 channels: vec![ChannelRecord {
882 id: "ch".into(),
883 team_id: "t".into(),
884 name: "General".into(),
885 membership_type: None,
886 last_message_at: None,
887 unread: false,
888 }],
889 hidden: false,
890 hidden_channel_ids: Vec::new(),
891 notifications: Default::default(),
892 }],
893 }
894 }
895
896 #[test]
897 fn empty_chat_title_falls_back_to_members() {
898 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
899 }
900
901 #[test]
902 fn selection_titles() {
903 assert_eq!(
904 selection_title(&sidebar(), &Selection::Channel("ch".into())),
905 "Team / General"
906 );
907 assert_eq!(
908 selection_title(&sidebar(), &Selection::Chat("c1".into())),
909 "First"
910 );
911 }
912
913 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
914 BackendEvent::Typing(TypingEvent {
915 conversation_id: "c1".into(),
916 user_id: user_id.into(),
917 display_name: format!("Name {user_id}"),
918 active,
919 received_at: Utc::now(),
920 })
921 }
922
923 #[gpui_kit::test]
924 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
925 cx.update(gpui_kit::init);
926 let store = Arc::new(Store::open_in_memory().unwrap());
927 let app = cx.update(|cx| {
928 cx.new(|_| {
929 let mut state = AppState::new(store.clone(), Mode::default());
930 state.directory.me = Some(Person {
931 user_id: "me".into(),
932 display_name: "Me".into(),
933 });
934 state
935 })
936 });
937 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
938 cx.update(|cx| {
939 app.update(cx, |state, cx| {
940 state.apply(typing_event("me", true), cx);
941 state.apply(typing_event("ada", true), cx);
942 })
943 });
944 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
945
946 let message = MessageRecord {
947 conversation_id: "c1".into(),
948 message_id: "m1".into(),
949 sender_id: Some("ada".into()),
950 created_at: Utc::now() + Duration::seconds(1),
951 ..Default::default()
952 };
953 store.upsert_messages(&[message]).unwrap();
954 cx.update(|cx| {
955 app.update(cx, |state, cx| {
956 state.apply(
957 BackendEvent::Core(CoreEvent::MessagesChanged {
958 conversation_id: "c1".into(),
959 }),
960 cx,
961 )
962 })
963 });
964 assert!(names(cx).is_empty());
965
966 cx.update(|cx| {
967 app.update(cx, |state, cx| {
968 state.apply(typing_event("ada", true), cx);
969 state.apply(typing_event("ada", false), cx);
970 })
971 });
972 assert!(names(cx).is_empty());
973 }
974
975 #[gpui_kit::test]
976 fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) {
977 cx.update(gpui_kit::init);
978 let store = Arc::new(Store::open_in_memory().unwrap());
979 let app = cx.update(|cx| {
980 cx.new(|_| {
981 let mut state = AppState::new(store.clone(), Mode::default());
982 let mut member_chat = chat("c1", "First", false);
983 member_chat.members = vec![MemberRecord {
984 user_id: Some("ada".into()),
985 display_name: "Ada Lovelace".into(),
986 }];
987 state.sidebar.chats = vec![member_chat];
988 state
989 })
990 });
991 cx.update(|cx| {
992 app.update(cx, |state, cx| {
993 state.apply(
994 BackendEvent::Typing(TypingEvent {
995 conversation_id: "c1".into(),
996 user_id: "ada".into(),
997 display_name: String::new(),
998 active: true,
999 received_at: Utc::now(),
1000 }),
1001 cx,
1002 )
1003 })
1004 });
1005 assert_eq!(
1006 cx.update(|cx| app.read(cx).typing.names("c1")),
1007 vec!["Ada Lovelace".to_owned()]
1008 );
1009 }
1010}