BlueGit

ict rusty-teams

Files

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

app_state.rs

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