BlueGit

ict rusty-teams

Files

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

app_state.rs

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