BlueGit

ict rusty-teams

Files

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

app_state.rs

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