BlueGit

ict rusty-teams

Files

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

app_state.rs

app_state.rs 40.6 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 mark_channel_read(&mut self, channel_id: &str, cx: &mut Context<Self>) {
742 if self.mode.read_only {
743 return;
744 }
745 let _ = self.store.mark_channel_read(channel_id);
746 self.reload_sidebar(cx);
747 if self.mode.demo {
748 return;
749 }
750 if let Some(engine) = self.engine.clone() {
751 let channel_id = channel_id.to_owned();
752 drop(crate::runtime::spawn(async move {
753 engine.mark_read(&channel_id).await
754 }));
755 }
756 }
757
758 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
759 self.new_chat = true;
760 self.show_call(false, cx);
761 cx.emit(AppEvent::Selection);
762 cx.notify();
763 }
764
765 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
766 if !self.new_chat {
767 return;
768 }
769 self.new_chat = false;
770 cx.emit(AppEvent::Selection);
771 cx.notify();
772 }
773
774 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
775 self.show_call(false, cx);
776 self.cancel_prejoin(cx);
777 let was_drafting = std::mem::take(&mut self.new_chat);
778 if !was_drafting && self.selection.as_ref() == Some(&selection) {
779 return;
780 }
781 let conversation_id = selection.conversation_id().to_owned();
782 self.selection = Some(selection);
783 self.keep_unread = None;
784 cx.emit(AppEvent::Selection);
785 cx.notify();
786 self.refresh_live_meeting(&conversation_id, cx);
787 self.refresh_language_stamps(&conversation_id, cx);
788 }
789
790 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
791 let is_me = self
792 .directory
793 .me
794 .as_ref()
795 .is_some_and(|me| me.user_id == event.user_id);
796 if is_me {
797 return;
798 }
799 if event.active {
800 let display_name = match event.display_name.trim() {
801 "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id))
802 .remove(&event.user_id)
803 .unwrap_or_default(),
804 _ => event.display_name.clone(),
805 };
806 self.typing.start(
807 &event.conversation_id,
808 &event.user_id,
809 &display_name,
810 Instant::now(),
811 event.received_at,
812 );
813 self.request_avatars(vec![event.user_id.clone()], cx);
814 self.schedule_typing_expiry(cx);
815 } else {
816 self.typing.clear(&event.conversation_id, &event.user_id);
817 }
818 cx.emit(AppEvent::Typing);
819 cx.notify();
820 }
821
822 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
823 if !self.typing.is_active(conversation_id) {
824 return;
825 }
826 let Ok(recent) = self
827 .store
828 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
829 else {
830 return;
831 };
832 let mut changed = false;
833 for message in recent {
834 if let Some(sender_id) = message.sender_id.as_deref() {
835 changed |= self
836 .typing
837 .message_from(conversation_id, sender_id, message.created_at);
838 }
839 }
840 if changed {
841 cx.emit(AppEvent::Typing);
842 cx.notify();
843 }
844 }
845
846 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
847 if self.typing_timer_running {
848 return;
849 }
850 self.typing_timer_running = true;
851 cx.spawn(async move |this, cx| {
852 loop {
853 let next = this.update(cx, |state, _| {
854 let next = state.typing.next_expiry();
855 state.typing_timer_running = next.is_some();
856 next
857 });
858 let Ok(Some(next)) = next else { return };
859 cx.background_executor()
860 .timer(next.saturating_duration_since(Instant::now()))
861 .await;
862 let alive = this.update(cx, |state, cx| {
863 if state.typing.expire(Instant::now()) {
864 cx.emit(AppEvent::Typing);
865 cx.notify();
866 }
867 });
868 if alive.is_err() {
869 return;
870 }
871 }
872 })
873 .detach();
874 }
875
876 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
877 if let Ok(sidebar) = self.store.sidebar() {
878 self.sidebar = sidebar;
879 self.apply_bot_titles();
880 }
881 self.calls_list.invalidate();
882 if !self.mode.demo {
883 self.reload_directory();
884 self.load_own_time_zone(cx);
885 }
886 cx.emit(AppEvent::Sidebar);
887 cx.notify();
888 }
889
890 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
891 match event {
892 BackendEvent::Connection(connection) => {
893 self.connection = connection;
894 cx.emit(AppEvent::Status);
895 }
896 BackendEvent::Calls(launcher) => {
897 launcher.set_default_camera(self.call_camera.clone());
898 self.call_launcher = Some(launcher);
899 self.load_own_time_zone(cx);
900 }
901 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
902 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
903 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
904 BackendEvent::ThreadChanged(conversation_id) => {
905 self.on_thread_changed(&conversation_id, cx)
906 }
907 BackendEvent::Engine(engine) => {
908 crate::agent_api::engine_ready(engine.clone(), cx);
909 self.engine = Some(engine);
910 self.resend_outbox(cx);
911 self.refresh_scheduled(cx);
912 self.refresh_translation_settings(cx);
913 self.refresh_recording_policy(cx);
914 let waiting = self.directory.waiting_presence_ids();
915 self.request_presence(waiting, cx);
916 self.refresh_own_status(cx);
917 cx.emit(AppEvent::Status);
918 }
919 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
920 BackendEvent::Core(
921 CoreEvent::MessagesChanged { conversation_id }
922 | CoreEvent::ReceiptsChanged { conversation_id },
923 ) => {
924 self.clear_typists_who_sent(&conversation_id, cx);
925 self.refresh_language_stamps(&conversation_id, cx);
926 cx.emit(AppEvent::Messages(conversation_id));
927 }
928 BackendEvent::Core(CoreEvent::MessagesStoredLate {
929 conversation_id,
930 message_ids,
931 }) => self.late_arrivals.insert(&conversation_id, message_ids),
932 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
933 self.refresh_pins(&conversation_id, cx);
934 }
935 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
936 if let Some(engine) = &self.engine {
937 for key in &keys {
938 let image = ImageRef {
939 id: String::new(),
940 url: key.clone(),
941 width: None,
942 height: None,
943 alt: None,
944 };
945 if let Some(path) = engine.image_path(&image) {
946 self.directory.set_image(key, &path);
947 }
948 }
949 }
950 cx.emit(AppEvent::Images(keys));
951 }
952 BackendEvent::Core(CoreEvent::PresenceChanged) => {
953 let changed = self.sync_presence();
954 self.directory.save_presence(&self.store, &changed);
955 cx.emit(AppEvent::Directory);
956 cx.notify();
957 }
958 BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {
959 self.apply_own_status(status, cx);
960 self.reload_directory();
961 }
962 BackendEvent::Core(_) => {
963 if !self.mode.demo {
964 self.reload_directory();
965 }
966 cx.emit(AppEvent::Directory);
967 }
968 BackendEvent::Typing(event) => self.apply_typing(event, cx),
969 BackendEvent::Live(live) => {
970 self.live = live;
971 cx.emit(AppEvent::Status);
972 }
973 BackendEvent::Favorites(ids) => {
974 self.favorite_ids = ids;
975 if !self.mode.demo {
976 self.reload_directory();
977 }
978 cx.emit(AppEvent::Sidebar);
979 }
980 BackendEvent::Synced(time) => {
981 if self.last_sync.is_none() {
982 self.refresh_saved(cx);
983 }
984 self.last_sync = Some(time);
985 cx.emit(AppEvent::Status);
986 }
987 }
988 cx.notify();
989 }
990}
991
992#[cfg(test)]
993mod tests {
994 use std::sync::Arc;
995
996 use chatsvc::TypingEvent;
997 use chrono::{Duration, Utc};
998 use gpui_kit::{AppContext as _, TestAppContext};
999 use store::{
1000 ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord,
1001 };
1002 use teams_core::CoreEvent;
1003
1004 use super::{AppState, Mode, Selection, chat_title, selection_for, selection_title};
1005 use crate::backend::BackendEvent;
1006 use crate::data::Person;
1007 use store::Sidebar;
1008
1009 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
1010 ChatRecord {
1011 id: id.into(),
1012 kind: "group".into(),
1013 title: title.into(),
1014 member_summary: "Member".into(),
1015 last_message_at: None,
1016 last_read_at: None,
1017 unread,
1018 ..Default::default()
1019 }
1020 }
1021
1022 #[test]
1023 fn selection_kind_follows_sidebar() {
1024 assert_eq!(
1025 selection_for(&sidebar(), "c1"),
1026 Some(Selection::Chat("c1".into()))
1027 );
1028 assert_eq!(
1029 selection_for(&sidebar(), "ch"),
1030 Some(Selection::Channel("ch".into()))
1031 );
1032 assert_eq!(selection_for(&sidebar(), "x"), None);
1033 }
1034
1035 fn sidebar() -> Sidebar {
1036 Sidebar {
1037 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
1038 teams: vec![SidebarTeam {
1039 team: TeamRecord {
1040 id: "t".into(),
1041 name: "Team".into(),
1042 },
1043 channels: vec![ChannelRecord {
1044 id: "ch".into(),
1045 team_id: "t".into(),
1046 name: "General".into(),
1047 membership_type: None,
1048 last_message_at: None,
1049 unread: false,
1050 }],
1051 hidden: false,
1052 hidden_channel_ids: Vec::new(),
1053 notifications: Default::default(),
1054 }],
1055 }
1056 }
1057
1058 #[test]
1059 fn empty_chat_title_falls_back_to_members() {
1060 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
1061 }
1062
1063 #[test]
1064 fn selection_titles() {
1065 assert_eq!(
1066 selection_title(&sidebar(), &Selection::Channel("ch".into())),
1067 "Team / General"
1068 );
1069 assert_eq!(
1070 selection_title(&sidebar(), &Selection::Chat("c1".into())),
1071 "First"
1072 );
1073 }
1074
1075 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
1076 BackendEvent::Typing(TypingEvent {
1077 conversation_id: "c1".into(),
1078 user_id: user_id.into(),
1079 display_name: format!("Name {user_id}"),
1080 active,
1081 received_at: Utc::now(),
1082 })
1083 }
1084
1085 #[gpui_kit::test]
1086 fn toggle_collapsed_ignores_pending_sections(cx: &mut TestAppContext) {
1087 cx.update(gpui_kit::init);
1088 let store = Arc::new(Store::open_in_memory().unwrap());
1089 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1090 cx.update(|cx| {
1091 app.update(cx, |state, cx| {
1092 state.toggle_collapsed("pending-section:1", cx);
1093 assert!(state.collapsed.is_empty());
1094 })
1095 });
1096 }
1097
1098 #[gpui_kit::test]
1099 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
1100 cx.update(gpui_kit::init);
1101 let store = Arc::new(Store::open_in_memory().unwrap());
1102 let app = cx.update(|cx| {
1103 cx.new(|_| {
1104 let mut state = AppState::new(store.clone(), Mode::default());
1105 state.directory.me = Some(Person {
1106 user_id: "me".into(),
1107 display_name: "Me".into(),
1108 });
1109 state
1110 })
1111 });
1112 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
1113 cx.update(|cx| {
1114 app.update(cx, |state, cx| {
1115 state.apply(typing_event("me", true), cx);
1116 state.apply(typing_event("ada", true), cx);
1117 })
1118 });
1119 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
1120
1121 let message = MessageRecord {
1122 conversation_id: "c1".into(),
1123 message_id: "m1".into(),
1124 sender_id: Some("ada".into()),
1125 created_at: Utc::now() + Duration::seconds(1),
1126 ..Default::default()
1127 };
1128 store.upsert_messages(&[message]).unwrap();
1129 cx.update(|cx| {
1130 app.update(cx, |state, cx| {
1131 state.apply(
1132 BackendEvent::Core(CoreEvent::MessagesChanged {
1133 conversation_id: "c1".into(),
1134 }),
1135 cx,
1136 )
1137 })
1138 });
1139 assert!(names(cx).is_empty());
1140
1141 cx.update(|cx| {
1142 app.update(cx, |state, cx| {
1143 state.apply(typing_event("ada", true), cx);
1144 state.apply(typing_event("ada", false), cx);
1145 })
1146 });
1147 assert!(names(cx).is_empty());
1148 }
1149
1150 #[gpui_kit::test]
1151 fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) {
1152 cx.update(gpui_kit::init);
1153 let store = Arc::new(Store::open_in_memory().unwrap());
1154 let app = cx.update(|cx| {
1155 cx.new(|_| {
1156 let mut state = AppState::new(store.clone(), Mode::default());
1157 let mut member_chat = chat("c1", "First", false);
1158 member_chat.members = vec![MemberRecord {
1159 user_id: Some("ada".into()),
1160 display_name: "Ada Lovelace".into(),
1161 }];
1162 state.sidebar.chats = vec![member_chat];
1163 state
1164 })
1165 });
1166 cx.update(|cx| {
1167 app.update(cx, |state, cx| {
1168 state.apply(
1169 BackendEvent::Typing(TypingEvent {
1170 conversation_id: "c1".into(),
1171 user_id: "ada".into(),
1172 display_name: String::new(),
1173 active: true,
1174 received_at: Utc::now(),
1175 }),
1176 cx,
1177 )
1178 })
1179 });
1180 assert_eq!(
1181 cx.update(|cx| app.read(cx).typing.names("c1")),
1182 vec!["Ada Lovelace".to_owned()]
1183 );
1184 }
1185}