BlueGit

ict rusty-teams

Files

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

app_state.rs

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