BlueGit

ict rusty-teams

Files

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

app_state.rs

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