BlueGit

ict rusty-teams

Files

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

app_state.rs

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