BlueGit

ict rusty-teams

Files

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

app_state.rs

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