BlueGit

ict rusty-teams

Files

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

app_state.rs

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