BlueGit

ict rusty-teams

Files

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

app_state.rs

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