BlueGit

ict rusty-teams

Files

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

app_state.rs

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