BlueGit

ict rusty-teams

Files

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

app_state.rs

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