BlueGit

ict rusty-teams

Files

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

app_state.rs

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