BlueGit

ict rusty-teams

Files

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

app_state.rs

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