BlueGit

ict rusty-teams

Files

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

app_state.rs

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