BlueGit

ict rusty-teams

Files

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

app_state.rs

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