BlueGit

ict rusty-teams

Files

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

app_state.rs

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