BlueGit

ict rusty-teams

Files

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

app_state.rs

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