BlueGit

ict rusty-teams

Files

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

app_state.rs

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