BlueGit

ict rusty-teams

Files

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

app_state.rs

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