BlueGit

ict rusty-teams

Files

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

app_state.rs

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