BlueGit

ict rusty-teams

Files

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

app_state.rs

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