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